perf: measure grpc fanout and recovery bounds
This commit is contained in:
@@ -0,0 +1,571 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Measured, bounded workloads against an already deployed run-owned LocalRig.
|
||||
|
||||
No capacity claim is inferred from profile input. Cardinalities come from actual
|
||||
acknowledgements, rates from elapsed monotonic time and fixture counters, and
|
||||
memory from the operating system/runtime. Missing accounting stays unavailable.
|
||||
"""
|
||||
import argparse
|
||||
from contextlib import contextmanager
|
||||
import hashlib
|
||||
import importlib.util
|
||||
import json
|
||||
import math
|
||||
from pathlib import Path
|
||||
import platform
|
||||
import threading
|
||||
import time
|
||||
|
||||
import rig
|
||||
from scenarios import ScenarioError, ScenarioRunner, restricted_json, fixture_browse_root
|
||||
|
||||
|
||||
class WorkloadError(RuntimeError):
|
||||
pass
|
||||
|
||||
|
||||
def adversarial_preflight(path):
|
||||
"""Required deterministic evidence is reconciled before any timing starts."""
|
||||
spec = importlib.util.spec_from_file_location('p11_adversarial_gate', Path(__file__).with_name('run-p11-adversarial.py'))
|
||||
gate = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(gate)
|
||||
try:
|
||||
return gate.checked_packet(path)
|
||||
except (gate.AdversarialError, OSError, ValueError, KeyError) as error:
|
||||
raise WorkloadError('passing current-candidate P11 adversarial packet required before measurement') from error
|
||||
|
||||
|
||||
def sharing_expectation(profile, observations):
|
||||
"""Count actual admitted source/view cohorts using the probe's exact indexing.
|
||||
|
||||
All selected clients use one principal, Cluster/Primary target and one cadence.
|
||||
Raw and UNS have distinct export proofs, so registry cohorts remain separate;
|
||||
physical references are deduplicated by driver/source across those proofs.
|
||||
The observed demand owner excludes legacy poll-group references. The seeded
|
||||
driver already has all seven legacy sources at200ms; their union stays seven.
|
||||
The real-host legacy merge is a separate mandatory adversarial selector.
|
||||
"""
|
||||
views = [(source, realm) for source in profile['sources'] for realm in ('Raw', 'Uns')[:profile['views_per_source']]]
|
||||
cohorts = set(); sources = set(); logical = 0
|
||||
for client in observations['clients']:
|
||||
if client.get('rejectedBeforeStream') is True:
|
||||
continue
|
||||
items = {item['id']: item for item in client['items']}
|
||||
for index in range(profile['registrations_per_client']):
|
||||
slot = index if profile['overlap'] else client['client'] * profile['registrations_per_client'] + index
|
||||
expected = views[slot % len(views)]
|
||||
item = items.get('r' + str(index), {})
|
||||
if (item.get('sourceId'), item.get('realm')) != expected:
|
||||
raise WorkloadError('observed source/view registration does not match sharing experiment')
|
||||
logical += 1; sources.add(expected[0]); cohorts.add(expected)
|
||||
if not logical or logical != sum(client.get('acknowledged', 0) for client in observations['clients']):
|
||||
raise WorkloadError('sharing expectation requires actual acknowledged registrations')
|
||||
return {'logical_interests': logical, 'registry_interests': logical, 'sharing_groups': len(cohorts),
|
||||
'physical_references': len(sources), 'driver_count': 1,
|
||||
'source_ids': sorted(sources), 'source_export_cohorts': sorted(cohorts),
|
||||
'principal': 'fixture-consumer', 'target': 'Cluster:SOURCE:Primary',
|
||||
'sampling_ms': profile['sampling_ms'], 'publishing_ms': profile['publishing_ms'], 'deadband': profile['deadband'],
|
||||
'legacy_scope': {'included_in_observed_demand_owner': False, 'seeded_legacy_unique_references': 7,
|
||||
'seeded_legacy_sampling_ms': 200, 'expected_legacy_grpc_reference_union': 7,
|
||||
'merge_evidence_obligation': 'legacy-physical-sharing'}}
|
||||
|
||||
|
||||
_FIELDS = {"id", "group", "sources", "clients", "registrations_per_client", "views_per_source", "duration_seconds",
|
||||
"sampling_ms", "publishing_ms", "source_hz", "deadband", "slow_clients", "slow_client_ms", "browse_burst",
|
||||
"browse_workers", "overlap", "hub_partitions", "compact_batches", "recovery_preflight", "admission_limit"}
|
||||
_SOURCES = {"scalar", "counter", "array0", "array1", "array2", "vector", "text"}
|
||||
# The seed's deployed 200 ms poll group keeps one acknowledged physical reservation.
|
||||
_RESIDENT_ORIGIN_DRIVERS = ("source-modbus",)
|
||||
|
||||
|
||||
def finite(value, low, high):
|
||||
return type(value) in (int, float) and math.isfinite(value) and low <= value <= high
|
||||
|
||||
|
||||
def validate_profiles(document):
|
||||
if not isinstance(document, dict) or document.get("schema_version") != 1:
|
||||
raise WorkloadError("unsupported workload schema")
|
||||
profiles = document.get("profiles")
|
||||
if not isinstance(profiles, list) or not 1 <= len(profiles) <= 64:
|
||||
raise WorkloadError("bounded nonempty profiles required")
|
||||
seen = set()
|
||||
for profile in profiles:
|
||||
if not isinstance(profile, dict) or set(profile) - _FIELDS or _FIELDS - {"recovery_preflight", "admission_limit"} - set(profile):
|
||||
raise WorkloadError("unknown or missing profile field")
|
||||
identity = profile["id"]
|
||||
if not isinstance(identity, str) or not rig._RUN_PATTERN.fullmatch(identity) or identity in seen:
|
||||
raise WorkloadError("safe unique profile id required")
|
||||
seen.add(identity)
|
||||
if profile["group"] not in {"smoke", "steady", "fan-out", "recovery"}:
|
||||
raise WorkloadError("unknown workload group")
|
||||
sources = profile["sources"]
|
||||
if (not isinstance(sources, list) or not sources or any(not isinstance(source, str) or source not in _SOURCES for source in sources)
|
||||
or len(set(sources)) != len(sources)):
|
||||
raise WorkloadError("profile requires known actual fixture sources")
|
||||
for name, low, high in (("clients", 1, 64), ("registrations_per_client", 1, 256), ("views_per_source", 1, 2),
|
||||
("duration_seconds", 2, 90), ("sampling_ms", 0, 10000), ("publishing_ms", 0, 10000),
|
||||
("slow_clients", 0, 64), ("slow_client_ms", 0, 5000), ("browse_burst", 0, 1024), ("browse_workers", 1, 32),
|
||||
("hub_partitions", 1, 16)):
|
||||
if type(profile[name]) is not int or not low <= profile[name] <= high:
|
||||
raise WorkloadError("profile integer outside bounded experiment range")
|
||||
if (profile["clients"] * profile["registrations_per_client"] > 4096
|
||||
or profile["slow_clients"] > profile["clients"] or not finite(profile["source_hz"], .1, 20)
|
||||
or type(profile["overlap"]) is not bool or type(profile["compact_batches"]) is not bool
|
||||
or type(profile.get("recovery_preflight", False)) is not bool
|
||||
or profile["registrations_per_client"] * (1 if profile["overlap"] else profile["clients"]) < len(sources) * profile["views_per_source"]
|
||||
or (not profile["overlap"] and profile["clients"] * profile["registrations_per_client"] > len(sources) * profile["views_per_source"])
|
||||
or (profile["deadband"] is not None and not finite(profile["deadband"], 0, 65535))):
|
||||
raise WorkloadError("invalid workload dimensions")
|
||||
if "admission_limit" in profile and (type(profile["admission_limit"]) is not int or not 1 <= profile["admission_limit"] < profile["clients"]):
|
||||
raise WorkloadError("admission experiment must exceed its independent configured stream bound")
|
||||
accounting = document.get("accounting", {})
|
||||
if (set(accounting) != {"settle_seconds", "consecutive_drained_observations", "sample_interval_seconds"}
|
||||
or not finite(accounting["settle_seconds"], 1, 120)
|
||||
or type(accounting["consecutive_drained_observations"]) is not int
|
||||
or not 2 <= accounting["consecutive_drained_observations"] <= 10
|
||||
or not finite(accounting["sample_interval_seconds"], .1, 5)):
|
||||
raise WorkloadError("explicit bounded physical-drain accounting required")
|
||||
comparisons = document.get("comparisons", [])
|
||||
if not isinstance(comparisons, list) or len(comparisons) > 32:
|
||||
raise WorkloadError("bounded controlled comparisons required")
|
||||
by_id = {profile["id"]: profile for profile in profiles}
|
||||
comparison_ids = set()
|
||||
for comparison in comparisons:
|
||||
if (not isinstance(comparison, dict) or set(comparison) != {"id", "baseline", "variant", "dimension"}
|
||||
or not isinstance(comparison["id"], str) or not rig._RUN_PATTERN.fullmatch(comparison["id"])
|
||||
or comparison["id"] in comparison_ids or comparison["baseline"] not in by_id or comparison["variant"] not in by_id
|
||||
or comparison["dimension"] not in {"hub_partitions", "compact_batches"}):
|
||||
raise WorkloadError("invalid controlled comparison")
|
||||
comparison_ids.add(comparison["id"])
|
||||
left, right = by_id[comparison["baseline"]], by_id[comparison["variant"]]
|
||||
if {key for key in left.keys() | right.keys() if left.get(key) != right.get(key)} != {"id", comparison["dimension"]}:
|
||||
raise WorkloadError("comparison must change exactly one measured dimension")
|
||||
return document
|
||||
|
||||
|
||||
def probe_options(profile, origin_paths):
|
||||
sources = []
|
||||
for name in profile["sources"]:
|
||||
sources.append({"id": name, "rawPath": origin_paths["raw"].rsplit("/", 1)[0] + "/" + name,
|
||||
"unsPath": origin_paths["uns"].rsplit("/", 1)[0] + "/" + name,
|
||||
"expectedKind": {"vector": "Array", "text": "String"}.get(name, "UInt16"), "expectedRank": 1 if name == "vector" else -1,
|
||||
"requireChanges": name in {"scalar", "counter", "vector", "text"}})
|
||||
return {"profileId": profile["id"], "sources": sources, "clients": profile["clients"],
|
||||
"registrationsPerClient": profile["registrations_per_client"], "viewsPerSource": profile["views_per_source"],
|
||||
"durationSeconds": profile["duration_seconds"], "samplingMilliseconds": profile["sampling_ms"],
|
||||
"publishingMilliseconds": profile["publishing_ms"], "deadband": profile["deadband"],
|
||||
"slowClientCount": profile["slow_clients"], "slowClientMilliseconds": profile["slow_client_ms"],
|
||||
"browseBurst": profile["browse_burst"], "browseWorkers": profile["browse_workers"], "overlap": profile["overlap"],
|
||||
"requireAllAdmitted": "admission_limit" not in profile,
|
||||
"hubPartitions": profile["hub_partitions"], "compactBatches": profile["compact_batches"]}
|
||||
|
||||
|
||||
def connections_drained(rows):
|
||||
"""Null/missing activity counters cannot prove retirement."""
|
||||
return isinstance(rows, list) and bool(rows) and all(isinstance(row, dict) and all(
|
||||
type(row.get(field)) is int and row[field] == 0 for field in ("activeStreams", "activeCalls", "registrationCount")) for row in rows)
|
||||
|
||||
|
||||
def origin_drained(observation):
|
||||
origin = observation.get("originAccounting") if isinstance(observation, dict) else None
|
||||
accounting = origin.get("workload") if isinstance(origin, dict) else None
|
||||
if not isinstance(accounting, dict):
|
||||
return False
|
||||
demand, hub = accounting.get("demand"), accounting.get("hub")
|
||||
return (isinstance(demand, dict) and isinstance(hub, dict)
|
||||
and all(type(demand.get(field)) is int and demand[field] == 0 for field in
|
||||
("logicalInterests", "sharingGroups", "registryInterests", "trackedDrivers", "desiredPhysicalReferences", "appliedPhysicalReferences", "retiringDrivers"))
|
||||
and type(accounting.get("reservedDrivers")) is int and accounting["reservedDrivers"] == len(_RESIDENT_ORIGIN_DRIVERS)
|
||||
and all(type(hub.get(field)) is int and hub[field] == 0 for field in ("snapshotItems", "interestItems")))
|
||||
|
||||
|
||||
def validate_origin_samples(samples, expected_partitions=None, sharing=None, consecutive=3):
|
||||
if not samples:
|
||||
raise WorkloadError("actual origin accounting samples missing")
|
||||
maximum_applied = 0
|
||||
stable = longest_stable = 0
|
||||
timestamps = set()
|
||||
for sample in samples:
|
||||
accounting = sample.get("originAccounting", {}).get("workload")
|
||||
if not isinstance(accounting, dict):
|
||||
raise WorkloadError("origin owner accounting unavailable")
|
||||
demand, hub = accounting.get("demand", {}), accounting.get("hub", {})
|
||||
fields = ("logicalInterests", "sharingGroups", "registryInterests", "desiredPhysicalReferences", "appliedPhysicalReferences")
|
||||
if (any(type(demand.get(field)) is not int or demand[field] < 0 for field in fields)
|
||||
or (expected_partitions is not None and (type(hub.get("partitionCount")) is not int or hub["partitionCount"] != expected_partitions))
|
||||
or not finite(hub.get("retainedBytes"), 0, 2**63) or not finite(hub.get("maximumRetainedBytes"), 1, 2**63)
|
||||
or hub["retainedBytes"] > hub["maximumRetainedBytes"]
|
||||
or not finite(accounting.get("reservedDrivers"), 0, 2**31)
|
||||
or not finite(accounting.get("maximumReservedDrivers"), 1, 2**31)
|
||||
or accounting["reservedDrivers"] > accounting["maximumReservedDrivers"]):
|
||||
raise WorkloadError("origin bounded resource invariant failed")
|
||||
maximum_applied = max(maximum_applied, demand["appliedPhysicalReferences"])
|
||||
if sharing is not None:
|
||||
limits = {'logicalInterests': sharing['logical_interests'], 'registryInterests': sharing['registry_interests'],
|
||||
'sharingGroups': sharing['sharing_groups'], 'desiredPhysicalReferences': sharing['physical_references'],
|
||||
'appliedPhysicalReferences': sharing['physical_references']}
|
||||
if any(demand[key] > limit for key, limit in limits.items()):
|
||||
raise WorkloadError('physical sharing/cardinality exceeds unique admitted source or authority cohorts')
|
||||
captured = accounting.get('capturedAtUtc')
|
||||
if not isinstance(captured, str) or not captured or captured in timestamps:
|
||||
raise WorkloadError('sharing requires distinct actual origin accounting observations')
|
||||
timestamps.add(captured)
|
||||
settled = all(demand[key] == limit for key, limit in limits.items()) and demand.get('trackedDrivers') == sharing['driver_count'] and demand.get('retiringDrivers') == 0
|
||||
stable = stable + 1 if settled else 0
|
||||
longest_stable = max(longest_stable, stable)
|
||||
if maximum_applied < 1:
|
||||
raise WorkloadError("no actual acknowledged physical acquisition observed")
|
||||
if sharing is not None and longest_stable < consecutive:
|
||||
raise WorkloadError('sharing cardinality never reached consecutive acknowledged steady observations')
|
||||
return {"maximum_applied_physical_references": maximum_applied,
|
||||
"maximum_logical_interests": max(row["originAccounting"]["workload"]["demand"]["logicalInterests"] for row in samples),
|
||||
"maximum_retained_bytes": max(row["originAccounting"]["workload"]["hub"]["retainedBytes"] for row in samples),
|
||||
"sharing_expectation": sharing, "consecutive_steady_observations": longest_stable}
|
||||
|
||||
|
||||
def summarize_comparisons(document, rows):
|
||||
"""Compare measured runs without treating a ratio as a capacity guarantee."""
|
||||
by_id = {row["id"]: row for row in rows}
|
||||
results = []
|
||||
for comparison in document.get("comparisons", []):
|
||||
result = dict(comparison)
|
||||
left, right = by_id.get(comparison["baseline"]), by_id.get(comparison["variant"])
|
||||
result["status"] = "not-selected" if left is None or right is None else "measured" if left["passed"] and right["passed"] else "failed"
|
||||
if result["status"] == "measured":
|
||||
fields = ("delivered_samples_per_second", "caller_process_cpu_core_equivalents", "device_read_requests_per_second", "typed_value_bytes_per_sample", "serialized_value_frame_bytes_per_sample")
|
||||
result["measurements"] = {field: {"baseline": left["measurements"][field], "variant": right["measurements"][field],
|
||||
"variant_to_baseline": right["measurements"][field] / left["measurements"][field] if left["measurements"][field] else None} for field in fields}
|
||||
results.append(result)
|
||||
return results
|
||||
|
||||
|
||||
def summarize_measurement(observations, profile, ledger_before, ledger_after, elapsed_seconds):
|
||||
"""Reconcile real probe evidence independently of its passed bit."""
|
||||
if not finite(elapsed_seconds, .001, 300) or not isinstance(observations, dict):
|
||||
raise WorkloadError("invalid measurement duration")
|
||||
expected = probe_options(profile, {"raw": "modbus/plc/scalar", "uns": "area/line/plc/scalar"})
|
||||
echo = observations.get("profile")
|
||||
if not isinstance(echo, dict) or any(echo.get(key) != value for key, value in expected.items()):
|
||||
raise WorkloadError("probe did not measure the requested dimensions")
|
||||
clients = observations.get("clients")
|
||||
if not isinstance(clients, list) or len(clients) != profile["clients"] or {client.get("client") for client in clients} != set(range(profile["clients"])):
|
||||
raise WorkloadError("client measurement coverage incomplete")
|
||||
measured_elapsed = observations.get("elapsedSeconds")
|
||||
if not finite(measured_elapsed, .001, 120):
|
||||
raise WorkloadError("actual stream sampling window missing")
|
||||
samples = byte_count = registrations = 0
|
||||
rejected_clients = 0
|
||||
for client in clients:
|
||||
if "admission_limit" in profile and client.get("rejectedBeforeStream") is True:
|
||||
if client.get("failure") is not None or client.get("acknowledged") != 0:
|
||||
raise WorkloadError("admission rejection has inconsistent evidence")
|
||||
rejected_clients += 1
|
||||
continue
|
||||
count = profile["registrations_per_client"]
|
||||
if (client.get("failure") is not None or client.get("acknowledged") != count or client.get("snapshots") != count
|
||||
or client.get("rejected") != 0 or client.get("unreadySamples") != 0
|
||||
or not isinstance(client.get("items"), list) or len(client["items"]) != count
|
||||
or {item.get("id") for item in client["items"]} != {"r" + str(index) for index in range(count)}
|
||||
or client.get("controls", {}).get("SnapshotEnd", 0) < 1):
|
||||
raise WorkloadError("registration admission/initialization mismatch")
|
||||
registrations += client["acknowledged"]
|
||||
for item in client["items"]:
|
||||
if (type(item.get("samples")) is not int or item["samples"] < 1
|
||||
or type(item.get("typedValueBytes")) is not int or item["typedValueBytes"] < 1
|
||||
or not finite(item.get("firstSnapshotMilliseconds"), 0, 120000)
|
||||
or item.get("sourceId") not in profile["sources"]
|
||||
or (item.get("sourceId") in {"scalar", "counter", "vector", "text"} and (type(item.get("changes")) is not int or item["changes"] < 1))
|
||||
or (item.get("sourceId") in {"scalar", "counter", "vector", "text"} and client["client"] >= profile["slow_clients"]
|
||||
and (type(item.get("changesAfterMidpoint")) is not int or item["changesAfterMidpoint"] < 1
|
||||
or not finite(item.get("hotTailMilliseconds"), 0, 5000)))):
|
||||
raise WorkloadError("per-registration progress evidence missing")
|
||||
samples += item["samples"]
|
||||
byte_count += item["typedValueBytes"]
|
||||
if "admission_limit" in profile and (rejected_clients < 1 or registrations < 1 or
|
||||
registrations > profile["admission_limit"] * profile["registrations_per_client"]):
|
||||
raise WorkloadError("independent configured admission bound not observed")
|
||||
before, after = observations.get("processBefore"), observations.get("processAfter")
|
||||
if not isinstance(before, dict) or not isinstance(after, dict):
|
||||
raise WorkloadError("actual process measurements missing")
|
||||
for row in (before, after):
|
||||
if any(not finite(row.get(field), 0, 2**63) for field in ("workingSet64", "managedBytes", "totalProcessorMilliseconds")):
|
||||
raise WorkloadError("actual memory/CPU counters unavailable")
|
||||
cpu_ms = after["totalProcessorMilliseconds"] - before["totalProcessorMilliseconds"]
|
||||
source_reads = ledger_after.get("read_total", -1) - ledger_before.get("read_total", -1)
|
||||
if cpu_ms < 0 or source_reads < 0:
|
||||
raise WorkloadError("measurement counter reset")
|
||||
encoding = encoding_measurement(observations, profile)
|
||||
return {"acknowledged_registrations": registrations, "delivered_samples": samples,
|
||||
"clients_rejected_before_stream": rejected_clients,
|
||||
"stream_sampling_seconds": measured_elapsed, "fixture_counter_window_seconds": elapsed_seconds,
|
||||
"delivered_samples_per_second": samples / measured_elapsed,
|
||||
"typed_value_bytes": byte_count, "typed_value_bytes_per_sample": byte_count / samples,
|
||||
"device_read_requests": source_reads, "device_read_requests_per_second": source_reads / elapsed_seconds,
|
||||
"caller_process_cpu_core_equivalents": cpu_ms / (measured_elapsed * 1000),
|
||||
"working_set_change_bytes": after["workingSet64"] - before["workingSet64"],
|
||||
"managed_change_bytes": after["managedBytes"] - before["managedBytes"],
|
||||
**encoding, "serialized_value_frame_bytes_per_sample": encoding["serialized_value_frame_bytes"] / samples,
|
||||
"source_rate_definition": "actual fixture Modbus read requests; requests may batch multiple registers",
|
||||
"bytes_definition": observations.get("bytesDefinition"),
|
||||
"leak_verdict": "not inferred from instantaneous GC/working-set differences"}
|
||||
|
||||
|
||||
def encoding_measurement(observations, profile):
|
||||
counters = ("compactFrameCount", "fallbackFrameCount", "serializedValueFrameBytes")
|
||||
snapshots = []
|
||||
for key in ("diagnosticsBefore", "diagnosticsAfter"):
|
||||
diagnostics = observations.get(key)
|
||||
rows = diagnostics.get("connections") if isinstance(diagnostics, dict) else None
|
||||
if not isinstance(rows, list):
|
||||
raise WorkloadError("actual encoding accounting missing")
|
||||
matches = [row for row in rows if isinstance(row, dict) and row.get("connectionId") == "consumer-source"]
|
||||
if len(matches) != 1 or any(type(matches[0].get(field)) is not int or matches[0][field] < 0 for field in counters):
|
||||
raise WorkloadError("actual encoding accounting missing")
|
||||
snapshots.append(matches[0])
|
||||
before, after = snapshots
|
||||
if any(before.get(field) != after.get(field) or before.get(field) is None for field in ("revision", "scopeVersion", "artifactRevision", "accountingInstanceId")):
|
||||
raise WorkloadError("encoding accounting owner changed")
|
||||
delta = {field: after[field] - before[field] for field in counters}
|
||||
expected = "compactFrameCount" if profile["compact_batches"] else "fallbackFrameCount"
|
||||
unexpected = "fallbackFrameCount" if profile["compact_batches"] else "compactFrameCount"
|
||||
if any(value < 0 for value in delta.values()) or delta[expected] < 1 or delta[unexpected] != 0 or delta["serializedValueFrameBytes"] < 1:
|
||||
raise WorkloadError("requested encoding not observed on accepted value frames")
|
||||
return {"compact_value_frames": delta["compactFrameCount"], "fallback_value_frames": delta["fallbackFrameCount"],
|
||||
"serialized_value_frame_bytes": delta["serializedValueFrameBytes"],
|
||||
"wire_bytes_definition": "accepted serialized protobuf value frames; excludes HTTP/2 and TLS overhead"}
|
||||
|
||||
|
||||
class WorkloadRunner(ScenarioRunner):
|
||||
@contextmanager
|
||||
def origin_samples(self, origin, samples):
|
||||
done = threading.Event()
|
||||
failures = []
|
||||
def sample():
|
||||
try:
|
||||
while not done.is_set():
|
||||
samples.append(self.probe(origin, "topology", timeout=5))
|
||||
done.wait(.5)
|
||||
except Exception as error:
|
||||
failures.append(type(error).__name__)
|
||||
worker = threading.Thread(target=sample, daemon=True)
|
||||
worker.start()
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
done.set()
|
||||
worker.join(timeout=7)
|
||||
if worker.is_alive() or failures:
|
||||
raise WorkloadError("actual origin accounting sampler failed to retire")
|
||||
|
||||
@contextmanager
|
||||
def source_updates(self, profile):
|
||||
done = threading.Event()
|
||||
failures = []
|
||||
initial_values = self.device()["writable"]
|
||||
initial = initial_values["20"]
|
||||
touched_addresses = ([20] if "scalar" in profile["sources"] else []) + ([24, 25, 26] if "vector" in profile["sources"] else []) + ([40] if "text" in profile["sources"] else [])
|
||||
updates = []
|
||||
def update():
|
||||
value = initial
|
||||
try:
|
||||
while not done.wait(1 / profile["source_hz"]):
|
||||
value = (value + max(1, int(profile["deadband"] or 0) + 1)) % 65536
|
||||
if "counter" in profile["sources"]:
|
||||
self.device("advance", steps=max(1, int(profile["deadband"] or 0) + 1))
|
||||
if "scalar" in profile["sources"]:
|
||||
self.device("set", address=20, value=value)
|
||||
if "vector" in profile["sources"]:
|
||||
for offset in range(3):
|
||||
self.device("set", address=24 + offset, value=(value + offset) % 65536)
|
||||
if "text" in profile["sources"]:
|
||||
self.device("set", address=40, value=((65 + value % 26) << 8) | 66)
|
||||
updates.append(time.monotonic())
|
||||
except Exception as error:
|
||||
failures.append(type(error).__name__)
|
||||
worker = threading.Thread(target=update, daemon=True)
|
||||
worker.start()
|
||||
try:
|
||||
yield updates
|
||||
if failures:
|
||||
raise WorkloadError("actual fixture producer failed")
|
||||
finally:
|
||||
done.set()
|
||||
worker.join(timeout=6)
|
||||
if worker.is_alive():
|
||||
raise WorkloadError("fixture producer did not retire")
|
||||
for address in touched_addresses:
|
||||
self.device("set", address=address, value=initial_values[str(address)])
|
||||
|
||||
def settle(self, caller, accounting):
|
||||
deadline = time.monotonic() + accounting["settle_seconds"]
|
||||
consecutive = 0
|
||||
rows = []
|
||||
while time.monotonic() < deadline:
|
||||
observations = self.probe(caller, "topology", timeout=5)
|
||||
rows.append(observations)
|
||||
consecutive = consecutive + 1 if connections_drained(observations.get("connections")) else 0
|
||||
if consecutive >= accounting["consecutive_drained_observations"]:
|
||||
return rows
|
||||
time.sleep(accounting["sample_interval_seconds"])
|
||||
raise WorkloadError("physical streams/calls/registrations did not settle")
|
||||
|
||||
def settle_origin(self, origin, accounting):
|
||||
expected_members = {self.node_id(node) for node, metadata in self.manifest["nodes"].items() if metadata["cluster_id"] == "SOURCE"}
|
||||
expected_node = self.node_id(origin)
|
||||
deployment = self.manifest["deployment"]
|
||||
if len(expected_members) != 2 or expected_node not in expected_members or not deployment.get("id") or not deployment.get("revision_hash"):
|
||||
raise WorkloadError("origin drain requires the deployed SOURCE pair identity")
|
||||
# The manifest uses a canonical UUID and the runtime artifact uses compact hexadecimal.
|
||||
expected_deployment_id = deployment["id"].replace("-", "")
|
||||
deadline = time.monotonic() + accounting["settle_seconds"]
|
||||
consecutive = 0
|
||||
rows = []
|
||||
while time.monotonic() < deadline:
|
||||
observed = self.probe(origin, "topology", timeout=5)
|
||||
members = observed.get("members")
|
||||
if (observed.get("self") != f"akka.tcp://otopcua@{expected_node}"
|
||||
or observed.get("deploymentId") != expected_deployment_id
|
||||
or observed.get("artifactRevision") != deployment["revision_hash"]
|
||||
or not isinstance(members, list) or len(members) != len(expected_members)
|
||||
or {f"{member.get('host')}:{member.get('port')}" for member in members
|
||||
if isinstance(member, dict) and member.get("status") == "Up"} != expected_members):
|
||||
raise WorkloadError("origin accounting identity does not match the deployed SOURCE pair")
|
||||
rows.append(observed)
|
||||
consecutive = consecutive + 1 if origin_drained(observed) else 0
|
||||
if consecutive >= accounting["consecutive_drained_observations"]:
|
||||
return rows
|
||||
time.sleep(accounting["sample_interval_seconds"])
|
||||
raise WorkloadError("origin demand and hub items did not drain to zero with exactly one resident reservation")
|
||||
|
||||
def hardware(self):
|
||||
info = json.loads(self.rig.compose("version", "--format", "json"))
|
||||
docker = json.loads(rig.run_command([*self.rig.docker, "info", "--format", "{{json .}}"], environment=self.rig.environment))
|
||||
resources = [row for row in self.rig.inspect_resources() if row["kind"] == "container"]
|
||||
containers = []
|
||||
for resource in resources:
|
||||
inspect = json.loads(rig.run_command([*self.rig.docker, "container", "inspect", resource["id"]], environment=self.rig.environment))[0]
|
||||
host = inspect.get("HostConfig", {})
|
||||
containers.append({"id": resource["id"], "service": resource["labels"].get("com.docker.compose.service"),
|
||||
"image_id": inspect.get("Image"), "limits": {key: host.get(key) for key in
|
||||
("Memory", "MemorySwap", "NanoCpus", "CpuQuota", "CpuPeriod", "CpusetCpus")}})
|
||||
return {"host_architecture": platform.machine(), "host_platform": platform.platform(), "compose": info,
|
||||
"docker": {key: docker.get(key) for key in ("Architecture", "OSType", "NCPU", "MemTotal", "KernelVersion", "ServerVersion")},
|
||||
"containers": containers, "tls": "TLS 1.2/1.3 with run-owned CA and exact DNS SAN verification",
|
||||
"compression": "no explicit gRPC compression configured", "encoding": "explicit compact opt-in/opt-out; actual accepted wire frame counters measured",
|
||||
"serialization_ceilings": ["DriverHostActor driver calls and SDK NodeManager operations retain their production serialization gates"],
|
||||
"unavailable_breakdowns": ["CPU per actor/partition", "retained/pool/cache bytes unless exposed by actual owner counters"]}
|
||||
|
||||
def run_workloads(self, document, selected=None, adversarial_packet=None):
|
||||
document = validate_profiles(document)
|
||||
profiles = [profile for profile in document["profiles"] if selected is None or profile["id"] in selected or profile["group"] in selected]
|
||||
if not profiles or (selected and set(selected) - {value for profile in document["profiles"] for value in (profile["id"], profile["group"])}):
|
||||
raise WorkloadError("unknown or empty workload selection")
|
||||
adversarial_path = adversarial_packet or self.rig.folder / 'adversarial-evidence' / 'packet.json'
|
||||
adversarial = adversarial_preflight(adversarial_path)
|
||||
if adversarial['runtime_source_tree_hash'] != self.manifest.get('source_tree_hash'):
|
||||
raise WorkloadError('adversarial packet and deployed rig belong to different candidates')
|
||||
self.folder = self.rig.folder / "workload-evidence"
|
||||
self.folder.mkdir(mode=0o700, exist_ok=True)
|
||||
self.active = "P11"
|
||||
self.deadline = time.monotonic() + 120
|
||||
self.save("hardware.json", self.hardware())
|
||||
self.rig.seed_helper("snapshot")
|
||||
rows = []
|
||||
for profile in profiles:
|
||||
self.active = "P11-" + profile["id"]
|
||||
self.deadline = time.monotonic() + 480
|
||||
started = time.monotonic()
|
||||
error = None
|
||||
restored = False
|
||||
row = {"id": profile["id"], "configuration": profile}
|
||||
try:
|
||||
with self.rig.hub_partitions(profile["hub_partitions"]), self.rig.compact_batches(profile["compact_batches"]):
|
||||
self.manifest = self.rig.load()
|
||||
caller = self.primary("consumer")
|
||||
origin = self.primary("source")
|
||||
if "admission_limit" in profile:
|
||||
baseline = restricted_json((self.rig.folder / "seed" / "baseline.json").resolve())
|
||||
connection = next(item for item in baseline["Connections"] if item["DataConnectionId"] == "consumer-source")
|
||||
connection["MaxStreams"] = profile["admission_limit"]
|
||||
self.mutate(upsert_connection=connection)
|
||||
# Deterministic correctness runs before timed sampling.
|
||||
self.probe(caller, "read")
|
||||
self.probe(caller, "metadata")
|
||||
if profile.get("recovery_preflight"):
|
||||
self.prepare_positive_projection(caller, "raw")
|
||||
with self.changing():
|
||||
self.live_cli_fault(caller, self.primary("source"), require_gap=True)
|
||||
self.wait_pair_topology("source")
|
||||
origin = self.primary("source")
|
||||
row["drained_before"] = self.settle(caller, document["accounting"])
|
||||
row["origin_drained_before"] = self.settle_origin(origin, document["accounting"])
|
||||
ledger_before = self.device()
|
||||
measured_start = time.monotonic()
|
||||
row["origin_samples"] = []
|
||||
with self.origin_samples(origin, row["origin_samples"]), self.source_updates(profile) as updates:
|
||||
observed = self.probe(caller, "workload", timeout=profile["duration_seconds"] + 20,
|
||||
workload=probe_options(profile, self.manifest["fixture"]["origin_paths"]),
|
||||
workloadUnsNamespaceUri=self.manifest["fixture"]["namespace_uris"]["uns"],
|
||||
workloadBrowseRoots={realm: fixture_browse_root(self.manifest["fixture"], realm) for realm in ("raw", "uns")})
|
||||
elapsed = time.monotonic() - measured_start
|
||||
ledger_after = self.device()
|
||||
row["measurements"] = summarize_measurement(observed, profile, ledger_before, ledger_after, elapsed)
|
||||
row["measurements"]["actual_producer_ticks"] = len(updates)
|
||||
row["measurements"]["origin"] = validate_origin_samples(row["origin_samples"], profile["hub_partitions"],
|
||||
sharing_expectation(profile, observed), document['accounting']['consecutive_drained_observations'])
|
||||
row["observations"] = observed
|
||||
row["drained_after"] = self.settle(caller, document["accounting"])
|
||||
row["origin_drained_after"] = self.settle_origin(origin, document["accounting"])
|
||||
except Exception as failure:
|
||||
error = type(failure).__name__ + (": " + str(failure) if isinstance(failure, (WorkloadError, ScenarioError)) else "")
|
||||
finally:
|
||||
try:
|
||||
self.manifest = self.rig.load()
|
||||
self.baseline()
|
||||
restored = True
|
||||
except Exception as failure:
|
||||
error = (error + "; " if error else "") + "restoration " + type(failure).__name__
|
||||
row.update(passed=error is None, failure=error, restored=restored, duration_seconds=time.monotonic() - started)
|
||||
rows.append(row)
|
||||
self.save("workload-results.json", {"schema_version": 1, "rows": rows, "complete": len(rows) == len(profiles), "passed": False})
|
||||
adversarial_error = None
|
||||
try:
|
||||
if adversarial_preflight(adversarial_path) != adversarial:
|
||||
raise WorkloadError('adversarial evidence changed during measurement')
|
||||
except WorkloadError as failure:
|
||||
adversarial_error = str(failure)
|
||||
report = {"schema_version": 1, "run_id": self.manifest["run_id"], "source_revision": self.manifest.get("source_revision"),
|
||||
"passed": adversarial_error is None and all(row["passed"] and row["restored"] for row in rows), "complete": True, "rows": rows,
|
||||
"adversarial_evidence": adversarial, "adversarial_evidence_error": adversarial_error,
|
||||
"capacity_claim": None, "comparisons": summarize_comparisons(document, rows),
|
||||
"origin_drain_expectation": {"seeded_resident_driver_ids": list(_RESIDENT_ORIGIN_DRIVERS),
|
||||
"reserved_driver_count": len(_RESIDENT_ORIGIN_DRIVERS), "workload_demand_and_hub_items": 0},
|
||||
"coverage_limits": ["array0/1/2 names are UInt16 scalars; vector is the actual array payload and text is the string payload",
|
||||
"Hub partition count is configured and observed; it is not an independent runtime worker-count setting",
|
||||
"Deterministic prerequisites are linked by the required candidate-matched adversarial packet; workload measurements do not extrapolate capacity"]}
|
||||
self.save("workload-results.json", report)
|
||||
self.save("index.json", {"files": [{"path": path.name, "sha256": hashlib.sha256(path.read_bytes()).hexdigest(), "bytes": path.stat().st_size}
|
||||
for path in sorted(self.folder.iterdir()) if path.is_file() and path.name != "index.json"]})
|
||||
return report
|
||||
|
||||
|
||||
def main(argv=None):
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--run-id", required=True)
|
||||
parser.add_argument("--profiles", type=Path, default=Path(__file__).with_name("workload-profiles.json"))
|
||||
parser.add_argument("--select", action="append", help="profile id or group; repeatable")
|
||||
parser.add_argument("--manifest", type=Path)
|
||||
parser.add_argument("--adversarial-packet", type=Path, help="restricted passing current-candidate packet; defaults to this rig's adversarial-evidence/packet.json")
|
||||
args = parser.parse_args(argv)
|
||||
try:
|
||||
document = validate_profiles(json.loads(args.profiles.read_text()))
|
||||
report = WorkloadRunner(args.run_id, manifest_path=args.manifest).run_workloads(document, args.select, args.adversarial_packet)
|
||||
print(json.dumps({"passed": report["passed"], "profiles": [row["id"] for row in report["rows"]]}))
|
||||
return 0 if report["passed"] else 1
|
||||
except Exception as error:
|
||||
print("grpc-data workload: " + type(error).__name__ + "; restricted diagnostics retained")
|
||||
return 2
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
Reference in New Issue
Block a user