111 lines
5.5 KiB
Python
111 lines
5.5 KiB
Python
#!/usr/bin/env python3
|
|
"""Repeat B idle and review using direct LAN PerfMon; preserve prior evidence."""
|
|
import csv
|
|
import datetime as dt
|
|
import hashlib
|
|
import json
|
|
import os
|
|
import statistics
|
|
import subprocess
|
|
import sys
|
|
import urllib.parse
|
|
import urllib.request
|
|
from pathlib import Path
|
|
|
|
import perfmon
|
|
import shelly
|
|
from tls import application_context
|
|
|
|
HERE = Path(__file__).resolve().parent
|
|
ROOT = HERE.parents[1]
|
|
PREVIOUS = HERE / "results/loaded-b-corrected-usb-off-26-4h-20261022-run1/run.json"
|
|
PRIVATE = HERE / ".private/fresh-20261021"
|
|
HOST = "192.168.1.125"
|
|
CA = PRIVATE / "healthapp-ca.crt"
|
|
USERS = PRIVATE / "dataset/users.csv"
|
|
previous = json.loads(PREVIOUS.read_text())
|
|
plan_sha = hashlib.sha256((HERE / "plans/review.jmx").read_bytes()).hexdigest()
|
|
if plan_sha != previous["plan_sha256"]:
|
|
raise SystemExit("Review plan does not match previous B plan; no run started")
|
|
if previous["distinct_accounts"] != 1:
|
|
raise SystemExit("Previous B measurement did not use the expected single account")
|
|
period_from, period_to = previous["period_from"], previous["period_to"]
|
|
with USERS.open(newline="") as file:
|
|
users = list(csv.DictReader(file))
|
|
if len(users) != 1:
|
|
raise SystemExit("Expected one previously prepared synthetic patient; no run started")
|
|
|
|
print("Preflight: connecting directly to test PC PerfMon 192.168.1.125:4444", flush=True)
|
|
perfmon.check_agent(HOST, 4444)
|
|
shelly.check_plug("192.168.1.44", 80, 0)
|
|
context = application_context(cafile=str(CA))
|
|
|
|
|
|
def api(path, token=None, body=None):
|
|
headers = {"Content-Type": "application/json"}
|
|
if token:
|
|
headers["Authorization"] = "Bearer " + token
|
|
request = urllib.request.Request(
|
|
f"https://{HOST}:5443" + path, headers=headers,
|
|
data=json.dumps(body).encode() if body is not None else None,
|
|
)
|
|
with urllib.request.urlopen(request, context=context, timeout=30) as response:
|
|
return json.load(response)
|
|
|
|
|
|
user = users[0]
|
|
login = api("/api/authentication/login", body={"accountId": user["account_id"], "password": user["password"]})
|
|
token = login["accessToken"]
|
|
patient = api("/api/patients/me", token=token)
|
|
if patient["patientId"] != user["patient_id"]:
|
|
raise SystemExit("Prepared account does not match test patient; no run started")
|
|
query = urllib.parse.urlencode({"from": period_from, "to": period_to})
|
|
path = f"/api/patients/{user['patient_id']}/observations?{query}"
|
|
history = api(path, token=token)
|
|
selected = api(path + "&setting=Home&activityCondition=AtRest", token=token)
|
|
if len(history) != 60 or len(selected) != 42:
|
|
raise SystemExit(f"Dataset differs from prepared 60 readings / 42 home-rest readings: {len(history)} / {len(selected)}; no run started")
|
|
print("Direct PerfMon, Shelly, HTTPS and prepared patient dataset preflight passed.", flush=True)
|
|
print("The direct connection must remain available; failed monitoring invalidates the run.", flush=True)
|
|
|
|
timestamp = dt.datetime.now(dt.timezone.utc).strftime("%Y%m%dT%H%M%SZ")
|
|
control = HERE / "results" / ("direct-b-" + timestamp)
|
|
control.mkdir(mode=0o700, parents=True, exist_ok=False)
|
|
metadata = {
|
|
"started_utc": dt.datetime.now(dt.timezone.utc).isoformat(),
|
|
"monitoring": "direct TCP 192.168.1.125:4444; no SSH forwarding",
|
|
"plan_sha256": plan_sha,
|
|
"period_from": period_from, "period_to": period_to,
|
|
"patient_observations": len(history), "home_at_rest_observations": len(selected),
|
|
"previous_run": str(PREVIOUS),
|
|
"note": "Dataset counts were checked; exact input values, monitoring overhead, USB state and machine configuration require separate verification.",
|
|
}
|
|
(control / "experiment.json").write_text(json.dumps(metadata, indent=2) + "\n")
|
|
base = [sys.executable, "-u", str(HERE / "run.py"), "--host", HOST,
|
|
"--perfmon-host", HOST, "--perfmon-port", "4444", "--shelly-host", "192.168.1.44",
|
|
"--warmup", "1800", "--duration", "14400", "--perfmon-interval-ms", "1000",
|
|
"--shelly-interval-ms", "1000", "--period-from", period_from, "--period-to", period_to]
|
|
for scenario in ("idle", "review"):
|
|
output = control / scenario
|
|
args = [*base, scenario, "--output", str(output)]
|
|
if scenario == "idle":
|
|
args += ["--ramp", "0"]
|
|
else:
|
|
args += ["--ramp", "60", "--users", "26", "--users-file", str(USERS), "--ca", str(CA),
|
|
"--allow-shared-read-account", "--capacity-trial", "--think-min-ms", "500",
|
|
"--think-mean-ms", "1000", "--think-stddev-ms", "250", "--session-pause-ms", "0",
|
|
"--session-stddev-ms", "0", "--seed", "42"]
|
|
print(f"Starting {scenario}: 30-minute warmup and four-hour measurement; output {output}", flush=True)
|
|
result = subprocess.run(args, cwd=ROOT, env=dict(os.environ, MPLCONFIGDIR="/tmp/healthapp-b-direct-matplotlib"))
|
|
if result.returncode:
|
|
raise SystemExit(f"{scenario} failed with exit code {result.returncode}; retained evidence in {control}")
|
|
run = json.loads((output / "run.json").read_text())
|
|
if scenario == "review":
|
|
with (output / "measured.csv").open(newline="") as file:
|
|
samples = list(csv.DictReader(file))
|
|
mean = statistics.mean(int(row["elapsed"]) for row in samples)
|
|
if run["measured_failed_http_samples"] != 0 or mean >= 200:
|
|
raise SystemExit(f"Review did not meet criteria: mean={mean:.3f} ms, failures={run['measured_failed_http_samples']}; retained evidence in {control}")
|
|
print(f"Review criteria passed: mean {mean:.3f} ms, zero HTTP failures.", flush=True)
|
|
print(f"Both direct-monitoring runs complete; evidence: {control}", flush=True)
|