Files
mtusi2026lab4/student-tests/upload_memory.py
T

212 lines
10 KiB
Python

"""Bounded upload experiment. Recreates only API; preserves all data volumes."""
import argparse
from concurrent.futures import ThreadPoolExecutor
import datetime as dt
import hashlib
import json
from pathlib import Path
import subprocess
import sys
import threading
import time
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tests'))
from client import Client, Failure, check
from upload_fixtures import generate
def docker(*args, required=True):
result = subprocess.run(['docker', *args], cwd=ROOT, capture_output=True, text=True, timeout=120)
if required:
check(result.returncode == 0, 'Docker operation failed: ' + args[0])
return result
def compose(*args):
return docker('compose', '--env-file', '.env', *args).stdout.strip()
def wait_two(c, ids):
aliases = {docker('exec', cid, '/server', 'instance-id').stdout.strip() for cid in ids}
deadline = time.monotonic() + 60
seen, stable = set(), 0
while True:
try:
alias = c.call('GET', '/health/ready', schema='Health')['headers']['X-Instance-Id']
check(alias in aliases, 'old API still in LB')
seen.add(alias)
stable += 1
if seen == aliases and stable >= 8:
return
except Failure:
seen, stable = set(), 0
check(time.monotonic() < deadline, 'two new API did not become ready')
time.sleep(0.2)
def resources(ids):
result = []
for cid in ids:
state = json.loads(docker('inspect', '--format', '{{json .State}}', cid).stdout)
item = {'container_id': cid, 'status': state['Status'], 'oom_killed': state['OOMKilled']}
probe = docker('exec', cid, '/resourceprobe', required=False)
if probe.returncode == 0:
item.update(json.loads(probe.stdout))
else:
item['cgroup_unavailable'] = True
result.append(item)
return result
def percentile(values, percentile):
ordered = sorted(values)
if not ordered:
return None
index = (len(ordered)-1) * percentile / 100
low = int(index)
return round(ordered[low] + (ordered[min(low+1, len(ordered)-1)] - ordered[low]) * (index-low), 4)
def experiment(args, fixture):
c = Client(args.base_url, timeout=65)
compose('up', '-d', '--force-recreate', '--no-deps', '--wait', '--wait-timeout', '60', 'api')
ids = compose('ps', '-q', 'api').split()
check(len(ids) == 2, 'expected two API')
wait_two(c, ids)
alice, bob, _, chat = c.bootstrap()
for _ in range(2):
c.attachment(alice, chat) # Same small warmup for every profile.
payload = Path(fixture['path']).read_bytes()
path = '/api/v1/chats/' + chat['id'] + '/attachments?filename=' + Path(fixture['path']).name
samples, stop = [], threading.Event()
def monitor():
while not stop.is_set():
observation = docker('stats', '--no-stream', '--format', '{{json .}}', *ids, required=False)
if observation.returncode == 0:
for line in observation.stdout.splitlines():
item = json.loads(line)
item['elapsed_seconds'] = round(time.monotonic() - observation_start, 3)
samples.append(item)
stop.wait(0.2)
observation_start = time.monotonic()
before = resources(ids)
check(all('memory_peak_bytes' in item for item in before), 'cgroup v2 measurement unavailable')
thread = threading.Thread(target=monitor, daemon=True)
thread.start()
results, batches = [], []
lock = threading.Lock()
active = maximum_active = 0
try:
for repeat in range(args.repeats):
barrier = threading.Barrier(args.concurrency)
def send(_):
nonlocal active, maximum_active
local = Client(args.base_url, timeout=65)
barrier.wait(timeout=15)
started = time.monotonic()
with lock:
active += 1
maximum_active = max(maximum_active, active)
try:
response = local.call('POST', path, 201, actor=alice, raw=payload,
headers={'Content-Type': fixture['content_type']}, schema='Attachment')
return {'ok': True, 'seconds': time.monotonic()-started, 'attachment': response['json'],
'instance': response['headers']['X-Instance-Id']}
except (Failure, OSError, TimeoutError) as exc:
return {'ok': False, 'seconds': time.monotonic()-started, 'error': str(exc)[:200]}
finally:
with lock:
active -= 1
started = time.monotonic()
with ThreadPoolExecutor(max_workers=args.concurrency) as executor:
batch = list(executor.map(send, range(args.concurrency)))
batches.append({'repeat': repeat+1, 'seconds': round(time.monotonic()-started, 4),
'successes': sum(item['ok'] for item in batch),
'errors': sum(not item['ok'] for item in batch)})
results.extend(batch)
after = resources(ids)
observation_seconds = time.monotonic() - observation_start
finally:
stop.set()
thread.join(timeout=5)
successes = [item for item in results if item['ok']]
verified = 0
for item in successes:
a = item['attachment']
check(a['sha256'] == fixture['sha256'] and a['size_bytes'] == len(payload), 'upload checksum/size mismatch')
response = c.call('GET', '/api/v1/attachments/' + a['id'] + '/content', actor=bob)
check(response['bytes'] == payload and hashlib.sha256(response['bytes']).hexdigest() == fixture['sha256'], 'download mismatch')
check(response['headers'].get_content_type() == fixture['content_type'], 'download MIME mismatch')
verified += 1
timed_seconds = sum(batch['seconds'] for batch in batches)
result = {
'fixture': {key: value for key, value in fixture.items() if key != 'path'},
'concurrency': args.concurrency, 'max_client_in_flight': maximum_active, 'repeats': args.repeats,
'warmup': '2 sample.png uploads after fresh API start', 'batches': batches,
'successful_requests': len(successes), 'error_count': len(results)-len(successes),
'error_fraction': (len(results)-len(successes))/len(results),
'errors': [item['error'] for item in results if not item['ok']],
'http_upload_seconds': round(timed_seconds, 4),
'successful_rps': round(len(successes)/timed_seconds, 3),
'latency_success_seconds': {f'p{p}': percentile([item['seconds'] for item in successes], p) for p in (50, 95, 99)},
'serving_instances': len({item['instance'] for item in successes}), 'downloads_verified': verified,
'resources_before': before, 'resources_after': after,
'resource_observation_seconds': round(observation_seconds, 4), 'docker_stats_samples': samples,
}
for first, last in zip(before, after):
if 'cpu_usage_usec' in last:
last['cpu_mean_percent_one_core'] = round((last['cpu_usage_usec']-first['cpu_usage_usec']) / (observation_seconds*10000), 2)
return result
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--base-url', default='http://127.0.0.1:8084')
parser.add_argument('--profiles', nargs='+', default=['rgb8_1mp', 'jpeg_1mp', 'rgba16_40mp', 'rgba16_wide_40mp'])
parser.add_argument('--concurrency', type=int, default=10)
parser.add_argument('--repeats', type=int, default=3)
parser.add_argument('--output', default='evidence/upload-memory.json')
args = parser.parse_args()
check(1 <= args.concurrency <= 32 and 1 <= args.repeats <= 5, 'invalid experiment bounds')
fixtures = {item['name']: item for item in generate()}
check(all(name in fixtures for name in args.profiles), 'missing fixture; run go run ./student-tests/fixturegen first')
engine = json.loads(docker('info', '--format', '{{json .}}').stdout)
report = {'utc': dt.datetime.now(dt.timezone.utc).isoformat(), 'python': sys.version.split()[0],
'docker': {'server': engine['ServerVersion'], 'cpus': engine['NCPU'], 'memory_bytes': engine['MemTotal']},
'method': 'synchronized finite batches, fresh API per profile, kernel peak since cgroup creation including warmup/probes; no upload retries',
'profiles': []}
output = ROOT / args.output
for name in args.profiles:
result = experiment(args, fixtures[name])
report['profiles'].append(result)
output.write_text(json.dumps(report, indent=2), encoding='utf-8')
print(json.dumps({'profile': name, 'successes': result['successful_requests'], 'errors': result['error_count'],
'peak_MiB': [round(item.get('memory_peak_bytes', 0)/1048576, 2) for item in result['resources_after']],
'oom_killed': [item['oom_killed'] for item in result['resources_after']]}), flush=True)
# Restore stopped API after a diagnostic failure without changing data volumes.
stopped = docker('compose', '--env-file', '.env', 'ps', '-a', '-q', 'api').stdout.split()
for cid in stopped:
if docker('inspect', '--format', '{{.State.Running}}', cid).stdout.strip() != 'true':
docker('start', cid)
check(all(profile['error_count'] == 0 for profile in report['profiles']), 'upload failures recorded; inspect JSON')
for profile in report['profiles']:
check(all(not item['oom_killed'] and item.get('oom_kills', 0) == 0 and item.get('swap_limit_bytes') == 0
for item in profile['resources_after']), 'OOM or unexpected swap configuration')
if args.concurrency >= 10:
check(profile['max_client_in_flight'] >= 10 and profile['serving_instances'] == 2,
'experiment did not reach ten overlapping uploads and both API')
print('PASS: upload concurrency/memory experiment and original-byte verification')
if __name__ == '__main__':
try:
main()
except (Failure, OSError, ValueError) as exc:
print('FAIL:', str(exc))
raise SystemExit(1)