Require recent guest polls in the Proxmox memory watch

A complete startup roster and another dashboard message can outlive PVE polling. Bind fresh guest sightings to the end of RSS sampling and retain the observed counts without changing the RSS gate or PBS group coverage.

Change-source: pulse-maintainer
This commit is contained in:
pulse-triage[bot]
2026-11-22 03:10:57 +00:00
parent e1f7327c2a
commit 72dc4f1f0d
6 changed files with 126 additions and 21 deletions

View File

@@ -233,7 +233,10 @@ a real, non-mock Pulse polling a synthetic 3-node Proxmox VE cluster (35 guests)
dashboard WebSocket (`scripts/memory/proxmox_load.py`). Neither mock mode nor
the agent estate exercises PVE/PBS polling, `recovery.db` ingestion, protection
posture refreshes, or PBS backup cloning. It requires node registration,
PVE/PBS polling, and dashboard state updates with all expected PVE guests. It
PVE/PBS polling, and dashboard state updates with all expected PVE guests. Each
guest must have a poll sighting within 60 seconds of the end of RSS sampling;
a roster retained since startup or an unrelated dashboard update is not enough.
This checks collection near the end, not uninterrupted polling. It
also requires a completed, nonempty snapshot response for each configured PBS
backup group on each datastore; registration, status requests and repeat reads
of one group cannot stand in for snapshot traffic. The per-build

View File

@@ -146,6 +146,8 @@ run_tree() {
local pid=$!
local driver=""
local driver_log=""
local start now rss rss_hwm
start=$(date +%s)
if [[ "${ESTATE}" == agents ]]; then
# The sampling loop ends the driver with SIGTERM. A driver deadline equal
# to the sampling window can expire as that signal arrives, and Python then
@@ -157,12 +159,11 @@ run_tree() {
elif [[ "${ESTATE}" == proxmox ]]; then
driver_log="${OUT_DIR}/proxmox-${label}.log"
python3 "${SCRIPT_DIR}/proxmox_load.py" --port "${port}" --duration "$((DURATION + 120))" \
--sample-until "$((start + DURATION))" \
--stats "${OUT_DIR}/proxmox-${label}.json" > "${driver_log}" 2>&1 &
driver=$!
fi
printf 'elapsed_s\trss_kib\tgo_heap_kib\tgo_other_kib\tanon_other_kib\tfile_kib\tcpu_ticks\twrite_bytes\twchar_bytes\trss_hwm_kib\n' > "${samples}"
local start now rss rss_hwm
start=$(date +%s)
while kill -0 "${pid}" 2>/dev/null; do
now=$(( $(date +%s) - start ))
(( now >= DURATION )) && break

View File

@@ -17,7 +17,8 @@ and authentication configured:
It runs until --duration elapses or SIGTERM arrives, then writes a JSON stats
file. It exits 1 when registration failed, PVE or PBS polling did not occur,
the fixture did not serve snapshots for every configured PBS group, or the
dashboard did not receive state updates and the full synthetic PVE inventory.
dashboard lacked the full synthetic PVE inventory with recent poll sightings
at the end of sampling.
"""
from __future__ import annotations
@@ -40,10 +41,27 @@ import urllib.parse
import urllib.request
from collections import Counter
from dataclasses import dataclass, field
from datetime import datetime
STOP = threading.Event()
DASHBOARD_SOCKETS: set[socket.socket] = set()
DASHBOARD_LOCK = threading.Lock()
# The default PVE poll interval is 10 seconds. Allow several cycles of
# scheduling and delivery slack without accepting the startup roster for RSS
# measured after collection has stopped.
GUEST_FRESHNESS_SECONDS = 60
def guest_seen_at(value: object) -> float | None:
if not isinstance(value, str):
return None
if value.endswith("Z"):
value = value[:-1] + "+00:00"
try:
when = datetime.fromisoformat(value)
return when.timestamp() if when.tzinfo is not None else None
except (ValueError, OverflowError, OSError):
return None
class ThreadedHTTPServer(socketserver.ThreadingMixIn, http.server.HTTPServer):
@@ -62,13 +80,15 @@ class DashboardStats:
ws_state_updates: int = 0
ws_state_bytes: int = 0
ws_errors: list[str] = field(default_factory=list)
resource_identities: dict[str, tuple[str | None, str | None]] = field(default_factory=dict)
resources: dict[str, tuple[str | None, str | None, float | None]] = field(default_factory=dict)
def update_guests(self, data: dict) -> None:
# Keep just the identity fields. Existing resource upserts are merge
# patches, so a metrics-only update must not erase a guest's identity.
# Existing resource upserts are merge patches. A metrics-only update
# neither erases identity nor proves a new guest poll. In this
# PVE-only guest estate lastSeen is the collector's sighting, not
# updatedAt, the frame time, or a new registration.
if "resources" in data:
self.resource_identities.clear()
self.resources.clear()
rows = data["resources"]
else:
delta = data.get("resourceDelta")
@@ -76,28 +96,38 @@ class DashboardStats:
return
removed = delta.get("removed", [])
if not isinstance(removed, list) or not all(isinstance(key, str) for key in removed):
self.resource_identities.clear()
self.resources.clear()
return
for resource_id in removed:
self.resource_identities.pop(resource_id, None)
self.resources.pop(resource_id, None)
rows = delta.get("upserts", [])
if not isinstance(rows, list):
self.resource_identities.clear()
self.resources.clear()
return
for row in rows:
if not isinstance(row, dict) or not isinstance(row.get("id"), str) or not row["id"]:
continue
resource_id = row["id"]
technology, name = self.resource_identities.get(resource_id, (None, None))
technology = row.get("technology", technology)
name = row.get("name", name)
self.resource_identities[resource_id] = (
old_technology, old_name, last_seen = self.resources.get(resource_id, (None, None, None))
technology = row.get("technology", old_technology)
name = row.get("name", old_name)
if "lastSeen" in row or (technology, name) != (old_technology, old_name):
last_seen = guest_seen_at(row.get("lastSeen"))
self.resources[resource_id] = (
technology if isinstance(technology, str) else None,
name if isinstance(name, str) else None,
last_seen,
)
def missing_guests(self) -> set[tuple[str, str]]:
return self.expected_guests.difference(self.resource_identities.values())
return self.expected_guests.difference((tech, name) for tech, name, _ in self.resources.values())
def missing_recent_guests(self, started: float, finished: float) -> set[tuple[str, str]]:
earliest = max(started, finished - GUEST_FRESHNESS_SECONDS)
return self.expected_guests.difference(
(tech, name) for tech, name, seen in self.resources.values()
if seen is not None and earliest <= seen <= finished
)
@dataclass
@@ -568,7 +598,7 @@ def record_ws_message(opcode: int, payload: bytes, stats: DashboardStats, has_in
if message.get("type") == "stateTooLarge":
# Pulse invalidates the delta baseline when it withholds a state.
with stats.lock:
stats.resource_identities.clear()
stats.resources.clear()
return False
data = message.get("data")
if not isinstance(data, dict) or not data:
@@ -577,7 +607,7 @@ def record_ws_message(opcode: int, payload: bytes, stats: DashboardStats, has_in
if message.get("type") == "initialState":
stats.ws_initial_states += 1
has_initial_state = True
stats.resource_identities.clear()
stats.resources.clear()
elif message.get("type") == "rawData" and has_initial_state:
stats.ws_state_updates += 1
else:
@@ -610,7 +640,7 @@ def run_dashboard(host: str, port: int, deadline: float, stats: DashboardStats)
raise ConnectionError(response.split(b"\r\n", 1)[0].decode(errors="replace"))
with stats.lock:
stats.ws_connects += 1
stats.resource_identities.clear()
stats.resources.clear()
has_initial_state = False
message_opcode = None
fragments = bytearray()
@@ -686,6 +716,7 @@ def main(argv: list[str]) -> int:
parser.add_argument("--pbs-instances", type=int, default=2)
parser.add_argument("--snapshots-per-group", type=int, default=50)
parser.add_argument("--duration", type=float, required=True, help="seconds to drive load")
parser.add_argument("--sample-until", type=int, required=True, help="planned end of RSS sampling (Unix seconds)")
parser.add_argument("--stats", required=True, help="path of the JSON stats file to write")
args = parser.parse_args(argv)
@@ -767,6 +798,7 @@ def main(argv: list[str]) -> int:
while not STOP.is_set() and time.time() < deadline:
STOP.wait(1)
finished = time.time()
STOP.set()
with DASHBOARD_LOCK:
@@ -791,6 +823,7 @@ def main(argv: list[str]) -> int:
pve_requests = req_counts.get("pve_requests", 0)
with dash_stats.lock:
missing_pve_guests = dash_stats.missing_guests()
missing_recent_guests = dash_stats.missing_recent_guests(started, finished)
result = {
"pve_nodes": args.nodes,
@@ -799,7 +832,10 @@ def main(argv: list[str]) -> int:
"pbs_instances": args.pbs_instances,
"snapshots_per_group": args.snapshots_per_group,
"total_pbs_snapshots": total_pbs_snapshots,
"elapsed_s": round(time.time() - started, 1),
"elapsed_s": round(finished - started, 1),
"sampling_end_reached": finished >= args.sample_until,
"pve_guests_recent": len(guest_refs) - len(missing_recent_guests),
"pve_guest_freshness_window_s": GUEST_FRESHNESS_SECONDS,
"registrations": reg_results,
"requests": req_counts,
"pve_requests": pve_requests,
@@ -820,6 +856,9 @@ def main(argv: list[str]) -> int:
json.dump(result, handle, indent=2)
handle.write("\n")
if not result["sampling_end_reached"]:
print("proxmox load ended before the planned end of RSS sampling", file=sys.stderr)
return 1
if reg_failed:
print(f"proxmox load registration failed: {reg_results}", file=sys.stderr)
return 1
@@ -844,6 +883,15 @@ def main(argv: list[str]) -> int:
file=sys.stderr,
)
return 1
if missing_recent_guests:
print(
f"proxmox load dashboard had recent poll sightings for "
f"{result['pve_guests_recent']}/{len(guest_refs)} PVE guests within the last "
f"{GUEST_FRESHNESS_SECONDS}s: missing recent sightings for "
f"{', '.join(f'{kind}/{name}' for kind, name in sorted(missing_recent_guests))}",
file=sys.stderr,
)
return 1
return 0

View File

@@ -157,6 +157,9 @@ def proxmox_lines(baseline: dict | None, candidate: dict | None) -> list[str]:
rows = (
("PVE API requests", lambda d: d["pve_requests"]),
("PVE guests observed in dashboard state", lambda d: d.get("pve_guests_observed", "n/a")),
("PVE guests with recent poll sightings at measurement end",
lambda d: (f"{d['pve_guests_recent']}/{d['guests']} (last {d['pve_guest_freshness_window_s']} s)"
if "pve_guests_recent" in d else "n/a")),
("PBS API requests", lambda d: d["pbs_requests"]),
("PBS snapshot groups served/configured", pbs_snapshot_coverage),
("Dashboard connections", lambda d: d["dashboard"]["connects"]),

View File

@@ -2,6 +2,7 @@
"""Exercise PVE guest and PBS snapshot coverage in the memory watch."""
from collections import Counter
from datetime import datetime, timezone
import json
from pathlib import Path
import sys
@@ -136,6 +137,53 @@ class ProxmoxMemoryLoadTests(unittest.TestCase):
self.frame("initialState", resources=rows[:1])
self.assertEqual(self.stats.missing_guests(), {("lxc", "ct-101")})
def test_a_retained_roster_or_unrelated_update_does_not_prove_late_collection(self):
old = "2026-11-21T00:00:30Z"
end = datetime(2026, 11, 21, 0, 5, tzinfo=timezone.utc).timestamp()
self.frame("initialState", resources=[
{"id": "a", "technology": "qemu", "name": "vm-100", "lastSeen": old},
{"id": "b", "technology": "lxc", "name": "ct-101", "lastSeen": old},
])
self.frame("rawData", resourceDelta={"upserts": [
{"id": "a", "lastSeen": "2026-11-21T00:04:00.999999999Z"},
{"id": "b", "updatedAt": "2026-11-21T00:04:55Z"},
]})
self.assertFalse(self.stats.missing_guests())
self.assertEqual(self.stats.missing_recent_guests(end - 300, end), {("lxc", "ct-101")})
self.frame("rawData", resourceDelta={"upserts": [
{"id": "b", "lastSeen": "2026-11-21T01:04:58+01:00"},
]})
self.assertFalse(self.stats.missing_recent_guests(end - 300, end))
def test_missing_or_invalid_times_and_previous_run_do_not_prove_a_poll(self):
end = datetime(2026, 11, 21, 0, 5, tzinfo=timezone.utc).timestamp()
for timestamp in ("2026-11-21T00:04:00Z", "2026-11-21T00:05:01Z",
"2026-11-21T00:04:59", "not a date", None):
with self.subTest(timestamp=timestamp):
self.frame("initialState", resources=[
{"id": "a", "technology": "qemu", "name": "vm-100", "lastSeen": timestamp},
{"id": "b", "technology": "lxc", "name": "ct-101"},
])
self.assertFalse(self.stats.missing_guests())
self.assertEqual(self.stats.missing_recent_guests(end - 30, end), self.expected)
def test_recent_sighting_stays_bound_to_the_guest_and_current_inventory(self):
end = datetime(2026, 11, 21, 0, 5, tzinfo=timezone.utc).timestamp()
self.frame("initialState", resources=[
{"id": "a", "technology": "qemu", "name": "vm-100", "lastSeen": "2026-11-21T00:04:51Z"},
{"id": "b", "technology": "lxc", "name": "ct-101", "lastSeen": "2026-11-21T00:04:52Z"},
])
self.frame("rawData", resourceDelta={"upserts": [{"id": "a", "cpu": {"current": 0.3}}]})
self.assertFalse(self.stats.missing_recent_guests(end - 300, end))
self.frame("rawData", resourceDelta={"upserts": [
{"id": "c", "technology": "qemu", "name": "vm-100"},
], "removed": ["a"]})
self.assertEqual(self.stats.missing_recent_guests(end - 300, end), {("qemu", "vm-100")})
self.frame("rawData", resourceDelta={"upserts": [
{"id": "b", "technology": "qemu", "name": "vm-100"},
]})
self.assertEqual(self.stats.missing_recent_guests(end - 300, end), self.expected)
if __name__ == "__main__":
unittest.main()

View File

@@ -97,7 +97,8 @@ class ReleaseMemorySummaryTests(unittest.TestCase):
"snapshots_per_group": 50, "pve_requests": 914, "pbs_requests": 210,
"dashboard": {"connects": 1, "messages": 60, "bytes": 1024},
}
candidate = dict(legacy, pve_guests_observed=35, pbs_snapshot_group_coverage={
candidate = dict(legacy, pve_guests_observed=35,
pve_guests_recent=34, pve_guest_freshness_window_s=60, pbs_snapshot_group_coverage={
"pbs1": {"store-fast": {"served_groups": 35, "expected_groups": 35},
"store-archive": {"served_groups": 17, "expected_groups": 17}},
"pbs2": {"store-fast": {"served_groups": 35, "expected_groups": 35},
@@ -105,6 +106,7 @@ class ReleaseMemorySummaryTests(unittest.TestCase):
})
lines = "\n".join(summary.proxmox_lines(legacy, candidate))
self.assertIn("| PVE guests observed in dashboard state | n/a | 35 |", lines)
self.assertIn("| PVE guests with recent poll sightings at measurement end | n/a | 34/35 (last 60 s) |", lines)
self.assertIn("| PBS API requests | 210 | 210 |", lines)
self.assertIn("| PBS snapshot groups served/configured | n/a | 92/104 |", lines)
self.assertIn("not snapshots Pulse retained or displayed", lines)