create tasks from 5

This commit is contained in:
EgorAnti
2026-11-03 20:49:07 +03:00
parent 6a4cd9534f
commit d235571a52
18 changed files with 1071 additions and 97 deletions
-132
View File
@@ -1,132 +0,0 @@
#!/usr/bin/env python3
"""Stop every observed API replica in turn and record recovery metrics."""
import json
import os
from pathlib import Path
import subprocess
import time
import uuid
from urllib.parse import quote
from client import Client, Failure, arguments, check, run
def executable(path, label):
value = Path(path).expanduser().resolve()
check(value.is_file() and os.access(value, os.X_OK), label + ' must be executable')
return value
def observe_instances(client, actor, attempts=60):
result = set()
for _ in range(attempts):
result.add(client.call(
'GET', '/api/v1/users/me', actor=actor, schema='User'
)['headers']['X-Instance-Id'])
return result
def message_history(client, actor, chat_id):
path = '/api/v1/chats/' + chat_id + '/messages?limit=100'
result = []
for _ in range(1000):
page = client.call(
'GET', path, actor=actor, schema='MessagePage')['json']
result.extend(page['items'])
if page['next_cursor'] is None:
return result
path = ('/api/v1/chats/' + chat_id + '/messages?limit=100&cursor='
+ quote(page['next_cursor'], safe=''))
raise Failure('history pagination exceeded safety bound')
def main():
def configure(parser):
parser.add_argument('--action-script', required=True)
parser.add_argument('--restore-script', required=True)
parser.add_argument('--window', type=float, default=15)
parser.add_argument('--output', default=None)
args = arguments('Sequential failover of every API replica', configure)
check(5 <= args.window <= 60, 'window must be 5..60 seconds')
action = executable(args.action_script, 'action script')
restore = executable(args.restore_script, 'restore script')
client = Client(args.base_url, args.ca_file, timeout=2)
alice, bob, _, chat = client.bootstrap()
targets = sorted(observe_instances(client, alice))
check(len(targets) >= 2, 'expected at least two API replicas')
targets = targets[:2]
summaries = []
for target in targets:
check(target in observe_instances(client, alice),
'target replica is not observable before stop')
env = dict(os.environ)
env['TARGET_INSTANCE_ID'] = target
process = subprocess.Popen(
[str(action)], env=env,
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
started = time.monotonic()
first_recovery = None
reads = writes = failures = 0
confirmed = []
key = uuid.uuid4().hex
text = 'failover-each-' + target + '-' + key
while time.monotonic() - started < args.window:
try:
if (reads + writes) % 2 == 0:
response = client.message(alice, chat, text, key=key)
confirmed.append(response['json'])
writes += 1
key = uuid.uuid4().hex
text = 'failover-each-' + target + '-' + key
else:
client.call('GET', '/api/v1/users/me', actor=bob, schema='User')
reads += 1
if process.poll() == 0 and first_recovery is None:
first_recovery = time.monotonic() - started
except Failure:
failures += 1
time.sleep(0.05)
check(process.wait(timeout=5) == 0, 'stop-one action failed')
elapsed = time.monotonic() - started
check(first_recovery is not None and first_recovery <= 10,
'recovery exceeded 10 seconds')
history = message_history(client, bob, chat['id'])
history_ids = {message['id'] for message in history}
check(all(message['id'] in history_ids for message in confirmed),
'confirmed message disappeared after failover')
summaries.append({
'target_instance_id': target,
'window_seconds': round(elapsed, 3),
'successful_reads': reads,
'successful_writes': writes,
'failed_attempts': failures,
'successful_rps': round((reads + writes) / elapsed, 3),
'first_recovery_seconds': round(first_recovery, 3),
})
check(subprocess.run(
[str(restore)], stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL, timeout=100).returncode == 0,
'restore action failed')
check(target in observe_instances(client, alice),
'stopped replica did not return after restore')
report = {
'scenario': 'sequential failover of each API replica',
'replicas': len(targets),
'results': summaries,
}
output = json.dumps(report, ensure_ascii=False, indent=2)
if args.output:
destination = Path(args.output)
destination.parent.mkdir(parents=True, exist_ok=True)
destination.write_text(output + '\n', encoding='utf-8')
print(output)
if __name__ == '__main__':
run(main)
-49
View File
@@ -1,49 +0,0 @@
#!/usr/bin/env python3
"""Prove that one idempotency scope is shared across API replicas."""
from concurrent.futures import ThreadPoolExecutor
import uuid
from client import Client, arguments, check, run
def main():
args = arguments('Concurrent cross-replica idempotency check')
bootstrap = Client(args.base_url, args.ca_file, timeout=5)
alice, _, _, chat = bootstrap.bootstrap()
key = uuid.uuid4().hex
text = 'Один результат для всех реплик ' + key
path = '/api/v1/chats/' + chat['id'] + '/messages'
def send(_):
client = Client(args.base_url, args.ca_file, timeout=10)
return client.call(
'POST',
path,
201,
actor=alice,
body={'text': text},
headers={'Idempotency-Key': key},
schema='Message')
with ThreadPoolExecutor(max_workers=16) as pool:
responses = list(pool.map(send, range(32)))
messages = [response['json'] for response in responses]
instances = {
response['headers']['X-Instance-Id'] for response in responses
}
check(all(message == messages[0] for message in messages),
'same key returned different messages')
check(len(instances) >= 2,
'requests did not exercise at least two API replicas')
page = bootstrap.call(
'GET', path + '?limit=100', actor=alice, schema='MessagePage')['json']
matches = [item for item in page['items'] if item['id'] == messages[0]['id']]
check(len(matches) == 1, 'idempotent message is missing or duplicated')
print('PASS: 32 concurrent requests used ' + str(len(instances))
+ ' replicas and created one message')
if __name__ == '__main__':
run(main)
-107
View File
@@ -1,107 +0,0 @@
#!/usr/bin/env python3
"""Run closed-loop writes while API replicas are replaced one at a time."""
from concurrent.futures import ThreadPoolExecutor
import json
import math
import os
from pathlib import Path
import subprocess
import threading
import time
from client import Client, Failure, arguments, check, run
def main():
def configure(parser):
parser.add_argument('--action-script', required=True)
parser.add_argument('--duration', type=float, default=180)
parser.add_argument('--concurrency', type=int, default=4)
parser.add_argument('--output', default=None)
args = arguments('Rolling replacement under write load', configure)
check(30 <= args.duration <= 300, 'duration must be 30..300 seconds')
check(1 <= args.concurrency <= 32, 'concurrency must be 1..32')
action = Path(args.action_script).expanduser().resolve()
check(action.is_file() and os.access(action, os.X_OK),
'action script must be executable')
bootstrap = Client(args.base_url, args.ca_file, timeout=5)
alice, _, _, chat = bootstrap.bootstrap()
barrier = threading.Barrier(args.concurrency + 1)
def worker(worker_id):
client = Client(args.base_url, args.ca_file, timeout=5)
barrier.wait()
deadline = time.monotonic() + args.duration
latencies = []
errors = 0
instances = set()
index = 0
while time.monotonic() < deadline:
started = time.monotonic()
try:
response = client.message(
alice, chat, 'rolling-%s-%s' % (worker_id, index))
latencies.append(time.monotonic() - started)
instances.add(response['headers']['X-Instance-Id'])
except Failure:
errors += 1
index += 1
return latencies, errors, instances
started = time.monotonic()
with ThreadPoolExecutor(max_workers=args.concurrency) as pool:
futures = [pool.submit(worker, number)
for number in range(args.concurrency)]
barrier.wait()
time.sleep(3)
action_started = time.monotonic()
process = subprocess.run(
[str(action)], stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL, timeout=args.duration - 5)
action_seconds = time.monotonic() - action_started
check(process.returncode == 0, 'rolling action failed')
results = [future.result() for future in futures]
elapsed = time.monotonic() - started
latencies = sorted(value for values, _, _ in results for value in values)
errors = sum(value for _, value, _ in results)
instances = set().union(*(value for _, _, value in results))
total = len(latencies) + errors
def percentile(fraction):
if not latencies:
return None
index = max(0, math.ceil(fraction * len(latencies)) - 1)
return round(1000 * latencies[index], 3)
report = {
'scenario': 'sequential API replacement under closed-loop writes',
'requested_duration_seconds': args.duration,
'elapsed_seconds': round(elapsed, 3),
'rolling_action_seconds': round(action_seconds, 3),
'concurrency': args.concurrency,
'observed_instance_ids': sorted(instances),
'successful_requests': len(latencies),
'failed_requests': errors,
'error_ratio': round(errors / total, 6) if total else None,
'successful_rps': round(len(latencies) / elapsed, 3),
'successful_latency_ms': {
'p50': percentile(.50),
'p95': percentile(.95),
'p99': percentile(.99),
},
'note': 'Closed-loop result on one host; success latency excludes failures.',
}
output = json.dumps(report, ensure_ascii=False, indent=2)
if args.output:
destination = Path(args.output)
destination.parent.mkdir(parents=True, exist_ok=True)
destination.write_text(output + '\n', encoding='utf-8')
print(output)
check(bool(latencies), 'no successful writes')
check(len(instances) >= 3,
'rolling replacement did not expose replacement instance IDs')
if __name__ == '__main__':
run(main)