| index db814c9fa..776078f06 100644 |
| --- a/scripts/region_ha_g2_probe_test.py |
| +++ b/scripts/region_ha_g2_probe_test.py |
| @@ -10,6 +10,7 @@ import subprocess |
| import sys |
| import tempfile |
| import threading |
| +import time |
| import unittest |
| from unittest.mock import patch |
| |
| @@ -24,7 +25,7 @@ SOURCE = (SCRIPT.parent / 'fixture/main.go').read_text() |
| FORMAT = json.loads(re.search(r'ResponseFormat\s*=\s*("[^"\n]*")', SOURCE)[1]) |
| RANGES_FORMAT = json.loads(re.search(r'RangesFormat\s*=\s*("[^"\n]*")', SOURCE)[1]) |
| KEYS = {'t', 'kind', 'fixture', 'entry', 'rid', 'rid_echo', 'status', |
| - 'box', 'hits', 'max', 'ms', 'err'} |
| + 'box', 'hits', 'max', 'ms', 'err', 'curl_exit', 'slot', 'slot_utc'} |
| |
| |
| class FakeClock: |
| @@ -57,7 +58,8 @@ class FakeRunner: |
| return subprocess.CompletedProcess(command, 0, body + '\n' + json.dumps( |
| {'http_code': 200, 'time_total': 0.025}), '') |
| assert command[0] == 'aws', command |
| - return subprocess.CompletedProcess(command, 0, json.dumps(self.lock), '') |
| + Path(command[-1]).write_text(json.dumps(self.lock)) |
| + return subprocess.CompletedProcess(command, 0, '{"ContentLength": 123}', '') |
| |
| |
| class ProbeTests(unittest.TestCase): |
| @@ -73,7 +75,7 @@ class ProbeTests(unittest.TestCase): |
| self.args = ['--fixture', 'example.com', '--entry', 'nlb-a=192.0.2.10', |
| '--write-entry', 'nlb-a', '--bucket', 'example-data', |
| '--profile', 'example', '--region', 'eu-west-1', |
| - '--duration', '3', '--out', str(self.out)] |
| + '--duration', '3', '--write-base', '0', '--out', str(self.out)] |
| self.block = patch.object(probe.subprocess, 'run', side_effect=AssertionError('Real process used.')) |
| self.block.start() |
| self.addCleanup(self.block.stop) |
| @@ -88,6 +90,7 @@ class ProbeTests(unittest.TestCase): |
| self.assertEqual(set(row), KEYS) |
| self.assertIsNone(row['status']) |
| self.assertEqual(row['err'], 'timeout') |
| + self.assertEqual(row['curl_exit'], 28) |
| self.assertIsNone(row['box']) |
| self.assertFalse(row['rid_echo']) |
| self.assertEqual(row['ms'], 5000) |
| @@ -106,17 +109,77 @@ class ProbeTests(unittest.TestCase): |
| self.assertIsNone(row['status']) |
| self.assertEqual(row['err'], 'timeout') |
| |
| - def test_slow_requests_skip_missed_slots(self): |
| - config = probe.parse_args(self.args + ['--duration', '8']) |
| - job = probe.Probe(config, runner=self.fake, clock=self.clock, out=self.stdout) |
| - job.start, job.end = 0, 8 |
| - starts = [] |
| - |
| - def slow_request(): |
| - starts.append(self.clock.monotonic()) |
| - self.clock.sleep(2.2) |
| - job.periodic(1, slow_request) |
| - self.assertEqual(starts, [0, 3, 6]) |
| + def test_five_second_curl_records_every_slot(self): |
| + started = [] |
| + active = peak = 0 |
| + mutex = threading.Lock() |
| + |
| + def slow_curl(command, **kwargs): |
| + nonlocal active, peak |
| + if command[0] != 'curl': |
| + return self.fake(command, **kwargs) |
| + with mutex: |
| + started.append((command[-1], time.monotonic())) |
| + active += 1 |
| + peak = max(peak, active) |
| + time.sleep(5) |
| + with mutex: |
| + active -= 1 |
| + return subprocess.CompletedProcess(command, 28, '\n{"http_code":"000","time_total":5}', '') |
| + |
| + self.assertEqual(probe.main(self.args + ['--duration', '6.2'], runner=slow_curl, |
| + clock=probe.Clock(), out=self.stdout), 0) |
| + rows = [json.loads(line) for line in self.out.read_text().splitlines()] |
| + for kind in ('get', 'write'): |
| + stream = sorted((row for row in rows if row['kind'] == kind), key=lambda row: row['slot']) |
| + self.assertEqual([row['slot'] for row in stream], list(range(7))) |
| + self.assertTrue(all(row['curl_exit'] == 28 for row in stream)) |
| + stamps = [datetime.fromisoformat(row['slot_utc']) for row in stream] |
| + self.assertEqual([(t - stamps[0]).total_seconds() for t in stamps], list(range(7))) |
| + sends = sorted(t for url, t in started if ('write?' in url) == (kind == 'write')) |
| + self.assertEqual(len(sends), 7) |
| + for slot, sent in enumerate(sends): |
| + self.assertAlmostEqual(sent - sends[0], slot, delta=0.5) |
| + self.assertGreater(peak, 2) |
| + self.assertLessEqual(peak, 12) |
| + self.assertNotIn('"kind": "skipped"', self.out.read_text()) |
| + self.assertIn('Expected slots: 7. Recorded slots: 7. Skipped slots: 0. Missing slots: 0.', self.stdout.getvalue()) |
| + self.assertIn('Longest run of non-200 responses in seconds: 7.', self.stdout.getvalue()) |
| + |
| + def test_in_flight_cap_emits_every_skipped_slot(self): |
| + config = probe.parse_args(self.args + ['--duration', '9']) |
| + release = threading.Event() |
| + calls = [] |
| + |
| + def blocked(command, **kwargs): |
| + calls.append(command) |
| + if not release.wait(3): |
| + raise AssertionError('The scheduler waited for a request.') |
| + return self.fake(command, **kwargs) |
| + |
| + job = probe.Probe(config, runner=blocked, clock=self.clock, out=self.stdout) |
| + job.start, job.end, job.started_at, job.write_base = 0, 9, NOW, 0 |
| + job.evidence = io.StringIO() |
| + record = job.record |
| + |
| + def observed(row): |
| + record(row) |
| + if row['slot'] == 8: |
| + release.set() |
| + |
| + job.record = observed |
| + try: |
| + job.http_loop('example.com', 'nlb-a') |
| + finally: |
| + release.set() |
| + rows = [json.loads(line) for line in job.evidence.getvalue().splitlines()] |
| + self.assertEqual(len(calls), 6) |
| + self.assertEqual(sorted(row['slot'] for row in rows), list(range(9))) |
| + skips = [row for row in rows if row['kind'] == 'skipped'] |
| + self.assertEqual([row['slot'] for row in skips], [6, 7, 8]) |
| + self.assertTrue(all(row['reason'] == 'in_flight_cap' for row in skips)) |
| + job.summary.print(self.stdout) |
| + self.assertIn('Expected slots: 9. Recorded slots: 6. Skipped slots: 3. Missing slots: 0.', self.stdout.getvalue()) |
| |
| def test_get_write_schema_and_echo(self): |
| for n in (None, 9): |
| @@ -181,8 +244,14 @@ class ProbeTests(unittest.TestCase): |
| aws = probe.AWSRunner('example', 'eu-west-1', runner=self.fake) |
| for body in ('null', '[]', '{}', '{', '{"generation":true}', '{"expires_at":false}'): |
| self.assertEqual(probe.classify_lock(body, NOW)['state'], 'lock_invalid') |
| - for stderr, state in [('(NoSuchKey)', 'lock_absent'), ('(AccessDenied)', 'read_error'), |
| - ('(NoSuchBucket)', 'read_error'), ('connect timeout', 'read_error')]: |
| + # pool-readiness.py:AWSRunner handles GetObject NoSuchKey as absence. |
| + for stderr, state in [ |
| + ('An error occurred (NoSuchKey) when calling the GetObject operation: The specified key does not exist.', 'lock_absent'), |
| + ('An error occurred (404) when calling the GetObject operation: Not Found', 'lock_absent'), |
| + ('An error occurred (AccessDenied) when calling the GetObject operation: Access Denied', 'read_error'), |
| + ('An error occurred (NoSuchBucket) when calling the GetObject operation: The specified bucket does not exist', 'read_error'), |
| + ('An error occurred (404) when calling the HeadObject operation: Key "lock.json" does not exist', 'read_error'), |
| + ('connect timeout', 'read_error')]: |
| self.fake.response = subprocess.CompletedProcess([], 1, '', stderr) |
| row = probe.lock_record('example.com', 'example-data', 'instances', aws=aws, clock=self.clock) |
| self.assertEqual(row['state'], state) |
| @@ -190,16 +259,15 @@ class ProbeTests(unittest.TestCase): |
| |
| def test_aws_runner_refuses_other_verbs_and_destinations(self): |
| aws = probe.AWSRunner('example', 'eu-west-1', runner=self.fake) |
| - for verb, source, dest in [('rm', 's3://example-data/lock.json', '-'), |
| - ('cp', '-', 's3://example-data/lock.json'), |
| - ('cp', 's3://example-data/lock.json', 'file'), |
| - ('sync', 's3://example-data/', '-')]: |
| + for verb in ('cp', 'rm', 'sync', 'put-object', 'delete-object', 'list-objects-v2'): |
| with self.assertRaises(ValueError): |
| - aws(verb, source, dest) |
| + aws(verb, bucket='example-data', key='lock.json') |
| self.assertEqual(self.fake.calls, []) |
| - aws('cp', 's3://example-data/instances/example.com/lock.json', '-') |
| + aws('get-object', bucket='example-data', key='instances/example.com/lock.json') |
| command, opts = self.fake.calls[0] |
| - self.assertEqual(command[-4:], ['s3', 'cp', 's3://example-data/instances/example.com/lock.json', '-']) |
| + self.assertEqual(command[-7:-1], ['s3api', 'get-object', '--bucket', 'example-data', |
| + '--key', 'instances/example.com/lock.json']) |
| + self.assertFalse(Path(command[-1]).exists()) |
| self.assertEqual(opts['env']['AWS_MAX_ATTEMPTS'], '1') |
| self.assertEqual(opts['env']['AWS_EC2_METADATA_DISABLED'], 'true') |
| |
| @@ -225,10 +293,27 @@ class ProbeTests(unittest.TestCase): |
| status = probe.main(self.args + ['--duration', '101', '--max-lock-gets', '20'], |
| runner=self.fake, clock=self.clock, out=self.stdout) |
| self.assertEqual(status, 2) |
| - self.assertIn('Lock GET budget exceeded.', self.stdout.getvalue()) |
| + self.assertIn('Lock GET estimate 21 exceeds the cap of 20.', self.stdout.getvalue()) |
| self.assertEqual(self.fake.calls, []) |
| self.assertFalse(self.out.exists()) |
| |
| + def test_budget_rounds_up_per_fixture(self): |
| + status = probe.main(self.args + ['--fixture', 'second.example.com', '--duration', '1', |
| + '--max-lock-gets', '1'], |
| + runner=self.fake, clock=self.clock, out=self.stdout) |
| + self.assertEqual(status, 2) |
| + self.assertEqual(self.stdout.getvalue(), 'Lock GET estimate 2 exceeds the cap of 1.\n') |
| + self.assertFalse(self.out.exists()) |
| + self.assertEqual(self.fake.calls, []) |
| + |
| + def test_curl_exit_codes_are_preserved(self): |
| + for code in (7, 35, 52, 56): |
| + self.fake.response = subprocess.CompletedProcess([], code, '\n{"http_code":"000","time_total":0.1}', '') |
| + row = self.http() |
| + self.assertEqual(row['curl_exit'], code) |
| + self.assertIsNone(row['status']) |
| + self.assertEqual(row['err'], 'curl_error') |
| + |
| def test_cap_stops_only_locks_once(self): |
| config = probe.parse_args(self.args + ['--duration', '7', '--max-lock-gets', '2']) |
| job = probe.Probe(config, runner=self.fake, clock=self.clock, out=self.stdout) |
| @@ -239,15 +324,18 @@ class ProbeTests(unittest.TestCase): |
| self.assertEqual(sum(r['kind'] == 'get' for r in rows), 7) |
| self.assertEqual(sum(r['kind'] == 'write' for r in rows), 7) |
| self.assertEqual(self.stdout.getvalue().count('Lock reader stopped at the cap.'), 1) |
| + notes = [r for r in rows if r.get('reason') == 'lock_cap'] |
| + self.assertEqual(len(notes), 1) |
| + self.assertEqual(notes[0]['message'], 'Lock reader stopped at the cap.') |
| |
| def test_http_and_lock_cadence(self): |
| self.assertEqual(probe.main(self.args + ['--duration', '11'], |
| runner=self.fake, clock=self.clock, out=self.stdout), 0) |
| rows = [json.loads(line) for line in self.out.read_text().splitlines()] |
| for kind, ticks in [('get', list(range(11))), ('write', list(range(11))), ('lock', [0, 5, 10])]: |
| - times = [(datetime.fromisoformat(row['t'].replace('Z', '+00:00')) - NOW).total_seconds() |
| + times = [(datetime.fromisoformat(row['slot_utc'].replace('Z', '+00:00')) - NOW).total_seconds() |
| for row in rows if row['kind'] == kind] |
| - self.assertEqual(times, ticks, kind) |
| + self.assertEqual(sorted(times), ticks, kind) |
| |
| def test_exclusive_evidence_files(self): |
| for path in (self.out, Path(str(self.out) + '.acks')): |
| @@ -257,16 +345,16 @@ class ProbeTests(unittest.TestCase): |
| self.assertEqual(status, 2) |
| self.assertEqual(path.read_text(), 'Original evidence.\n') |
| self.assertEqual(self.fake.calls, []) |
| + other = Path(str(self.out) + '.acks') if path == self.out else self.out |
| + self.assertFalse(other.exists()) |
| path.unlink() |
| - if self.out.exists(): |
| - self.out.unlink() |
| |
| def test_threads_jsonl_acks_and_compare(self): |
| args = self.args + ['--entry', 'backhaul=192.0.2.20', '--fixture', 'second.example.com'] |
| self.assertEqual(probe.main(args, runner=self.fake, clock=self.clock, out=self.stdout), 0) |
| rows = [json.loads(line) for line in self.out.read_text().splitlines()] |
| - self.assertEqual(len(rows), 20) |
| - self.assertEqual(len({r['rid'] for r in rows if r['kind'] != 'lock'}), 18) |
| + self.assertEqual(len(rows), 21) |
| + self.assertEqual(len({r['rid'] for r in rows if r['kind'] in ('get', 'write')}), 18) |
| self.assertEqual(json.loads(Path(str(self.out) + '.acks').read_text()), |
| {'example.com': [1, 2, 3], 'second.example.com': [1, 2, 3]}) |
| self.assertIn('Summary for example.com through backhaul (get).', self.stdout.getvalue()) |
| @@ -279,6 +367,95 @@ class ProbeTests(unittest.TestCase): |
| self.assertIn('Lost acknowledged writes for example.com: [2].', self.stdout.getvalue()) |
| self.assertIn('Lost acknowledged writes for second.example.com: [3].', self.stdout.getvalue()) |
| |
| + def test_second_run_uses_new_numbers_and_compare_rebuilds(self): |
| + stored = set(range(1, 4)) |
| + writes = [] |
| + |
| + def fixture(command, **kwargs): |
| + if command[0] == 'curl' and '/write?n=' in command[-1]: |
| + n = int(command[-1].split('=')[-1]) |
| + writes.append(n) |
| + stored.add(n) |
| + return self.fake(command, **kwargs) |
| + |
| + args = self.args.copy() |
| + at = args.index('--write-base') |
| + del args[at:at + 2] |
| + self.assertEqual(probe.main(args, runner=fixture, clock=self.clock, out=self.stdout), 0) |
| + base = int(NOW.timestamp()) * 1000000 |
| + expected = [base + n for n in (1, 2, 3)] |
| + self.assertEqual(sorted(writes), expected) |
| + self.assertEqual(len(stored), 6) |
| + ack_path = Path(str(self.out) + '.acks') |
| + self.assertEqual(json.loads(ack_path.read_text()), {'example.com': expected}) |
| + ranges = Path(self.tmp.name) / 'ranges.txt' |
| + ranges.write_text(f'1-3,{base + 1},{base + 3}') |
| + compare_args = ['--out', str(self.out), '--compare', str(ranges)] |
| + # Stale acknowledgements outside this run must never count as losses. |
| + ack_path.write_text(json.dumps({'example.com': [99] + expected})) |
| + for rebuild in ('saved', 'empty', 'missing'): |
| + if rebuild == 'empty': |
| + ack_path.write_text('') |
| + elif rebuild == 'missing': |
| + ack_path.unlink() |
| + output = io.StringIO() |
| + self.assertEqual(probe.main(compare_args, out=output), 0) |
| + self.assertEqual(output.getvalue(), f'Lost acknowledged writes for example.com: [{base + 2}].\n') |
| + # A later invocation shares the database but must use a different range. |
| + later = FakeClock() |
| + later.now = lambda: NOW + timedelta(seconds=1) |
| + second = Path(self.tmp.name) / 'second.jsonl' |
| + writes.clear() |
| + self.assertEqual(probe.main(args + ['--out', str(second)], runner=fixture, |
| + clock=later, out=self.stdout), 0) |
| + self.assertEqual(sorted(writes), [base + 1000000 + n for n in (1, 2, 3)]) |
| + self.assertEqual(len(stored), 9) |
| + |
| + def test_worker_failure_is_evidence_and_acks_use_jsonl(self): |
| + def broken(command, **kwargs): |
| + if command[0] == 'curl' and '/write?n=2' in command[-1]: |
| + raise RuntimeError('Synthetic failure.') |
| + return self.fake(command, **kwargs) |
| + |
| + self.assertEqual(probe.main(self.args, runner=broken, clock=self.clock, out=self.stdout), 2) |
| + rows = [json.loads(line) for line in self.out.read_text().splitlines()] |
| + notes = [row for row in rows if row.get('reason') == 'worker_failed'] |
| + self.assertEqual(len(notes), 1) |
| + self.assertEqual(notes[0]['failed_slot'], 1) |
| + writes = [row for row in rows if row['kind'] == 'write'] |
| + self.assertEqual(sorted(row['slot'] for row in writes), [0, 1, 2]) |
| + self.assertEqual(json.loads(Path(str(self.out) + '.acks').read_text()), {'example.com': [1, 3]}) |
| + |
| + def test_summary_counts_slot_span_in_completion_order(self): |
| + summary = probe.Summary(['example.com'], 7) |
| + # Slot 2 is missing, slot 3 is skipped, and completions arrive out of order. |
| + for slot, status in [(6, 200), (5, None), (0, 200), (1, 503), (4, 503)]: |
| + row = self.http() |
| + row.update(slot=slot, status=status) |
| + summary.add(row) |
| + summary.add(dict(kind='skipped', stream='get', fixture='example.com', entry='nlb-a', slot=3)) |
| + item = summary.metrics(summary.rows['example.com', 'nlb-a', 'get']) |
| + self.assertEqual(item, dict(expected=7, recorded=5, skipped=[3], missing=[2], longest=5)) |
| + |
| + def test_released_marker_without_iid_keeps_ref(self): |
| + lock = dict(FIXTURES['locks']['marker_clean']) |
| + lock['owner'] = 'released/v1;ref=fixture-box' |
| + row = probe.classify_lock(json.dumps(lock), NOW) |
| + self.assertEqual(row['state'], 'marker_clean') |
| + self.assertEqual(row['ref'], 'fixture-box') |
| + self.assertIsNone(row['iid']) |
| + |
| + def test_unconfirmed_writes_are_not_rebuilt_as_acks(self): |
| + self.assertEqual(probe.main(self.args, runner=self.fake, clock=self.clock, out=self.stdout), 0) |
| + rows = [json.loads(line) for line in self.out.read_text().splitlines()] |
| + for row in rows: |
| + if row['kind'] == 'write' and row['n'] == 2: |
| + row['rid_echo'] = False |
| + if row['kind'] == 'write' and row['n'] == 3: |
| + row['err'] = 'timeout' |
| + self.out.write_text(''.join(json.dumps(row) + '\n' for row in rows)) |
| + self.assertEqual(probe.evidence_acks(self.out)[0], {'example.com': [1]}) |
| + |
| def test_compare_exact_ranges_and_refusals(self): |
| self.assertEqual(probe.lost_acks([1, 2, 3, 4, 8, 9], RANGES_FORMAT % '1-3,8'), [4, 9]) |
| self.assertEqual(probe.lost_acks([1, 9], ''), [1, 9]) |
| @@ -300,8 +477,10 @@ class ProbeTests(unittest.TestCase): |
| aws = directory / 'aws' |
| aws.write_text('#!' + sys.executable + '\n' + |
| 'import sys\n' + |
| - 'assert sys.argv[-4:-2] == ["s3", "cp"] and sys.argv[-1] == "-"\n' + |
| - 'print(' + repr(json.dumps(FIXTURES['locks']['held'])) + ')\n') |
| + 'from pathlib import Path\n' + |
| + 'assert sys.argv[-7:-5] == ["s3api", "get-object"]\n' + |
| + 'Path(sys.argv[-1]).write_text(' + repr(json.dumps(FIXTURES['locks']['held'])) + ')\n' + |
| + 'print(123)\n') |
| curl.chmod(0o700) |
| aws.chmod(0o700) |
| result = RUN_PROCESS([sys.executable, str(SCRIPT), *self.args, '--duration', '0.2'], |
| @@ -309,12 +488,14 @@ class ProbeTests(unittest.TestCase): |
| stdin=subprocess.DEVNULL, capture_output=True, text=True, timeout=10) |
| self.assertEqual(result.returncode, 0, result.stdout + result.stderr) |
| rows = [json.loads(line) for line in self.out.read_text().splitlines()] |
| - self.assertEqual({row['kind'] for row in rows}, {'get', 'write', 'lock'}) |
| - self.assertEqual(len(rows), 3) |
| + self.assertEqual({row['kind'] for row in rows}, {'get', 'write', 'lock', 'note'}) |
| + self.assertEqual(len(rows), 4) |
| self.assertTrue(all(row['err'] is None for row in rows)) |
| self.assertEqual(json.loads(Path(str(self.out) + '.acks').read_text()), {'example.com': [1]}) |
| |
| def test_comparison_missing_fixture_and_bad_ack_file_refuse(self): |
| + self.assertEqual(probe.main(self.args, runner=self.fake, clock=self.clock, out=self.stdout), 0) |
| + self.fake.calls.clear() |
| ack_path = Path(str(self.out) + '.acks') |
| ranges = Path(self.tmp.name) / 'ranges.json' |
| args = ['--out', str(self.out), '--compare', str(ranges)] |
| @@ -327,21 +508,23 @@ class ProbeTests(unittest.TestCase): |
| self.assertEqual(self.fake.calls, []) |
| |
| def test_summary_tracks_consecutive_failures_and_only_confirmed_acks(self): |
| - summary = probe.Summary(['example.com']) |
| + summary = probe.Summary(['example.com'], 9) |
| for n, status in enumerate((200, None, 503, 200, 502, 503, None), 1): |
| row = self.http(n=n) |
| row['status'] = status |
| + row['slot'] = n - 1 |
| summary.add(row) |
| row = self.http(n=8) |
| row['rid_echo'] = False |
| + row['slot'] = 7 |
| summary.add(row) |
| row = self.http(n=9) |
| row['err'] = 'timeout' |
| + row['slot'] = 8 |
| summary.add(row) |
| - self.assertEqual(summary.acks, {'example.com': {1, 4}}) |
| summary.print(self.stdout) |
| text = self.stdout.getvalue() |
| - self.assertIn('Longest run of non-200 responses: 3.', text) |
| + self.assertIn('Longest run of non-200 responses in seconds: 3.', text) |
| self.assertIn('"503": 2', text) |
| self.assertIn('"fixture-box": 9', text) |
| |