From 6aab21380e1943a68d23ea2bc7f455f0e1830679 Mon Sep 17 00:00:00 2001 From: ktechmidas <9920871+ktechmidas@users.noreply.github.com> Date: Sun, 22 Nov 2026 23:43:24 +0300 Subject: [PATCH 1/3] fix: remediation cases end, and the page lists what is wrong now The remediation queue held 2,660 open cases, about a dozen of them real (dashpay/infra#99). A case could only end on a proof that often cannot arrive: a job that left the queue is no longer listed, a deleted devnet is no longer probed, a removed task container has no state to prove healthy. Cases now end, and say how: - queue_wait: recovered when the job is gone from a whole, current listing of its repository; closed after a day unseen. - job_failed: recovered by a later attempt or a later run on the same branch; closed a day after the failure. Jobs listed in remediation.ignoredCiJobs (policy checks) are not filed. - Hosts, endpoints, disks, runners, reporters and AWS resources absent from complete inventories for ten minutes are closed as removed; a deleted network takes its cases with it. - A host fault nothing can prove healthy is dropped after ten healthy samples in a row. - A verified scale-in control alarm is not a case. - A release task is closed when its line has a newer release. A backlog for an absent receiver keeps the newest event per issue and forgets issues that opened and ended unseen. The page opens on open faults with what is wrong on each, folds repeats of one job together, and shows recovered and closed cases as a separate view. With dispatch switched off and no worker reporting it says so, instead of reading as stale and stalled. Co-Authored-By: Claude Fable 5.2 --- README.md | 25 ++ agent/aws-health.test.js | 14 +- deploy/INCIDENTS.md | 60 ++++- scripts/browser-check.mjs | 27 ++ server/ci.js | 31 ++- server/ci.test.js | 39 +++ server/incident-closure.test.js | 457 ++++++++++++++++++++++++++++++++ server/incident-service.js | 11 +- server/incidents.js | 234 +++++++++++++--- server/incidents.test.js | 19 +- server/release-webhook.js | 41 ++- server/remediation-activity.js | 2 + server/remediation.js | 117 ++++++-- server/remediation.test.js | 3 + server/web.js | 5 +- src/pages/Remediation.jsx | 141 +++++++--- 16 files changed, 1117 insertions(+), 109 deletions(-) create mode 100644 server/incident-closure.test.js 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..4237e5b 100644 --- a/deploy/INCIDENTS.md +++ b/deploy/INCIDENTS.md @@ -14,11 +14,51 @@ 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 + +Every 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. A resolved case records why in +`resolutionEvidence.reason`, and the board shows two kinds of ending apart. + +**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`: the job is not in a current queue listing that is whole for its repository (no page cut short, no error, not cut for display), for a run the poller still follows. It started, finished or was cancelled. | +| `later_attempt_passed`, `later_run_passed` | `job_failed`: a later attempt of the same run, or a later run of the same workflow job on the same branch, passed after the failure. Such a failure is not filed at all when the pass is already on record. | +| `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. An inventory with an error, a failed discovery or a stale report 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 superseded release is never opened as a task. | + +A hold or an exclusion does not keep a closed case open: maintenance on a +network does not preserve the cases of 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 undelivered event of each +issue, and drops every event of an issue that opened and ended without the +receiver ever being told of it. The producer records the highest revision the +receiver acknowledged per issue (`delivered`) to know which is which. A +receiver that returns is told the current state of each issue it knows and of +each fault still open, not the history it missed. + ## Data and delivery The unprivileged `STATUS_MODE=incidents` sidecar is the **single writer** of @@ -386,7 +426,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 +480,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..2936fb7 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$/; @@ -234,24 +236,36 @@ 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 = []; 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']) { + const page = (await api(`/repos/${repo}/actions/runs?status=${status}&per_page=30`))?.workflow_runs || []; + 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 (!v || (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; 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, windowMs: QUEUE_WINDOW_MS, jobs: waiting.sort((a, b) => a.createdAt.localeCompare(b.createdAt)), error }; } let lastQueue = 0, ticking = false; @@ -282,7 +296,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 +414,10 @@ 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, total: queued.length, jobs: whole ? queued : queued.slice(0, 50) } : null, 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..4267eaf 100644 --- a/server/ci.test.js +++ b/server/ci.test.js @@ -81,6 +81,8 @@ 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)]); 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 +91,43 @@ 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 Response.json({ workflow_runs: [] }, { headers }); + if (url.includes('/jobs')) { + if (mode === 'error') return new Response('{}', { status: 502, 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); + for (const cut of ['many-runs', 'many-jobs', '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..ebbb52c --- /dev/null +++ b/server/incident-closure.test.js @@ -0,0 +1,457 @@ +// 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 } 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'], 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'); + s = reconcile(s, deriveCi(now + 4 * MIN, { ...ciHost(now + 4 * MIN), queue: queueOf(now + 4 * MIN, []) }), now + 4 * MIN); + const left = only(s, 'queue_wait'); + assert.deepEqual([left.status, reason(left), left.observedAt], ['resolved', 'left_queue', stamp(now + 4 * MIN)]); + 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: the job's own creation + // time stands in for it, with half the window as allowance. + const legacy = (createdAt) => { + const state = structuredClone(initial), evidence = state.issues.find((i) => i.code === 'queue_wait').evidence; + delete evidence.runCreatedAt; evidence.createdAt = createdAt; + return only(reconcile(state, deriveCi(now + 10 * MIN, { ...ciHost(now + 10 * MIN), queue: queueOf(now + 10 * MIN, []) }), now + 10 * MIN), 'queue_wait'); + }; + assert.equal(reason(legacy(stamp(now - 20 * MIN))), 'left_queue'); + assert.equal(legacy(stamp(now - 13 * HOUR)).status, 'open'); + 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', + 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 })]) + 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)]); + // 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']) 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'); +}); + +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 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); + 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']); + // 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')); +}); + +// ---- 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('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'); + // 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 the newest undelivered event of each issue and forgets issues that came and went unseen', () => { + const filler = Array.from({ length: BACKLOG_EVENTS }, (_, n) => `f${n}`); + const state = { issues: [issueOf('seen', 9, 'resolved'), issueOf('unseen', 2, 'resolved'), issueOf('still', 3), issueOf('known', 7, 'resolved', { delivered: 4 }), + issueOf('never', 3, 'resolved', { delivered: 0 }), ...filler.map((id) => issueOf(id, 1))], + outbox: [event('seen', 7), event('unseen', 1), event('still', 1), event('seen', 8), event('known', 5), event('gone', 4), event('never', 2), + ...filler.map((id) => event(id, 1)), event('still', 2), event('unseen', 2, 'resolved'), event('seen', 9, 'resolved'), event('still', 3), event('known', 7, 'resolved'), event('gone', 5, 'resolved'), event('never', 3, '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); + const kept = state.outbox.filter((e) => !e.issue.id.startsWith('f')).map((e) => e.eventId); + // seen: revisions below 7 were delivered, so its ending is. unseen: opened and ended without the receiver hearing of it. + // gone: no longer in the issue list, so nothing says it was never delivered. never: recorded as never delivered. + assert.deepEqual(kept, ['seen:9', 'still:3', 'known:7', 'gone:5']); + assert.equal(state.outbox.length, BACKLOG_EVENTS + 4); + assert.deepEqual(['seen', 'unseen', 'still', 'known'].map((id) => state.issues.find((i) => i.id === id).delivered), [6, 0, 0, 4]); + // Stable: a second pass changes nothing, and what is left is still one event per issue. + const once = structuredClone(state); compactBacklog(state); assert.deepEqual(state, once); +}); + +test('the producer records what the receiver acknowledged, so a later ending is told only to a receiver that knows the issue', 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' } }); }; + await cycle({ dataDir, ci, destination, secret: 'test-secret', now: clock, fetcher: accept }); + let state = loadIncidentState(dataDir); + const waits = sent.filter((e) => e.issue.code === 'queue_wait'); + assert.ok(waits.length > 0 && waits.length < 60, 'one batch of the sixty reached the receiver'); + const told = new Set(waits.map((e) => e.issue.id)); + assert.ok(byCode(state, 'queue_wait').every((i) => i.delivered === (told.has(i.id) ? 1 : 0))); + // The receiver goes away; every job then leaves the queue. + clock += 5 * MIN; queue = queueOf(clock, []); + sent.length = 0; + await cycle({ dataDir, ci, destination, secret: 'test-secret', now: clock, fetcher: async () => { throw new Error('connection refused'); } }); + 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.map((e) => e.issue.id).sort(), [...told].sort(), 'only the endings of the jobs the receiver was told about are kept'); + assert.ok(pending.every((e) => e.transition === 'resolved')); +}); + +// ---- 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=