perf: measure grpc fanout and recovery bounds

This commit is contained in:
Joseph Doherty
2026-11-17 22:01:27 -05:00
parent 29fec57fac
commit 4cf3acb1c5
14 changed files with 3444 additions and 0 deletions
@@ -0,0 +1,134 @@
import copy
import importlib.util
import json
import os
from pathlib import Path
import sys
import tempfile
import unittest
from unittest.mock import patch
HERE = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(HERE))
spec = importlib.util.spec_from_file_location('p11_adversarial_tests', HERE / 'run-p11-adversarial.py')
gate = importlib.util.module_from_spec(spec)
spec.loader.exec_module(gate)
class P11AdversarialTests(unittest.TestCase):
def fixture(self, root):
project = 'tests/Example/Example.Tests.csproj'
source = 'tests/Example/Cases.cs'
(root / source).parent.mkdir(parents=True)
(root / source).write_text('namespace Example; class Cases { public void Case() {} }')
(root / project).write_text('<Project/>')
case = {'source': source, 'project': project, 'selector': 'Example.Cases.Case'}
return {'schema_version': 1, 'obligations': [{'id': 'test-obligation', 'description': 'Actual deterministic assertion', 'tests': [case]}]}
def trx(self, root, outcome='Passed', name='Example.Cases.Case', suffix=''):
path = root / ('results' + suffix + '.trx')
path.write_text(f'<TestRun><TestDefinitions><UnitTest id="1"><TestMethod className="Example.Cases" name="Case"/></UnitTest></TestDefinitions><Results><UnitTestResult testId="1" testName="{name}" outcome="{outcome}"><Output><ErrorInfo><Message>reason</Message></ErrorInfo></Output></UnitTestResult></Results></TestRun>')
return path
def test_registry_covers_every_obligation_with_exact_methods_and_source_paths(self):
document = gate.registry()
self.assertEqual(gate.REQUIRED, {row['id'] for row in document['obligations']})
for obligation in document['obligations']:
self.assertTrue(obligation['tests'])
for case in obligation['tests']:
self.assertNotIn('~', case['selector'])
self.assertTrue(case['project'].endswith('.csproj'))
def test_only_exact_selected_projects_methods_are_executed(self):
cases = [{'selector': 'Example.Cases.First'}, {'selector': 'Example.Cases.Second'}]
discovery, execute = gate.commands('tests/Example/Example.Tests.csproj', cases, '/private/trx')
self.assertEqual(execute[:3], ['dotnet', 'test', 'tests/Example/Example.Tests.csproj'])
expression = execute[execute.index('--filter') + 1]
self.assertEqual(expression, 'FullyQualifiedName=Example.Cases.First|FullyQualifiedName=Example.Cases.Second')
self.assertNotIn('Category', expression)
self.assertNotIn('--no-build', discovery)
self.assertIn('--no-build', execute)
def test_consumer_role_continuity_registers_all_exact_methods(self):
obligation = next(row for row in gate.registry()['obligations'] if row['id'] == 'consumer-role-continuity')
methods = {case['selector'].rsplit('.', 1)[-1] for case in obligation['tests']}
self.assertEqual(methods, {
'Hot_eligible_role_transitions_preserve_the_existing_route_but_epoch_aba_invalidates_it',
'Host_effective_non_hot_mode_drains_even_when_artifact_is_hot',
'Retained_metadata_guard_survives_borrower_disposal_but_not_unobserved_epoch_loss',
'Non_hot_retained_metadata_does_not_revive_after_missed_ineligible_transition',
'Read_epoch_is_stable_between_known_roles_and_changes_on_unknown_and_owner_replacement',
'Hot_retained_guard_reads_role_without_waiting_for_dispatch_fence',
'Healthy_origin_catalog_stays_ready_while_another_thread_holds_the_dispatch_fence',
})
def test_actual_passes_need_nonzero_discovery_and_all_theory_rows(self):
with tempfile.TemporaryDirectory() as folder:
root = Path(folder); document = self.fixture(root)
self.trx(root, name='Example.Cases.Case(value: 1)')
rows = gate.result_rows(root)
discovery = {'Example.Cases.Case': ['Example.Cases.Case(value: 1)']}
self.assertTrue(gate.reconcile(document, discovery, rows, root)['passed'])
discovery['Example.Cases.Case'].append('Example.Cases.Case(value: 2)')
self.assertFalse(gate.reconcile(document, discovery, rows, root)['passed'])
self.assertFalse(gate.reconcile(document, {}, rows, root)['passed'])
self.assertFalse(gate.reconcile(document, discovery, [], root)['passed'])
def test_skipped_failed_and_missing_source_never_become_synthetic_passes(self):
for outcome in ('NotExecuted', 'Failed', 'Inconclusive'):
with self.subTest(outcome=outcome), tempfile.TemporaryDirectory() as folder:
root = Path(folder); document = self.fixture(root); self.trx(root, outcome)
report = gate.reconcile(document, {'Example.Cases.Case': ['Example.Cases.Case']}, gate.result_rows(root), root)
self.assertFalse(report['passed'])
with tempfile.TemporaryDirectory() as folder:
root = Path(folder); document = self.fixture(root); self.trx(root)
(root / document['obligations'][0]['tests'][0]['source']).unlink()
report = gate.reconcile(document, {'Example.Cases.Case': ['Example.Cases.Case']}, gate.result_rows(root), root)
self.assertFalse(report['passed'])
self.assertEqual(len(report['source_gaps']), 1)
def test_unexpected_method_is_a_failure(self):
with tempfile.TemporaryDirectory() as folder:
root = Path(folder); document = self.fixture(root); self.trx(root)
rows = gate.result_rows(root)
rows.append({**rows[0], 'selector': 'Example.Cases.Other'})
self.assertFalse(gate.reconcile(document, {'Example.Cases.Case': ['Example.Cases.Case']}, rows, root)['passed'])
def test_packet_rechecks_real_trx_hash_and_candidate_not_just_passed_bit(self):
with tempfile.TemporaryDirectory() as folder:
root = Path(folder); document = self.fixture(root); trx = self.trx(root)
registry = root / 'registry.json'; registry.write_text(json.dumps(document))
packet = root / 'packet.json'
identity = {'input_sha256': 'same-candidate', 'runtime_source_tree_hash': 'runtime', 'files': {}}
payload = {'schema_version': 1, 'passed': True, 'registry_sha256': gate.digest(registry), 'identity': identity,
'discovery': {'Example.Cases.Case': ['Example.Cases.Case']}, 'command_exit_codes': {'0-discovery': 0, '0-test': 0},
'trx_files': {str(trx.resolve()): gate.digest(trx)}}
gate.private_json(packet, payload)
real_reconcile = gate.reconcile
with patch.object(gate, 'registry', return_value=document), patch.object(gate, 'input_identity', return_value=identity), patch.object(gate, 'reconcile', side_effect=lambda d, n, r: real_reconcile(d, n, r, root)):
self.assertTrue(gate.checked_packet(packet, registry)['passed'])
self.trx(root, 'NotExecuted')
with self.assertRaises(gate.AdversarialError): gate.checked_packet(packet, registry)
payload['trx_files'][str(trx.resolve())] = gate.digest(trx)
packet.write_text(json.dumps(payload))
with self.assertRaises(gate.AdversarialError): gate.checked_packet(packet, registry)
self.trx(root)
payload['trx_files'][str(trx.resolve())] = gate.digest(trx)
payload['identity'] = {'input_sha256': 'old-candidate'}
packet.write_text(json.dumps(payload))
with self.assertRaises(gate.AdversarialError): gate.checked_packet(packet, registry)
def test_invalid_registry_patterns_or_missing_obligations_fail(self):
document = gate.registry()
with tempfile.TemporaryDirectory() as folder:
path = Path(folder) / 'registry.json'
for mutate in ('pattern', 'missing'):
modified = copy.deepcopy(document)
if mutate == 'pattern': modified['obligations'][0]['tests'][0]['selector'] += '*'
else: modified['obligations'].pop()
path.write_text(json.dumps(modified))
with self.assertRaises(gate.AdversarialError): gate.registry(path)
if __name__ == '__main__':
unittest.main()
@@ -0,0 +1,361 @@
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()