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.

test(alerts): automate operator qualification

rcourtman248b24203494
diff --git a/docs/release-control/v6/internal/status.json b/docs/release-control/v6/internal/status.json
index 0f1795d2ec..f475e26a87 100644
--- a/docs/release-control/v6/internal/status.json
+++ b/docs/release-control/v6/internal/status.json
@@ -9764,34 +9764,6 @@
}
]
},
- {
- "id": "alert-lifecycle-contract-coverage",
- "summary": "Alert transition semantics (hysteresis, sustained-for delays, severity derivation, confirmations) have no deterministic engine-independent contract harness, so transition-core regressions ship undetected (#1682, #1683, #1553, #1693, #1724) and cross-family drift is invisible. Resolution is Phase 1 of docs/ALERT_ENGINE_EVOLUTION.md: a pure characterization reducer (internal/alerts/reducer) plus a parity harness driving reducer and manager through identical sequences; the first metric-family slice already surfaced and fixed a silent stale-resolve defect in checkMetric.",
- "owner": "project-owner",
- "status": "triaged",
- "recorded_at": "2026-08-26",
- "lane_ids": [
- "L6",
- "L13"
- ],
- "subsystem_ids": [
- "alerts"
- ],
- "proposed_resolution": "lane-expansion",
- "coverage_impact": 5,
- "evidence": [
- {
- "repo": "pulse",
- "path": "docs/ALERT_ENGINE_EVOLUTION.md",
- "kind": "file"
- },
- {
- "repo": "pulse",
- "path": "docs/release-control/v6/internal/records/alert-lifecycle-contract-coverage-2026-08-26.md",
- "kind": "file"
- }
- ]
- },
{
"id": "alert-identity-config-migration",
"summary": "Persisted alert state (threshold override keys, ack records, active-alert IDs) still carries legacy identity forms bridged at read time by alias layers (thresholdOverrideForResourceNoLock registry translation, lookupGuestOverride's three-key fallback, storageThresholdLookupIDs, testAlertEquivalentIDs' ~8 equivalent forms). The Phase 3 policy fold contains the bridging behind one resolution surface, but the alias code must be maintained until an explicit, versioned config migration rewrites persisted keys to canonical identity. Deliberately deferred from the 2026-08 evolution work: rewriting user override keys requires the live resource registry for translation and carries the #1738 failure mode in reverse (silently orphaning overrides), so it needs its own migration design, dry-run tooling, and test round rather than landing mid-RC.",
diff --git a/tests/integration/package.json b/tests/integration/package.json
index f3eac27746..8273a8c0c7 100644
--- a/tests/integration/package.json
+++ b/tests/integration/package.json
@@ -5,6 +5,7 @@
"type": "module",
"scripts": {
"test": "node ./scripts/run-playwright.mjs",
+ "test:alerts:qualification": "node ./scripts/run-alert-qualification.mjs",
"check:e2e-tiers": "node ./scripts/check-e2e-tiering.mjs",
"evals": "node ./scripts/run-evals.mjs",
"test:visual": "npm test -- tests/06-theme-visual.spec.ts --project=chromium",
diff --git a/tests/integration/scripts/managed-local-backend.mjs b/tests/integration/scripts/managed-local-backend.mjs
index 13f06a0afc..baebab5556 100644
--- a/tests/integration/scripts/managed-local-backend.mjs
+++ b/tests/integration/scripts/managed-local-backend.mjs
@@ -140,6 +140,40 @@ function withManagedLocalBackendPort(state, port) {
};
}
+const managedLocalBackendFixtureMappings = [
+ {
+ envKey: 'PULSE_E2E_ALERT_HISTORY_FIXTURE',
+ destination: path.join('alerts', 'alert-history.json'),
+ },
+ {
+ envKey: 'PULSE_E2E_ACTIVE_ALERTS_FIXTURE',
+ destination: path.join('alerts', 'active-alerts.json'),
+ },
+];
+
+async function seedManagedLocalBackendFixtures(state, env, logger) {
+ for (const fixture of managedLocalBackendFixtureMappings) {
+ const sourcePath = trim(env[fixture.envKey]);
+ if (sourcePath === '') {
+ continue;
+ }
+
+ const sourceStats = await fs.stat(sourcePath);
+ if (!sourceStats.isFile()) {
+ throw new Error(`${fixture.envKey} must name a regular file: ${sourcePath}`);
+ }
+
+ const destinationPath = path.join(state.dataDir, fixture.destination);
+ await fs.mkdir(path.dirname(destinationPath), {
+ recursive: true,
+ mode: 0o700,
+ });
+ await fs.copyFile(sourcePath, destinationPath);
+ await fs.chmod(destinationPath, 0o600);
+ logger.log(`[integration] Seeded ${fixture.destination} from ${fixture.envKey}`);
+ }
+}
+
export function buildManagedLocalBackendEnv(state, env = process.env) {
const allowedOrigins = [
`http://${state.host}:5173`,
@@ -593,6 +627,7 @@ export async function startManagedLocalBackend({
`${backendEnv.PULSE_E2E_BOOTSTRAP_TOKEN}\n`,
{ mode: 0o600 },
);
+ await seedManagedLocalBackendFixtures(state, env, logger);
await ensureFrontendAssets(state, logger);
await ensureBackendBinary(state, logger);
@@ -623,7 +658,10 @@ export async function startManagedLocalBackend({
baseURL: state.baseURL,
pid: child.pid,
dataDir: state.dataDir,
+ rootDir: state.rootDir,
logPath: state.logPath,
+ binaryPath: state.binaryPath,
+ auditSigningKey: backendEnv.PULSE_AUDIT_SIGNING_KEY,
billingStatePath: state.billingStatePath,
primaryAPIToken: securityState.primaryAPIToken,
};
@@ -644,10 +682,90 @@ export async function startManagedLocalBackend({
}
}
+export async function restartManagedLocalBackend({ env = process.env, logger = console } = {}) {
+ const runtimeState = await readRuntimeState(env);
+ if (!runtimeState?.managedLocalBackend) {
+ throw new Error('Managed local backend restart requires an active managed backend runtime');
+ }
+
+ const parsedBaseURL = new URL(runtimeState.baseURL);
+ const configuredState = buildManagedLocalBackendState(env);
+ const rootDir = trim(runtimeState.rootDir) || path.dirname(runtimeState.dataDir);
+ const state = {
+ ...configuredState,
+ host: parsedBaseURL.hostname,
+ port: parsedBaseURL.port,
+ baseURL: runtimeState.baseURL.replace(/\/+$/, ''),
+ rootDir,
+ dataDir: runtimeState.dataDir,
+ logPath: runtimeState.logPath,
+ pidPath: path.join(rootDir, 'pulse.pid'),
+ billingStatePath: runtimeState.billingStatePath || path.join(runtimeState.dataDir, 'billing.json'),
+ binaryPath: trim(runtimeState.binaryPath) || configuredState.binaryPath,
+ };
+ const backendEnv = buildManagedLocalBackendEnv(state, {
+ ...env,
+ PULSE_AUDIT_SIGNING_KEY: trim(runtimeState.auditSigningKey) || trim(env.PULSE_AUDIT_SIGNING_KEY),
+ });
+
+ await stopManagedLocalBackend({
+ env,
+ logger,
+ state: runtimeState,
+ preserveData: true,
+ preserveRuntimeState: true,
+ });
+
+ const logHandle = await fs.open(state.logPath, 'a');
+ const child = spawn(state.binaryPath, [], {
+ cwd: state.rootDir,
+ env: backendEnv,
+ detached: true,
+ stdio: ['ignore', logHandle.fd, logHandle.fd],
+ });
+ child.unref();
+ await logHandle.close();
+
+ if (!Number.isInteger(child.pid) || child.pid <= 0) {
+ throw new Error('Managed local backend failed to restart');
+ }
+
+ await fs.writeFile(state.pidPath, `${child.pid}\n`, 'utf8');
+ try {
+ await waitForHealth(`${state.baseURL}/api/health`, child.pid);
+ await assertManagedLocalBackendStartupHealthy(state);
+ const securityState = await ensureManagedLocalBackendSecurity(state, backendEnv, logger);
+ const nextRuntimeState = {
+ ...runtimeState,
+ pid: child.pid,
+ rootDir: state.rootDir,
+ dataDir: state.dataDir,
+ logPath: state.logPath,
+ binaryPath: state.binaryPath,
+ auditSigningKey: backendEnv.PULSE_AUDIT_SIGNING_KEY,
+ primaryAPIToken: securityState.primaryAPIToken,
+ };
+ await writeRuntimeState(nextRuntimeState, env);
+ logger.log(`[integration] Restarted managed local backend at ${state.baseURL} (pid ${child.pid})`);
+ return nextRuntimeState;
+ } catch (error) {
+ if (await pidExists(child.pid)) {
+ try {
+ process.kill(child.pid, 'SIGTERM');
+ } catch {
+ // process exited between checks
+ }
+ }
+ throw error;
+ }
+}
+
export async function stopManagedLocalBackend({
env = process.env,
logger = console,
state = null,
+ preserveData = false,
+ preserveRuntimeState = false,
} = {}) {
const runtimeState = state || await readRuntimeState(env);
if (!runtimeState || !runtimeState.managedLocalBackend) {
@@ -673,10 +791,19 @@ export async function stopManagedLocalBackend({
}
}
- if (trim(runtimeState.dataDir) !== '') {
- await fs.rm(path.dirname(runtimeState.dataDir), { recursive: true, force: true });
+ if (!preserveData && trim(runtimeState.dataDir) !== '') {
+ await fs.rm(path.dirname(runtimeState.dataDir), {
+ recursive: true,
+ force: true,
+ });
}
- await clearRuntimeState(env);
- logger.log('[integration] Stopped managed local backend');
+ if (!preserveRuntimeState) {
+ await clearRuntimeState(env);
+ }
+ logger.log(
+ preserveData
+ ? '[integration] Stopped managed local backend and preserved its data'
+ : '[integration] Stopped managed local backend',
+ );
return true;
}
diff --git a/tests/integration/scripts/run-alert-qualification.mjs b/tests/integration/scripts/run-alert-qualification.mjs
new file mode 100644
index 0000000000..ea28e99512
--- /dev/null
+++ b/tests/integration/scripts/run-alert-qualification.mjs
@@ -0,0 +1,107 @@
+#!/usr/bin/env node
+
+import fs from 'node:fs/promises';
+import path from 'node:path';
+import { spawn } from 'node:child_process';
+import { fileURLToPath } from 'node:url';
+
+const scriptsDir = path.dirname(fileURLToPath(import.meta.url));
+const integrationRoot = path.resolve(scriptsDir, '..');
+const repoRoot = path.resolve(integrationRoot, '..', '..');
+const runId = `alert-qualification-${Date.now()}-${process.pid}`;
+const runRoot = path.join(repoRoot, 'tmp', runId);
+const fixtureRoot = path.join(runRoot, 'fixtures');
+const runtimeStatePath = path.join(repoRoot, 'tmp', `${runId}.runtime-state.json`);
+const binaryPath = path.join(repoRoot, 'tmp', 'integration-local-backend', 'bin', 'pulse-alert-qualification');
+
+const minutesAgo = (minutes) => new Date(Date.now() - minutes * 60_000).toISOString();
+
+const legacyHistory = [
+ {
+ alert: {
+ id: 'legacy-history-qualification',
+ type: 'cpu',
+ level: 'warning',
+ resourceId: 'qualification-legacy-vm',
+ resourceName: 'Legacy Qualification VM',
+ node: 'qualification-node',
+ nodeDisplayName: 'Qualification Node',
+ instance: 'qualification',
+ message: 'Legacy history import rendered from SQLite',
+ value: 91,
+ threshold: 80,
+ startTime: minutesAgo(90),
+ lastSeen: minutesAgo(60),
+ acknowledged: false,
+ metadata: { resourceType: 'vm' },
+ },
+ timestamp: minutesAgo(60),
+ },
+];
+
+const activeAlerts = [
+ {
+ id: 'active-overlay-qualification',
+ type: 'memory',
+ level: 'warning',
+ resourceId: 'agent:qualification-active',
+ resourceName: 'Active Overlay Node',
+ node: 'qualification-active',
+ nodeDisplayName: 'Active Overlay Node',
+ instance: 'qualification',
+ message: 'Active alert remains visible after history clear',
+ value: 86,
+ threshold: 80,
+ startTime: minutesAgo(10),
+ lastSeen: minutesAgo(1),
+ acknowledged: false,
+ metadata: { resourceType: 'agent' },
+ },
+];
+
+const run = (command, args, options = {}) =>
+ new Promise((resolve, reject) => {
+ const child = spawn(command, args, { stdio: 'inherit', ...options });
+ child.on('error', reject);
+ child.on('close', (code) => resolve(code ?? 1));
+ });
+
+await fs.mkdir(fixtureRoot, { recursive: true });
+const historyFixturePath = path.join(fixtureRoot, 'alert-history.json');
+const activeFixturePath = path.join(fixtureRoot, 'active-alerts.json');
+await fs.writeFile(historyFixturePath, `${JSON.stringify(legacyHistory, null, 2)}\n`, 'utf8');
+await fs.writeFile(activeFixturePath, `${JSON.stringify(activeAlerts, null, 2)}\n`, 'utf8');
+
+let exitCode = 1;
+try {
+ exitCode = await run(
+ process.execPath,
+ [
+ './scripts/run-playwright.mjs',
+ 'tests/93-alert-operator-qualification.spec.ts',
+ 'tests/94-alert-history-real-backend.spec.ts',
+ '--project=chromium',
+ ],
+ {
+ cwd: integrationRoot,
+ env: {
+ ...process.env,
+ PULSE_E2E_USE_LOCAL_BACKEND: '1',
+ PULSE_MOCK_MODE: 'false',
+ PULSE_E2E_ALERT_HISTORY_QUALIFICATION: '1',
+ PULSE_E2E_ALERT_HISTORY_FIXTURE: historyFixturePath,
+ PULSE_E2E_ACTIVE_ALERTS_FIXTURE: activeFixturePath,
+ PULSE_E2E_LOCAL_BACKEND_BINARY: binaryPath,
+ PULSE_E2E_RUN_ID: runId,
+ PULSE_E2E_RUNTIME_STATE_PATH: runtimeStatePath,
+ PULSE_E2E_REPORT_DIR: path.join(runRoot, 'playwright-report'),
+ PULSE_E2E_RESULTS_DIR: path.join(runRoot, 'test-results'),
+ },
+ },
+ );
+} finally {
+ await fs.rm(fixtureRoot, { recursive: true, force: true });
+ await fs.rm(runtimeStatePath, { force: true });
+}
+
+process.exit(exitCode);
diff --git a/tests/integration/tests/93-alert-operator-qualification.spec.ts b/tests/integration/tests/93-alert-operator-qualification.spec.ts
new file mode 100644
index 0000000000..de9c5ca5dd
--- /dev/null
+++ b/tests/integration/tests/93-alert-operator-qualification.spec.ts
@@ -0,0 +1,428 @@
+import fs from 'node:fs';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+import { expect, test as base, type Page } from '@playwright/test';
+
+import { createAuthenticatedStorageState } from './helpers';
+
+const __dirname = path.dirname(fileURLToPath(import.meta.url));
+
+type WorkerFixtures = {
+ authStorageStatePath: string;
+};
+
+const test = base.extend<{}, WorkerFixtures>({
+ storageState: async ({ authStorageStatePath }, use) => use(authStorageStatePath),
+ authStorageStatePath: [
+ async ({ browser }, use, workerInfo) => {
+ const storageStatePath = path.resolve(
+ __dirname,
+ '..',
+ '..',
+ 'tmp',
+ 'playwright-auth',
+ `alert-operator-qualification-${workerInfo.project.name}.json`,
+ );
+ fs.mkdirSync(path.dirname(storageStatePath), { recursive: true });
+ await createAuthenticatedStorageState(browser, storageStatePath);
+ try {
+ await use(storageStatePath);
+ } finally {
+ fs.rmSync(storageStatePath, { force: true });
+ }
+ },
+ { scope: 'worker' },
+ ],
+});
+
+const now = Date.now();
+const minutesAgo = (minutes: number) => new Date(now - minutes * 60_000).toISOString();
+
+const qualificationHistory = [
+ {
+ id: 'qualification-database-critical',
+ type: 'cpu',
+ level: 'critical',
+ resourceId: 'agent:database-primary',
+ resourceName: 'Database Primary',
+ node: 'database-node.internal.example',
+ nodeDisplayName: 'Database Node With A Deliberately Long Operator-Facing Label',
+ instance: 'qualification',
+ message:
+ 'CPU saturation persisted while a deliberately long diagnostic message remained readable without widening the alert history page.',
+ value: 97,
+ threshold: 90,
+ startTime: minutesAgo(25),
+ lastSeen: minutesAgo(20),
+ acknowledged: false,
+ metadata: { resourceType: 'agent' },
+ },
+ {
+ id: 'qualification-cache-warning',
+ type: 'memory',
+ level: 'warning',
+ resourceId: 'agent:cache-primary',
+ resourceName: 'Cache Primary',
+ node: 'cache-node',
+ instance: 'qualification',
+ message: 'Memory pressure crossed the warning threshold.',
+ value: 84,
+ threshold: 80,
+ startTime: minutesAgo(65),
+ lastSeen: minutesAgo(50),
+ acknowledged: false,
+ metadata: { resourceType: 'agent' },
+ },
+ {
+ id: 'qualification-router-critical',
+ type: 'host-offline',
+ level: 'critical',
+ resourceId: 'agent:edge-router',
+ resourceName: 'Edge Router',
+ node: 'edge-router',
+ instance: 'qualification',
+ message: 'The edge router stopped reporting.',
+ value: 0,
+ threshold: 0,
+ startTime: minutesAgo(125),
+ lastSeen: minutesAgo(115),
+ acknowledged: true,
+ metadata: { resourceType: 'agent' },
+ },
+];
+
+const activeDeliveryAlert = {
+ id: 'qualification-delivery-alert',
+ type: 'cpu',
+ level: 'critical',
+ resourceId: 'agent:delivery-node',
+ resourceName: 'Delivery Node',
+ node: 'delivery-node',
+ instance: 'qualification',
+ message: 'CPU saturation is waiting behind the hourly notification limit.',
+ value: 96,
+ threshold: 90,
+ startTime: minutesAgo(10),
+ lastSeen: minutesAgo(1),
+ acknowledged: false,
+ metadata: { resourceType: 'agent' },
+};
+
+async function routeStateWithActiveAlerts(page: Page, activeAlerts: unknown[]) {
+ await page.routeWebSocket('**/ws*', (webSocket) => {
+ webSocket.send(
+ JSON.stringify({
+ type: 'initialState',
+ data: {
+ resources: [],
+ connectedInfrastructure: [],
+ activeAlerts,
+ recentlyResolved: [],
+ capabilityCatalog: {},
+ policyCatalog: {},
+ },
+ }),
+ );
+ });
+}
+
+async function routeAlertHistory(page: Page, history: unknown[]) {
+ await page.route('**/api/alerts/config', (route) =>
+ route.fulfill({
+ status: 200,
+ contentType: 'application/json',
+ body: JSON.stringify({
+ enabled: true,
+ activationState: 'active',
+ overrides: {},
+ }),
+ }),
+ );
+ await page.route('**/api/alerts/active', (route) =>
+ route.fulfill({ status: 200, contentType: 'application/json', body: '[]' }),
+ );
+ await page.route('**/api/alerts/history**', (route) =>
+ route.fulfill({
+ status: 200,
+ contentType: 'application/json',
+ body: JSON.stringify(history),
+ }),
+ );
+}
+
+async function expectNoHorizontalOverflow(page: Page) {
+ await expect
+ .poll(() =>
+ page.evaluate(() => ({
+ clientWidth: document.documentElement.clientWidth,
+ scrollWidth: document.documentElement.scrollWidth,
+ })),
+ )
+ .toEqual(
+ expect.objectContaining({
+ clientWidth: expect.any(Number),
+ scrollWidth: expect.any(Number),
+ }),
+ );
+ const overflow = await page.evaluate(
+ () => document.documentElement.scrollWidth - document.documentElement.clientWidth,
+ );
+ expect(overflow, 'Alert history must stay inside the viewport').toBeLessThanOrEqual(1);
+}
+
+test.describe('Alert operator qualification', () => {
+ test('keeps History filters in the URL across refresh and browser navigation', async ({ page }) => {
+ await page.setViewportSize({ width: 1440, height: 1000 });
+ await routeStateWithActiveAlerts(page, []);
+ await routeAlertHistory(page, qualificationHistory);
+
+ await page.goto('/alerts/history', { waitUntil: 'domcontentloaded' });
+ await expect(page.getByRole('heading', { name: 'Alert History' })).toBeVisible();
+ const desktopHistory = page.locator('table.alert-history-responsive-table');
+ await expect(desktopHistory.getByText('Database Primary')).toBeVisible();
+
+ const search = page.getByPlaceholder('Search alerts...');
+ await search.fill('database');
+ await expect.poll(() => new URL(page.url()).searchParams.get('q')).toBe('database');
+
+ await page
+ .getByRole('group', { name: 'Severity' })
+ .getByRole('button', { name: /Critical/ })
+ .click();
+ await page.getByRole('group', { name: 'Period' }).getByRole('button', { name: 'All time' }).click();
+ await expect.poll(() => new URL(page.url()).searchParams.get('severity')).toBe('critical');
+ await expect.poll(() => new URL(page.url()).searchParams.get('period')).toBe('all');
+ await expect(desktopHistory.getByText('Database Primary')).toBeVisible();
+ await expect(page.getByText('Cache Primary')).toHaveCount(0);
+
+ await page.reload({ waitUntil: 'domcontentloaded' });
+ await expect(search).toHaveValue('database');
+ await expect(
+ page.getByRole('group', { name: 'Severity' }).getByRole('button', { name: /Critical/ }),
+ ).toHaveAttribute('aria-pressed', 'true');
+ await expect(page.getByRole('group', { name: 'Period' }).getByRole('button', { name: 'All time' })).toHaveAttribute(
+ 'aria-pressed',
+ 'true',
+ );
+
+ await page.getByRole('button', { name: 'Overview', exact: true }).click();
+ await expect(page).toHaveURL(/\/alerts\/overview$/);
+ await page.goBack({ waitUntil: 'domcontentloaded' });
+ await expect.poll(() => new URL(page.url()).searchParams.get('q')).toBe('database');
+ await page.goForward({ waitUntil: 'domcontentloaded' });
+ await expect(page).toHaveURL(/\/alerts\/overview$/);
+ await page.goBack({ waitUntil: 'domcontentloaded' });
+
+ await page.getByRole('button', { name: 'Clear filters' }).click();
+ await expect.poll(() => new URL(page.url()).search).toBe('');
+ await expect(desktopHistory.getByText('Cache Primary')).toBeVisible();
+ });
+
+ test('keeps long History content readable, keyboard reachable, and contained at 390px', async ({
+ page,
+ }, testInfo) => {
+ await page.setViewportSize({ width: 390, height: 844 });
+ await routeStateWithActiveAlerts(page, []);
+ await routeAlertHistory(page, qualificationHistory);
+
+ await page.goto('/alerts/history', { waitUntil: 'domcontentloaded' });
+ await expect(page.getByRole('heading', { name: 'Alert History' })).toBeVisible();
+ const mobileList = page.getByTestId('alert-history-mobile-list');
+ await expect(mobileList).toBeVisible();
+ const databaseCard = mobileList.locator('article').filter({ hasText: 'Database Primary' });
+ await expect(databaseCard).toContainText('deliberately long diagnostic message');
+ await expect(databaseCard).toContainText('Database Node With A Deliberately Long');
+
+ const search = page.getByPlaceholder('Search alerts...');
+ await search.focus();
+ await expect(search).toBeFocused();
+ await search.fill('cache');
+ await expect(page.getByText('Cache Primary').first()).toBeVisible();
+ await page.keyboard.press('Escape');
+ await expect(search).toHaveValue('');
+
+ const filtersButton = page.getByRole('button', { name: /Filters/ });
+ await filtersButton.focus();
+ await expect(filtersButton).toBeFocused();
+ await page.keyboard.press('Enter');
+ await expect(page.getByRole('group', { name: 'Severity' })).toBeVisible();
+ await expectNoHorizontalOverflow(page);
+
+ await testInfo.attach('alert-history-390px', {
+ body: await page.screenshot({ fullPage: true }),
+ contentType: 'image/png',
+ });
+ });
+
+ test('shows per-alert delivery diagnosis and interleaves held notification evidence', async ({ page }) => {
+ await page.setViewportSize({ width: 1440, height: 1000 });
+ await routeStateWithActiveAlerts(page, [activeDeliveryAlert]);
+ await page.route('**/api/alerts/config', (route) =>
+ route.fulfill({
+ status: 200,
+ contentType: 'application/json',
+ body: JSON.stringify({
+ enabled: true,
+ activationState: 'active',
+ overrides: {},
+ }),
+ }),
+ );
+ await page.route('**/api/alerts/delivery-diagnosis', (route) =>
+ route.fulfill({
+ status: 200,
+ contentType: 'application/json',
+ body: JSON.stringify([
+ {
+ alertIdentifier: activeDeliveryAlert.id,
+ alertId: activeDeliveryAlert.id,
+ status: 'suppressed',
+ reason: 'rate_limited',
+ message: 'Hourly notification limit reached.',
+ },
+ ]),
+ }),
+ );
+ await page.route('**/api/notifications/health', (route) =>
+ route.fulfill({
+ status: 200,
+ contentType: 'application/json',
+ body: JSON.stringify({
+ overall_healthy: true,
+ queue: {
+ status: 'healthy',
+ healthy: true,
+ pending: 0,
+ sending: 0,
+ sent: 1,
+ failed: 0,
+ dlq: 0,
+ terminal_failure_count: 0,
+ attention_required: 0,
+ reason_codes: [],
+ completed_retention_days: 7,
+ dead_letter_retention_days: 30,
+ counts_are_retention_bounded: true,
+ retry_attempts_affect_health: false,
+ terminal_failures_affect_health: true,
+ failure_classes_7d: {},
+ failure_classes_available: true,
+ failure_class_window_days: 7,
+ },
+ }),
+ }),
+ );
+ await page.route('**/api/notifications/delivery-log**', (route) =>
+ route.fulfill({
+ status: 200,
+ contentType: 'application/json',
+ body: JSON.stringify({
+ window_days: 7,
+ entries: [
+ {
+ notificationId: 'attempt-1',
+ timestamp: minutesAgo(4),
+ type: 'email',
+ destinationId: 'email:qualification',
+ outcome: 'sent',
+ success: true,
+ alertIds: ['qualification-delivered-alert'],
+ alertCount: 1,
+ attempts: 1,
+ },
+ ],
+ }),
+ }),
+ );
+ let heldEventsAvailable = true;
+ await page.route('**/api/alerts/events**', (route) =>
+ route.fulfill({
+ status: heldEventsAvailable ? 200 : 503,
+ contentType: 'application/json',
+ body: heldEventsAvailable
+ ? JSON.stringify([
+ {
+ id: 'held-1',
+ type: 'notification_deferred',
+ alertId: activeDeliveryAlert.id,
+ alertType: activeDeliveryAlert.type,
+ resourceName: activeDeliveryAlert.resourceName,
+ reason: 'quiet_hours',
+ message: 'Held until quiet hours end.',
+ occurredAt: minutesAgo(2),
+ },
+ ])
+ : JSON.stringify({ error: 'event log unavailable' }),
+ }),
+ );
+
+ await page.goto('/alerts/overview', { waitUntil: 'domcontentloaded' });
+ await expect(page.getByText('Delivery Node').first()).toBeVisible();
+ await expect(page.getByText('Hourly notification limit reached')).toBeVisible();
+
+ await page.goto('/alerts/notifications', { waitUntil: 'domcontentloaded' });
+ await expect(page.getByRole('heading', { name: 'Notifications', exact: true })).toBeVisible();
+ await expect(page.getByRole('heading', { name: 'Delivery activity' })).toBeVisible();
+ await expect(page.getByText('Deferred')).toBeVisible();
+ await expect(page.getByText('Quiet hours')).toBeVisible();
+ await expect(page.getByText('Delivered', { exact: true })).toBeVisible();
+
+ heldEventsAvailable = false;
+ const refresh = page
+ .getByRole('heading', { name: 'Recent delivery activity' })
+ .locator('..')
+ .locator('..')
+ .getByRole('button', { name: 'Refresh delivery status' });
+ await refresh.focus();
+ await page.keyboard.press('Enter');
+ await expect(page.getByText('Deferred')).toHaveCount(0);
+ await expect(page.getByText('Delivered', { exact: true })).toBeVisible();
+ await expect(page.getByText(/Delivery history is unavailable/i)).toHaveCount(0);
+ });
+
+ test('mounts a bounded runway and renders 10,000 History records within budget', async ({ page }, testInfo) => {
+ test.skip(testInfo.project.name !== 'chromium', 'One Chromium scale measurement owns this budget');
+ test.setTimeout(120_000);
+ await page.setViewportSize({ width: 1440, height: 1000 });
+ await routeStateWithActiveAlerts(page, []);
+ const scaleHistory = Array.from({ length: 10_000 }, (_, index) => ({
+ id: `qualification-scale-${index}`,
+ type: index % 3 === 0 ? 'cpu' : 'memory',
+ level: index % 5 === 0 ? 'critical' : 'warning',
+ resourceId: `agent:scale-${index}`,
+ resourceName: `Scale Resource ${String(index).padStart(5, '0')}`,
+ node: `scale-node-${index % 250}`,
+ instance: 'qualification',
+ message: `Qualification record ${index}`,
+ value: 80 + (index % 20),
+ threshold: 80,
+ startTime: new Date(now - index * 30_000).toISOString(),
+ lastSeen: new Date(now - index * 30_000 + 10_000).toISOString(),
+ acknowledged: false,
+ metadata: { resourceType: 'agent' },
+ }));
+ await routeAlertHistory(page, scaleHistory);
+
+ const startedAt = Date.now();
+ await page.goto('/alerts/history', { waitUntil: 'domcontentloaded' });
+ await expect(page.locator('table.alert-history-responsive-table').getByText('Scale Resource 00000')).toBeVisible();
+ const renderedAtMs = Date.now() - startedAt;
+
+ const mountedRows = await page.locator('tbody tr').count();
+ expect(mountedRows, '10,000 records must not become 10,000 mounted table rows').toBeLessThan(180);
+ await expect(
+ page.locator('table.alert-history-responsive-table').locator('[data-platform-window-spacer="bottom"]'),
+ ).toHaveCount(1);
+ expect(renderedAtMs, `10,000-row History first render took ${renderedAtMs}ms`).toBeLessThan(8_000);
+
+ console.log(
+ `[qualification] History 10,000-row first render: ${renderedAtMs}ms; mounted rows: ${mountedRows}`,
+ );
+
+ await testInfo.attach('alert-history-10000-performance.json', {
+ body: Buffer.from(JSON.stringify({ recordCount: scaleHistory.length, mountedRows, renderedAtMs }, null, 2)),
+ contentType: 'application/json',
+ });
+ });
+});
diff --git a/tests/integration/tests/94-alert-history-real-backend.spec.ts b/tests/integration/tests/94-alert-history-real-backend.spec.ts
new file mode 100644
index 0000000000..ea79ada1b5
--- /dev/null
+++ b/tests/integration/tests/94-alert-history-real-backend.spec.ts
@@ -0,0 +1,152 @@
+import fs from 'node:fs';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+import { expect, test as base } from '@playwright/test';
+
+import { restartManagedLocalBackend } from '../scripts/managed-local-backend.mjs';
+import { readRuntimeState } from '../scripts/runtime-state.mjs';
+import { apiRequest, createAuthenticatedStorageState, ensureAuthenticated } from './helpers';
+
+const __dirname = path.dirname(fileURLToPath(import.meta.url));
+
+type WorkerFixtures = {
+ authStorageStatePath: string;
+};
+
+const test = base.extend<{}, WorkerFixtures>({
+ storageState: async ({ authStorageStatePath }, use) => use(authStorageStatePath),
+ authStorageStatePath: [
+ async ({ browser }, use, workerInfo) => {
+ const storageStatePath = path.resolve(
+ __dirname,
+ '..',
+ '..',
+ 'tmp',
+ 'playwright-auth',
+ `alert-history-real-backend-${workerInfo.project.name}.json`,
+ );
+ fs.mkdirSync(path.dirname(storageStatePath), { recursive: true });
+ await createAuthenticatedStorageState(browser, storageStatePath);
+ try {
+ await use(storageStatePath);
+ } finally {
+ fs.rmSync(storageStatePath, { force: true });
+ }
+ },
+ { scope: 'worker' },
+ ],
+});
+
+const qualificationEnabled = ['1', 'true', 'yes', 'on'].includes(
+ String(process.env.PULSE_E2E_ALERT_HISTORY_QUALIFICATION || '')
+ .trim()
+ .toLowerCase(),
+);
+
+const LEGACY_ALERT_ID = 'legacy-history-qualification';
+const ACTIVE_ALERT_ID = 'active-overlay-qualification';
+
+type HistoryAlert = {
+ id: string;
+ resourceName: string;
+ node?: string;
+ nodeDisplayName?: string;
+ message: string;
+ type: string;
+ startTime: string;
+ lastSeen: string;
+};
+
+async function readHistory(page: import('@playwright/test').Page): Promise<HistoryAlert[]> {
+ const response = await apiRequest(page, '/api/alerts/history?limit=0');
+ expect(response.ok(), `history API returned ${response.status()}`).toBeTruthy();
+ return (await response.json()) as HistoryAlert[];
+}
+
+test.describe('Real backend alert history qualification', () => {
+ test.skip(!qualificationEnabled, 'Run through npm run test:alerts:qualification');
+ test.setTimeout(240_000);
+
+ test('imports once, renders exact fields, survives restart, and preserves clear tombstones', async ({
+ page,
+ }, testInfo) => {
+ test.skip(testInfo.project.name !== 'chromium', 'The isolated qualification runner owns Chromium');
+
+ const runtimeState = await readRuntimeState();
+ expect(runtimeState?.managedLocalBackend).toBe(true);
+ expect(runtimeState?.dataDir).toBeTruthy();
+ expect(runtimeState?.logPath).toBeTruthy();
+ const alertsDir = path.join(runtimeState!.dataDir, 'alerts');
+ const importedPath = path.join(alertsDir, 'alert-history.json.imported');
+ const sourcePath = path.join(alertsDir, 'alert-history.json');
+
+ expect(fs.existsSync(importedPath), 'legacy history source must retire after import').toBe(true);
+ expect(fs.existsSync(sourcePath), 'retired legacy history source must leave the load path').toBe(false);
+ expect(fs.readFileSync(runtimeState!.logPath, 'utf8')).toContain(
+ 'legacy alert history imported into the event log; JSON history files retired',
+ );
+
+ await page.goto('/alerts/history', { waitUntil: 'domcontentloaded' });
+ await expect(page.getByRole('heading', { name: 'Alert History' })).toBeVisible();
+ const legacyRow = page.locator('tr').filter({ hasText: 'Legacy Qualification VM' }).first();
+ await expect(legacyRow).toContainText('Legacy history import rendered from SQLite');
+ await expect(legacyRow).toContainText('CPU');
+ await expect(legacyRow).toContainText('Qualification Node');
+ await expect(legacyRow).toContainText('30m');
+ await expect(
+ page.locator('table.alert-history-responsive-table').getByText('Active Overlay Node').first(),
+ ).toBeVisible();
+
+ let history = await readHistory(page);
+ expect(history.filter((alert) => alert.id === LEGACY_ALERT_ID)).toHaveLength(1);
+ expect(history.filter((alert) => alert.id === ACTIVE_ALERT_ID)).toHaveLength(1);
+ const importedAlert = history.find((alert) => alert.id === LEGACY_ALERT_ID);
+ expect(importedAlert).toMatchObject({
+ resourceName: 'Legacy Qualification VM',
+ node: 'qualification-node',
+ nodeDisplayName: 'Qualification Node',
+ message: 'Legacy history import rendered from SQLite',
+ type: 'cpu',
+ });
+ expect(Date.parse(importedAlert!.lastSeen) - Date.parse(importedAlert!.startTime)).toBe(30 * 60_000);
+
+ await restartManagedLocalBackend();
+ await ensureAuthenticated(page);
+ await page.goto('/alerts/history', { waitUntil: 'domcontentloaded' });
+ await expect(
+ page.locator('table.alert-history-responsive-table').getByText('Legacy Qualification VM'),
+ ).toBeVisible();
+ history = await readHistory(page);
+ expect(
+ history.filter((alert) => alert.id === LEGACY_ALERT_ID),
+ 'restart must not duplicate the imported occurrence',
+ ).toHaveLength(1);
+
+ page.once('dialog', (dialog) => dialog.accept());
+ await page.getByRole('button', { name: 'Clear All History' }).click();
+ await expect(page.getByText('Legacy Qualification VM')).toHaveCount(0);
+ await expect(
+ page.locator('table.alert-history-responsive-table').getByText('Active Overlay Node').first(),
+ ).toBeVisible();
+ history = await readHistory(page);
+ expect(history.map((alert) => alert.id)).not.toContain(LEGACY_ALERT_ID);
+ expect(history.map((alert) => alert.id)).toContain(ACTIVE_ALERT_ID);
+
+ await restartManagedLocalBackend();
+ await ensureAuthenticated(page);
+ await page.goto('/alerts/history', { waitUntil: 'domcontentloaded' });
+ await expect(page.getByText('Legacy Qualification VM')).toHaveCount(0);
+ await expect(
+ page.locator('table.alert-history-responsive-table').getByText('Active Overlay Node').first(),
+ ).toBeVisible();
+ history = await readHistory(page);
+ expect(history.map((alert) => alert.id)).not.toContain(LEGACY_ALERT_ID);
+ expect(history.filter((alert) => alert.id === ACTIVE_ALERT_ID)).toHaveLength(1);
+
+ await testInfo.attach('real-backend-alert-history-final.json', {
+ body: Buffer.from(JSON.stringify(history, null, 2)),
+ contentType: 'application/json',
+ });
+ });
+});