diff --git a/worker/README.md b/worker/README.md index 223304e..c717307 100644 --- a/worker/README.md +++ b/worker/README.md @@ -157,8 +157,11 @@ Passkey removal stays disabled until an email-code recovery implementation is live. This deliberately avoids a last-factor lockout in the passkey-only configuration. -The one-minute Cron trigger runs Mail send and reconciliation only. A separate -`1-59 * * * *` trigger runs one cleanup lane per invocation: challenge cleanup, +Separate Cron triggers run Mail send every minute and reconciliation every +minute except minute zero (at most a two-minute reconciliation gap). Each +invocation processes at most one operation, retaining its own scan cursor. +Idle runs do not import an unused HMAC key; secret validation remains eager. A separate +`0-58 * * * *` trigger runs one cleanup lane per invocation: challenge cleanup, email-operation repair, Mail retention, expired Sessions, each of the four Identity rate-limit policies, Support queue repair/inactive sweep, and each of the four Support/Admin rate-limit policies. The 14 lanes rotate using the @@ -166,7 +169,9 @@ scheduled UTC time, including across hour boundaries, so each runs every 14–15 minutes. This gives cleanup its own invocation CPU budget instead of combining every task under the Workers Free 10 ms limit. Authentication and rate-limit checks still enforce expiry on access; cleanup only reclaims or -repairs stored data. +repairs stored data. Paged Identity and Support cleanup also consumes at most +one record per invocation. Support cleanup composes only storage, its clock, +and limiters; it does not build Identity, roles, or HTTP handlers. Each run reads its cursor record once, merges successful lane results into a single conditional update, and skips unchanged cursors (including empty @@ -260,19 +265,38 @@ webhook secret in the same maintenance window. `GITHUB_ALLOWED_REPOSITORY_IDS` (comma-separated numeric IDs). Names are display data only; IDs are the allowlist authority. -**Schedules:** `* * * * *` runs Identity Mail send/reconciliation. -`1-59 * * * *` runs one rotating Identity or Support cleanup lane. -`0 */6 * * *` runs -GitHub release reconciliation only (public `/repos/{owner}/{repo}/releases/latest` -with conditional ETags, bounded timeouts/bodies). Reconciliation is also the -initial backfill path; it never fabricates `@pegma/webhooks` receipt rows. - -After deploying maintenance changes, check invocation CPU times and outcomes -for both mail and cleanup triggers in Workers Observability. Local D1 tests -verify cursor writes and dispatch, but do not enforce Cloudflare's production -CPU limit. A busy mail page or large cleanup page can still require smaller -pages or Workers Paid; reducing cron frequency alone does not raise the -per-invocation allowance. +**Schedules:** `* * * * *` runs Identity Mail send. +`1-59 * * * *` independently runs Mail reconciliation, skipping minute zero. +`0-58 * * * *` runs one rotating Identity or Support cleanup lane. +`0-59 */6 * * *` reconciles one GitHub repository per invocation, using the +scheduled UTC minute as the slot in the allowlisted catalog. The current +13-repository catalog completes in minutes 0-12 of each six-hour window; +remaining slots return without database or GitHub I/O. The 60-slot capacity is +checked in code. Fetches use stable numeric repository IDs, conditional ETags, +and bounded timeouts/bodies. Full-catalog backfill remains available explicitly. + +Each successful scheduled shard records its scheduled timestamp durably in the +existing operations collection. Global reconciliation health advances only +when every currently allowlisted catalog repository has succeeded in that +six-hour cycle. Failed or missing shards keep the prior full-catalog success; +concurrent shards merge progress and preserve webhook ETag invalidation. +Existing records decode missing per-repository progress as empty. No D1 schema +migration is required, and reconciliation never fabricates webhook receipts. + +After deploying maintenance changes, check CPU distributions and resource-limit +outcomes for all four triggers, including populated mail pages and release +200/304 responses. Local D1 tests prove bounded page progress and delivery +idempotency, not Cloudflare's production CPU accounting. These changes target +the Workers Free 10 ms allowance; they cannot guarantee an absolute CPU ceiling. + +One-record pages trade throughput for headroom: mail scans at most 60 send and 59 reconciliation operation +records per hour, including retained terminal records. A full scan +must remain comfortably shorter than the email-code lifetime; inspect scan +backlogs as usage grows. Cleanup pages advance once per lane every 14-15 +minutes. The published Sessions and rate-limit packages still expose +whole-partition sweeps, so their work grows with partition size. Sustained +backlogs need indexed discovery and paginated component APIs, or a larger CPU +allowance. Reducing frequency alone does not raise the per-invocation limit. **Organization webhook (Phase E):** create one org webhook subscribed only to `release` events, payload URL `https://pegma.dev/api/webhooks/github/releases`, diff --git a/worker/src/identity-maintenance.test.ts b/worker/src/identity-maintenance.test.ts index 69fd0bc..e0f9e2c 100644 --- a/worker/src/identity-maintenance.test.ts +++ b/worker/src/identity-maintenance.test.ts @@ -185,12 +185,12 @@ describe('Identity maintenance', () => { await runIdentityMaintenance(value.runtime, value.logger, { tasks: ['mail_send'], }); - expect(value.sendPage).toHaveBeenNthCalledWith(2, { limit: 5 }); + expect(value.sendPage).toHaveBeenNthCalledWith(2, { limit: 1 }); await runIdentityMaintenance(value.runtime, value.logger, { tasks: ['mail_send'], }); expect(value.sendPage).toHaveBeenNthCalledWith(3, { - limit: 5, + limit: 1, cursor: 'send-next', }); }); @@ -293,20 +293,20 @@ describe('Identity maintenance', () => { expect(value.challengeSweep).toHaveBeenNthCalledWith( 2, - 100, + 1, 'challenge-next', ); expect(value.operationSweep).toHaveBeenNthCalledWith( 2, - 100, + 1, 'operation-next', ); expect(value.sendPage).toHaveBeenNthCalledWith(2, { - limit: 5, + limit: 1, cursor: 'send-next', }); expect(value.reconciliationPage).toHaveBeenNthCalledWith(2, { - limit: 5, + limit: 1, }); expect(value.mailSweep).toHaveBeenCalledTimes(2); expect(value.limiterSweep).toHaveBeenCalledTimes(2); diff --git a/worker/src/identity-maintenance.ts b/worker/src/identity-maintenance.ts index 6e4cbcb..1f4a432 100644 --- a/worker/src/identity-maintenance.ts +++ b/worker/src/identity-maintenance.ts @@ -55,10 +55,9 @@ type CursorName = | 'mailSweepCursor'; const KEY = { partition: 'identity', id: 'maintenance' } as const; -// Each provider call has a 10-second timeout and workers process a page -// sequentially. Five keeps a worst-case I/O lane inside the one-minute cadence -// and far below Cloudflare's scheduled-handler wall limit. -const MAIL_PROVIDER_PAGE_LIMIT = 5; +// A record can require several conditional writes and a provider call. Bound +// CPU work as well as I/O; durable cursors continue the scan on the next tick. +const MAINTENANCE_PAGE_LIMIT = 1; const maintenance = defineCollection({ name: 'pegma-dev-maintenance', key: (value) => ({ @@ -164,12 +163,18 @@ export async function runIdentityMaintenance( const tasks: Record Promise> = { challenges: async () => { const previous = cursor(prior?.challengeCursor ?? null); - const result = await runtime.identity.sweepChallenges(100, previous); + const result = await runtime.identity.sweepChallenges( + MAINTENANCE_PAGE_LIMIT, + previous, + ); saveCursor('challengeCursor', result.hasMore ? result.cursor : null); }, email_operations: async () => { const previous = cursor(prior?.emailOperationCursor ?? null); - const result = await runtime.identity.sweepEmailOperations(100, previous); + const result = await runtime.identity.sweepEmailOperations( + MAINTENANCE_PAGE_LIMIT, + previous, + ); saveCursor('emailOperationCursor', result.hasMore ? result.cursor : null); }, rate_limits: async () => { @@ -187,7 +192,7 @@ export async function runIdentityMaintenance( if (mailWorker === null) return; const previous = cursor(prior?.mailSendCursor ?? null); const result = await mailWorker.runSendPage({ - limit: MAIL_PROVIDER_PAGE_LIMIT, + limit: MAINTENANCE_PAGE_LIMIT, ...(previous === undefined ? {} : { cursor: previous }), }); const terminal = result.results.filter( @@ -206,7 +211,7 @@ export async function runIdentityMaintenance( if (mailWorker === null) return; const previous = cursor(prior?.mailReconcileCursor ?? null); const result = await mailWorker.runReconciliationPage({ - limit: MAIL_PROVIDER_PAGE_LIMIT, + limit: MAINTENANCE_PAGE_LIMIT, ...(previous === undefined ? {} : { cursor: previous }), }); const terminal = result.results.filter( @@ -225,7 +230,7 @@ export async function runIdentityMaintenance( if (runtime.mailWorker === null) return; const previous = cursor(prior?.mailSweepCursor ?? null); const result = await runtime.identity.sweepMail({ - limit: 100, + limit: MAINTENANCE_PAGE_LIMIT, ...(previous === undefined ? {} : { cursor: previous }), terminalBefore: new Date( Date.now() - 7 * 24 * 60 * 60_000, diff --git a/worker/src/identity-runtime.test.ts b/worker/src/identity-runtime.test.ts index 92b6556..6630db7 100644 --- a/worker/src/identity-runtime.test.ts +++ b/worker/src/identity-runtime.test.ts @@ -39,6 +39,30 @@ function mutation(path: string, body: unknown): Request { } describe('published Identity composition', () => { + it('avoids importing an unused email HMAC key on idle maintenance', async () => { + const imported = vi.spyOn(crypto.subtle, 'importKey'); + try { + const runtime = createIdentityRuntime( + options({ emailEnabled: true, resendApiKey: 're_test_secret' }), + logger, + ); + await runtime.identity.sweepChallenges(1); + await runtime.identity.sweepEmailOperations(1); + await runtime.mailWorker!.runSendPage({ limit: 1 }); + await runtime.mailWorker!.runReconciliationPage({ limit: 1 }); + expect(imported).not.toHaveBeenCalled(); + const response = await runtime.api( + mutation('/api/identity/email-code/account/options', { + email: 'lazy@example.test', + }), + ); + expect(response.status).toBe(200); + expect(imported).toHaveBeenCalledTimes(1); + } finally { + imported.mockRestore(); + } + }); + it('composes Identity, the claims adapter, Sessions, and the account API', async () => { const runtime = createIdentityRuntime(options(), logger); const user = await runtime.identity.provisionVerifiedUser({ diff --git a/worker/src/identity-runtime.ts b/worker/src/identity-runtime.ts index a337c5e..b88c151 100644 --- a/worker/src/identity-runtime.ts +++ b/worker/src/identity-runtime.ts @@ -3,6 +3,7 @@ import { createHmacEmailCodeProtector, createIdentity, type Identity, + type EmailCodeProtector, type MailProvider, type MailReconciliationPort, type MailWorker, @@ -91,6 +92,18 @@ function durableLimiter( ); } +/** Keep key validation eager, but import HMAC only when code work needs it. */ +function deferredEmailCodeProtector(secret: Uint8Array): EmailCodeProtector { + let protector: EmailCodeProtector | undefined; + const get = () => (protector ??= createHmacEmailCodeProtector(secret)); + return { + deriveCode: (handleHash) => get().deriveCode(handleHash), + verifier: (handleHash, code) => get().verifier(handleHash, code), + matches: (expected, handleHash, code) => + get().matches(expected, handleHash, code), + }; +} + /** * Production composition for pegma.dev's first-party Identity provider. * @@ -159,7 +172,7 @@ export function createIdentityRuntime( origins: ['https://pegma.dev'], registrationLimiter, authenticationLimiter, - emailCodeProtector: createHmacEmailCodeProtector( + emailCodeProtector: deferredEmailCodeProtector( emailCodeSecret(options.emailCodeSecretBase64), ), emailCodeRequestLimiter, @@ -167,29 +180,25 @@ export function createIdentityRuntime( }); const resendKey = - typeof options.resendApiKey === 'string' && - options.resendApiKey.length > 0 + typeof options.resendApiKey === 'string' && options.resendApiKey.length > 0 ? options.resendApiKey : null; - const delivery = - !options.emailEnabled - ? null - : options.mailDelivery ?? - (resendKey === null - ? null - : (() => { - const ports = createResendMailPorts({ - apiKey: resendKey, - from: options.emailFrom, - ...(options.fetch === undefined - ? {} - : { fetch: options.fetch }), - }); - return { - ...ports, - classifyFailure: classifyResendFailure, - }; - })()); + const delivery = !options.emailEnabled + ? null + : (options.mailDelivery ?? + (resendKey === null + ? null + : (() => { + const ports = createResendMailPorts({ + apiKey: resendKey, + from: options.emailFrom, + ...(options.fetch === undefined ? {} : { fetch: options.fetch }), + }); + return { + ...ports, + classifyFailure: classifyResendFailure, + }; + })())); const mailWorker = delivery === null ? null diff --git a/worker/src/index.ts b/worker/src/index.ts index da08c65..cc59964 100644 --- a/worker/src/index.ts +++ b/worker/src/index.ts @@ -34,12 +34,18 @@ import { createAdminLookupLimiter, createAdminMutationLimiter, createProductionSupportRuntime, + createProductionSupportMaintenanceRuntime, probeSupportStore, supportHealthProbeEnabled, type SupportRuntimeEnv, } from './support-desk'; import { runSupportMaintenance } from './support-maintenance'; -import { MAIL_CRON, CLEANUP_CRON, cleanupLaneAt } from './maintenance-schedule'; +import { + MAIL_CRON, + MAIL_RECONCILE_CRON, + CLEANUP_CRON, + cleanupLaneAt, +} from './maintenance-schedule'; import { createPegmaMcpHandler } from './mcp-server'; import type { CatalogFetchEnv } from './mcp-catalog-fetch'; @@ -387,6 +393,7 @@ export default { store: createProductionStore(env), logger, config: releasesConfig, + scheduledTime: controller.scheduledTime, }); } catch (error) { logger.log('error', 'release_reconciliation.unavailable', { @@ -402,7 +409,11 @@ export default { controller.cron === CLEANUP_CRON ? cleanupLaneAt(controller.scheduledTime) : null; - if (controller.cron !== MAIL_CRON && cleanup === null) { + if ( + controller.cron !== MAIL_CRON && + controller.cron !== MAIL_RECONCILE_CRON && + cleanup === null + ) { logger.log('warn', 'maintenance.unknown_cron', { cron: controller.cron }); return; } @@ -415,7 +426,13 @@ export default { createProductionIdentityRuntime(env, logger), logger, cleanup === null - ? { tasks: ['mail_send', 'mail_reconcile'] } + ? { + tasks: [ + controller.cron === MAIL_CRON + ? 'mail_send' + : 'mail_reconcile', + ], + } : { tasks: [cleanup.task], ...(cleanup.limiterIndex === undefined @@ -435,37 +452,8 @@ export default { ctx.waitUntil( (async () => { try { - const identityRuntime = createProductionIdentityRuntime( - env, - logger, - ); - const supportRuntime = createProductionSupportRuntime(env, { - sessions: identityRuntime.sessions, - identity: identityRuntime.identity, - identityLinkFromClaims: identityLinkKeyFromVerifiedIdentityClaims, - logger, - }); await runSupportMaintenance( - { - store: supportRuntime.store, - clock: supportRuntime.clock, - // The admin mutation limiter joins the sweep: without it, - // expired pegma.admin.role.mutate counters would sit in D1 - // forever. - limiters: [ - ...supportRuntime.limiters, - createAdminMutationLimiter( - supportRuntime.store, - supportRuntime.clock, - ), - createAdminLookupLimiter( - supportRuntime.store, - supportRuntime.clock, - ), - ], - terminalRetentionMilliseconds: - supportRuntime.terminalRetentionMilliseconds, - }, + createProductionSupportMaintenanceRuntime(env), logger, { tasks: [cleanup.task], diff --git a/worker/src/maintenance-cursors.d1.test.ts b/worker/src/maintenance-cursors.d1.test.ts index 7210b0a..8067e3a 100644 --- a/worker/src/maintenance-cursors.d1.test.ts +++ b/worker/src/maintenance-cursors.d1.test.ts @@ -16,6 +16,7 @@ import { createProductionSupportRuntime, createAdminMutationLimiter, createAdminLookupLimiter, + createProductionSupportMaintenanceRuntime, } from './support-desk'; import { identityLinkKeyFromVerifiedIdentityClaims } from '@pegma/authorization-identity'; import { cleanupLaneAt } from './maintenance-schedule'; @@ -118,6 +119,60 @@ function fixture() { } describe('maintenance cursor writes over D1', () => { + it('drains real mail jobs one per tick and resumes safely after wrapping', async () => { + const { store } = fixture(); + const send = vi.fn(async () => ({ + providerMessageRef: crypto.randomUUID(), + })); + const runtime = createIdentityRuntime( + { + store, + emailCodeSecretBase64: btoa( + String.fromCharCode(...new Uint8Array(32).fill(7)), + ), + emailFrom: 'Pegma ', + emailEnabled: true, + mailDelivery: { + provider: { send }, + reconciliation: { reconcile: async () => ({ status: 'unknown' }) }, + classifyFailure: () => 'unavailable', + }, + }, + logger, + ); + for (let index = 0; index < 3; index++) { + const response = await runtime.api( + new Request( + 'https://pegma.dev/api/identity/email-code/account/options', + { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + Origin: 'https://pegma.dev', + 'Sec-Fetch-Site': 'same-origin', + 'CF-Connecting-IP': '192.0.2.1', + }, + body: JSON.stringify({ + email: `maintenance-${index}@example.test`, + }), + }, + ), + ); + expect(response.status).toBe(200); + } + for (let tick = 0; tick < 6; tick++) { + const before = send.mock.calls.length; + await runIdentityMaintenance(runtime, logger, { tasks: ['mail_send'] }); + expect(send.mock.calls.length - before).toBeLessThanOrEqual(1); + } + expect(send).toHaveBeenCalledTimes(3); + expect(logger.log).not.toHaveBeenCalledWith( + 'error', + expect.anything(), + expect.anything(), + ); + }); + it('covers every limiter in the real production compositions', () => { const identity = createProductionIdentityRuntime( { @@ -139,6 +194,9 @@ describe('maintenance cursor writes over D1', () => { createAdminMutationLimiter(support.store), createAdminLookupLimiter(support.store), ]; + expect( + createProductionSupportMaintenanceRuntime(env).limiters, + ).toHaveLength(supportLimiters.length); const lanes = Array.from({ length: 14 }, (_, index) => cleanupLaneAt(Date.parse('2026-10-15T12:01:00Z') + index * 60_000), ); diff --git a/worker/src/maintenance-schedule.test.ts b/worker/src/maintenance-schedule.test.ts index 6676bbe..47027d9 100644 --- a/worker/src/maintenance-schedule.test.ts +++ b/worker/src/maintenance-schedule.test.ts @@ -1,6 +1,11 @@ import { readFileSync } from 'node:fs'; import { describe, expect, it, vi, beforeEach } from 'vitest'; -import { MAIL_CRON, CLEANUP_CRON, cleanupLaneAt } from './maintenance-schedule'; +import { + MAIL_CRON, + MAIL_RECONCILE_CRON, + CLEANUP_CRON, + cleanupLaneAt, +} from './maintenance-schedule'; import { RELEASE_RECONCILIATION_CRON, runReleaseReconciliation, @@ -16,6 +21,12 @@ vi.mock('./identity-runtime', () => ({ createProductionIdentityRuntime: () => ({ sessions: {}, identity: {} }), })); vi.mock('./support-desk', () => ({ + createProductionSupportMaintenanceRuntime: () => ({ + store: {}, + clock: {}, + limiters: [{}, {}, {}, {}], + terminalRetentionMilliseconds: 1, + }), createProductionSupportRuntime: () => ({ store: {}, clock: {}, @@ -67,8 +78,8 @@ describe('maintenance dispatch', () => { }), ); } - expect(cleanupLaneAt(Date.parse('2026-10-15T12:00:00Z'))).toEqual( - cleanupLaneAt(Date.parse('2026-10-15T11:59:00Z')), + expect(cleanupLaneAt(Date.parse('2026-10-15T11:59:00Z'))).toEqual( + cleanupLaneAt(Date.parse('2026-10-15T11:58:00Z')), ); }); @@ -80,17 +91,52 @@ describe('maintenance dispatch', () => { const crons = JSON.parse(config.match(/"crons":\s*(\[[^\]]*\])/)![1]!); expect(crons).toEqual([ MAIL_CRON, + MAIL_RECONCILE_CRON, CLEANUP_CRON, RELEASE_RECONCILIATION_CRON, ]); }); + it('advances each cleanup lane exactly once per eligible tick in the configured cron', () => { + // Read eligibility from the actual cron, rather than hard-coding the + // skipped minute independently of the configuration under test. + const match = /^(\d+)-(\d+) \* \* \* \*$/.exec(CLEANUP_CRON); + expect(match).not.toBeNull(); + const first = Number(match![1]); + const last = Number(match![2]); + const start = Date.parse('2026-10-15T00:00:00Z'); + const observed: string[] = []; + for (let minute = 0; minute < 2 * 24 * 60; minute++) { + const time = start + minute * 60_000; + const utcMinute = new Date(time).getUTCMinutes(); + if (utcMinute >= first && utcMinute <= last) { + observed.push(JSON.stringify(cleanupLaneAt(time))); + } + } + const cycle = observed.slice(0, 14); + expect(new Set(cycle).size).toBe(14); + for (let index = 0; index < observed.length; index++) { + expect(observed[index]).toBe(cycle[index % cycle.length]); + } + }); + it('keeps mail minute-by-minute without running cleanup or releases', async () => { await scheduled(MAIL_CRON, Date.parse('2026-10-15T12:00:00Z')); expect(runIdentityMaintenance).toHaveBeenCalledExactlyOnceWith( expect.anything(), expect.anything(), - { tasks: ['mail_send', 'mail_reconcile'] }, + { tasks: ['mail_send'] }, + ); + expect(runSupportMaintenance).not.toHaveBeenCalled(); + expect(runReleaseReconciliation).not.toHaveBeenCalled(); + }); + + it('reconciles mail in its own invocation every minute', async () => { + await scheduled(MAIL_RECONCILE_CRON, Date.parse('2026-10-15T12:01:00Z')); + expect(runIdentityMaintenance).toHaveBeenCalledExactlyOnceWith( + expect.anything(), + expect.anything(), + { tasks: ['mail_reconcile'] }, ); expect(runSupportMaintenance).not.toHaveBeenCalled(); expect(runReleaseReconciliation).not.toHaveBeenCalled(); @@ -101,7 +147,7 @@ describe('maintenance dispatch', () => { const start = Date.parse('2026-10-15T23:53:00Z'); for (let minute = 0; minute < 15; minute++) { const time = start + minute * 60_000; - if (new Date(time).getUTCMinutes() === 0) continue; + if (new Date(time).getUTCMinutes() === 59) continue; const lane = cleanupLaneAt(time); lanes.push(JSON.stringify(lane)); vi.clearAllMocks(); @@ -143,7 +189,11 @@ describe('maintenance dispatch', () => { Date.parse('2026-10-15T12:00:00Z'), ); await scheduled('unknown', Date.parse('2026-10-15T12:00:00Z')); - expect(runReleaseReconciliation).toHaveBeenCalledTimes(1); + expect(runReleaseReconciliation).toHaveBeenCalledExactlyOnceWith( + expect.objectContaining({ + scheduledTime: Date.parse('2026-10-15T12:00:00Z'), + }), + ); expect(runIdentityMaintenance).not.toHaveBeenCalled(); expect(runSupportMaintenance).not.toHaveBeenCalled(); }); diff --git a/worker/src/maintenance-schedule.ts b/worker/src/maintenance-schedule.ts index a03917f..39a6eb0 100644 --- a/worker/src/maintenance-schedule.ts +++ b/worker/src/maintenance-schedule.ts @@ -2,9 +2,10 @@ import type { IdentityMaintenanceTask } from './identity-maintenance'; import type { SupportMaintenanceTask } from './support-maintenance'; export const MAIL_CRON = '* * * * *'; -// A separate invocation gives cleanup its own CPU allowance. Skip minute zero -// (also used by release reconciliation), while rotating through 14 small lanes. -export const CLEANUP_CRON = '1-59 * * * *'; +// Skip minute zero so every trigger has a distinct schedule. +export const MAIL_RECONCILE_CRON = '1-59 * * * *'; +// Cleanup skips minute 59 and rotates through 14 small lanes. +export const CLEANUP_CRON = '0-58 * * * *'; type CleanupLane = | { @@ -40,8 +41,8 @@ const CLEANUP_LANES: readonly CleanupLane[] = [ /** Deterministic across cold starts, delayed delivery, and UTC hour boundaries. */ export function cleanupLaneAt(scheduledTime: number): CleanupLane { const minute = Math.floor(scheduledTime / 60_000); - // Count only eligible minutes so skipping minute zero never skips a lane. - const tick = minute - Math.floor(minute / 60) - 1; + // Count only eligible minutes so skipping minute 59 never skips a lane. + const tick = minute - Math.floor((minute + 1) / 60); const length = CLEANUP_LANES.length; return CLEANUP_LANES[((tick % length) + length) % length]!; } diff --git a/worker/src/release-ops-state.test.ts b/worker/src/release-ops-state.test.ts index 244c25d..195cd7c 100644 --- a/worker/src/release-ops-state.test.ts +++ b/worker/src/release-ops-state.test.ts @@ -10,6 +10,33 @@ import { } from './release-ops-state'; describe('release ops state', () => { + it('prunes removed progress without discarding active progress or ETag fences', async () => { + const store = createMemoryStore(); + const start = Date.parse('2026-10-15T12:00:00Z'); + await markReleaseWebhookSuccess(store, new Date(start).toISOString()); + await invalidateReleaseRepositoryEtag(store, 'removed'); + await mergeReleaseRepositoryEtagUpdates(store, [], null, { + repositoryIds: ['active', 'removed'], + succeeded: ['active', 'removed'], + scheduledTime: start, + }); + await mergeReleaseRepositoryEtagUpdates(store, [], null, { + repositoryIds: ['active', 'added'], + succeeded: ['added'], + scheduledTime: start + 60_000, + }); + const ops = await readReleaseOpsState(store); + expect(ops.repositoryReconciledAt).toEqual({ + active: start, + added: start + 60_000, + }); + expect(ops.repositoryEtagEpochs).toEqual({ removed: 1 }); + expect(ops.lastSuccessfulWebhookAt).toBe(new Date(start).toISOString()); + expect(ops.lastSuccessfulReconciliationAt).toBe( + new Date(start).toISOString(), + ); + }); + it('records webhook and reconciliation markers independently', async () => { const store = createMemoryStore(); await markReleaseWebhookSuccess(store, '2026-07-28T10:00:00.000Z'); @@ -27,9 +54,7 @@ describe('release ops state', () => { const ops = await readReleaseOpsState(store); expect(ops.lastSuccessfulWebhookAt).toBe('2026-07-28T10:00:00.000Z'); - expect(ops.lastSuccessfulReconciliationAt).toBe( - '2026-07-28T12:00:00.000Z', - ); + expect(ops.lastSuccessfulReconciliationAt).toBe('2026-07-28T12:00:00.000Z'); expect(ops.repositoryEtags).toEqual({ '1313911960': '"etag"' }); }); @@ -55,9 +80,7 @@ describe('release ops state', () => { const ops = await readReleaseOpsState(store); expect(ops.repositoryEtags).toEqual({ '1312512520': '"keep"' }); expect(ops.repositoryEtagEpochs['1313911960']).toBe(1); - expect(ops.lastSuccessfulReconciliationAt).toBe( - '2026-07-28T12:00:00.000Z', - ); + expect(ops.lastSuccessfulReconciliationAt).toBe('2026-07-28T12:00:00.000Z'); }); it('does not restore ETags after concurrent invalidation', async () => { diff --git a/worker/src/release-ops-state.ts b/worker/src/release-ops-state.ts index a93f5ff..21c35d9 100644 --- a/worker/src/release-ops-state.ts +++ b/worker/src/release-ops-state.ts @@ -20,6 +20,8 @@ export interface ReleaseOpsState { * cannot restore a stale ETag after a concurrent webhook projection. */ readonly repositoryEtagEpochs: Readonly>; + /** Successful scheduled observations, used to certify a complete cycle. */ + readonly repositoryReconciledAt: Readonly>; } type EncodedReleaseOpsState = { @@ -27,6 +29,7 @@ type EncodedReleaseOpsState = { readonly lastSuccessfulReconciliationAt: StoredValue; readonly repositoryEtagsJson: StoredValue; readonly repositoryEtagEpochsJson: StoredValue; + readonly repositoryReconciledAtJson: StoredValue; }; function opsKey(): EntityKey { @@ -38,17 +41,29 @@ function encodeStringMap(map: Readonly>): string { } function decodeStringMap(value: StoredValue): Record { - if (typeof value !== 'string' || value.length === 0 || value.length > 32_768) { + if ( + typeof value !== 'string' || + value.length === 0 || + value.length > 32_768 + ) { return {}; } try { const parsed: unknown = JSON.parse(value); - if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) { + if ( + parsed === null || + typeof parsed !== 'object' || + Array.isArray(parsed) + ) { return {}; } const result: Record = {}; for (const [key, entry] of Object.entries(parsed)) { - if (typeof entry === 'string' && entry.length > 0 && entry.length <= 512) { + if ( + typeof entry === 'string' && + entry.length > 0 && + entry.length <= 512 + ) { result[key] = entry; } } @@ -63,17 +78,29 @@ function encodeEpochMap(map: Readonly>): string { } function decodeEpochMap(value: StoredValue): Record { - if (typeof value !== 'string' || value.length === 0 || value.length > 32_768) { + if ( + typeof value !== 'string' || + value.length === 0 || + value.length > 32_768 + ) { return {}; } try { const parsed: unknown = JSON.parse(value); - if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) { + if ( + parsed === null || + typeof parsed !== 'object' || + Array.isArray(parsed) + ) { return {}; } const result: Record = {}; for (const [key, entry] of Object.entries(parsed)) { - if (typeof entry === 'number' && Number.isSafeInteger(entry) && entry >= 0) { + if ( + typeof entry === 'number' && + Number.isSafeInteger(entry) && + entry >= 0 + ) { result[key] = entry; } } @@ -89,6 +116,7 @@ function encode(value: ReleaseOpsState): EncodedReleaseOpsState { lastSuccessfulReconciliationAt: value.lastSuccessfulReconciliationAt, repositoryEtagsJson: encodeStringMap(value.repositoryEtags), repositoryEtagEpochsJson: encodeEpochMap(value.repositoryEtagEpochs), + repositoryReconciledAtJson: encodeEpochMap(value.repositoryReconciledAt), }; } @@ -106,6 +134,9 @@ function decode(record: StoredRecord): ReleaseOpsState { repositoryEtagEpochs: decodeEpochMap( record['repositoryEtagEpochsJson'] ?? null, ), + repositoryReconciledAt: decodeEpochMap( + record['repositoryReconciledAtJson'] ?? null, + ), }; } @@ -122,9 +153,12 @@ const EMPTY: ReleaseOpsState = { lastSuccessfulReconciliationAt: null, repositoryEtags: {}, repositoryEtagEpochs: {}, + repositoryReconciledAt: {}, }; -export async function readReleaseOpsState(store: Store): Promise { +export async function readReleaseOpsState( + store: Store, +): Promise { const current = await store.collection(releaseOpsCollection()).get(opsKey()); return current ?? EMPTY; } @@ -159,13 +193,15 @@ export async function markReleaseWebhookSuccess( store: Store, at: string, ): Promise { - await store.collection(releaseOpsCollection()).update(opsKey(), (current) => ({ - action: 'write', - value: { - ...(current ?? EMPTY), - lastSuccessfulWebhookAt: at, - }, - })); + await store + .collection(releaseOpsCollection()) + .update(opsKey(), (current) => ({ + action: 'write', + value: { + ...(current ?? EMPTY), + lastSuccessfulWebhookAt: at, + }, + })); } /** One repository ETag update conditioned on the epoch observed at fetch time. */ @@ -185,6 +221,11 @@ export async function mergeReleaseRepositoryEtagUpdates( store: Store, updates: readonly ConditionalEtagUpdate[], markSuccessAt: string | null, + scheduled?: { + readonly repositoryIds: readonly string[]; + readonly succeeded: readonly string[]; + readonly scheduledTime: number; + }, ): Promise { await store.collection(releaseOpsCollection()).update(opsKey(), (current) => { const base = current ?? EMPTY; @@ -201,14 +242,45 @@ export async function mergeReleaseRepositoryEtagUpdates( etags[update.repositoryId] = update.etag; } } + const reconciled = { ...base.repositoryReconciledAt }; + let completedAt = markSuccessAt ?? base.lastSuccessfulReconciliationAt; + if (scheduled !== undefined) { + // Progress is meaningful only for the current catalog. ETag epochs are + // deliberately retained separately: they fence concurrent webhooks. + for (const id of Object.keys(reconciled)) { + if (!scheduled.repositoryIds.includes(id)) delete reconciled[id]; + } + for (const id of scheduled.succeeded) { + reconciled[id] = Math.max(reconciled[id] ?? 0, scheduled.scheduledTime); + } + const cycleStart = + Math.floor(scheduled.scheduledTime / (6 * 60 * 60_000)) * + 6 * + 60 * + 60_000; + if ( + scheduled.repositoryIds.length > 0 && + scheduled.repositoryIds.every( + (id) => (reconciled[id] ?? -1) >= cycleStart, + ) + ) { + // The oldest successful shard certifies the full catalog. Late retries + // must neither regress health nor let one successful repo hide failures. + const oldest = Math.min( + ...scheduled.repositoryIds.map((id) => reconciled[id]!), + ); + if (completedAt === null || oldest > Date.parse(completedAt)) + completedAt = new Date(oldest).toISOString(); + } + } return { action: 'write', value: { ...base, repositoryEtags: etags, repositoryEtagEpochs: epochs, - lastSuccessfulReconciliationAt: - markSuccessAt ?? base.lastSuccessfulReconciliationAt, + repositoryReconciledAt: reconciled, + lastSuccessfulReconciliationAt: completedAt, }, }; }); diff --git a/worker/src/release-reconciliation.test.ts b/worker/src/release-reconciliation.test.ts index 65b153c..1c6f2f8 100644 --- a/worker/src/release-reconciliation.test.ts +++ b/worker/src/release-reconciliation.test.ts @@ -59,6 +59,88 @@ describe('githubLatestToFacts', () => { }); describe('runReleaseReconciliation', () => { + it('bounds scheduled fetches, survives a failed shard, and certifies only a full cycle', async () => { + const store = createMemoryStore(); + const fetchImpl = vi.fn( + async () => new Response(null, { status: 404 }), + ); + const start = Date.parse('2026-10-15T12:00:00Z'); + const run = (scheduledTime: number) => + runReleaseReconciliation({ + store, + logger, + config, + scheduledTime, + fetchImpl, + }); + await run(start); + expect(fetchImpl).toHaveBeenCalledTimes(1); + expect(String(fetchImpl.mock.calls[0]![0])).toContain( + `/repositories/${SPINE_ID}/`, + ); + expect( + (await readReleaseOpsState(store)).lastSuccessfulReconciliationAt, + ).toBeNull(); + fetchImpl.mockResolvedValueOnce(new Response(null, { status: 503 })); + await run(start + 60_000); + expect( + (await readReleaseOpsState(store)).lastSuccessfulReconciliationAt, + ).toBeNull(); + await run(start + 60_000); + expect( + (await readReleaseOpsState(store)).lastSuccessfulReconciliationAt, + ).toBe(new Date(start).toISOString()); + expect(String(fetchImpl.mock.calls[2]![0])).toContain( + `/repositories/${WEBHOOKS_ID}/`, + ); + await run(start + 2 * 60_000); + expect(fetchImpl).toHaveBeenCalledTimes(3); + + // A later cycle cannot borrow a successful observation from the prior one. + await run(start + 6 * 60 * 60_000); + expect( + (await readReleaseOpsState(store)).lastSuccessfulReconciliationAt, + ).toBe(new Date(start).toISOString()); + await run(start + 6 * 60 * 60_000 + 60_000); + expect( + (await readReleaseOpsState(store)).lastSuccessfulReconciliationAt, + ).toBe(new Date(start + 6 * 60 * 60_000).toISOString()); + // A delayed replay cannot move the full-catalog health marker backwards. + await run(start); + expect( + (await readReleaseOpsState(store)).lastSuccessfulReconciliationAt, + ).toBe(new Date(start + 6 * 60 * 60_000).toISOString()); + }); + + it('preserves concurrent shard progress and webhook ETag invalidation', async () => { + const store = createMemoryStore(); + const { invalidateReleaseRepositoryEtag } = + await import('./release-ops-state'); + const start = Date.parse('2026-10-15T12:00:00Z'); + const fetchImpl: typeof fetch = async (input) => { + if (String(input).includes(SPINE_ID)) + await invalidateReleaseRepositoryEtag(store, SPINE_ID); + return Response.json(webhooksLatest, { headers: { etag: 'new-etag' } }); + }; + await Promise.all( + [0, 1].map((slot) => + runReleaseReconciliation({ + store, + logger, + config, + scheduledTime: start + slot * 60_000, + fetchImpl, + }), + ), + ); + const ops = await readReleaseOpsState(store); + expect(ops.repositoryEtags[SPINE_ID]).toBeUndefined(); + expect(ops.repositoryEtags[WEBHOOKS_ID]).toBe('new-etag'); + expect(ops.lastSuccessfulReconciliationAt).toBe( + new Date(start).toISOString(), + ); + }); + it('backfills stable releases and records success markers', async () => { const store = createMemoryStore(); const fetchImpl = vi.fn(async (input: RequestInfo | URL) => { @@ -140,12 +222,14 @@ describe('runReleaseReconciliation', () => { })) as unknown as typeof fetch, }); - const fetchImpl = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => { - const headers = new Headers(init?.headers); - expect(headers.get('If-None-Match')).toBe('"etag-1"'); - // Simulate unpublish of the only stable release. - return new Response('Not Found', { status: 404 }); - }); + const fetchImpl = vi.fn( + async (input: RequestInfo | URL, init?: RequestInit) => { + const headers = new Headers(init?.headers); + expect(headers.get('If-None-Match')).toBe('"etag-1"'); + // Simulate unpublish of the only stable release. + return new Response('Not Found', { status: 404 }); + }, + ); const summary = await runReleaseReconciliation({ store, @@ -207,7 +291,10 @@ describe('runReleaseReconciliation', () => { config: { allowedRepositoryIds: new Set([WEBHOOKS_ID]) }, now: NOW, fetchImpl: (async () => - new Response(null, { status: 304, headers: { ETag: '"etag-1"' } })) as unknown as typeof fetch, + new Response(null, { + status: 304, + headers: { ETag: '"etag-1"' }, + })) as unknown as typeof fetch, }); expect(summary.notModified).toBe(1); @@ -286,9 +373,8 @@ describe('runReleaseReconciliation', () => { observedAt: '2026-07-28T11:00:00.000Z', }, })); - const { invalidateReleaseRepositoryEtag } = await import( - './release-ops-state' - ); + const { invalidateReleaseRepositoryEtag } = + await import('./release-ops-state'); await invalidateReleaseRepositoryEtag(store, WEBHOOKS_ID); // Missed delete of B: GitHub is A again. Without ETag invalidation this diff --git a/worker/src/release-reconciliation.ts b/worker/src/release-reconciliation.ts index f22d034..b4d6b41 100644 --- a/worker/src/release-reconciliation.ts +++ b/worker/src/release-reconciliation.ts @@ -21,8 +21,8 @@ import { } from './release-projection'; import type { ComponentRelease } from './component-release'; -/** Cron expression for six-hour release reconciliation (not identity). */ -export const RELEASE_RECONCILIATION_CRON = '0 */6 * * *'; +/** One repository per minute during each six-hour reconciliation window. */ +export const RELEASE_RECONCILIATION_CRON = '0-59 */6 * * *'; const GITHUB_API = 'https://api.github.com'; const REQUEST_TIMEOUT_MS = 10_000; @@ -47,6 +47,8 @@ export interface RunReleaseReconciliationOptions { readonly config: ReleaseReconciliationConfig; readonly now?: string; readonly fetchImpl?: typeof fetch; + /** Cron timestamp selects one catalog slot; omit for explicit full backfill. */ + readonly scheduledTime?: number; } function asRecord(value: unknown): Record | null { @@ -178,16 +180,15 @@ async function clearCurrentRelease( throw new Error('Release clear conflicted repeatedly.'); } -async function reconcileOneRepository( - options: { - readonly store: Store; - readonly entry: ReleaseCatalogEntry; - readonly etag: string | undefined; - readonly observedAt: string; - readonly fetchImpl: typeof fetch; - }, -): Promise<{ - readonly outcome: 'upserted' | 'cleared' | 'not_modified' | 'unchanged' | 'failed'; +async function reconcileOneRepository(options: { + readonly store: Store; + readonly entry: ReleaseCatalogEntry; + readonly etag: string | undefined; + readonly observedAt: string; + readonly fetchImpl: typeof fetch; +}): Promise<{ + readonly outcome: + 'upserted' | 'cleared' | 'not_modified' | 'unchanged' | 'failed'; readonly etag: string | undefined; }> { const { store, entry, observedAt, fetchImpl } = options; @@ -283,9 +284,26 @@ export async function runReleaseReconciliation( const { store, logger, config } = options; const observedAt = options.now ?? new Date().toISOString(); const fetchImpl = options.fetchImpl ?? fetch; - const catalog = allowedReleaseCatalog(config.allowedRepositoryIds); + const fullCatalog = allowedReleaseCatalog(config.allowedRepositoryIds); + if (options.scheduledTime !== undefined && fullCatalog.length > 60) + throw new RangeError('Release catalog exceeds scheduled slots.'); + if ( + options.scheduledTime !== undefined && + (!Number.isFinite(new Date(options.scheduledTime).getTime()) || + options.scheduledTime < 0) + ) + throw new RangeError('Invalid release schedule timestamp.'); + const slot = + options.scheduledTime === undefined + ? undefined + : new Date(options.scheduledTime).getUTCMinutes(); + const catalog = + slot === undefined ? fullCatalog : fullCatalog.slice(slot, slot + 1); + if (slot !== undefined && catalog.length === 0) + return { examined: 0, upserted: 0, cleared: 0, notModified: 0, failed: 0 }; // Epoch-conditioned ETag updates so a concurrent webhook invalidation wins. const etagUpdates: ConditionalEtagUpdate[] = []; + const succeeded: string[] = []; let examined = 0; let upserted = 0; @@ -300,11 +318,7 @@ export async function runReleaseReconciliation( const expectedEpoch = live.repositoryEtagEpochs[entry.repositoryId] ?? 0; let result: { readonly outcome: - | 'upserted' - | 'cleared' - | 'not_modified' - | 'unchanged' - | 'failed'; + 'upserted' | 'cleared' | 'not_modified' | 'unchanged' | 'failed'; readonly etag: string | undefined; }; try { @@ -323,7 +337,10 @@ export async function runReleaseReconciliation( if (result.outcome === 'failed') { failed += 1; - } else if (result.outcome === 'cleared') { + } else { + succeeded.push(entry.repositoryId); + } + if (result.outcome === 'cleared') { cleared += 1; etagUpdates.push({ repositoryId: entry.repositoryId, @@ -332,7 +349,7 @@ export async function runReleaseReconciliation( }); } else if (result.outcome === 'not_modified') { notModified += 1; - } else { + } else if (result.outcome !== 'failed') { if (result.outcome === 'upserted') { upserted += 1; } @@ -354,8 +371,21 @@ export async function runReleaseReconciliation( // Persist success only when every repository completed without failure so // health "stale" stays honest. Merge ETag updates for successful repos. + const scheduled = + options.scheduledTime === undefined + ? undefined + : { + repositoryIds: fullCatalog.map((entry) => entry.repositoryId), + succeeded, + scheduledTime: options.scheduledTime, + }; if (summary.failed === 0) { - await mergeReleaseRepositoryEtagUpdates(store, etagUpdates, observedAt); + await mergeReleaseRepositoryEtagUpdates( + store, + etagUpdates, + scheduled === undefined ? observedAt : null, + scheduled, + ); logger.log('info', 'release_reconciliation.completed', { examined: summary.examined, upserted: summary.upserted, @@ -363,7 +393,12 @@ export async function runReleaseReconciliation( notModified: summary.notModified, }); } else { - await mergeReleaseRepositoryEtagUpdates(store, etagUpdates, null); + await mergeReleaseRepositoryEtagUpdates( + store, + etagUpdates, + null, + scheduled, + ); logger.log('error', 'release_reconciliation.partial_failure', { examined: summary.examined, upserted: summary.upserted, diff --git a/worker/src/support-desk.ts b/worker/src/support-desk.ts index e383f7c..0d3e23c 100644 --- a/worker/src/support-desk.ts +++ b/worker/src/support-desk.ts @@ -220,7 +220,13 @@ export function createAdminMutationLimiter( store: Store, clock: Clock = systemClock, ): DurableRateLimiter { - return durableLimiter(store, 'pegma.admin.role.mutate', 30, 60 * 60_000, clock); + return durableLimiter( + store, + 'pegma.admin.role.mutate', + 30, + 60 * 60_000, + clock, + ); } /** @@ -241,6 +247,48 @@ export function createAdminLookupLimiter( ); } +function createSupportLimiters(store: Store, clock: Clock) { + return { + createLimiter: durableLimiter( + store, + SUPPORT_CREATE_LIMIT_POLICY, + 10, + 60 * 60_000, + clock, + ), + replyLimiter: durableLimiter( + store, + SUPPORT_REPLY_LIMIT_POLICY, + 30, + 60 * 60_000, + clock, + ), + }; +} + +/** Maintenance does not need Identity, HTTP APIs, roles, or ticket commands. */ +export function createProductionSupportMaintenanceRuntime( + env: SupportRuntimeEnv, +) { + const store = createCloudflareD1Store({ + database: env.IDENTITY_DB, + createSchemaIfMissing: false, + }); + const clock = systemClock; + const { createLimiter, replyLimiter } = createSupportLimiters(store, clock); + return { + store, + clock, + terminalRetentionMilliseconds: SUPPORT_TERMINAL_RETENTION_MS, + limiters: [ + createLimiter, + replyLimiter, + createAdminMutationLimiter(store, clock), + createAdminLookupLimiter(store, clock), + ], + }; +} + /** * Production Support Desk composition for pegma.dev. * @@ -265,12 +313,9 @@ export function createSupportRuntime( ): SupportRuntime { const store = options.store; const clock = options.clock ?? systemClock; - const createLimiter = - options.createLimiter ?? - durableLimiter(store, SUPPORT_CREATE_LIMIT_POLICY, 10, 60 * 60_000, clock); - const replyLimiter = - options.replyLimiter ?? - durableLimiter(store, SUPPORT_REPLY_LIMIT_POLICY, 30, 60 * 60_000, clock); + const defaults = createSupportLimiters(store, clock); + const createLimiter = options.createLimiter ?? defaults.createLimiter; + const replyLimiter = options.replyLimiter ?? defaults.replyLimiter; const application = createSupportDeskApplication({ store, diff --git a/worker/src/support-maintenance.ts b/worker/src/support-maintenance.ts index 4263fe2..201ce7a 100644 --- a/worker/src/support-maintenance.ts +++ b/worker/src/support-maintenance.ts @@ -20,7 +20,8 @@ export interface SupportMaintenanceRuntime { readonly terminalRetentionMilliseconds?: number; } -const PAGE_LIMIT = 50; +// Queue repair can read and update several records for one ticket. +const PAGE_LIMIT = 1; export const SUPPORT_MAINTENANCE_TASKS = [ 'queue_repair', diff --git a/worker/wrangler.jsonc b/worker/wrangler.jsonc index b41f37d..88038fb 100644 --- a/worker/wrangler.jsonc +++ b/worker/wrangler.jsonc @@ -19,8 +19,8 @@ "GITHUB_ALLOWED_REPOSITORY_IDS": "1312512520,1312519623,1312811498,1312961609,1312942188,1313911960,1313917945,1314116350,1314093835,1313927900,1314239450,1314421283,1313936481", }, "triggers": { - // Minute mail delivery; one cleanup lane per nonzero minute; six-hour releases. - "crons": ["* * * * *", "1-59 * * * *", "0 */6 * * *"], + // Separate minute mail lanes; rotating cleanup; one release repo per minute. + "crons": ["* * * * *", "1-59 * * * *", "0-58 * * * *", "0-59 */6 * * *"], }, "d1_databases": [ {