Выполнена лабораторная работа 3

This commit is contained in:
2026-11-12 20:51:39 +03:00
parent 0ab3a341aa
commit 21ad522707
142 changed files with 41889 additions and 50 deletions
+16
View File
@@ -0,0 +1,16 @@
from pathlib import Path
import secrets
root = Path(__file__).resolve().parents[1]
directory = root / 'secrets'
directory.mkdir(exist_ok=True)
password_file = directory / 'db_password'
if not password_file.exists():
password_file.write_text(secrets.token_hex(32), encoding='utf-8')
url_file = directory / 'database_url'
if not url_file.exists():
url_file.write_text('postgresql://messenger:' + password_file.read_text().strip() + '@postgres:5432/messenger', encoding='utf-8')
environment = root / '.env'
if not environment.exists():
environment.write_text('API_REPLICAS=2\nAPI_CPUS=0.5\nAPI_MEMORY=256m\nDB_POOL_SIZE=1\nSESSION_TTL_SECONDS=3600\n', encoding='utf-8')
print('Local configuration prepared; existing credentials preserved.')
+32
View File
@@ -0,0 +1,32 @@
import csv
from datetime import datetime, timezone
import json
from research import OUT, benchmark, dataset, deploy, graph
def main():
rows = json.loads((OUT / 'results.json').read_text(encoding='utf-8'))
environment = json.loads((OUT / 'environment.json').read_text(encoding='utf-8'))
environment['confirmation'] = {'date_utc': datetime.now(timezone.utc).isoformat(), 'order': [4, 2, 2, 4], 'duration_seconds': 15, 'concurrency': 24, 'cpu_total': 1, 'memory_total_mb': 512, 'dataset_before': dataset()}
try:
for index, replicas in enumerate((4, 2, 2, 4), 1):
deploy(replicas, 1/replicas, 512//replicas, 8)
print(f'Confirmation {index}/4: {replicas} replicas', flush=True)
result = benchmark(f'confirm-{index}-{replicas}', 15, 24)
rows.append(dict(series='confirmation', replicas=replicas, cpu_each=1/replicas, memory_mb_each=512//replicas, pool=8, repeat=index, **result))
(OUT / 'results.json').write_text(json.dumps(rows, indent=2), encoding='utf-8')
environment['confirmation']['dataset_after'] = dataset()
(OUT / 'environment.json').write_text(json.dumps(environment, indent=2), encoding='utf-8')
graph(rows)
fields = ['series', 'replicas', 'cpu_each', 'memory_mb_each', 'pool', 'repeat', 'concurrency', 'successful_rps', 'failed_requests', 'error_ratio']
with (OUT / 'results.csv').open('w', encoding='utf-8', newline='') as stream:
writer = csv.DictWriter(stream, fieldnames=fields, extrasaction='ignore')
writer.writeheader()
writer.writerows(rows)
finally:
deploy(2, 0.5, 256, 1)
if __name__ == '__main__':
main()
+81
View File
@@ -0,0 +1,81 @@
import argparse
from concurrent.futures import ThreadPoolExecutor
from datetime import datetime, timezone
import json
import math
from pathlib import Path
import sys
import threading
import time
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests'))
from client import Client, Failure, check
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--duration', type=float, default=15)
parser.add_argument('--concurrency', type=int, default=24)
parser.add_argument('--output', required=True)
parser.add_argument('--ready-file')
args = parser.parse_args()
check(1 <= args.duration <= 3600 and 1 <= args.concurrency <= 128, 'invalid load parameters')
startup = time.monotonic()
c = Client()
alice, bob, eve, chat = c.bootstrap()
timing = {}
def warm_start():
timing['warm_deadline'] = time.monotonic() + 3
def measure_start():
timing['started'] = time.monotonic()
timing['started_epoch'] = time.time()
timing['started_utc'] = datetime.now(timezone.utc).isoformat()
timing['deadline'] = timing['started'] + args.duration
if args.ready_file:
Path(args.ready_file).write_text(json.dumps({'measurement_started_epoch': timing['started_epoch']}), encoding='utf-8')
warm_barrier = threading.Barrier(args.concurrency, action=warm_start, timeout=120)
measurement_barrier = threading.Barrier(args.concurrency, action=measure_start, timeout=120)
def worker(index):
client = Client(timeout=5)
warm_barrier.wait()
sequence = 0
while time.monotonic() < timing['warm_deadline']:
try:
client.message(alice, chat, f'warm-{index}-{sequence}')
except Failure:
pass
sequence += 1
measurement_barrier.wait()
latencies, errors = [], 0
while time.monotonic() < timing['deadline']:
started = time.monotonic()
try:
client.message(alice, chat, f'active-{index}-{sequence}')
latencies.append(time.monotonic() - started)
except Failure:
errors += 1
sequence += 1
return latencies, errors
with ThreadPoolExecutor(max_workers=args.concurrency) as executor:
results = list(executor.map(worker, range(args.concurrency)))
elapsed = time.monotonic() - timing['started']
latencies = sorted(value for values, _ in results for value in values)
errors = sum(number for _, number in results)
total = len(latencies) + errors
def percentile(value):
return round(1000 * latencies[max(0, math.ceil(value * len(latencies)) - 1)], 3) if latencies else None
result = {'lab': 3, 'workload': 'closed-loop POST messages; synchronized active window; no retries', 'requested_duration_seconds': args.duration, 'warmup_seconds': 3, 'startup_seconds': round(timing['started']-startup, 3), 'measurement_started_utc': timing['started_utc'], 'measurement_started_epoch': timing['started_epoch'], 'measurement_finished_epoch': time.time(), 'elapsed_seconds': round(elapsed, 3), 'concurrency': args.concurrency, 'successful_requests': len(latencies), 'failed_requests': errors, 'error_ratio': errors/total if total else None, 'successful_rps': round(len(latencies)/elapsed, 3), 'successful_latency_ms': {'p50': percentile(.5), 'p95': percentile(.95), 'p99': percentile(.99)}, 'maximum_successful_latency_ms': round(1000*max(latencies), 3) if latencies else None, 'note': 'Client construction and warmup excluded. Active window includes drain of in-flight requests. Success percentiles only; closed-loop coordinated omission remains.'}
Path(args.output).write_text(json.dumps(result, indent=2) + '\n', encoding='utf-8')
print(json.dumps(result, indent=2))
check(bool(latencies), 'no successful writes')
if __name__ == '__main__':
main()
+68
View File
@@ -0,0 +1,68 @@
import json
import os
from pathlib import Path
import subprocess
import sys
ROOT = Path(__file__).resolve().parents[1]
def docker(*args):
return subprocess.check_output(['docker', *args], cwd=ROOT, text=True).strip()
def containers():
ids = docker('compose', 'ps', '-q', 'api').split()
return json.loads(docker('inspect', *ids)) if ids else []
def main():
mode = sys.argv[1]
if mode == 'restart':
subprocess.run(['docker', 'compose', 'restart', 'postgres', 'api', 'lb'], cwd=ROOT, check=True)
elif mode == 'stop':
target = os.environ.get('TARGET_INSTANCE_ID')
matches = [item for item in containers() if item['Config']['Hostname'] == target]
if len(matches) != 1:
raise SystemExit('Target must identify exactly one running API container')
print('Stopping API container ' + matches[0]['Id'][:12])
docker('stop', '-t', '2', matches[0]['Id'])
elif mode == 'rolling':
import time
import urllib.request
for item in containers():
name = item['Name'].lstrip('/')
started = time.time()
stages = {}
docker('stop', '-t', '6', item['Id'])
stages['stopped_seconds'] = round(time.time() - started, 3)
docker('rm', item['Id'])
stages['removed_seconds'] = round(time.time() - started, 3)
docker('compose', 'up', '-d', '--no-deps', '--scale', 'api=2', 'api')
stages['created_seconds'] = round(time.time() - started, 3)
deadline = time.monotonic() + 45
observations = []
previous = None
while time.monotonic() < deadline:
active = containers()
state = [(c['Id'][:12], c.get('State', {}).get('Health', {}).get('Status')) for c in active]
if state != previous:
observations.append({'elapsed_seconds': round(time.time()-started, 3), 'containers': [{'id': c['Id'][:12], 'health': c.get('State', {}).get('Health', {})} for c in active]})
previous = state
if len(active) == 2 and all(c.get('State', {}).get('Health', {}).get('Status') == 'healthy' for c in active):
break
time.sleep(0.5)
else:
raise SystemExit('Replacement did not become healthy: ' + name)
stages['healthy_seconds'] = round(time.time() - started, 3)
with urllib.request.urlopen(os.getenv('BASE_URL', 'http://localhost:8080').rstrip('/') + '/health/ready', timeout=3) as response:
if response.status != 200:
raise SystemExit('LB unavailable')
time.sleep(3)
print(json.dumps({'event': 'rolling_replacement', 'old_name': name, 'old_container': item['Id'][:12], 'started_epoch': started, 'finished_epoch': time.time(), 'stages': stages, 'health_observations': observations, 'new_containers': [c['Id'][:12] for c in active]}), flush=True)
else:
raise SystemExit('Unknown operation')
if __name__ == '__main__':
main()
+65
View File
@@ -0,0 +1,65 @@
import argparse
import csv
from datetime import datetime, timezone
import json
from research import OUT, benchmark, dataset, deploy
def graph(rows):
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import statistics
selected = [row for row in rows if row['series'] == 'active-window']
fig, axes = plt.subplots(1, 2, figsize=(11, 4), layout='constrained')
groups = [[row['successful_rps'] for row in selected if row['pool'] == 8 and row['concurrency'] == count] for count in (4, 16, 64)]
axes[0].errorbar([4, 16, 64], [statistics.mean(group) for group in groups], yerr=[(max(group)-min(group))/2 for group in groups], marker='o', capsize=4)
axes[0].set(title='Synchronized active window, pool=8', xlabel='Concurrent clients', ylabel='Successful requests / second')
groups = [[row['successful_rps'] for row in selected if row['pool'] == pool and row['concurrency'] == 64] for pool in (8, 1)]
axes[1].bar(['pool=8', 'pool=1'], [statistics.mean(group) for group in groups], yerr=[(max(group)-min(group))/2 for group in groups], capsize=5, color=['#2563eb', '#16a34a'])
axes[1].set(title='Paired comparison, 64 clients', ylabel='Successful requests / second')
for axis in axes:
axis.set_ylim(bottom=0)
axis.grid(axis='y', alpha=0.25)
fig.savefig(OUT / 'active-window.png', dpi=160)
fig.savefig(OUT / 'active-window.svg')
plt.close(fig)
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--resume', action='store_true')
args = parser.parse_args()
rows = json.loads((OUT / 'results.json').read_text(encoding='utf-8'))
if not args.resume:
rows = [row for row in rows if row['series'] != 'active-window']
completed = {row['repeat'] for row in rows if row['series'] == 'active-window'}
environment = json.loads((OUT / 'environment.json').read_text(encoding='utf-8'))
order = [(8, 4), (8, 16), (8, 64), (1, 64), (1, 64), (8, 64)]
environment.setdefault('active_window_study', {'date_utc': datetime.now(timezone.utc).isoformat(), 'order_pool_concurrency': order, 'replicas': 4, 'cpu_each': 0.5, 'memory_mb_each': 256, 'duration_seconds': 15})
environment['active_window_study']['dataset_at_resume' if args.resume else 'dataset_before'] = dataset()
(OUT / 'environment.json').write_text(json.dumps(environment, indent=2), encoding='utf-8')
try:
for index, (pool, concurrency) in enumerate(order, 1):
if index in completed:
continue
deploy(4, 0.5, 256, pool)
print(f'Active window {index}/6: pool={pool}, clients={concurrency}', flush=True)
result = benchmark(f'active-{index}-p{pool}-c{concurrency}', 15, concurrency, active=True)
rows.append(dict(series='active-window', replicas=4, cpu_each=0.5, memory_mb_each=256, pool=pool, repeat=index, **result))
(OUT / 'results.json').write_text(json.dumps(rows, indent=2), encoding='utf-8')
environment['active_window_study']['dataset_after'] = dataset()
(OUT / 'environment.json').write_text(json.dumps(environment, indent=2), encoding='utf-8')
graph(rows)
fields = ['series', 'replicas', 'cpu_each', 'memory_mb_each', 'pool', 'repeat', 'concurrency', 'successful_rps', 'failed_requests', 'error_ratio']
with (OUT / 'results.csv').open('w', encoding='utf-8', newline='') as stream:
writer = csv.DictWriter(stream, fieldnames=fields, extrasaction='ignore')
writer.writeheader()
writer.writerows(rows)
finally:
deploy(2, 0.5, 256, 1)
if __name__ == '__main__':
main()
+143
View File
@@ -0,0 +1,143 @@
import argparse
import csv
from datetime import datetime, timezone
import json
import os
from pathlib import Path
import platform
import subprocess
import sys
import time
from concurrent.futures import ThreadPoolExecutor
ROOT = Path(__file__).resolve().parents[1]
OUT = ROOT / 'evidence' / 'scaling'
def command(args, env=None):
result = subprocess.run(args, cwd=ROOT, env=env, text=True, encoding='utf-8', capture_output=True)
if result.returncode:
raise RuntimeError('Command failed: ' + ' '.join(args) + '\n' + result.stderr[-2000:] + result.stdout[-1000:])
return result.stdout
def deploy(replicas, cpu, memory, pool):
env = dict(os.environ, API_REPLICAS=str(replicas), API_CPUS=str(cpu), API_MEMORY=str(memory) + 'm', DB_POOL_SIZE=str(pool))
command(['docker', 'compose', 'up', '-d', '--no-deps', '--scale', 'api=' + str(replicas), 'api'], env)
deadline = time.monotonic() + 90
while time.monotonic() < deadline:
ids = command(['docker', 'compose', 'ps', '-q', 'api'], env).split()
items = json.loads(command(['docker', 'inspect', *ids], env)) if ids else []
if len(items) == replicas and all(item['State'].get('Health', {}).get('Status') == 'healthy' for item in items):
break
time.sleep(1)
else:
raise RuntimeError('API replicas did not become healthy within 90 seconds')
time.sleep(4)
def stats():
rows = command(['docker', 'stats', '--no-stream', '--format', '{{json .}}']).splitlines()
return [json.loads(row) for row in rows if row.strip() and 'mtusi-lab3-' in json.loads(row).get('Name', '')]
def dataset():
return json.loads(command(['docker', 'compose', 'exec', '-T', 'postgres', 'psql', '-U', 'messenger', '-d', 'messenger', '-tAc', "SELECT json_build_object('users',(SELECT count(*) FROM users),'chats',(SELECT count(*) FROM chats),'messages',(SELECT count(*) FROM messages),'database_bytes',pg_database_size(current_database()))"]))
def benchmark(name, duration, concurrency, active=False):
if not active:
command([sys.executable, 'tests/load.py', '--duration', '3', '--concurrency', str(concurrency)])
started = datetime.now(timezone.utc).isoformat()
snapshots = []
with ThreadPoolExecutor(max_workers=1) as executor:
pending = executor.submit(command, [sys.executable, 'scripts/load_active.py' if active else 'tests/load.py', '--duration', str(duration), '--concurrency', str(concurrency), '--output', str(OUT / (name + '.json'))])
while not pending.done():
snapshots.append({'at': time.time(), 'containers': stats()})
time.sleep(0.5)
pending.result()
(OUT / (name + '-resources.json')).write_text(json.dumps(snapshots, indent=2), encoding='utf-8')
logs = command(['docker', 'compose', 'logs', '--no-color', '--since', started, 'api'])
metrics = []
for line in logs.splitlines():
if '"event": "pool_metrics"' in line:
metrics.append(json.loads(line[line.index('{'):]))
(OUT / (name + '-pool.json')).write_text(json.dumps(metrics, indent=2), encoding='utf-8')
return json.loads((OUT / (name + '.json')).read_text(encoding='utf-8'))
def graph(rows):
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import statistics
fig, axes = plt.subplots(1, 2, figsize=(11, 4), layout='constrained')
for series, color in {'fixed': '#2563eb', 'growing': '#16a34a'}.items():
groups = [[r['successful_rps'] for r in rows if r['series'] == series and r['replicas'] == count] for count in (1, 2, 4)]
axes[0].errorbar([1, 2, 4], [statistics.mean(g) for g in groups], yerr=[(max(g)-min(g))/2 for g in groups], marker='o', capsize=4, color=color, label=series)
axes[0].set(title='API scaling, 24 clients', xlabel='API replicas', ylabel='Successful requests / second', xticks=[1, 2, 4])
axes[0].legend()
for series, label in [('saturation', 'pool=8'), ('pool-saturation', 'pool=1')]:
selected = [r for r in rows if r['series'] == series]
axes[1].plot([r['concurrency'] for r in selected], [r['successful_rps'] for r in selected], marker='o', label=label)
axes[1].set(title='Public driver, including client startup', xlabel='Concurrent clients', ylabel='Successful requests / second')
axes[1].legend()
for axis in axes:
axis.grid(alpha=0.25)
axis.set_ylim(bottom=0)
fig.savefig(OUT / 'throughput.svg')
fig.savefig(OUT / 'throughput.png', dpi=160)
plt.close(fig)
def main():
import matplotlib
parser = argparse.ArgumentParser()
parser.add_argument('--duration', type=int, default=15)
parser.add_argument('--repeats', type=int, default=2)
args = parser.parse_args()
OUT.mkdir(parents=True, exist_ok=True)
metadata = {'date_utc': datetime.now(timezone.utc).isoformat(), 'matplotlib_version': matplotlib.__version__, 'base_url': os.environ.get('BASE_URL', 'http://localhost:8080'), 'platform': platform.platform(), 'logical_cpus': os.cpu_count(), 'docker': json.loads(command(['docker', 'info', '--format', '{{json .}}'])), 'duration': args.duration, 'warmup_seconds': 3, 'concurrency': 24, 'repeats': args.repeats, 'dataset_before': dataset()}
safe = {key: metadata['docker'].get(key) for key in ('ServerVersion', 'NCPU', 'MemTotal', 'OperatingSystem', 'KernelVersion', 'Architecture')}
metadata['docker'] = safe
(OUT / 'environment.json').write_text(json.dumps(metadata, indent=2), encoding='utf-8')
rows = []
try:
for series in ('fixed', 'growing'):
for replicas in (1, 2, 4):
cpu = 1 / replicas if series == 'fixed' else 0.5
memory = 512 // replicas if series == 'fixed' else 256
deploy(replicas, cpu, memory, 8)
for repeat in range(args.repeats):
name = f'{series}-{replicas}-r{repeat+1}'
print('Measuring ' + name, flush=True)
result = benchmark(name, args.duration, 24)
rows.append(dict(series=series, replicas=replicas, cpu_each=cpu, memory_mb_each=memory, pool=8, repeat=repeat+1, **result))
(OUT / 'results.json').write_text(json.dumps(rows, indent=2), encoding='utf-8')
deploy(2, 0.5, 256, 1)
for repeat in range(args.repeats):
result = benchmark('pool-one-r' + str(repeat+1), args.duration, 24)
rows.append(dict(series='pool-one', replicas=2, cpu_each=0.5, memory_mb_each=256, pool=1, repeat=repeat+1, **result))
deploy(4, 0.5, 256, 8)
for concurrency in (4, 16, 64):
result = benchmark('saturation-c' + str(concurrency), args.duration, concurrency)
rows.append(dict(series='saturation', replicas=4, cpu_each=0.5, memory_mb_each=256, pool=8, repeat=1, **result))
deploy(4, 0.5, 256, 1)
for concurrency in (4, 16, 64):
result = benchmark('pool-saturation-c' + str(concurrency), args.duration, concurrency)
rows.append(dict(series='pool-saturation', replicas=4, cpu_each=0.5, memory_mb_each=256, pool=1, repeat=1, **result))
(OUT / 'results.json').write_text(json.dumps(rows, indent=2), encoding='utf-8')
metadata['dataset_after'] = dataset()
(OUT / 'environment.json').write_text(json.dumps(metadata, indent=2), encoding='utf-8')
graph(rows)
fields = ['series', 'replicas', 'cpu_each', 'memory_mb_each', 'pool', 'repeat', 'concurrency', 'successful_rps', 'failed_requests', 'error_ratio']
with (OUT / 'results.csv').open('w', encoding='utf-8', newline='') as stream:
writer = csv.DictWriter(stream, fieldnames=fields, extrasaction='ignore')
writer.writeheader()
writer.writerows(rows)
finally:
deploy(2, 0.5, 256, 1)
if __name__ == '__main__':
main()
+2
View File
@@ -0,0 +1,2 @@
@echo off
python "%~dp0operate.py" restart
+4
View File
@@ -0,0 +1,4 @@
#!/bin/sh
set -eu
cd "$(dirname "$0")/.."
python3 scripts/operate.py restart
+2
View File
@@ -0,0 +1,2 @@
@echo off
python "%~dp0operate.py" stop
+4
View File
@@ -0,0 +1,4 @@
#!/bin/sh
set -eu
cd "$(dirname "$0")/.."
python3 scripts/operate.py stop
+119
View File
@@ -0,0 +1,119 @@
from collections import defaultdict
from datetime import datetime
import json
from pathlib import Path
import statistics
ROOT = Path(__file__).resolve().parents[1]
OUT = ROOT / 'evidence'
SCALING = OUT / 'scaling'
def read(path):
return json.loads(path.read_text(encoding='utf-8-sig'))
def analysis(rows):
selected = [row for row in rows if row['series'] == 'active-window' and row['concurrency'] == 64]
if len(selected) < 4:
return
by_pool = {pool: [row for row in selected if row['pool'] == pool] for pool in (8, 1)}
rates = {pool: statistics.mean(row['successful_rps'] for row in values) for pool, values in by_pool.items()}
p95 = {pool: statistics.mean(row['successful_latency_ms']['p95'] for row in values) for pool, values in by_pool.items()}
growth = 100 * (rates[1] / rates[8] - 1)
latency_change = 100 * (1 - p95[1] / p95[8])
fixed = {count: statistics.mean(row['successful_rps'] for row in rows if row['series'] == 'fixed' and row['replicas'] == count) for count in (1, 2, 4)}
growing = {count: statistics.mean(row['successful_rps'] for row in rows if row['series'] == 'growing' and row['replicas'] == count) for count in (1, 2, 4)}
confirmed = {count: statistics.mean(row['successful_rps'] for row in rows if row['series'] == 'confirmation' and row['replicas'] == count) for count in (2, 4)}
lines = ['# Разбор исследования', '', '## Гипотеза и воспроизводимость', '', 'Гипотеза: репликация без увеличения суммарного CPU/RAM не даёт линейного ускорения; слишком большой пул при жёстком CPU-лимите может увеличивать конкуренцию за CPU и хвостовую задержку. Все запросы синтетические, без вложений, через HAProxy. Каждый POST имеет уникальный Idempotency-Key. Сессии создаются до измерения.', '', 'Команды из корня проекта после запуска стенда: `python scripts/research.py --duration 15 --repeats 2`, `python scripts/confirm.py`, `python scripts/pool_study.py`, `python scripts/summarize.py`. Перед ними установите requirements-research.txt и BASE_URL для выбранного порта. Настройки и порядок прогонов фиксируются в scaling/environment.json.', '', '## Цена масштабирования', '', f'При фиксированных суммарных 1 CPU/512 MiB API: 1/2/4 реплики дали {fixed[1]:.2f}/{fixed[2]:.2f}/{fixed[4]:.2f} RPS. При росте бюджета по 0.5 CPU/256 MiB на реплику: {growing[1]:.2f}/{growing[2]:.2f}/{growing[4]:.2f} RPS. Добавление CPU помогает, но переход 2 → 4 дал лишь {100*(growing[4]/growing[2]-1):.1f}% при удвоении API-ресурсов.', '', f'Контрольный порядок 4 → 2 → 2 → 4 дал для двух реплик {confirmed[2]:.2f}, для четырёх {confirmed[4]:.2f} RPS. Он не подтвердил первоначальный вывод о безусловном преимуществе двух реплик. Одинаковая конфигурация в разные моменты даёт разные RPS: есть дрейф нагрузки host и CPU throttling. Поэтому уменьшение числа реплик не объявляется доказанным улучшением. Две реплики выбраны как обязательный минимум доступности.', '', 'Публичный driver включает создание потоков и SSL contexts в elapsed. При 64 клиентах этот старт значителен. Первые графики показывают именно его end-to-end результат. Сравнение разной конкуренции уточнено отдельным генератором с barrier, 3 секундами прогрева и 15 секундами активной нагрузки; его elapsed включает только активное окно и завершение отправленных запросов.', '', '## Подтверждённое улучшение', '', f'При неизменных четырёх API по 0.5 CPU/256 MiB, PostgreSQL 1 CPU/512 MiB и LB 0.5 CPU/128 MiB выполнен порядок pool=8 → 1 → 1 → 8, 64 клиента. Средний активный throughput: {rates[8]:.3f} → {rates[1]:.3f} RPS ({growth:+.2f}%). Среднее p95 отдельных прогонов: {p95[8]:.3f} → {p95[1]:.3f} ms (снижение {latency_change:.2f}%). Ошибок в этих четырёх прогонах: ' + str(sum(row['failed_requests'] for row in selected)) + '.', '', 'Улучшение — ограничение числа одновременных операций с БД на CPU-ограниченной API-реплике. Изменён DB_POOL_SIZE по умолчанию с 8 на 1 в compose, bootstrap и приложении. Это ограничивает активную конкуренцию и переносит ожидание в контролируемую очередь пула. Настройка подтверждена для этого профиля; при других CPU/SQL/latency её надо измерять заново. Большой пул сам по себе не означает большую пропускную способность.', '', '![Масштабирование](scaling/throughput.png)', '', '![Активное окно и сравнение пула](scaling/active-window.png)', '', '## Насыщение и ресурсы', '', '| Пул, 64 клиента | Компонент | CPU, среднее % одного ядра | CPU, max % | RAM, max MiB | Максимум ожидающих pool на реплике |', '| --- | --- | --- | --- | --- | --- |']
for pool, values in by_pool.items():
collected = defaultdict(list)
waiting = 0
for row in values:
name = f"active-{row['repeat']}-p{pool}-c64"
for sample in read(SCALING / (name + '-resources.json')):
if row['measurement_started_epoch'] <= sample['at'] <= row['measurement_finished_epoch']:
for item in sample['containers']:
service = item['Name'].rsplit('-', 2)[-2]
import re
memory = re.fullmatch(r'([\d.]+)([A-Za-z]+)', item['MemUsage'].split('/')[0].strip())
scale = {'B': 1/1024**2, 'KiB': 1/1024, 'MiB': 1, 'GiB': 1024}
memory_mb = float(memory[1])*scale[memory[2]]
collected[service].append((float(item['CPUPerc'].rstrip('%')), memory_mb))
for sample in read(SCALING / (name + '-pool.json')):
if row['measurement_started_epoch'] <= datetime.fromisoformat(sample['at']).timestamp() <= row['measurement_finished_epoch']:
waiting = max(waiting, sample['stats'].get('requests_waiting', 0))
for service, samples in sorted(collected.items()):
lines.append(f'| {pool} | {service} | {statistics.mean(value[0] for value in samples):.2f} | {max(value[0] for value in samples):.2f} | {max(value[1] for value in samples):.2f} | {waiting if service == "api" else "—"} |')
lines += ['', 'Для API среднее относится к одной реплике; суммарная загрузка — примерно в четыре раза больше. Лимит каждой API — 50% одного ядра. PostgreSQL ограничен 100%, LB — 50%. Снимки показывают приближение API к CPU quota и накопление очередей пула; предела CPU PostgreSQL/LB этот профиль не достиг. При 64 клиентах ожидание пула наблюдается непосредственно в requests_waiting, requests_queued и requests_wait_ms. Увеличение количества соединений на этих CPU-лимитах не устраняет очередь, а ухудшает итоговый throughput.', '', 'Точка насыщения относится к выбранному профилю и очереди синхронного пути, а не к универсальной capacity БД: переход от 4 к 16/64 клиентам с pool=8 уже не даёт роста полезной скорости и увеличивает p95. На 64 клиентах очередь пула зафиксирована напрямую. Чистый аппаратный предел PostgreSQL или HAProxy не измерен; утверждать обратное по этим данным нельзя.', '', '## Отказы, инциденты и ограничения', '', 'Итоговые функциональные проверки и отказы на настроенном стенде приведены в RESULTS.md, исходные выводы — в соседних TXT/JSON. Сохранность проверяется прежним токеном и сравнением подтверждённых сообщений. Rolling replacement фиксирует старые/новые ID и время замены внутри активного окна нагрузки.', '', 'Во время первого запуска активной серии Compose --wait отказался продолжить из-за оставшегося unhealthy после нагрузки состояния одной реплики. Первые два измерения завершились без HTTP-ошибок; третье ещё не начиналось. Hook эксперимента исправлен: явно ожидает восстановления readiness до 90 секунд. Серия продолжена с --resume без удаления завершённых результатов. Подробности: scaling/active-window-incident.txt. Under CPU pressure readiness использует тот же ограниченный pool и тоже может задерживаться; отдельный резерв readiness-подключений не реализован.', '', 'Два повтора сравнения пула и короткие окна не являются статистическим доказательством для любого оборудования. Порядок ABBA снижает влияние временного дрейфа, но не устраняет его полностью. Closed loop сохраняет coordinated omission; клиент, HTTP и Docker Desktop входят в путь. На машине есть соседний учебный стенд, его конфигурация не менялась. Между прогонами растёт набор данных. Один Docker host, единственные БД и LB остаются SPOF.']
(OUT / 'ANALYSIS.md').write_text('\n'.join(lines) + '\n', encoding='utf-8')
def main():
rows = read(SCALING / 'results.json')
from research import graph
graph(rows)
if any(row['series'] == 'active-window' for row in rows):
from pool_study import graph as graph_active
graph_active(rows)
environment = read(SCALING / 'environment.json')
lines = ['# Фактические результаты', '', 'Дата измерений UTC: ' + environment['date_utc'] + '.', '', 'Команды: `python scripts/verify.py`, `python scripts/research.py --duration 15 --repeats 2`. Адрес: ' + environment['base_url'] + '.', '', '## Функциональные проверки', '']
for name in ('contract', 'smoke', 'concurrent', 'persistence', 'public-failover', 'rolling-action', 'smoke-after-rolling'):
path = OUT / (name + '.txt')
lines.append(f'- [{name}]({path.name}): см. фактический вывод.')
lines += ['', '## Отказы', '', '| Остановленный контейнер | Записи / с | Чтения / с | Ошибки | Восстановление, с | Потеря подтверждений |', '| --- | --- | --- | --- | --- | --- |']
for row in read(OUT / 'failover-matrix.json'):
lines.append(f"| {row['container']} | {row['successful_writes']/row['elapsed_seconds']:.2f} | {row['successful_reads']/row['elapsed_seconds']:.2f} | {row['failed_attempts']} | {row['recovery_seconds']:.3f} | {row['lost_confirmations']} |")
rolling = read(OUT / 'rolling-load.json')
lines += ['', f"Rolling replacement: {rolling['successful_requests']} успешных записей, {rolling['failed_requests']} ошибок ({rolling['error_ratio']*100:.2f}%), {rolling['successful_rps']:.2f} RPS, p95={rolling['successful_latency_ms']['p95']:.2f} ms. Это замена без предварительного drain backend; обнаружение отказа допускает краткие ошибки, автоматического retry в этом профиле нет. После замены публичный smoke проходит.", '', '## Среда', '', f"Docker VM: {environment['docker']['NCPU']} CPU, {environment['docker']['MemTotal']/1024**3:.2f} GiB RAM; {environment['docker']['OperatingSystem']}; Engine {environment['docker']['ServerVersion']}. Host: {environment['platform']}.", '', 'Объём данных до: `' + json.dumps(environment['dataset_before']) + '`, после: `' + json.dumps(environment['dataset_after']) + '`.', '', '## Масштабирование', '', 'Фиксированный бюджет: суммарно 1 CPU/512 MiB API. Растущий: по 0.5 CPU/256 MiB каждой API. PostgreSQL 1 CPU/512 MiB, LB 0.5 CPU/128 MiB во всех сериях. Таблица содержит среднее RPS по повторам и диапазон p95 отдельных прогонов; это не объединённый percentile.', '', '| Серия | Реплики | Пул каждой | Клиенты | RPS, среднее | RPS, min–max | p50, ms | p95, ms | p99, ms | Ошибок |', '| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |']
groups = defaultdict(list)
for row in rows:
groups[(row['series'], row['replicas'], row['pool'], row['concurrency'])].append(row)
for (series, replicas, pool, concurrency), values in groups.items():
rates = [r['successful_rps'] for r in values]
latencies = {p: [r['successful_latency_ms'][p] for r in values] for p in ('p50', 'p95', 'p99')}
lines.append(f"| {series} | {replicas} | {pool} | {concurrency} | {statistics.mean(rates):.2f} | {min(rates):.2f}–{max(rates):.2f} | {statistics.mean(latencies['p50']):.1f} | {min(latencies['p95']):.1f}–{max(latencies['p95']):.1f} | {statistics.mean(latencies['p99']):.1f} | {sum(r['failed_requests'] for r in values)} |")
lines += ['', '![Графики масштабирования](scaling/throughput.png)', '', 'Публичный driver включает создание клиентских потоков/SSL contexts в elapsed. Его RPS при разной конкуренции содержит заметные расходы старта генератора. Строки active-window измерены после подготовки клиентов и 3 секунд прогрева, включая завершение запросов после дедлайна; эти методики нельзя смешивать.', '']
if any(row['series'] == 'active-window' for row in rows):
lines += ['![Измерения в активном окне](scaling/active-window.png)', '']
lines += ['## Наблюдение ресурсов', '', '| Серия / прогон | Компонент | CPU, среднее % одного ядра | CPU, максимум % | RAM, максимум MiB |', '| --- | --- | --- | --- | --- |']
resources = {}
for path in sorted(SCALING.glob('*-resources.json')):
values = defaultdict(list)
summary = read(path.with_name(path.name.replace('-resources.json', '.json')))
for snapshot in read(path):
if 'measurement_started_epoch' in summary and not summary['measurement_started_epoch'] <= snapshot['at'] <= summary['measurement_finished_epoch']:
continue
for item in snapshot['containers']:
service = item['Name'].rsplit('-', 2)[-2]
memory = item['MemUsage'].split('/')[0].strip()
factors = {'B': 1/1024**2, 'KiB': 1/1024, 'MiB': 1, 'GiB': 1024}
import re
match = re.fullmatch(r'([\d.]+)([A-Za-z]+)', memory)
memory_mb = float(match[1]) * factors[match[2]] if match else 0
values[service].append((float(item['CPUPerc'].rstrip('%')), memory_mb))
for service, samples in sorted(values.items()):
cpu = [c for c, _ in samples]
resources[(path.stem, service)] = statistics.mean(cpu)
lines.append(f'| {path.stem.removesuffix("-resources")} | {service} | {statistics.mean(cpu):.2f} | {max(cpu):.2f} | {max(m for _, m in samples):.2f} |')
lines += ['', 'Для API CPU/RAM в этой таблице относятся к отдельным контейнерам, усреднённым по репликам и снимкам; максимум — отдельный контейнер. Суммарный CPU API вычисляется умножением среднего на число реплик. Docker CPU 100% соответствует одному ядру, независимо от quota.', '', '## Счётчики ожидания пула', '', '| Прогон | Реплик со снимками | Запросы в очереди, прирост | Ожидание, ms, прирост | Максимум ожидающих в снимке |', '| --- | --- | --- | --- | --- |']
for path in sorted(SCALING.glob('*-pool.json')):
by_instance = defaultdict(list)
summary = read(path.with_name(path.name.replace('-pool.json', '.json')))
for sample in read(path):
if 'measurement_started_epoch' in summary and not summary['measurement_started_epoch'] <= datetime.fromisoformat(sample['at']).timestamp() <= summary['measurement_finished_epoch']:
continue
by_instance[sample['instance']].append(sample['stats'])
queued, wait, maximum = 0, 0, 0
for samples in by_instance.values():
queued += samples[-1].get('requests_queued', 0) - samples[0].get('requests_queued', 0)
wait += samples[-1].get('requests_wait_ms', 0) - samples[0].get('requests_wait_ms', 0)
maximum = max(maximum, *(sample.get('requests_waiting', 0) for sample in samples))
lines.append(f'| {path.stem.removesuffix("-pool")} | {len(by_instance)} | {queued} | {wait} | {maximum} |')
lines += ['', 'Счётчики берутся каждые 5 секунд и включают readiness и вспомогательные запросы; прирост между первым и последним снимком покрывает часть измерения. Это диагностический сигнал, а не точный процент запросов измерительного окна.', '', '## Границы вывода', '', 'Короткий closed-loop профиль, два повтора основных серий, фиксированный порядок и растущий набор данных. Percentiles считаются только по успехам. Есть расходы генератора и Docker Desktop, а также соседний учебный стенд; его работа не изменялась. Полученные RPS не являются универсальной production capacity. Данные и графики получены реальным запуском, а не оценены по формуле.']
(OUT / 'RESULTS.md').write_text('\n'.join(lines) + '\n', encoding='utf-8')
analysis(rows)
if __name__ == '__main__':
main()
+126
View File
@@ -0,0 +1,126 @@
import argparse
from concurrent.futures import ThreadPoolExecutor
import json
import os
from pathlib import Path
import subprocess
import sys
import time
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tests'))
sys.path.insert(0, str(ROOT / 'scripts'))
from client import Client, Failure, check
from operate import containers
OUT = ROOT / 'evidence'
def run(args, name):
result = subprocess.run(args, cwd=ROOT, capture_output=True, text=True, encoding='utf-8')
(OUT / (name + '.txt')).write_text(result.stdout + result.stderr, encoding='utf-8')
if result.returncode:
raise RuntimeError(name + ': ' + result.stdout[-1000:] + result.stderr[-1000:])
print(name + ': PASS', flush=True)
def restore():
subprocess.run(['docker', 'compose', 'up', '-d', '--no-deps', '--scale', 'api=2', '--wait', 'api'], cwd=ROOT, check=True, capture_output=True)
time.sleep(4)
def snapshot():
ids = subprocess.check_output(['docker', 'compose', 'ps', '-q'], cwd=ROOT, text=True).split()
inspected = json.loads(subprocess.check_output(['docker', 'inspect', *ids], cwd=ROOT, text=True))
return [{'id': item['Id'][:12], 'service': item['Config']['Labels']['com.docker.compose.service'], 'hostname': item['Config']['Hostname'], 'started_at': item['State']['StartedAt'], 'status': item['State']['Status'], 'cpu_nanoseconds': item['HostConfig']['NanoCpus'], 'memory_bytes': item['HostConfig']['Memory'], 'pool_size': next((value.split('=', 1)[1] for value in item['Config']['Env'] if value.startswith('DB_POOL_SIZE=')), None), 'published_ports': item['HostConfig']['PortBindings']} for item in inspected]
def matrix():
c = Client(timeout=2)
alice, bob, eve, chat = c.bootstrap()
confirmed = c.message(alice, chat, 'before matrix')['json']
rows = []
for item in containers():
restore()
target = item['Config']['Hostname']
started = time.monotonic()
errors, successes, reads, recovery, observed = 0, [], 0, None, set()
with ThreadPoolExecutor(max_workers=1) as pool:
action = pool.submit(subprocess.run, ['docker', 'kill', item['Id']], cwd=ROOT, check=True, capture_output=True)
key = os.urandom(16).hex()
while time.monotonic() - started < 12:
try:
result = c.message(alice, chat, 'matrix-' + key, key=key)
successes.append(result['json'])
observed.add(result['headers']['X-Instance-Id'])
key = os.urandom(16).hex()
page = c.call('GET', '/api/v1/chats/' + chat['id'] + '/messages?limit=100', actor=bob, schema='MessagePage')['json']
check(confirmed in page['items'], 'confirmed data missing during failure')
reads += 1
if action.done() and recovery is None:
recovery = time.monotonic() - started
except Failure:
errors += 1
time.sleep(0.1)
action.result()
state = json.loads(subprocess.check_output(['docker', 'inspect', '--format', '{{json .State}}', item['Id']], text=True))
check(not state['Running'], 'target still running')
check(recovery is not None and recovery <= 10, 'recovery deadline exceeded')
from resilience import history
stored = history(c, bob, chat)
check(all(message in stored for message in successes), 'lost confirmed write')
texts = [message['text'] for message in stored]
check(len(texts) == len(set(texts)), 'retry duplicated data')
elapsed = time.monotonic() - started
rows.append({'target': target, 'container': item['Id'][:12], 'state': state['Status'], 'successful_writes': len(successes), 'successful_reads': reads, 'failed_attempts': errors, 'elapsed_seconds': round(elapsed, 3), 'write_rps': round(len(successes)/elapsed, 3), 'read_rps': round(reads/elapsed, 3), 'recovery_seconds': round(recovery, 3), 'observed_instances': sorted(observed), 'lost_confirmations': 0})
print('Hard failure verified: ' + target, flush=True)
restore()
(OUT / 'failover-matrix.json').write_text(json.dumps(rows, indent=2), encoding='utf-8')
def rolling():
ready_file = OUT / 'rolling-ready.json'
if ready_file.exists():
ready_file.unlink()
with ThreadPoolExecutor(max_workers=1) as pool:
load = pool.submit(run, [sys.executable, 'scripts/load_active.py', '--duration', '45', '--concurrency', '16', '--output', 'evidence/rolling-load.json', '--ready-file', str(ready_file)], 'rolling-load')
deadline = time.monotonic() + 90
while not ready_file.exists():
if load.done():
load.result()
raise RuntimeError('Load ended before measurement window started')
check(time.monotonic() < deadline, 'load setup exceeded 90 seconds')
time.sleep(0.2)
run([sys.executable, 'scripts/operate.py', 'rolling'], 'rolling-action')
load.result()
summary = json.loads((OUT / 'rolling-load.json').read_text(encoding='utf-8'))
replacements = [json.loads(line) for line in (OUT / 'rolling-action.txt').read_text(encoding='utf-8').splitlines() if line.startswith('{')]
check(len(replacements) == 2, 'rolling must replace exactly two processes')
check(all(summary['measurement_started_epoch'] <= row['started_epoch'] <= row['finished_epoch'] <= summary['measurement_finished_epoch'] for row in replacements), 'replacement happened outside active load window')
run([sys.executable, 'tests/smoke.py'], 'smoke-after-rolling')
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--rolling-only', action='store_true')
args = parser.parse_args()
OUT.mkdir(exist_ok=True)
if not args.rolling_only:
run([sys.executable, 'scripts/check_contract.py'], 'contract')
run([sys.executable, 'tests/smoke.py'], 'smoke')
run([sys.executable, 'student-tests/acceptance.py'], 'concurrent')
suffix = '.cmd' if os.name == 'nt' else '.sh'
before = snapshot()
run([sys.executable, 'tests/resilience.py', '--mode', 'persistence', '--action-script', 'scripts/restart' + suffix], 'persistence')
after = snapshot()
check(all(any(new['id'] == old['id'] and new['started_at'] != old['started_at'] for new in after) for old in before), 'restart hook did not restart all running services')
(OUT / 'restart-processes.json').write_text(json.dumps({'before': before, 'after': after}, indent=2), encoding='utf-8')
restore()
run([sys.executable, 'tests/resilience.py', '--mode', 'failover', '--action-script', 'scripts/stop-one' + suffix], 'public-failover')
restore()
matrix()
rolling()
if __name__ == '__main__':
main()