diff --git a/README.md b/README.md index ac57806..cf06518 100644 --- a/README.md +++ b/README.md @@ -431,6 +431,31 @@ already-delivered events from starting repairs. Removing the ID re-enables admission after a fresh observation. This does not cancel an already-running response; settle that owner separately before changing its work. +### CI jobs that are not CI faults + +Some jobs fail to say something about the change under test: a pull request +without a milestone, a title that fails the lint, a review bot's verdict. They +are not faults of the runners. List them in `remediation.ignoredCiJobs` in +`settings.json` and no case is filed when they fail; cases already filed for +them are closed. + +```json +"remediation": { + "ignoredCiJobs": [ + { "workflow": "Check PR milestone", "note": "a pull request without a milestone" }, + { "repo": "dashpay/platform", "workflow": "Pull Request Linter" }, + { "repo": "dashpay/dash-evo-tool", "job": "Platform pin guard" } + ] +} +``` + +An entry takes `repo`, `workflow`, `job`, `event` and `branch`, and needs at +least a `workflow` or a `job`. Every field given must match; `*` matches any run +of characters and case is ignored. `note` is for the reader. The failures still +appear on the CI page and in its counts: only the remediation cases go. The +console refuses to save a malformed list; a list damaged on disk ignores +nothing. How cases end in general is in `deploy/INCIDENTS.md`. + Console GitHub login sessions last seven days from sign-in (both the server session and browser cookie). Existing sessions keep their original expiry; sign in again to receive the new lifetime. After a console deployment, verify retained capabilities as well as legacy APIs: diff --git a/agent/aws-health.test.js b/agent/aws-health.test.js index 77d5926..c6dda66 100644 --- a/agent/aws-health.test.js +++ b/agent/aws-health.test.js @@ -6,7 +6,7 @@ import { join } from 'node:path'; import { createAwsHealth } from './aws-health.js'; import { writeAtomic, readJSON } from '../shared/settings.js'; import { DEFAULT_SETTINGS } from '../shared/settings.js'; -import { deriveIssues, reconcile } from '../server/incidents.js'; +import { deriveIssues, issueId, reconcile } from '../server/incidents.js'; const fixture = JSON.parse(readFileSync(new URL('../shared/fixtures/dynamodb-scale-in.json', import.meta.url))); const now = Date.parse('2026-10-02T18:00:00Z'); @@ -60,7 +60,17 @@ test('exact read/write alarms replay as verified informational controls and posi assert.equal(prior.issues.filter((i) => i.code === 'aws_alarm').length, 2); const current = derive(health); assert.equal(current.issues.filter((i) => i.code === 'aws_alarm').length, 0); - assert.equal(current.issues.filter((i) => i.code === 'aws_scaling_control' && i.severity === 'info').length, 2); + assert.equal(current.issues.filter((i) => i.code === 'aws_scaling_control').length, 0, 'a verified control alarms by design: it is not a case'); + // Cases an earlier release filed for these controls end; none is filed again. + const legacy = health.alarms.map((a) => ({ id: issueId('aws', a.region, a.name, 'aws_scaling_control'), domain: 'aws', scope: a.region, target: a.name, + code: 'aws_scaling_control', severity: 'info', status: 'open', sourceKey: 'aws:health', revision: 203, + observedAt: oldHealth.at, firstSeen: oldHealth.at, lastSeen: oldHealth.at, lastFaultAt: oldHealth.at, lastEventAt: oldHealth.at })); + const controls = (state) => state.issues.filter((i) => i.code === 'aws_scaling_control'); + const ended = reconcile({ schemaVersion: 1, issues: legacy, outbox: [] }, current, now); + assert.equal(controls(ended).length, 2); + for (const issue of controls(ended)) assert.deepEqual([issue.status, issue.resolutionEvidence.reason, issue.revision], ['resolved', 'verified_control_signal', 204]); + const later = { ...health, at: new Date(now + 60_000).toISOString(), alarms: health.alarms.map((a) => ({ ...a, scalingControl: { ...a.scalingControl, verifiedAt: new Date(now + 60_000).toISOString() } })) }; + assert.deepEqual(controls(reconcile(ended, derive(later, now + 60_000), now + 60_000)).map((i) => i.status), ['resolved', 'resolved'], 'still in ALARM, and not filed again'); const next = reconcile(prior, current, now); for (const issue of next.issues.filter((i) => i.code === 'aws_alarm')) { assert.equal(issue.status, 'resolved'); diff --git a/deploy/INCIDENTS.md b/deploy/INCIDENTS.md index 6c13ae2..d3637ea 100644 --- a/deploy/INCIDENTS.md +++ b/deploy/INCIDENTS.md @@ -14,11 +14,58 @@ Admins, or a dedicated read-only bearer token loaded through state. Never put tokens in query strings or reuse the OAuth/agent credential. Records carry stable fingerprints, revisions, first/last observation, severity, -source identity, and open/resolved state. Resolution requires positive fresh +source identity, and open/resolved state. Recovery requires positive fresh rule-specific evidence. Missing observations, maintenance suppression and failed collection never count as recovery. Evidence is untrusted data, not executable instructions. Incident history is separate from operation history. +### How a case ends + +A case that could only end by a proof that can never arrive (a job that already +left the queue, a host that no longer exists) used to stay open for good, and +the queue filled with them. The rules below end them. A resolved case records +why in `resolutionEvidence.reason`, and the board shows two kinds of ending +apart. + +Three kinds of case still wait for their own proof and can stay open: an +`aws_collection_failed` for a scan that is not refreshed with every inventory +(it has no completeness clock of its own), an `aws_alarm` that moved from +`ALARM` to `INSUFFICIENT_DATA`, and every case of a CI host listed in +`remediation.excludedCiHosts`, which is left exactly as it is while excluded. + +**Recovered**: monitoring saw the fault end. + +| Reason | Rule | +|---|---| +| (none) | The rule's own check passed on a fresh, complete observation taken after the last fault. | +| `left_queue` | `queue_wait`: GitHub recorded the job starting on one of our runners; or the job is not among the queued jobs of a current listing that is whole for its repository (every page answered, none cut short, not cut for display, every queued job counted whatever its labels), for a run the poller still follows, in two listings in a row (one listing can miss a run that changes status between its two requests). Then it started, finished or was cancelled. A case that does not record when its run began cannot use the listing. | +| `later_attempt_passed`, `later_run_passed` | `job_failed`: a later attempt of the same run, or a later run (a higher run id) of the same workflow job on the same refs, passed after the failure. An older run that was slow to pass does not count. The refs are the head branch and the run's own ref, so pull requests from two forks with the same branch name stay apart, except under `pull_request_target`, where the ref is the base branch. Such a failure is not filed at all when the pass is already on record, and a pass still on record wins over expiry. | +| `quiet` | `host_health`: every fault is either proven healthy by its own rule or has gone unreported through `QUIET_SAMPLES` (10) consecutive valid probes of the host. A fault such as a task container that was removed has no state that could prove it healthy. On a host that stays faulty the same count drops such a fault from the evidence. | +| `verified_control_signal` | A verified scale-in control alarm (below). | + +**Closed**: the case is over without a recovery. No repair is implied. + +| Reason | Rule | +|---|---| +| `network_removed` | The network is no longer configured. | +| `target_removed` | The host, endpoint, disk, runner, reporter, volume, address, instance or alarm has been absent for 10 minutes (`GONE_AFTER_MS`), judged only by complete, current inventories of its kind. The 10 minutes are measured between the inventories' own times, so it takes a later inventory to end a case; the same one read again counts once. The collector and discovery cases of a network generation that a reset replaced end the same way. An inventory with an error, a failed discovery, a stale report, or a host report that lists only the first six of more disks is not evidence of absence, and does not restart the clock. A replaced instance is a new identity: its predecessor's case closes this way, never because the successor is healthy. | +| `expired` | `job_failed`: 24 hours after the failure with no later pass on record (the producer sees finished jobs for a day). `queue_wait`: not seen waiting for 24 hours while the queue was being observed. | +| `ignored_job` | `job_failed` for a job listed in `remediation.ignoredCiJobs` (see the README). | +| `superseded` | A release compatibility task whose release has a newer one in the same `major.minor` line. A release is superseded only by a newer release; a prerelease by any newer version. A superseded release is never opened as a task. | + +A maintenance hold does not keep a closed case open: an operation on a network +does not preserve the cases of the hosts it replaced. + +### Backlog + +When more than one delivery batch (50 events) is waiting, the receiver is away +or behind. The producer then keeps only the newest waiting event of each issue. +A receiver that returns is told the current state of each issue, not the +history it missed. The newest event is kept even when it is the ending of an +issue the receiver may never have heard of: an earlier event can have been +accepted with its acknowledgement lost, and only the ending closes it there. +Events are never rewritten, so a redelivered one still matches by ID and bytes. + ## Data and delivery The unprivileged `STATUS_MODE=incidents` sidecar is the **single writer** of @@ -386,7 +433,21 @@ Not covered: images with no GitHub release (nightlies, forks, patched tags). ## Remediation board -`/remediation` shows unique issues, queued event revisions, active work, waiting +`/remediation` opens on the faults monitoring reports now: counts by severity, +then each open case with what is wrong (the failing reasons of a host, the job +and branch of a CI failure with a link to its run, disk use, and so on; details +for administrators only). Cases of the same job are folded into one line. +Recovered and closed cases are a separate view, listed for 24 hours and at most +200 at a time; the counts are complete. + +With dispatch switched off in the console and no repair worker reporting, the +board says exactly that: automatic repair is off. It does not call the missing +worker a stall, and it does not present what the worker last said about a case +(queued, working) as its current state; the last blocker and summary remain as +history. If the worker never acknowledged the switch-off, the board says so. +With dispatch switched on, a missing worker is a gap again and is shown as one. + +It also shows queued event revisions, active work, waiting reasons, blockers and recovery. `GET /api/remediation` is read-only; the existing incident API bearer token or administrator session enables curated repair notes. Public responses omit target identities, session keys, resource locks and notes, @@ -426,6 +487,8 @@ in the checked-in status IAM policy. Names alone never suppress alarms; denied, partial, stale or mismatched evidence keeps the warning actionable. Correction of an old generic warning records explicit classification evidence and is shown as **Monitoring corrected**, not table recovery. No scaling policy is modified. +A verified control is in `ALARM` whenever its table is idle, so no case is filed +for it; an alarm that fails verification is filed as `aws_alarm` as before. Each readmission has a distinct attempt ID derived from its persisted admission time. Earlier receipts/results are retained, not overwritten by retrying the diff --git a/scripts/browser-check.mjs b/scripts/browser-check.mjs index 3ef17bb..9d05dd6 100644 --- a/scripts/browser-check.mjs +++ b/scripts/browser-check.mjs @@ -222,6 +222,13 @@ try { lastResponse: outcome ? { outcome, summary: `Private ${id} response`, blocker: id === 'blocked' ? 'Root cause still open' : null, nextAction: 'Existing owner retains follow-up', changes: ['Verified supporting-service correction'] } : null }); } + // The same job failing twice is one line that opens into its two cases, each + // saying what failed. An ended case says why it ended. + for (const n of [1, 2]) board.issues.push({ id: `job-${n}`, domain: 'ci', scope: 'private-ci-host', target: `dashpay/platform/${n}/private-ci-host`, + code: 'job_failed', severity: 'warning', status: 'open', firstSeen: at, lastSeen: at, + evidence: { repo: 'dashpay/platform', runId: 100 + n, attempt: 1, jobName: 'Swift SDK build', workflow: 'Tests', branch: 'private-branch', runner: 'private-ci-host' } }); + board.issues.push({ id: 'gone', domain: 'network', scope: 'testnet', target: 'private-gone-host', code: 'host_health', severity: 'critical', status: 'resolved', + firstSeen: at, lastSeen: at, resolvedAt: at, resolutionEvidence: { reason: 'target_removed' } }); const boardFile = join(dataDir, 'incidents', 'state.json'); writeFileSync(boardFile, JSON.stringify(board)); const boardErrors = []; @@ -230,6 +237,15 @@ try { await page.setViewportSize(viewport); await page.getByRole('link', { name: 'Remediation', exact: true }).click(); await page.getByText('Autonomous dispatch enabled').waitFor(); + // The page opens on what is wrong now: six open faults, the ended ones a click away. + assert.match(await page.locator('[data-fault-summary]').innerText(), /OPEN FAULTS\s*6/i); + assert.equal(await page.locator('[data-issue-id="followup"]').count(), 0, 'a recovered case is not listed among open faults'); + assert.equal(await page.locator('[data-issue-group]').count(), 1); + await page.locator('[data-issue-group] > summary').click(); + assert.match(await page.locator('[data-issue-id="job-1"] [data-issue-detail]').innerText(), /dashpay\/platform · Tests · Swift SDK build · private-branch/); + await page.getByLabel('Remediation state').selectOption('history'); + assert.match(await page.locator('[data-issue-id="gone"]').innerText(), /Closed[\s\S]*no longer exists/); + await page.getByLabel('Remediation state').selectOption('all'); await page.locator('[data-issue-id="blocked"] summary').click(); await page.getByText('Root cause still open').waitFor(); assert.ok((await page.locator('[data-issue-id="blocked"]').innerText()).includes('Blocked')); @@ -259,8 +275,19 @@ try { board.delivery.receiver.remediation.enabled = false; writeFileSync(boardFile, JSON.stringify(board)); await anon.getByText('New dispatch paused', { exact: true }).waitFor({ timeout: 10_000 }); + // The worker stops reporting while dispatch is switched off in the console + // (no control file means off): the page is a list of faults, not a stalled queue. board.delivery.receiver.remediation.generatedAt = '2020-01-01T00:00:00Z'; writeFileSync(boardFile, JSON.stringify(board)); + await anon.getByText('Automatic repair is switched off', { exact: true }).waitFor({ timeout: 10_000 }); + assert.equal(await anon.locator('[data-repair-summary]').count(), 0); + assert.equal(await anon.getByText('Remediation cannot make progress').count(), 0); + await anon.setViewportSize({ width: 390, height: 844 }); + await anon.screenshot({ path: 'artifacts/remediation-off-mobile.png', fullPage: true }); + assert.ok(await anon.evaluate(() => document.documentElement.scrollWidth <= innerWidth + 1), 'faults list fits a phone'); + // Switched on in the console with the worker still silent: that is a gap. + writeFileSync(join(dataDir, 'remediation-control.json'), JSON.stringify({ schemaVersion: 1, seq: 1, dispatch: 'on', clearSeq: 0 })); + writeFileSync(boardFile, JSON.stringify(board)); await anon.getByText('Remediation status is stale or unavailable').waitFor({ timeout: 10_000 }); assert.deepEqual(boardErrors, []); await anon.close(); diff --git a/server/ci.js b/server/ci.js index 8e990e2..1163075 100644 --- a/server/ci.js +++ b/server/ci.js @@ -20,6 +20,8 @@ const STALE_MS = 3 * 60_000; // Busy spans are kept for the 48-hour strip; one per single-use runner. const SPAN_KEEP_MS = 49 * 3_600_000; const SPAN_MAX = 2000; +// The queue poll follows runs created within this window. +const QUEUE_WINDOW_MS = DAY; const ID = /^[a-z0-9][a-z0-9-]{0,39}$/; const REPO = /^[A-Za-z0-9_.-]{1,100}\/[A-Za-z0-9_.-]{1,100}$/; const TS = /^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\dZ$/; @@ -64,6 +66,8 @@ function cleanReport(b) { hostname: str(h.hostname, 100), os: str(h.os, 100), arch: str(h.arch, 20), cpus: int(h.cpus), load: Array.isArray(h.load) ? h.load.slice(0, 3).map(num) : [], memTotal: num(h.memTotal), memUsed: num(h.memUsed), uptimeSec: num(h.uptimeSec), disks: Array.isArray(h.disks) ? h.disks.slice(0, 6).map((d) => ({ path: str(d?.path, 100), total: num(d?.total), free: num(d?.free) })) : [], + // More disks than are kept: a disk missing from this list may still be mounted. + disksCut: Array.isArray(h.disks) && h.disks.length > 6, docker, }, runners: b.runners.filter((r) => typeof r?.key === 'string' && r.key).map((r) => ({ @@ -234,24 +238,43 @@ export function createCi({ dataDir, fetcher = fetch, clock = Date.now, github = const repos = [...new Set(jobs.filter((j) => j.repo && j.visibility === 'public' && Date.parse(j.start) > now - 7 * DAY).map((j) => j.repo))].slice(0, 8); const served = servedLabels(); const waiting = []; + // Repositories whose waiting jobs were listed in full: for these, a job + // that is not listed is not waiting. A cut-off page proves nothing. + const covered = []; + // Every job GitHub lists as queued, whatever its labels. `waiting` is what + // we show and file cases for; this says which jobs have not left the queue, + // and that must not depend on which runners report to us today. + const queued = []; let error = null; for (const repo of repos) { try { const runs = new Map(); // a run can move from queued to in progress between the two calls - for (const status of ['queued', 'in_progress']) for (const r of (await api(`/repos/${repo}/actions/runs?status=${status}&per_page=30`))?.workflow_runs || []) runs.set(r.id, r); - for (const run of [...runs.values()].filter((r) => Date.parse(r.created_at) > now - DAY).slice(0, 25)) { + let whole = true; + for (const status of ['queued', 'in_progress']) { + // A 404 comes back as null: no listing, so no coverage. + const page = (await api(`/repos/${repo}/actions/runs?status=${status}&per_page=30`))?.workflow_runs; + if (!Array.isArray(page)) { whole = false; continue; } + if (page.length >= 30) whole = false; + for (const r of page) runs.set(r.id, r); + } + const recent = [...runs.values()].filter((r) => Date.parse(r.created_at) > now - QUEUE_WINDOW_MS); + if (recent.length > 25) whole = false; + for (const run of recent.slice(0, 25)) { const v = await api(`/repos/${repo}/actions/runs/${run.id}/jobs?filter=latest&per_page=100`); + if (!Array.isArray(v?.jobs) || v.jobs.length >= 100) whole = false; for (const j of (v?.jobs || []).map(compactJob)) { // Waiting for a runner only (not for approval or a concurrency group). if (j.status !== 'queued') continue; + if (Number.isSafeInteger(j.id)) queued.push(j.id); const labels = j.labels.map((l) => l.toLowerCase()); if (!labels.includes('self-hosted') && !served.has(JSON.stringify([...j.labels].sort()))) continue; - waiting.push({ id: j.id, repo, workflow: String(run.name || '').slice(0, 200), name: j.name, labels: j.labels, createdAt: j.createdAt, url: j.url, branch: String(run.head_branch || '').slice(0, 200) }); + waiting.push({ id: j.id, repo, workflow: String(run.name || '').slice(0, 200), name: j.name, labels: j.labels, createdAt: j.createdAt, runCreatedAt: run.created_at, url: j.url, branch: String(run.head_branch || '').slice(0, 200) }); } } + if (whole) covered.push(repo); } catch (err) { error = err.message; if (/rate limit/.test(err.message)) break; } } - gh.queue = { at: new Date(now).toISOString(), repos, jobs: waiting.sort((a, b) => a.createdAt.localeCompare(b.createdAt)), error }; + gh.queue = { at: new Date(now).toISOString(), repos, covered, queued, windowMs: QUEUE_WINDOW_MS, jobs: waiting.sort((a, b) => a.createdAt.localeCompare(b.createdAt)), error }; } let lastQueue = 0, ticking = false; @@ -282,7 +305,10 @@ export function createCi({ dataDir, fetcher = fetch, clock = Date.now, github = return { queueSec: Number.isFinite(q) && q >= 0 ? Math.round(q) : null, url: best.g.url, labels: best.g.labels }; } - function summary({ admin = false } = {}) { + // `whole` is for the incident producer: every waiting job and every job that + // finished in the last day, instead of the lists cut for display. Closing a + // case because its job left the queue, or passed later, needs the whole list. + function summary({ admin = false, whole = false } = {}) { const now = clock(); const hosts = list(dirs.hosts); const regs = reporters(); @@ -397,10 +423,12 @@ export function createCi({ dataDir, fetcher = fetch, clock = Date.now, github = hosts: hosts.map((h) => ({ id: h.id, label: regs[h.id]?.label || h.id, receivedAt: h.receivedAt, measuredAt: h.at, stale: now - Date.parse(h.receivedAt) > STALE_MS, reporter: h.reporter, python: h.python, ...h.host })).sort((a, b) => a.label.localeCompare(b.label)), runners, pools, - queue: gh.queue ? { ...gh.queue, jobs: queued.slice(0, 50) } : null, + queue: gh.queue ? { ...gh.queue, queued: whole ? gh.queue.queued : undefined, total: queued.length, jobs: whole ? queued : queued.slice(0, 50) } : null, + // Jobs GitHub says started on one of our runners: a job among them has left the queue. + startedJobs: whole ? Object.values(gh.runs).flatMap((e) => (e.jobs || []).filter((j) => j.startedAt && Number.isSafeInteger(j.id)).map((j) => j.id)) : undefined, workflows: workflows.slice(0, 40), daily, - recent: jobs.filter((j) => j.end).sort((a, b) => b.end.localeCompare(a.end)).slice(0, 60) + recent: (whole ? jobs.filter((j) => j.end && Date.parse(j.end) > now - DAY) : jobs.filter((j) => j.end)).sort((a, b) => b.end.localeCompare(a.end)).slice(0, whole ? 20_000 : 60) .map((j) => ({ ...j, durationSec: dur(j), url: j.url || (j.repo && j.runId ? `https://github.com/${j.repo}/actions/runs/${j.runId}` : null) })), github: { enabled: !!github, rate: gh.rate, enriched: Object.values(gh.runs).filter((e) => e.jobs).length }, ...(admin ? { reporters: Object.entries(regs).map(([id, r]) => ({ id, label: r.label, createdAt: r.createdAt, lastSeen: hosts.find((h) => h.id === id)?.receivedAt || null })) } : {}), diff --git a/server/ci.test.js b/server/ci.test.js index e7c8fab..a308534 100644 --- a/server/ci.test.js +++ b/server/ci.test.js @@ -81,6 +81,12 @@ test('GitHub timing adds queue time; queued self-hosted jobs are listed', async assert.equal(s.recent[0].url, 'https://github.com/dashpay/platform/actions/runs/220/job/1'); assert.equal(s.totals.queuedNow, 1); assert.equal(s.queue.jobs[0].name, 'Swift SDK build'); + // The listing says which repositories it covers in full, and when each run began. + assert.deepEqual([s.queue.covered, s.queue.windowMs, s.queue.total, s.queue.jobs[0].runCreatedAt], [['dashpay/platform'], 86_400_000, 1, iso(T0 - 10 * 60_000)]); + // For the producer: every queued job, the one whose labels we do not serve + // included, and the jobs GitHub recorded as started on our runners. + const whole = ci.summary({ whole: true }); + assert.deepEqual([whole.queue.queued, whole.startedJobs, s.queue.queued, s.startedJobs], [[2, 3], [1], undefined, undefined]); assert.equal(s.workflows[0].medianQueueSec, 303); // A completed run is not fetched again. const before = calls.filter((c) => c.url.includes('/attempts/')).length; @@ -89,6 +95,46 @@ test('GitHub timing adds queue time; queued self-hosted jobs are listed', async assert.ok(JSON.parse(readFileSync(join(dataDir, 'ci', 'github.json'), 'utf8')).rate.remaining > 0); }); +test('a queue listing that was cut short or failed does not claim to cover its repository; the producer gets whole lists', async () => { + const dataDir = mkdtempSync(join(tmpdir(), 'ci-')); + const headers = { 'x-ratelimit-remaining': '4999', 'x-ratelimit-reset': String(T0 / 1000 + 3600) }; + const queuedJob = (id) => ({ id, name: `Job ${id}`, status: 'queued', created_at: iso(T0 - 20 * 60_000), labels: ['self-hosted'], html_url: `u${id}` }); + let mode = 'whole'; + const fetcher = async (url) => { + if (url.includes('/attempts/')) return new Response('{}', { status: 404, headers }); + const runs = mode === 'many-runs' ? 30 : 1; + if (url.includes('status=queued')) return Response.json({ workflow_runs: Array.from({ length: runs }, (_, n) => ({ id: 500 + n, name: 'Tests', created_at: iso(T0 - 30 * 60_000), head_branch: 'x' })) }, { headers }); + if (url.includes('status=in_progress')) return mode === 'not-found' ? new Response('{}', { status: 404, headers }) : Response.json({ workflow_runs: [] }, { headers }); + if (url.includes('/jobs')) { + if (mode === 'error') return new Response('{}', { status: 502, headers }); + if (mode === 'jobs-not-found') return new Response('{}', { status: 404, headers }); + return Response.json({ jobs: Array.from({ length: mode === 'many-jobs' ? 100 : 60 }, (_, n) => queuedJob(Number(url.match(/runs\/(\d+)/)[1]) * 1000 + n)) }, { headers }); + } + return new Response('{}', { status: 404, headers }); + }; + let now = T0; + const ci = createCi({ dataDir, clock: () => now, fetcher }); + const { id } = ci.addReporter('brian'); + ci.ingest(id, report(Array.from({ length: 70 }, (_, n) => job(600 - n, 1, { runId: 1000 + n })))); + await ci.tick(); + // For display: fifty waiting jobs and sixty finished ones. For the producer: all of them. + assert.deepEqual([ci.summary().queue.jobs.length, ci.summary().queue.total, ci.summary().recent.length], [50, 60, 60]); + const whole = ci.summary({ admin: true, whole: true }); + assert.deepEqual([whole.queue.jobs.length, whole.queue.total, whole.queue.covered, whole.recent.length], [60, 60, ['dashpay/platform'], 70]); + assert.equal(ci.publicSummary().queue.covered, undefined); + assert.equal(whole.queue.queued.length, 60); + // A listing that was cut short, failed or answered "not found" covers nothing. + for (const cut of ['many-runs', 'many-jobs', 'not-found', 'jobs-not-found', 'error']) { + mode = cut; now += 3 * 60_000; ci.ingest(id, report()); + await ci.tick(); + assert.deepEqual(ci.summary({ whole: true }).queue.covered, [], cut); + } + assert.match(ci.summary({ whole: true }).queue.error, /GitHub 502/); + // Only jobs that finished within the last day reach the producer. + now += 23 * 3600_000; ci.ingest(id, report()); + assert.equal(ci.summary({ whole: true }).recent.length, 0); +}); + test('before sign-in: statistics without names, hosts, branches, links or private repositories', () => { const ci = createCi({ dataDir: mkdtempSync(join(tmpdir(), 'ci-')), clock: () => T0 }); const { id } = ci.addReporter('mac-runner-brian'); diff --git a/server/incident-closure.test.js b/server/incident-closure.test.js new file mode 100644 index 0000000..cc3e6c9 --- /dev/null +++ b/server/incident-closure.test.js @@ -0,0 +1,544 @@ +// How cases end: recovery that monitoring can see, and closures that are not +// recoveries (the target is gone, the case aged out, a release was superseded). +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { mkdtempSync, mkdirSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { BACKLOG_EVENTS, GONE_AFTER_MS, JOB_FAILED_MAX_AGE_MS, QUEUE_WAIT_UNSEEN_MS, QUIET_SAMPLES, + ciJobIgnored, compactBacklog, deriveIssues, loadIncidentState, reconcile, saveIncidentState, validIgnoredCiJobs, wildcard } from './incidents.js'; +import { cycle } from './incident-service.js'; +import { reconcileReleaseTasks, supersededBy } from './release-webhook.js'; +import { remediationView, HISTORY_MAX, HISTORY_MS } from './remediation.js'; +import { DEFAULT_SETTINGS } from '../shared/settings.js'; + +const now = Date.parse('2026-11-22T12:00:00Z'); +const stamp = (ms) => new Date(ms).toISOString(); +const byCode = (s, code) => s.issues.filter((i) => i.code === code); +const only = (s, code) => { const found = byCode(s, code); assert.equal(found.length, 1, code); return found[0]; }; +const reason = (issue) => issue.resolutionEvidence?.reason; +const MIN = 60_000, HOUR = 3600_000; + +// ---- CI ------------------------------------------------------------------ +const ciHost = (ms, overrides = {}) => ({ reporters: [{ id: 'shared' }], hosts: [{ id: 'shared', receivedAt: stamp(ms), measuredAt: stamp(ms), + disks: [{ path: '/', total: 100, free: 50 }], memTotal: 100, memUsed: 30, ...overrides }], + runners: [{ host: 'shared', name: 'runner', receivedAt: stamp(ms), status: 'idle' }], recent: [] }); +const deriveCi = (ms, ci, remediation) => deriveIssues({ settings: { ...DEFAULT_SETTINGS, networks: [], ...(remediation ? { remediation } : {}) }, states: {}, ci, now: ms }); +const waiting = (ms, overrides = {}) => ({ repo: 'dashpay/platform', id: 7, name: 'Swift SDK build', workflow: 'Tests', branch: 'feat/x', + url: 'https://github.com/dashpay/platform/actions/runs/5/job/7', createdAt: stamp(ms - 20 * MIN), runCreatedAt: stamp(ms - 30 * MIN), ...overrides }); +const queueOf = (ms, jobs, overrides = {}) => ({ at: stamp(ms), error: null, repos: ['dashpay/platform'], covered: ['dashpay/platform'], queued: jobs.map((j) => j.id), windowMs: 24 * HOUR, total: jobs.length, jobs, ...overrides }); + +test('a waiting job that leaves a whole listing of its repository is recovered, and says how', () => { + let s = reconcile(null, deriveCi(now, { ...ciHost(now), queue: queueOf(now, [waiting(now)]) }), now); + const opened = only(s, 'queue_wait'); + assert.deepEqual([opened.status, opened.evidence.name, opened.evidence.branch, opened.evidence.url], ['open', 'Swift SDK build', 'feat/x', 'https://github.com/dashpay/platform/actions/runs/5/job/7']); + // Still listed: still open, however often it is seen. + s = reconcile(s, deriveCi(now + 2 * MIN, { ...ciHost(now + 2 * MIN), queue: queueOf(now + 2 * MIN, [waiting(now)]) }), now + 2 * MIN); + assert.equal(only(s, 'queue_wait').status, 'open'); + // Still queued, but no longer shown as ours (the runner that served its labels + // stopped reporting): GitHub lists it as queued, so it has not left. + const hidden = reconcile(s, deriveCi(now + 4 * MIN, { ...ciHost(now + 4 * MIN), queue: queueOf(now + 4 * MIN, [], { queued: [7] }) }), now + 4 * MIN); + assert.equal(only(hidden, 'queue_wait').status, 'open'); + // One listing without it is not enough: a run that changes status between the + // listing's two requests is in neither. The same listing read again is still one. + s = reconcile(s, deriveCi(now + 4 * MIN, { ...ciHost(now + 4 * MIN), queue: queueOf(now + 4 * MIN, []) }), now + 4 * MIN); + assert.deepEqual([only(s, 'queue_wait').status, only(s, 'queue_wait').absentAt], ['open', stamp(now + 4 * MIN)]); + s = reconcile(s, deriveCi(now + 5 * MIN, { ...ciHost(now + 5 * MIN), queue: queueOf(now + 4 * MIN, []) }), now + 5 * MIN); + assert.equal(only(s, 'queue_wait').status, 'open'); + // Back in the next listing: it never left, and the count starts over. + const back = reconcile(s, deriveCi(now + 6 * MIN, { ...ciHost(now + 6 * MIN), queue: queueOf(now + 6 * MIN, [waiting(now)]) }), now + 6 * MIN); + assert.deepEqual([only(back, 'queue_wait').status, only(back, 'queue_wait').absentAt, back.outbox.length], ['open', undefined, s.outbox.length]); + s = reconcile(s, deriveCi(now + 6 * MIN, { ...ciHost(now + 6 * MIN), queue: queueOf(now + 6 * MIN, []) }), now + 6 * MIN); + const left = only(s, 'queue_wait'); + assert.deepEqual([left.status, reason(left), left.resolutionEvidence.how, left.observedAt, left.absentAt], ['resolved', 'left_queue', 'no longer queued', stamp(now + 6 * MIN), undefined]); + assert.equal(s.outbox.at(-1).transition, 'resolved'); +}); + +test('a run the poller no longer follows cannot prove its job left; the case ends by age instead, once the queue is being observed', () => { + // The run is 23 h 55 min old when the job is first seen waiting. + const old = waiting(now, { runCreatedAt: stamp(now - 24 * HOUR + 5 * MIN) }); + const initial = reconcile(null, deriveCi(now, { ...ciHost(now), queue: queueOf(now, [old]) }), now); + const gone = (ms, overrides) => reconcile(initial, deriveCi(ms, { ...ciHost(ms), queue: queueOf(ms, [], overrides) }), ms); + assert.equal(only(gone(now + 10 * MIN), 'queue_wait').status, 'open', 'the run has left the window the poller lists'); + // A case filed before the run's start was recorded cannot use the listing at + // all, however recently its job was created: a job is younger than its run. + const legacy = (ci) => { + const state = structuredClone(initial), evidence = state.issues.find((i) => i.code === 'queue_wait').evidence; + delete evidence.runCreatedAt; evidence.createdAt = stamp(now - 20 * MIN); + return only(reconcile(state, deriveCi(now + 10 * MIN, { ...ciHost(now + 10 * MIN), queue: queueOf(now + 10 * MIN, []), ...ci }), now + 10 * MIN), 'queue_wait'); + }; + assert.equal(legacy({}).status, 'open'); + // What does end it: GitHub recorded the job starting on one of our runners. + // That is a fact about the job, and needs neither window nor a current listing. + assert.equal(legacy({ startedJobs: [8, 9] }).status, 'open'); + const started = legacy({ startedJobs: [7] }); + assert.deepEqual([started.status, reason(started), started.resolutionEvidence.how], ['resolved', 'left_queue', 'started on a runner']); + assert.equal(reason(legacy({ startedJobs: [7], queue: queueOf(now + 10 * MIN, [], { error: 'GitHub 502' }) })), 'left_queue'); + assert.equal(only(gone(now + QUEUE_WAIT_UNSEEN_MS - MIN), 'queue_wait').status, 'open'); + const expired = only(gone(now + QUEUE_WAIT_UNSEEN_MS), 'queue_wait'); + assert.deepEqual([expired.status, reason(expired)], ['resolved', 'expired']); + // A queue that cannot be read says nothing about how long a job went unseen. + assert.equal(only(gone(now + 3 * QUEUE_WAIT_UNSEEN_MS, { error: 'GitHub 502' }), 'queue_wait').status, 'open'); +}); + +const failed = (ms, overrides = {}) => ({ host: 'shared', repo: 'dashpay/platform', runId: 9, attempt: 1, name: 'Tests', workflow: 'CI', event: 'pull_request', headRef: 'feat/x', ref: 'refs/pull/77/merge', + runnerName: 'runner', start: stamp(ms - 10 * MIN), end: stamp(ms), result: 'Failed', ...overrides }); + +test('a failed job is recovered by a later attempt or a later run on its branch, never by an earlier, other or failed one', () => { + const failure = failed(now); + const initial = reconcile(null, deriveCi(now, { ...ciHost(now), recent: [failure] }), now); + assert.deepEqual([only(initial, 'job_failed').evidence.workflow, only(initial, 'job_failed').evidence.branch, only(initial, 'job_failed').evidence.event], ['CI', 'feat/x', 'pull_request']); + const after = (others) => byCode(reconcile(initial, deriveCi(now + 30 * MIN, { ...ciHost(now + 30 * MIN), recent: [failure, ...others] }), now + 30 * MIN), 'job_failed').find((i) => i.evidence.runId === 9 && i.evidence.attempt === 1); + const pass = (overrides) => failed(now + 20 * MIN, { result: 'Succeeded', runId: 10, ...overrides }); + for (const other of [pass({ headRef: 'feat/y' }), pass({ workflow: 'Nightly' }), pass({ name: 'Lint' }), pass({ repo: 'dashpay/grovedb' }), + pass({ result: 'Failed' }), pass({ result: 'Canceled' }), pass({ end: stamp(now - MIN), start: stamp(now - 5 * MIN) }), pass({ headRef: undefined, ref: undefined }), + // An older run that was slow to pass says nothing about the newer run that failed. + pass({ runId: 8 }), + // Another fork's pull request with a branch of the same name: its own refs/pull//merge keeps it apart. + pass({ ref: 'refs/pull/78/merge' })]) + assert.equal(after([other]).status, 'open', JSON.stringify(other)); + const rerun = after([pass({ runId: 9, attempt: 2 })]); + assert.deepEqual([rerun.status, reason(rerun), rerun.observedAt], ['resolved', 'later_attempt_passed', stamp(now + 20 * MIN)]); + const next = after([pass()]); + assert.deepEqual([next.status, reason(next), next.resolutionEvidence.runId, next.observedAt], ['resolved', 'later_run_passed', 10, stamp(now + 20 * MIN)]); + // The newest run passed before the failure finished; the one before it passed after. That one counts. + const outOfOrder = after([pass({ runId: 12, start: stamp(now - 20 * MIN), end: stamp(now - 5 * MIN) }), pass({ runId: 11 })]); + assert.deepEqual([reason(outOfOrder), outOfOrder.resolutionEvidence.runId], ['later_run_passed', 11]); + // A case filed before workflow and branch were kept in its evidence: the ledger still knows them. + const stripped = structuredClone(initial); + for (const key of ['workflow', 'branch', 'event', 'headRef', 'ref']) delete only(stripped, 'job_failed').evidence[key]; + assert.equal(reason(only(reconcile(stripped, deriveCi(now + 30 * MIN, { ...ciHost(now + 30 * MIN), recent: [failure, pass()] }), now + 30 * MIN), 'job_failed')), 'later_run_passed'); + assert.equal(only(reconcile(stripped, deriveCi(now + 30 * MIN, { ...ciHost(now + 30 * MIN), recent: [pass()] }), now + 30 * MIN), 'job_failed').status, 'open', 'without the ledger entry or the evidence, nothing ties the pass to it'); + // A pass already on record when the failure is first seen: no case at all. + assert.equal(byCode(reconcile(null, deriveCi(now + 30 * MIN, { ...ciHost(now + 30 * MIN), recent: [failure, pass()] }), now + 30 * MIN), 'job_failed').length, 0); + // A push to a branch without a pull request is matched by its ref. + const pushed = failed(now, { headRef: null, ref: 'refs/heads/master', event: 'push' }); + const onMaster = reconcile(reconcile(null, deriveCi(now, { ...ciHost(now), recent: [pushed] }), now), + deriveCi(now + 30 * MIN, { ...ciHost(now + 30 * MIN), recent: [pushed, failed(now + 20 * MIN, { ...pushed, result: 'Succeeded', runId: 11, start: stamp(now + 10 * MIN), end: stamp(now + 20 * MIN) })] }), now + 30 * MIN); + assert.equal(reason(only(onMaster, 'job_failed')), 'later_run_passed'); +}); + +test('a failed job with no later pass is closed after a day, as expired and not as recovered', () => { + const failure = failed(now); + let s = reconcile(null, deriveCi(now, { ...ciHost(now), recent: [failure] }), now); + const late = now + JOB_FAILED_MAX_AGE_MS - MIN; + s = reconcile(s, deriveCi(late, { ...ciHost(late), recent: [failure] }), late); + assert.equal(only(s, 'job_failed').status, 'open'); + // Dropped from the ledger early: omission alone is not an ending. + assert.equal(only(reconcile(s, deriveCi(late, { ...ciHost(late), recent: [] }), late), 'job_failed').status, 'open'); + const end = now + JOB_FAILED_MAX_AGE_MS + MIN; + s = reconcile(s, deriveCi(end, { ...ciHost(end), recent: [failure] }), end); + assert.deepEqual([only(s, 'job_failed').status, reason(only(s, 'job_failed'))], ['resolved', 'expired']); + // The same failure reported again later does not come back. + const again = reconcile(s, deriveCi(end + MIN, { ...ciHost(end + MIN), recent: [failure] }), end + MIN); + assert.equal(only(again, 'job_failed').status, 'resolved'); + // The failure has aged out of the ledger but a later pass is still in it: + // that is a recovery, whichever is noticed first. + const open = reconcile(null, deriveCi(now, { ...ciHost(now), recent: [failure] }), now); + const pass = failed(now + 23 * HOUR, { result: 'Succeeded', runId: 10 }); + const noticed = reconcile(open, deriveCi(end, { ...ciHost(end), recent: [pass] }), end); + assert.deepEqual([only(noticed, 'job_failed').status, reason(only(noticed, 'job_failed')), only(noticed, 'job_failed').resolutionEvidence.runId], ['resolved', 'later_run_passed', 10]); +}); + +test('policy checks listed in settings are never filed; cases already filed for them end; nothing else is hidden', () => { + const remediation = { ignoredCiJobs: [{ workflow: 'Check PR milestone' }, { repo: 'dashpay/platform', job: 'policy / *' }, { repo: 'dashpay/dash-evo-tool', workflow: 'Tests', job: 'Platform pin guard' }] }; + const jobs = [failed(now, { repo: 'dashpay/dash', workflow: 'Check PR milestone', name: 'Require a milestone', runId: 1 }), + failed(now, { workflow: 'PR Hygiene policy', name: 'policy / reconcile', runId: 2 }), + failed(now, { repo: 'dashpay/dash-evo-tool', workflow: 'Tests', name: 'Platform pin guard', runId: 3 }), + failed(now, { repo: 'dashpay/dash-evo-tool', workflow: 'Tests', name: 'Unit tests', runId: 4 }), + failed(now, { repo: 'dashpay/grovedb', workflow: 'PR Hygiene policy', name: 'policy / reconcile', runId: 5 })]; + const all = reconcile(null, deriveCi(now, { ...ciHost(now), recent: jobs }), now); + assert.equal(byCode(all, 'job_failed').length, 5); + assert.deepEqual(byCode(reconcile(null, deriveCi(now, { ...ciHost(now), recent: jobs }, remediation), now), 'job_failed').map((i) => i.evidence.runId).sort(), [4, 5]); + const next = reconcile(all, deriveCi(now + MIN, { ...ciHost(now + MIN), recent: jobs }, remediation), now + MIN); + assert.deepEqual(byCode(next, 'job_failed').map((i) => [i.evidence.runId, i.status, reason(i) || null]).sort(), + [[1, 'resolved', 'ignored_job'], [2, 'resolved', 'ignored_job'], [3, 'resolved', 'ignored_job'], [4, 'open', null], [5, 'open', null]]); + // Cases filed before the workflow was kept in their evidence end the same way while the ledger has the job. + const legacy = structuredClone(all); + for (const issue of byCode(legacy, 'job_failed')) for (const key of ['workflow', 'branch', 'event']) delete issue.evidence[key]; + assert.deepEqual(byCode(reconcile(legacy, deriveCi(now + MIN, { ...ciHost(now + MIN), recent: jobs }, remediation), now + MIN), 'job_failed').filter((i) => reason(i) === 'ignored_job').map((i) => i.evidence.runId).sort(), [1, 2, 3]); + // Without the ledger, a record that lacks the workflow is not matched by a rule that names one. + assert.deepEqual(byCode(reconcile(legacy, deriveCi(now + MIN, { ...ciHost(now + MIN), recent: [] }, remediation), now + MIN), 'job_failed').filter((i) => reason(i) === 'ignored_job').map((i) => i.evidence.runId).sort(), [2]); + const ignored = ciJobIgnored({ remediation }); + assert.equal(ignored({ repo: 'dashpay/dash', job: 'Require a milestone' }), false); + assert.equal(ignored({ repo: 'dashpay/platform', job: 'POLICY / reconcile' }), true, 'case is ignored, * is a wildcard'); + assert.equal(ignored({ repo: 'dashpay/platform', job: 'xpolicy / reconcile' }), false, 'a pattern is anchored at both ends'); + assert.equal(ciJobIgnored({ remediation: { ignoredCiJobs: [{ job: 'a.b' }] } })({ job: 'aXb' }), false, 'only * is special'); + for (const [pattern, value, expected] of [['', '', true], ['*', '', true], ['*', 'anything', true], ['a*', 'a', true], ['*a', 'ba', true], ['a*c', 'abc', true], ['a*c', 'ac', true], + ['a*c', 'abd', false], ['a**c', 'abbc', true], ['*a*b*', 'xaxbx', true], ['*a*b*', 'xbxax', false], ['abc', 'ABC', true], ['abc', 'abcd', false], [' abc ', 'abc', true], + ['a(b)[c]+?', 'a(b)[c]+?', true], ['a(b)[c]+?', 'abc', false], ['Check PR title*', 'Check PR title and description', true]]) + assert.equal(wildcard(pattern, value), expected, JSON.stringify([pattern, value])); + // A rule cannot make a cycle slow, whatever it looks like. + const began = Date.now(); + assert.equal(wildcard('*a*a*a*a*a*a*a*a*a*a*z', 'a'.repeat(20_000)), false); + assert.ok(Date.now() - began < 1000, 'matching is bounded by pattern times text'); + for (const bad of [{}, { repo: 'dashpay/dash' }, { job: '' }, { job: 5 }, { job: 'x', commands: 'y' }, 'Require a milestone']) + assert.throws(() => validIgnoredCiJobs([bad]), /ignoredCiJobs/, JSON.stringify(bad)); + assert.throws(() => validIgnoredCiJobs('all'), /ignoredCiJobs/); + assert.deepEqual(validIgnoredCiJobs(undefined), []); + // A list damaged on disk ignores nothing: every failure stays visible. + assert.equal(byCode(reconcile(null, deriveCi(now, { ...ciHost(now), recent: jobs }, { ignoredCiJobs: [{ workflow: 'Check PR milestone' }, { repo: 'only' }] }), now), 'job_failed').length, 5); +}); + +test('a disk or runner missing from a current report for ten minutes is gone; a deregistered reporter takes its cases with it', () => { + const bad = ciHost(now, { disks: [{ path: '/', total: 100, free: 5 }, { path: '/data', total: 100, free: 5 }] }); bad.runners[0].status = 'offline'; + let s = reconcile(null, deriveCi(now, bad), now); + const initial = s; + assert.equal(byCode(s, 'disk_pressure').length, 2); + const without = (ms, overrides = {}) => { const ci = ciHost(ms, { disks: [{ path: '/', total: 100, free: 5 }], ...overrides }); ci.runners = []; return ci; }; + for (const ms of [now + MIN, now + 5 * MIN, now + MIN + GONE_AFTER_MS - 1]) { + s = reconcile(s, deriveCi(ms, without(ms)), ms); + assert.deepEqual([byCode(s, 'disk_pressure').map((i) => i.status), only(s, 'runner_offline').status], [['open', 'open'], 'open'], stamp(ms)); + } + // A stale report is not an inventory: it neither ends the case nor restarts the clock. + const stale = reconcile(s, deriveCi(now + HOUR, without(now + 30 * MIN)), now + HOUR); + assert.equal(byCode(stale, 'disk_pressure').filter((i) => i.status === 'open').length, 2); + assert.equal(byCode(stale, 'disk_pressure').find((i) => i.target === '/data').missingSince, stamp(now + MIN)); + // The clock is read off the reports, not the cycles: the last report read again an hour on is still the last report. + const reread = reconcile(s, deriveCi(now + MIN + GONE_AFTER_MS, { ...without(now + MIN + GONE_AFTER_MS - 1), hosts: [{ ...without(now + MIN + GONE_AFTER_MS - 1).hosts[0], receivedAt: stamp(now + MIN + GONE_AFTER_MS) }] }), now + MIN + GONE_AFTER_MS); + assert.equal(byCode(reread, 'disk_pressure').filter((i) => i.status === 'open').length, 2); + const ended = reconcile(s, deriveCi(now + MIN + GONE_AFTER_MS, without(now + MIN + GONE_AFTER_MS)), now + MIN + GONE_AFTER_MS); + const disks = Object.fromEntries(byCode(ended, 'disk_pressure').map((i) => [i.target, [i.status, reason(i) || null]])); + assert.deepEqual(disks, { '/': ['open', null], '/data': ['resolved', 'target_removed'] }); + assert.deepEqual([only(ended, 'runner_offline').status, reason(only(ended, 'runner_offline'))], ['resolved', 'target_removed']); + // The reporter keeps six disks of a host that has more: one it does not list may still be mounted. + const cut = reconcile(s, deriveCi(now + MIN + GONE_AFTER_MS, without(now + MIN + GONE_AFTER_MS, { disksCut: true })), now + MIN + GONE_AFTER_MS); + assert.deepEqual([byCode(cut, 'disk_pressure').filter((i) => i.status === 'open').length, only(cut, 'runner_offline').status], [2, 'resolved']); + // Seen again before the ten minutes are up: the clock starts over. + let back = reconcile(s, deriveCi(now + 8 * MIN, bad.hosts[0] && { ...ciHost(now + 8 * MIN, { disks: bad.hosts[0].disks }), runners: [{ ...bad.runners[0], receivedAt: stamp(now + 8 * MIN) }] }), now + 8 * MIN); + back = reconcile(back, deriveCi(now + 12 * MIN, without(now + 12 * MIN)), now + 12 * MIN); + assert.equal(byCode(back, 'disk_pressure').filter((i) => i.status === 'open').length, 2); + // The reporter itself removed from the console. + const removed = (ms) => deriveCi(ms, { reporters: [], hosts: [], runners: [], recent: [] }); + let gone = reconcile(initial, removed(now + MIN), now + MIN); + assert.ok([...byCode(gone, 'disk_pressure'), ...byCode(gone, 'runner_offline')].every((i) => i.status === 'open')); + gone = reconcile(gone, removed(now + MIN + GONE_AFTER_MS), now + MIN + GONE_AFTER_MS); + assert.ok([...byCode(gone, 'disk_pressure'), ...byCode(gone, 'runner_offline')].every((i) => i.status === 'resolved' && reason(i) === 'target_removed')); +}); + +test('cases of a host excluded from remediation are left as they are: nothing ends them, nothing is parked for them', () => { + const remediation = { excludedCiHosts: ['shared'] }; + const bad = ciHost(now, { disks: [{ path: '/', total: 100, free: 5 }, { path: '/data', total: 100, free: 5 }] }); + const failure = failed(now); + let s = reconcile(null, deriveCi(now, { ...bad, recent: [failure] }), now); + const parked = () => (s.quarantined || []).length; + // Excluded from then on; the disk goes, the reporter is deregistered, the failure ages out. + s = reconcile(s, deriveCi(now + MIN, { ...ciHost(now + MIN, { disks: [{ path: '/', total: 100, free: 5 }] }), recent: [failure] }, remediation), now + MIN); + const before = parked(); + for (const ms of [now + 20 * MIN, now + 40 * MIN, now + 25 * HOUR, now + 26 * HOUR]) s = reconcile(s, deriveCi(ms, { reporters: [], hosts: [], runners: [], recent: [] }, remediation), ms); + assert.deepEqual(s.issues.filter((i) => i.scope === 'shared').map((i) => [i.code, i.status, i.remediationExcluded]).sort(), + [['disk_pressure', 'open', true], ['disk_pressure', 'open', true], ['job_failed', 'open', true]]); + assert.equal(parked(), before, 'no ending is emitted only to be quarantined'); + // The exclusion is lifted: the cases end by the ordinary rules, and their endings are sent. + s = reconcile(s, deriveCi(now + 27 * HOUR, { reporters: [], hosts: [], runners: [], recent: [] }), now + 27 * HOUR); + s = reconcile(s, deriveCi(now + 28 * HOUR, { reporters: [], hosts: [], runners: [], recent: [] }), now + 28 * HOUR); + assert.deepEqual(s.issues.filter((i) => i.scope === 'shared').map((i) => [i.code, reason(i)]).sort(), [['disk_pressure', 'target_removed'], ['disk_pressure', 'target_removed'], ['job_failed', 'expired']]); + assert.equal(s.outbox.filter((e) => e.issue.scope === 'shared' && e.transition === 'resolved').length, 3); +}); + +// ---- networks ------------------------------------------------------------ +const settingsFor = (names = ['testnet'], overrides = {}) => ({ ...structuredClone(DEFAULT_SETTINGS), networks: names.map((name) => ({ + name, chainType: 'testnet', coreNetwork: 'test', endpoints: [{ label: 'API', url: 'https://api.example.org/' }], ...overrides })) }); +const host = (ms, data = {}, overrides = {}) => ({ name: 'explorer-1', instanceId: 'i-one', state: 'running', role: 'service', probe: { at: stamp(ms), ok: true, data }, ...overrides }); +const network = (ms, hosts = [], endpoints = [], discovery = {}) => ({ generatedAt: stamp(ms), discovery: { at: stamp(ms), error: null, ...discovery }, hosts, endpoints }); +const deriveNet = (ms, states, settings = settingsFor(Object.keys(states))) => deriveIssues({ settings, states, now: ms }); +const down = [{ service: 'api', ok: false }]; + +test('a deleted network, a replaced host and a removed endpoint end their cases as closed after ten minutes, never as recovered', () => { + const states = (ms, instanceId = 'i-one', endpoints = [{ label: 'API', kind: 'http', ok: false }]) => ({ + testnet: network(ms, [host(ms, { services: down }, { instanceId })], endpoints), + 'devnet-drill': network(ms, [host(ms, { services: down }, { instanceId: 'i-drill' })], [{ label: 'API', kind: 'http', ok: false }]) }); + const both = settingsFor(['testnet', 'devnet-drill']); + let s = reconcile(null, deriveNet(now, states(now), both), now); + assert.deepEqual([byCode(s, 'host_health').length, byCode(s, 'endpoint_failed').length], [2, 2]); + // devnet-drill is deleted; on testnet the instance is replaced by a healthy one and the endpoint is removed. + const after = (ms) => deriveNet(ms, { testnet: network(ms, [host(ms, { services: [{ service: 'api', ok: true }] }, { instanceId: 'i-two' })], []) }, settingsFor(['testnet'])); + const cases = () => s.issues.filter((i) => i.domain === 'network'); + s = reconcile(s, after(now + MIN), now + MIN); + assert.ok(cases().every((i) => i.status === 'open'), 'a predecessor is not cleared by its successor being healthy'); + s = reconcile(s, after(now + MIN + GONE_AFTER_MS - 1), now + MIN + GONE_AFTER_MS - 1); + assert.ok(cases().every((i) => i.status === 'open')); + s = reconcile(s, after(now + MIN + GONE_AFTER_MS), now + MIN + GONE_AFTER_MS); + assert.deepEqual(cases().map((i) => [i.scope, i.code, i.status, reason(i)]).sort(), [ + ['devnet-drill', 'endpoint_failed', 'resolved', 'network_removed'], ['devnet-drill', 'host_health', 'resolved', 'network_removed'], + ['testnet', 'endpoint_failed', 'resolved', 'target_removed'], ['testnet', 'host_health', 'resolved', 'target_removed']]); + assert.ok(cases().every((i) => !('missingSince' in i))); +}); + +test('a host missing from a failed or stale discovery is not gone, and a hold does not keep a removed host open', () => { + let s = reconcile(null, deriveNet(now, { testnet: network(now, [host(now, { services: down })]) }), now); + // Discovery errors for an hour: the host is absent, the inventory is not complete. + for (const ms of [now + MIN, now + 30 * MIN, now + HOUR]) { + s = reconcile(s, deriveNet(ms, { testnet: network(ms, [], [], { error: 'AccessDenied' }) }), ms); + assert.equal(only(s, 'host_health').status, 'open', stamp(ms)); + assert.equal(only(s, 'host_health').missingSince, undefined); + } + // No observation at all (collector down). + assert.equal(only(reconcile(s, deriveNet(now + 2 * HOUR, { testnet: null }), now + 2 * HOUR), 'host_health').status, 'open'); + // Removed while the network is under an operation (a reset replaces every instance). + const held = (ms) => deriveIssues({ settings: settingsFor(['testnet']), states: { testnet: network(ms, [host(ms, {}, { instanceId: 'i-new' })]) }, maintenance: { testnet: { active: true } }, now: ms }); + s = reconcile(s, held(now + 3 * HOUR), now + 3 * HOUR); + assert.equal(only(s, 'host_health').status, 'open'); + s = reconcile(s, held(now + 3 * HOUR + GONE_AFTER_MS), now + 3 * HOUR + GONE_AFTER_MS); + assert.deepEqual([only(s, 'host_health').status, reason(only(s, 'host_health'))], ['resolved', 'target_removed']); +}); + +test('after a reset, the collector and discovery cases of the old generation end once the new one is being observed', () => { + const broken = (ms) => ({ testnet: network(ms, [], [], { error: 'AccessDenied' }) }); + let s = reconcile(null, deriveNet(now, broken(now), settingsFor(['testnet'], { generation: 1 })), now); + assert.equal(only(s, 'discovery_failed').status, 'open'); + const reset = (ms) => deriveNet(ms, { testnet: network(ms, [host(ms, {})]) }, settingsFor(['testnet'], { generation: 2 })); + s = reconcile(s, reset(now + MIN), now + MIN); + assert.equal(only(s, 'discovery_failed').status, 'open'); + s = reconcile(s, reset(now + MIN + GONE_AFTER_MS), now + MIN + GONE_AFTER_MS); + assert.deepEqual([only(s, 'discovery_failed').status, reason(only(s, 'discovery_failed'))], ['resolved', 'target_removed']); +}); + +test('AWS cases end when the resource is gone from a complete inventory, not from a partial one', () => { + const make = (ms, { volumes = [], addresses = [], instances = [], alarms = [], errors = [], healthErrors = [] } = {}) => ({ at: stamp(ms), errors, regions: ['us-west-2'], volumes, addresses, + health: { at: stamp(ms), errors: healthErrors, instances, alarms } }); + const derive = (ms, aws) => deriveIssues({ settings: { ...DEFAULT_SETTINGS, networks: [] }, states: {}, aws, now: ms }); + const all = { volumes: [{ region: 'us-west-2', id: 'vol-1', state: 'available', sizeGiB: 20 }], addresses: [{ region: 'us-west-2', allocationId: 'eipalloc-1', associated: false }], + instances: [{ region: 'us-west-2', id: 'i-one', state: 'running', instanceStatus: 'impaired', systemStatus: 'ok', events: [] }], alarms: [{ region: 'us-west-2', name: 'api', state: 'ALARM' }] }; + const codes = ['idle_volume', 'idle_address', 'aws_instance_impaired', 'aws_alarm']; + let s = reconcile(null, derive(now, make(now, all)), now); + for (const code of codes) assert.equal(only(s, code).status, 'open'); + s = reconcile(s, derive(now + MIN, make(now + MIN)), now + MIN); + const partial = [{ errors: [{ region: 'us-west-2', scope: 'ec2:DescribeVolumes', error: 'throttled' }] }, { healthErrors: [{ region: 'us-west-2', scope: 'cloudwatch:DescribeAlarms', error: 'denied' }] }]; + const first = reconcile(s, derive(now + HOUR, make(now + HOUR, partial[0])), now + HOUR); + assert.deepEqual(['idle_volume', 'idle_address'].map((c) => only(first, c).status), ['open', 'open'], 'an inventory with errors does not say a volume is gone'); + assert.deepEqual(['aws_instance_impaired', 'aws_alarm'].map((c) => only(first, c).status), ['resolved', 'resolved']); + const second = reconcile(s, derive(now + HOUR, make(now + HOUR, partial[1])), now + HOUR); + assert.deepEqual(['aws_instance_impaired', 'aws_alarm'].map((c) => only(second, c).status), ['open', 'open']); + assert.deepEqual(['idle_volume', 'idle_address'].map((c) => only(second, c).status), ['resolved', 'resolved']); + const done = reconcile(s, derive(now + MIN + GONE_AFTER_MS, make(now + MIN + GONE_AFTER_MS)), now + MIN + GONE_AFTER_MS); + for (const code of codes) assert.deepEqual([only(done, code).status, reason(only(done, code))], ['resolved', 'target_removed'], code); +}); + +test('a host fault that nothing can prove healthy is dropped after ten healthy samples in a row, and the host then recovers', () => { + const POLL = 30_000; + const bad = (ms) => ({ testnet: network(ms, [host(ms, { containers: [{ name: 'incident-4619-replay', state: 'exited', exitCode: 1, running: false }], services: down })]) }); + const fine = (ms, probeAt = ms) => ({ testnet: network(ms, [host(probeAt, { containers: [], services: [{ service: 'api', ok: true }] })]) }); + let s = reconcile(null, deriveNet(now, bad(now)), now); + assert.deepEqual(only(s, 'host_health').evidence.faults, ['["container","incident-4619-replay"]', '["service","api"]']); + // The task container is removed and the service recovers: the service fault + // is proven healthy at once, the container can never be. + let ms = now; + for (let n = 1; n < QUIET_SAMPLES; n++) { + ms += POLL; s = reconcile(s, deriveNet(ms, fine(ms)), ms); + assert.equal(only(s, 'host_health').status, 'open', `sample ${n}`); + assert.equal(only(s, 'host_health').quiet['["container","incident-4619-replay"]'].n, n); + } + // The same probe seen again, and a stale one, are not further samples. + s = reconcile(s, deriveNet(ms + 1000, fine(ms + 1000, ms)), ms + 1000); + assert.equal(only(s, 'host_health').status, 'open'); + assert.equal(only(reconcile(s, deriveNet(ms + HOUR, fine(ms + HOUR, ms + POLL)), ms + HOUR), 'host_health').status, 'open', 'a stale observation is not a healthy sample'); + ms += POLL; s = reconcile(s, deriveNet(ms, fine(ms)), ms); + const recovered = only(s, 'host_health'); + assert.deepEqual([recovered.status, reason(recovered), recovered.resolutionEvidence.faults], ['resolved', 'quiet', ['["container","incident-4619-replay"]']]); + assert.equal(recovered.quiet, undefined); +}); + +test('a fault that returns restarts its count; one that stays away is dropped from the evidence of a host that is still faulty', () => { + const POLL = 30_000; + const state = (ms, container, service) => ({ testnet: network(ms, [host(ms, { containers: container ? [{ name: 'task', state: 'exited', exitCode: 1, running: false }] : [], services: [{ service: 'api', ok: !service }] })]) }); + let s = reconcile(null, deriveNet(now, state(now, true, true)), now), ms = now; + const step = (container, service) => { ms += POLL; s = reconcile(s, deriveNet(ms, state(ms, container, service)), ms); return only(s, 'host_health'); }; + for (let n = 0; n < 4; n++) step(false, true); + assert.equal(only(s, 'host_health').quiet['["container","task"]'].n, 4); + assert.equal(step(true, true).quiet, undefined, 'seen again: no fault is waiting to be dropped'); + for (let n = 1; n < QUIET_SAMPLES; n++) assert.equal(step(false, true).evidence.faults.length, 2, `sample ${n}`); + const before = s.outbox.length; + const trimmed = step(false, true); + assert.deepEqual([trimmed.status, trimmed.evidence.faults, trimmed.evidence.reasons.length], ['open', ['["service","api"]'], 1]); + assert.equal(s.outbox.at(-1).transition, 'changed'); assert.equal(s.outbox.length, before + 1); +}); + +// ---- release tasks ------------------------------------------------------- +const release = (tag, releaseId, repository = 'dashpay/platform', repositoryId = 424232911) => ({ schemaVersion: 1, repository, repositoryId, releaseId, tag, + prerelease: tag.includes('-'), publishedAt: stamp(now - releaseId * HOUR), receivedAt: stamp(now), deliveryId: 'f26d6500-c333-11f1-8d56-cc2ba732156b', url: `https://github.com/${repository}/releases/tag/${tag}` }); + +test('a release with a newer one in its line is superseded: its task closes, and it is never opened afresh', () => { + const tags = ['v5.0.0-beta.3', 'v5.0.0-beta.10', 'v5.0.0-rc.1', 'v5.0.0', 'v5.0.9', 'v5.0.10', 'v5.1.0-dev.1']; + const releases = tags.map((tag, i) => release(tag, 100 + i)); + const by = (tag) => supersededBy(releases.find((r) => r.tag === tag), releases)?.tag || null; + assert.deepEqual(tags.map(by), ['v5.0.10', 'v5.0.10', 'v5.0.10', 'v5.0.10', 'v5.0.10', null, null]); + assert.equal(supersededBy(release('v5.0.0-beta.3', 1), [release('v5.0.0-beta.3', 1), release('v5.0.0-beta.10', 2), release('v5.0.0-alpha.99', 3)]).tag, 'v5.0.0-beta.10', 'numeric identifiers compare as numbers'); + assert.equal(supersededBy(release('v5.0.0-rc.1', 1), [release('v5.0.0-rc.1.1', 2)]).tag, 'v5.0.0-rc.1.1'); + assert.equal(supersededBy(release('v5.0.0', 1), [release('v5.0.0-rc.9', 2), release('v6.0.0', 3), release('v5.0.1', 4, 'dashpay/dash', 19352450)]), null, 'a prerelease, another line and another repository do not supersede'); + // 5.0.3 stays in service while 5.0.4-rc.1 is tried: a prerelease supersedes prereleases only. + const trial = [release('v5.0.3', 1), release('v5.0.4-rc.1', 2), release('v5.0.4-beta.2', 3)]; + assert.deepEqual(trial.map((r) => supersededBy(r, trial)?.tag || null), [null, null, 'v5.0.4-rc.1']); + assert.equal(supersededBy(trial[1], [...trial, release('v5.0.4', 4)]).tag, 'v5.0.4'); + // Tasks filed one by one as the releases came out, none of them ever worked on. + const state = { schemaVersion: 1, issues: [], outbox: [], revisionCounters: {}, delivery: { receiver: {} } }; + reconcileReleaseTasks(state, releases.slice(0, 1), now); + assert.deepEqual(state.issues.map((i) => [i.target, i.status]), [['Platform v5.0.0-beta.3', 'open']]); + reconcileReleaseTasks(state, releases, now + MIN); + assert.deepEqual(state.issues.map((i) => [i.target, i.status, i.resolutionEvidence?.by || null]), + [['Platform v5.0.0-beta.3', 'resolved', 'v5.0.10'], ['Platform v5.0.10', 'open', null], ['Platform v5.1.0-dev.1', 'open', null]]); + assert.deepEqual(state.outbox.map((e) => [e.issue.target, e.transition]), + [['Platform v5.0.0-beta.3', 'opened'], ['Platform v5.0.0-beta.3', 'resolved'], ['Platform v5.0.10', 'opened'], ['Platform v5.1.0-dev.1', 'opened']]); + const again = structuredClone(state); reconcileReleaseTasks(again, releases, now + 2 * MIN); + assert.deepEqual(again, state, 'nothing is opened, closed or sent twice'); + const view = remediationView({ ...state, generatedAt: stamp(now + MIN), control: { dispatch: 'off' } }, { full: true, now: now + MIN }); + const shown = view.cases.find((c) => c.title.endsWith('v5.0.0-beta.3')); + assert.deepEqual([shown.stage, shown.reason], ['closed', 'Superseded by v5.0.10']); +}); + +// ---- backlog ------------------------------------------------------------- +const event = (id, revision, status = 'open', transition = status === 'resolved' ? 'resolved' : revision === 1 ? 'opened' : 'changed') => + ({ schemaVersion: 1, eventId: `${id}:${revision}`, occurredAt: stamp(now), transition, issue: { id, revision, domain: 'ci', scope: 'github', target: id, code: 'queue_wait', severity: 'warning', status, sourceKey: 'ci:queue' } }); +const issueOf = (id, revision, status = 'open', extra = {}) => ({ id, revision, domain: 'ci', scope: 'github', target: id, code: 'queue_wait', severity: 'warning', status, ...extra }); + +test('a backlog keeps only the newest waiting event of each issue, an ending included', () => { + const filler = Array.from({ length: BACKLOG_EVENTS }, (_, n) => `f${n}`); + const issues = [issueOf('seen', 9, 'resolved'), issueOf('unseen', 2, 'resolved'), issueOf('still', 3), ...filler.map((id) => issueOf(id, 1))]; + const state = { issues: structuredClone(issues), outbox: [event('seen', 7), event('unseen', 1), event('still', 1), event('seen', 8), event('gone', 4), + ...filler.map((id) => event(id, 1)), event('still', 2), event('unseen', 2, 'resolved'), event('seen', 9, 'resolved'), event('still', 3), event('gone', 5, 'resolved')] }; + const small = { issues: state.issues, outbox: state.outbox.slice(0, BACKLOG_EVENTS) }; + assert.equal(compactBacklog(structuredClone(small)).outbox.length, BACKLOG_EVENTS, 'one batch is not a backlog: every event is delivered as it is'); + compactBacklog(state); + // unseen opened and ended with nothing acknowledged, and its ending is kept all the + // same: its opening may have been accepted by a receiver whose answer was lost. + assert.deepEqual(state.outbox.filter((e) => !e.issue.id.startsWith('f')).map((e) => e.eventId), ['unseen:2', 'seen:9', 'still:3', 'gone:5']); + assert.equal(state.outbox.length, BACKLOG_EVENTS + 4); + assert.deepEqual(state.issues, issues, 'issues are not touched'); + // Stable: a second pass changes nothing, and no event was rewritten. + const once = structuredClone(state); compactBacklog(state); assert.deepEqual(state, once); + assert.deepEqual(state.outbox.at(-1), event('gone', 5, 'resolved')); +}); + +test('a receiver that accepted an opening and lost its answer is still told the ending, once it returns', async () => { + const dataDir = mkdtempSync(join(tmpdir(), 'incidents-backlog-')); + mkdirSync(join(dataDir, 'incidents')); + writeFileSync(join(dataDir, 'settings.json'), JSON.stringify(DEFAULT_SETTINGS)); + const jobs = (ms) => Array.from({ length: 60 }, (_, n) => waiting(ms, { id: 100 + n })); + let queue = queueOf(now, jobs(now)), clock = now; + const ci = { summary: (options) => { assert.equal(options.whole, true); return { ...ciHost(clock), queue }; } }; + const destination = 'https://receiver.example-tailnet.ts.net:8444/v1/events'; + const sent = []; + const accept = async (_, opts) => { const batch = JSON.parse(opts.body).events; sent.push(...batch); return Response.json({ accepted: batch.map((e) => e.eventId), health: { status: 'ok' } }); }; + // The receiver stores the first batch; the connection drops before it answers. + const stored = []; + await cycle({ dataDir, ci, destination, secret: 'test-secret', now: clock, fetcher: async (_, opts) => { stored.push(...JSON.parse(opts.body).events); throw new Error('connection lost after acceptance'); } }); + const openThere = new Set(stored.filter((e) => e.issue.code === 'queue_wait').map((e) => e.issue.id)); + assert.ok(openThere.size > 0 && openThere.size < 60, 'one batch of the sixty openings is with the receiver, unacknowledged'); + // The receiver goes away; every job then leaves the queue (two listings say so). + for (const minutes of [5, 2]) { + clock += minutes * MIN; queue = queueOf(clock, []); + await cycle({ dataDir, ci, destination, secret: 'test-secret', now: clock, fetcher: async () => { throw new Error('connection refused'); } }); + } + const state = loadIncidentState(dataDir); + assert.ok(byCode(state, 'queue_wait').every((i) => i.status === 'resolved')); + const pending = state.outbox.filter((e) => e.issue.code === 'queue_wait'); + assert.deepEqual([pending.length, pending.every((e) => e.transition === 'resolved')], [60, true], 'one waiting event per job: its ending'); + // It returns: every ending arrives, each once, the ones it holds open among them. + for (let n = 0; n < 6 && loadIncidentState(dataDir).outbox.length; n++) { clock += 20 * MIN; queue = queueOf(clock, []); await cycle({ dataDir, ci, destination, secret: 'test-secret', now: clock, fetcher: accept }); } + const endings = sent.filter((e) => e.issue.code === 'queue_wait'); + assert.deepEqual([endings.length, new Set(endings.map((e) => e.eventId)).size, endings.every((e) => e.transition === 'resolved')], [60, 60, true]); + assert.ok([...openThere].every((id) => endings.some((e) => e.issue.id === id))); + assert.equal(loadIncidentState(dataDir).outbox.filter((e) => e.issue.code === 'queue_wait').length, 0); +}); + +// ---- the page ------------------------------------------------------------ +test('with repair switched off and no worker, the page lists open faults with what is wrong, and shows endings for a day', () => { + const at = stamp(now); + const base = { domain: 'ci', scope: 'mac-runner-pasta', severity: 'warning', status: 'open', firstSeen: stamp(now - HOUR), lastSeen: at, revision: 1 }; + const closed = (id, why, extra = {}) => ({ ...base, id, code: 'job_failed', target: id, status: 'resolved', resolvedAt: stamp(now - HOUR), resolutionEvidence: { reason: why }, ...extra }); + const issues = [ + { ...base, id: 'job1', code: 'job_failed', target: 'dashpay/platform/9/mac-runner-pasta/x', evidence: { repo: 'dashpay/platform', runId: 9, attempt: 2, jobName: 'Swift SDK build', workflow: 'Tests', branch: 'feat/x', runner: 'mac-runner-pasta' } }, + { ...base, id: 'job2', code: 'job_failed', target: 'dashpay/platform/10/mac-runner-pasta/y', evidence: { repo: 'dashpay/platform', runId: 10, attempt: 1, jobName: 'Swift SDK build', runner: 'mac-runner-pasta' } }, + { ...base, id: 'evil', code: 'job_failed', target: 'x', evidence: { repo: 'dashpay/platform/../../evil.example', runId: '9?x=