Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions changelog.d/1230.added.md
Original file line number Diff line number Diff line change
@@ -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.
12 changes: 12 additions & 0 deletions deploy/prometheus/fledge-alerts.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
16 changes: 16 additions & 0 deletions docs/architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
5 changes: 5 additions & 0 deletions docs/deploy.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
29 changes: 23 additions & 6 deletions docs/observability.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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:

Expand All @@ -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.
Expand Down
2 changes: 1 addition & 1 deletion src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5764,7 +5764,7 @@ export async function buildApp(options: BuildOptions): Promise<BuiltApp> {
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,
Expand Down
61 changes: 61 additions & 0 deletions src/db.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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<LiveLeaseRow>(
`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<ReapedLeaseRow>(
`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
Expand Down
55 changes: 54 additions & 1 deletion src/jobs/automationHealth.ts
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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 }>
Expand All @@ -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<string, string> = {}): number | null {
Expand All @@ -88,7 +120,7 @@ function gaugeValue(name: string, labels: Record<string, string> = {}): 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')
Expand All @@ -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)),
},
}
}
15 changes: 13 additions & 2 deletions src/jobs/service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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()
Expand Down
22 changes: 19 additions & 3 deletions src/views/pages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 `<section class="card">
<h2>${escapeHtml(t('自动化健康', 'Automation health'))}</h2>
<p class="muted">${escapeHtml(t('读取刚结束的调度检查;数字来自进程内的计数器,重启后从零开始。', 'From the dispatch check that just ran; the numbers come from in-process counters and restart from zero.'))}</p>
<p class="muted">${escapeHtml(t('读取刚结束的调度检查;计数器重启后从零开始,租约记录来自数据库。', 'From the dispatch check that just ran; the counters restart from zero, while the lease rows are read from the database.'))}</p>
<div class="list">
<div class="list-row"><div class="list-main"><strong>${idle}</strong><small>${escapeHtml(idleBody)}</small></div></div>
<div class="list-row"><div class="list-main"><strong>${escapeHtml(automationLatencyText(t, summary.dispatchLatencyMs))}</strong><small>${escapeHtml(latencyBody)}</small></div></div>
<div class="list-row"><div class="list-main"><strong>${summary.queueDepth === null ? '—' : summary.queueDepth}</strong><small>${escapeHtml(queueBody)}</small></div></div>
<div class="list-row"><div class="list-main"><strong>${lease === null ? '—' : escapeHtml(automationWaitText(t, lease.ageSeconds))}</strong><small>${escapeHtml(leaseBody)}</small></div></div>
<div class="list-row"><div class="list-main"><strong>${reaped === null ? '—' : escapeHtml(automationWaitText(t, reaped.ageSeconds))}</strong><small>${escapeHtml(reapedBody)}</small></div></div>
</div>
<p class="fine">${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.`,
))}</p>
</section>`
}
Expand Down
Loading
Loading