Поставить несколько реплик API за общий балансировщик.

Сессия и ключ идемпотентности общие для реплик, миграция выполняется один раз, остановка одной реплики не теряет подтверждённые сообщения.
This commit is contained in:
2026-10-30 01:15:28 +03:00
parent 0ab3a341aa
commit 59f8c55f93
45 changed files with 3367 additions and 36 deletions
+254
View File
@@ -0,0 +1,254 @@
"""Grade 4 evidence: parallel idempotency, each replica stopped, rolling replace.
Leaves two API replicas running. Does not print tokens.
"""
import json
import subprocess
import sys
import threading
import time
import uuid
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests'))
sys.path.insert(0, str(Path(__file__).resolve().parent))
from client import Client, Failure
import stand
ROOT = stand.ROOT
OUT = ROOT / 'evidence' / 'grade4.json'
def history_texts(client, actor, chat_id):
page = client.call('GET', '/api/v1/chats/%s/messages?limit=100' % chat_id, actor=actor, schema='MessagePage')['json']
return [item['text'] for item in page['items']]
def parallel_same_key(client, alice, chat):
key = uuid.uuid4().hex
text = 'параллельный ключ ' + key[:8]
barrier = threading.Barrier(16)
found = []
def worker():
local = Client(stand.BASE, timeout=5)
barrier.wait()
try:
response = local.message(alice, chat, text, key=key)
found.append(('ok', response['json']['id'], response['headers']['X-Instance-Id']))
except Failure as exc:
found.append(('err', str(exc), ''))
threads = [threading.Thread(target=worker) for _ in range(16)]
for thread in threads:
thread.start()
for thread in threads:
thread.join()
ids = {item[1] for item in found if item[0] == 'ok'}
instances = {item[2] for item in found if item[0] == 'ok'}
texts = history_texts(client, alice, chat['id'])
return {
'attempts': len(found),
'successes': sum(1 for item in found if item[0] == 'ok'),
'errors': sum(1 for item in found if item[0] != 'ok'),
'distinct_message_ids': len(ids),
'history_copies': texts.count(text),
'instances': sorted(instances),
}
def parallel_conflict(client, alice, chat):
key = uuid.uuid4().hex
barrier = threading.Barrier(8)
found = []
def worker(index):
local = Client(stand.BASE, timeout=5)
barrier.wait()
try:
response = local.message(alice, chat, 'вариант-%s-%s' % (key[:6], index), key=key)
found.append(response['status'])
except Failure as exc:
text = str(exc)
found.append(409 if '409' in text else text)
threads = [threading.Thread(target=worker, args=(index,)) for index in range(8)]
for thread in threads:
thread.start()
for thread in threads:
thread.join()
created = sum(1 for item in found if item == 201)
conflicts = sum(1 for item in found if item == 409)
return {'created': created, 'conflicts': conflicts, 'other': [item for item in found if item not in (201, 409)]}
def run_load(alice, chat, seconds, errors, successes, stop_flag):
def worker(worker_id):
local = Client(stand.BASE, timeout=2)
index = 0
while not stop_flag['flag']:
try:
response = local.message(alice, chat, 'нагрузка-%s-%s' % (worker_id, index))
successes.append((time.monotonic(), response['headers']['X-Instance-Id']))
except Failure:
errors.append(time.monotonic())
index += 1
threads = [threading.Thread(target=worker, args=(i,)) for i in range(4)]
for thread in threads:
thread.start()
return threads
def stop_each(alice, chat):
rounds = []
containers = stand.api_containers()
if len(containers) < 2:
raise SystemExit('need 2 running replicas before sequential stop')
for target in containers:
errors, successes = [], []
stop_flag = {'flag': False}
threads = run_load(alice, chat, 0, errors, successes, stop_flag)
time.sleep(2)
before = len(successes)
started = time.monotonic()
subprocess.run(['docker', 'stop', '-t', '6', target['id']], check=True, capture_output=True)
stopped_at = time.monotonic()
deadline = time.monotonic() + 10
recovered = None
while time.monotonic() < deadline:
recent = [item for item in successes if item[0] >= started and item[1] != target['hostname']]
if recent:
recovered = recent[0][0] - started
break
time.sleep(0.1)
time.sleep(2)
stop_flag['flag'] = True
for thread in threads:
thread.join()
after = [item for item in successes if item[0] >= started]
err_after = [item for item in errors if item >= started]
subprocess.run(['docker', 'start', target['id']], check=True, capture_output=True)
back = time.monotonic()
seen_again = False
while time.monotonic() - back < 30:
running = {row['hostname'] for row in stand.api_containers()}
if target['hostname'] in running:
ids = stand.observe_instances(alice, 2, attempts=15)
seen_again = target['hostname'] in ids
if seen_again:
break
time.sleep(0.4)
rounds.append({
'stopped_instance': target['hostname'],
'container': target['name'],
'successful_writes_before_stop': before,
'successful_writes_after_stop_call': len(after),
'failed_attempts_after_stop_call': len(err_after),
'docker_stop_seconds': round(stopped_at - started, 3),
'first_other_instance_seconds': None if recovered is None else round(recovered, 3),
'target_seen_again_after_start': seen_again,
})
stand.wait_ready()
restored = stand.observe_instances(alice, 2, attempts=50)
if len(restored) < 2:
raise SystemExit('replica %s did not return to the load balancer' % target['hostname'])
return rounds
def rolling(alice):
errors = []
successes = []
stop_flag = {'flag': False}
def worker():
local = Client(stand.BASE, timeout=2)
while not stop_flag['flag']:
try:
response = local.call('GET', '/api/v1/users/me', actor=alice, schema='User')
successes.append((time.monotonic(), response['headers']['X-Instance-Id']))
except Failure:
errors.append(time.monotonic())
threads = [threading.Thread(target=worker) for _ in range(4)]
for thread in threads:
thread.start()
time.sleep(1)
started = time.monotonic()
script = ROOT / 'scripts' / 'rolling-replace.sh'
# Windows executes the PowerShell equivalent; the shell script is the Linux procedure.
if os_name_is_windows():
completed = subprocess.run(
['powershell', '-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', str(ROOT / 'scripts' / 'rolling-replace.ps1')],
cwd=ROOT,
text=True,
capture_output=True,
)
else:
completed = subprocess.run(['sh', str(script)], cwd=ROOT, text=True, capture_output=True)
finished = time.monotonic()
time.sleep(2)
stop_flag['flag'] = True
for thread in threads:
thread.join()
during = [item for item in successes if item[0] >= started]
err = [item for item in errors if item >= started]
instances = stand.observe_instances(alice, 2, attempts=40)
return {
'script_exit': completed.returncode,
'elapsed_seconds': round(finished - started, 3),
'successful_reads': len(during),
'failed_reads': len(err),
'instances_after': sorted(instances),
'stderr_tail': (completed.stderr or '')[-400:],
}
def os_name_is_windows():
return sys.platform.startswith('win')
def main():
stand.wait_ready()
client = Client(stand.BASE, timeout=10)
alice, _bob, _eve, chat = client.bootstrap()
seen = stand.observe_instances(alice, 2)
if len(seen) < 2:
raise SystemExit('observed %s instances, need 2' % len(seen))
report = {
'instances_before': sorted(seen),
'parallel_same_key': parallel_same_key(client, alice, chat),
'parallel_different_body': parallel_conflict(client, alice, chat),
'stop_each_replica': stop_each(alice, chat),
'rolling_replace': rolling(alice),
}
same = report['parallel_same_key']
conflict = report['parallel_different_body']
if same['distinct_message_ids'] != 1 or same['history_copies'] != 1:
raise SystemExit('same key created more than one message')
if conflict['created'] != 1 or conflict['other']:
raise SystemExit('different bodies with one key were not one 201 and the rest 409')
for item in report['stop_each_replica']:
if item['first_other_instance_seconds'] is None or item['first_other_instance_seconds'] > 10:
raise SystemExit('replica did not fail over within 10s: %s' % item['stopped_instance'])
if report['rolling_replace']['script_exit'] != 0 or len(report['rolling_replace']['instances_after']) < 2:
raise SystemExit('rolling replace did not leave two instances')
OUT.parent.mkdir(parents=True, exist_ok=True)
OUT.write_text(json.dumps(report, ensure_ascii=False, indent=2) + '\n', encoding='utf-8')
print(json.dumps({
'same_key_ids': same['distinct_message_ids'],
'same_key_instances': same['instances'],
'conflict_created': conflict['created'],
'conflict_409': conflict['conflicts'],
'failovers': [
{'instance': item['stopped_instance'], 'recovery_s': item['first_other_instance_seconds'], 'errors': item['failed_attempts_after_stop_call']}
for item in report['stop_each_replica']
],
'rolling_errors': report['rolling_replace']['failed_reads'],
'rolling_ok': report['rolling_replace']['successful_reads'],
}, ensure_ascii=False, indent=2))
if __name__ == '__main__':
main()
+206
View File
@@ -0,0 +1,206 @@
"""Track 1. Fixed total CPU/RAM, then a growing budget, then one pool change.
The strict cap takes one global lock per message. The shipped default is cap off.
This script measures both and writes evidence/track1.json plus evidence/track1.svg.
"""
import json
import platform
import subprocess
import sys
import threading
import time
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests'))
sys.path.insert(0, str(Path(__file__).resolve().parent))
from client import Client
import stand
ROOT = stand.ROOT
DURATION = 12
CONCURRENCY = 8
RUNS = [
{'series': 'fixed-strict', 'replicas': 1, 'cpus': '1.0', 'memory': '1024M', 'cap': 'strict', 'pool': 4},
{'series': 'fixed-strict', 'replicas': 2, 'cpus': '0.50', 'memory': '512M', 'cap': 'strict', 'pool': 4},
{'series': 'fixed-strict', 'replicas': 4, 'cpus': '0.25', 'memory': '256M', 'cap': 'strict', 'pool': 4},
{'series': 'fixed-off', 'replicas': 1, 'cpus': '1.0', 'memory': '1024M', 'cap': 'off', 'pool': 4},
{'series': 'fixed-off', 'replicas': 2, 'cpus': '0.50', 'memory': '512M', 'cap': 'off', 'pool': 4},
{'series': 'fixed-off', 'replicas': 4, 'cpus': '0.25', 'memory': '256M', 'cap': 'off', 'pool': 4},
{'series': 'grow-off', 'replicas': 1, 'cpus': '0.50', 'memory': '256M', 'cap': 'off', 'pool': 4},
{'series': 'grow-off', 'replicas': 2, 'cpus': '0.50', 'memory': '256M', 'cap': 'off', 'pool': 4},
{'series': 'grow-off', 'replicas': 4, 'cpus': '0.50', 'memory': '256M', 'cap': 'off', 'pool': 4},
{'series': 'pool-16', 'replicas': 4, 'cpus': '0.50', 'memory': '256M', 'cap': 'off', 'pool': 16},
]
def deploy(cfg):
stand.compose(
['up', '-d', '--no-deps', '--force-recreate', '--scale', 'api=%d' % cfg['replicas'], 'api'],
extra_env={
'API_CPUS': cfg['cpus'],
'API_MEMORY': cfg['memory'],
'CAP_MODE': cfg['cap'],
'POOL_MAX': str(cfg['pool']),
'API_REPLICAS': str(cfg['replicas']),
},
)
stand.wait_ready(timeout=120)
def run_load(output):
samples = []
stop = {'flag': False}
def stats():
while not stop['flag']:
try:
samples.append(stand.sample_stats())
except Exception:
pass
time.sleep(2)
thread = threading.Thread(target=stats)
thread.start()
completed = subprocess.run(
[
sys.executable,
str(ROOT / 'tests' / 'load.py'),
'--base-url', stand.BASE,
'--duration', str(DURATION),
'--concurrency', str(CONCURRENCY),
'--output', str(output),
],
cwd=ROOT,
text=True,
capture_output=True,
)
stop['flag'] = True
thread.join()
report = json.loads(output.read_text(encoding='utf-8')) if output.exists() else {}
report['load_exit'] = completed.returncode
if completed.returncode != 0 and 'successful_requests' not in report:
report['stderr_tail'] = (completed.stderr or completed.stdout or '')[-400:]
return report, samples
def svg(rows):
width, height = 920, 420
groups = []
for series in ('fixed-strict', 'fixed-off', 'grow-off', 'pool-16'):
items = [row for row in rows if row['series'] == series]
if items:
groups.append((series, items))
bar_w = 28
gap = 14
group_gap = 36
max_rps = max((row['successful_rps'] or 0) for row in rows) or 1
parts = [
'<svg xmlns="http://www.w3.org/2000/svg" width="%d" height="%d">' % (width, height),
'<rect width="100%" height="100%" fill="#f7f4ee"/>',
'<text x="24" y="32" font-family="sans-serif" font-size="18">Successful RPS, closed loop, %ds, concurrency %d</text>' % (DURATION, CONCURRENCY),
]
x = 48
colors = {
'fixed-strict': '#8c4a3a',
'fixed-off': '#2f6f4e',
'grow-off': '#24577a',
'pool-16': '#a56b12',
}
labels = {
'fixed-strict': 'fixed CPU, strict cap',
'fixed-off': 'fixed CPU, cap off',
'grow-off': 'CPU grows with replicas',
'pool-16': 'pool 16',
}
for series, items in groups:
parts.append('<text x="%d" y="58" font-family="sans-serif" font-size="12">%s</text>' % (x, labels[series]))
for item in items:
rps = item['successful_rps'] or 0
bar_h = int(280 * rps / max_rps)
y = 340 - bar_h
parts.append('<rect x="%d" y="%d" width="%d" height="%d" fill="%s"/>' % (x, y, bar_w, bar_h, colors[series]))
parts.append('<text x="%d" y="%d" font-family="sans-serif" font-size="11">%s</text>' % (x, y - 4, round(rps, 1)))
parts.append('<text x="%d" y="360" font-family="sans-serif" font-size="11">x%d</text>' % (x, item['replicas']))
x += bar_w + gap
x += group_gap
parts.append('<text x="24" y="400" font-family="sans-serif" font-size="12">xN is the API replica count. Fixed series keeps 1.0 CPU and 1024 MiB in total.</text>')
parts.append('</svg>')
return '\n'.join(parts)
def restore():
stand.compose(
['up', '-d', '--no-deps', '--force-recreate', '--scale', 'api=2', 'api'],
extra_env={
'API_CPUS': '0.50',
'API_MEMORY': '512M',
'CAP_MODE': 'off',
'POOL_MAX': '4',
'API_REPLICAS': '2',
},
)
stand.wait_ready(timeout=120)
def main():
info = subprocess.run(['docker', 'info', '--format', '{{.NCPU}} {{.MemTotal}}'], text=True, capture_output=True)
stand.wait_ready()
client = Client(stand.BASE, timeout=10)
alice = client.user('track')
rows = []
for cfg in RUNS:
print('run %s x%s' % (cfg['series'], cfg['replicas']), flush=True)
deploy(cfg)
seen = stand.observe_instances(alice, cfg['replicas'], attempts=60)
output = ROOT / 'evidence' / ('load-%s-%s.json' % (cfg['series'], cfg['replicas']))
report, samples = run_load(output)
rows.append({
'series': cfg['series'],
'replicas': cfg['replicas'],
'cpus_each': cfg['cpus'],
'memory_each': cfg['memory'],
'cap': cfg['cap'],
'pool_max': cfg['pool'],
'instances_seen': len(seen),
'successful_rps': report.get('successful_rps'),
'failed_requests': report.get('failed_requests'),
'successful_requests': report.get('successful_requests'),
'latency_ms': report.get('successful_latency_ms'),
'cpu_api_mean': stand.mean_cpu(samples, '-api-'),
'cpu_postgres_mean': stand.mean_cpu(samples, '-postgres-'),
'cpu_lb_mean': stand.mean_cpu(samples, '-lb-'),
'load_exit': report.get('load_exit'),
})
evidence = {
'hypothesis': 'A global message-cap lock saturates before extra API replicas help. Removing it raises RPS until Postgres or the pool does.',
'profile': {
'tool': 'tests/load.py closed-loop POST messages',
'duration_seconds': DURATION,
'concurrency': CONCURRENCY,
'fixed_total': '1.0 CPU and 1024 MiB split across 1/2/4 replicas',
'grow': '0.50 CPU and 256 MiB per replica, count 1/2/4',
},
'host': {
'platform': platform.platform(),
'python': platform.python_version(),
'cpu_count': os_cpu(),
'docker_info': (info.stdout or '').strip(),
},
'runs': rows,
}
dest = ROOT / 'evidence' / 'track1.json'
dest.write_text(json.dumps(evidence, ensure_ascii=False, indent=2) + '\n', encoding='utf-8')
(ROOT / 'evidence' / 'track1.svg').write_text(svg(rows), encoding='utf-8')
restore()
print(json.dumps(rows, ensure_ascii=False, indent=2))
def os_cpu():
import os
return os.cpu_count()
if __name__ == '__main__':
main()
+138
View File
@@ -0,0 +1,138 @@
"""Helpers for the local compose stand. No tokens are printed or stored."""
import json
import os
import subprocess
import time
import urllib.error
import urllib.request
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
BASE = 'http://127.0.0.1:8080'
def compose(args, extra_env=None, check=True):
env = os.environ.copy()
if extra_env:
env.update({key: str(value) for key, value in extra_env.items()})
command = ['docker', 'compose', '--env-file', str(ROOT / '.env'), *args]
result = subprocess.run(command, cwd=ROOT, env=env, text=True, capture_output=True)
if check and result.returncode != 0:
raise SystemExit((result.stderr or result.stdout or 'compose failed').strip())
return result
def inspect(cid, template):
result = subprocess.run(
['docker', 'inspect', '-f', template, cid],
text=True,
capture_output=True,
check=True,
)
return result.stdout.strip()
def api_containers(running_only=True):
args = ['ps', '-q', 'api'] if running_only else ['ps', '-aq', 'api']
result = compose(args)
found = []
for line in result.stdout.splitlines():
cid = line.strip()
if not cid:
continue
hostname = inspect(cid, '{{.Config.Hostname}}')
name = inspect(cid, '{{.Name}}').lstrip('/')
found.append({'id': cid, 'hostname': hostname, 'name': name})
return found
def wait_ready(timeout=90):
deadline = time.monotonic() + timeout
last = 'none'
while time.monotonic() < deadline:
try:
with urllib.request.urlopen(BASE + '/health/ready', timeout=2) as response:
if response.status == 200 and response.headers.get('X-Instance-Id'):
return response.headers.get('X-Instance-Id')
except (urllib.error.URLError, TimeoutError, OSError) as exc:
last = type(exc).__name__
time.sleep(0.4)
raise SystemExit('load balancer did not become ready (%s)' % last)
def observe_instances(actor, expect, attempts=40):
import sys
sys.path.insert(0, str(ROOT / 'tests'))
from client import Client
seen = set()
client = Client(BASE, timeout=3)
for _ in range(attempts):
try:
seen.add(client.call('GET', '/api/v1/users/me', actor=actor, schema='User')['headers']['X-Instance-Id'])
except Exception:
time.sleep(0.3)
continue
if len(seen) >= expect:
return seen
time.sleep(0.05)
return seen
def started_at():
result = subprocess.run(
['docker', 'ps', '-a', '--filter', 'label=com.docker.compose.project=mtusi-lab3', '--format', '{{.Names}}\t{{.Status}}\t{{.ID}}'],
text=True,
capture_output=True,
check=True,
)
rows = []
for line in result.stdout.splitlines():
if not line.strip():
continue
name = line.split('\t', 1)[0]
rows.append({
'name': name,
'started_at': inspect(name, '{{.State.StartedAt}}'),
'status': inspect(name, '{{.State.Status}}'),
})
return rows
def sample_stats():
result = subprocess.run(
['docker', 'stats', '--no-stream', '--format', '{{json .}}'],
text=True,
capture_output=True,
check=True,
)
rows = []
for line in result.stdout.splitlines():
if not line.strip():
continue
item = json.loads(line)
name = item.get('Name', '')
if 'mtusi-lab3' not in name:
continue
rows.append({
'name': name,
'cpu': item.get('CPUPerc'),
'mem': item.get('MemUsage'),
})
return rows
def mean_cpu(samples, role):
values = []
for sample in samples:
for row in sample:
if role not in row['name']:
continue
text = (row.get('cpu') or '').strip().rstrip('%')
try:
values.append(float(text))
except ValueError:
continue
if not values:
return None
return round(sum(values) / len(values), 2)