diff --git a/tests/README.md b/tests/README.md index 0dfa3f89..293aa200 100644 --- a/tests/README.md +++ b/tests/README.md @@ -1,6 +1,6 @@ # Публичные проверки -Python **3.9+**, стандартная библиотека. Сервер уже должен быть запущен; проверки не создают готовое приложение и сами не управляют Docker. `make check` можно выполнить на исходном skeleton, `make test` — только после реализации API. Полная OpenAPI-валидация отдельно: `make validate` после установки `requirements-dev.txt` в venv. +Python **3.9+**, стандартная библиотека. Публичные проверки обращаются к уже запущенному серверу. Сценарии восстановления outbox и worker запускают собственные проекты Docker Compose. `make check` можно выполнить на исходном skeleton, `make test` — после реализации API. Полная валидация OpenAPI выполняется через `make validate` после установки `requirements-dev.txt` в venv. ```sh make check @@ -35,6 +35,26 @@ make test-failover ACTION_SCRIPT=scripts/stop-one.sh Перед отказом тест наблюдает ≥2 API-реплики; 15 секунд отправляет сообщения параллельно выполнению hook, повторяет неопределённый POST с тем же ключом, проверяет восстановление записи за ≤10 секунд, отсутствие остановленной реплики в последних ответах, сохранность подтверждённых сообщений и отсутствие дублей. Ошибки переходного периода учитываются. Затем восстановите реплику и повторите для другой. Скрипт — проверка одного отказа API, не гарантия HA БД/LB/host. Вывод hook скрыт, чтобы не утекли секреты; отлаживайте его отдельно с безопасным выводом. +## Восстановление outbox после сбоя API, lab5 + +```sh +python3 -X utf8 tests/outbox_crash.py +``` + +Сценарий поднимает отдельный проект Docker Compose с одной API-репликой и временными томами. Тест загружает PNG, получает `202` и проверяет запись в PostgreSQL. Затем тестовый preload аварийно завершает API с кодом 86 при вызове producer перед отправкой данных в Kafka. Тест проверяет ID задания в маркере сбоя, сохранённую строку outbox и неизменившийся offset топика. + +Новый контейнер API запускается с обычным publisher и теми же данными стенда. Тест проверяет `ready` у того же ID, целостность исходных байтов и удаление записи из outbox после подтверждения Kafka. Сценарий выполняет одну загрузку и удаляет только свой тестовый проект с его томами. + +## Восстановление worker после записи в S3, lab5 + +```sh +python3 -X utf8 tests/worker_crash.py +``` + +В отдельном Compose-проекте тест публикует два задания, запускает worker с тестовым preload и завершает его с кодом 87 сразу после записи последнего объекта в S3. Тест проверяет сохранённую аренду `processing`, смещение группы Kafka и состояние второго задания. Preload записывает параметры запроса Kafka Fetch для проверки лимитов на запрос и раздел. + +После запуска обычного worker сценарий ожидает истечения аренды и повторную обработку того же ID и поколения. Он сравнивает SHA-256 оригинала и трёх вариантов до и после повтора. Очистка staging проверяется в двух состояниях с тестовым временем для cleaner. Активные исходники защищены, а после `ready` удаляются staging-объекты с сохранением опубликованного результата. Тест удаляет только свой Compose-проект и его тома. + ## Нагрузка ```sh @@ -43,6 +63,18 @@ python3 tests/load.py --duration 30 --concurrency 4 --output evidence/load.json Это простой **closed-loop** генератор POST сообщений; он ограничен производительностью клиента и страдает coordinated omission. Он выдаёт successful RPS, ошибки и p50/p95/p99 **только успешных запросов**. Во время нагрузки нет прозрачных retry; timeout мог скрыть совершённую запись, поэтому это throughput HTTP-подтверждений, не точный счётчик COMMIT. Изменение размера истории входит в профиль. Для серьёзного исследования используйте k6/Locust/wrk либо свой обоснованный генератор, а не выводите максимальную пропускную способность из одного запуска этого скрипта. Для нагрузки pipeline изображений нужен отдельный сценарий студента. +## Трек 1. Очередь вложений под перегрузкой + +```sh +python3 -X utf8 tests/queue_overload.py --capacity 16 --output evidence/queue-overload.json +``` + +Сценарий создаёт отдельный Compose-проект с четырьмя партициями Kafka и одной репликой worker. Он сравнивает три профиля concurrency/prefetch — **1 / 8 КиБ**, **2 / 64 КиБ**, **4 / 1 МиБ** — на одинаковых синтетических PNG стороной 256, 1024 и 3072 пикселя. Гипотеза для сравнения профилей состоит в том, что параллельная обработка может поднять throughput и сократить ожидание в очереди при увеличении RSS, особенно для больших изображений. + +Для каждого прогона тест останавливает worker и заполняет очередь до заданной ёмкости. Ещё три запроса должны вернуть `429` с `Retry-After`. Число принятых задач должно совпасть с ёмкостью. Затем тест запускает worker с выбранными параметрами, проверяет переход всех принятых ID в `ready` и нулевой lag. Контрольная загрузка после дренирования тоже должна дойти до `ready`. + +JSON-отчёт содержит throughput по времени исполнения worker, p95 от `created_at` до записи `ready`, серию Kafka lag по зафиксированным offset, пиковый RSS процесса и распределение заданий по партициям. Время дренирования с учётом старта контейнера записывается отдельно. P95 включает ожидание при заполнении очереди. Прогоны создают управляемый всплеск нагрузки с одинаковым размером группы задач. Результаты характеризуют сочетания настроек и синтетический набор PNG на конкретной машине. + ## HTTPS, lab7 ```sh diff --git a/tests/outbox-crash.cjs b/tests/outbox-crash.cjs new file mode 100644 index 00000000..1c18f049 --- /dev/null +++ b/tests/outbox-crash.cjs @@ -0,0 +1,26 @@ +const { existsSync, writeSync } = require('node:fs'); +const { setTimeout: delay } = require('node:timers/promises'); +const { Kafka } = require('kafkajs'); + +const originalProducer = Kafka.prototype.producer; +Kafka.prototype.producer = function (options) { + const producer = originalProducer.call(this, options); + const { connect, send } = producer; + + producer.connect = async () => { + // Let the HTTP upload commit and respond before the publisher claims the row. + while (!existsSync('/tmp/lab5-outbox-crash-release')) await delay(100); + await connect.call(producer); + }; + producer.send = (batch) => { + if (batch.topic === 'attachments.process.v1') { + writeSync(2, JSON.stringify({ + event: 'outbox_crash_before_publish', + attachmentIds: batch.messages.map(({ key }) => key), + }) + '\n'); + process.exit(86); + } + return send.call(producer, batch); + }; + return producer; +}; diff --git a/tests/outbox_crash.py b/tests/outbox_crash.py new file mode 100644 index 00000000..753db567 --- /dev/null +++ b/tests/outbox_crash.py @@ -0,0 +1,139 @@ +#!/usr/bin/env python3 +"""Crash the API in an isolated Compose project after outbox COMMIT.""" +import json +import re +import subprocess +import tempfile +import time +import urllib.request +import uuid +from pathlib import Path + +from client import Client, Failure, NoRedirect, ROOT, check, run + +TOPIC = 'attachments.process.v1' +GATE = '/tmp/lab5-outbox-crash-release' +PRELOAD = '/app/outbox-crash.cjs' + + +def docker(*args, timeout=60, show_output=False, include_stderr=False): + try: + result = subprocess.run( + ['docker', *args], cwd=ROOT, text=True, encoding='utf-8', + errors='replace', capture_output=not show_output, timeout=timeout, + ) + except subprocess.TimeoutExpired: + raise Failure(f'Docker command timed out after {timeout} seconds') from None + if result.returncode: + raise Failure(f'Docker command failed with exit code {result.returncode}: {args[0]}') + output = result.stdout or '' + if include_stderr: + output += result.stderr or '' + return output.strip() + + +def api_client(compose): + binding = compose('port', 'api', '8080') + check(re.fullmatch(r'127\.0\.0\.1:[0-9]+', binding), 'expected a loopback API port') + client = Client('http://' + binding, timeout=30) + client.opener = urllib.request.build_opener(urllib.request.ProxyHandler({}), NoRedirect()) + return client + + +def snapshot(compose, attachment_id): + query = ( + 'SELECT a.status, a.published_at IS NOT NULL, a.generation, ' + '(SELECT count(*) FROM attachment_outbox AS o WHERE o.attachment_id = a.id) ' + f"FROM attachments AS a WHERE a.id = '{attachment_id}'::uuid" + ) + return compose( + 'exec', '-T', 'postgres', 'sh', '-c', + 'exec psql -X -At -v ON_ERROR_STOP=1 -U "$POSTGRES_USER" -d "$POSTGRES_DB" -c "$1"', + 'sh', query, + ) + + +def topic_offset(compose): + output = compose( + 'exec', '-T', 'kafka', '/opt/kafka/bin/kafka-get-offsets.sh', + '--bootstrap-server', 'kafka:9092', '--topic', TOPIC, timeout=90, + ) + offsets = re.findall(r'^' + re.escape(TOPIC) + r':0:([0-9]+)$', output, re.MULTILINE) + check(len(offsets) == 1, 'expected the Kafka attachment topic offset') + return int(offsets[0]) + + +def main(): + project = 'lab5-outbox-crash-' + uuid.uuid4().hex[:12] + with tempfile.TemporaryDirectory(prefix=project + '-') as directory: + overlay = Path(directory) / 'compose.json' + api = { + 'deploy': {'replicas': 1}, + 'restart': 'no', + 'ports': [{'host_ip': '127.0.0.1', 'target': 8080, 'published': '0'}], + 'healthcheck': {'start_period': '120s'}, + } + instrumented = dict( + api, + environment={'NODE_OPTIONS': '--require=' + PRELOAD}, + volumes=[{ + 'type': 'bind', 'source': str(ROOT / 'tests/outbox-crash.cjs'), + 'target': PRELOAD, 'read_only': True, + }], + ) + + def configure(api_config): + overlay.write_text(json.dumps({'services': {'api': api_config}}), encoding='utf-8') + + def compose(*args, **options): + return docker( + 'compose', '-p', project, '-f', str(ROOT / 'compose.yaml'), '-f', + str(overlay), *args, **options, + ) + + configure(instrumented) + try: + print('Starting isolated Compose test: ' + project, flush=True) + compose('up', '-d', '--build', '--wait', '--wait-timeout', '240', + 'api', timeout=900, show_output=True) + compose('up', '-d', '--build', '--no-deps', 'worker', + timeout=900, show_output=True) + client = api_client(compose) + alice, bob, _, chat = client.bootstrap() + accepted, original = client.attachment(alice, chat) + attachment_id = str(uuid.UUID(accepted['id'])) + check(snapshot(compose, attachment_id) == 'queued|f|0|1', 'upload was not committed to outbox') + before = topic_offset(compose) + check(before == 0, 'the attachment topic is not empty before injection') + + container = compose('ps', '-q', 'api') + check(re.fullmatch(r'[0-9a-f]{12,64}', container), 'expected a single API container') + compose('exec', '-T', 'api', 'touch', GATE) + check(docker('container', 'wait', container, timeout=90) == '86', 'expected injected API exit code 86') + logs = docker('container', 'logs', container, include_stderr=True) + marker = {'event': 'outbox_crash_before_publish', 'attachmentIds': [attachment_id]} + check(json.dumps(marker, separators=(',', ':')) in logs, 'wrong attachment in injected crash') + check(snapshot(compose, attachment_id) == 'queued|f|0|1', 'outbox job changed during the crash') + check(topic_offset(compose) == before, 'Kafka received a record before the API crashed') + print('PASS: committed upload survived injected exit before Kafka publish', flush=True) + + configure(api) + compose('up', '-d', '--no-deps', '--no-build', '--force-recreate', '--wait', + '--wait-timeout', '180', 'api', timeout=240, show_output=True) + recovered = api_client(compose) + ready = recovered.wait_ready(bob, accepted, wait_seconds=120) + check(ready['id'] == attachment_id and ready['sha256'] == accepted['sha256'], + 'recovery returned a different attachment') + content = recovered.call('GET', '/api/v1/attachments/' + attachment_id + '/content', actor=bob) + check(content['bytes'] == original, 'original bytes changed after recovery') + deadline = time.monotonic() + 30 + while snapshot(compose, attachment_id) != 'ready|t|0|0': + check(time.monotonic() < deadline, 'publisher did not clear the outbox after Kafka confirmation') + time.sleep(0.5) + print('PASS: the same attachment reached ready through outbox after restarting API') + finally: + compose('down', '--volumes', '--timeout', '5', timeout=150, show_output=True) + + +if __name__ == '__main__': + run(main) diff --git a/tests/queue_overload.py b/tests/queue_overload.py new file mode 100644 index 00000000..d7babb4a --- /dev/null +++ b/tests/queue_overload.py @@ -0,0 +1,323 @@ +#!/usr/bin/env python3 +"""Compare identical overloaded queue cohorts in an isolated lab5 Compose project.""" +import argparse +import json +import math +import os +import random +import re +import struct +import tempfile +import time +import uuid +import zlib +from pathlib import Path + +from client import Failure, ROOT, check, run, timestamp +from outbox_crash import api_client, docker + +PROFILES = ((1, 8 * 1024), (2, 64 * 1024), (4, 1024 * 1024)) +SIZES = (256, 1024, 3072) +PARTITIONS = 4 +PRELOAD = '/app/track1-rss.cjs' +SAMPLE = """ +const { PrismaService } = require('./dist/prisma/prisma.service.js'); +const { attachmentKafka, ATTACHMENT_GROUP, ATTACHMENT_TOPIC } = + require('./dist/Attachment/attachment-kafka.js'); +const db = new PrismaService(); +const admin = attachmentKafka('track1-monitor').admin(); +async function sample() { + try { + await admin.connect(); + const [rows, ends, [group]] = await Promise.all([ + db.attachment.findMany({ where: { chatId: process.argv[1] }, select: { + id: true, status: true, createdAt: true, updatedAt: true, + } }), + admin.fetchTopicOffsets(ATTACHMENT_TOPIC), + admin.fetchOffsets({ groupId: ATTACHMENT_GROUP, topics: [ATTACHMENT_TOPIC] }), + ]); + const committed = new Map(group.partitions.map(({ partition, offset }) => + [partition, BigInt(offset)])); + const partitions = ends.map(({ partition, low, high }) => { + const offset = committed.get(partition) ?? -1n; + const start = offset < BigInt(low) ? BigInt(low) : offset; + return { partition, high, lag: Math.max(0, Number(BigInt(high) - start)) }; + }); + console.log(JSON.stringify({ rows, partitions })); + } finally { + await Promise.all([db.$disconnect(), admin.disconnect()]); + } +} +void sample().catch(() => { process.exitCode = 1; }); +""" + + +def png_fixture(side): + def chunk(kind, body): + return (struct.pack('>I', len(body)) + kind + body + + struct.pack('>I', zlib.crc32(kind + body))) + + row = random.Random(side).randbytes(side * 3) + compressor = zlib.compressobj() + data = [] + for y in range(side): + shift = (y * 17 % side) * 3 + data.append(compressor.compress(b'\x00' + row[shift:] + row[:shift])) + data.append(compressor.flush()) + header = struct.pack('>IIBBBBB', side, side, 8, 2, 0, 0, 0) + return (b'\x89PNG\r\n\x1a\n' + chunk(b'IHDR', header) + + chunk(b'IDAT', b''.join(data)) + chunk(b'IEND', b'')) + + +def eventually(read, accept, message, timeout=240): + deadline = time.monotonic() + timeout + while time.monotonic() < deadline: + value = read() + check(all(row['status'] != 'failed' for row in value['rows']), + 'an accepted attachment reached failed') + if accept(value): + return value + time.sleep(0.5) + raise Failure(message) + + +def lag(sample): + return sum(partition['lag'] for partition in sample['partitions']) + + +def queue_sample(compose, chat_id): + output = compose('exec', '-T', 'api', 'node', '-e', SAMPLE, chat_id) + value = json.loads(output.splitlines()[-1]) + check(len(value['partitions']) == PARTITIONS, 'unexpected Kafka partition count') + return value + + +def warmup_attachment(compose, client, actor, chat_id, image): + chat_id = str(uuid.UUID(chat_id)) + path = '/api/v1/chats/' + chat_id + '/attachments?filename=warmup.png' + query = f"SELECT id FROM attachments WHERE chat_id = '{chat_id}'::uuid ORDER BY created_at LIMIT 1" + for _ in range(5): + response = client.call('POST', path, (202, 503), actor=actor, raw=image, + headers={'Content-Type': 'image/png'}, schema='Attachment') + if response['status'] == 202: + return response['json'] + saved = compose( + 'exec', '-T', 'postgres', 'sh', '-c', + 'exec psql -X -At -v ON_ERROR_STOP=1 -U "$POSTGRES_USER" -d "$POSTGRES_DB" -c "$1"', + 'sh', query, + ) + if saved: + return {'id': str(uuid.UUID(saved))} + time.sleep(2) + raise Failure('API returned 503 on all warmup uploads') + + +def report_failures(compose): + try: + logs = compose('logs', '--no-color', '--no-log-prefix', '--tail', '50', 'api', 'worker') + except Failure: + return + for line in logs.splitlines(): + if not line.startswith('{'): + continue + try: + record = json.loads(line) + except ValueError: + continue + error = record.get('err') + status = record.get('status') + if isinstance(error, dict) and isinstance(status, int) and status >= 500: + cause = error.get('cause') + cause = cause if isinstance(cause, dict) else {} + print('API error:', error.get('type'), error.get('code'), + 'cause:', cause.get('type'), cause.get('code'), flush=True) + elif record.get('logger') == 'kafkajs' and record.get('level') == 'ERROR': + print('Kafka error:', record.get('error'), flush=True) + + +def worker_metrics(compose, accepted, concurrency, prefetch): + container = compose('ps', '-a', '-q', 'worker') + check(re.fullmatch(r'[0-9a-f]{12,64}', container), 'expected one worker container') + logs = docker('container', 'logs', container, include_stderr=True) + records = [json.loads(line) for line in logs.splitlines() + if line.startswith('{"event":"track1_')] + settings = next((row for row in records if row['event'] == 'track1_worker_settings'), None) + check(settings is not None and settings['concurrency'] == concurrency + and settings['prefetch'] == prefetch, 'worker used unexpected settings') + peak = next((row for row in records if row['event'] == 'track1_worker_rss'), None) + check(peak is not None and peak['peakBytes'] > 0, 'worker did not report peak RSS') + check(0 < peak['peakActive'] <= concurrency, 'worker exceeded configured concurrency') + jobs = {} + for record in records: + if record['event'] == 'track1_job_finished' and record['id'] in accepted: + jobs.setdefault(record['id'], record) + check(set(jobs) == accepted, 'missing worker timing for accepted job') + seconds = (max(row['finished'] for row in jobs.values()) + - min(row['started'] for row in jobs.values())) / 1000 + check(seconds > 0, 'invalid worker execution window') + return peak, len(accepted) / seconds + + +def trial(compose, client, actor, chat_id, side, image, capacity, concurrency, prefetch): + path = '/api/v1/chats/' + chat_id + '/attachments?filename=track1.png' + + def upload(): + return client.call('POST', path, (202, 429), actor=actor, raw=image, + headers={'Content-Type': 'image/png'}, schema='Attachment') + + def sample(): + return queue_sample(compose, chat_id) + + baseline = sample() + check(lag(baseline) == 0, 'previous trial left Kafka lag') + accepted = set() + for _ in range(capacity): + response = upload() + check(response['status'] == 202 and response['json']['status'] == 'queued', + 'queue rejected a request before reaching its capacity') + accepted.add(response['json']['id']) + check(len(accepted) == capacity, 'upload returned duplicate attachment IDs') + for _ in range(3): + response = upload() + check(response['status'] == 429 and response['json']['error']['code'] == 'rate_limited' + and response['headers'].get('Retry-After', '').isdigit() + and int(response['headers']['Retry-After']) > 0, 'expected backpressure with Retry-After') + + saturated = eventually(sample, lambda value: lag(value) >= capacity, + 'publisher did not deliver the saturated cohort') + check({row['id'] for row in saturated['rows']} == accepted + and all(row['status'] == 'queued' for row in saturated['rows']), + 'queue contains extra work after overload') + partition_load = [ + int(item['high']) - int(next(old['high'] for old in baseline['partitions'] + if old['partition'] == item['partition'])) + for item in saturated['partitions'] + ] + + started = time.monotonic() + compose('up', '-d', '--no-build', '--no-deps', '--force-recreate', 'worker', show_output=True) + series = [] + + def observe(): + value = sample() + series.append({'seconds': round(time.monotonic() - started, 3), + 'kafka_lag': lag(value), + 'ready': sum(row['status'] == 'ready' for row in value['rows']), + 'processing': sum(row['status'] == 'processing' for row in value['rows'])}) + check(series[-1]['processing'] <= concurrency, 'worker exceeded configured concurrency') + return value + + drained = eventually(observe, lambda value: len(value['rows']) == capacity + and all(row['status'] == 'ready' for row in value['rows']) + and lag(value) == 0, 'worker did not drain the admitted cohort') + elapsed = time.monotonic() - started + check({row['id'] for row in drained['rows']} == accepted, 'accepted attachment IDs changed') + latency_ms = sorted((timestamp(row['updatedAt']) - timestamp(row['createdAt'])).total_seconds() * 1000 + for row in drained['rows']) + + response = upload() + check(response['status'] == 202, 'API did not resume admission after draining') + client.wait_ready(actor, response['json'], wait_seconds=120) + eventually(sample, lambda value: lag(value) == 0, 'Kafka did not acknowledge the recovery upload') + compose('stop', '--timeout', '120', 'worker', timeout=150, show_output=True) + peak, throughput = worker_metrics(compose, accepted, concurrency, prefetch) + return { + 'concurrency': concurrency, 'prefetch_bytes_per_partition': prefetch, + 'image_side_px': side, 'image_bytes': len(image), 'accepted': capacity, + 'rejected_429': 3, 'recovery_upload_ready': True, + 'partition_load': partition_load, + 'throughput_ready_per_second': round(throughput, 3), + 'cold_drain_seconds': round(elapsed, 3), + 'p95_created_to_ready_ms': round(latency_ms[math.ceil(0.95 * capacity) - 1], 3), + 'initial_kafka_lag': lag(saturated), + 'peak_observed_kafka_lag': max(lag(saturated), *(point['kafka_lag'] for point in series)), + 'worker_peak_rss_bytes': peak['peakBytes'], 'peak_active_handlers': peak['peakActive'], + 'samples': series, + } + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--capacity', type=int, default=16, choices=range(4, 65), metavar='4..64') + parser.add_argument('--output', type=Path, default=ROOT / 'evidence' / 'queue-overload.json') + args = parser.parse_args() + project = 'lab5-track1-' + uuid.uuid4().hex[:12] + os.environ['ATTACHMENT_TOPIC_PARTITIONS'] = str(PARTITIONS) + fixtures = {side: png_fixture(side) for side in SIZES} + results = [] + + with tempfile.TemporaryDirectory(prefix=project + '-') as directory: + overlay = Path(directory) / 'compose.json' + api = { + 'deploy': {'replicas': 1}, + 'ports': [{'host_ip': '127.0.0.1', 'target': 8080, 'published': '0'}], + 'healthcheck': {'start_period': '120s'}, + 'environment': {'ATTACHMENT_QUEUE_CAPACITY': str(args.capacity)}, + } + + def configure(concurrency, prefetch, warmup=False): + worker = { + 'restart': 'unless-stopped' if warmup else 'no', + 'environment': { + 'NODE_OPTIONS': '--require=' + PRELOAD, + 'WORKER_CONCURRENCY': str(concurrency), + 'WORKER_PREFETCH_BYTES': str(prefetch), + 'DB_POOL_MAX': '8', + }, + 'volumes': [{ + 'type': 'bind', 'source': str(ROOT / 'tests/track1-rss.cjs'), + 'target': PRELOAD, 'read_only': True, + }], + } + overlay.write_text(json.dumps({'services': {'api': api, 'worker': worker}}), encoding='utf-8') + + def compose(*command, **options): + return docker('compose', '-p', project, '-f', str(ROOT / 'compose.yaml'), + '-f', str(overlay), *command, **options) + + # On a new broker the group coordinator may come up after the broker listener. + configure(*PROFILES[0], warmup=True) + try: + compose('build', 'api', 'worker', 'migrate', 's3-init', timeout=900, show_output=True) + compose('up', '-d', '--no-build', '--wait', '--wait-timeout', '360', + 'api', timeout=600, show_output=True) + client = api_client(compose) + actor = client.user('track1') + + def new_chat(): + return client.call('POST', '/api/v1/chats', 201, actor=actor, + body={'title': 'Track 1', 'member_ids': [actor['id']]}, + schema='Chat')['json'] + + compose('up', '-d', '--no-build', '--no-deps', 'worker', show_output=True) + warmup_chat = new_chat() + warmup = warmup_attachment(compose, client, actor, warmup_chat['id'], fixtures[SIZES[0]]) + client.wait_ready(actor, warmup, wait_seconds=240) + eventually(lambda: queue_sample(compose, warmup_chat['id']), + lambda value: lag(value) == 0, 'warmup offset was not committed') + compose('stop', '--timeout', '120', 'worker', timeout=150, show_output=True) + for concurrency, prefetch in PROFILES: + configure(concurrency, prefetch) + for side, image in fixtures.items(): + chat_id = new_chat()['id'] + result = trial(compose, client, actor, chat_id, side, image, + args.capacity, concurrency, prefetch) + results.append(result) + print(f'PASS: {side}px, concurrency={concurrency}, prefetch={prefetch}, ' + f'{result["throughput_ready_per_second"]} jobs/s, ' + f'p95={result["p95_created_to_ready_ms"]} ms, ' + f'peak RSS={result["worker_peak_rss_bytes"]} bytes', flush=True) + except Failure: + report_failures(compose) + raise + finally: + compose('down', '--volumes', '--timeout', '5', timeout=150, show_output=True) + + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps({'partitions': PARTITIONS, 'trials': results}, indent=2) + '\n', + encoding='utf-8') + print('Report:', args.output) + + +if __name__ == '__main__': + run(main) diff --git a/tests/track1-rss.cjs b/tests/track1-rss.cjs new file mode 100644 index 00000000..07c807fc --- /dev/null +++ b/tests/track1-rss.cjs @@ -0,0 +1,48 @@ +const { writeSync } = require('node:fs'); +const { Kafka } = require('kafkajs'); +const { AttachmentWorker } = require('./dist/Attachment/attachment-worker.js'); + +function marker(event) { + writeSync(2, JSON.stringify(event) + '\n'); +} + +const consumer = Kafka.prototype.consumer; +Kafka.prototype.consumer = function (options) { + const instance = consumer.call(this, options); + const { run } = instance; + instance.run = (settings) => { + marker({ + event: 'track1_worker_settings', + concurrency: settings.partitionsConsumedConcurrently ?? 1, + prefetch: options.maxBytesPerPartition ?? 1048576, + }); + return run.call(instance, settings); + }; + return instance; +}; + +const processJob = AttachmentWorker.prototype.process; +let active = 0; +let peakActive = 0; +AttachmentWorker.prototype.process = async function (job, ...args) { + const started = performance.now(); + active++; + peakActive = Math.max(active, peakActive); + try { + const completed = await processJob.call(this, job, ...args); + if (completed) marker({ + event: 'track1_job_finished', id: job.id, started, finished: performance.now(), + }); + return completed; + } finally { + active--; + } +}; + +process.on('exit', () => { + marker({ + event: 'track1_worker_rss', + peakBytes: process.resourceUsage().maxRSS * 1024, + peakActive, + }); +}); diff --git a/tests/worker-crash.cjs b/tests/worker-crash.cjs new file mode 100644 index 00000000..e0fcd681 --- /dev/null +++ b/tests/worker-crash.cjs @@ -0,0 +1,46 @@ +const { writeSync } = require('node:fs'); +const { Kafka } = require('kafkajs'); +const Broker = require('kafkajs/src/broker'); +const { StorageService } = require('./dist/Storage/storage.service.js'); + +function marker(event) { + writeSync(2, JSON.stringify(event) + '\n'); +} + +const consumer = Kafka.prototype.consumer; +Kafka.prototype.consumer = function (options) { + const instance = consumer.call(this, options); + const { run } = instance; + instance.run = (settings) => { + marker({ + event: 'worker_consumer_settings', + concurrency: settings.partitionsConsumedConcurrently ?? 1, + autoCommit: settings.autoCommit, + }); + return run.call(instance, settings); + }; + return instance; +}; + +const fetch = Broker.prototype.fetch; +let fetchLogged = false; +Broker.prototype.fetch = function (request) { + const topic = request.topics.find(({ topic }) => topic === 'attachments.process.v1'); + if (topic && !fetchLogged) { + fetchLogged = true; + marker({ + event: 'worker_fetch_budget', + maxBytes: request.maxBytes, + partitions: topic.partitions.map(({ partition, maxBytes }) => ({ partition, maxBytes })), + }); + } + return fetch.call(this, request); +}; + +const publishCopy = StorageService.prototype.publishCopy; +StorageService.prototype.publishCopy = async function (...args) { + await publishCopy.apply(this, args); + const [staging, original] = args; + marker({ event: 'worker_crash_after_s3_write', staging, original }); + process.exit(87); +}; diff --git a/tests/worker_crash.py b/tests/worker_crash.py new file mode 100644 index 00000000..a26a5ed3 --- /dev/null +++ b/tests/worker_crash.py @@ -0,0 +1,265 @@ +#!/usr/bin/env python3 +"""Redeliver a worker job after S3 writes and before the Kafka offset commit.""" +import json +import re +import tempfile +import time +import uuid +from pathlib import Path + +from client import Failure, ROOT, check, run +from outbox_crash import api_client, docker + +PRELOAD = '/app/worker-crash.cjs' +VARIANTS = {'thumbnail', 'crop', 'optimized'} + +KAFKA_STATE = """ +const { ATTACHMENT_GROUP, ATTACHMENT_TOPIC, attachmentKafka } = + require('./dist/Attachment/attachment-kafka.js'); +const admin = attachmentKafka('worker-crash-check').admin(); +async function readOffset() { + await admin.connect(); + try { + const [[topic], result] = await Promise.all([ + admin.fetchOffsets({ groupId: ATTACHMENT_GROUP, topics: [ATTACHMENT_TOPIC] }), + admin.describeGroups([ATTACHMENT_GROUP]), + ]); + console.log(JSON.stringify({ + offset: Number(topic.partitions.find(({ partition }) => partition === 0).offset), + members: result.groups[0].members.length, + })); + } finally { + await admin.disconnect(); + } +} +void readOffset().catch(() => { process.exitCode = 1; }); +""" + +OBJECT_HASHES = """ +const { createHash } = require('node:crypto'); +const { StorageService } = require('./dist/Storage/storage.service.js'); +const { variantKeyFor } = require('./dist/Attachment/attachment-keys.js'); +const [chatId, id] = process.argv.slice(1); +const keys = { + original: `originals/${chatId}/${id}`, + ...Object.fromEntries(['thumbnail', 'crop', 'optimized'].map( + (name) => [name, variantKeyFor({ chatId, id }, name)], + )), +}; +const storage = new StorageService(); +async function readHashes() { + try { + const hashes = {}; + for (const [name, key] of Object.entries(keys)) { + const hash = createHash('sha256'); + for await (const chunk of await storage.get(key)) hash.update(chunk); + hashes[name] = hash.digest('hex'); + } + console.log(JSON.stringify(hashes)); + } finally { + storage.onModuleDestroy(); + } +} +void readHashes().catch(() => { process.exitCode = 1; }); +""" + +STAGING_CLEANUP = """ +const { PrismaService } = require('./dist/prisma/prisma.service.js'); +const { StorageService } = require('./dist/Storage/storage.service.js'); +const { cleanStaging } = require('./dist/Attachment/staging-cleanup.js'); +const [chatId, firstId, secondId] = process.argv.slice(1); +const db = new PrismaService(); +const storage = new StorageService(); +async function clean() { + try { + // Age the fixtures for the cleaner without advancing the worker lease clock. + const now = new Date(Date.now() + 3_600_000); + const report = await cleanStaging(db, storage, { + apply: true, graceSeconds: 600, prefix: `originals/${chatId}/`, + }, now); + const remaining = []; + for (const id of [firstId, secondId]) { + if (await storage.stat(`staging/${chatId}/${id}`)) remaining.push(id); + } + console.log(JSON.stringify({ ...report, remaining })); + } finally { + storage.onModuleDestroy(); + await db.$disconnect(); + } +} +void clean().catch(() => { process.exitCode = 1; }); +""" + + +def eventually(read, accept, timeout, message): + deadline = time.monotonic() + timeout + while time.monotonic() < deadline: + value = read() + if accept(value): + return value + time.sleep(0.5) + raise Failure(message) + + +def state(compose, attachment_id): + query = ( + 'SELECT json_build_object(\'status\', status, \'failures\', failures, ' + '\'generation\', generation, \'lease\', extract(epoch FROM lease_until), ' + '\'updated\', extract(epoch FROM updated_at), \'published\', published_at IS NOT NULL) ' + f"FROM attachments WHERE id = '{attachment_id}'::uuid" + ) + result = compose( + 'exec', '-T', 'postgres', 'sh', '-c', + 'exec psql -X -At -v ON_ERROR_STOP=1 -U "$POSTGRES_USER" -d "$POSTGRES_DB" -c "$1"', + 'sh', query, + ) + check(bool(result), 'missing attachment in PostgreSQL') + return json.loads(result) + + +def worker_event(logs, event): + for line in logs.splitlines(): + if json.dumps(event) in line: + record = json.loads(line) + if record.get('event') == event: + return record + raise Failure('missing worker event ' + event) + + +def main(): + project = 'lab5-worker-crash-' + uuid.uuid4().hex[:12] + with tempfile.TemporaryDirectory(prefix=project + '-') as directory: + overlay = Path(directory) / 'compose.json' + api = { + 'deploy': {'replicas': 1}, + 'ports': [{'host_ip': '127.0.0.1', 'target': 8080, 'published': '0'}], + 'healthcheck': {'start_period': '120s'}, + } + instrumented = { + 'restart': 'no', + 'environment': {'NODE_OPTIONS': '--require=' + PRELOAD}, + 'volumes': [{ + 'type': 'bind', 'source': str(ROOT / 'tests/worker-crash.cjs'), + 'target': PRELOAD, 'read_only': True, + }], + } + + def configure(worker): + overlay.write_text(json.dumps({'services': {'api': api, 'worker': worker}}), encoding='utf-8') + + def compose(*args, **options): + return docker('compose', '-p', project, '-f', str(ROOT / 'compose.yaml'), + '-f', str(overlay), *args, **options) + + def run_api_js(script, *args): + return compose('exec', '-T', 'api', 'node', '-e', script, *args) + + def kafka_state(): + return json.loads(run_api_js(KAFKA_STATE).splitlines()[-1]) + + def cleanup(chat_id, first_id, second_id): + return json.loads(compose( + 'run', '--rm', '--no-deps', '-T', 'reconciler', 'node', '-e', + STAGING_CLEANUP, chat_id, first_id, second_id, timeout=90, + )) + + configure(instrumented) + try: + print('Starting isolated Compose test: ' + project, flush=True) + compose('build', 'api', 'worker', 'reconciler', 'migrate', 's3-init', + timeout=900, show_output=True) + compose('up', '-d', '--no-build', '--wait', '--wait-timeout', '360', + 'api', timeout=600, show_output=True) + client = api_client(compose) + alice, bob, _, chat = client.bootstrap() + first, original = client.attachment(alice, chat) + first_id = str(uuid.UUID(first['id'])) + eventually(lambda: state(compose, first_id), lambda row: row['published'], + 90, 'publisher did not confirm the first queued job') + second, _ = client.attachment(alice, chat) + chat_id = str(uuid.UUID(chat['id'])) + second_id = str(uuid.UUID(second['id'])) + eventually(lambda: state(compose, second_id), lambda row: row['published'], + 90, 'publisher did not confirm the second queued job') + + compose('up', '-d', '--no-build', '--no-deps', 'worker', show_output=True) + container = compose('ps', '-a', '-q', 'worker') + check(re.fullmatch(r'[0-9a-f]{12,64}', container), 'expected a single worker container') + check(docker('container', 'wait', container, timeout=120) == '87', + 'expected an injected worker exit after the copy') + logs = docker('container', 'logs', container, include_stderr=True) + marker = worker_event(logs, 'worker_crash_after_s3_write') + check(marker['staging'] == f'staging/{chat_id}/{first_id}' + and marker['original'] == f'originals/{chat_id}/{first_id}', + 'fault occurred on the wrong attachment') + settings = worker_event(logs, 'worker_consumer_settings') + check(settings['concurrency'] == 1 and settings['autoCommit'] is False, + 'expected serial consumption with manual offset commit') + fetch = worker_event(logs, 'worker_fetch_budget') + check(0 < fetch['maxBytes'] <= 10 * 1024 * 1024 + and len(fetch['partitions']) == 1 + and fetch['partitions'][0]['partition'] == 0 + and 0 < fetch['partitions'][0]['maxBytes'] <= 1024 * 1024, + 'Kafka fetch exceeds the worker prefetch budget') + + interrupted = state(compose, first_id) + check(interrupted['status'] == 'processing' and interrupted['failures'] == 0 + and interrupted['lease'] is not None + and interrupted['lease'] > interrupted['updated'], + 'interrupted job has no recoverable processing lease') + waiting = state(compose, second_id) + check(waiting['status'] == 'queued' and waiting['failures'] == 0 + and waiting['lease'] is None, 'second job started before the interrupted job completed') + check(kafka_state()['offset'] <= 0, + 'Kafka committed the interrupted job') + before = json.loads(run_api_js(OBJECT_HASHES, chat_id, first_id)) + check(before['original'] == first['sha256'], 'original was not stored before worker exit') + protected = cleanup(chat_id, first_id, second_id) + check(set(protected['remaining']) == {first_id, second_id} + and protected['stagingDeleted'] == 0, 'cleanup removed active staging') + print('PASS: worker crashed after S3 writes, before Kafka ack; staging is protected', + flush=True) + + eventually(kafka_state, lambda value: value['members'] == 0, + 240, 'Kafka did not expire the crashed consumer session') + + configure({}) + compose('up', '-d', '--no-deps', '--no-build', '--force-recreate', + 'worker', show_output=True) + try: + ready = client.wait_ready(bob, first, wait_seconds=300) + client.wait_ready(bob, second, wait_seconds=120) + except Failure as error: + first_state = state(compose, first_id) + second_state = state(compose, second_id) + container = compose('ps', '-a', '-q', 'worker') + details = docker('container', 'logs', '--tail', '15', container, include_stderr=True) + print(details, flush=True) + raise Failure(f'{error}. First job: {first_state}; second job: {second_state}') from error + metadata = state(compose, first_id) + check(ready['id'] == first_id and metadata['generation'] == 0 + and metadata['failures'] == 1 and metadata['lease'] is None + and metadata['updated'] >= interrupted['lease'], + 'worker did not recover the same job after lease expiry') + after = json.loads(run_api_js(OBJECT_HASHES, chat_id, first_id)) + check(before == after and {item['name'] for item in ready['variants']} == VARIANTS + and len(ready['variants']) == len(VARIANTS) + and all(item['sha256'] == after[item['name']] for item in ready['variants']), + 'redelivery changed the stored result') + content = client.call('GET', f'/api/v1/attachments/{first_id}/content', actor=bob) + check(content['bytes'] == original, 'download differs after redelivery') + eventually(kafka_state, lambda value: value['offset'] >= 2, + 30, 'worker did not commit completed jobs') + + cleaned = cleanup(chat_id, first_id, second_id) + check(cleaned['remaining'] == [] and cleaned['stagingDeleted'] == 2, + 'cleanup did not delete staging after ready') + check(json.loads(run_api_js(OBJECT_HASHES, chat_id, first_id)) == after, + 'cleanup changed the published result') + print('PASS: worker crash, lease recovery, bounded fetch, and safe staging cleanup') + finally: + compose('down', '--volumes', '--timeout', '5', timeout=150, show_output=True) + + +if __name__ == '__main__': + run(main)