Files
accounted/lib/cron/heartbeat-evaluation.ts
T
Claude Code c3a2ace846
masterplan-lock / check (pull_request) Successful in 8s
security / scan (pull_request) Failing after 2m43s
feat(cron): missad-tick-detektion — heartbeat per schema, 503 när ett jobb slutar komma
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.
2026-11-15 19:56:45 +01:00

147 lines
5.1 KiB
TypeScript

/**
* Missed-cron detection, the pure half.
*
* The store and the endpoint live in ./heartbeat-store.ts and
* app/api/cron/health/route.ts; everything that decides ok/stale is here so it
* can be tested without a database.
*
* The threshold is deliberately generous, because the cost of the two mistakes
* is not symmetric. Too tight and every slow run flaps the container
* unhealthy, which trains people to ignore the check. Too loose and a stalled
* schedule keeps looking fine — the failure mode this exists to catch (see the
* 2026-11-15 pids_limit incident in the cron_heartbeats migration). Two missed
* intervals plus a two-minute floor means a per-minute job is flagged after
* 4 minutes and a daily job after 48 h 2 min, while one skipped tick or one
* slow run is not.
*/
import type { CronScheduleEntry } from './schedules.generated'
/** A run is stale after this many missed intervals. */
export const CRON_STALE_MULTIPLIER = 2
/** Floor added on top of the interval, absorbing clock skew and one slow run. */
export const CRON_STALE_GRACE_SECONDS = 120
export type CronHeartbeatState = 'ok' | 'pending' | 'stale'
/** A row as the store returns it (snake_case columns already mapped). */
export interface CronHeartbeatRow {
path: string
declaredAt: string | null
lastStartedAt: string | null
lastCompletedAt: string | null
lastStatus: string | null
lastHttpStatus: number | null
lastDurationMs: number | null
}
export interface CronHeartbeatCheck {
path: string
schedule: string
maxIntervalSeconds: number
/** Age at which this path is reported stale. */
allowedAgeSeconds: number
lastStartedAt: string | null
ageSeconds: number | null
state: CronHeartbeatState
lastStatus: string | null
lastHttpStatus: number | null
lastDurationMs: number | null
}
export interface CronHeartbeatReport {
/** False only when at least one path is stale. Pending paths do not fail. */
ok: boolean
checkedAt: string
total: number
stale: number
pending: number
checks: CronHeartbeatCheck[]
}
export function allowedAgeSeconds(maxIntervalSeconds: number): number {
return maxIntervalSeconds * CRON_STALE_MULTIPLIER + CRON_STALE_GRACE_SECONDS
}
function ageInSeconds(reference: string | null, now: number): number | null {
if (!reference) return null
const at = Date.parse(reference)
if (!Number.isFinite(at)) return null
return Math.max(0, Math.round((now - at) / 1000))
}
/**
* Evaluate every scheduled path against its heartbeat row.
*
* States:
* ok — a run started within the allowed age.
* pending — no run yet, but the path has not been declared longer than its
* own cadence allows. A freshly added job, or a fresh install.
* stale — a run used to arrive and stopped, OR the path was declared
* longer ago than its cadence and has never run. Both are real
* defects; only `stale` fails the endpoint.
*
* A path with neither a row nor a declaration is reported `pending` here; the
* route declares it before evaluating, so this only happens on the first call.
*/
export function evaluateCronHeartbeats(params: {
entries: readonly CronScheduleEntry[]
rows: readonly CronHeartbeatRow[]
now: number
}): CronHeartbeatReport {
const byPath = new Map(params.rows.map((row) => [row.path, row]))
const checks: CronHeartbeatCheck[] = params.entries.map((entry) => {
const row = byPath.get(entry.path)
const allowed = allowedAgeSeconds(entry.maxIntervalSeconds)
// Staleness is measured from the last START. A run that hangs never
// completes, and supercronic skips every later tick while it hangs, so
// last_completed_at would keep a dead schedule looking alive.
const ranAt = row?.lastStartedAt ?? null
const reference = ranAt ?? row?.declaredAt ?? null
const age = ageInSeconds(reference, params.now)
let state: CronHeartbeatState = 'ok'
if (age === null) state = 'pending'
else if (age > allowed) state = 'stale'
else if (ranAt === null) state = 'pending'
return {
path: entry.path,
schedule: entry.schedule,
maxIntervalSeconds: entry.maxIntervalSeconds,
allowedAgeSeconds: allowed,
lastStartedAt: ranAt,
ageSeconds: age,
state,
lastStatus: row?.lastStatus ?? null,
lastHttpStatus: row?.lastHttpStatus ?? null,
lastDurationMs: row?.lastDurationMs ?? null,
}
})
const stale = checks.filter((check) => check.state === 'stale').length
const pending = checks.filter((check) => check.state === 'pending').length
return {
ok: stale === 0,
checkedAt: new Date(params.now).toISOString(),
total: checks.length,
stale,
pending,
checks,
}
}
/**
* A run that finished non-2xx is not a missed tick (it ran), but it is worth
* surfacing next to the heartbeat: a schedule that "works" while every run
* fails is the same silent outage with an extra step.
*/
export function isFailingStatus(status: string | null, httpStatus: number | null): boolean {
if (status && status !== 'ok') return true
return httpStatus !== null && (httpStatus < 200 || httpStatus >= 300)
}