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): add external installed lifecycle acceptance driver

pulse-triage[bot]0f87aad59ffb
diff --git a/tests/qualification/alert-lifecycle/README.md b/tests/qualification/alert-lifecycle/README.md
new file mode 100644
index 0000000000..70de5530b7
--- /dev/null
+++ b/tests/qualification/alert-lifecycle/README.md
@@ -0,0 +1,123 @@
+# Installed alert lifecycle probe
+
+This is an external Python-standard-library driver, not a notifier mock. It uses
+normal HTTP host ingest and notification APIs and receives real webhook requests.
+It does **not** start an installed Pulse instance. Local harness tests do not prove
+installed acceptance.
+
+## Exact target and fixture contract
+
+Target: public source `2dcf23b9d75742049f72f7eac21b0bf7266ebf6e`,
+`rcourtman/pulse:6.4.4-beta.2`, published server manifest digest
+`sha256:d7d24aec91da45b901e7b1c4094d508b5f6c708dca114c0f4dbbdfddd86a82b4`.
+Never substitute current main or rebuild the binary to pass this probe.
+
+The fixture operator must supply:
+- A disposable, **empty** instance with no provider connections, agents, customer
+ data, or real destinations, isolated from production. The driver changes alert
+ settings and uses global terminal recovery actions; loopback alone does not
+ establish a disposable instance.
+- An independently inspected immutable artifact, fresh persistent volume, and
+ an identity JSON with `source` and `image_digest` above. Retain the registry
+ inspection, selected platform digest/container image ID, process identity,
+ volume identity, and launch command alongside it. This file is an operator
+ attestation, not independent artifact verification by the driver.
+- The normal webhook allowlist containing only `127.0.0.1/32`. Use the supported
+ settings, not a security bypass. Pulse and the driver must share the same
+ isolated network namespace (for example, both inside a disposable VM with the
+ server using host networking); the receiver binds only loopback.
+- A disposable admin API token with agent:report, monitoring:read,
+ settings:read and settings:write scopes, injected as
+ `PULSE_ACCEPTANCE_TOKEN` without writing it to evidence or command arguments.
+- An executable restart hook taking no arguments. It must verify the server is
+ still healthy, gracefully stop/start **only this server** with the same exact
+ image and volume, and wait for authenticated HTTP readiness. It must fail on
+ unexpected exit/crash rather than restart away the adverse result. It emits
+ only JSON with `before_process`, `after_process`, `same_volume: true`, and
+ `image_digest`. Process identity must include start time/container identity,
+ not merely a reused PID. Retain the underlying inspection and restart logs.
+ The hook timeout is 120s; the driver does not invoke a shell.
+
+Do not point this at an existing installation, disable enforced URL checks, use
+customer destinations, delete state, or inspect database internals. If the server
+crashes, stop, retain logs and failed results, and do not attempt crash diagnosis
+through this driver. No process restart is performed by the local harness tests.
+
+## Run
+
+From the repository root, after the fixture operator supplies the above:
+
+```sh
+pulse-heavy-run -- python3 tests/qualification/alert-lifecycle/acceptance.py \
+ --base http://127.0.0.1:7655 --port 18765 \
+ --identity /absolute/private/fixture-identity.json \
+ --restart-hook /absolute/private/restart-fixture \
+ --evidence /absolute/private/new-evidence-directory \
+ --run-id unique01 --disposable-fixture
+```
+
+The evidence directory must not exist. It is private and append-only by numbered
+files within the run. Keep the data volume after failure; do not rerun against
+the now-populated fixture. A new attempt needs a separately recorded fresh
+fixture. API credentials and response headers are not recorded. Proxies and
+HTTP redirects are disabled for the authenticated client.
+
+## Scenarios and bounds
+
+1. CPU 95% through `POST /api/agents/agent/report`, threshold 80/60 and no delay,
+ using synthetic unified-agent identities with commands disabled.
+2. Controlled first HTTP503 with `Retry-After: 0`, then HTTP200; require both
+ recipient observations, active CPU alert, and sent delivery audit. This is
+ transport retry acceptance, not proof that a durable queue retry occurred.
+3. Indefinite HTTP503 until a dead-letter audit appears (600s deadline); retain
+ the exact notification IDs and occurrence-specific incident timeline.
+4. Actual operator-owned restart; require retained incident ID and terminal
+ audit, then low CPU to clear and high CPU for a distinct recurrence.
+5. Global terminal Retry; require the **original terminal notification ID** to
+ gain a sent audit and two distinct delivered occurrence start times. Retain
+ old and current incident timelines separately.
+6. Disable agent alerts; ingest a fresh high-CPU identity for 30s and require
+ no CPU alert or successful alert delivery for that identity.
+7. Re-enable agent alerts, exhaust that identity (another 600s bound), Dismiss
+ terminal failures, require healthy queue status and retention of all prior
+ delivery-audit identities within the 200-entry query window.
+
+Other waits default to 90s, HTTP requests to 10s. Observation errors fail rather
+than being ignored. No queue budgets, retry timings, production thresholds or
+product source are changed. Only the disposable alert *configuration* is set for
+the controlled CPU stimulus. The driver deliberately disables grouping,
+escalation and resolved notifications to isolate these scenarios.
+
+## Interpretation and remaining checks
+
+A zero exit means only the named assertions passed. The result deliberately
+keeps `installed_acceptance_complete: false`. Review all receipt/snapshot files,
+including failures. Do not infer that the entire release is qualified.
+
+Still separate: recurrence timeline side-effect correctness (historical replay
+must not mark the new occurrence delivered), retirement of the visible system
+notification-warning, resolved-message delivery, pending/sending restart windows,
+acknowledgement/snooze/quiet-hours policies, SMTP/email-provider acceptance, UI
+reload and reporter acceptance. The driver does not automate these claims.
+An ordinary generic-webhook recipient is not a real email provider.
+
+## Contract proof
+
+```sh
+python3 -m unittest discover -s tests/qualification/alert-lifecycle -v
+go test ./tests/qualification/alert-lifecycle -run TestExternalDriverWireContract -count=1
+```
+
+Python tests exercise the real loopback recipient's failure/success responses,
+persistent failure, resolved-event exclusion, evidence preservation, URL and
+redirect guards, deadlines and observer errors. The Go test decodes the driver's
+actual report against production host wire types and executes its template
+against production webhook payload types. Neither test launches Pulse.
+
+The target's route/field contracts were traced in:
+`internal/api/agent_ingest.go`, `internal/api/alerting/{alerts,notifications,notification_queue}.go`,
+`internal/api/router_routes_monitoring.go`, `pkg/agents/host/report.go`,
+`internal/alerts/config/types.go`, and
+`internal/notifications/{notifications,webhook_enhanced,delivery_log}.go`.
+Use `git show 2dcf23b9:<path>` when reviewing the installed target; current main
+has newer incident-read implementation and must not stand in for this artifact.
diff --git a/tests/qualification/alert-lifecycle/acceptance.py b/tests/qualification/alert-lifecycle/acceptance.py
new file mode 100644
index 0000000000..3bfa0438a2
--- /dev/null
+++ b/tests/qualification/alert-lifecycle/acceptance.py
@@ -0,0 +1,338 @@
+#!/usr/bin/env python3
+"""External, synthetic-only installed alert probe. No product imports or DB access."""
+import argparse
+import datetime
+import ipaddress
+import json
+import os
+from pathlib import Path
+import subprocess
+import threading
+import time
+import urllib.error
+import urllib.parse
+import urllib.request
+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
+
+SOURCE = "2dcf23b9d75742049f72f7eac21b0bf7266ebf6e"
+DIGEST = "sha256:d7d24aec91da45b901e7b1c4094d508b5f6c708dca114c0f4dbbdfddd86a82b4"
+TEMPLATE = ('{"id":"{{.ID}}","resource":"{{.ResourceName}}",'
+ '"start":"{{.StartTime}}","event":"{{.Event}}"}')
+
+
+class NoRedirect(urllib.request.HTTPRedirectHandler):
+ def redirect_request(self, req, fp, code, msg, headers, newurl):
+ return None
+
+
+def check(condition, message):
+ if not condition:
+ raise AssertionError(message)
+
+
+def loopback_url(url):
+ parsed = urllib.parse.urlsplit(url)
+ check(parsed.scheme == "http" and not parsed.username and not parsed.password
+ and not parsed.query and not parsed.fragment, "plain loopback HTTP URL required")
+ check(ipaddress.ip_address(parsed.hostname).is_loopback, "non-loopback target refused")
+ return url.rstrip("/")
+
+
+def report(name, cpu):
+ return {"agent": {"id": name, "type": "unified", "intervalSeconds": 5,
+ "commandsEnabled": False},
+ "host": {"hostname": name, "platform": "linux", "cpuCount": 1},
+ "metrics": {"cpuUsagePercent": cpu,
+ "memory": {"totalBytes": 1073741824, "usedBytes": 104857600,
+ "freeBytes": 968884224, "usage": 10}},
+ "timestamp": datetime.datetime.now(datetime.timezone.utc).isoformat()}
+
+
+class Evidence:
+ def __init__(self, directory):
+ self.directory = Path(directory)
+ self.directory.mkdir(mode=0o700, parents=True, exist_ok=False)
+ self.lock = threading.Lock()
+ self.counter = 0
+
+ def save(self, label, data):
+ with self.lock:
+ self.counter += 1
+ path = self.directory / ("%04d-%s.json" % (self.counter, label))
+ path.write_text(json.dumps(data, indent=2) + "\n")
+
+
+class Recipient:
+ def __init__(self, evidence):
+ self.evidence = evidence
+ self.lock = threading.Lock()
+ self.failures = 0
+ self.receipts = []
+
+ def mode(self, failures):
+ with self.lock:
+ self.failures = failures # -1 fails indefinitely
+
+ def accept(self, payload):
+ with self.lock:
+ status = 503 if self.failures else 200
+ if self.failures > 0:
+ self.failures -= 1
+ record = {"monotonic": time.monotonic(), "status": status, "payload": payload}
+ self.receipts.append(record)
+ self.evidence.save("recipient", record)
+ return status
+
+ def matching(self, name, status=200):
+ with self.lock:
+ return [r for r in self.receipts if r["status"] == status
+ and r["payload"].get("resource") == name
+ and r["payload"].get("event") == "alert"]
+
+
+def serve(recipient, port):
+ class Handler(BaseHTTPRequestHandler):
+ def log_message(self, *_):
+ pass
+
+ def do_POST(self):
+ if self.path != "/receipt":
+ self.send_error(404)
+ return
+ size = int(self.headers.get("Content-Length", "0"))
+ if not 0 < size <= 65536:
+ self.send_error(413)
+ return
+ try:
+ payload = json.loads(self.rfile.read(size))
+ check(isinstance(payload, dict), "object required")
+ except (ValueError, AssertionError):
+ self.send_error(400)
+ return
+ status = recipient.accept(payload)
+ self.send_response(status)
+ if status == 503:
+ self.send_header("Retry-After", "0")
+ self.end_headers()
+ self.wfile.write(b"controlled recipient\n")
+
+ server = ThreadingHTTPServer(("127.0.0.1", port), Handler)
+ threading.Thread(target=server.serve_forever, daemon=True).start()
+ return server
+
+
+class Driver:
+ def __init__(self, args, evidence, recipient):
+ self.args, self.evidence, self.recipient = args, evidence, recipient
+ self.base = loopback_url(args.base)
+ self.token = os.environ["PULSE_ACCEPTANCE_TOKEN"]
+ self.opener = urllib.request.build_opener(urllib.request.ProxyHandler({}), NoRedirect())
+ self.names = ["acceptance-" + args.run_id + "-" + x for x in ("retry", "terminal", "quiet")]
+ self.results = []
+ self.record_observations = False
+
+ def api(self, path, body=None, method=None):
+ data = None if body is None else json.dumps(body).encode()
+ req = urllib.request.Request(self.base + path, data=data, method=method,
+ headers={"X-API-Token": self.token,
+ "Content-Type": "application/json"})
+ try:
+ with self.opener.open(req, timeout=10) as response:
+ result = json.load(response)
+ except urllib.error.HTTPError as error:
+ # Do not retain error bodies that might echo authentication material.
+ self.evidence.save("http-error", {"path": path, "status": error.code})
+ raise RuntimeError("HTTP %s on %s" % (error.code, path)) from None
+ if self.record_observations and path.startswith((
+ "/api/alerts/active", "/api/alerts/history", "/api/alerts/incidents",
+ "/api/notifications/delivery-log", "/api/notifications/health",
+ "/api/notifications/queue/stats")):
+ self.evidence.save("observation", {"path": path, "response": result})
+ return result
+
+ def snapshot(self, label, alert=None):
+ data = {path: self.api("/api/" + path) for path in
+ ("alerts/active", "alerts/history", "notifications/delivery-log?limit=200",
+ "notifications/health", "notifications/queue/stats")}
+ if alert:
+ query = urllib.parse.urlencode({"alertIdentifier": alert["id"],
+ "started_at": alert["startTime"]})
+ data["incident"] = self.api("/api/alerts/incidents?" + query)
+ self.evidence.save(label, data)
+ return data
+
+ def wait(self, label, predicate, timeout=90, tick=None):
+ deadline = time.monotonic() + timeout
+ while True:
+ if tick:
+ tick()
+ result = predicate()
+ if result:
+ self.results.append(label)
+ self.evidence.save("assertion", {"check": label, "result": "pass"})
+ return result
+ if time.monotonic() >= deadline:
+ raise TimeoutError(label)
+ time.sleep(2)
+
+ def ingest(self, name, cpu):
+ response = self.api("/api/agents/agent/report", report(name, cpu))
+ check(response.get("success") is True, "ingest rejected")
+ check(response.get("serverVersion", "").lstrip("v") == "6.4.4-beta.2",
+ "installed server version mismatch")
+
+ def active(self, name):
+ return next((a for a in (self.api("/api/alerts/active") or [])
+ if a["resourceName"] == name and a["type"] == "cpu"), None)
+
+ def delivery(self, alert, outcome):
+ entries = self.api("/api/notifications/delivery-log?limit=200")["entries"] or []
+ return [e for e in entries if alert["id"] in (e["alertIds"] or [])
+ and e["outcome"] == outcome]
+
+ def run(self):
+ # Operator supplies independent immutable image inspection, not an API version claim.
+ identity = json.loads(Path(self.args.identity).read_text())
+ check(identity["source"] == SOURCE and identity["image_digest"] == DIGEST,
+ "wrong inspected artifact")
+ self.evidence.save("identity-owner-attestation", identity)
+ check(not self.api("/api/notifications/webhooks"), "fixture already has webhooks")
+ check(not self.api("/api/alerts/active"), "fixture already has alerts")
+ check(not self.api("/api/alerts/history"), "fixture already has alert history")
+ check(not self.api("/api/notifications/delivery-log")["entries"], "fixture has deliveries")
+ for channel in ("email", "apprise"):
+ check(not self.api("/api/notifications/" + channel).get("enabled"),
+ "fixture has enabled external destination")
+ self.record_observations = True
+ config = self.api("/api/alerts/config")
+ config.update(enabled=True, activationState="active", disableAllAgents=False,
+ disableAllAgentsOffline=True, flappingEnabled=False,
+ agentDefaults={"cpu": {"trigger": 80, "clear": 60}},
+ timeThresholds={"agent": 0},
+ metricTimeThresholds={"agent": {"cpu": 0}},
+ metricEvaluationWindows={"agent": {"cpu": 0}})
+ config["schedule"] = {"initialNotify": "webhook", "cooldown": 0,
+ "maxAlertsHour": 60, "notifyOnResolve": False,
+ "grouping": {"enabled": False},
+ "quietHours": {"enabled": False},
+ "escalation": {"enabled": False}}
+ self.api("/api/alerts/config", config, "PUT")
+ self.api("/api/notifications/webhooks",
+ {"id": "acceptance-" + self.args.run_id, "name": "Synthetic acceptance",
+ "url": "http://127.0.0.1:%d/receipt" % self.args.port,
+ "enabled": True, "method": "POST", "service": "generic",
+ "template": TEMPLATE})
+ first, terminal, quiet = self.names
+ self.recipient.mode(1)
+ alert = self.wait("firing", lambda: self.active(first),
+ tick=lambda: self.ingest(first, 95))
+ self.wait("ordinary-recipient-after-transient", lambda: self.recipient.matching(first))
+ check(self.recipient.matching(first, 503), "transient failure not observed")
+ self.wait("sent-audit", lambda: self.delivery(alert, "sent"))
+ self.snapshot("firing-transient", alert)
+
+ self.recipient.mode(-1)
+ old = self.wait("terminal-firing", lambda: self.active(terminal),
+ tick=lambda: self.ingest(terminal, 95))
+ terminal_entries = self.wait("exhaustion", lambda: self.delivery(old, "dead_letter"),
+ timeout=600, tick=lambda: self.ingest(terminal, 95))
+ terminal_ids = {entry["notificationId"] for entry in terminal_entries}
+ before = self.snapshot("before-restart", old)
+ # This hook belongs to Delivery and must restart only the disposable server.
+ proc = subprocess.run([self.args.restart_hook], timeout=120, capture_output=True)
+ check(proc.returncode == 0, "restart hook failed (retain owner logs separately)")
+ receipt = json.loads(proc.stdout)
+ check(receipt["before_process"] != receipt["after_process"]
+ and receipt["same_volume"] is True and receipt["image_digest"] == DIGEST,
+ "restart owner receipt does not establish changed process / preserved volume")
+ self.evidence.save("restart-owner-attestation", receipt)
+ # Hook must return only after authenticated readiness; an error is not retried away.
+ after = self.snapshot("after-restart", old)
+ check(after["incident"]["id"] == before["incident"]["id"], "incident changed at restart")
+ check(self.delivery(old, "dead_letter"), "terminal audit lost at restart")
+ self.results.append("restart-preserved-terminal-and-incident")
+
+ self.wait("resolved", lambda: not self.active(terminal),
+ tick=lambda: self.ingest(terminal, 10))
+ current = self.wait("recurrence", lambda: self.active(terminal),
+ tick=lambda: self.ingest(terminal, 95))
+ check(current["startTime"] != old["startTime"], "recurrence reused old start")
+ self.snapshot("recurrence-before-replay", current)
+ self.recipient.mode(0)
+ retry = self.api("/api/notifications/terminal-failures/retry", {})
+ check(retry.get("affected", 0) >= 1, "no terminal retry admitted")
+ self.evidence.save("retry-response", retry)
+ self.wait("historical-retry-sent", lambda: any(
+ entry["notificationId"] in terminal_ids for entry in self.delivery(old, "sent")))
+ self.wait("recurrence-recipient", lambda: len({
+ r["payload"]["start"] for r in self.recipient.matching(terminal)}) >= 2)
+ self.snapshot("old-occurrence-after-replay", old)
+ self.snapshot("current-occurrence-after-replay", current)
+ # Occurrence-side-effect correctness requires review of both retained timelines.
+ config["disableAllAgents"] = True
+ self.api("/api/alerts/config", config, "PUT")
+ deadline = time.monotonic() + 30
+ while time.monotonic() < deadline:
+ self.ingest(quiet, 95)
+ check(not self.active(quiet), "disabled-agent alert fired")
+ check(not self.recipient.matching(quiet), "disabled-agent notification delivered")
+ time.sleep(2)
+ self.results.append("disabled-agent-suppression-30s")
+ config["disableAllAgents"] = False
+ self.api("/api/alerts/config", config, "PUT")
+ self.recipient.mode(-1)
+ dismissed = self.wait("dismissal-firing", lambda: self.active(quiet),
+ tick=lambda: self.ingest(quiet, 95))
+ self.wait("dismissal-exhaustion", lambda: self.delivery(dismissed, "dead_letter"),
+ timeout=600, tick=lambda: self.ingest(quiet, 95))
+ saved = self.snapshot("before-dismiss", dismissed)
+ dismissal = self.api("/api/notifications/terminal-failures/dismiss", {})
+ check(dismissal.get("affected", 0) >= 1, "nothing dismissed")
+ self.evidence.save("dismiss-response", dismissal)
+ self.wait("dismissal-health", lambda: self.api("/api/notifications/health")["overall_healthy"])
+ retained = self.snapshot("after-dismiss", dismissed)
+ def audit_keys(snapshot):
+ return {(e["notificationId"], e["timestamp"], e["outcome"])
+ for e in snapshot["notifications/delivery-log?limit=200"]["entries"]}
+ check(audit_keys(saved) <= audit_keys(retained), "dismissal lost delivery history")
+ self.results.append("dismissal-retains-audit")
+ self.snapshot("final")
+ return {"passed": self.results, "installed_acceptance_complete": False,
+ "requires_review": ["occurrence-specific replay side effects",
+ "system notification-warning retirement",
+ "email/provider acceptance", "reporter acceptance"]}
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--base", required=True)
+ parser.add_argument("--identity", required=True)
+ parser.add_argument("--restart-hook", required=True)
+ parser.add_argument("--evidence", required=True)
+ parser.add_argument("--run-id", required=True)
+ parser.add_argument("--port", type=int, default=18765)
+ parser.add_argument("--disposable-fixture", action="store_true", required=True)
+ args = parser.parse_args()
+ check(args.run_id.isalnum() and len(args.run_id) <= 24, "short alphanumeric run ID required")
+ loopback_url(args.base)
+ os.umask(0o077)
+ evidence = Evidence(args.evidence)
+ recipient = Recipient(evidence)
+ server = serve(recipient, args.port)
+ driver = None
+ try:
+ driver = Driver(args, evidence, recipient)
+ result = driver.run()
+ evidence.save("result", result)
+ except Exception as error:
+ evidence.save("result", {"installed_acceptance_complete": False,
+ "passed": driver.results if driver else [],
+ "failure_type": type(error).__name__})
+ raise
+ finally:
+ server.shutdown()
+ server.server_close()
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tests/qualification/alert-lifecycle/test_acceptance.py b/tests/qualification/alert-lifecycle/test_acceptance.py
new file mode 100644
index 0000000000..1a25e49708
--- /dev/null
+++ b/tests/qualification/alert-lifecycle/test_acceptance.py
@@ -0,0 +1,116 @@
+import argparse
+import json
+import io
+import os
+from pathlib import Path
+import tempfile
+import unittest
+from unittest.mock import patch
+import urllib.error
+import urllib.request
+
+import acceptance as a
+
+
+class AcceptanceContractTests(unittest.TestCase):
+ def setUp(self):
+ self.temp = tempfile.TemporaryDirectory()
+ self.addCleanup(self.temp.cleanup)
+ self.evidence = a.Evidence(Path(self.temp.name) / "proof")
+
+ def test_refuses_remote_or_credential_bearing_targets(self):
+ for url in ("https://127.0.0.1", "http://example.com", "http://10.0.0.1",
+ "http://user:[email protected]", "http://127.0.0.1?token=secret"):
+ with self.subTest(url=url), self.assertRaises((ValueError, AssertionError)):
+ a.loopback_url(url)
+ self.assertEqual(a.loopback_url("http://127.0.0.1:7655/"), "http://127.0.0.1:7655")
+
+ def test_real_http_recipient_transient_then_success_retains_both(self):
+ recipient = a.Recipient(self.evidence)
+ server = a.serve(recipient, 0)
+ self.addCleanup(server.server_close)
+ self.addCleanup(server.shutdown)
+ recipient.mode(1)
+ payload = {"resource": "synthetic", "event": "alert", "start": "old"}
+ request = urllib.request.Request(
+ "http://127.0.0.1:%d/receipt" % server.server_port,
+ data=json.dumps(payload).encode(), headers={"Content-Type": "application/json"})
+ with self.assertRaises(urllib.error.HTTPError) as failed:
+ urllib.request.urlopen(request)
+ self.assertEqual(failed.exception.code, 503)
+ self.assertEqual(failed.exception.headers["Retry-After"], "0")
+ failed.exception.close()
+ with urllib.request.urlopen(request) as response:
+ self.assertEqual(response.status, 200)
+ self.assertEqual(len(recipient.matching("synthetic", 503)), 1)
+ self.assertEqual(len(recipient.matching("synthetic")), 1)
+ self.assertEqual(len(list(self.evidence.directory.glob("*recipient.json"))), 2)
+
+ def test_persistent_failure_does_not_silently_recover(self):
+ recipient = a.Recipient(self.evidence)
+ recipient.mode(-1)
+ for _ in range(25):
+ self.assertEqual(recipient.accept({"resource": "x", "event": "alert"}), 503)
+ self.assertFalse(recipient.matching("x"))
+ recipient.mode(0)
+ self.assertEqual(recipient.accept({"resource": "x", "event": "alert"}), 200)
+
+ def test_resolved_delivery_cannot_satisfy_firing(self):
+ recipient = a.Recipient(self.evidence)
+ recipient.accept({"resource": "x", "event": "resolved"})
+ self.assertFalse(recipient.matching("x"))
+
+ def test_evidence_cannot_overwrite_prior_attempt(self):
+ with self.assertRaises(FileExistsError):
+ a.Evidence(self.evidence.directory)
+
+ def test_report_is_monitoring_only_and_has_real_host_wire_shape(self):
+ payload = a.report("acceptance-test", 95)
+ self.assertEqual(payload["agent"]["type"], "unified")
+ self.assertFalse(payload["agent"]["commandsEnabled"])
+ self.assertEqual(payload["metrics"]["cpuUsagePercent"], 95)
+ self.assertEqual(payload["host"]["hostname"], "acceptance-test")
+ self.assertIn("timestamp", payload)
+
+ def driver(self):
+ args = argparse.Namespace(base="http://127.0.0.1:12345", run_id="test")
+ with patch.dict(os.environ, {"PULSE_ACCEPTANCE_TOKEN": "synthetic-secret"}):
+ return a.Driver(args, self.evidence, a.Recipient(self.evidence))
+
+ def test_deadline_fails_instead_of_passing_empty_observation(self):
+ driver = self.driver()
+ with patch.object(a.time, "monotonic", side_effect=[0, 2]):
+ with self.assertRaises(TimeoutError):
+ driver.wait("never-seen", lambda: False, timeout=1)
+ self.assertFalse(driver.results)
+
+ def test_observer_error_not_treated_as_transient_success(self):
+ driver = self.driver()
+ def broken():
+ raise RuntimeError("observer failed")
+ with self.assertRaises(RuntimeError):
+ driver.wait("broken", broken)
+ self.assertFalse(driver.results)
+
+ def test_no_redirect_token_forwarding(self):
+ handler = a.NoRedirect()
+ self.assertIsNone(handler.redirect_request(None, None, 302, "", {}, "http://remote"))
+
+ def test_retained_observation_excludes_authentication_header(self):
+ driver = self.driver()
+ driver.record_observations = True
+ with patch.object(driver.opener, "open", return_value=io.StringIO('[]')):
+ self.assertEqual(driver.api("/api/alerts/active"), [])
+ saved = next(self.evidence.directory.glob("*observation.json")).read_text()
+ self.assertIn("/api/alerts/active", saved)
+ self.assertNotIn("synthetic-secret", saved)
+ self.assertNotIn("X-API-Token", saved)
+
+ def test_wait_retains_named_success(self):
+ driver = self.driver()
+ self.assertEqual(driver.wait("observed", lambda: {"id": 42}), {"id": 42})
+ self.assertEqual(driver.results, ["observed"])
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/qualification/alert-lifecycle/wire_contract_test.go b/tests/qualification/alert-lifecycle/wire_contract_test.go
new file mode 100644
index 0000000000..6c9a4c8e8c
--- /dev/null
+++ b/tests/qualification/alert-lifecycle/wire_contract_test.go
@@ -0,0 +1,58 @@
+package alertlifecycle
+
+import (
+ "bytes"
+ "encoding/json"
+ "os/exec"
+ "testing"
+ "text/template"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/notifications"
+ agentshost "github.com/rcourtman/pulse-go-rewrite/pkg/agents/host"
+)
+
+// This proves driver fixtures against production wire types, not installed delivery.
+func TestExternalDriverWireContract(t *testing.T) {
+ cmd := exec.Command("python3", "-c", "import acceptance,json; print(json.dumps({'report':acceptance.report('acceptance-contract',95),'template':acceptance.TEMPLATE}))")
+ output, err := cmd.Output()
+ if err != nil {
+ t.Fatal(err)
+ }
+ var fixture struct {
+ Report json.RawMessage
+ Template string
+ }
+ if err := json.Unmarshal(output, &fixture); err != nil {
+ t.Fatal(err)
+ }
+ var report agentshost.Report
+ decoder := json.NewDecoder(bytes.NewReader(fixture.Report))
+ decoder.DisallowUnknownFields()
+ if err := decoder.Decode(&report); err != nil {
+ t.Fatal(err)
+ }
+ if report.Agent.ID != "acceptance-contract" || report.Agent.CommandsEnabled ||
+ report.Host.Hostname != report.Agent.ID || report.Metrics.CPUUsagePercent != 95 ||
+ report.Timestamp.IsZero() {
+ t.Fatalf("driver report lost required monitoring identity/metrics: %+v", report)
+ }
+ tmpl, err := template.New("receipt").Option("missingkey=error").Parse(fixture.Template)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var body bytes.Buffer
+ if err := tmpl.Execute(&body, notifications.WebhookPayloadData{
+ ID: "agent-cpu", ResourceName: report.Host.Hostname,
+ StartTime: "2026-09-10T14:30:00Z", Event: "alert",
+ }); err != nil {
+ t.Fatal(err)
+ }
+ var receipt map[string]string
+ if err := json.Unmarshal(body.Bytes(), &receipt); err != nil {
+ t.Fatal(err)
+ }
+ if receipt["id"] != "agent-cpu" || receipt["resource"] != report.Host.Hostname ||
+ receipt["start"] != "2026-09-10T14:30:00Z" || receipt["event"] != "alert" {
+ t.Fatalf("invalid receipt: %v", receipt)
+ }
+}