From 7f3737cee2011207055d18afdad140865ca770a2 Mon Sep 17 00:00:00 2001 From: HugoXK Date: Mon, 23 Nov 2026 16:10:47 +0800 Subject: [PATCH 1/2] feat(jobs): expose lease health in metrics and the admin console (#1230) --- changelog.d/1230.added.md | 1 + deploy/prometheus/fledge-alerts.yml | 12 +++ docs/architecture.md | 16 ++++ docs/observability.md | 29 +++++-- src/app.ts | 2 +- src/db.ts | 61 ++++++++++++++ src/jobs/automationHealth.ts | 55 ++++++++++++- src/jobs/service.ts | 15 +++- src/views/pages.ts | 22 ++++- test/automationHealth.test.ts | 25 +++++- test/leaseHealth.test.ts | 123 ++++++++++++++++++++++++++++ test/pages.test.ts | 6 +- 12 files changed, 350 insertions(+), 17 deletions(-) create mode 100644 changelog.d/1230.added.md create mode 100644 test/leaseHealth.test.ts diff --git a/changelog.d/1230.added.md b/changelog.d/1230.added.md new file mode 100644 index 00000000..016fcb40 --- /dev/null +++ b/changelog.d/1230.added.md @@ -0,0 +1 @@ +The admin automation card now names the oldest live job lease (job, kind, repository, age and expiry) and the newest reaped attempt, both read from the durable lease rows rather than the process counters. `/metrics` adds `fledge_job_lease_age_seconds` (absent when no lease is live) and `fledge_job_lease_renew_failures_total{kind}` for a live renewal refused because the lease moved, beside the existing `fledge_lease_expired_total{kind}` for the reaper's terminal attempt, and `FledgeLeaseReaped` pages when that counter increases within 15 minutes. diff --git a/deploy/prometheus/fledge-alerts.yml b/deploy/prometheus/fledge-alerts.yml index e0d3435b..db9e7524 100644 --- a/deploy/prometheus/fledge-alerts.yml +++ b/deploy/prometheus/fledge-alerts.yml @@ -77,6 +77,18 @@ groups: summary: Fledge p95 dispatch latency is above 15 minutes runbook_url: https://github.com/HugoXK/fledge/blob/main/docs/observability.md + - alert: FledgeLeaseReaped + # #1230: a worker that stopped renewing loses its lease and the reaper + # writes a terminal `reaped` attempt. One is enough to look, so there is + # no `for` delay; the 15-minute increase keeps a reaped lease visible for + # a window instead of paging on a raw counter that never resets. + expr: increase(fledge_lease_expired_total[15m]) > 0 + labels: + severity: warning + annotations: + summary: Fledge reaped a job lease whose worker stopped renewing it + runbook_url: https://github.com/HugoXK/fledge/blob/main/docs/observability.md + - alert: FledgeRouterUnavailable # #282: the shared model router is a dependency with its own health # endpoint. `fledge_router_up` is absent — not 0 — when diff --git a/docs/architecture.md b/docs/architecture.md index 35db4313..c898b7d0 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -2286,6 +2286,22 @@ branch and repository contents with the repository token. A 401/403 marks `repos The repository page shows the credential banner until a refresh or a successful preflight clears it. +### Lease health (#1230) + +A running job holds a worker lease; the heartbeat renews it every fifth of the +lease window, and a renewal refused because another worker took the row is a lost +lease. The scheduler publishes `fledge_job_lease_age_seconds` for the oldest +lease still held, on every tick, and removes the series when no lease is live so +an empty panel means "none" rather than a stale reading. A live job's refused +renewal increments `fledge_job_lease_renew_failures_total{kind}`; the reaper's +terminal `reaped` attempt increments `fledge_lease_expired_total{kind}`. +`FledgeLeaseReaped` pages on the 15-minute increase of the reaped counter. + +The `/admin/metrics` automation card reads the same rows from the database +instead of the process counters: it names the oldest live lease (job, kind, +repository, age and expiry) and the newest reaped attempt (job, kind, repository +and age). The lease rows survive a restart even though the counters do not. + ### The model router as a dependency The shared model router serves every model call the bridge and the gateway make, diff --git a/docs/observability.md b/docs/observability.md index 56516329..68f3b18a 100644 --- a/docs/observability.md +++ b/docs/observability.md @@ -40,9 +40,19 @@ Core series: dispatch, and a repository that is merely throttled shows `cooldown` — so a `cooldown` on a repository whose last work job succeeded means something other than the success wait held it. -- `fledge_queue_depth`, `fledge_lease_expired_total`, +- `fledge_queue_depth`, `fledge_lease_expired_total{kind}`, `fledge_admission_rejected_total{reason}`, `fledge_meta_issue_total`, `fledge_auto_merge_candidates`, `fledge_ops_alerts_open` +- `fledge_job_lease_age_seconds` — the age of the oldest lease the platform + still holds, published on each scheduler tick. The series is **absent** when no + lease is live, so an empty panel means "no live lease", not "the scheduler is + silent". The `/admin/metrics` automation card names the job, kind and + repository behind the reading. +- `fledge_job_lease_renew_failures_total{kind}` — a live job's heartbeat renewal + was refused because the lease moved; a terminal row releasing its lease is the + normal end and is not counted. The reaper's own count is + `fledge_lease_expired_total{kind}`, which counts the terminal `reaped` + attempt. - `fledge_retries_total{kind}`, `fledge_merges_total{result}`, `fledge_path_guard_blocked_total`, `fledge_verification_failed_total` - `fledge_gateway_requests_total{tenant}` — only while @@ -94,11 +104,13 @@ Core series: leaving the previous reading, so an empty panel means "unknown", and a deployment with no `MODEL_ROUTER_URL` publishes none of these series. -The `/admin/metrics` page carries the same three numbers as one `Automation -health` card — repositories with ready work and no active job, the mean dispatch -latency since the process started, and the queue depth — so an operator reading -the page and an operator reading a dashboard are looking at one measurement, not -two definitions of it. +The `/admin/metrics` page carries the same numbers as one `Automation health` +card — repositories with ready work and no active job, the mean dispatch latency +since the process started, the queue depth, the oldest live lease and the last +reaped lease — so an operator reading the page and an operator reading a +dashboard are looking at one measurement, not two definitions of it. The counter +rows restart from zero with the process; the two lease rows are read from the +database, so a reap survives a restart. Automation alerts: @@ -116,6 +128,11 @@ Automation alerts: - `FledgeDispatchLatencyHigh` pages when the p95 dispatch latency is above 15 minutes. Thresholds are configured in the rules file; the store threshold is configured by `AUTOMATION_IDLE_ALERT_MINUTES`. +- `FledgeLeaseReaped` pages when `increase(fledge_lease_expired_total[15m]) > 0`: + a worker stopped renewing and the reaper wrote a terminal `reaped` attempt. The + counter names the job kind; the admin card names the job, kind and repository. + A refused renewal that has not been reaped yet is + `fledge_job_lease_renew_failures_total{kind}`. - Labels carry a `owner/name` repository label, the job kind and the reason. No issue title, URL, token or email reaches a metric label: the dispatcher passes only those three values. diff --git a/src/app.ts b/src/app.ts index 77d853d8..5612c29f 100644 --- a/src/app.ts +++ b/src/app.ts @@ -5764,7 +5764,7 @@ export async function buildApp(options: BuildOptions): Promise { alerts: store.alerts({ usdCny: config.quota.usdCny, automationIdleMinutes: config.ops.automationIdleAlertMinutes, instancesManaged: config.flybot.instanceImage !== '' }), windowDays, failures: failureBreakdown(store.failedJobsSince(since)), - automation: automationHealth(), + automation: automationHealth(store), since, notice: request.flash?.notice?.text, error: request.flash?.error?.text, diff --git a/src/db.ts b/src/db.ts index e19503f4..216d30c4 100644 --- a/src/db.ts +++ b/src/db.ts @@ -726,6 +726,33 @@ export interface JobAttemptRow { refused_reason: string | null } +// #1230: the lease a live job holds, as one row the admin card and the age +// gauge can read. `since` is the attempt start for a running job and the row's +// own start/creation time for a claim that has not started yet. +export interface LiveLeaseRow { + job_id: string + kind: string + repo_id: string + owner: string + name: string + lease_owner: string | null + lease_until: string | null + since: string +} + +// #1230: the newest attempt the reaper closed. The attempt row is written in +// the transaction that finalises the job, so this is the durable record of a +// reap rather than an in-process counter. +export interface ReapedLeaseRow { + job_id: string + kind: string + repo_id: string + owner: string + name: string + at: string | null + error: string | null +} + export interface WorkItemRow { id: string repo_id: string @@ -7649,6 +7676,40 @@ export class Store { ) } + // #1230: the oldest lease the platform still holds. A queued row can hold a + // dispatch claim before it starts, so both active statuses count. A running + // row's lease age starts at its attempt; a claim that has not started falls + // back to the row's own start/creation time. + oldestLiveLease(): LiveLeaseRow | undefined { + return this.get( + `SELECT j.id AS job_id, j.kind, j.repo_id, r.owner, r.name, + j.lease_owner, j.lease_until, + COALESCE(a.started_at, j.started_at, j.created_at) AS since + FROM jobs j + JOIN repos r ON r.id = j.repo_id + LEFT JOIN job_attempts a ON a.job_id = j.id AND a.status = 'running' + WHERE j.status IN ('queued', 'running') AND j.lease_until IS NOT NULL + ORDER BY since ASC, j.id ASC + LIMIT 1`, + ) + } + + // #1230: the newest attempt the reaper closed, for the same card. Only a + // terminal `reaped` attempt counts; a failed or succeeded attempt is a normal + // end, not a lost lease. + lastReapedLease(): ReapedLeaseRow | undefined { + return this.get( + `SELECT a.job_id, j.kind, j.repo_id, r.owner, r.name, + a.finished_at AS at, a.error + FROM job_attempts a + JOIN jobs j ON j.id = a.job_id + JOIN repos r ON r.id = j.repo_id + WHERE a.status = 'reaped' AND a.finished_at IS NOT NULL + ORDER BY a.finished_at DESC, a.id DESC + LIMIT 1`, + ) + } + // #247: start one dispatch attempt in the same transaction that marks the job // running. The attempt number chains through `jobs.retry_of`, so a retry after // a reap is attempt N+1 linked to the attempt it continues; the lease epoch is diff --git a/src/jobs/automationHealth.ts b/src/jobs/automationHealth.ts index 1a58ebbb..6e2e35c2 100644 --- a/src/jobs/automationHealth.ts +++ b/src/jobs/automationHealth.ts @@ -1,3 +1,4 @@ +import type { Store } from '../db.js' import { clearGauge, incCounter, metricsSnapshot, observeHistogram, setGauge } from '../lib/metrics.js' // #807: the console could say when the last run happened, not whether the @@ -67,6 +68,33 @@ export function recordDispatched(input: { repo: RepoSeries; kind: string; readyA observeHistogram('fledge_automation_dispatch_latency_seconds', Math.max(0, input.now - input.readyAt) / 1_000, { kind: input.kind }, 'Time from ready work to a dispatched job') } +// #1230: the oldest live lease is a gauge, not a histogram. It is published on +// every scheduler tick and removed when no job holds a lease, so an empty panel +// means "no live lease", not "the scheduler is silent". The attempt's start is +// the lease grant; a queued claim that has not started falls back to the row. +export function recordLeaseHealth(input: { oldestSince: number | null; now: number }): void { + if (input.oldestSince === null || !Number.isFinite(input.oldestSince)) { + clearGauge('fledge_job_lease_age_seconds') + return + } + setGauge('fledge_job_lease_age_seconds', Math.max(0, Math.round((input.now - input.oldestSince) / 1_000)), {}, 'Seconds the oldest live job lease has been held') +} + +export interface LeaseHealth { + jobId: string + kind: string + repo: string + ageSeconds: number + expiresInSeconds: number | null +} + +export interface ReapedLeaseHealth { + jobId: string + kind: string + repo: string + ageSeconds: number +} + export interface AutomationHealthSummary { /** Repositories that have ready work and no active job, oldest wait first. */ idleWithWork: Array<{ repo: string; seconds: number }> @@ -75,6 +103,10 @@ export interface AutomationHealthSummary { /** Mean over the samples taken since this process started; null when none. */ dispatchLatencyMs: number | null dispatchSamples: number + /** The oldest lease the platform still holds; null when none is live. */ + lease: LeaseHealth | null + /** The newest attempt the reaper closed; null when none was recorded. */ + lastReaped: ReapedLeaseHealth | null } function gaugeValue(name: string, labels: Record = {}): number | null { @@ -88,7 +120,7 @@ function gaugeValue(name: string, labels: Record = {}): number | return null } -export function automationHealth(): AutomationHealthSummary { +export function automationHealth(store?: Store, now = Date.now()): AutomationHealthSummary { const snapshot = metricsSnapshot() const idleWithWork = snapshot.gauges .filter((entry) => entry.name === 'fledge_automation_idle_with_work_seconds') @@ -101,11 +133,32 @@ export function automationHealth(): AutomationHealthSummary { sum += entry.sum count += entry.count } + const live = store?.oldestLiveLease() + const reaped = store?.lastReapedLease() return { idleWithWork, queueDepth: gaugeValue('fledge_queue_depth'), activeJobs: gaugeValue('fledge_jobs_active'), dispatchLatencyMs: count === 0 ? null : Math.round((sum / count) * 1_000), dispatchSamples: count, + lease: live === undefined + ? null + : { + jobId: live.job_id, + kind: live.kind, + repo: `${live.owner}/${live.name}`, + ageSeconds: Math.max(0, Math.round((now - Date.parse(live.since)) / 1_000)), + expiresInSeconds: live.lease_until === null + ? null + : Math.max(0, Math.round((Date.parse(live.lease_until) - now) / 1_000)), + }, + lastReaped: reaped === undefined + ? null + : { + jobId: reaped.job_id, + kind: reaped.kind, + repo: `${reaped.owner}/${reaped.name}`, + ageSeconds: reaped.at === null ? 0 : Math.max(0, Math.round((now - Date.parse(reaped.at)) / 1_000)), + }, } } diff --git a/src/jobs/service.ts b/src/jobs/service.ts index 77d46837..27a8361f 100644 --- a/src/jobs/service.ts +++ b/src/jobs/service.ts @@ -61,7 +61,7 @@ import { GithubApp } from '../repos/app.js' import { parseIssueUrl, parsePrUrl } from './prUrl.js' import { promoteDiscoveredIssue } from './discoveryPromotion.js' import { buildCarryOver, buildRunDigest, carryOverPullState, decideNextJob, failureStreak, lastDurationMs, lastWorkSucceeded, MIN_DISCOVERY_INTERVAL_MINUTES, parseCarryOverLink, type CarryOverReader, type OutputKind } from './continuity.js' -import { clearIdleWithWork, readySinceMs, recordBlockedDispatch, recordDispatched, type DispatchBlockReason } from './automationHealth.js' +import { clearIdleWithWork, readySinceMs, recordBlockedDispatch, recordDispatched, recordLeaseHealth, type DispatchBlockReason } from './automationHealth.js' import { isTemporalStatus, summariseDelta, type TemporalDelta, type TemporalStatus } from '../lib/temporal.js' import { planTick, scheduleFromRow, type TickPlan } from '../schedules/tick.js' import { parseRunNowKey } from '../schedules/runNow.js' @@ -4887,7 +4887,14 @@ export class Jobs { private startLeaseHeartbeat(jobId: string, owner: string, leaseMs: number): void { this.clearLeaseHeartbeat(jobId) const timer = setInterval(() => { - if (!this.store.renewJobLease(jobId, owner, leaseMs)) this.clearLeaseHeartbeat(jobId) + if (this.store.renewJobLease(jobId, owner, leaseMs)) return + // A refused renewal on a live row means the lease moved to another worker; + // a terminal row releasing its lease is the normal end and is not counted. + const job = this.store.getJob(jobId) + if (job !== undefined && (job.status === 'queued' || job.status === 'running')) { + incCounter('fledge_job_lease_renew_failures_total', { kind: job.kind }, 1, 'Job lease renewals refused because the lease moved') + } + this.clearLeaseHeartbeat(jobId) }, Math.max(1000, Math.floor(leaseMs / 5))) timer.unref() this.leaseTimers.set(jobId, timer) @@ -4987,6 +4994,10 @@ export class Jobs { incCounter('fledge_lease_expired_total', { kind: job.kind }, 1, 'Jobs whose worker lease expired') this.finish(job.id, { status: 'failed', error: '任务租约过期:worker 未续约。', errorCode: 'JOB_LEASE_EXPIRED' }, revoke, null, null, null, null, true) } + // #1230: one gauge for the oldest lease still held. It is removed when no + // lease is live, so a dashboard says "none", not a stale reading. + const oldestLease = this.store.oldestLiveLease() + recordLeaseHealth({ oldestSince: oldestLease === undefined ? null : Date.parse(oldestLease.since), now: Date.now() }) this.store.deleteExpiredJobTokens() if (Date.now() - this.lastPruneAt > 60 * 60 * 1_000) { this.lastPruneAt = Date.now() diff --git a/src/views/pages.ts b/src/views/pages.ts index 331a1073..1243a2be 100644 --- a/src/views/pages.ts +++ b/src/views/pages.ts @@ -4826,17 +4826,33 @@ export function automationHealthCard(locale: Locale, summary: AutomationHealthSu const queueBody = summary.queueDepth === null ? t('还没有测量。', 'Not measured yet.') : t('等待 worker 的任务数。', 'Jobs waiting for a worker.') + const lease = summary.lease + const leaseBody = lease === null + ? t('没有存活的租约。', 'No live lease.') + : t( + `最老的存活租约:${lease.jobId}(${lease.kind},${lease.repo}),已持有 ${automationWaitText(t, lease.ageSeconds)}${lease.expiresInSeconds === null ? '' : `,${automationWaitText(t, lease.expiresInSeconds)} 后到期`}。`, + `Oldest live lease: ${lease.jobId} (${lease.kind}, ${lease.repo}), held for ${automationWaitText(t, lease.ageSeconds)}${lease.expiresInSeconds === null ? '' : `, expires in ${automationWaitText(t, lease.expiresInSeconds)}`}.`, + ) + const reaped = summary.lastReaped + const reapedBody = reaped === null + ? t('没有租约被回收的记录。', 'No reaped lease recorded.') + : t( + `最近回收:${reaped.jobId}(${reaped.kind},${reaped.repo}),${automationWaitText(t, reaped.ageSeconds)} 前。`, + `Last reaped: ${reaped.jobId} (${reaped.kind}, ${reaped.repo}), ${automationWaitText(t, reaped.ageSeconds)} ago.`, + ) return `

${escapeHtml(t('自动化健康', 'Automation health'))}

-

${escapeHtml(t('读取刚结束的调度检查;数字来自进程内的计数器,重启后从零开始。', 'From the dispatch check that just ran; the numbers come from in-process counters and restart from zero.'))}

+

${escapeHtml(t('读取刚结束的调度检查;计数器重启后从零开始,租约记录来自数据库。', 'From the dispatch check that just ran; the counters restart from zero, while the lease rows are read from the database.'))}

${idle}${escapeHtml(idleBody)}
${escapeHtml(automationLatencyText(t, summary.dispatchLatencyMs))}${escapeHtml(latencyBody)}
${summary.queueDepth === null ? '—' : summary.queueDepth}${escapeHtml(queueBody)}
+
${lease === null ? '—' : escapeHtml(automationWaitText(t, lease.ageSeconds))}${escapeHtml(leaseBody)}
+
${reaped === null ? '—' : escapeHtml(automationWaitText(t, reaped.ageSeconds))}${escapeHtml(reapedBody)}

${escapeHtml(t( - `有就绪工作却没有任务在跑,超过 ${idleAlertMinutes} 分钟就会告警;本页只读,不会触发派发。`, - `An alert fires when ready work waits more than ${idleAlertMinutes} minutes with no job running; this page is read-only and dispatches nothing.`, + `有就绪工作却没有任务在跑,超过 ${idleAlertMinutes} 分钟就会告警;租约被回收也会告警。本页只读,不会触发派发。`, + `An alert fires when ready work waits more than ${idleAlertMinutes} minutes with no job running, and when a lease is reaped; this page is read-only and dispatches nothing.`, ))}

` } diff --git a/test/automationHealth.test.ts b/test/automationHealth.test.ts index 845ae121..132fa60e 100644 --- a/test/automationHealth.test.ts +++ b/test/automationHealth.test.ts @@ -10,7 +10,7 @@ import { recordBlockedDispatch, recordDispatched, } from '../src/jobs/automationHealth.js' -import { metricsSnapshot, renderMetrics, resetMetrics, setGauge } from '../src/lib/metrics.js' +import { incCounter, metricsSnapshot, renderMetrics, resetMetrics, setGauge } from '../src/lib/metrics.js' import { automationHealthCard } from '../src/views/pages.js' const root = fileURLToPath(new URL('..', import.meta.url)) @@ -127,6 +127,8 @@ test('the summary reads the three numbers off the same registry, and says nothin activeJobs: null, dispatchLatencyMs: null, dispatchSamples: 0, + lease: null, + lastReaped: null, }) const now = Date.parse('2026-11-16T12:00:00.000Z') @@ -151,11 +153,15 @@ test('the card names the three numbers in both languages and has an empty state' activeJobs: 1, dispatchLatencyMs: 4500, dispatchSamples: 7, + lease: { jobId: 'job_1', kind: 'iterate', repo: 'octo/demo', ageSeconds: 300, expiresInSeconds: 120 }, + lastReaped: { jobId: 'job_0', kind: 'review', repo: 'octo/demo', ageSeconds: 600 }, }, 30) assert.match(en, /Automation health/) assert.match(en, /1 repository with ready work/) assert.match(en, /4\.5 s/) assert.match(en, />3 { + resetMetrics() + incCounter('fledge_lease_expired_total', { kind: 'iterate' }, 1, 'Jobs whose worker lease expired') + const rendered = renderMetrics() + const rules = readFileSync(`${root}/deploy/prometheus/fledge-alerts.yml`, 'utf8') + const block = /- alert: FledgeLeaseReaped[\s\S]*?(?=\n\s*- alert:|\s*$)/.exec(rules) + assert.ok(block, 'deploy/prometheus/fledge-alerts.yml must page on a reaped lease') + const named = new Set([...block[0].matchAll(/fledge_[a-z0-9_]+/g)].map((match) => match[0])) + assert.ok(named.size > 0, 'the rule must name the series it reads') + for (const name of named) { + assert.match(rendered, new RegExp(`^${name}(_bucket)?[{ ]`, 'm'), `the rule names ${name}, which the code does not record`) + } +}) + diff --git a/test/leaseHealth.test.ts b/test/leaseHealth.test.ts new file mode 100644 index 00000000..55de0e7c --- /dev/null +++ b/test/leaseHealth.test.ts @@ -0,0 +1,123 @@ +import test from 'node:test' +import assert from 'node:assert/strict' +import { Store } from '../src/db.js' +import { makeUser } from './helpers.js' +import { automationHealth, recordLeaseHealth } from '../src/jobs/automationHealth.js' +import { metricsSnapshot, resetMetrics } from '../src/lib/metrics.js' + +function fixture(store: Store, name: string) { + const user = makeUser(store, { login: `${name}-owner`, status: 'approved' }) + const repo = store.createRepo({ + id: `repo_${name}`, + userId: user.id, + owner: 'octo', + name, + defaultBranch: 'main', + tokenEnc: 'x', + permission: 'admin', + repoRole: 'maintainer', + goal: '', + autoIterate: false, + intervalMinutes: 1440, + }) + return { user, repo } +} + +test('the oldest live lease is read from the attempt, with its repo and expiry', () => { + const store = new Store(':memory:') + try { + const { user, repo } = fixture(store, 'live') + const job = store.createJob({ + id: 'job_live', + repoId: repo.id, + userId: user.id, + trigger: 'schedule', + goal: 'g', + callbackHash: 'cb_live', + platformTokenHash: '', + kind: 'iterate', + createdAt: '2026-11-23T10:00:00.000Z', + }) + const attempt = store.startJobAttempt(job.id, 'worker:1', 300_000) + assert.ok(attempt) + store.run('UPDATE jobs SET started_at = ?, lease_until = ? WHERE id = ?', '2026-11-23T10:00:00.000Z', '2026-11-23T10:05:00.000Z', job.id) + store.run('UPDATE job_attempts SET started_at = ? WHERE job_id = ?', '2026-11-23T10:00:00.000Z', job.id) + + assert.equal(store.oldestLiveLease()?.job_id, job.id) + assert.equal(store.oldestLiveLease()?.owner, 'octo') + assert.equal(store.oldestLiveLease()?.name, 'live') + assert.equal(store.oldestLiveLease()?.since, '2026-11-23T10:00:00.000Z') + + const summary = automationHealth(store, Date.parse('2026-11-23T10:02:00.000Z')) + assert.deepEqual(summary.lease, { + jobId: job.id, + kind: 'iterate', + repo: 'octo/live', + ageSeconds: 120, + expiresInSeconds: 180, + }) + assert.equal(summary.lastReaped, null) + } finally { + store.close() + } +}) + +test('the last reaped lease is the newest terminal reaped attempt', () => { + const store = new Store(':memory:') + try { + const { user, repo } = fixture(store, 'reaped') + const job = store.createJob({ + id: 'job_reaped', + repoId: repo.id, + userId: user.id, + trigger: 'schedule', + goal: 'g', + callbackHash: 'cb_reaped', + platformTokenHash: '', + kind: 'review', + }) + const attempt = store.startJobAttempt(job.id, 'worker:1', 300_000) + assert.ok(attempt) + const claimed = store.claimJobTerminal( + job.id, + 'failed', + null, + { error: 'lease expired', finished_at: '2026-11-23T10:06:00.000Z' }, + { epoch: attempt.epoch, outcome: 'reaped', error: 'lease expired' }, + ) + assert.equal(claimed, true) + // The attempt's terminal time is written by `claimJobTerminal`; pin it so + // the card's age is deterministic rather than reading the wall clock. + store.run('UPDATE job_attempts SET finished_at = ? WHERE job_id = ?', '2026-11-23T10:06:00.000Z', job.id) + + const reaped = store.lastReapedLease() + assert.equal(reaped?.job_id, job.id) + assert.equal(reaped?.kind, 'review') + assert.equal(reaped?.at, '2026-11-23T10:06:00.000Z') + assert.equal(reaped?.owner, 'octo') + assert.equal(reaped?.name, 'reaped') + + const summary = automationHealth(store, Date.parse('2026-11-23T10:08:00.000Z')) + assert.deepEqual(summary.lastReaped, { + jobId: job.id, + kind: 'review', + repo: 'octo/reaped', + ageSeconds: 120, + }) + assert.equal(summary.lease, null) + } finally { + store.close() + } +}) + +test('the lease gauge is set from the oldest start and removed when none is live', () => { + resetMetrics() + const now = Date.parse('2026-11-23T10:02:00.000Z') + recordLeaseHealth({ oldestSince: Date.parse('2026-11-23T10:00:00.000Z'), now }) + const gauge = metricsSnapshot().gauges.find((entry) => entry.name === 'fledge_job_lease_age_seconds') + assert.ok(gauge) + assert.equal(gauge.value, 120) + + recordLeaseHealth({ oldestSince: null, now }) + assert.equal(metricsSnapshot().gauges.some((entry) => entry.name === 'fledge_job_lease_age_seconds'), false) +}) diff --git a/test/pages.test.ts b/test/pages.test.ts index cb3f2e6b..39d03e83 100644 --- a/test/pages.test.ts +++ b/test/pages.test.ts @@ -1114,7 +1114,7 @@ test('the admin metrics page shows delivery, cost and alerts', () => { windowDays: 7, failures: [{ kind: 'quota', count: 1 }], since: '2026-01-01T00:00:00.000Z', - automation: { idleWithWork: [{ repo: 'o/r', seconds: 1_200 }], queueDepth: 2, activeJobs: 1, dispatchLatencyMs: 4_500, dispatchSamples: 3 }, + automation: { idleWithWork: [{ repo: 'o/r', seconds: 1_200 }], queueDepth: 2, activeJobs: 1, dispatchLatencyMs: 4_500, dispatchSamples: 3, lease: null, lastReaped: null }, }) assert.match(page, /Delivery efficiency/) // #807: the automation card is on the same page as the numbers it reads. @@ -1607,7 +1607,7 @@ test('admin metrics shows the failure breakdown', () => { windowDays: 30, failures: [{ kind: 'quota', count: 1 }, { kind: 'github', count: 1 }], since: '2026-01-01T00:00:00.000Z', - automation: { idleWithWork: [], queueDepth: 0, activeJobs: 0, dispatchLatencyMs: null, dispatchSamples: 0 }, + automation: { idleWithWork: [], queueDepth: 0, activeJobs: 0, dispatchLatencyMs: null, dispatchSamples: 0, lease: null, lastReaped: null }, }) assert.match(page, /Failure breakdown/) assert.match(page, /Platform quota exhausted/) @@ -3287,7 +3287,7 @@ function sparkMetricsPage(input: { windowDays: input.windowDays ?? 7, failures: [], since: '2026-01-01T00:00:00.000Z', - automation: { idleWithWork: [], queueDepth: 0, activeJobs: 1, dispatchLatencyMs: 4_500, dispatchSamples: 3 }, + automation: { idleWithWork: [], queueDepth: 0, activeJobs: 1, dispatchLatencyMs: 4_500, dispatchSamples: 3, lease: null, lastReaped: null }, }) } finally { store.close() From 4ea3de4435050335476729246c45e2dc3acc4a9e Mon Sep 17 00:00:00 2001 From: HugoXK Date: Mon, 23 Nov 2026 16:34:41 +0800 Subject: [PATCH 2/2] docs(deploy): name the lease-reaped rule and the lease health surface --- docs/deploy.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/docs/deploy.md b/docs/deploy.md index 8cdb640b..aa4c39e4 100644 --- a/docs/deploy.md +++ b/docs/deploy.md @@ -1413,6 +1413,11 @@ problem through `OPS_ALERT_COOLDOWN_MINUTES`: a stale copy, a failed drill, or a drill older than the expected interval. A platform that has never written a copy raises nothing; the card's `no backup copy recorded yet` is the answer there. +`FledgeLeaseReaped` is the lease rule: it pages when +`increase(fledge_lease_expired_total[15m]) > 0`, because the reaper writes a +terminal `reaped` attempt when a worker stops renewing. The admin Automation +health card names the oldest live lease and the last reaped attempt; the series +and their presence rules are in `docs/observability.md`. Back up `.env` separately (it contains the encryption key). Without `TOKEN_ENCRYPTION_KEY`, stored GitHub/model tokens cannot be decrypted.