Skip to content

armgit / Pulse

Public Imported from GitHub
0

Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.

Retain partial frontend unit observations in CI

pulse-triage[bot]1f3538c151de
diff --git a/.github/workflows/build-and-test.yml b/.github/workflows/build-and-test.yml
index 0ce86c2653..70ab328fc1 100644
--- a/.github/workflows/build-and-test.yml
+++ b/.github/workflows/build-and-test.yml
@@ -290,6 +290,9 @@ jobs:
node --test scripts/tests/check-frontend-serialization.test.mjs
node scripts/check-frontend-serialization.mjs
+ - name: Validate frontend unit evidence reporter
+ run: node --test scripts/tests/frontend-unit-receipts.test.mjs
+
- name: Install frontend dependencies
working-directory: frontend-modern
# The explicit bounded audit below owns the advisory verdict. Avoid
@@ -564,7 +567,23 @@ jobs:
# filter can silently leave part of the suite behind.
- name: Frontend unit tests
working-directory: frontend-modern
- run: npm run test -- --shard=${{ matrix.shard }}/4
+ env:
+ PULSE_UNIT_RECEIPT: ${{ runner.temp }}/frontend-unit-${{ matrix.shard }}-${{ github.run_attempt }}.json
+ PULSE_UNIT_SOURCE_SHA: ${{ github.sha }}
+ run: >-
+ npm run test -- --shard=${{ matrix.shard }}/4
+ --reporter=default --reporter=./scripts/ci-unit-receipts.mjs
+
+ # Flush after each module, not only at run end. A partial receipt names
+ # what remains unobserved; it cannot turn cancellation into passing proof.
+ - name: Retain frontend unit observations
+ if: always()
+ uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
+ with:
+ name: frontend-unit-${{ matrix.shard }}-${{ github.run_attempt }}
+ path: ${{ runner.temp }}/frontend-unit-${{ matrix.shard }}-${{ github.run_attempt }}.json
+ if-no-files-found: warn
+ retention-days: 7
# Preserve the required check name; a failed/cancelled/skipped shard or a
# failed audit/build/runtime check must never produce a green Frontend.
diff --git a/frontend-modern/scripts/ci-unit-receipts.mjs b/frontend-modern/scripts/ci-unit-receipts.mjs
new file mode 100644
index 0000000000..2e85915fff
--- /dev/null
+++ b/frontend-modern/scripts/ci-unit-receipts.mjs
@@ -0,0 +1,127 @@
+// Vitest 4 reporter used only by the explicit CI command. Keep the default
+// reporter: this receipt contains counts, not errors, stdout or a process exit.
+import fs from 'node:fs';
+import path from 'node:path';
+import { createHash } from 'node:crypto';
+
+const terminalStates = new Set(['passed', 'failed', 'skipped']);
+const testStates = ['passed', 'failed', 'skipped', 'pending'];
+
+export default class CIUnitReceipts {
+ constructor({ outputFile = process.env.PULSE_UNIT_RECEIPT,
+ sourceSha = process.env.PULSE_UNIT_SOURCE_SHA } = {}) {
+ if (!outputFile || !/^[a-f0-9]{40}$/.test(sourceSha ?? '')) {
+ throw new Error('Unit receipts require an output file and exact source SHA');
+ }
+ this.outputFile = path.resolve(outputFile);
+ this.sourceSha = sourceSha;
+ }
+
+ onInit(ctx) {
+ if (fs.existsSync(this.outputFile)) {
+ throw new Error('Unit receipt destination already exists');
+ }
+ this.root = path.resolve(ctx.config.root);
+ this.modules = new Map();
+ this.receipt = {
+ schema_version: 1,
+ source_sha: this.sourceSha,
+ package_lock_sha256: createHash('sha256')
+ .update(fs.readFileSync(path.join(this.root, 'package-lock.json'))).digest('hex'),
+ shard: ctx.config.shard ?? { index: 1, count: 1 },
+ inventory_observed: false,
+ test_run_end_observed: false,
+ test_run_reason: null,
+ unhandled_error_count: null,
+ };
+ this.write();
+ }
+
+ onTestRunStart(specifications) {
+ const modules = new Map();
+ for (const spec of specifications) {
+ const module = path.relative(this.root, spec.moduleId);
+ if (!module || path.isAbsolute(module) || module === '..'
+ || module.startsWith(`..${path.sep}`) || !spec.taskId || modules.has(spec.taskId)) {
+ throw new Error('Invalid or duplicate unit inventory entry');
+ }
+ modules.set(spec.taskId, {
+ id: spec.taskId,
+ module: module.split(path.sep).join('/'),
+ project: spec.project.name,
+ pool: spec.pool,
+ state: 'unobserved',
+ tests: null,
+ module_error_count: null,
+ });
+ }
+ this.modules = modules;
+ this.receipt.inventory_observed = true;
+ this.receipt.test_run_end_observed = false;
+ this.receipt.test_run_reason = null;
+ this.receipt.unhandled_error_count = null;
+ this.write();
+ }
+
+ observe(module) {
+ const entry = this.modules.get(module.id);
+ if (!entry) throw new Error('Unit result is absent from the selected inventory');
+ const state = module.state();
+ if (!terminalStates.has(state) && state !== 'pending' && state !== 'queued') {
+ throw new Error('Unknown unit module state');
+ }
+ const tests = Object.fromEntries(testStates.map(state => [state, 0]));
+ for (const test of module.children.allTests()) {
+ const result = test.result().state;
+ if (!testStates.includes(result)) throw new Error('Unknown unit test state');
+ tests[result]++;
+ }
+ this.modules.set(module.id, {
+ ...entry, state, tests, module_error_count: module.errors().length,
+ });
+ }
+
+ onTestModuleEnd(module) {
+ this.observe(module);
+ this.write();
+ }
+
+ onTestRunEnd(modules, unhandledErrors, reason) {
+ if (!['passed', 'failed', 'interrupted'].includes(reason)) {
+ throw new Error('Unknown unit run end reason');
+ }
+ for (const module of modules) this.observe(module);
+ this.receipt.test_run_end_observed = true;
+ this.receipt.test_run_reason = reason;
+ this.receipt.unhandled_error_count = unhandledErrors.length;
+ this.write();
+ }
+
+ write() {
+ const modules = [...this.modules.values()].sort((a, b) =>
+ a.module.localeCompare(b.module) || a.id.localeCompare(b.id));
+ const unobserved = modules.filter(module => !terminalStates.has(module.state))
+ .map(module => module.id);
+ const receipt = {
+ ...this.receipt,
+ // A run-end callback is not an observed process exit or a passing suite.
+ collection_complete: this.receipt.inventory_observed && modules.length > 0
+ && this.receipt.test_run_end_observed
+ && this.receipt.test_run_reason !== 'interrupted' && unobserved.length === 0,
+ unobserved_modules: unobserved,
+ modules,
+ };
+ fs.mkdirSync(path.dirname(this.outputFile), { recursive: true });
+ const temporary = `${this.outputFile}.${process.pid}.tmp`;
+ let owned = false;
+ try {
+ fs.writeFileSync(temporary, `${JSON.stringify(receipt, null, 2)}\n`,
+ { flag: 'wx', mode: 0o600 });
+ owned = true;
+ fs.renameSync(temporary, this.outputFile);
+ owned = false;
+ } finally {
+ if (owned) fs.unlinkSync(temporary);
+ }
+ }
+}
diff --git a/scripts/tests/frontend-unit-receipts.test.mjs b/scripts/tests/frontend-unit-receipts.test.mjs
new file mode 100644
index 0000000000..9d1d7886c2
--- /dev/null
+++ b/scripts/tests/frontend-unit-receipts.test.mjs
@@ -0,0 +1,165 @@
+import assert from 'node:assert/strict';
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+import { createHash } from 'node:crypto';
+import { test } from 'node:test';
+import CIUnitReceipts from '../../frontend-modern/scripts/ci-unit-receipts.mjs';
+
+const sha = 'a'.repeat(40);
+
+function fixture(t) {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'unit-receipts-'));
+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));
+ const lock = '{"synthetic":"lock"}\n';
+ fs.writeFileSync(path.join(root, 'package-lock.json'), lock);
+ const outputFile = path.join(root, 'evidence', 'units.json');
+ const reporter = new CIUnitReceipts({ outputFile, sourceSha: sha });
+ const ctx = { config: { root, shard: { index: 2, count: 4 } } };
+ const spec = name => ({
+ taskId: name, moduleId: path.join(root, `${name}.test.ts`),
+ project: { name: '' }, pool: 'forks',
+ });
+ const module = (name, state = 'passed', states = ['passed'], errors = []) => ({
+ id: name, state: () => state, errors: () => errors,
+ children: { *allTests() {
+ for (const state of states) yield {
+ result: () => ({ state, errors: [{ message: 'SYNTHETIC_PRIVATE_ERROR' }] }),
+ fullName: 'SYNTHETIC_PRIVATE_NAME',
+ };
+ } },
+ });
+ const read = () => JSON.parse(fs.readFileSync(outputFile, 'utf8'));
+ reporter.onInit(ctx);
+ return { root, lock, outputFile, reporter, ctx, spec, module, read };
+}
+
+test('initial receipt binds source, lock and actual shard, with no invented inventory or exit', t => {
+ const f = fixture(t);
+ const receipt = f.read();
+ assert.equal(receipt.source_sha, sha);
+ assert.equal(receipt.package_lock_sha256, createHash('sha256').update(f.lock).digest('hex'));
+ assert.deepEqual(receipt.shard, { index: 2, count: 4 });
+ assert.equal(receipt.inventory_observed, false);
+ assert.equal(receipt.collection_complete, false);
+ assert.equal(receipt.test_run_end_observed, false);
+ assert.equal(receipt.test_run_reason, null);
+ assert.equal(receipt.unhandled_error_count, null);
+ assert.deepEqual(receipt.modules, []);
+ assert.equal('exit_code' in receipt, false);
+ assert.equal('passed' in receipt, false);
+ assert.equal(fs.statSync(f.outputFile).mode & 0o777, 0o600);
+});
+
+test('completed failure and success survive while another selected module is unobserved', t => {
+ const { reporter, spec, module, read, outputFile } = fixture(t);
+ reporter.onTestRunStart(['z-held', 'b-pass', 'a-fail'].map(spec));
+ reporter.onTestModuleEnd(module('b-pass', 'passed', ['passed', 'skipped']));
+ reporter.onTestModuleEnd(module('a-fail', 'failed', ['failed'], [{ message: 'SYNTHETIC_PRIVATE_ERROR' }]));
+ const receipt = read();
+ assert.deepEqual(receipt.modules.map(m => m.id), ['a-fail', 'b-pass', 'z-held']);
+ assert.deepEqual(receipt.unobserved_modules, ['z-held']);
+ assert.equal(receipt.collection_complete, false);
+ assert.equal(receipt.test_run_end_observed, false);
+ assert.equal(receipt.modules[0].state, 'failed');
+ assert.equal(receipt.modules[0].module_error_count, 1);
+ assert.equal(receipt.modules[1].tests.skipped, 1);
+ assert.equal(receipt.modules[2].tests, null);
+ const bytes = fs.readFileSync(outputFile, 'utf8');
+ assert.ok(!bytes.includes('SYNTHETIC_PRIVATE'));
+ assert.ok(!bytes.includes('message'));
+});
+
+test('complete failed run remains failed, including collection and unhandled errors', t => {
+ const { reporter, spec, module, read } = fixture(t);
+ const before = process.exitCode;
+ reporter.onTestRunStart(['bad-import', 'skip', 'pass'].map(spec));
+ reporter.onTestRunEnd([
+ module('bad-import', 'failed', [], [{ message: 'secret' }]),
+ module('skip', 'skipped', ['skipped']), module('pass'),
+ ], [{ message: 'secret' }], 'failed');
+ const receipt = read();
+ assert.equal(receipt.collection_complete, true);
+ assert.equal(receipt.test_run_reason, 'failed');
+ assert.equal(receipt.unhandled_error_count, 1);
+ assert.deepEqual(receipt.modules[0].tests, { passed: 0, failed: 0, skipped: 0, pending: 0 });
+ assert.equal(receipt.modules[0].module_error_count, 1);
+ assert.equal(process.exitCode, before, 'the reporter must never replace the test runner verdict');
+});
+
+test('an interrupted end, missing results or an empty inventory cannot claim complete proof', t => {
+ const { reporter, spec, module, read } = fixture(t);
+ reporter.onTestRunStart(['pass', 'held'].map(spec));
+ reporter.onTestRunEnd([module('pass')], [], 'interrupted');
+ assert.equal(read().collection_complete, false);
+ assert.deepEqual(read().unobserved_modules, ['held']);
+ reporter.onTestRunEnd([], [], 'failed');
+ assert.equal(read().collection_complete, false);
+ reporter.onTestRunStart([]);
+ assert.equal(read().test_run_end_observed, false);
+ assert.equal(read().test_run_reason, null);
+ reporter.onTestRunEnd([], [], 'passed');
+ assert.equal(read().collection_complete, false);
+});
+
+test('queued and pending are observations, not terminal completions', t => {
+ const { reporter, spec, module, read } = fixture(t);
+ reporter.onTestRunStart(['held'].map(spec));
+ for (const state of ['queued', 'pending']) {
+ reporter.onTestRunEnd([module('held', state, ['pending'])], [], 'failed');
+ assert.equal(read().modules[0].state, state);
+ assert.equal(read().modules[0].tests.pending, 1);
+ assert.equal(read().collection_complete, false);
+ assert.deepEqual(read().unobserved_modules, ['held']);
+ }
+});
+
+test('all selected terminal modules and the run end are required for a complete observation', t => {
+ const { reporter, spec, module, read } = fixture(t);
+ reporter.onTestRunStart(['one', 'two'].map(spec));
+ reporter.onTestModuleEnd(module('one'));
+ reporter.onTestModuleEnd(module('two'));
+ assert.equal(read().collection_complete, false);
+ reporter.onTestRunEnd([module('one'), module('two')], [], 'passed');
+ assert.equal(read().collection_complete, true);
+ assert.equal(read().test_run_reason, 'passed');
+ assert.equal(read().unhandled_error_count, 0);
+ assert.deepEqual(read().unobserved_modules, []);
+});
+
+test('unknown results, duplicate inventories and outside-root paths fail without replacing proof', t => {
+ const { reporter, spec, module, read, root } = fixture(t);
+ reporter.onTestRunStart(['known'].map(spec));
+ const before = read();
+ for (const bad of [
+ () => reporter.onTestModuleEnd(module('unknown')),
+ () => reporter.onTestRunStart([spec('known'), spec('known')]),
+ () => reporter.onTestRunStart([{ ...spec('outside'), moduleId: path.join(root, '..', 'outside.ts') }]),
+ () => reporter.onTestModuleEnd(module('known', 'unexpected')),
+ () => reporter.onTestModuleEnd(module('known', 'passed', ['unexpected'])),
+ () => reporter.onTestRunEnd([], [], 'unknown'),
+ ]) {
+ assert.throws(bad);
+ assert.deepEqual(read(), before);
+ }
+});
+
+test('a failed atomic write preserves the last complete JSON snapshot', t => {
+ const { reporter, spec, module, read, outputFile } = fixture(t);
+ reporter.onTestRunStart(['one'].map(spec));
+ const before = read();
+ const temporary = `${outputFile}.${process.pid}.tmp`;
+ fs.mkdirSync(temporary);
+ assert.throws(() => reporter.onTestModuleEnd(module('one')));
+ assert.deepEqual(read(), before);
+ assert.equal(fs.statSync(temporary).isDirectory(), true, 'do not remove an unowned temporary');
+});
+
+test('missing source binding and stale output refuse rather than reusing prior proof', t => {
+ assert.throws(() => new CIUnitReceipts({ outputFile: '/unused', sourceSha: 'main' }));
+ assert.throws(() => new CIUnitReceipts({ outputFile: '/unused', sourceSha: '' }));
+ const { outputFile, ctx, read } = fixture(t);
+ const before = read();
+ assert.throws(() => new CIUnitReceipts({ outputFile, sourceSha: sha }).onInit(ctx));
+ assert.deepEqual(read(), before);
+});
diff --git a/scripts/tests/test_frontend_workflow_order.py b/scripts/tests/test_frontend_workflow_order.py
index ad54c22800..dce9f78489 100644
--- a/scripts/tests/test_frontend_workflow_order.py
+++ b/scripts/tests/test_frontend_workflow_order.py
@@ -131,18 +131,42 @@ class FrontendWorkflowOrderTest(unittest.TestCase):
steps = unit["steps"]
self.assertEqual([step["name"] for step in steps], [
"Checkout repository", "Set up Node.js", "Install frontend dependencies", "Frontend unit tests",
+ "Retain frontend unit observations",
])
- for step in steps:
+ for step in steps[:-1]:
self.assertNotIn("if", step)
self.assertNotIn("continue-on-error", step)
if step["name"] != "Frontend unit tests":
self.assertEqual(step, self.step(step["name"]))
- self.assertEqual(steps[-1], {
+ self.assertEqual(steps[-2], {
"name": "Frontend unit tests", "working-directory": "frontend-modern",
- "run": "npm run test -- --shard=${{ matrix.shard }}/4",
+ "env": {
+ "PULSE_UNIT_RECEIPT": "${{ runner.temp }}/frontend-unit-${{ matrix.shard }}-${{ github.run_attempt }}.json",
+ "PULSE_UNIT_SOURCE_SHA": "${{ github.sha }}",
+ },
+ "run": "npm run test -- --shard=${{ matrix.shard }}/4 "
+ "--reporter=default --reporter=./scripts/ci-unit-receipts.mjs",
+ })
+ self.assertEqual(steps[-1], {
+ "name": "Retain frontend unit observations", "if": "always()",
+ "uses": "actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9",
+ "with": {
+ "name": "frontend-unit-${{ matrix.shard }}-${{ github.run_attempt }}",
+ "path": "${{ runner.temp }}/frontend-unit-${{ matrix.shard }}-${{ github.run_attempt }}.json",
+ "if-no-files-found": "warn", "retention-days": 7,
+ },
})
self.assertEqual(self.workflow["permissions"], {"contents": "read"})
+ def test_unit_reporter_controls_are_registered_and_run_before_dependency_work(self):
+ step = self.step("Validate frontend unit evidence reporter")
+ self.assertEqual(step["run"], "node --test scripts/tests/frontend-unit-receipts.test.mjs")
+ names = [step["name"] for step in self.steps]
+ self.assertLess(names.index(step["name"]), names.index("Install frontend dependencies"))
+ result = subprocess.run(["node", "--test", "scripts/tests/frontend-unit-receipts.test.mjs"],
+ cwd=ROOT, text=True, capture_output=True, timeout=15)
+ self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
+
def test_runtime_and_units_are_independent_required_siblings(self):
runtime = self.jobs["frontend-checks"]
unit = self.jobs["frontend-unit"]