362 lines
24 KiB
Python
362 lines
24 KiB
Python
import copy
|
|
from contextlib import contextmanager, nullcontext
|
|
import importlib.util
|
|
import json
|
|
from pathlib import Path
|
|
import sys
|
|
import tempfile
|
|
from types import SimpleNamespace
|
|
import unittest
|
|
from unittest.mock import Mock, call, patch
|
|
|
|
HERE = Path(__file__).resolve().parents[1]
|
|
sys.path.insert(0, str(HERE))
|
|
import workload
|
|
|
|
|
|
class WorkloadResultsTests(unittest.TestCase):
|
|
def setUp(self):
|
|
self.document = json.loads((HERE / 'workload-profiles.json').read_text())
|
|
self.profile = copy.deepcopy(self.document['profiles'][0])
|
|
|
|
def observations(self):
|
|
process = {'workingSet64': 100, 'managedBytes': 80, 'totalProcessorMilliseconds': 10}
|
|
diagnostics = {'connectionId': 'consumer-source', 'revision': 1, 'scopeVersion': 1, 'artifactRevision': 'fixture', 'accountingInstanceId': 'owner-one',
|
|
'compactFrameCount': 0, 'fallbackFrameCount': 0, 'serializedValueFrameBytes': 0}
|
|
return {'profile': workload.probe_options(self.profile, {'raw': 'modbus/plc/scalar', 'uns': 'area/line/plc/scalar'}),
|
|
'elapsedSeconds': 2,
|
|
'clients': [{'client': 0, 'failure': None, 'acknowledged': 1, 'snapshots': 1, 'rejected': 0, 'unreadySamples': 0, 'controls': {'SnapshotEnd': 1},
|
|
'items': [{'id': 'r0', 'sourceId': 'scalar', 'realm': 'Raw', 'samples': 3, 'typedValueBytes': 24, 'changesAfterMidpoint': 1, 'hotTailMilliseconds': 100,
|
|
'firstSnapshotMilliseconds': 100, 'requireChanges': True, 'changes': 2}]}],
|
|
'processBefore': process, 'processAfter': {**process, 'totalProcessorMilliseconds': 110},
|
|
'diagnosticsBefore': {'connections': [diagnostics]},
|
|
'diagnosticsAfter': {'connections': [{**diagnostics, 'compactFrameCount': 2, 'serializedValueFrameBytes': 100}]},
|
|
'bytesDefinition': 'typed value protobuf only'}
|
|
|
|
def summarize(self, observation=None):
|
|
return workload.summarize_measurement(observation or self.observations(), self.profile,
|
|
{'read_total': 12}, {'read_total': 22}, 2)
|
|
|
|
def test_catalog_has_real_smoke_steady_fanout_recovery_and_payload_profiles(self):
|
|
workload.validate_profiles(self.document)
|
|
self.assertEqual({'smoke', 'steady', 'fan-out', 'recovery'}, {row['group'] for row in self.document['profiles']})
|
|
typed = next(row for row in self.document['profiles'] if row['id'] == 'typed-payloads')
|
|
options = workload.probe_options(typed, {'raw': 'modbus/plc/scalar', 'uns': 'area/line/plc/scalar'})
|
|
self.assertEqual([('UInt16', -1), ('Array', 1), ('String', -1)], [(item['expectedKind'], item['expectedRank']) for item in options['sources']])
|
|
self.assertEqual('modbus/plc/vector', options['sources'][1]['rawPath'])
|
|
|
|
def test_measures_actual_acks_counters_and_elapsed_time(self):
|
|
measured = self.summarize()
|
|
self.assertEqual(1, measured['acknowledged_registrations'])
|
|
self.assertEqual(1.5, measured['delivered_samples_per_second'])
|
|
self.assertEqual(8, measured['typed_value_bytes_per_sample'])
|
|
self.assertEqual(5, measured['device_read_requests_per_second'])
|
|
self.assertAlmostEqual(.05, measured['caller_process_cpu_core_equivalents'])
|
|
self.assertEqual(2, measured['compact_value_frames'])
|
|
self.assertEqual(100 / 3, measured['serialized_value_frame_bytes_per_sample'])
|
|
self.assertNotIn('capacity', measured)
|
|
self.assertIn('not inferred', measured['leak_verdict'])
|
|
|
|
def test_missing_or_null_accounting_does_not_mean_zero(self):
|
|
valid = [{'activeStreams': 0, 'activeCalls': 0, 'registrationCount': 0}]
|
|
self.assertTrue(workload.connections_drained(valid))
|
|
for rows in (None, [], [{}], [{**valid[0], 'registrationCount': None}], [{**valid[0], 'activeCalls': 1}]):
|
|
with self.subTest(rows=rows):
|
|
self.assertFalse(workload.connections_drained(rows))
|
|
|
|
def test_refuses_inferred_admission_missing_snapshot_or_hot_starvation(self):
|
|
for field, value in [('acknowledged', 0), ('snapshots', 0), ('rejected', 1), ('unreadySamples', 1), ('failure', 'Unavailable')]:
|
|
observed = self.observations()
|
|
observed['clients'][0][field] = value
|
|
with self.subTest(field=field), self.assertRaises(workload.WorkloadError):
|
|
self.summarize(observed)
|
|
observed = self.observations()
|
|
observed['clients'][0]['items'][0]['changes'] = 0
|
|
with self.assertRaises(workload.WorkloadError):
|
|
self.summarize(observed)
|
|
|
|
def test_rejects_wrong_measured_configuration_and_missing_memory(self):
|
|
observed = self.observations()
|
|
observed['profile']['clients'] = 2
|
|
with self.assertRaises(workload.WorkloadError):
|
|
self.summarize(observed)
|
|
observed = self.observations()
|
|
observed['processAfter']['workingSet64'] = None
|
|
with self.assertRaises(workload.WorkloadError):
|
|
self.summarize(observed)
|
|
|
|
def test_rejects_fake_unbounded_or_ambiguous_dimensions(self):
|
|
for field, value in [('clients', True), ('clients', 65), ('source_hz', float('nan')),
|
|
('sources', ['not-a-fixture-source']), ('workers', 10), ('slow_clients', 2),
|
|
('hub_partitions', True), ('hub_partitions', 17), ('compact_batches', 1)]:
|
|
document = copy.deepcopy(self.document)
|
|
document['profiles'][0][field] = value
|
|
with self.subTest(field=field), self.assertRaises(workload.WorkloadError):
|
|
workload.validate_profiles(document)
|
|
|
|
def test_rejects_duplicate_profile_ids_and_instantaneous_settle(self):
|
|
document = copy.deepcopy(self.document)
|
|
document['profiles'][1]['id'] = document['profiles'][0]['id']
|
|
with self.assertRaises(workload.WorkloadError):
|
|
workload.validate_profiles(document)
|
|
document = copy.deepcopy(self.document)
|
|
document['accounting']['consecutive_drained_observations'] = 1
|
|
with self.assertRaises(workload.WorkloadError):
|
|
workload.validate_profiles(document)
|
|
|
|
def test_counter_reset_cannot_be_a_rate(self):
|
|
observed = self.observations()
|
|
observed['processAfter']['totalProcessorMilliseconds'] = 0
|
|
with self.assertRaises(workload.WorkloadError):
|
|
self.summarize(observed)
|
|
|
|
def test_actual_origin_counts_remain_separate_and_cleanup_requires_all_owners(self):
|
|
demand = dict.fromkeys(('logicalInterests', 'sharingGroups', 'registryInterests', 'trackedDrivers',
|
|
'desiredPhysicalReferences', 'appliedPhysicalReferences', 'retiringDrivers'), 0)
|
|
hub = {'snapshotItems': 0, 'interestItems': 0, 'retainedBytes': 256, 'maximumRetainedBytes': 1024}
|
|
observed = {'originAccounting': {'workload': {'demand': demand, 'hub': hub,
|
|
'reservedDrivers': 1, 'maximumReservedDrivers': 4}}}
|
|
self.assertTrue(workload.origin_drained(observed))
|
|
for value in (0, 2, True, 1.0, None):
|
|
other = copy.deepcopy(observed)
|
|
other['originAccounting']['workload']['reservedDrivers'] = value
|
|
with self.subTest(reserved_drivers=value):
|
|
self.assertFalse(workload.origin_drained(other))
|
|
for category, fields in (('demand', demand), ('hub', ('snapshotItems', 'interestItems'))):
|
|
for field in fields:
|
|
other = copy.deepcopy(observed)
|
|
other['originAccounting']['workload'][category][field] = 1
|
|
with self.subTest(category=category, field=field):
|
|
self.assertFalse(workload.origin_drained(other))
|
|
held = copy.deepcopy(observed)
|
|
held['originAccounting']['workload']['demand']['appliedPhysicalReferences'] = 1
|
|
held['originAccounting']['workload']['demand']['logicalInterests'] = 8
|
|
self.assertFalse(workload.origin_drained(held))
|
|
measured = workload.validate_origin_samples([held])
|
|
self.assertEqual(1, measured['maximum_applied_physical_references'])
|
|
self.assertEqual(8, measured['maximum_logical_interests'])
|
|
with self.assertRaises(workload.WorkloadError):
|
|
workload.validate_origin_samples([observed])
|
|
held['originAccounting']['workload']['hub']['retainedBytes'] = 1025
|
|
with self.assertRaises(workload.WorkloadError):
|
|
workload.validate_origin_samples([held])
|
|
|
|
def test_origin_settle_requires_consecutive_accounting_from_the_exact_deployed_source(self):
|
|
runner = object.__new__(workload.WorkloadRunner)
|
|
peers = ('source-1', 'source-2')
|
|
runner.manifest = {'nodes': {node: {'node_id': node + ':4053', 'cluster_id': 'SOURCE'} for node in peers},
|
|
'deployment': {'id': '7a4154db-48d5-4250-ad10-53e890dda436', 'revision_hash': 'revision'}}
|
|
demand = dict.fromkeys(('logicalInterests', 'sharingGroups', 'registryInterests', 'trackedDrivers',
|
|
'desiredPhysicalReferences', 'appliedPhysicalReferences', 'retiringDrivers'), 0)
|
|
drained = {'self': 'akka.tcp://otopcua@source-1:4053', 'deploymentId': '7a4154db48d54250ad1053e890dda436', 'artifactRevision': 'revision',
|
|
'members': [{'host': node, 'port': 4053, 'status': 'Up'} for node in peers],
|
|
'originAccounting': {'workload': {'demand': demand, 'hub': {'snapshotItems': 0, 'interestItems': 0},
|
|
'reservedDrivers': 1}}}
|
|
held = copy.deepcopy(drained)
|
|
held['originAccounting']['workload']['demand']['retiringDrivers'] = 1
|
|
observations = [drained, held, drained, drained, drained]
|
|
runner.probe = Mock(side_effect=observations)
|
|
with patch.object(workload.time, 'sleep'):
|
|
self.assertEqual(runner.settle_origin('source-1', self.document['accounting']), observations)
|
|
self.assertEqual(runner.probe.call_args_list, [call('source-1', 'topology', timeout=5)] * len(observations))
|
|
|
|
for field, value in (('self', 'akka.tcp://otopcua@source-2:4053'), ('deploymentId', 'stale'), ('artifactRevision', 'stale'),
|
|
('members', drained['members'][:1]), ('members', [drained['members'][0], {'host': 'foreign', 'port': 4053, 'status': 'Up'}])):
|
|
runner.probe = Mock(return_value={**drained, field: value})
|
|
with self.subTest(field=field, value=value), self.assertRaisesRegex(workload.WorkloadError, 'identity'):
|
|
runner.settle_origin('source-1', self.document['accounting'])
|
|
|
|
def test_partition_variant_requires_actual_origin_partition_count(self):
|
|
demand = dict.fromkeys(('logicalInterests', 'sharingGroups', 'registryInterests', 'desiredPhysicalReferences', 'appliedPhysicalReferences'), 1)
|
|
observed = {'originAccounting': {'workload': {'demand': demand, 'hub': {'retainedBytes': 16, 'maximumRetainedBytes': 1024, 'partitionCount': 4},
|
|
'reservedDrivers': 1, 'maximumReservedDrivers': 4}}}
|
|
workload.validate_origin_samples([observed], 4)
|
|
with self.assertRaises(workload.WorkloadError):
|
|
workload.validate_origin_samples([observed], 1)
|
|
del observed['originAccounting']['workload']['hub']['partitionCount']
|
|
with self.assertRaises(workload.WorkloadError):
|
|
workload.validate_origin_samples([observed], 4)
|
|
|
|
def test_encoding_requires_actual_accepted_frames_and_stable_accounting_owner(self):
|
|
for field, value in [('compactFrameCount', 0), ('fallbackFrameCount', 1), ('serializedValueFrameBytes', None), ('revision', 2), ('accountingInstanceId', 'owner-two')]:
|
|
observed = self.observations()
|
|
observed['diagnosticsAfter']['connections'][0][field] = value
|
|
with self.subTest(field=field), self.assertRaises(workload.WorkloadError):
|
|
self.summarize(observed)
|
|
self.profile['compact_batches'] = False
|
|
observed = self.observations()
|
|
observed['diagnosticsAfter']['connections'][0].update(compactFrameCount=0, fallbackFrameCount=2)
|
|
self.assertEqual(2, self.summarize(observed)['fallback_value_frames'])
|
|
|
|
def test_controlled_matrix_changes_exactly_one_real_dimension(self):
|
|
workload.validate_profiles(self.document)
|
|
self.assertEqual({'hub_partitions', 'compact_batches'}, {row['dimension'] for row in self.document['comparisons']})
|
|
document = copy.deepcopy(self.document)
|
|
variant = next(profile for profile in document['profiles'] if profile['id'] == document['comparisons'][0]['variant'])
|
|
variant['clients'] += 1
|
|
with self.assertRaises(workload.WorkloadError):
|
|
workload.validate_profiles(document)
|
|
document = copy.deepcopy(self.document)
|
|
document['profiles'][0].update(clients=2, overlap=False)
|
|
with self.assertRaises(workload.WorkloadError):
|
|
workload.validate_profiles(document)
|
|
document = copy.deepcopy(self.document)
|
|
document['profiles'][0]['sources'].append('counter')
|
|
with self.assertRaises(workload.WorkloadError):
|
|
workload.validate_profiles(document)
|
|
|
|
def test_comparison_reports_observed_ratios_and_incomplete_selection(self):
|
|
comparison = self.document['comparisons'][0]
|
|
metrics = {'delivered_samples_per_second': 2, 'caller_process_cpu_core_equivalents': 0,
|
|
'device_read_requests_per_second': 1, 'typed_value_bytes_per_sample': 8,
|
|
'serialized_value_frame_bytes_per_sample': 100}
|
|
rows = [{'id': comparison['baseline'], 'passed': True, 'measurements': metrics},
|
|
{'id': comparison['variant'], 'passed': True, 'measurements': {**metrics, 'delivered_samples_per_second': 3}}]
|
|
report = workload.summarize_comparisons(self.document, rows)
|
|
self.assertEqual('measured', report[0]['status'])
|
|
self.assertEqual(1.5, report[0]['measurements']['delivered_samples_per_second']['variant_to_baseline'])
|
|
self.assertIsNone(report[0]['measurements']['caller_process_cpu_core_equivalents']['variant_to_baseline'])
|
|
self.assertEqual('not-selected', report[1]['status'])
|
|
rows[1]['passed'] = False
|
|
self.assertEqual('failed', workload.summarize_comparisons(self.document, rows)[0]['status'])
|
|
|
|
def test_bounded_admission_counts_accepted_handles_separately_from_rejected_clients(self):
|
|
self.profile.update(clients=2, admission_limit=1)
|
|
observed = self.observations()
|
|
observed['clients'].append({'client': 1, 'rejectedBeforeStream': True, 'failure': None, 'acknowledged': 0})
|
|
measured = self.summarize(observed)
|
|
self.assertEqual(1, measured['acknowledged_registrations'])
|
|
self.assertEqual(1, measured['clients_rejected_before_stream'])
|
|
observed['clients'][1]['acknowledged'] = 1
|
|
with self.assertRaises(workload.WorkloadError):
|
|
self.summarize(observed)
|
|
|
|
def sharing_observations(self, profile, accepted=None):
|
|
views = [(source, realm) for source in profile['sources'] for realm in ('Raw', 'Uns')[:profile['views_per_source']]]
|
|
clients = []
|
|
for client in range(profile['clients']):
|
|
if accepted is not None and client not in accepted:
|
|
clients.append({'client': client, 'rejectedBeforeStream': True, 'acknowledged': 0})
|
|
continue
|
|
items = []
|
|
for index in range(profile['registrations_per_client']):
|
|
slot = index if profile['overlap'] else client * profile['registrations_per_client'] + index
|
|
source, realm = views[slot % len(views)]
|
|
items.append({'id': 'r' + str(index), 'sourceId': source, 'realm': realm})
|
|
clients.append({'client': client, 'items': items, 'acknowledged': len(items)})
|
|
return {'clients': clients}
|
|
|
|
def sharing_samples(self, expected):
|
|
return [{'originAccounting': {'workload': {'capturedAtUtc': '2026-11-17T10:00:0' + str(index) + 'Z',
|
|
'demand': {'logicalInterests': expected['logical_interests'], 'registryInterests': expected['registry_interests'],
|
|
'sharingGroups': expected['sharing_groups'], 'desiredPhysicalReferences': expected['physical_references'],
|
|
'appliedPhysicalReferences': expected['physical_references'], 'trackedDrivers': 1, 'retiringDrivers': 0},
|
|
'hub': {'retainedBytes': 256, 'maximumRetainedBytes': 1024, 'partitionCount': 4},
|
|
'reservedDrivers': 1, 'maximumReservedDrivers': 4}}} for index in range(3)]
|
|
|
|
def test_sharing_derives_unique_sources_authority_proofs_and_actual_logical_admission(self):
|
|
profile = next(item for item in self.document['profiles'] if item['id'] == 'fan-out')
|
|
expected = workload.sharing_expectation(profile, self.sharing_observations(profile))
|
|
self.assertEqual(64, expected['logical_interests'])
|
|
self.assertEqual(4, expected['sharing_groups'])
|
|
self.assertEqual(2, expected['physical_references'])
|
|
self.assertFalse(expected['legacy_scope']['included_in_observed_demand_owner'])
|
|
self.assertEqual(7, expected['legacy_scope']['expected_legacy_grpc_reference_union'])
|
|
samples = self.sharing_samples(expected)
|
|
measured = workload.validate_origin_samples(samples, 4, expected)
|
|
self.assertEqual(3, measured['consecutive_steady_observations'])
|
|
self.assertEqual(expected, measured['sharing_expectation'])
|
|
|
|
def test_one_physical_reference_per_registration_cannot_pass_overlap_experiment(self):
|
|
profile = next(item for item in self.document['profiles'] if item['id'] == 'fan-out')
|
|
expected = workload.sharing_expectation(profile, self.sharing_observations(profile))
|
|
samples = self.sharing_samples(expected)
|
|
samples[1]['originAccounting']['workload']['demand']['appliedPhysicalReferences'] = expected['logical_interests']
|
|
with self.assertRaises(workload.WorkloadError): workload.validate_origin_samples(samples, 4, expected)
|
|
|
|
def test_single_good_snapshot_or_replayed_observation_does_not_establish_sharing(self):
|
|
expected = workload.sharing_expectation(self.profile, self.observations())
|
|
samples = self.sharing_samples(expected)
|
|
with self.assertRaises(workload.WorkloadError): workload.validate_origin_samples(samples[:1], 4, expected)
|
|
with self.assertRaises(workload.WorkloadError): workload.validate_origin_samples([samples[0]] * 3, 4, expected)
|
|
samples[1]['originAccounting']['workload']['demand']['appliedPhysicalReferences'] = 0
|
|
with self.assertRaises(workload.WorkloadError): workload.validate_origin_samples(samples, 4, expected)
|
|
|
|
def test_nonoverlap_and_bounded_admission_count_only_actual_admitted_source_views(self):
|
|
profile = next(item for item in self.document['profiles'] if item['id'] == 'interval-deadband')
|
|
observed = self.sharing_observations(profile)
|
|
expected = workload.sharing_expectation(profile, observed)
|
|
self.assertEqual((4, 4, 2), (expected['logical_interests'], expected['sharing_groups'], expected['physical_references']))
|
|
observed['clients'][1]['items'][0]['realm'] = 'Uns'
|
|
with self.assertRaises(workload.WorkloadError): workload.sharing_expectation(profile, observed)
|
|
profile = next(item for item in self.document['profiles'] if item['id'] == 'bounded-admission')
|
|
expected = workload.sharing_expectation(profile, self.sharing_observations(profile, accepted={2}))
|
|
self.assertEqual((1, 1, 1), (expected['logical_interests'], expected['sharing_groups'], expected['physical_references']))
|
|
|
|
def test_missing_or_stale_adversarial_packet_blocks_before_hardware_or_timing(self):
|
|
instance = workload.WorkloadRunner.__new__(workload.WorkloadRunner)
|
|
instance.rig = SimpleNamespace(folder=Path('/private/rig'))
|
|
instance.manifest = {'source_tree_hash': 'current'}
|
|
instance.hardware = Mock()
|
|
with patch.object(workload, 'adversarial_preflight', side_effect=workload.WorkloadError('missing')):
|
|
with self.assertRaises(workload.WorkloadError): instance.run_workloads(self.document)
|
|
with patch.object(workload, 'adversarial_preflight', return_value={'runtime_source_tree_hash': 'stale'}):
|
|
with self.assertRaises(workload.WorkloadError): instance.run_workloads(self.document)
|
|
instance.hardware.assert_not_called()
|
|
with tempfile.TemporaryDirectory() as folder:
|
|
with self.assertRaises(workload.WorkloadError): workload.adversarial_preflight(Path(folder) / 'missing-packet.json')
|
|
|
|
def test_recovery_prepares_the_recreated_callers_raw_leaf_before_faulting(self):
|
|
for browse_ready in (True, False):
|
|
with self.subTest(browse_ready=browse_ready), tempfile.TemporaryDirectory() as folder:
|
|
events = Mock()
|
|
runner = object.__new__(workload.WorkloadRunner)
|
|
previous_manifest = {'source_tree_hash': 'current', 'consumer': 'consumer-2'}
|
|
refreshed_manifest = {**previous_manifest, 'run_id': 'test', 'consumer': 'consumer-1', 'source': 'source-1'}
|
|
runner.manifest = previous_manifest
|
|
runner.rig = SimpleNamespace(folder=Path(folder), load=Mock(return_value=refreshed_manifest),
|
|
seed_helper=Mock(), hub_partitions=lambda _: nullcontext())
|
|
|
|
@contextmanager
|
|
def compact_batches(enabled):
|
|
events.recreate_consumers(enabled)
|
|
yield
|
|
|
|
runner.rig.compact_batches = compact_batches
|
|
runner.primary = lambda pair: runner.manifest[pair]
|
|
runner.hardware = Mock()
|
|
runner.save = Mock()
|
|
runner.baseline = events.baseline
|
|
runner.probe = events.probe
|
|
runner.wait_connection_ready = events.wait_connection_ready
|
|
runner.cli = events.cli
|
|
runner.changing = events.changing
|
|
runner.changing.return_value = nullcontext()
|
|
runner.live_cli_fault = events.live_cli_fault
|
|
runner.wait_pair_topology = events.wait_pair_topology
|
|
runner.settle = events.settle
|
|
runner.settle.side_effect = workload.WorkloadError('stop after recovery preflight')
|
|
if not browse_ready:
|
|
runner.cli.side_effect = workload.ScenarioError('projected leaf missing from Browse')
|
|
|
|
with patch.object(workload, 'adversarial_preflight', return_value={'runtime_source_tree_hash': 'current'}):
|
|
report = runner.run_workloads(self.document, selected=['recovery'])
|
|
|
|
expected = [call.recreate_consumers(True), call.probe('consumer-1', 'read'),
|
|
call.probe('consumer-1', 'metadata'), call.wait_connection_ready('consumer-1', 'raw'),
|
|
call.cli('browse', 'consumer-1', 'raw', recursive=True)]
|
|
if browse_ready:
|
|
expected.extend([call.changing(), call.live_cli_fault('consumer-1', 'source-1', require_gap=True),
|
|
call.wait_pair_topology('source'),
|
|
call.settle('consumer-1', self.document['accounting'])])
|
|
self.assertEqual(expected + [call.baseline()], events.mock_calls)
|
|
row = report['rows'][0]
|
|
self.assertEqual(row['failure'], 'WorkloadError: stop after recovery preflight' if browse_ready
|
|
else 'ScenarioError: projected leaf missing from Browse')
|
|
self.assertTrue(row['restored'])
|
|
self.assertFalse(row['passed'])
|
|
|
|
|
|
if __name__ == '__main__':
|
|
unittest.main()
|