feat(cron): missad-tick-detektion — heartbeat per schema, 503 när ett jobb slutar komma
masterplan-lock / check (pull_request) Successful in 8s
security / scan (pull_request) Failing after 2m43s

Den 2026-11-15 tappade accounted-cron 1 497 av 10 455 körningar på ett dygn
(14,3 %) när pids_limit 30 fick fork/exec /bin/sh att misslyckas. supercronic
hoppade tyst över tickarna. Containern var Up hela tiden, appen svarade 200 på
allt, och enda spåret var cron-containerns egen logg. Orsaken är fixad i #43;
det här gör att ett tappat jobb SYNS nästa gång.

Tre luckor stängs:
1. Ingen körningshistorik — with-cron-context loggade men skrev inget
   beständigt, så en körning som aldrig startade lämnade inget spår.
2. Cron-tjänstens healthcheck var `ps ax | grep supercronic`, som bara blir röd
   när processen dör, inte när scheman slutar köra.
3. Ingen hade kodifierat vad "för sen" betyder per schema.

Implementering:
- lib/cron/cron-interval.ts: tolkare för 5-fälters cron (det enda vercel.json
  använder) som räknar ut VÄRSTA gapet i sekunder över ett 12-årsfönster
  (behövs för 29 februari), inte medelgapet. Okänd syntax kastar hellre än
  gissar.
- scripts/generate-crontabs.ts skriver nu även lib/cron/schedules.generated.ts
  (path + schedule + maxIntervalSeconds) från samma vercel.json-array som
  crontaben, så en schemalagd path som kontrollen inte känner till inte kan
  uppstå. Drift-testet jämför filen byte för byte.
- supabase/migrations/20261115190000_cron_heartbeats.sql: en rad per path
  (declared_at, last_started_at, last_completed_at, last_status,
  last_http_status, last_duration_ms). RLS på, noll policies: instansglobal
  schemaläggning är inte tenantdata.
- lib/cron/heartbeat-evaluation.ts: ren utvärdering — ok / pending (aldrig körd
  men deklarerad inom sin egen kadens) / stale. Tröskel 2 x kadens + 120 s.
  Mätt från last_started_at, inte completion: en hängd körning avslutas aldrig
  och supercronic skjuter då upp varje senare tick, så ett completion-baserat
  mått hade sett levande ut.
- lib/cron/heartbeat-store.ts: Supabase-IO. Skrivningar är best effort (kastar
  aldrig — en mätningsskrivning får inte fälla jobbet den mäter); läsningar
  kastar så endpointen kan säga "kan inte verifiera" istället för att ljuga
  grönt. No-op utan Supabase-env.
- app/api/cron/health/route.ts: 200 när alla scheman ligger inom sina fönster,
  503 vid stale eller oläsbart lager. Deklarerar okända paths först (nytt jobb
  får respit istället för omedelbart rött). Autentiseras med befintlig
  cron-hemlighet, report:false så en felkopplad probe inte spammar auth-larm.
- lib/api/with-cron-context.ts: skriver heartbeat per körning (path ur
  request-URL:en) med status och duration. 401 räknas inte som körning.
- docker-compose.yml: cron-healthcheck byter från supercronic-grep till att
  anropa /api/cron/health med `$${CRON_SECRET}`/`$${APP_URL}` (dubbelt $ krävs,
  annars interpolerar compose på värden), start_period 120 s.

Migrationen är redan applicerad på accounted-sb-db (additiv, 0 rader) så
endpointen fungerar direkt vid deploy. Ordning vid utrullning: deploya appen
först, recreata cron-containern sedan — den gamla imagen saknar routen, och
healthchecken failar då korrekt stängt (verifierat i containern: curl -f ger
404/rc=22 mot icke-deployad route).

Verifiering: 99 nya tester (kadens 60/120/300/3600/7200/86400/604800 s,
29 februari, cron-regeln OR; utvärdering ok/pending/stale/hängd körning;
endpoint 200/503/401/unverifiable; wiring inklusive 401 utan heartbeat och
kastat heartbeat-fel som inte fäller körningen; drift av genererad fil).
Hela sviten 1687 filer / 22 400 tester grön; check:types 533/533; check:lint
0 fel; check:guards passed.

Revert: git revert <sha> (kod + migration + compose i en commit). Migrationen
kan lämnas kvar om bara koden rullas tillbaka.
This commit is contained in:
Claude Code
2026-11-15 19:56:45 +01:00
parent 9482d64aa2
commit c3a2ace846
15 changed files with 1616 additions and 3 deletions
@@ -4,6 +4,8 @@ import { join, dirname } from 'node:path'
import { fileURLToPath } from 'node:url'
import {
buildCrontab,
buildScheduleEntries,
buildScheduleModule,
readVercelCrons,
scheduleFor,
EXCLUDED_PATHS,
@@ -283,3 +285,39 @@ describe('every cron route has a schedule', () => {
}
})
})
describe('lib/cron/schedules.generated.ts mirrors the self-hosted crontab', () => {
const generated = readFileSync(join(ROOT, 'lib', 'cron', 'schedules.generated.ts'), 'utf8')
const entries = buildScheduleEntries(crons, 'self-hosted')
it('on-disk file matches the generator output byte for byte', () => {
expect(
generated,
'lib/cron/schedules.generated.ts is stale: run `npm run crontabs:generate`.',
).toBe(buildScheduleModule(crons, 'self-hosted'))
})
it('covers exactly the paths crontab.self-hosted runs', () => {
expect(entries.map((entry) => entry.path)).toEqual(
parseCrontab(crontabText('self-hosted')).map((job) => job.path),
)
})
it('carries the same schedule string as the crontab it mirrors', () => {
const crontabJobs = parseCrontab(crontabText('self-hosted'))
for (const entry of entries) {
const job = crontabJobs.find((candidate) => candidate.path === entry.path)
expect(job?.schedule, entry.path).toBe(entry.schedule)
}
})
it('gives every path a positive worst-case interval', () => {
// A zero or NaN interval would make the heartbeat check either permanently
// red or permanently green — the two ways this control can be useless.
for (const entry of entries) {
expect(Number.isFinite(entry.maxIntervalSeconds), entry.path).toBe(true)
expect(entry.maxIntervalSeconds, entry.path).toBeGreaterThanOrEqual(60)
expect(entry.maxIntervalSeconds, entry.path).toBeLessThanOrEqual(366 * 86_400)
}
})
})
+91
View File
@@ -24,11 +24,19 @@
import { readFileSync, writeFileSync } from 'node:fs'
import { join, dirname } from 'node:path'
import { fileURLToPath } from 'node:url'
import { describeGap, maxIntervalSeconds } from '../lib/cron/cron-interval'
const __filename = fileURLToPath(import.meta.url)
const ROOT = dirname(dirname(__filename))
const VERCEL_JSON_PATH = join(ROOT, 'vercel.json')
const DOCKER_DIR = join(ROOT, 'docker')
/**
* Heartbeat detection reads the cadence at runtime, so the same vercel.json
* array is also emitted as a TypeScript module. One generator, one source of
* truth: an expression that is scheduled but unknown to the health check is
* exactly the "silently never runs" failure the check exists to catch.
*/
const SCHEDULE_MODULE_PATH = join(ROOT, 'lib', 'cron', 'schedules.generated.ts')
export type CrontabVariant = 'hosted' | 'self-hosted'
@@ -243,6 +251,82 @@ export function buildCrontab(
return `${lines.join('\n')}\n`
}
export interface CronScheduleEntry {
readonly path: string
readonly schedule: string
/** Worst-case seconds between two runs, over a 12-year scan window. */
readonly maxIntervalSeconds: number
}
/**
* The job set one variant actually runs (vercel.json minus exclusions, plus
* that variant's EXTRA_JOBS) with its worst-case cadence resolved.
*
* The health check uses the self-hosted set, because that is the crontab a
* Docker install runs; a hosted deployment gets its schedule from Vercel and is
* not the deployment this check guards.
*/
export function buildScheduleEntries(
crons: VercelCron[],
variant: CrontabVariant,
): CronScheduleEntry[] {
const scheduled = crons
.filter((cron) => !(cron.path in EXCLUDED_PATHS))
.map((cron) => ({ path: cron.path, schedule: scheduleFor(cron, variant) }))
const extra = EXTRA_JOBS[variant].map((job) => ({ path: job.path, schedule: job.schedule }))
return [...scheduled, ...extra].map((job) => ({
path: job.path,
schedule: job.schedule,
maxIntervalSeconds: maxIntervalSeconds(job.schedule),
}))
}
/** Render lib/cron/schedules.generated.ts. Always LF, always newline-terminated. */
export function buildScheduleModule(crons: VercelCron[], variant: CrontabVariant): string {
const entries = buildScheduleEntries(crons, variant)
const width =
entries.reduce((max, entry) => Math.max(max, entry.path.length + 3), 0) + 2
const lines = [
'// AUTO-GENERATED: do not edit. Run `npm run crontabs:generate` to regenerate.',
'//',
`// Variant: ${variant} (the crontab a Docker install runs).`,
'// Source of truth: the `crons` array in vercel.json, via',
'// scripts/generate-crontabs.ts. scripts/__tests__/generate-crontabs.test.ts',
'// fails CI if this file drifts from it.',
'//',
'// Consumed by lib/cron/heartbeats.ts: app/api/cron/health compares the last',
'// recorded run of each path against maxIntervalSeconds and answers 503 when a',
'// schedule stops arriving. The container healthcheck on the cron service calls',
'// that endpoint, so a silent stop becomes a visible unhealthy container',
'// instead of a log line nobody reads (see the 2026-11-15 pids_limit incident).',
'//',
'// maxIntervalSeconds is the WORST-CASE gap over a 12-year scan, not an',
'// average: a daily job must be allowed 24 h, and 29 February must not make a',
'// yearly job look dead for four years.',
'',
'export interface CronScheduleEntry {',
' readonly path: string',
' readonly schedule: string',
' /** Worst-case seconds between two runs, over a 12-year scan window. */',
' readonly maxIntervalSeconds: number',
'}',
'',
'export const CRON_SCHEDULES: readonly CronScheduleEntry[] = [',
...entries.map(
(entry) =>
` { path: '${entry.path}',`.padEnd(width + 2) +
` schedule: '${entry.schedule}',`.padEnd(24) +
` maxIntervalSeconds: ${entry.maxIntervalSeconds} }, // ${describeGap(entry.maxIntervalSeconds)}`,
),
']',
'',
]
return `${lines.join('\n')}`
}
function main(): void {
const crons = readVercelCrons(readFileSync(VERCEL_JSON_PATH, 'utf8'))
@@ -282,6 +366,13 @@ function main(): void {
)
}
// The runtime half of the same source of truth: heartbeat detection needs
// each path's worst-case cadence, so the self-hosted job set is emitted as a
// TypeScript module next to the crontab it mirrors.
const scheduleEntries = buildScheduleEntries(crons, 'self-hosted')
writeFileSync(SCHEDULE_MODULE_PATH, buildScheduleModule(crons, 'self-hosted'), 'utf8')
console.log(`Wrote lib/cron/schedules.generated.ts: ${scheduleEntries.length} schedules`)
const skipped = Object.keys(EXCLUDED_PATHS)
if (skipped.length > 0) {
console.log(`Excluded ${skipped.length} path(s): ${skipped.join(', ')}`)