diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md index e6e63eb2..29a0daa4 100644 --- a/.github/pull_request_template.md +++ b/.github/pull_request_template.md @@ -1,18 +1,23 @@ ## Лабораторная 3 -Автор / группа: TODO -Целевая оценка (3/4/5): TODO -Трек 5, если заявлен: TODO +Автор / группа: Синюк Максим Павлович БПИ2301 +Целевая оценка (3/4/5): 5 +Трек 1, если заявлен: "Цена масштабирования" -Что реализовано и что перенесено: TODO -Команды запуска из чистого clone: TODO -Результаты проверок и ссылка на REPORT.md: TODO -Ограничения / известные ошибки: TODO -Источники и использование ИИ: TODO +Что реализовано и что перенесено: перенесены пользовательские тесты, валидация(перенастроена на пароль), роуты(перенастроены на защиту по токену сессии), модели ORM и работа с БД PostgreSQL, Redis кэширование +Команды запуска из чистого clone: cd mtusi2026lab3 | docker compose -d --build | docker compose logs api --tail 50 +Результаты проверок и ссылка на REPORT.md: https://gitea.privcloud.tech/Atelier77/mtusi2026lab3/src/branch/solution/БПИ2301-Синюк/REPORT.md +Ограничения / известные ошибки: описано в REPORT.md +Источники и использование ИИ: руками, составление прогонов конкурентности -- [ ] Весь обязательный минимум текущей и предыдущих работ сохранён с объявленными переходами. -- [ ] Контракт и публичные тесты не ослаблены. -- [ ] make check и make test выполнены; приложен реальный вывод. -- [ ] Сценарии отказов/безопасности своего уровня воспроизведены. -- [ ] Все секреты и приватные ключи находятся вне Git; отчёт не содержит tokens. -- [ ] README задания сохранён, REPORT.md содержит инструкцию именно моего решения. +Graceful Degradation: SIGTERM перестаёт принимать новые запросы, выполняет уже полученные в течение 30 секунд и останавливает процесс, встроенная функция сервера Uvicorn. Для проверки отказоустойчивости был использован скрипт `scripts/failover_test.sh`, который выполняет нагрузочное тестирование (`tests/load.py`) с помощью файла `scripts/test_idempotency_failover.py` и последовательно останавливает/восстанавливает(проверка на отказоустойчивость) реплики API. Результат описан в README.md и метрики представлены в `results/failover_metrics.json`. Идемпотентность при параллельных запросах с одинаковым idempotency-key проводилась с concurrency 4, duration 60s и при 2 репликах api с ограничениями cpus 0.5 и memory 512M. Cache Stampede при холодном запуске решается через Redis Lock на idempotency-key для конкретного запроса благодаря асинхронности запросов. Параллельные запросы с одним idempotent-key создают одну запись, response кэшируется и отдаётся без обращения к БД. Health/readiness и timeouts настроены в `docker-compose.yml` и `nginx.conf`, время обнаружения отказа инстанса ~20 сек. Миграции вынесены в отдельный сервис `migrate` в `docker-compose.yml`. Сервис `api` имеет зависимость `depends_on: migrate (condition: service_completed_successfully)`. В виду этого миграции выполняются только один раз перед запуском реплик api. Реплики API только проверяют подключение к БД и инициализируют Redis. + +В эксперименте проверена обработка насыщения пула соединений, при которой клиент поулчает статус ошибки 503 вместо выдачи общего 500 для retry запросов в скрипте `python scripts/check_503_retry_after.py --n 64`. Первые запросы занимают вес пул, а оставшиеся получают response 503 с extra_headers `Retry-After`. Все запросы корректны обработаны, ключ и тело запросов не менялись. Конкуренция: 64; wall time: 0.50s; реплик наблюдалось: 2 ['api-24fde5d9', 'api-df7eae98'] результат в `results/check_overloaded_handler_503.log`. Конфигурации с идентичным CPU API (2×1.0) и зафиксированным PostgreSQL (1.0): D_pool_starved: DB_POOL_SIZE=2, DB_MAX_OVERFLOW=0, DB_POOL_TIMEOUT=5. D_pool_normal: DB_POOL_SIZE=10, DB_MAX_OVERFLOW=20, DB_POOL_TIMEOUT=30. суммарный пул растёт как replicas × (pool_size + max_overflow). При 4 репликах × 30 = 120 потенциальных соединений против ёмкости одноядерной БД добавление реплик усиливает contention, а не пропускную способность. Рост реплик перестаёт увеличивать RPS. Диаграммы получены через `scripts/plot_scaling.py` и хранятся в `results/scaling/*.png`. Конкуренция в эксперименте проводилась с параметрами [8, 16, 32, 64] + + +- [+] Весь обязательный минимум текущей и предыдущих работ сохранён с объявленными переходами. +- [+] Контракт и публичные тесты не ослаблены. +- [+] make check и make test выполнены; приложен реальный вывод. +- [+] Сценарии отказов/безопасности своего уровня воспроизведены. +- [+] Все секреты и приватные ключи находятся вне Git; отчёт не содержит tokens. +- [+] README задания сохранён, REPORT.md содержит инструкцию именно моего решения. diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 00000000..82c04a64 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,37 @@ +FROM python:3.13-slim AS Builder + +WORKDIR /app + +COPY requirements.txt . + +RUN python -m venv /opt/venv + +ENV PATH="/opt/venv/bin:$PATH" + +RUN pip install --no-cache-dir --upgrade pip && pip install --no-cache-dir -r requirements.txt + +FROM python:3.13-slim + +WORKDIR /app + +COPY --from=Builder /opt/venv /opt/venv + +ENV PATH="/opt/venv/bin:$PATH" + +RUN groupadd -r appuser && useradd -r -g appuser -d /app -s /sbin/nologin appuser + +COPY src/ ./src/ + +COPY scripts/ ./scripts/ + +RUN chown -R appuser:appuser /app + +USER appuser + +EXPOSE 8080 + +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8080/health/live')" || exit 1 + +STOPSIGNAL SIGTERM + +CMD ["python", "-m", "uvicorn", "src.main:application", "--host", "0.0.0.0", "--port", "8080", "--workers", "1"] \ No newline at end of file diff --git a/Makefile b/Makefile index 5d86d171..8b1646cd 100644 --- a/Makefile +++ b/Makefile @@ -1,4 +1,5 @@ -PYTHON ?= python3 +PYTHON ?= python +export PYTHONUTF8 := 1 BASE_URL ?= http://localhost:8080 CA_FILE ?= ACTION_SCRIPT ?= diff --git a/REPORT.md b/REPORT.md index c2679005..47a1fec2 100644 --- a/REPORT.md +++ b/REPORT.md @@ -1,37 +1,75 @@ # Отчёт — лабораторная 3 -- Автор, группа: TODO -- Целевая оценка; выбранный трек 5, если нужен: TODO -- Commit/PR: TODO после публикации -- Использованные источники, библиотеки и помощь ИИ: TODO +- Автор, группа: Синюк Максим Павлович БПИ2301 +- Целевая оценка; выбранный трек 5, если нужен: 5, трек 1 "Цена масштабирования" +- Commit/PR: https://gitea.privcloud.tech/mtusi2026/mtusi2026lab3/pulls/166 +- Использованные источники, библиотеки и помощь ИИ: перенос базы lab2, python, fastapi, uvicorn, pydantic, pytest, sqlalchemy, argon2-cffi, redis ## Запуск из чистого clone TODO: версии runtime/образов, prerequisites, команды создания локальных secrets/.env, build, миграций, запуска, ожидания готовности, тестов и остановки. Указать необходимые действия оператора. Не вставлять секреты. Отдельно указать безопасную остановку и команду намеренного удаления учебных данных. +git clone -b "solution/БПИ2301-Синюк" https://gitea.privcloud.tech/Atelier77/mtusi2026lab3 +docker compose build +docker compose up -d +docker ps +docker compose down + ## Архитектура и решения TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab2, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации. +Из lab2 перенесены описание классов для работы с таблицами БД через ORM - src/api/repositories/ +модели ORM таблиц для PostgreSQL - src/models/ +валидация - src/pydantic_valid/ +student_tests/ +Добавлен Nginx для LB, работающий по имени сервиса api c 2 репликами, где каждая реплика обладает своим X-INSTANCE_ID в headers. +Idempotent-Key, генерируемый при отправке запросов обеспечивает сохранность состояния системы в использовании метода send_message. + ## Доказательства критериев | Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства | | --- | --- | --- | --- | -| Публичный smoke | make test | TODO | TODO | +| Публичный smoke | make test | PASS: lab3 public API scenario; infrastructure and grading evidence remain separate. | results/make_test.log | | Остальные пункты уровня 3 | TODO | TODO | TODO | +| Пользовательские тесты | `python -m pytest student_tests/ -v` | 20 passed in 10.50s | `results/student_tests.log` | +| Проверка контрактов | python scripts/check_contract.py | PASS: offline skeleton structure, local refs and Python syntax; application NOT tested. | `results/check_contract.log` | +| Валидация openapi | python scripts/check_contract.py | PASS: full OpenAPI 3.1 and JSON Schema validation; application NOT tested. | `results/validate_openapi.log` | +| Нагрузочный тест | `python tests/load.py --duration 30 --concurrency 10| "successful_rps": 134.009, "error_ratio": 0.0 | `results/load.log` | +| Проверка нагрузки | python tests/load.py | Latency percentiles cover successes only. | `results/test_load.log` | | Все пункты уровня 4, если заявлен | TODO | TODO | TODO | +| Последовательно остановите API-реплику, соберите RPS, ошибки, идемпотентность при параллельных запросах с одним ключом | chmod +x scripts/failover.sh --> git bash: ./scripts/failover_test.sh | Отправка 5 параллельных запросов с ключом: failover-test-key-48cc8fb4cd7a46b282292636122fa0c8 +Полученные статусы: [201, 201, 201, 201, 201] +Полученные ID сообщений: ['41646804-dfd6-43bf-b839-983c1244c8ee', '41646804-dfd6-43bf-b839-983c1244c8ee', '41646804-dfd6-43bf-b839-983c1244c8ee', '41646804-dfd6-43bf-b839-983c1244c8ee', '41646804-dfd6-43bf-b839-983c1244c8ee'] +PASS: Идемпотентность работает! Создано ровно 1 сообщение (ID: 41646804-dfd6-43bf-b839-983c1244c8ee) | results/failover_metrics.json | | Выбранный трек 5, если заявлен | TODO | TODO | TODO | +| Проверка обработки status 503 при перегрузке сервера вместо выдачи общего 500 для retry запросов| `python scripts/check_503_retry_after.py --n 64` | PASS: 503 unavailable + Retry-After correct, retries are safe, no dublicates | `results/check_overloaded_handler_503.log` | TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены. ## Эксперименты и отказы TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения. +1. Использование Keepalive у Nginx приведёт к росту RPS, так как TCP-handshake сократится и будет меньше занимать ресурсов. +2. | Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных | | --- | --- | --- | --- | | TODO | TODO | TODO | TODO | +| Cравнение 1/2/4 API-реплик при фиксированном суммарном CPU/RAM при возрастающих concurrency(нагрузке) | В определённой точке увеличение реплик не будет давать прироста RPS и снижения latency(p95, p99) | в `results/scaling/raw.json` находится результат измерений | "error_ratio":0.0, потерь нет, "requested_duration_seconds": 30.0 | +| Сравнение на диаграммах влияния роста реплик при остальных неизменных, влияние роста суммарного CPU при остальынх равных переменных, влияние keepalive и ситуация, когда суммарный пул при росте реплик replicas × (pool_size + max_overflow) оказывается больше, чем ёмкости самой БД и когда мы намеренно сужаем пул | рост RPS при добавление Keepalive; рост реплик перестанет увеличивать RPS | | conc | starved RPS | normal RPS | Δ | +|---|---|---|---| +| 10 | 87.5 | 95.0 | normal +8.5% | +| 15 | 98.5 | 103.5 | normal +5.1% | +| 32 | 99.5 | 89.0 | starved +11.8% | +| 64 | 104.5 | 76.5 | starved +36.6% | Разница проявилась при нагрузке c=32 и c=64 | потерь нет ни в одном из случаев | ## Ограничения и следующие шаги TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза. +Исчерпание пула соединений PostgreSQL: sqlalchemy.exc.TimeoutError → 503 unavailable + Retry-After: 1. Блокировка идемпотентности снимается, безопасный повтор с тем же ключом даёт 201. +Недоступность Redis: Graceful degradation: идемпотентность и кэш сессий не работают, но запросы проходят напрямую в PostgreSQL. Функциональность сохраняется. +PostgreSQL — единственная БД, не реплицирована. +Сессии и идемпотентность хранятся в Redis. Отказ Redis --> потеря идемпотентности +Nginx - единая точка входа, не реплицирована +Сетевой разрыв между API и PostgreSQL - 503 unavailable + Retry-After: 5 \ No newline at end of file diff --git a/docker-compose.yaml b/docker-compose.yaml new file mode 100644 index 00000000..3b4077a9 --- /dev/null +++ b/docker-compose.yaml @@ -0,0 +1,106 @@ +services: + migrate: + build: . + command: python -m scripts.run_migrations + environment: + - DATABASE_URL=postgresql+asyncpg://mtusi:1878@postgres:5432/mtusi-messenger + depends_on: + postgres: + condition: service_healthy + nginx: + image: nginx:1.25-alpine + ports: + - "8080:80" + volumes: + - ./infra/nginx.conf.template:/etc/nginx/templates/nginx.conf.template:ro + environment: + - NGINX_ENVSUBST_OUTPUT_DIR=/etc/nginx + - KEEPALIVE_DIRECTIVE=${KEEPALIVE_DIRECTIVE:-} + - PROXY_HTTP_VERSION_DIRECTIVE=${PROXY_HTTP_VERSION_DIRECTIVE:-} + - PROXY_CONNECTION_DIRECTIVE=${PROXY_CONNECTION_DIRECTIVE:-} + depends_on: + api: + condition: service_healthy + deploy: + resources: + limits: + cpus: '${NGINX_CPU:-1.0}' + memory: ${NGINX_MEM:-256M} + restart: unless-stopped + api: + build: . + environment: + - APP_HOST=${APP_HOST} + - APP_PORT=${APP_PORT} + - DATABASE_URL=${DATABASE_URL} + - SESSION_TTL_SECONDS=${SESSION_TTL_SECONDS} + - REDIS_URL=${REDIS_URL} + - INSTANCE_ID_PREFIX=api + - DB_POOL_SIZE=${DB_POOL_SIZE:-10} + - DB_MAX_OVERFLOW=${DB_MAX_OVERFLOW:-20} + - DB_POOL_TIMEOUT=${DB_POOL_TIMEOUT:-30} + - DB_POOL_RECYCLE=${DB_POOL_RECYCLE:-3600} + depends_on: + postgres: + condition: service_healthy + redis: + condition: service_healthy + migrate: + condition: service_completed_successfully + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8080/health/ready', timeout=2)"] #засекретить? + interval: 10s + timeout: 3s + start_period: 15s + retries: 3 + deploy: + replicas: ${API_REPLICAS:-2} + resources: + limits: + cpus: '${API_CPU:-1.0}' + memory: ${API_MEM:-512M} + + postgres: + image: postgres:16.3-alpine + environment: + POSTGRES_USER: ${POSTGRES_USER} + POSTGRES_PASSWORD: ${POSTGRES_PASSWORD} + POSTGRES_DB: ${POSTGRES_DB} + ports: + - "127.0.0.1:5433:5432" + volumes: + - pgdata:/var/lib/postgresql/data + - ./migrations:/docker-entrypoint-initdb.d:ro + command: postgres -c shared_preload_libraries=pg_stat_statements + healthcheck: + test: ["CMD-SHELL", "pg_isready -U ${POSTGRES_USER} -d ${POSTGRES_DB}"] + interval: 5s + timeout: 3s + start_period: 10s + retries: 5 + restart: unless-stopped + + redis: + image: redis:8.10-alpine + command: redis-server --appendonly yes --save 60 1 + ports: + - "127.0.0.1:6379:6379" + volumes: + - redisdata:/data + deploy: + resources: + limits: + cpus: '${REDIS_CPU:-0.5}' + memory: ${REDIS_MEM:-256M} + healthcheck: + test: ["CMD", "redis-cli", "ping"] + interval: 5s + timeout: 3s + start_period: 5s + retries: 5 + restart: unless-stopped + +volumes: + pgdata: + redisdata: \ No newline at end of file diff --git a/infra/nginx.conf b/infra/nginx.conf new file mode 100644 index 00000000..5eb67a39 --- /dev/null +++ b/infra/nginx.conf @@ -0,0 +1,31 @@ +worker_processes auto; + +events { + worker_connections 1024; +} + +http { + upstream backend{ + server api:8080 max_fails=2 fail_timeout=10s; + } + server { + listen 80; + server_name localhost; + proxy_connect_timeout 5s; + proxy_read_timeout 30s; + + location / { + proxy_pass http://backend; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + } + + location /nginx-health { + access_log off; + return 200 "healthy\n"; + add_header Content-Type text/plain; + } + } +} diff --git a/infra/nginx.conf.template b/infra/nginx.conf.template new file mode 100644 index 00000000..8116ae29 --- /dev/null +++ b/infra/nginx.conf.template @@ -0,0 +1,40 @@ +worker_processes auto; + +events { + worker_connections 4096; +} + +http { + access_log off; + sendfile on; + tcp_nopush on; + + upstream backend { + server api:8080 max_fails=2 fail_timeout=10s; + ${KEEPALIVE_DIRECTIVE} + } + + server { + listen 80; + server_name _; + + proxy_connect_timeout 5s; + proxy_send_timeout 30s; + proxy_read_timeout 30s; + proxy_next_upstream error timeout http_502 http_503 http_504; + proxy_next_upstream_tries 2; + proxy_next_upstream_timeout 10s; + + location / { + proxy_pass http://backend; + + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + + ${PROXY_HTTP_VERSION_DIRECTIVE} + ${PROXY_CONNECTION_DIRECTIVE} + } + } +} \ No newline at end of file diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 00000000..20c99be5 Binary files /dev/null and b/requirements.txt differ diff --git a/results/failover_metrics.json b/results/failover_metrics.json new file mode 100644 index 00000000..07ce3535 --- /dev/null +++ b/results/failover_metrics.json @@ -0,0 +1,17 @@ +{ + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 60.0, + "elapsed_seconds": 60.241, + "concurrency": 4, + "successful_requests": 1127, + "failed_requests": 18, + "error_ratio": 0.015721, + "successful_rps": 18.708, + "successful_latency_ms": { + "p50": 106.965, + "p95": 237.71, + "p99": 406.082 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/results/scaling/load/A_r1_c16_r0.json b/results/scaling/load/A_r1_c16_r0.json new file mode 100644 index 00000000..06d4f55f --- /dev/null +++ b/results/scaling/load/A_r1_c16_r0.json @@ -0,0 +1,17 @@ +{ + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.478, + "concurrency": 16, + "successful_requests": 2026, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 66.475, + "successful_latency_ms": { + "p50": 234.353, + "p95": 281.039, + "p99": 344.44 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/results/scaling/load/A_r1_c16_r1.json b/results/scaling/load/A_r1_c16_r1.json new file mode 100644 index 00000000..dbdaa236 --- /dev/null +++ b/results/scaling/load/A_r1_c16_r1.json @@ -0,0 +1,17 @@ +{ + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.525, + "concurrency": 16, + "successful_requests": 1849, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 60.574, + "successful_latency_ms": { + "p50": 248.988, + "p95": 336.154, + "p99": 461.645 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/results/scaling/load/A_r1_c32_r0.json b/results/scaling/load/A_r1_c32_r0.json new file mode 100644 index 00000000..d74c2ae6 --- /dev/null +++ b/results/scaling/load/A_r1_c32_r0.json @@ -0,0 +1,17 @@ +{ + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.994, + "concurrency": 32, + "successful_requests": 2034, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 65.625, + "successful_latency_ms": { + "p50": 468.588, + "p95": 552.38, + "p99": 651.877 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/results/scaling/load/A_r1_c32_r1.json b/results/scaling/load/A_r1_c32_r1.json new file mode 100644 index 00000000..26cfc436 --- /dev/null +++ b/results/scaling/load/A_r1_c32_r1.json @@ -0,0 +1,17 @@ +{ + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 31.009, + "concurrency": 32, + "successful_requests": 2038, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 65.724, + "successful_latency_ms": { + "p50": 465.812, + "p95": 576.753, + "p99": 610.491 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/results/scaling/load/A_r1_c64_r0.json b/results/scaling/load/A_r1_c64_r0.json new file mode 100644 index 00000000..f893a45d --- /dev/null +++ b/results/scaling/load/A_r1_c64_r0.json @@ -0,0 +1,17 @@ +{ + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 32.232, + "concurrency": 64, + "successful_requests": 1977, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 61.336, + "successful_latency_ms": { + "p50": 932.19, + "p95": 1549.981, + "p99": 1981.849 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/results/scaling/load/A_r1_c64_r1.json b/results/scaling/load/A_r1_c64_r1.json new file mode 100644 index 00000000..ffd000c0 --- /dev/null +++ b/results/scaling/load/A_r1_c64_r1.json @@ -0,0 +1,17 @@ +{ + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 32.24, + "concurrency": 64, + "successful_requests": 1960, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 60.795, + "successful_latency_ms": { + "p50": 931.875, + "p95": 1485.929, + "p99": 1885.831 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/results/scaling/load/A_r1_c8_r0.json b/results/scaling/load/A_r1_c8_r0.json new file mode 100644 index 00000000..1017ce75 --- /dev/null +++ b/results/scaling/load/A_r1_c8_r0.json @@ -0,0 +1,17 @@ +{ + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.185, + "concurrency": 8, + "successful_requests": 2616, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 86.667, + "successful_latency_ms": { + "p50": 85.718, + "p95": 134.249, + "p99": 187.593 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/results/scaling/load/A_r1_c8_r1.json b/results/scaling/load/A_r1_c8_r1.json new file mode 100644 index 00000000..537f26df --- /dev/null +++ b/results/scaling/load/A_r1_c8_r1.json @@ -0,0 +1,17 @@ +{ + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.28, + "concurrency": 8, + "successful_requests": 2286, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 75.496, + "successful_latency_ms": { + "p50": 100.869, + "p95": 150.892, + "p99": 185.123 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/results/scaling/load/A_r1_c8_warmup.json b/results/scaling/load/A_r1_c8_warmup.json new file mode 100644 index 00000000..8863fc04 --- /dev/null +++ b/results/scaling/load/A_r1_c8_warmup.json @@ -0,0 +1,17 @@ +{ + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 10.0, + "elapsed_seconds": 10.292, + "concurrency": 8, + "successful_requests": 825, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 80.162, + "successful_latency_ms": { + "p50": 94.073, + "p95": 142.321, + "p99": 166.258 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/results/scaling/load/A_r2_c16_r0.json b/results/scaling/load/A_r2_c16_r0.json new file mode 100644 index 00000000..a044294f --- /dev/null +++ b/results/scaling/load/A_r2_c16_r0.json @@ -0,0 +1,17 @@ +{ + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.512, + "concurrency": 16, + "successful_requests": 3027, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 99.205, + "successful_latency_ms": { + "p50": 153.453, + "p95": 285.16, + "p99": 493.002 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/results/scaling/load/A_r2_c16_r1.json b/results/scaling/load/A_r2_c16_r1.json new file mode 100644 index 00000000..42791cda --- /dev/null +++ b/results/scaling/load/A_r2_c16_r1.json @@ -0,0 +1,17 @@ +{ + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.501, + "concurrency": 16, + "successful_requests": 2846, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 93.31, + "successful_latency_ms": { + "p50": 159.716, + "p95": 309.903, + "p99": 481.809 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/results/scaling/load/A_r2_c32_r0.json b/results/scaling/load/A_r2_c32_r0.json new file mode 100644 index 00000000..a2d71773 --- /dev/null +++ b/results/scaling/load/A_r2_c32_r0.json @@ -0,0 +1,17 @@ +{ + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.99, + "concurrency": 32, + "successful_requests": 2989, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 96.452, + "successful_latency_ms": { + "p50": 308.318, + "p95": 488.57, + "p99": 774.614 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/results/scaling/load/A_r2_c32_r1.json b/results/scaling/load/A_r2_c32_r1.json new file mode 100644 index 00000000..41b6671c --- /dev/null +++ b/results/scaling/load/A_r2_c32_r1.json @@ -0,0 +1,17 @@ +{ + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 31.056, + "concurrency": 32, + "successful_requests": 2980, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 95.956, + "successful_latency_ms": { + "p50": 319.373, + "p95": 495.198, + "p99": 665.019 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/results/scaling/load/A_r2_c64_r0.json b/results/scaling/load/A_r2_c64_r0.json new file mode 100644 index 00000000..323e9412 --- /dev/null +++ b/results/scaling/load/A_r2_c64_r0.json @@ -0,0 +1,17 @@ +{ + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 31.945, + "concurrency": 64, + "successful_requests": 2936, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 91.909, + "successful_latency_ms": { + "p50": 637.034, + "p95": 1229.16, + "p99": 1584.022 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/results/scaling/load/A_r2_c64_r1.json b/results/scaling/load/A_r2_c64_r1.json new file mode 100644 index 00000000..2cc60c66 --- /dev/null +++ b/results/scaling/load/A_r2_c64_r1.json @@ -0,0 +1,17 @@ +{ + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 32.068, + "concurrency": 64, + "successful_requests": 2975, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 92.77, + "successful_latency_ms": { + "p50": 641.492, + "p95": 1037.372, + "p99": 1272.2 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/results/scaling/load/A_r2_c8_r0.json b/results/scaling/load/A_r2_c8_r0.json new file mode 100644 index 00000000..ae80af07 --- /dev/null +++ b/results/scaling/load/A_r2_c8_r0.json @@ -0,0 +1,17 @@ +{ + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.224, + "concurrency": 8, + "successful_requests": 2982, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 98.663, + "successful_latency_ms": { + "p50": 75.859, + "p95": 120.146, + "p99": 269.584 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/results/scaling/load/A_r2_c8_r1.json b/results/scaling/load/A_r2_c8_r1.json new file mode 100644 index 00000000..697ea7d2 --- /dev/null +++ b/results/scaling/load/A_r2_c8_r1.json @@ -0,0 +1,17 @@ +{ + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.277, + "concurrency": 8, + "successful_requests": 2869, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 94.76, + "successful_latency_ms": { + "p50": 78.89, + "p95": 123.066, + "p99": 297.534 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/results/scaling/load/A_r2_c8_warmup.json b/results/scaling/load/A_r2_c8_warmup.json new file mode 100644 index 00000000..fc2714b7 --- /dev/null +++ b/results/scaling/load/A_r2_c8_warmup.json @@ -0,0 +1,17 @@ +{ + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 10.0, + "elapsed_seconds": 10.316, + "concurrency": 8, + "successful_requests": 945, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 91.607, + "successful_latency_ms": { + "p50": 77.755, + "p95": 132.126, + "p99": 302.922 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/results/scaling/load/A_r4_c16_r0.json b/results/scaling/load/A_r4_c16_r0.json new file mode 100644 index 00000000..c9fb0eb8 --- /dev/null +++ b/results/scaling/load/A_r4_c16_r0.json @@ -0,0 +1,17 @@ +{ + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.681, + "concurrency": 16, + "successful_requests": 2376, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 77.441, + "successful_latency_ms": { + "p50": 105.541, + "p95": 583.001, + "p99": 660.285 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/results/scaling/load/A_r4_c16_r1.json b/results/scaling/load/A_r4_c16_r1.json new file mode 100644 index 00000000..ad63ebe9 --- /dev/null +++ b/results/scaling/load/A_r4_c16_r1.json @@ -0,0 +1,17 @@ +{ + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.722, + "concurrency": 16, + "successful_requests": 2434, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 79.226, + "successful_latency_ms": { + "p50": 141.848, + "p95": 474.128, + "p99": 722.98 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/results/scaling/load/A_r4_c32_r0.json b/results/scaling/load/A_r4_c32_r0.json new file mode 100644 index 00000000..dac71891 --- /dev/null +++ b/results/scaling/load/A_r4_c32_r0.json @@ -0,0 +1,17 @@ +{ + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 31.872, + "concurrency": 32, + "successful_requests": 2650, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 83.144, + "successful_latency_ms": { + "p50": 257.054, + "p95": 1070.315, + "p99": 1698.114 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/results/scaling/load/A_r4_c32_r1.json b/results/scaling/load/A_r4_c32_r1.json new file mode 100644 index 00000000..a7ea9f2a --- /dev/null +++ b/results/scaling/load/A_r4_c32_r1.json @@ -0,0 +1,17 @@ +{ + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 32.15, + "concurrency": 32, + "successful_requests": 2404, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 74.775, + "successful_latency_ms": { + "p50": 334.773, + "p95": 1079.491, + "p99": 1308.01 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/results/scaling/load/A_r4_c64_r0.json b/results/scaling/load/A_r4_c64_r0.json new file mode 100644 index 00000000..9399421d --- /dev/null +++ b/results/scaling/load/A_r4_c64_r0.json @@ -0,0 +1,17 @@ +{ + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 33.168, + "concurrency": 64, + "successful_requests": 2487, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 74.981, + "successful_latency_ms": { + "p50": 691.618, + "p95": 1469.65, + "p99": 2366.364 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/results/scaling/load/A_r4_c64_r1.json b/results/scaling/load/A_r4_c64_r1.json new file mode 100644 index 00000000..5d3d692a --- /dev/null +++ b/results/scaling/load/A_r4_c64_r1.json @@ -0,0 +1,17 @@ +{ + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 33.445, + "concurrency": 64, + "successful_requests": 2507, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 74.959, + "successful_latency_ms": { + "p50": 769.191, + "p95": 1376.986, + "p99": 1608.463 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/results/scaling/load/A_r4_c8_r0.json b/results/scaling/load/A_r4_c8_r0.json new file mode 100644 index 00000000..f8396ab9 --- /dev/null +++ b/results/scaling/load/A_r4_c8_r0.json @@ -0,0 +1,17 @@ +{ + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.444, + "concurrency": 8, + "successful_requests": 2533, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 83.202, + "successful_latency_ms": { + "p50": 77.127, + "p95": 221.638, + "p99": 399.064 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/results/scaling/load/A_r4_c8_r1.json b/results/scaling/load/A_r4_c8_r1.json new file mode 100644 index 00000000..45d6cd5c --- /dev/null +++ b/results/scaling/load/A_r4_c8_r1.json @@ -0,0 +1,17 @@ +{ + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.258, + "concurrency": 8, + "successful_requests": 2434, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 80.44, + "successful_latency_ms": { + "p50": 90.472, + "p95": 203.446, + "p99": 310.23 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/results/scaling/load/A_r4_c8_warmup.json b/results/scaling/load/A_r4_c8_warmup.json new file mode 100644 index 00000000..055e5cc4 --- /dev/null +++ b/results/scaling/load/A_r4_c8_warmup.json @@ -0,0 +1,17 @@ +{ + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 10.0, + "elapsed_seconds": 10.356, + "concurrency": 8, + "successful_requests": 808, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 78.019, + "successful_latency_ms": { + "p50": 80.287, + "p95": 253.262, + "p99": 485.933 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/results/scaling/load/B_cpu1_c16_r0.json b/results/scaling/load/B_cpu1_c16_r0.json new file mode 100644 index 00000000..9d00bc43 --- /dev/null +++ b/results/scaling/load/B_cpu1_c16_r0.json @@ -0,0 +1,17 @@ +{ + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.543, + "concurrency": 16, + "successful_requests": 2045, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 66.955, + "successful_latency_ms": { + "p50": 231.418, + "p95": 464.595, + "p99": 896.102 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/results/scaling/load/B_cpu1_c16_r1.json b/results/scaling/load/B_cpu1_c16_r1.json new file mode 100644 index 00000000..8d11afe9 --- /dev/null +++ b/results/scaling/load/B_cpu1_c16_r1.json @@ -0,0 +1,17 @@ +{ + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.52, + "concurrency": 16, + "successful_requests": 2001, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 65.564, + "successful_latency_ms": { + "p50": 218.925, + "p95": 489.238, + "p99": 797.207 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/results/scaling/load/B_cpu1_c32_r0.json b/results/scaling/load/B_cpu1_c32_r0.json new file mode 100644 index 00000000..22a7e7d8 --- /dev/null +++ b/results/scaling/load/B_cpu1_c32_r0.json @@ -0,0 +1,17 @@ +{ + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 31.045, + "concurrency": 32, + "successful_requests": 1918, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 61.782, + "successful_latency_ms": { + "p50": 496.99, + "p95": 1004.052, + "p99": 1596.716 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/results/scaling/load/B_cpu1_c32_r1.json b/results/scaling/load/B_cpu1_c32_r1.json new file mode 100644 index 00000000..234f6e11 --- /dev/null +++ b/results/scaling/load/B_cpu1_c32_r1.json @@ -0,0 +1,17 @@ +{ + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.933, + "concurrency": 32, + "successful_requests": 2167, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 70.055, + "successful_latency_ms": { + "p50": 490.549, + "p95": 891.009, + "p99": 1314.072 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/results/scaling/load/B_cpu1_c64_r0.json b/results/scaling/load/B_cpu1_c64_r0.json new file mode 100644 index 00000000..909a7a93 --- /dev/null +++ b/results/scaling/load/B_cpu1_c64_r0.json @@ -0,0 +1,17 @@ +{ + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 31.903, + "concurrency": 64, + "successful_requests": 2064, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 64.697, + "successful_latency_ms": { + "p50": 873.782, + "p95": 1666.5, + "p99": 2075.07 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/results/scaling/load/B_cpu1_c64_r1.json b/results/scaling/load/B_cpu1_c64_r1.json new file mode 100644 index 00000000..ca590e81 --- /dev/null +++ b/results/scaling/load/B_cpu1_c64_r1.json @@ -0,0 +1,17 @@ +{ + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 31.751, + "concurrency": 64, + "successful_requests": 2170, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 68.343, + "successful_latency_ms": { + "p50": 868.913, + "p95": 1334.096, + "p99": 1783.243 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/results/scaling/load/B_cpu1_c8_r0.json b/results/scaling/load/B_cpu1_c8_r0.json new file mode 100644 index 00000000..fd3aa24f --- /dev/null +++ b/results/scaling/load/B_cpu1_c8_r0.json @@ -0,0 +1,17 @@ +{ + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.342, + "concurrency": 8, + "successful_requests": 1599, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 52.7, + "successful_latency_ms": { + "p50": 120.975, + "p95": 390.329, + "p99": 512.922 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/results/scaling/load/B_cpu1_c8_r1.json b/results/scaling/load/B_cpu1_c8_r1.json new file mode 100644 index 00000000..0cb3d8a9 --- /dev/null +++ b/results/scaling/load/B_cpu1_c8_r1.json @@ -0,0 +1,17 @@ +{ + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.373, + "concurrency": 8, + "successful_requests": 1705, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 56.136, + "successful_latency_ms": { + "p50": 118.07, + "p95": 281.239, + "p99": 479.55 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/results/scaling/load/B_cpu1_c8_warmup.json b/results/scaling/load/B_cpu1_c8_warmup.json new file mode 100644 index 00000000..19d4e903 --- /dev/null +++ b/results/scaling/load/B_cpu1_c8_warmup.json @@ -0,0 +1,17 @@ +{ + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 10.0, + "elapsed_seconds": 10.462, + "concurrency": 8, + "successful_requests": 485, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 46.359, + "successful_latency_ms": { + "p50": 155.551, + "p95": 467.648, + "p99": 687.875 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/results/scaling/load/B_cpu2_c16_r0.json b/results/scaling/load/B_cpu2_c16_r0.json new file mode 100644 index 00000000..c99de590 --- /dev/null +++ b/results/scaling/load/B_cpu2_c16_r0.json @@ -0,0 +1,17 @@ +{ + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.378, + "concurrency": 16, + "successful_requests": 4292, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 141.288, + "successful_latency_ms": { + "p50": 104.807, + "p95": 186.077, + "p99": 314.013 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/results/scaling/load/B_cpu2_c16_r1.json b/results/scaling/load/B_cpu2_c16_r1.json new file mode 100644 index 00000000..05ee8376 --- /dev/null +++ b/results/scaling/load/B_cpu2_c16_r1.json @@ -0,0 +1,17 @@ +{ + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.374, + "concurrency": 16, + "successful_requests": 4247, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 139.822, + "successful_latency_ms": { + "p50": 108.724, + "p95": 188.603, + "p99": 315.751 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/results/scaling/load/B_cpu2_c32_r0.json b/results/scaling/load/B_cpu2_c32_r0.json new file mode 100644 index 00000000..75dda559 --- /dev/null +++ b/results/scaling/load/B_cpu2_c32_r0.json @@ -0,0 +1,17 @@ +{ + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.746, + "concurrency": 32, + "successful_requests": 4413, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 143.532, + "successful_latency_ms": { + "p50": 207.516, + "p95": 328.611, + "p99": 585.259 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/results/scaling/load/B_cpu2_c32_r1.json b/results/scaling/load/B_cpu2_c32_r1.json new file mode 100644 index 00000000..386754fc --- /dev/null +++ b/results/scaling/load/B_cpu2_c32_r1.json @@ -0,0 +1,17 @@ +{ + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.702, + "concurrency": 32, + "successful_requests": 4354, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 141.813, + "successful_latency_ms": { + "p50": 209.27, + "p95": 335.597, + "p99": 544.982 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/results/scaling/load/B_cpu2_c64_r0.json b/results/scaling/load/B_cpu2_c64_r0.json new file mode 100644 index 00000000..57ce7daa --- /dev/null +++ b/results/scaling/load/B_cpu2_c64_r0.json @@ -0,0 +1,17 @@ +{ + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 31.457, + "concurrency": 64, + "successful_requests": 4383, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 139.332, + "successful_latency_ms": { + "p50": 405.878, + "p95": 693.679, + "p99": 932.377 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/results/scaling/load/B_cpu2_c64_r1.json b/results/scaling/load/B_cpu2_c64_r1.json new file mode 100644 index 00000000..724372dd --- /dev/null +++ b/results/scaling/load/B_cpu2_c64_r1.json @@ -0,0 +1,17 @@ +{ + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 31.551, + "concurrency": 64, + "successful_requests": 4259, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 134.987, + "successful_latency_ms": { + "p50": 427.633, + "p95": 644.277, + "p99": 869.437 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/results/scaling/load/B_cpu2_c8_r0.json b/results/scaling/load/B_cpu2_c8_r0.json new file mode 100644 index 00000000..59967ba5 --- /dev/null +++ b/results/scaling/load/B_cpu2_c8_r0.json @@ -0,0 +1,17 @@ +{ + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.169, + "concurrency": 8, + "successful_requests": 4375, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 145.015, + "successful_latency_ms": { + "p50": 50.258, + "p95": 84.407, + "p99": 176.587 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/results/scaling/load/B_cpu2_c8_r1.json b/results/scaling/load/B_cpu2_c8_r1.json new file mode 100644 index 00000000..a9f88911 --- /dev/null +++ b/results/scaling/load/B_cpu2_c8_r1.json @@ -0,0 +1,17 @@ +{ + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.193, + "concurrency": 8, + "successful_requests": 3929, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 130.129, + "successful_latency_ms": { + "p50": 55.65, + "p95": 104.916, + "p99": 176.69 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/results/scaling/load/B_cpu2_c8_warmup.json b/results/scaling/load/B_cpu2_c8_warmup.json new file mode 100644 index 00000000..be59ad98 --- /dev/null +++ b/results/scaling/load/B_cpu2_c8_warmup.json @@ -0,0 +1,17 @@ +{ + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 10.0, + "elapsed_seconds": 10.178, + "concurrency": 8, + "successful_requests": 1538, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 151.113, + "successful_latency_ms": { + "p50": 47.348, + "p95": 84.649, + "p99": 170.89 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/results/scaling/load/B_cpu4_c16_r0.json b/results/scaling/load/B_cpu4_c16_r0.json new file mode 100644 index 00000000..f0a2de17 --- /dev/null +++ b/results/scaling/load/B_cpu4_c16_r0.json @@ -0,0 +1,17 @@ +{ + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.383, + "concurrency": 16, + "successful_requests": 4496, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 147.976, + "successful_latency_ms": { + "p50": 108.467, + "p95": 176.095, + "p99": 202.449 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/results/scaling/load/B_cpu4_c16_r1.json b/results/scaling/load/B_cpu4_c16_r1.json new file mode 100644 index 00000000..5e7f92b4 --- /dev/null +++ b/results/scaling/load/B_cpu4_c16_r1.json @@ -0,0 +1,17 @@ +{ + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.413, + "concurrency": 16, + "successful_requests": 4427, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 145.565, + "successful_latency_ms": { + "p50": 111.739, + "p95": 177.898, + "p99": 195.162 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/results/scaling/load/B_cpu4_c32_r0.json b/results/scaling/load/B_cpu4_c32_r0.json new file mode 100644 index 00000000..5ecfe37d --- /dev/null +++ b/results/scaling/load/B_cpu4_c32_r0.json @@ -0,0 +1,17 @@ +{ + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.804, + "concurrency": 32, + "successful_requests": 4546, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 147.581, + "successful_latency_ms": { + "p50": 215.344, + "p95": 350.556, + "p99": 396.933 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/results/scaling/load/B_cpu4_c32_r1.json b/results/scaling/load/B_cpu4_c32_r1.json new file mode 100644 index 00000000..f8aaa268 --- /dev/null +++ b/results/scaling/load/B_cpu4_c32_r1.json @@ -0,0 +1,17 @@ +{ + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.783, + "concurrency": 32, + "successful_requests": 4551, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 147.843, + "successful_latency_ms": { + "p50": 216.853, + "p95": 320.175, + "p99": 349.21 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/results/scaling/load/B_cpu4_c64_r0.json b/results/scaling/load/B_cpu4_c64_r0.json new file mode 100644 index 00000000..8cfcb33b --- /dev/null +++ b/results/scaling/load/B_cpu4_c64_r0.json @@ -0,0 +1,17 @@ +{ + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 31.592, + "concurrency": 64, + "successful_requests": 4427, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 140.131, + "successful_latency_ms": { + "p50": 427.55, + "p95": 542.637, + "p99": 632.95 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/results/scaling/load/B_cpu4_c64_r1.json b/results/scaling/load/B_cpu4_c64_r1.json new file mode 100644 index 00000000..6bcd9963 --- /dev/null +++ b/results/scaling/load/B_cpu4_c64_r1.json @@ -0,0 +1,17 @@ +{ + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 31.652, + "concurrency": 64, + "successful_requests": 4250, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 134.272, + "successful_latency_ms": { + "p50": 440.725, + "p95": 631.239, + "p99": 757.651 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/results/scaling/load/B_cpu4_c8_r0.json b/results/scaling/load/B_cpu4_c8_r0.json new file mode 100644 index 00000000..3cc1c19a --- /dev/null +++ b/results/scaling/load/B_cpu4_c8_r0.json @@ -0,0 +1,17 @@ +{ + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.19, + "concurrency": 8, + "successful_requests": 4416, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 146.276, + "successful_latency_ms": { + "p50": 51.785, + "p95": 78.57, + "p99": 112.757 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/results/scaling/load/B_cpu4_c8_r1.json b/results/scaling/load/B_cpu4_c8_r1.json new file mode 100644 index 00000000..da808ce3 --- /dev/null +++ b/results/scaling/load/B_cpu4_c8_r1.json @@ -0,0 +1,17 @@ +{ + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.2, + "concurrency": 8, + "successful_requests": 4433, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 146.788, + "successful_latency_ms": { + "p50": 52.148, + "p95": 77.722, + "p99": 94.042 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/results/scaling/load/B_cpu4_c8_warmup.json b/results/scaling/load/B_cpu4_c8_warmup.json new file mode 100644 index 00000000..9b9b73d4 --- /dev/null +++ b/results/scaling/load/B_cpu4_c8_warmup.json @@ -0,0 +1,17 @@ +{ + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 10.0, + "elapsed_seconds": 10.202, + "concurrency": 8, + "successful_requests": 1443, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 141.441, + "successful_latency_ms": { + "p50": 50.563, + "p95": 97.307, + "p99": 137.588 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/results/scaling/load/B_cpu4_db2_c16_r0.json b/results/scaling/load/B_cpu4_db2_c16_r0.json new file mode 100644 index 00000000..7b2a2fd5 --- /dev/null +++ b/results/scaling/load/B_cpu4_db2_c16_r0.json @@ -0,0 +1,17 @@ +{ + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.402, + "concurrency": 16, + "successful_requests": 4586, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 150.848, + "successful_latency_ms": { + "p50": 104.502, + "p95": 172.493, + "p99": 194.08 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/results/scaling/load/B_cpu4_db2_c16_r1.json b/results/scaling/load/B_cpu4_db2_c16_r1.json new file mode 100644 index 00000000..31bc2823 --- /dev/null +++ b/results/scaling/load/B_cpu4_db2_c16_r1.json @@ -0,0 +1,17 @@ +{ + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.404, + "concurrency": 16, + "successful_requests": 4635, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 152.448, + "successful_latency_ms": { + "p50": 103.106, + "p95": 170.171, + "p99": 185.575 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/results/scaling/load/B_cpu4_db2_c32_r0.json b/results/scaling/load/B_cpu4_db2_c32_r0.json new file mode 100644 index 00000000..37ef59b7 --- /dev/null +++ b/results/scaling/load/B_cpu4_db2_c32_r0.json @@ -0,0 +1,17 @@ +{ + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.801, + "concurrency": 32, + "successful_requests": 4456, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 144.67, + "successful_latency_ms": { + "p50": 219.412, + "p95": 334.013, + "p99": 371.502 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/results/scaling/load/B_cpu4_db2_c32_r1.json b/results/scaling/load/B_cpu4_db2_c32_r1.json new file mode 100644 index 00000000..ec3ded46 --- /dev/null +++ b/results/scaling/load/B_cpu4_db2_c32_r1.json @@ -0,0 +1,17 @@ +{ + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.848, + "concurrency": 32, + "successful_requests": 4569, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 148.111, + "successful_latency_ms": { + "p50": 207.272, + "p95": 314.043, + "p99": 351.771 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/results/scaling/load/B_cpu4_db2_c64_r0.json b/results/scaling/load/B_cpu4_db2_c64_r0.json new file mode 100644 index 00000000..7f7e356c --- /dev/null +++ b/results/scaling/load/B_cpu4_db2_c64_r0.json @@ -0,0 +1,17 @@ +{ + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 31.627, + "concurrency": 64, + "successful_requests": 4694, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 148.418, + "successful_latency_ms": { + "p50": 404.299, + "p95": 556.187, + "p99": 641.569 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/results/scaling/load/B_cpu4_db2_c64_r1.json b/results/scaling/load/B_cpu4_db2_c64_r1.json new file mode 100644 index 00000000..9540ba9e --- /dev/null +++ b/results/scaling/load/B_cpu4_db2_c64_r1.json @@ -0,0 +1,17 @@ +{ + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 31.596, + "concurrency": 64, + "successful_requests": 4670, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 147.803, + "successful_latency_ms": { + "p50": 403.418, + "p95": 558.308, + "p99": 665.799 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/results/scaling/load/B_cpu4_db2_c8_r0.json b/results/scaling/load/B_cpu4_db2_c8_r0.json new file mode 100644 index 00000000..79f2ba99 --- /dev/null +++ b/results/scaling/load/B_cpu4_db2_c8_r0.json @@ -0,0 +1,17 @@ +{ + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.244, + "concurrency": 8, + "successful_requests": 4182, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 138.275, + "successful_latency_ms": { + "p50": 55.931, + "p95": 84.018, + "p99": 98.142 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/results/scaling/load/B_cpu4_db2_c8_r1.json b/results/scaling/load/B_cpu4_db2_c8_r1.json new file mode 100644 index 00000000..bbc980ca --- /dev/null +++ b/results/scaling/load/B_cpu4_db2_c8_r1.json @@ -0,0 +1,17 @@ +{ + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.192, + "concurrency": 8, + "successful_requests": 4380, + "failed_requests": 1, + "error_ratio": 0.000228, + "successful_rps": 145.07, + "successful_latency_ms": { + "p50": 51.436, + "p95": 83.217, + "p99": 123.483 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/results/scaling/load/B_cpu4_db2_c8_warmup.json b/results/scaling/load/B_cpu4_db2_c8_warmup.json new file mode 100644 index 00000000..4c7ce0ad --- /dev/null +++ b/results/scaling/load/B_cpu4_db2_c8_warmup.json @@ -0,0 +1,17 @@ +{ + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 10.0, + "elapsed_seconds": 10.208, + "concurrency": 8, + "successful_requests": 1321, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 129.411, + "successful_latency_ms": { + "p50": 56.017, + "p95": 99.568, + "p99": 130.942 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/results/scaling/load/C_after_c16_r0.json b/results/scaling/load/C_after_c16_r0.json new file mode 100644 index 00000000..4164ab65 --- /dev/null +++ b/results/scaling/load/C_after_c16_r0.json @@ -0,0 +1,17 @@ +{ + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.381, + "concurrency": 16, + "successful_requests": 4035, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 132.815, + "successful_latency_ms": { + "p50": 120.123, + "p95": 243.769, + "p99": 387.436 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/results/scaling/load/C_after_c16_r1.json b/results/scaling/load/C_after_c16_r1.json new file mode 100644 index 00000000..a36864a1 --- /dev/null +++ b/results/scaling/load/C_after_c16_r1.json @@ -0,0 +1,17 @@ +{ + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.536, + "concurrency": 16, + "successful_requests": 3519, + "failed_requests": 1, + "error_ratio": 0.000284, + "successful_rps": 115.241, + "successful_latency_ms": { + "p50": 126.575, + "p95": 245.77, + "p99": 414.042 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/results/scaling/load/C_after_c32_r0.json b/results/scaling/load/C_after_c32_r0.json new file mode 100644 index 00000000..81bd6f63 --- /dev/null +++ b/results/scaling/load/C_after_c32_r0.json @@ -0,0 +1,17 @@ +{ + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.877, + "concurrency": 32, + "successful_requests": 3798, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 123.006, + "successful_latency_ms": { + "p50": 245.379, + "p95": 434.78, + "p99": 813.811 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/results/scaling/load/C_after_c32_r1.json b/results/scaling/load/C_after_c32_r1.json new file mode 100644 index 00000000..a9fc0de0 --- /dev/null +++ b/results/scaling/load/C_after_c32_r1.json @@ -0,0 +1,17 @@ +{ + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.81, + "concurrency": 32, + "successful_requests": 4168, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 135.281, + "successful_latency_ms": { + "p50": 211.169, + "p95": 337.457, + "p99": 763.31 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/results/scaling/load/C_after_c64_r0.json b/results/scaling/load/C_after_c64_r0.json new file mode 100644 index 00000000..663e43fa --- /dev/null +++ b/results/scaling/load/C_after_c64_r0.json @@ -0,0 +1,17 @@ +{ + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 31.582, + "concurrency": 64, + "successful_requests": 4328, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 137.042, + "successful_latency_ms": { + "p50": 421.653, + "p95": 710.484, + "p99": 1016.113 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/results/scaling/load/C_after_c64_r1.json b/results/scaling/load/C_after_c64_r1.json new file mode 100644 index 00000000..e2ef7344 --- /dev/null +++ b/results/scaling/load/C_after_c64_r1.json @@ -0,0 +1,17 @@ +{ + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 31.766, + "concurrency": 64, + "successful_requests": 3989, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 125.574, + "successful_latency_ms": { + "p50": 452.114, + "p95": 791.945, + "p99": 1016.634 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/results/scaling/load/C_after_c8_r0.json b/results/scaling/load/C_after_c8_r0.json new file mode 100644 index 00000000..9873e736 --- /dev/null +++ b/results/scaling/load/C_after_c8_r0.json @@ -0,0 +1,17 @@ +{ + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.234, + "concurrency": 8, + "successful_requests": 3895, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 128.827, + "successful_latency_ms": { + "p50": 54.77, + "p95": 93.745, + "p99": 198.174 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/results/scaling/load/C_after_c8_r1.json b/results/scaling/load/C_after_c8_r1.json new file mode 100644 index 00000000..116d8c9f --- /dev/null +++ b/results/scaling/load/C_after_c8_r1.json @@ -0,0 +1,17 @@ +{ + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.216, + "concurrency": 8, + "successful_requests": 3282, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 108.616, + "successful_latency_ms": { + "p50": 61.722, + "p95": 146.556, + "p99": 252.043 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/results/scaling/load/C_after_c8_warmup.json b/results/scaling/load/C_after_c8_warmup.json new file mode 100644 index 00000000..dad23d28 --- /dev/null +++ b/results/scaling/load/C_after_c8_warmup.json @@ -0,0 +1,17 @@ +{ + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 10.0, + "elapsed_seconds": 10.218, + "concurrency": 8, + "successful_requests": 1538, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 150.513, + "successful_latency_ms": { + "p50": 47.964, + "p95": 77.854, + "p99": 153.869 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/results/scaling/load/C_before_c16_r0.json b/results/scaling/load/C_before_c16_r0.json new file mode 100644 index 00000000..3d158bed --- /dev/null +++ b/results/scaling/load/C_before_c16_r0.json @@ -0,0 +1,17 @@ +{ + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.394, + "concurrency": 16, + "successful_requests": 4062, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 133.644, + "successful_latency_ms": { + "p50": 119.527, + "p95": 215.968, + "p99": 343.529 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/results/scaling/load/C_before_c16_r1.json b/results/scaling/load/C_before_c16_r1.json new file mode 100644 index 00000000..7c822d8c --- /dev/null +++ b/results/scaling/load/C_before_c16_r1.json @@ -0,0 +1,17 @@ +{ + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.453, + "concurrency": 16, + "successful_requests": 3822, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 125.505, + "successful_latency_ms": { + "p50": 117.086, + "p95": 221.724, + "p99": 300.679 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/results/scaling/load/C_before_c32_r0.json b/results/scaling/load/C_before_c32_r0.json new file mode 100644 index 00000000..abaa4522 --- /dev/null +++ b/results/scaling/load/C_before_c32_r0.json @@ -0,0 +1,17 @@ +{ + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.784, + "concurrency": 32, + "successful_requests": 4200, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 136.436, + "successful_latency_ms": { + "p50": 225.049, + "p95": 338.21, + "p99": 565.592 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/results/scaling/load/C_before_c32_r1.json b/results/scaling/load/C_before_c32_r1.json new file mode 100644 index 00000000..0b3849fd --- /dev/null +++ b/results/scaling/load/C_before_c32_r1.json @@ -0,0 +1,17 @@ +{ + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.739, + "concurrency": 32, + "successful_requests": 4209, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 136.927, + "successful_latency_ms": { + "p50": 217.814, + "p95": 338.734, + "p99": 588.003 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/results/scaling/load/C_before_c64_r0.json b/results/scaling/load/C_before_c64_r0.json new file mode 100644 index 00000000..083eeaa6 --- /dev/null +++ b/results/scaling/load/C_before_c64_r0.json @@ -0,0 +1,17 @@ +{ + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 31.497, + "concurrency": 64, + "successful_requests": 4305, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 136.679, + "successful_latency_ms": { + "p50": 417.647, + "p95": 717.13, + "p99": 932.864 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/results/scaling/load/C_before_c64_r1.json b/results/scaling/load/C_before_c64_r1.json new file mode 100644 index 00000000..7501d4c0 --- /dev/null +++ b/results/scaling/load/C_before_c64_r1.json @@ -0,0 +1,17 @@ +{ + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 32.048, + "concurrency": 64, + "successful_requests": 4070, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 126.997, + "successful_latency_ms": { + "p50": 484.389, + "p95": 795.946, + "p99": 943.134 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/results/scaling/load/C_before_c8_r0.json b/results/scaling/load/C_before_c8_r0.json new file mode 100644 index 00000000..edf0b8e1 --- /dev/null +++ b/results/scaling/load/C_before_c8_r0.json @@ -0,0 +1,17 @@ +{ + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.183, + "concurrency": 8, + "successful_requests": 4301, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 142.496, + "successful_latency_ms": { + "p50": 51.983, + "p95": 80.987, + "p99": 148.524 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/results/scaling/load/C_before_c8_r1.json b/results/scaling/load/C_before_c8_r1.json new file mode 100644 index 00000000..7d35b8ad --- /dev/null +++ b/results/scaling/load/C_before_c8_r1.json @@ -0,0 +1,17 @@ +{ + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.194, + "concurrency": 8, + "successful_requests": 3919, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 129.792, + "successful_latency_ms": { + "p50": 55.238, + "p95": 104.713, + "p99": 181.21 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/results/scaling/load/C_before_c8_warmup.json b/results/scaling/load/C_before_c8_warmup.json new file mode 100644 index 00000000..3f02da66 --- /dev/null +++ b/results/scaling/load/C_before_c8_warmup.json @@ -0,0 +1,17 @@ +{ + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 10.0, + "elapsed_seconds": 10.195, + "concurrency": 8, + "successful_requests": 1330, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 130.455, + "successful_latency_ms": { + "p50": 52.304, + "p95": 121.626, + "p99": 192.689 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/results/scaling/load/D_pool_normal_c16_r0.json b/results/scaling/load/D_pool_normal_c16_r0.json new file mode 100644 index 00000000..c097e4d4 --- /dev/null +++ b/results/scaling/load/D_pool_normal_c16_r0.json @@ -0,0 +1,17 @@ +{ + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.459, + "concurrency": 16, + "successful_requests": 3085, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 101.283, + "successful_latency_ms": { + "p50": 153.651, + "p95": 286.247, + "p99": 390.87 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/results/scaling/load/D_pool_normal_c16_r1.json b/results/scaling/load/D_pool_normal_c16_r1.json new file mode 100644 index 00000000..c6a84a8b --- /dev/null +++ b/results/scaling/load/D_pool_normal_c16_r1.json @@ -0,0 +1,17 @@ +{ + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.451, + "concurrency": 16, + "successful_requests": 3231, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 106.106, + "successful_latency_ms": { + "p50": 142.19, + "p95": 265.706, + "p99": 419.588 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/results/scaling/load/D_pool_normal_c32_r0.json b/results/scaling/load/D_pool_normal_c32_r0.json new file mode 100644 index 00000000..5dc8026b --- /dev/null +++ b/results/scaling/load/D_pool_normal_c32_r0.json @@ -0,0 +1,17 @@ +{ + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.986, + "concurrency": 32, + "successful_requests": 3216, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 103.79, + "successful_latency_ms": { + "p50": 269.013, + "p95": 518.976, + "p99": 886.085 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/results/scaling/load/D_pool_normal_c32_r1.json b/results/scaling/load/D_pool_normal_c32_r1.json new file mode 100644 index 00000000..a5595357 --- /dev/null +++ b/results/scaling/load/D_pool_normal_c32_r1.json @@ -0,0 +1,17 @@ +{ + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 31.69, + "concurrency": 32, + "successful_requests": 2354, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 74.283, + "successful_latency_ms": { + "p50": 369.394, + "p95": 783.569, + "p99": 1111.781 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/results/scaling/load/D_pool_normal_c64_r0.json b/results/scaling/load/D_pool_normal_c64_r0.json new file mode 100644 index 00000000..45ae42c4 --- /dev/null +++ b/results/scaling/load/D_pool_normal_c64_r0.json @@ -0,0 +1,17 @@ +{ + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 32.502, + "concurrency": 64, + "successful_requests": 2276, + "failed_requests": 1, + "error_ratio": 0.000439, + "successful_rps": 70.026, + "successful_latency_ms": { + "p50": 686.258, + "p95": 1379.716, + "p99": 4132.014 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/results/scaling/load/D_pool_normal_c64_r1.json b/results/scaling/load/D_pool_normal_c64_r1.json new file mode 100644 index 00000000..37c804f7 --- /dev/null +++ b/results/scaling/load/D_pool_normal_c64_r1.json @@ -0,0 +1,17 @@ +{ + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 32.411, + "concurrency": 64, + "successful_requests": 2667, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 82.287, + "successful_latency_ms": { + "p50": 643.335, + "p95": 1390.41, + "p99": 1641.975 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/results/scaling/load/D_pool_normal_c8_r0.json b/results/scaling/load/D_pool_normal_c8_r0.json new file mode 100644 index 00000000..32fb30f9 --- /dev/null +++ b/results/scaling/load/D_pool_normal_c8_r0.json @@ -0,0 +1,17 @@ +{ + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.277, + "concurrency": 8, + "successful_requests": 2782, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 91.883, + "successful_latency_ms": { + "p50": 81.766, + "p95": 135.009, + "p99": 287.643 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/results/scaling/load/D_pool_normal_c8_r1.json b/results/scaling/load/D_pool_normal_c8_r1.json new file mode 100644 index 00000000..ca14266b --- /dev/null +++ b/results/scaling/load/D_pool_normal_c8_r1.json @@ -0,0 +1,17 @@ +{ + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.243, + "concurrency": 8, + "successful_requests": 2954, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 97.675, + "successful_latency_ms": { + "p50": 72.722, + "p95": 160.538, + "p99": 216.538 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/results/scaling/load/D_pool_normal_c8_warmup.json b/results/scaling/load/D_pool_normal_c8_warmup.json new file mode 100644 index 00000000..81cf385d --- /dev/null +++ b/results/scaling/load/D_pool_normal_c8_warmup.json @@ -0,0 +1,17 @@ +{ + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 10.0, + "elapsed_seconds": 10.236, + "concurrency": 8, + "successful_requests": 879, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 85.876, + "successful_latency_ms": { + "p50": 85.043, + "p95": 176.253, + "p99": 272.571 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/results/scaling/load/D_pool_starved_c16_r0.json b/results/scaling/load/D_pool_starved_c16_r0.json new file mode 100644 index 00000000..83d9945b --- /dev/null +++ b/results/scaling/load/D_pool_starved_c16_r0.json @@ -0,0 +1,17 @@ +{ + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.771, + "concurrency": 16, + "successful_requests": 3124, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 101.523, + "successful_latency_ms": { + "p50": 113.746, + "p95": 413.322, + "p99": 726.637 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/results/scaling/load/D_pool_starved_c16_r1.json b/results/scaling/load/D_pool_starved_c16_r1.json new file mode 100644 index 00000000..7e1dfa35 --- /dev/null +++ b/results/scaling/load/D_pool_starved_c16_r1.json @@ -0,0 +1,17 @@ +{ + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.56, + "concurrency": 16, + "successful_requests": 2922, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 95.614, + "successful_latency_ms": { + "p50": 119.6, + "p95": 510.127, + "p99": 908.637 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/results/scaling/load/D_pool_starved_c32_r0.json b/results/scaling/load/D_pool_starved_c32_r0.json new file mode 100644 index 00000000..06b5d31d --- /dev/null +++ b/results/scaling/load/D_pool_starved_c32_r0.json @@ -0,0 +1,17 @@ +{ + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 31.231, + "concurrency": 32, + "successful_requests": 3168, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 101.437, + "successful_latency_ms": { + "p50": 216.453, + "p95": 1047.966, + "p99": 1769.263 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/results/scaling/load/D_pool_starved_c32_r1.json b/results/scaling/load/D_pool_starved_c32_r1.json new file mode 100644 index 00000000..c064909f --- /dev/null +++ b/results/scaling/load/D_pool_starved_c32_r1.json @@ -0,0 +1,17 @@ +{ + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 31.116, + "concurrency": 32, + "successful_requests": 3043, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 97.797, + "successful_latency_ms": { + "p50": 233.299, + "p95": 994.507, + "p99": 1727.046 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/results/scaling/load/D_pool_starved_c64_r0.json b/results/scaling/load/D_pool_starved_c64_r0.json new file mode 100644 index 00000000..e51c063b --- /dev/null +++ b/results/scaling/load/D_pool_starved_c64_r0.json @@ -0,0 +1,17 @@ +{ + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 32.358, + "concurrency": 64, + "successful_requests": 3413, + "failed_requests": 1, + "error_ratio": 0.000293, + "successful_rps": 105.476, + "successful_latency_ms": { + "p50": 495.835, + "p95": 1305.867, + "p99": 2902.993 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/results/scaling/load/D_pool_starved_c64_r1.json b/results/scaling/load/D_pool_starved_c64_r1.json new file mode 100644 index 00000000..c164abba --- /dev/null +++ b/results/scaling/load/D_pool_starved_c64_r1.json @@ -0,0 +1,17 @@ +{ + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 31.881, + "concurrency": 64, + "successful_requests": 3323, + "failed_requests": 1, + "error_ratio": 0.000301, + "successful_rps": 104.233, + "successful_latency_ms": { + "p50": 439.879, + "p95": 1541.484, + "p99": 2527.471 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/results/scaling/load/D_pool_starved_c8_r0.json b/results/scaling/load/D_pool_starved_c8_r0.json new file mode 100644 index 00000000..3ca31748 --- /dev/null +++ b/results/scaling/load/D_pool_starved_c8_r0.json @@ -0,0 +1,17 @@ +{ + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.329, + "concurrency": 8, + "successful_requests": 2727, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 89.913, + "successful_latency_ms": { + "p50": 72.25, + "p95": 196.561, + "p99": 359.412 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/results/scaling/load/D_pool_starved_c8_r1.json b/results/scaling/load/D_pool_starved_c8_r1.json new file mode 100644 index 00000000..a2b136a5 --- /dev/null +++ b/results/scaling/load/D_pool_starved_c8_r1.json @@ -0,0 +1,17 @@ +{ + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.537, + "concurrency": 8, + "successful_requests": 2620, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 85.799, + "successful_latency_ms": { + "p50": 74.935, + "p95": 206.454, + "p99": 348.505 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/results/scaling/load/D_pool_starved_c8_warmup.json b/results/scaling/load/D_pool_starved_c8_warmup.json new file mode 100644 index 00000000..f2d38683 --- /dev/null +++ b/results/scaling/load/D_pool_starved_c8_warmup.json @@ -0,0 +1,17 @@ +{ + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 10.0, + "elapsed_seconds": 10.253, + "concurrency": 8, + "successful_requests": 956, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 93.245, + "successful_latency_ms": { + "p50": 67.913, + "p95": 182.971, + "p99": 246.146 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/results/scaling/raw.json b/results/scaling/raw.json new file mode 100644 index 00000000..27cc6c45 --- /dev/null +++ b/results/scaling/raw.json @@ -0,0 +1,3408 @@ +{ + "started_at": "2026-11-17T13:36:12.673910+00:00", + "base_url": "http://localhost:8080", + "profile": { + "duration_s": 30, + "warmup_s": 10, + "concurrency": [ + 8, + 16, + 32, + 64 + ], + "repeats": 2, + "tool": "tests/load.py (closed-loop, no retries)" + }, + "configs": [ + { + "series": "A", + "name": "A_r1", + "replicas": 1, + "api_cpu": 2.0, + "api_mem": "1024M", + "pg_cpu": 1.0, + "pool": 10, + "overflow": 20, + "pool_timeout": 30, + "nginx_mode": "baseline", + "observed_instance_ids": [ + "api-d080c412" + ], + "points": [ + { + "concurrency": 8, + "repeat": 0, + "metrics": { + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.185, + "concurrency": 8, + "successful_requests": 2616, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 86.667, + "successful_latency_ms": { + "p50": 85.718, + "p95": 134.249, + "p99": 187.593 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." + }, + "pg_before": { + "numbackends": "9", + "active": "1", + "waits": "", + "top_sql": "" + }, + "pg_after": { + "numbackends": "9", + "active": "1", + "waits": "", + "top_sql": "" + }, + "stats_csv": "C:\\Courses\\Course_4\\WidthBrand System\\L2+\\mtusi2026lab3\\results\\scaling\\stats\\A_r1_c8_r0.csv" + }, + { + "concurrency": 8, + "repeat": 1, + "metrics": { + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.28, + "concurrency": 8, + "successful_requests": 2286, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 75.496, + "successful_latency_ms": { + "p50": 100.869, + "p95": 150.892, + "p99": 185.123 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." + }, + "pg_before": { + "numbackends": "9", + "active": "1", + "waits": "", + "top_sql": "" + }, + "pg_after": { + "numbackends": "9", + "active": "1", + "waits": "", + "top_sql": "" + }, + "stats_csv": "C:\\Courses\\Course_4\\WidthBrand System\\L2+\\mtusi2026lab3\\results\\scaling\\stats\\A_r1_c8_r1.csv" + }, + { + "concurrency": 16, + "repeat": 0, + "metrics": { + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.478, + "concurrency": 16, + "successful_requests": 2026, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 66.475, + "successful_latency_ms": { + "p50": 234.353, + "p95": 281.039, + "p99": 344.44 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." + }, + "pg_before": { + "numbackends": "9", + "active": "1", + "waits": "", + "top_sql": "" + }, + "pg_after": { + "numbackends": "11", + "active": "1", + "waits": "", + "top_sql": "" + }, + "stats_csv": "C:\\Courses\\Course_4\\WidthBrand System\\L2+\\mtusi2026lab3\\results\\scaling\\stats\\A_r1_c16_r0.csv" + }, + { + "concurrency": 16, + "repeat": 1, + "metrics": { + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.525, + "concurrency": 16, + "successful_requests": 1849, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 60.574, + "successful_latency_ms": { + "p50": 248.988, + "p95": 336.154, + "p99": 461.645 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." + }, + "pg_before": { + "numbackends": "11", + "active": "1", + "waits": "", + "top_sql": "" + }, + "pg_after": { + "numbackends": "11", + "active": "1", + "waits": "", + "top_sql": "" + }, + "stats_csv": "C:\\Courses\\Course_4\\WidthBrand System\\L2+\\mtusi2026lab3\\results\\scaling\\stats\\A_r1_c16_r1.csv" + }, + { + "concurrency": 32, + "repeat": 0, + "metrics": { + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.994, + "concurrency": 32, + "successful_requests": 2034, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 65.625, + "successful_latency_ms": { + "p50": 468.588, + "p95": 552.38, + "p99": 651.877 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." + }, + "pg_before": { + "numbackends": "11", + "active": "1", + "waits": "", + "top_sql": "" + }, + "pg_after": { + "numbackends": "11", + "active": "1", + "waits": "", + "top_sql": "" + }, + "stats_csv": "C:\\Courses\\Course_4\\WidthBrand System\\L2+\\mtusi2026lab3\\results\\scaling\\stats\\A_r1_c32_r0.csv" + }, + { + "concurrency": 32, + "repeat": 1, + "metrics": { + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 31.009, + "concurrency": 32, + "successful_requests": 2038, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 65.724, + "successful_latency_ms": { + "p50": 465.812, + "p95": 576.753, + "p99": 610.491 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." + }, + "pg_before": { + "numbackends": "11", + "active": "1", + "waits": "", + "top_sql": "" + }, + "pg_after": { + "numbackends": "11", + "active": "1", + "waits": "", + "top_sql": "" + }, + "stats_csv": "C:\\Courses\\Course_4\\WidthBrand System\\L2+\\mtusi2026lab3\\results\\scaling\\stats\\A_r1_c32_r1.csv" + }, + { + "concurrency": 64, + "repeat": 0, + "metrics": { + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 32.232, + "concurrency": 64, + "successful_requests": 1977, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 61.336, + "successful_latency_ms": { + "p50": 932.19, + "p95": 1549.981, + "p99": 1981.849 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." + }, + "pg_before": { + "numbackends": "11", + "active": "1", + "waits": "", + "top_sql": "" + }, + "pg_after": { + "numbackends": "11", + "active": "1", + "waits": "", + "top_sql": "" + }, + "stats_csv": "C:\\Courses\\Course_4\\WidthBrand System\\L2+\\mtusi2026lab3\\results\\scaling\\stats\\A_r1_c64_r0.csv" + }, + { + "concurrency": 64, + "repeat": 1, + "metrics": { + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 32.24, + "concurrency": 64, + "successful_requests": 1960, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 60.795, + "successful_latency_ms": { + "p50": 931.875, + "p95": 1485.929, + "p99": 1885.831 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." + }, + "pg_before": { + "numbackends": "11", + "active": "1", + "waits": "", + "top_sql": "" + }, + "pg_after": { + "numbackends": "11", + "active": "1", + "waits": "", + "top_sql": "" + }, + "stats_csv": "C:\\Courses\\Course_4\\WidthBrand System\\L2+\\mtusi2026lab3\\results\\scaling\\stats\\A_r1_c64_r1.csv" + } + ], + "summary": { + "8": { + "median_rps": 86.667, + "runs": 2 + }, + "16": { + "median_rps": 66.475, + "runs": 2 + }, + "32": { + "median_rps": 65.724, + "runs": 2 + }, + "64": { + "median_rps": 61.336, + "runs": 2 + } + } + }, + { + "series": "A", + "name": "A_r2", + "replicas": 2, + "api_cpu": 1.0, + "api_mem": "512M", + "pg_cpu": 1.0, + "pool": 10, + "overflow": 20, + "pool_timeout": 30, + "nginx_mode": "baseline", + "observed_instance_ids": [ + "api-3f523027", + "api-d0842496" + ], + "points": [ + { + "concurrency": 8, + "repeat": 0, + "metrics": { + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.224, + "concurrency": 8, + "successful_requests": 2982, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 98.663, + "successful_latency_ms": { + "p50": 75.859, + "p95": 120.146, + "p99": 269.584 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." + }, + "pg_before": { + "numbackends": "16", + "active": "1", + "waits": "", + "top_sql": "" + }, + "pg_after": { + "numbackends": "17", + "active": "1", + "waits": "", + "top_sql": "" + }, + "stats_csv": "C:\\Courses\\Course_4\\WidthBrand System\\L2+\\mtusi2026lab3\\results\\scaling\\stats\\A_r2_c8_r0.csv" + }, + { + "concurrency": 8, + "repeat": 1, + "metrics": { + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.277, + "concurrency": 8, + "successful_requests": 2869, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 94.76, + "successful_latency_ms": { + "p50": 78.89, + "p95": 123.066, + "p99": 297.534 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." + }, + "pg_before": { + "numbackends": "17", + "active": "1", + "waits": "", + "top_sql": "" + }, + "pg_after": { + "numbackends": "17", + "active": "1", + "waits": "", + "top_sql": "" + }, + "stats_csv": "C:\\Courses\\Course_4\\WidthBrand System\\L2+\\mtusi2026lab3\\results\\scaling\\stats\\A_r2_c8_r1.csv" + }, + { + "concurrency": 16, + "repeat": 0, + "metrics": { + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.512, + "concurrency": 16, + "successful_requests": 3027, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 99.205, + "successful_latency_ms": { + "p50": 153.453, + "p95": 285.16, + "p99": 493.002 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." + }, + "pg_before": { + "numbackends": "17", + "active": "1", + "waits": "", + "top_sql": "" + }, + "pg_after": { + "numbackends": "19", + "active": "1", + "waits": "", + "top_sql": "" + }, + "stats_csv": "C:\\Courses\\Course_4\\WidthBrand System\\L2+\\mtusi2026lab3\\results\\scaling\\stats\\A_r2_c16_r0.csv" + }, + { + "concurrency": 16, + "repeat": 1, + "metrics": { + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.501, + "concurrency": 16, + "successful_requests": 2846, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 93.31, + "successful_latency_ms": { + "p50": 159.716, + "p95": 309.903, + "p99": 481.809 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." + }, + "pg_before": { + "numbackends": "19", + "active": "1", + "waits": "", + "top_sql": "" + }, + "pg_after": { + "numbackends": "20", + "active": "1", + "waits": "", + "top_sql": "" + }, + "stats_csv": "C:\\Courses\\Course_4\\WidthBrand System\\L2+\\mtusi2026lab3\\results\\scaling\\stats\\A_r2_c16_r1.csv" + }, + { + "concurrency": 32, + "repeat": 0, + "metrics": { + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.99, + "concurrency": 32, + "successful_requests": 2989, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 96.452, + "successful_latency_ms": { + "p50": 308.318, + "p95": 488.57, + "p99": 774.614 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." + }, + "pg_before": { + "numbackends": "20", + "active": "1", + "waits": "", + "top_sql": "" + }, + "pg_after": { + "numbackends": "21", + "active": "1", + "waits": "", + "top_sql": "" + }, + "stats_csv": "C:\\Courses\\Course_4\\WidthBrand System\\L2+\\mtusi2026lab3\\results\\scaling\\stats\\A_r2_c32_r0.csv" + }, + { + "concurrency": 32, + "repeat": 1, + "metrics": { + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 31.056, + "concurrency": 32, + "successful_requests": 2980, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 95.956, + "successful_latency_ms": { + "p50": 319.373, + "p95": 495.198, + "p99": 665.019 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." + }, + "pg_before": { + "numbackends": "21", + "active": "1", + "waits": "", + "top_sql": "" + }, + "pg_after": { + "numbackends": "21", + "active": "1", + "waits": "", + "top_sql": "" + }, + "stats_csv": "C:\\Courses\\Course_4\\WidthBrand System\\L2+\\mtusi2026lab3\\results\\scaling\\stats\\A_r2_c32_r1.csv" + }, + { + "concurrency": 64, + "repeat": 0, + "metrics": { + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 31.945, + "concurrency": 64, + "successful_requests": 2936, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 91.909, + "successful_latency_ms": { + "p50": 637.034, + "p95": 1229.16, + "p99": 1584.022 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." + }, + "pg_before": { + "numbackends": "21", + "active": "1", + "waits": "", + "top_sql": "" + }, + "pg_after": { + "numbackends": "21", + "active": "1", + "waits": "", + "top_sql": "" + }, + "stats_csv": "C:\\Courses\\Course_4\\WidthBrand System\\L2+\\mtusi2026lab3\\results\\scaling\\stats\\A_r2_c64_r0.csv" + }, + { + "concurrency": 64, + "repeat": 1, + "metrics": { + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 32.068, + "concurrency": 64, + "successful_requests": 2975, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 92.77, + "successful_latency_ms": { + "p50": 641.492, + "p95": 1037.372, + "p99": 1272.2 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." + }, + "pg_before": { + "numbackends": "21", + "active": "1", + "waits": "", + "top_sql": "" + }, + "pg_after": { + "numbackends": "21", + "active": "1", + "waits": "", + "top_sql": "" + }, + "stats_csv": "C:\\Courses\\Course_4\\WidthBrand System\\L2+\\mtusi2026lab3\\results\\scaling\\stats\\A_r2_c64_r1.csv" + } + ], + "summary": { + "8": { + "median_rps": 98.663, + "runs": 2 + }, + "16": { + "median_rps": 99.205, + "runs": 2 + }, + "32": { + "median_rps": 96.452, + "runs": 2 + }, + "64": { + "median_rps": 92.77, + "runs": 2 + } + } + }, + { + "series": "A", + "name": "A_r4", + "replicas": 4, + "api_cpu": 0.5, + "api_mem": "256M", + "pg_cpu": 1.0, + "pool": 10, + "overflow": 20, + "pool_timeout": 30, + "nginx_mode": "baseline", + "observed_instance_ids": [ + "api-923bbde0", + "api-d86ffd5f", + "api-e3a19ea2", + "api-e8e88fa9" + ], + "points": [ + { + "concurrency": 8, + "repeat": 0, + "metrics": { + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.444, + "concurrency": 8, + "successful_requests": 2533, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 83.202, + "successful_latency_ms": { + "p50": 77.127, + "p95": 221.638, + "p99": 399.064 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." + }, + "pg_before": { + "numbackends": "23", + "active": "1", + "waits": "", + "top_sql": "" + }, + "pg_after": { + "numbackends": "27", + "active": "1", + "waits": "", + "top_sql": "" + }, + "stats_csv": "C:\\Courses\\Course_4\\WidthBrand System\\L2+\\mtusi2026lab3\\results\\scaling\\stats\\A_r4_c8_r0.csv" + }, + { + "concurrency": 8, + "repeat": 1, + "metrics": { + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.258, + "concurrency": 8, + "successful_requests": 2434, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 80.44, + "successful_latency_ms": { + "p50": 90.472, + "p95": 203.446, + "p99": 310.23 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." + }, + "pg_before": { + "numbackends": "27", + "active": "1", + "waits": "", + "top_sql": "" + }, + "pg_after": { + "numbackends": "28", + "active": "1", + "waits": "", + "top_sql": "" + }, + "stats_csv": "C:\\Courses\\Course_4\\WidthBrand System\\L2+\\mtusi2026lab3\\results\\scaling\\stats\\A_r4_c8_r1.csv" + }, + { + "concurrency": 16, + "repeat": 0, + "metrics": { + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.681, + "concurrency": 16, + "successful_requests": 2376, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 77.441, + "successful_latency_ms": { + "p50": 105.541, + "p95": 583.001, + "p99": 660.285 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." + }, + "pg_before": { + "numbackends": "28", + "active": "1", + "waits": "", + "top_sql": "" + }, + "pg_after": { + "numbackends": "32", + "active": "1", + "waits": "", + "top_sql": "" + }, + "stats_csv": "C:\\Courses\\Course_4\\WidthBrand System\\L2+\\mtusi2026lab3\\results\\scaling\\stats\\A_r4_c16_r0.csv" + }, + { + "concurrency": 16, + "repeat": 1, + "metrics": { + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.722, + "concurrency": 16, + "successful_requests": 2434, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 79.226, + "successful_latency_ms": { + "p50": 141.848, + "p95": 474.128, + "p99": 722.98 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." + }, + "pg_before": { + "numbackends": "32", + "active": "1", + "waits": "", + "top_sql": "" + }, + "pg_after": { + "numbackends": "35", + "active": "1", + "waits": "", + "top_sql": "" + }, + "stats_csv": "C:\\Courses\\Course_4\\WidthBrand System\\L2+\\mtusi2026lab3\\results\\scaling\\stats\\A_r4_c16_r1.csv" + }, + { + "concurrency": 32, + "repeat": 0, + "metrics": { + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 31.872, + "concurrency": 32, + "successful_requests": 2650, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 83.144, + "successful_latency_ms": { + "p50": 257.054, + "p95": 1070.315, + "p99": 1698.114 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." + }, + "pg_before": { + "numbackends": "35", + "active": "1", + "waits": "", + "top_sql": "" + }, + "pg_after": { + "numbackends": "40", + "active": "1", + "waits": "", + "top_sql": "" + }, + "stats_csv": "C:\\Courses\\Course_4\\WidthBrand System\\L2+\\mtusi2026lab3\\results\\scaling\\stats\\A_r4_c32_r0.csv" + }, + { + "concurrency": 32, + "repeat": 1, + "metrics": { + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 32.15, + "concurrency": 32, + "successful_requests": 2404, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 74.775, + "successful_latency_ms": { + "p50": 334.773, + "p95": 1079.491, + "p99": 1308.01 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." + }, + "pg_before": { + "numbackends": "40", + "active": "1", + "waits": "", + "top_sql": "" + }, + "pg_after": { + "numbackends": "41", + "active": "1", + "waits": "", + "top_sql": "" + }, + "stats_csv": "C:\\Courses\\Course_4\\WidthBrand System\\L2+\\mtusi2026lab3\\results\\scaling\\stats\\A_r4_c32_r1.csv" + }, + { + "concurrency": 64, + "repeat": 0, + "metrics": { + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 33.168, + "concurrency": 64, + "successful_requests": 2487, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 74.981, + "successful_latency_ms": { + "p50": 691.618, + "p95": 1469.65, + "p99": 2366.364 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." + }, + "pg_before": { + "numbackends": "41", + "active": "1", + "waits": "", + "top_sql": "" + }, + "pg_after": { + "numbackends": "41", + "active": "1", + "waits": "", + "top_sql": "" + }, + "stats_csv": "C:\\Courses\\Course_4\\WidthBrand System\\L2+\\mtusi2026lab3\\results\\scaling\\stats\\A_r4_c64_r0.csv" + }, + { + "concurrency": 64, + "repeat": 1, + "metrics": { + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 33.445, + "concurrency": 64, + "successful_requests": 2507, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 74.959, + "successful_latency_ms": { + "p50": 769.191, + "p95": 1376.986, + "p99": 1608.463 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." + }, + "pg_before": { + "numbackends": "41", + "active": "1", + "waits": "", + "top_sql": "" + }, + "pg_after": { + "numbackends": "41", + "active": "1", + "waits": "", + "top_sql": "" + }, + "stats_csv": "C:\\Courses\\Course_4\\WidthBrand System\\L2+\\mtusi2026lab3\\results\\scaling\\stats\\A_r4_c64_r1.csv" + } + ], + "summary": { + "8": { + "median_rps": 83.202, + "runs": 2 + }, + "16": { + "median_rps": 79.226, + "runs": 2 + }, + "32": { + "median_rps": 83.144, + "runs": 2 + }, + "64": { + "median_rps": 74.981, + "runs": 2 + } + } + }, + { + "series": "B", + "name": "B_cpu1", + "replicas": 2, + "api_cpu": 0.5, + "api_mem": "512M", + "pg_cpu": 1.0, + "pool": 10, + "overflow": 20, + "pool_timeout": 30, + "nginx_mode": "keepalive", + "observed_instance_ids": [ + "api-11b1c0e9", + "api-c03cd23b" + ], + "points": [ + { + "concurrency": 8, + "repeat": 0, + "metrics": { + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.342, + "concurrency": 8, + "successful_requests": 1599, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 52.7, + "successful_latency_ms": { + "p50": 120.975, + "p95": 390.329, + "p99": 512.922 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." + }, + "pg_before": { + "numbackends": "17", + "active": "1", + "waits": "", + "top_sql": "" + }, + "pg_after": { + "numbackends": "17", + "active": "1", + "waits": "", + "top_sql": "" + }, + "stats_csv": "C:\\Courses\\Course_4\\WidthBrand System\\L2+\\mtusi2026lab3\\results\\scaling\\stats\\B_cpu1_c8_r0.csv" + }, + { + "concurrency": 8, + "repeat": 1, + "metrics": { + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.373, + "concurrency": 8, + "successful_requests": 1705, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 56.136, + "successful_latency_ms": { + "p50": 118.07, + "p95": 281.239, + "p99": 479.55 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." + }, + "pg_before": { + "numbackends": "17", + "active": "1", + "waits": "", + "top_sql": "" + }, + "pg_after": { + "numbackends": "17", + "active": "1", + "waits": "", + "top_sql": "" + }, + "stats_csv": "C:\\Courses\\Course_4\\WidthBrand System\\L2+\\mtusi2026lab3\\results\\scaling\\stats\\B_cpu1_c8_r1.csv" + }, + { + "concurrency": 16, + "repeat": 0, + "metrics": { + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.543, + "concurrency": 16, + "successful_requests": 2045, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 66.955, + "successful_latency_ms": { + "p50": 231.418, + "p95": 464.595, + "p99": 896.102 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." + }, + "pg_before": { + "numbackends": "17", + "active": "1", + "waits": "", + "top_sql": "" + }, + "pg_after": { + "numbackends": "21", + "active": "1", + "waits": "", + "top_sql": "" + }, + "stats_csv": "C:\\Courses\\Course_4\\WidthBrand System\\L2+\\mtusi2026lab3\\results\\scaling\\stats\\B_cpu1_c16_r0.csv" + }, + { + "concurrency": 16, + "repeat": 1, + "metrics": { + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.52, + "concurrency": 16, + "successful_requests": 2001, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 65.564, + "successful_latency_ms": { + "p50": 218.925, + "p95": 489.238, + "p99": 797.207 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." + }, + "pg_before": { + "numbackends": "21", + "active": "1", + "waits": "", + "top_sql": "" + }, + "pg_after": { + "numbackends": "21", + "active": "1", + "waits": "", + "top_sql": "" + }, + "stats_csv": "C:\\Courses\\Course_4\\WidthBrand System\\L2+\\mtusi2026lab3\\results\\scaling\\stats\\B_cpu1_c16_r1.csv" + }, + { + "concurrency": 32, + "repeat": 0, + "metrics": { + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 31.045, + "concurrency": 32, + "successful_requests": 1918, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 61.782, + "successful_latency_ms": { + "p50": 496.99, + "p95": 1004.052, + "p99": 1596.716 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." + }, + "pg_before": { + "numbackends": "21", + "active": "1", + "waits": "", + "top_sql": "" + }, + "pg_after": { + "numbackends": "21", + "active": "1", + "waits": "", + "top_sql": "" + }, + "stats_csv": "C:\\Courses\\Course_4\\WidthBrand System\\L2+\\mtusi2026lab3\\results\\scaling\\stats\\B_cpu1_c32_r0.csv" + }, + { + "concurrency": 32, + "repeat": 1, + "metrics": { + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.933, + "concurrency": 32, + "successful_requests": 2167, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 70.055, + "successful_latency_ms": { + "p50": 490.549, + "p95": 891.009, + "p99": 1314.072 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." + }, + "pg_before": { + "numbackends": "21", + "active": "1", + "waits": "", + "top_sql": "" + }, + "pg_after": { + "numbackends": "21", + "active": "1", + "waits": "", + "top_sql": "" + }, + "stats_csv": "C:\\Courses\\Course_4\\WidthBrand System\\L2+\\mtusi2026lab3\\results\\scaling\\stats\\B_cpu1_c32_r1.csv" + }, + { + "concurrency": 64, + "repeat": 0, + "metrics": { + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 31.903, + "concurrency": 64, + "successful_requests": 2064, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 64.697, + "successful_latency_ms": { + "p50": 873.782, + "p95": 1666.5, + "p99": 2075.07 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." + }, + "pg_before": { + "numbackends": "21", + "active": "1", + "waits": "", + "top_sql": "" + }, + "pg_after": { + "numbackends": "21", + "active": "1", + "waits": "", + "top_sql": "" + }, + "stats_csv": "C:\\Courses\\Course_4\\WidthBrand System\\L2+\\mtusi2026lab3\\results\\scaling\\stats\\B_cpu1_c64_r0.csv" + }, + { + "concurrency": 64, + "repeat": 1, + "metrics": { + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 31.751, + "concurrency": 64, + "successful_requests": 2170, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 68.343, + "successful_latency_ms": { + "p50": 868.913, + "p95": 1334.096, + "p99": 1783.243 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." + }, + "pg_before": { + "numbackends": "21", + "active": "1", + "waits": "", + "top_sql": "" + }, + "pg_after": { + "numbackends": "21", + "active": "1", + "waits": "", + "top_sql": "" + }, + "stats_csv": "C:\\Courses\\Course_4\\WidthBrand System\\L2+\\mtusi2026lab3\\results\\scaling\\stats\\B_cpu1_c64_r1.csv" + } + ], + "summary": { + "8": { + "median_rps": 56.136, + "runs": 2 + }, + "16": { + "median_rps": 66.955, + "runs": 2 + }, + "32": { + "median_rps": 70.055, + "runs": 2 + }, + "64": { + "median_rps": 68.343, + "runs": 2 + } + } + }, + { + "series": "B", + "name": "B_cpu2", + "replicas": 2, + "api_cpu": 1.0, + "api_mem": "512M", + "pg_cpu": 1.0, + "pool": 10, + "overflow": 20, + "pool_timeout": 30, + "nginx_mode": "keepalive", + "observed_instance_ids": [ + "api-2f2b2c43", + "api-c899f23f" + ], + "points": [ + { + "concurrency": 8, + "repeat": 0, + "metrics": { + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.169, + "concurrency": 8, + "successful_requests": 4375, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 145.015, + "successful_latency_ms": { + "p50": 50.258, + "p95": 84.407, + "p99": 176.587 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." + }, + "pg_before": { + "numbackends": "15", + "active": "1", + "waits": "", + "top_sql": "" + }, + "pg_after": { + "numbackends": "17", + "active": "1", + "waits": "", + "top_sql": "" + }, + "stats_csv": "C:\\Courses\\Course_4\\WidthBrand System\\L2+\\mtusi2026lab3\\results\\scaling\\stats\\B_cpu2_c8_r0.csv" + }, + { + "concurrency": 8, + "repeat": 1, + "metrics": { + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.193, + "concurrency": 8, + "successful_requests": 3929, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 130.129, + "successful_latency_ms": { + "p50": 55.65, + "p95": 104.916, + "p99": 176.69 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." + }, + "pg_before": { + "numbackends": "17", + "active": "1", + "waits": "", + "top_sql": "" + }, + "pg_after": { + "numbackends": "17", + "active": "1", + "waits": "", + "top_sql": "" + }, + "stats_csv": "C:\\Courses\\Course_4\\WidthBrand System\\L2+\\mtusi2026lab3\\results\\scaling\\stats\\B_cpu2_c8_r1.csv" + }, + { + "concurrency": 16, + "repeat": 0, + "metrics": { + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.378, + "concurrency": 16, + "successful_requests": 4292, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 141.288, + "successful_latency_ms": { + "p50": 104.807, + "p95": 186.077, + "p99": 314.013 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." + }, + "pg_before": { + "numbackends": "17", + "active": "1", + "waits": "", + "top_sql": "" + }, + "pg_after": { + "numbackends": "21", + "active": "1", + "waits": "", + "top_sql": "" + }, + "stats_csv": "C:\\Courses\\Course_4\\WidthBrand System\\L2+\\mtusi2026lab3\\results\\scaling\\stats\\B_cpu2_c16_r0.csv" + }, + { + "concurrency": 16, + "repeat": 1, + "metrics": { + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.374, + "concurrency": 16, + "successful_requests": 4247, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 139.822, + "successful_latency_ms": { + "p50": 108.724, + "p95": 188.603, + "p99": 315.751 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." + }, + "pg_before": { + "numbackends": "21", + "active": "1", + "waits": "", + "top_sql": "" + }, + "pg_after": { + "numbackends": "21", + "active": "1", + "waits": "", + "top_sql": "" + }, + "stats_csv": "C:\\Courses\\Course_4\\WidthBrand System\\L2+\\mtusi2026lab3\\results\\scaling\\stats\\B_cpu2_c16_r1.csv" + }, + { + "concurrency": 32, + "repeat": 0, + "metrics": { + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.746, + "concurrency": 32, + "successful_requests": 4413, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 143.532, + "successful_latency_ms": { + "p50": 207.516, + "p95": 328.611, + "p99": 585.259 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." + }, + "pg_before": { + "numbackends": "21", + "active": "1", + "waits": "", + "top_sql": "" + }, + "pg_after": { + "numbackends": "21", + "active": "1", + "waits": "", + "top_sql": "" + }, + "stats_csv": "C:\\Courses\\Course_4\\WidthBrand System\\L2+\\mtusi2026lab3\\results\\scaling\\stats\\B_cpu2_c32_r0.csv" + }, + { + "concurrency": 32, + "repeat": 1, + "metrics": { + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.702, + "concurrency": 32, + "successful_requests": 4354, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 141.813, + "successful_latency_ms": { + "p50": 209.27, + "p95": 335.597, + "p99": 544.982 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." + }, + "pg_before": { + "numbackends": "21", + "active": "1", + "waits": "", + "top_sql": "" + }, + "pg_after": { + "numbackends": "21", + "active": "1", + "waits": "", + "top_sql": "" + }, + "stats_csv": "C:\\Courses\\Course_4\\WidthBrand System\\L2+\\mtusi2026lab3\\results\\scaling\\stats\\B_cpu2_c32_r1.csv" + }, + { + "concurrency": 64, + "repeat": 0, + "metrics": { + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 31.457, + "concurrency": 64, + "successful_requests": 4383, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 139.332, + "successful_latency_ms": { + "p50": 405.878, + "p95": 693.679, + "p99": 932.377 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." + }, + "pg_before": { + "numbackends": "21", + "active": "1", + "waits": "", + "top_sql": "" + }, + "pg_after": { + "numbackends": "21", + "active": "1", + "waits": "", + "top_sql": "" + }, + "stats_csv": "C:\\Courses\\Course_4\\WidthBrand System\\L2+\\mtusi2026lab3\\results\\scaling\\stats\\B_cpu2_c64_r0.csv" + }, + { + "concurrency": 64, + "repeat": 1, + "metrics": { + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 31.551, + "concurrency": 64, + "successful_requests": 4259, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 134.987, + "successful_latency_ms": { + "p50": 427.633, + "p95": 644.277, + "p99": 869.437 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." + }, + "pg_before": { + "numbackends": "21", + "active": "1", + "waits": "", + "top_sql": "" + }, + "pg_after": { + "numbackends": "21", + "active": "1", + "waits": "", + "top_sql": "" + }, + "stats_csv": "C:\\Courses\\Course_4\\WidthBrand System\\L2+\\mtusi2026lab3\\results\\scaling\\stats\\B_cpu2_c64_r1.csv" + } + ], + "summary": { + "8": { + "median_rps": 145.015, + "runs": 2 + }, + "16": { + "median_rps": 141.288, + "runs": 2 + }, + "32": { + "median_rps": 143.532, + "runs": 2 + }, + "64": { + "median_rps": 139.332, + "runs": 2 + } + } + }, + { + "series": "B", + "name": "B_cpu4", + "replicas": 2, + "api_cpu": 2.0, + "api_mem": "512M", + "pg_cpu": 1.0, + "pool": 10, + "overflow": 20, + "pool_timeout": 30, + "nginx_mode": "keepalive", + "observed_instance_ids": [ + "api-013a5b67", + "api-d415a00b" + ], + "points": [ + { + "concurrency": 8, + "repeat": 0, + "metrics": { + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.19, + "concurrency": 8, + "successful_requests": 4416, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 146.276, + "successful_latency_ms": { + "p50": 51.785, + "p95": 78.57, + "p99": 112.757 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." + }, + "pg_before": { + "numbackends": "11", + "active": "1", + "waits": "", + "top_sql": "" + }, + "pg_after": { + "numbackends": "14", + "active": "1", + "waits": "", + "top_sql": "" + }, + "stats_csv": "C:\\Courses\\Course_4\\WidthBrand System\\L2+\\mtusi2026lab3\\results\\scaling\\stats\\B_cpu4_c8_r0.csv" + }, + { + "concurrency": 8, + "repeat": 1, + "metrics": { + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.2, + "concurrency": 8, + "successful_requests": 4433, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 146.788, + "successful_latency_ms": { + "p50": 52.148, + "p95": 77.722, + "p99": 94.042 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." + }, + "pg_before": { + "numbackends": "14", + "active": "1", + "waits": "", + "top_sql": "" + }, + "pg_after": { + "numbackends": "14", + "active": "1", + "waits": "", + "top_sql": "" + }, + "stats_csv": "C:\\Courses\\Course_4\\WidthBrand System\\L2+\\mtusi2026lab3\\results\\scaling\\stats\\B_cpu4_c8_r1.csv" + }, + { + "concurrency": 16, + "repeat": 0, + "metrics": { + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.383, + "concurrency": 16, + "successful_requests": 4496, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 147.976, + "successful_latency_ms": { + "p50": 108.467, + "p95": 176.095, + "p99": 202.449 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." + }, + "pg_before": { + "numbackends": "14", + "active": "1", + "waits": "", + "top_sql": "" + }, + "pg_after": { + "numbackends": "21", + "active": "1", + "waits": "", + "top_sql": "" + }, + "stats_csv": "C:\\Courses\\Course_4\\WidthBrand System\\L2+\\mtusi2026lab3\\results\\scaling\\stats\\B_cpu4_c16_r0.csv" + }, + { + "concurrency": 16, + "repeat": 1, + "metrics": { + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.413, + "concurrency": 16, + "successful_requests": 4427, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 145.565, + "successful_latency_ms": { + "p50": 111.739, + "p95": 177.898, + "p99": 195.162 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." + }, + "pg_before": { + "numbackends": "21", + "active": "1", + "waits": "", + "top_sql": "" + }, + "pg_after": { + "numbackends": "21", + "active": "1", + "waits": "", + "top_sql": "" + }, + "stats_csv": "C:\\Courses\\Course_4\\WidthBrand System\\L2+\\mtusi2026lab3\\results\\scaling\\stats\\B_cpu4_c16_r1.csv" + }, + { + "concurrency": 32, + "repeat": 0, + "metrics": { + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.804, + "concurrency": 32, + "successful_requests": 4546, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 147.581, + "successful_latency_ms": { + "p50": 215.344, + "p95": 350.556, + "p99": 396.933 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." + }, + "pg_before": { + "numbackends": "21", + "active": "1", + "waits": "", + "top_sql": "" + }, + "pg_after": { + "numbackends": "21", + "active": "1", + "waits": "", + "top_sql": "" + }, + "stats_csv": "C:\\Courses\\Course_4\\WidthBrand System\\L2+\\mtusi2026lab3\\results\\scaling\\stats\\B_cpu4_c32_r0.csv" + }, + { + "concurrency": 32, + "repeat": 1, + "metrics": { + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.783, + "concurrency": 32, + "successful_requests": 4551, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 147.843, + "successful_latency_ms": { + "p50": 216.853, + "p95": 320.175, + "p99": 349.21 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." + }, + "pg_before": { + "numbackends": "21", + "active": "1", + "waits": "", + "top_sql": "" + }, + "pg_after": { + "numbackends": "21", + "active": "1", + "waits": "", + "top_sql": "" + }, + "stats_csv": "C:\\Courses\\Course_4\\WidthBrand System\\L2+\\mtusi2026lab3\\results\\scaling\\stats\\B_cpu4_c32_r1.csv" + }, + { + "concurrency": 64, + "repeat": 0, + "metrics": { + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 31.592, + "concurrency": 64, + "successful_requests": 4427, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 140.131, + "successful_latency_ms": { + "p50": 427.55, + "p95": 542.637, + "p99": 632.95 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." + }, + "pg_before": { + "numbackends": "21", + "active": "1", + "waits": "", + "top_sql": "" + }, + "pg_after": { + "numbackends": "21", + "active": "1", + "waits": "", + "top_sql": "" + }, + "stats_csv": "C:\\Courses\\Course_4\\WidthBrand System\\L2+\\mtusi2026lab3\\results\\scaling\\stats\\B_cpu4_c64_r0.csv" + }, + { + "concurrency": 64, + "repeat": 1, + "metrics": { + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 31.652, + "concurrency": 64, + "successful_requests": 4250, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 134.272, + "successful_latency_ms": { + "p50": 440.725, + "p95": 631.239, + "p99": 757.651 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." + }, + "pg_before": { + "numbackends": "21", + "active": "1", + "waits": "", + "top_sql": "" + }, + "pg_after": { + "numbackends": "21", + "active": "1", + "waits": "", + "top_sql": "" + }, + "stats_csv": "C:\\Courses\\Course_4\\WidthBrand System\\L2+\\mtusi2026lab3\\results\\scaling\\stats\\B_cpu4_c64_r1.csv" + } + ], + "summary": { + "8": { + "median_rps": 146.788, + "runs": 2 + }, + "16": { + "median_rps": 147.976, + "runs": 2 + }, + "32": { + "median_rps": 147.843, + "runs": 2 + }, + "64": { + "median_rps": 140.131, + "runs": 2 + } + } + }, + { + "series": "B", + "name": "B_cpu4_db2", + "replicas": 2, + "api_cpu": 2.0, + "api_mem": "512M", + "pg_cpu": 2.0, + "pool": 10, + "overflow": 20, + "pool_timeout": 30, + "nginx_mode": "keepalive", + "observed_instance_ids": [ + "api-35066fa1", + "api-94a4809e" + ], + "points": [ + { + "concurrency": 8, + "repeat": 0, + "metrics": { + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.244, + "concurrency": 8, + "successful_requests": 4182, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 138.275, + "successful_latency_ms": { + "p50": 55.931, + "p95": 84.018, + "p99": 98.142 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." + }, + "pg_before": { + "numbackends": "14", + "active": "1", + "waits": "", + "top_sql": "" + }, + "pg_after": { + "numbackends": "14", + "active": "1", + "waits": "", + "top_sql": "" + }, + "stats_csv": "C:\\Courses\\Course_4\\WidthBrand System\\L2+\\mtusi2026lab3\\results\\scaling\\stats\\B_cpu4_db2_c8_r0.csv" + }, + { + "concurrency": 8, + "repeat": 1, + "metrics": { + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.192, + "concurrency": 8, + "successful_requests": 4380, + "failed_requests": 1, + "error_ratio": 0.000228, + "successful_rps": 145.07, + "successful_latency_ms": { + "p50": 51.436, + "p95": 83.217, + "p99": 123.483 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." + }, + "pg_before": { + "numbackends": "14", + "active": "1", + "waits": "", + "top_sql": "" + }, + "pg_after": { + "numbackends": "14", + "active": "1", + "waits": "", + "top_sql": "" + }, + "stats_csv": "C:\\Courses\\Course_4\\WidthBrand System\\L2+\\mtusi2026lab3\\results\\scaling\\stats\\B_cpu4_db2_c8_r1.csv" + }, + { + "concurrency": 16, + "repeat": 0, + "metrics": { + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.402, + "concurrency": 16, + "successful_requests": 4586, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 150.848, + "successful_latency_ms": { + "p50": 104.502, + "p95": 172.493, + "p99": 194.08 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." + }, + "pg_before": { + "numbackends": "14", + "active": "1", + "waits": "", + "top_sql": "" + }, + "pg_after": { + "numbackends": "21", + "active": "1", + "waits": "", + "top_sql": "" + }, + "stats_csv": "C:\\Courses\\Course_4\\WidthBrand System\\L2+\\mtusi2026lab3\\results\\scaling\\stats\\B_cpu4_db2_c16_r0.csv" + }, + { + "concurrency": 16, + "repeat": 1, + "metrics": { + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.404, + "concurrency": 16, + "successful_requests": 4635, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 152.448, + "successful_latency_ms": { + "p50": 103.106, + "p95": 170.171, + "p99": 185.575 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." + }, + "pg_before": { + "numbackends": "21", + "active": "1", + "waits": "", + "top_sql": "" + }, + "pg_after": { + "numbackends": "21", + "active": "1", + "waits": "", + "top_sql": "" + }, + "stats_csv": "C:\\Courses\\Course_4\\WidthBrand System\\L2+\\mtusi2026lab3\\results\\scaling\\stats\\B_cpu4_db2_c16_r1.csv" + }, + { + "concurrency": 32, + "repeat": 0, + "metrics": { + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.801, + "concurrency": 32, + "successful_requests": 4456, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 144.67, + "successful_latency_ms": { + "p50": 219.412, + "p95": 334.013, + "p99": 371.502 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." + }, + "pg_before": { + "numbackends": "21", + "active": "1", + "waits": "", + "top_sql": "" + }, + "pg_after": { + "numbackends": "21", + "active": "1", + "waits": "", + "top_sql": "" + }, + "stats_csv": "C:\\Courses\\Course_4\\WidthBrand System\\L2+\\mtusi2026lab3\\results\\scaling\\stats\\B_cpu4_db2_c32_r0.csv" + }, + { + "concurrency": 32, + "repeat": 1, + "metrics": { + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.848, + "concurrency": 32, + "successful_requests": 4569, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 148.111, + "successful_latency_ms": { + "p50": 207.272, + "p95": 314.043, + "p99": 351.771 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." + }, + "pg_before": { + "numbackends": "21", + "active": "1", + "waits": "", + "top_sql": "" + }, + "pg_after": { + "numbackends": "21", + "active": "1", + "waits": "", + "top_sql": "" + }, + "stats_csv": "C:\\Courses\\Course_4\\WidthBrand System\\L2+\\mtusi2026lab3\\results\\scaling\\stats\\B_cpu4_db2_c32_r1.csv" + }, + { + "concurrency": 64, + "repeat": 0, + "metrics": { + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 31.627, + "concurrency": 64, + "successful_requests": 4694, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 148.418, + "successful_latency_ms": { + "p50": 404.299, + "p95": 556.187, + "p99": 641.569 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." + }, + "pg_before": { + "numbackends": "21", + "active": "1", + "waits": "", + "top_sql": "" + }, + "pg_after": { + "numbackends": "21", + "active": "1", + "waits": "", + "top_sql": "" + }, + "stats_csv": "C:\\Courses\\Course_4\\WidthBrand System\\L2+\\mtusi2026lab3\\results\\scaling\\stats\\B_cpu4_db2_c64_r0.csv" + }, + { + "concurrency": 64, + "repeat": 1, + "metrics": { + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 31.596, + "concurrency": 64, + "successful_requests": 4670, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 147.803, + "successful_latency_ms": { + "p50": 403.418, + "p95": 558.308, + "p99": 665.799 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." + }, + "pg_before": { + "numbackends": "21", + "active": "1", + "waits": "", + "top_sql": "" + }, + "pg_after": { + "numbackends": "21", + "active": "1", + "waits": "", + "top_sql": "" + }, + "stats_csv": "C:\\Courses\\Course_4\\WidthBrand System\\L2+\\mtusi2026lab3\\results\\scaling\\stats\\B_cpu4_db2_c64_r1.csv" + } + ], + "summary": { + "8": { + "median_rps": 145.07, + "runs": 2 + }, + "16": { + "median_rps": 152.448, + "runs": 2 + }, + "32": { + "median_rps": 148.111, + "runs": 2 + }, + "64": { + "median_rps": 148.418, + "runs": 2 + } + } + }, + { + "series": "C", + "name": "C_before", + "replicas": 2, + "api_cpu": 1.0, + "api_mem": "512M", + "pg_cpu": 1.0, + "pool": 10, + "overflow": 20, + "pool_timeout": 30, + "nginx_mode": "baseline", + "observed_instance_ids": [ + "api-9d7ded8a", + "api-f9fec23a" + ], + "points": [ + { + "concurrency": 8, + "repeat": 0, + "metrics": { + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.183, + "concurrency": 8, + "successful_requests": 4301, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 142.496, + "successful_latency_ms": { + "p50": 51.983, + "p95": 80.987, + "p99": 148.524 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." + }, + "pg_before": { + "numbackends": "14", + "active": "1", + "waits": "", + "top_sql": "" + }, + "pg_after": { + "numbackends": "14", + "active": "1", + "waits": "", + "top_sql": "" + }, + "stats_csv": "C:\\Courses\\Course_4\\WidthBrand System\\L2+\\mtusi2026lab3\\results\\scaling\\stats\\C_before_c8_r0.csv" + }, + { + "concurrency": 8, + "repeat": 1, + "metrics": { + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.194, + "concurrency": 8, + "successful_requests": 3919, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 129.792, + "successful_latency_ms": { + "p50": 55.238, + "p95": 104.713, + "p99": 181.21 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." + }, + "pg_before": { + "numbackends": "14", + "active": "1", + "waits": "", + "top_sql": "" + }, + "pg_after": { + "numbackends": "14", + "active": "1", + "waits": "", + "top_sql": "" + }, + "stats_csv": "C:\\Courses\\Course_4\\WidthBrand System\\L2+\\mtusi2026lab3\\results\\scaling\\stats\\C_before_c8_r1.csv" + }, + { + "concurrency": 16, + "repeat": 0, + "metrics": { + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.394, + "concurrency": 16, + "successful_requests": 4062, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 133.644, + "successful_latency_ms": { + "p50": 119.527, + "p95": 215.968, + "p99": 343.529 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." + }, + "pg_before": { + "numbackends": "14", + "active": "1", + "waits": "", + "top_sql": "" + }, + "pg_after": { + "numbackends": "21", + "active": "1", + "waits": "", + "top_sql": "" + }, + "stats_csv": "C:\\Courses\\Course_4\\WidthBrand System\\L2+\\mtusi2026lab3\\results\\scaling\\stats\\C_before_c16_r0.csv" + }, + { + "concurrency": 16, + "repeat": 1, + "metrics": { + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.453, + "concurrency": 16, + "successful_requests": 3822, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 125.505, + "successful_latency_ms": { + "p50": 117.086, + "p95": 221.724, + "p99": 300.679 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." + }, + "pg_before": { + "numbackends": "21", + "active": "1", + "waits": "", + "top_sql": "" + }, + "pg_after": { + "numbackends": "21", + "active": "1", + "waits": "", + "top_sql": "" + }, + "stats_csv": "C:\\Courses\\Course_4\\WidthBrand System\\L2+\\mtusi2026lab3\\results\\scaling\\stats\\C_before_c16_r1.csv" + }, + { + "concurrency": 32, + "repeat": 0, + "metrics": { + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.784, + "concurrency": 32, + "successful_requests": 4200, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 136.436, + "successful_latency_ms": { + "p50": 225.049, + "p95": 338.21, + "p99": 565.592 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." + }, + "pg_before": { + "numbackends": "21", + "active": "1", + "waits": "", + "top_sql": "" + }, + "pg_after": { + "numbackends": "21", + "active": "1", + "waits": "", + "top_sql": "" + }, + "stats_csv": "C:\\Courses\\Course_4\\WidthBrand System\\L2+\\mtusi2026lab3\\results\\scaling\\stats\\C_before_c32_r0.csv" + }, + { + "concurrency": 32, + "repeat": 1, + "metrics": { + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.739, + "concurrency": 32, + "successful_requests": 4209, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 136.927, + "successful_latency_ms": { + "p50": 217.814, + "p95": 338.734, + "p99": 588.003 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." + }, + "pg_before": { + "numbackends": "21", + "active": "1", + "waits": "", + "top_sql": "" + }, + "pg_after": { + "numbackends": "21", + "active": "1", + "waits": "", + "top_sql": "" + }, + "stats_csv": "C:\\Courses\\Course_4\\WidthBrand System\\L2+\\mtusi2026lab3\\results\\scaling\\stats\\C_before_c32_r1.csv" + }, + { + "concurrency": 64, + "repeat": 0, + "metrics": { + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 31.497, + "concurrency": 64, + "successful_requests": 4305, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 136.679, + "successful_latency_ms": { + "p50": 417.647, + "p95": 717.13, + "p99": 932.864 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." + }, + "pg_before": { + "numbackends": "21", + "active": "1", + "waits": "", + "top_sql": "" + }, + "pg_after": { + "numbackends": "21", + "active": "1", + "waits": "", + "top_sql": "" + }, + "stats_csv": "C:\\Courses\\Course_4\\WidthBrand System\\L2+\\mtusi2026lab3\\results\\scaling\\stats\\C_before_c64_r0.csv" + }, + { + "concurrency": 64, + "repeat": 1, + "metrics": { + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 32.048, + "concurrency": 64, + "successful_requests": 4070, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 126.997, + "successful_latency_ms": { + "p50": 484.389, + "p95": 795.946, + "p99": 943.134 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." + }, + "pg_before": { + "numbackends": "21", + "active": "1", + "waits": "", + "top_sql": "" + }, + "pg_after": { + "numbackends": "21", + "active": "1", + "waits": "", + "top_sql": "" + }, + "stats_csv": "C:\\Courses\\Course_4\\WidthBrand System\\L2+\\mtusi2026lab3\\results\\scaling\\stats\\C_before_c64_r1.csv" + } + ], + "summary": { + "8": { + "median_rps": 142.496, + "runs": 2 + }, + "16": { + "median_rps": 133.644, + "runs": 2 + }, + "32": { + "median_rps": 136.927, + "runs": 2 + }, + "64": { + "median_rps": 136.679, + "runs": 2 + } + } + }, + { + "series": "C", + "name": "C_after", + "replicas": 2, + "api_cpu": 1.0, + "api_mem": "512M", + "pg_cpu": 1.0, + "pool": 10, + "overflow": 20, + "pool_timeout": 30, + "nginx_mode": "keepalive", + "observed_instance_ids": [ + "api-6ac1161d", + "api-780fde4b" + ], + "points": [ + { + "concurrency": 8, + "repeat": 0, + "metrics": { + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.234, + "concurrency": 8, + "successful_requests": 3895, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 128.827, + "successful_latency_ms": { + "p50": 54.77, + "p95": 93.745, + "p99": 198.174 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." + }, + "pg_before": { + "numbackends": "16", + "active": "1", + "waits": "", + "top_sql": "" + }, + "pg_after": { + "numbackends": "17", + "active": "1", + "waits": "", + "top_sql": "" + }, + "stats_csv": "C:\\Courses\\Course_4\\WidthBrand System\\L2+\\mtusi2026lab3\\results\\scaling\\stats\\C_after_c8_r0.csv" + }, + { + "concurrency": 8, + "repeat": 1, + "metrics": { + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.216, + "concurrency": 8, + "successful_requests": 3282, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 108.616, + "successful_latency_ms": { + "p50": 61.722, + "p95": 146.556, + "p99": 252.043 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." + }, + "pg_before": { + "numbackends": "17", + "active": "1", + "waits": "", + "top_sql": "" + }, + "pg_after": { + "numbackends": "17", + "active": "1", + "waits": "", + "top_sql": "" + }, + "stats_csv": "C:\\Courses\\Course_4\\WidthBrand System\\L2+\\mtusi2026lab3\\results\\scaling\\stats\\C_after_c8_r1.csv" + }, + { + "concurrency": 16, + "repeat": 0, + "metrics": { + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.381, + "concurrency": 16, + "successful_requests": 4035, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 132.815, + "successful_latency_ms": { + "p50": 120.123, + "p95": 243.769, + "p99": 387.436 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." + }, + "pg_before": { + "numbackends": "17", + "active": "1", + "waits": "", + "top_sql": "" + }, + "pg_after": { + "numbackends": "21", + "active": "1", + "waits": "", + "top_sql": "" + }, + "stats_csv": "C:\\Courses\\Course_4\\WidthBrand System\\L2+\\mtusi2026lab3\\results\\scaling\\stats\\C_after_c16_r0.csv" + }, + { + "concurrency": 16, + "repeat": 1, + "metrics": { + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.536, + "concurrency": 16, + "successful_requests": 3519, + "failed_requests": 1, + "error_ratio": 0.000284, + "successful_rps": 115.241, + "successful_latency_ms": { + "p50": 126.575, + "p95": 245.77, + "p99": 414.042 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." + }, + "pg_before": { + "numbackends": "21", + "active": "1", + "waits": "", + "top_sql": "" + }, + "pg_after": { + "numbackends": "21", + "active": "1", + "waits": "", + "top_sql": "" + }, + "stats_csv": "C:\\Courses\\Course_4\\WidthBrand System\\L2+\\mtusi2026lab3\\results\\scaling\\stats\\C_after_c16_r1.csv" + }, + { + "concurrency": 32, + "repeat": 0, + "metrics": { + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.877, + "concurrency": 32, + "successful_requests": 3798, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 123.006, + "successful_latency_ms": { + "p50": 245.379, + "p95": 434.78, + "p99": 813.811 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." + }, + "pg_before": { + "numbackends": "21", + "active": "1", + "waits": "", + "top_sql": "" + }, + "pg_after": { + "numbackends": "21", + "active": "1", + "waits": "", + "top_sql": "" + }, + "stats_csv": "C:\\Courses\\Course_4\\WidthBrand System\\L2+\\mtusi2026lab3\\results\\scaling\\stats\\C_after_c32_r0.csv" + }, + { + "concurrency": 32, + "repeat": 1, + "metrics": { + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.81, + "concurrency": 32, + "successful_requests": 4168, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 135.281, + "successful_latency_ms": { + "p50": 211.169, + "p95": 337.457, + "p99": 763.31 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." + }, + "pg_before": { + "numbackends": "21", + "active": "1", + "waits": "", + "top_sql": "" + }, + "pg_after": { + "numbackends": "21", + "active": "1", + "waits": "", + "top_sql": "" + }, + "stats_csv": "C:\\Courses\\Course_4\\WidthBrand System\\L2+\\mtusi2026lab3\\results\\scaling\\stats\\C_after_c32_r1.csv" + }, + { + "concurrency": 64, + "repeat": 0, + "metrics": { + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 31.582, + "concurrency": 64, + "successful_requests": 4328, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 137.042, + "successful_latency_ms": { + "p50": 421.653, + "p95": 710.484, + "p99": 1016.113 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." + }, + "pg_before": { + "numbackends": "21", + "active": "1", + "waits": "", + "top_sql": "" + }, + "pg_after": { + "numbackends": "21", + "active": "1", + "waits": "", + "top_sql": "" + }, + "stats_csv": "C:\\Courses\\Course_4\\WidthBrand System\\L2+\\mtusi2026lab3\\results\\scaling\\stats\\C_after_c64_r0.csv" + }, + { + "concurrency": 64, + "repeat": 1, + "metrics": { + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 31.766, + "concurrency": 64, + "successful_requests": 3989, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 125.574, + "successful_latency_ms": { + "p50": 452.114, + "p95": 791.945, + "p99": 1016.634 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." + }, + "pg_before": { + "numbackends": "21", + "active": "1", + "waits": "", + "top_sql": "" + }, + "pg_after": { + "numbackends": "21", + "active": "1", + "waits": "", + "top_sql": "" + }, + "stats_csv": "C:\\Courses\\Course_4\\WidthBrand System\\L2+\\mtusi2026lab3\\results\\scaling\\stats\\C_after_c64_r1.csv" + } + ], + "summary": { + "8": { + "median_rps": 128.827, + "runs": 2 + }, + "16": { + "median_rps": 132.815, + "runs": 2 + }, + "32": { + "median_rps": 135.281, + "runs": 2 + }, + "64": { + "median_rps": 137.042, + "runs": 2 + } + } + }, + { + "series": "D", + "name": "D_pool_starved", + "replicas": 2, + "api_cpu": 1.0, + "api_mem": "512M", + "pg_cpu": 1.0, + "pool": 2, + "overflow": 0, + "pool_timeout": 5, + "nginx_mode": "keepalive", + "observed_instance_ids": [ + "api-81838c35", + "api-f031d0cf" + ], + "points": [ + { + "concurrency": 8, + "repeat": 0, + "metrics": { + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.329, + "concurrency": 8, + "successful_requests": 2727, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 89.913, + "successful_latency_ms": { + "p50": 72.25, + "p95": 196.561, + "p99": 359.412 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." + }, + "pg_before": { + "numbackends": "5", + "active": "1", + "waits": "", + "top_sql": "" + }, + "pg_after": { + "numbackends": "5", + "active": "1", + "waits": "", + "top_sql": "" + }, + "stats_csv": "C:\\Courses\\Course_4\\WidthBrand System\\L2+\\mtusi2026lab3\\results\\scaling\\stats\\D_pool_starved_c8_r0.csv" + }, + { + "concurrency": 8, + "repeat": 1, + "metrics": { + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.537, + "concurrency": 8, + "successful_requests": 2620, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 85.799, + "successful_latency_ms": { + "p50": 74.935, + "p95": 206.454, + "p99": 348.505 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." + }, + "pg_before": { + "numbackends": "5", + "active": "1", + "waits": "", + "top_sql": "" + }, + "pg_after": { + "numbackends": "5", + "active": "1", + "waits": "", + "top_sql": "" + }, + "stats_csv": "C:\\Courses\\Course_4\\WidthBrand System\\L2+\\mtusi2026lab3\\results\\scaling\\stats\\D_pool_starved_c8_r1.csv" + }, + { + "concurrency": 16, + "repeat": 0, + "metrics": { + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.771, + "concurrency": 16, + "successful_requests": 3124, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 101.523, + "successful_latency_ms": { + "p50": 113.746, + "p95": 413.322, + "p99": 726.637 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." + }, + "pg_before": { + "numbackends": "5", + "active": "1", + "waits": "", + "top_sql": "" + }, + "pg_after": { + "numbackends": "5", + "active": "1", + "waits": "", + "top_sql": "" + }, + "stats_csv": "C:\\Courses\\Course_4\\WidthBrand System\\L2+\\mtusi2026lab3\\results\\scaling\\stats\\D_pool_starved_c16_r0.csv" + }, + { + "concurrency": 16, + "repeat": 1, + "metrics": { + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.56, + "concurrency": 16, + "successful_requests": 2922, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 95.614, + "successful_latency_ms": { + "p50": 119.6, + "p95": 510.127, + "p99": 908.637 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." + }, + "pg_before": { + "numbackends": "5", + "active": "1", + "waits": "", + "top_sql": "" + }, + "pg_after": { + "numbackends": "5", + "active": "1", + "waits": "", + "top_sql": "" + }, + "stats_csv": "C:\\Courses\\Course_4\\WidthBrand System\\L2+\\mtusi2026lab3\\results\\scaling\\stats\\D_pool_starved_c16_r1.csv" + }, + { + "concurrency": 32, + "repeat": 0, + "metrics": { + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 31.231, + "concurrency": 32, + "successful_requests": 3168, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 101.437, + "successful_latency_ms": { + "p50": 216.453, + "p95": 1047.966, + "p99": 1769.263 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." + }, + "pg_before": { + "numbackends": "5", + "active": "1", + "waits": "", + "top_sql": "" + }, + "pg_after": { + "numbackends": "5", + "active": "1", + "waits": "", + "top_sql": "" + }, + "stats_csv": "C:\\Courses\\Course_4\\WidthBrand System\\L2+\\mtusi2026lab3\\results\\scaling\\stats\\D_pool_starved_c32_r0.csv" + }, + { + "concurrency": 32, + "repeat": 1, + "metrics": { + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 31.116, + "concurrency": 32, + "successful_requests": 3043, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 97.797, + "successful_latency_ms": { + "p50": 233.299, + "p95": 994.507, + "p99": 1727.046 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." + }, + "pg_before": { + "numbackends": "5", + "active": "1", + "waits": "", + "top_sql": "" + }, + "pg_after": { + "numbackends": "5", + "active": "1", + "waits": "", + "top_sql": "" + }, + "stats_csv": "C:\\Courses\\Course_4\\WidthBrand System\\L2+\\mtusi2026lab3\\results\\scaling\\stats\\D_pool_starved_c32_r1.csv" + }, + { + "concurrency": 64, + "repeat": 0, + "metrics": { + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 32.358, + "concurrency": 64, + "successful_requests": 3413, + "failed_requests": 1, + "error_ratio": 0.000293, + "successful_rps": 105.476, + "successful_latency_ms": { + "p50": 495.835, + "p95": 1305.867, + "p99": 2902.993 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." + }, + "pg_before": { + "numbackends": "5", + "active": "1", + "waits": "", + "top_sql": "" + }, + "pg_after": { + "numbackends": "5", + "active": "1", + "waits": "", + "top_sql": "" + }, + "stats_csv": "C:\\Courses\\Course_4\\WidthBrand System\\L2+\\mtusi2026lab3\\results\\scaling\\stats\\D_pool_starved_c64_r0.csv" + }, + { + "concurrency": 64, + "repeat": 1, + "metrics": { + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 31.881, + "concurrency": 64, + "successful_requests": 3323, + "failed_requests": 1, + "error_ratio": 0.000301, + "successful_rps": 104.233, + "successful_latency_ms": { + "p50": 439.879, + "p95": 1541.484, + "p99": 2527.471 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." + }, + "pg_before": { + "numbackends": "5", + "active": "1", + "waits": "", + "top_sql": "" + }, + "pg_after": { + "numbackends": "5", + "active": "1", + "waits": "", + "top_sql": "" + }, + "stats_csv": "C:\\Courses\\Course_4\\WidthBrand System\\L2+\\mtusi2026lab3\\results\\scaling\\stats\\D_pool_starved_c64_r1.csv" + } + ], + "summary": { + "8": { + "median_rps": 89.913, + "runs": 2 + }, + "16": { + "median_rps": 101.523, + "runs": 2 + }, + "32": { + "median_rps": 101.437, + "runs": 2 + }, + "64": { + "median_rps": 105.476, + "runs": 2 + } + } + }, + { + "series": "D", + "name": "D_pool_normal", + "replicas": 2, + "api_cpu": 1.0, + "api_mem": "512M", + "pg_cpu": 1.0, + "pool": 10, + "overflow": 20, + "pool_timeout": 30, + "nginx_mode": "keepalive", + "observed_instance_ids": [ + "api-48961cd5", + "api-8509b9d5" + ], + "points": [ + { + "concurrency": 8, + "repeat": 0, + "metrics": { + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.277, + "concurrency": 8, + "successful_requests": 2782, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 91.883, + "successful_latency_ms": { + "p50": 81.766, + "p95": 135.009, + "p99": 287.643 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." + }, + "pg_before": { + "numbackends": "15", + "active": "1", + "waits": "", + "top_sql": "" + }, + "pg_after": { + "numbackends": "16", + "active": "1", + "waits": "", + "top_sql": "" + }, + "stats_csv": "C:\\Courses\\Course_4\\WidthBrand System\\L2+\\mtusi2026lab3\\results\\scaling\\stats\\D_pool_normal_c8_r0.csv" + }, + { + "concurrency": 8, + "repeat": 1, + "metrics": { + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.243, + "concurrency": 8, + "successful_requests": 2954, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 97.675, + "successful_latency_ms": { + "p50": 72.722, + "p95": 160.538, + "p99": 216.538 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." + }, + "pg_before": { + "numbackends": "16", + "active": "1", + "waits": "", + "top_sql": "" + }, + "pg_after": { + "numbackends": "16", + "active": "1", + "waits": "", + "top_sql": "" + }, + "stats_csv": "C:\\Courses\\Course_4\\WidthBrand System\\L2+\\mtusi2026lab3\\results\\scaling\\stats\\D_pool_normal_c8_r1.csv" + }, + { + "concurrency": 16, + "repeat": 0, + "metrics": { + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.459, + "concurrency": 16, + "successful_requests": 3085, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 101.283, + "successful_latency_ms": { + "p50": 153.651, + "p95": 286.247, + "p99": 390.87 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." + }, + "pg_before": { + "numbackends": "16", + "active": "1", + "waits": "", + "top_sql": "" + }, + "pg_after": { + "numbackends": "20", + "active": "1", + "waits": "", + "top_sql": "" + }, + "stats_csv": "C:\\Courses\\Course_4\\WidthBrand System\\L2+\\mtusi2026lab3\\results\\scaling\\stats\\D_pool_normal_c16_r0.csv" + }, + { + "concurrency": 16, + "repeat": 1, + "metrics": { + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.451, + "concurrency": 16, + "successful_requests": 3231, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 106.106, + "successful_latency_ms": { + "p50": 142.19, + "p95": 265.706, + "p99": 419.588 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." + }, + "pg_before": { + "numbackends": "20", + "active": "1", + "waits": "", + "top_sql": "" + }, + "pg_after": { + "numbackends": "21", + "active": "1", + "waits": "", + "top_sql": "" + }, + "stats_csv": "C:\\Courses\\Course_4\\WidthBrand System\\L2+\\mtusi2026lab3\\results\\scaling\\stats\\D_pool_normal_c16_r1.csv" + }, + { + "concurrency": 32, + "repeat": 0, + "metrics": { + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 30.986, + "concurrency": 32, + "successful_requests": 3216, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 103.79, + "successful_latency_ms": { + "p50": 269.013, + "p95": 518.976, + "p99": 886.085 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." + }, + "pg_before": { + "numbackends": "21", + "active": "1", + "waits": "", + "top_sql": "" + }, + "pg_after": { + "numbackends": "21", + "active": "1", + "waits": "", + "top_sql": "" + }, + "stats_csv": "C:\\Courses\\Course_4\\WidthBrand System\\L2+\\mtusi2026lab3\\results\\scaling\\stats\\D_pool_normal_c32_r0.csv" + }, + { + "concurrency": 32, + "repeat": 1, + "metrics": { + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 31.69, + "concurrency": 32, + "successful_requests": 2354, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 74.283, + "successful_latency_ms": { + "p50": 369.394, + "p95": 783.569, + "p99": 1111.781 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." + }, + "pg_before": { + "numbackends": "21", + "active": "1", + "waits": "", + "top_sql": "" + }, + "pg_after": { + "numbackends": "21", + "active": "1", + "waits": "", + "top_sql": "" + }, + "stats_csv": "C:\\Courses\\Course_4\\WidthBrand System\\L2+\\mtusi2026lab3\\results\\scaling\\stats\\D_pool_normal_c32_r1.csv" + }, + { + "concurrency": 64, + "repeat": 0, + "metrics": { + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 32.502, + "concurrency": 64, + "successful_requests": 2276, + "failed_requests": 1, + "error_ratio": 0.000439, + "successful_rps": 70.026, + "successful_latency_ms": { + "p50": 686.258, + "p95": 1379.716, + "p99": 4132.014 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." + }, + "pg_before": { + "numbackends": "21", + "active": "1", + "waits": "", + "top_sql": "" + }, + "pg_after": { + "numbackends": "21", + "active": "1", + "waits": "", + "top_sql": "" + }, + "stats_csv": "C:\\Courses\\Course_4\\WidthBrand System\\L2+\\mtusi2026lab3\\results\\scaling\\stats\\D_pool_normal_c64_r0.csv" + }, + { + "concurrency": 64, + "repeat": 1, + "metrics": { + "lab": 3, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 30.0, + "elapsed_seconds": 32.411, + "concurrency": 64, + "successful_requests": 2667, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 82.287, + "successful_latency_ms": { + "p50": 643.335, + "p95": 1390.41, + "p99": 1641.975 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." + }, + "pg_before": { + "numbackends": "21", + "active": "1", + "waits": "", + "top_sql": "" + }, + "pg_after": { + "numbackends": "21", + "active": "1", + "waits": "", + "top_sql": "" + }, + "stats_csv": "C:\\Courses\\Course_4\\WidthBrand System\\L2+\\mtusi2026lab3\\results\\scaling\\stats\\D_pool_normal_c64_r1.csv" + } + ], + "summary": { + "8": { + "median_rps": 97.675, + "runs": 2 + }, + "16": { + "median_rps": 106.106, + "runs": 2 + }, + "32": { + "median_rps": 103.79, + "runs": 2 + }, + "64": { + "median_rps": 82.287, + "runs": 2 + } + } + } + ], + "finished_at": "2026-11-17T14:34:04.204345+00:00" +} \ No newline at end of file diff --git a/results/scaling/serie_a_fixed_budget.png b/results/scaling/serie_a_fixed_budget.png new file mode 100644 index 00000000..7c40435d Binary files /dev/null and b/results/scaling/serie_a_fixed_budget.png differ diff --git a/results/scaling/serie_b_resource_growth.png b/results/scaling/serie_b_resource_growth.png new file mode 100644 index 00000000..b675b8db Binary files /dev/null and b/results/scaling/serie_b_resource_growth.png differ diff --git a/results/scaling/serie_c_keepalive_ab.png b/results/scaling/serie_c_keepalive_ab.png new file mode 100644 index 00000000..d078ea9a Binary files /dev/null and b/results/scaling/serie_c_keepalive_ab.png differ diff --git a/results/scaling/serie_d_pool_saturation.png b/results/scaling/serie_d_pool_saturation.png new file mode 100644 index 00000000..0ae5416b Binary files /dev/null and b/results/scaling/serie_d_pool_saturation.png differ diff --git a/results/scaling/stats/A_r1_c16_r0.csv b/results/scaling/stats/A_r1_c16_r0.csv new file mode 100644 index 00000000..e69de29b diff --git a/results/scaling/stats/A_r1_c16_r1.csv b/results/scaling/stats/A_r1_c16_r1.csv new file mode 100644 index 00000000..e69de29b diff --git a/results/scaling/stats/A_r1_c32_r0.csv b/results/scaling/stats/A_r1_c32_r0.csv new file mode 100644 index 00000000..e69de29b diff --git a/results/scaling/stats/A_r1_c32_r1.csv b/results/scaling/stats/A_r1_c32_r1.csv new file mode 100644 index 00000000..e69de29b diff --git a/results/scaling/stats/A_r1_c64_r0.csv b/results/scaling/stats/A_r1_c64_r0.csv new file mode 100644 index 00000000..e69de29b diff --git a/results/scaling/stats/A_r1_c64_r1.csv b/results/scaling/stats/A_r1_c64_r1.csv new file mode 100644 index 00000000..e69de29b diff --git a/results/scaling/stats/A_r1_c8_r0.csv b/results/scaling/stats/A_r1_c8_r0.csv new file mode 100644 index 00000000..e69de29b diff --git a/results/scaling/stats/A_r1_c8_r1.csv b/results/scaling/stats/A_r1_c8_r1.csv new file mode 100644 index 00000000..e69de29b diff --git a/results/scaling/stats/A_r2_c16_r0.csv b/results/scaling/stats/A_r2_c16_r0.csv new file mode 100644 index 00000000..e69de29b diff --git a/results/scaling/stats/A_r2_c16_r1.csv b/results/scaling/stats/A_r2_c16_r1.csv new file mode 100644 index 00000000..e69de29b diff --git a/results/scaling/stats/A_r2_c32_r0.csv b/results/scaling/stats/A_r2_c32_r0.csv new file mode 100644 index 00000000..e69de29b diff --git a/results/scaling/stats/A_r2_c32_r1.csv b/results/scaling/stats/A_r2_c32_r1.csv new file mode 100644 index 00000000..e69de29b diff --git a/results/scaling/stats/A_r2_c64_r0.csv b/results/scaling/stats/A_r2_c64_r0.csv new file mode 100644 index 00000000..e69de29b diff --git a/results/scaling/stats/A_r2_c64_r1.csv b/results/scaling/stats/A_r2_c64_r1.csv new file mode 100644 index 00000000..e69de29b diff --git a/results/scaling/stats/A_r2_c8_r0.csv b/results/scaling/stats/A_r2_c8_r0.csv new file mode 100644 index 00000000..e69de29b diff --git a/results/scaling/stats/A_r2_c8_r1.csv b/results/scaling/stats/A_r2_c8_r1.csv new file mode 100644 index 00000000..e69de29b diff --git a/results/scaling/stats/A_r4_c16_r0.csv b/results/scaling/stats/A_r4_c16_r0.csv new file mode 100644 index 00000000..e69de29b diff --git a/results/scaling/stats/A_r4_c16_r1.csv b/results/scaling/stats/A_r4_c16_r1.csv new file mode 100644 index 00000000..e69de29b diff --git a/results/scaling/stats/A_r4_c32_r0.csv b/results/scaling/stats/A_r4_c32_r0.csv new file mode 100644 index 00000000..e69de29b diff --git a/results/scaling/stats/A_r4_c32_r1.csv b/results/scaling/stats/A_r4_c32_r1.csv new file mode 100644 index 00000000..e69de29b diff --git a/results/scaling/stats/A_r4_c64_r0.csv b/results/scaling/stats/A_r4_c64_r0.csv new file mode 100644 index 00000000..e69de29b diff --git a/results/scaling/stats/A_r4_c64_r1.csv b/results/scaling/stats/A_r4_c64_r1.csv new file mode 100644 index 00000000..e69de29b diff --git a/results/scaling/stats/A_r4_c8_r0.csv b/results/scaling/stats/A_r4_c8_r0.csv new file mode 100644 index 00000000..e69de29b diff --git a/results/scaling/stats/A_r4_c8_r1.csv b/results/scaling/stats/A_r4_c8_r1.csv new file mode 100644 index 00000000..e69de29b diff --git a/results/scaling/stats/B_cpu1_c16_r0.csv b/results/scaling/stats/B_cpu1_c16_r0.csv new file mode 100644 index 00000000..e69de29b diff --git a/results/scaling/stats/B_cpu1_c16_r1.csv b/results/scaling/stats/B_cpu1_c16_r1.csv new file mode 100644 index 00000000..e69de29b diff --git a/results/scaling/stats/B_cpu1_c32_r0.csv b/results/scaling/stats/B_cpu1_c32_r0.csv new file mode 100644 index 00000000..e69de29b diff --git a/results/scaling/stats/B_cpu1_c32_r1.csv b/results/scaling/stats/B_cpu1_c32_r1.csv new file mode 100644 index 00000000..e69de29b diff --git a/results/scaling/stats/B_cpu1_c64_r0.csv b/results/scaling/stats/B_cpu1_c64_r0.csv new file mode 100644 index 00000000..e69de29b diff --git a/results/scaling/stats/B_cpu1_c64_r1.csv b/results/scaling/stats/B_cpu1_c64_r1.csv new file mode 100644 index 00000000..e69de29b diff --git a/results/scaling/stats/B_cpu1_c8_r0.csv b/results/scaling/stats/B_cpu1_c8_r0.csv new file mode 100644 index 00000000..e69de29b diff --git a/results/scaling/stats/B_cpu1_c8_r1.csv b/results/scaling/stats/B_cpu1_c8_r1.csv new file mode 100644 index 00000000..e69de29b diff --git a/results/scaling/stats/B_cpu2_c16_r0.csv b/results/scaling/stats/B_cpu2_c16_r0.csv new file mode 100644 index 00000000..e69de29b diff --git a/results/scaling/stats/B_cpu2_c16_r1.csv b/results/scaling/stats/B_cpu2_c16_r1.csv new file mode 100644 index 00000000..e69de29b diff --git a/results/scaling/stats/B_cpu2_c32_r0.csv b/results/scaling/stats/B_cpu2_c32_r0.csv new file mode 100644 index 00000000..e69de29b diff --git a/results/scaling/stats/B_cpu2_c32_r1.csv b/results/scaling/stats/B_cpu2_c32_r1.csv new file mode 100644 index 00000000..e69de29b diff --git a/results/scaling/stats/B_cpu2_c64_r0.csv b/results/scaling/stats/B_cpu2_c64_r0.csv new file mode 100644 index 00000000..e69de29b diff --git a/results/scaling/stats/B_cpu2_c64_r1.csv b/results/scaling/stats/B_cpu2_c64_r1.csv new file mode 100644 index 00000000..e69de29b diff --git a/results/scaling/stats/B_cpu2_c8_r0.csv b/results/scaling/stats/B_cpu2_c8_r0.csv new file mode 100644 index 00000000..e69de29b diff --git a/results/scaling/stats/B_cpu2_c8_r1.csv b/results/scaling/stats/B_cpu2_c8_r1.csv new file mode 100644 index 00000000..e69de29b diff --git a/results/scaling/stats/B_cpu4_c16_r0.csv b/results/scaling/stats/B_cpu4_c16_r0.csv new file mode 100644 index 00000000..e69de29b diff --git a/results/scaling/stats/B_cpu4_c16_r1.csv b/results/scaling/stats/B_cpu4_c16_r1.csv new file mode 100644 index 00000000..e69de29b diff --git a/results/scaling/stats/B_cpu4_c32_r0.csv b/results/scaling/stats/B_cpu4_c32_r0.csv new file mode 100644 index 00000000..e69de29b diff --git a/results/scaling/stats/B_cpu4_c32_r1.csv b/results/scaling/stats/B_cpu4_c32_r1.csv new file mode 100644 index 00000000..e69de29b diff --git a/results/scaling/stats/B_cpu4_c64_r0.csv b/results/scaling/stats/B_cpu4_c64_r0.csv new file mode 100644 index 00000000..e69de29b diff --git a/results/scaling/stats/B_cpu4_c64_r1.csv b/results/scaling/stats/B_cpu4_c64_r1.csv new file mode 100644 index 00000000..e69de29b diff --git a/results/scaling/stats/B_cpu4_c8_r0.csv b/results/scaling/stats/B_cpu4_c8_r0.csv new file mode 100644 index 00000000..e69de29b diff --git a/results/scaling/stats/B_cpu4_c8_r1.csv b/results/scaling/stats/B_cpu4_c8_r1.csv new file mode 100644 index 00000000..e69de29b diff --git a/results/scaling/stats/B_cpu4_db2_c16_r0.csv b/results/scaling/stats/B_cpu4_db2_c16_r0.csv new file mode 100644 index 00000000..e69de29b diff --git a/results/scaling/stats/B_cpu4_db2_c16_r1.csv b/results/scaling/stats/B_cpu4_db2_c16_r1.csv new file mode 100644 index 00000000..e69de29b diff --git a/results/scaling/stats/B_cpu4_db2_c32_r0.csv b/results/scaling/stats/B_cpu4_db2_c32_r0.csv new file mode 100644 index 00000000..e69de29b diff --git a/results/scaling/stats/B_cpu4_db2_c32_r1.csv b/results/scaling/stats/B_cpu4_db2_c32_r1.csv new file mode 100644 index 00000000..e69de29b diff --git a/results/scaling/stats/B_cpu4_db2_c64_r0.csv b/results/scaling/stats/B_cpu4_db2_c64_r0.csv new file mode 100644 index 00000000..e69de29b diff --git a/results/scaling/stats/B_cpu4_db2_c64_r1.csv b/results/scaling/stats/B_cpu4_db2_c64_r1.csv new file mode 100644 index 00000000..e69de29b diff --git a/results/scaling/stats/B_cpu4_db2_c8_r0.csv b/results/scaling/stats/B_cpu4_db2_c8_r0.csv new file mode 100644 index 00000000..e69de29b diff --git a/results/scaling/stats/B_cpu4_db2_c8_r1.csv b/results/scaling/stats/B_cpu4_db2_c8_r1.csv new file mode 100644 index 00000000..e69de29b diff --git a/results/scaling/stats/C_after_c16_r0.csv b/results/scaling/stats/C_after_c16_r0.csv new file mode 100644 index 00000000..e69de29b diff --git a/results/scaling/stats/C_after_c16_r1.csv b/results/scaling/stats/C_after_c16_r1.csv new file mode 100644 index 00000000..e69de29b diff --git a/results/scaling/stats/C_after_c32_r0.csv b/results/scaling/stats/C_after_c32_r0.csv new file mode 100644 index 00000000..e69de29b diff --git a/results/scaling/stats/C_after_c32_r1.csv b/results/scaling/stats/C_after_c32_r1.csv new file mode 100644 index 00000000..e69de29b diff --git a/results/scaling/stats/C_after_c64_r0.csv b/results/scaling/stats/C_after_c64_r0.csv new file mode 100644 index 00000000..e69de29b diff --git a/results/scaling/stats/C_after_c64_r1.csv b/results/scaling/stats/C_after_c64_r1.csv new file mode 100644 index 00000000..e69de29b diff --git a/results/scaling/stats/C_after_c8_r0.csv b/results/scaling/stats/C_after_c8_r0.csv new file mode 100644 index 00000000..e69de29b diff --git a/results/scaling/stats/C_after_c8_r1.csv b/results/scaling/stats/C_after_c8_r1.csv new file mode 100644 index 00000000..e69de29b diff --git a/results/scaling/stats/C_before_c16_r0.csv b/results/scaling/stats/C_before_c16_r0.csv new file mode 100644 index 00000000..e69de29b diff --git a/results/scaling/stats/C_before_c16_r1.csv b/results/scaling/stats/C_before_c16_r1.csv new file mode 100644 index 00000000..e69de29b diff --git a/results/scaling/stats/C_before_c32_r0.csv b/results/scaling/stats/C_before_c32_r0.csv new file mode 100644 index 00000000..e69de29b diff --git a/results/scaling/stats/C_before_c32_r1.csv b/results/scaling/stats/C_before_c32_r1.csv new file mode 100644 index 00000000..e69de29b diff --git a/results/scaling/stats/C_before_c64_r0.csv b/results/scaling/stats/C_before_c64_r0.csv new file mode 100644 index 00000000..e69de29b diff --git a/results/scaling/stats/C_before_c64_r1.csv b/results/scaling/stats/C_before_c64_r1.csv new file mode 100644 index 00000000..e69de29b diff --git a/results/scaling/stats/C_before_c8_r0.csv b/results/scaling/stats/C_before_c8_r0.csv new file mode 100644 index 00000000..e69de29b diff --git a/results/scaling/stats/C_before_c8_r1.csv b/results/scaling/stats/C_before_c8_r1.csv new file mode 100644 index 00000000..e69de29b diff --git a/results/scaling/stats/D_pool_normal_c16_r0.csv b/results/scaling/stats/D_pool_normal_c16_r0.csv new file mode 100644 index 00000000..e69de29b diff --git a/results/scaling/stats/D_pool_normal_c16_r1.csv b/results/scaling/stats/D_pool_normal_c16_r1.csv new file mode 100644 index 00000000..e69de29b diff --git a/results/scaling/stats/D_pool_normal_c32_r0.csv b/results/scaling/stats/D_pool_normal_c32_r0.csv new file mode 100644 index 00000000..e69de29b diff --git a/results/scaling/stats/D_pool_normal_c32_r1.csv b/results/scaling/stats/D_pool_normal_c32_r1.csv new file mode 100644 index 00000000..e69de29b diff --git a/results/scaling/stats/D_pool_normal_c64_r0.csv b/results/scaling/stats/D_pool_normal_c64_r0.csv new file mode 100644 index 00000000..e69de29b diff --git a/results/scaling/stats/D_pool_normal_c64_r1.csv b/results/scaling/stats/D_pool_normal_c64_r1.csv new file mode 100644 index 00000000..e69de29b diff --git a/results/scaling/stats/D_pool_normal_c8_r0.csv b/results/scaling/stats/D_pool_normal_c8_r0.csv new file mode 100644 index 00000000..e69de29b diff --git a/results/scaling/stats/D_pool_normal_c8_r1.csv b/results/scaling/stats/D_pool_normal_c8_r1.csv new file mode 100644 index 00000000..e69de29b diff --git a/results/scaling/stats/D_pool_starved_c16_r0.csv b/results/scaling/stats/D_pool_starved_c16_r0.csv new file mode 100644 index 00000000..e69de29b diff --git a/results/scaling/stats/D_pool_starved_c16_r1.csv b/results/scaling/stats/D_pool_starved_c16_r1.csv new file mode 100644 index 00000000..e69de29b diff --git a/results/scaling/stats/D_pool_starved_c32_r0.csv b/results/scaling/stats/D_pool_starved_c32_r0.csv new file mode 100644 index 00000000..e69de29b diff --git a/results/scaling/stats/D_pool_starved_c32_r1.csv b/results/scaling/stats/D_pool_starved_c32_r1.csv new file mode 100644 index 00000000..e69de29b diff --git a/results/scaling/stats/D_pool_starved_c64_r0.csv b/results/scaling/stats/D_pool_starved_c64_r0.csv new file mode 100644 index 00000000..e69de29b diff --git a/results/scaling/stats/D_pool_starved_c64_r1.csv b/results/scaling/stats/D_pool_starved_c64_r1.csv new file mode 100644 index 00000000..e69de29b diff --git a/results/scaling/stats/D_pool_starved_c8_r0.csv b/results/scaling/stats/D_pool_starved_c8_r0.csv new file mode 100644 index 00000000..e69de29b diff --git a/results/scaling/stats/D_pool_starved_c8_r1.csv b/results/scaling/stats/D_pool_starved_c8_r1.csv new file mode 100644 index 00000000..e69de29b diff --git a/results/scaling/summary_table.md b/results/scaling/summary_table.md new file mode 100644 index 00000000..01276c4d --- /dev/null +++ b/results/scaling/summary_table.md @@ -0,0 +1,46 @@ +| config | replicas | Σcpu API | conc | median RPS | p50 | p95 | p99 | err | +|---|---|---|---|---|---|---|---|---| +| A_r1 | 1 | 2.0 | 8 | 81.082 | 93.293 | 142.57 | 186.358 | 0.0 | +| A_r1 | 1 | 2.0 | 16 | 63.524 | 241.671 | 308.596 | 403.043 | 0.0 | +| A_r1 | 1 | 2.0 | 32 | 65.674 | 467.2 | 564.567 | 631.184 | 0.0 | +| A_r1 | 1 | 2.0 | 64 | 61.066 | 932.033 | 1517.955 | 1933.84 | 0.0 | +| A_r2 | 2 | 2.0 | 8 | 96.712 | 77.374 | 121.606 | 283.559 | 0.0 | +| A_r2 | 2 | 2.0 | 16 | 96.257 | 156.584 | 297.532 | 487.406 | 0.0 | +| A_r2 | 2 | 2.0 | 32 | 96.204 | 313.846 | 491.884 | 719.817 | 0.0 | +| A_r2 | 2 | 2.0 | 64 | 92.34 | 639.263 | 1133.266 | 1428.111 | 0.0 | +| A_r4 | 4 | 2.0 | 8 | 81.821 | 83.799 | 212.542 | 354.647 | 0.0 | +| A_r4 | 4 | 2.0 | 16 | 78.334 | 123.695 | 528.564 | 691.632 | 0.0 | +| A_r4 | 4 | 2.0 | 32 | 78.96 | 295.913 | 1074.903 | 1503.062 | 0.0 | +| A_r4 | 4 | 2.0 | 64 | 74.97 | 730.405 | 1423.318 | 1987.414 | 0.0 | +| B_cpu1 | 2 | 1.0 | 8 | 54.418 | 119.522 | 335.784 | 496.236 | 0.0 | +| B_cpu1 | 2 | 1.0 | 16 | 66.26 | 225.172 | 476.917 | 846.654 | 0.0 | +| B_cpu1 | 2 | 1.0 | 32 | 65.918 | 493.769 | 947.531 | 1455.394 | 0.0 | +| B_cpu1 | 2 | 1.0 | 64 | 66.52 | 871.348 | 1500.298 | 1929.157 | 0.0 | +| B_cpu2 | 2 | 2.0 | 8 | 137.572 | 52.954 | 94.661 | 176.638 | 0.0 | +| B_cpu2 | 2 | 2.0 | 16 | 140.555 | 106.766 | 187.34 | 314.882 | 0.0 | +| B_cpu2 | 2 | 2.0 | 32 | 142.673 | 208.393 | 332.104 | 565.12 | 0.0 | +| B_cpu2 | 2 | 2.0 | 64 | 137.159 | 416.755 | 668.978 | 900.907 | 0.0 | +| B_cpu4 | 2 | 4.0 | 8 | 146.532 | 51.966 | 78.146 | 103.4 | 0.0 | +| B_cpu4 | 2 | 4.0 | 16 | 146.77 | 110.103 | 176.996 | 198.805 | 0.0 | +| B_cpu4 | 2 | 4.0 | 32 | 147.712 | 216.099 | 335.365 | 373.072 | 0.0 | +| B_cpu4 | 2 | 4.0 | 64 | 137.202 | 434.138 | 586.938 | 695.301 | 0.0 | +| B_cpu4_db2 | 2 | 4.0 | 8 | 141.673 | 53.683 | 83.618 | 110.812 | 0.0 | +| B_cpu4_db2 | 2 | 4.0 | 16 | 151.648 | 103.804 | 171.332 | 189.827 | 0.0 | +| B_cpu4_db2 | 2 | 4.0 | 32 | 146.39 | 213.342 | 324.028 | 361.637 | 0.0 | +| B_cpu4_db2 | 2 | 4.0 | 64 | 148.111 | 403.858 | 557.247 | 653.684 | 0.0 | +| C_before | 2 | 2.0 | 8 | 136.144 | 53.611 | 92.85 | 164.867 | 0.0 | +| C_before | 2 | 2.0 | 16 | 129.575 | 118.306 | 218.846 | 322.104 | 0.0 | +| C_before | 2 | 2.0 | 32 | 136.681 | 221.431 | 338.472 | 576.798 | 0.0 | +| C_before | 2 | 2.0 | 64 | 131.838 | 451.018 | 756.538 | 937.999 | 0.0 | +| C_after | 2 | 2.0 | 8 | 118.721 | 58.246 | 120.151 | 225.108 | 0.0 | +| C_after | 2 | 2.0 | 16 | 124.028 | 123.349 | 244.769 | 400.739 | 0.0 | +| C_after | 2 | 2.0 | 32 | 129.144 | 228.274 | 386.118 | 788.561 | 0.0 | +| C_after | 2 | 2.0 | 64 | 131.308 | 436.884 | 751.215 | 1016.374 | 0.0 | +| D_pool_starved | 2 | 2.0 | 8 | 87.856 | 73.593 | 201.507 | 353.958 | 0.0 | +| D_pool_starved | 2 | 2.0 | 16 | 98.569 | 116.673 | 461.725 | 817.637 | 0.0 | +| D_pool_starved | 2 | 2.0 | 32 | 99.617 | 224.876 | 1021.236 | 1748.155 | 0.0 | +| D_pool_starved | 2 | 2.0 | 64 | 104.855 | 467.857 | 1423.675 | 2715.232 | 0.0 | +| D_pool_normal | 2 | 2.0 | 8 | 94.779 | 77.244 | 147.774 | 252.09 | 0.0 | +| D_pool_normal | 2 | 2.0 | 16 | 103.695 | 147.921 | 275.976 | 405.229 | 0.0 | +| D_pool_normal | 2 | 2.0 | 32 | 89.037 | 319.203 | 651.273 | 998.933 | 0.0 | +| D_pool_normal | 2 | 2.0 | 64 | 76.156 | 664.797 | 1385.063 | 2886.994 | 0.0 | \ No newline at end of file diff --git a/scripts/check_503_retry_after.py b/scripts/check_503_retry_after.py new file mode 100644 index 00000000..e2dcb1d3 --- /dev/null +++ b/scripts/check_503_retry_after.py @@ -0,0 +1,161 @@ +import argparse +import base64 +import json +import statistics +import sys +import time +import urllib.error +import urllib.request +import uuid +from concurrent.futures import ThreadPoolExecutor + +BASE = "http://localhost:8080" + + +def setup(): + pwd = "SecurePassword123!" + ids = [] + for _ in range(2): + u = f"ra_{uuid.uuid4().hex[:10]}" + s, _, user, _ = call("POST", "/api/v1/users", + body={"username": u, "display_name": "RA", "password": pwd}) + assert s == 201, (s, user) + ids.append((u, user["id"])) + cred = base64.b64encode(f"{ids[0][0]}:{pwd}".encode()).decode() + s, _, sess, _ = call("POST", "/api/v1/auth/sessions", + headers={"Authorization": f"Basic {cred}"}) + assert s == 201, (s, sess) + h = {"Authorization": f"Bearer {sess['token']}"} + s, _, chat, _ = call("POST", "/api/v1/chats", headers=h, + body={"title": "Retry-After check", "member_ids": [i[1] for i in ids]}) + assert s == 201, (s, chat) + return h, chat["id"] + + +def pct(vals, p): + if not vals: + return None + v = sorted(vals) + return round(1000 * v[min(len(v) - 1, int(p * len(v)))], 1) + + +def call(method, path, headers=None, body=None): + data = json.dumps(body).encode() if body is not None else None + req = urllib.request.Request(BASE + path, data=data, method=method) + req.add_header("Accept", "application/json") + if data: + req.add_header("Content-Type", "application/json") + for k, v in (headers or {}).items(): + req.add_header(k, v) + t0 = time.monotonic() + try: + with urllib.request.urlopen(req, timeout=60) as r: + raw = r.read().decode() + hdr = {k.lower(): v for k, v in r.headers.items()} + return r.status, hdr, json.loads(raw) if raw else None, time.monotonic() - t0 + except urllib.error.HTTPError as e: + raw = e.read().decode() + hdr = {k.lower(): v for k, v in e.headers.items()} + try: + parsed = json.loads(raw) if raw else None + except ValueError: + parsed = {"_raw": raw[:200]} + return e.code, hdr, parsed, time.monotonic() - t0 + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--n", type=int, default=64) + ap.add_argument("--allow-zero-503", action="store_true") + args = ap.parse_args() + n = args.n + + h, chat_id = setup() + keys = [f"ra-{uuid.uuid4().hex}" for _ in range(n)] + bodies = [{"text": f"retry-after probe {i}"} for i in range(n)] + + def send(i): + s, hdr, body, dt = call("POST", f"/api/v1/chats/{chat_id}/messages", + headers={**h, "Idempotency-Key": keys[i]}, body=bodies[i]) + return i, s, hdr, body, dt + + wall0 = time.monotonic() + with ThreadPoolExecutor(max_workers=n) as ex: + first = list(ex.map(send, range(n))) + wall = time.monotonic() - wall0 + + codes, problems, retry_idx, lat = {}, [], [], [] + instances = set() + for i, s, hdr, body, dt in first: + codes[s] = codes.get(s, 0) + 1 + lat.append(dt) + if hdr.get("x-instance-id"): + instances.add(hdr["x-instance-id"]) + if s == 503: + retry_idx.append(i) + ra = hdr.get("retry-after") + err = (body or {}).get("error", {}) + if err.get("code") != "unavailable": + problems.append(f"[{i}] code={err.get('code')}, ожидался unavailable") + if not ra or not ra.isdigit() or int(ra) < 1: + problems.append(f"[{i}] некорректный Retry-After: {ra!r}") + if err.get("request_id") != hdr.get("x-request-id"): + problems.append(f"[{i}] request_id в теле != заголовку") + if not hdr.get("x-instance-id"): + problems.append(f"[{i}] нет X-Instance-Id") + if "QueuePool" in json.dumps(body): + problems.append(f"[{i}] утечка внутренних деталей") + if s == 500: + problems.append(f"[{i}] 500 instead of 503: {body}") + + print(f"Concurrent: {n}; wall time: {wall:.2f}s; replices found: {len(instances)} {sorted(instances)}") + print(f"Statusues of 1 cycle: {codes}") + print(f"Latency, ms: p50={pct(lat,.5)} p95={pct(lat,.95)} p99={pct(lat,.99)}") + print(f"503 с Retry-After: {len(retry_idx)}") + if retry_idx: + smp = next(r for r in first if r[1] == 503) + print(f"Example: Retry-After={smp[2].get('retry-after')}, " + f"message={smp[3]['error']['message']!r}") + + ok_ids = {b["id"] for _, s, _, b, _ in first if s == 201} + for i in retry_idx: + s, hdr, body, _ = call("POST", f"/api/v1/chats/{chat_id}/messages", + headers={**h, "Idempotency-Key": keys[i]}, body=bodies[i]) + if s != 201: + problems.append(f"retry[{i}] -> {s}, expected 201: {body}") + else: + ok_ids.add(body["id"]) + + total, cursor = 0, None + while True: + p = f"/api/v1/chats/{chat_id}/messages?limit=100" + if cursor: + p += "&cursor=" + cursor + s, _, page, _ = call("GET", p, headers=h) + assert s == 200, (s, page) + total += len(page["items"]) + cursor = page["next_cursor"] + if cursor is None: + break + + print(f"Messages in chat: {total}; unique id: {len(ok_ids)}; keys: {n}") + if total != n or len(ok_ids) != n: + problems.append(f"dublicates/losses: total={total}, ids={len(ok_ids)}, expected {n}") + + if problems: + print("\nFAIL:") + for p in problems[:15]: + print(" -", p) + if len(problems) > 15: + print(f" ... и ещё {len(problems)-15}") + sys.exit(1) + + if not retry_idx and not args.allow_zero_503: + print("\nINCONCLUSIVE: 503 не наблюдалось — маппинг пула НЕ проверен.") + sys.exit(2) + + print("\nPASS: 503 unavailable + Retry-After correct, retries are safe, no dublicates") + + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/scripts/failover_test.sh b/scripts/failover_test.sh new file mode 100644 index 00000000..c597d9c4 --- /dev/null +++ b/scripts/failover_test.sh @@ -0,0 +1,26 @@ +#!/bin/bash +set -e +export PYTHONUTF8=1 + +echo "Запуск фоновой нагрузки на 60 секунд" +python tests/load.py --duration 60 --concurrency 4 --output results/failover_metrics.json & LOAD_PID=$! + +echo "Прогрев (10 секунд)" +sleep 10 + +echo "Имитация отказа: остановка 1 реплики API" +docker stop mtusi2026lab3-api-1 + +echo "Ожидание перенаправления трафика (15 секунд)" +sleep 15 + +echo "Восстановление: запуск 1 реплики(Rolling Update)" +docker start mtusi2026lab3-api-1 + +echo "Ожидание завершения нагрузочного теста" +wait $LOAD_PID + +echo "Проверка идемпотентности (параллельный запрос с одним ключом)" +python scripts/test_idempotency_failover.py + +echo "Результаты в results/failover_metrics.json" diff --git a/scripts/plot_scaling.py b/scripts/plot_scaling.py new file mode 100644 index 00000000..34ab2376 --- /dev/null +++ b/scripts/plot_scaling.py @@ -0,0 +1,75 @@ +import json +import statistics +from pathlib import Path +import matplotlib +matplotlib.use("Agg") +import matplotlib.pyplot as plt + +ROOT = Path(__file__).resolve().parents[1] +RAW = ROOT / "results" / "scaling" / "raw.json" +OUT = ROOT / "results" / "scaling" +OUT.mkdir(parents=True, exist_ok=True) + +data = json.loads(RAW.read_text(encoding="utf-8")) + + +def points(cfg, key): + agg = {} + for p in cfg["points"]: + agg.setdefault(p["concurrency"], []).append(p["metrics"]) + xs = sorted(agg) + ys = [] + for x in xs: + vals = [m[key] if key in m else m["successful_latency_ms"][key] for m in agg[x]] + ys.append(statistics.median(vals)) + return xs, ys + + +def plot_series(series, fname, title): + cfgs = [c for c in data["configs"] if c["series"] == series] + if not cfgs: + return + fig, ax = plt.subplots(1, 3, figsize=(16, 4.2)) + for c in cfgs: + label = f"{c['name']} (r={c['replicas']}, Σcpu={c['replicas']*c['api_cpu']:.1f})" + x, y = points(c, "successful_rps"); ax[0].plot(x, y, "o-", label=label) + x, y = points(c, "p95"); ax[1].plot(x, y, "o-", label=label) + x, y = points(c, "error_ratio"); ax[2].plot(x, y, "o-", label=label) + ax[0].set(xlabel="concurrency", ylabel="successful RPS", title="Throughput") + ax[1].set(xlabel="concurrency", ylabel="p95 latency, ms", title="Tail latency") + ax[2].set(xlabel="concurrency", ylabel="error ratio", title="Errors") + for a in ax: + a.grid(alpha=.3); a.legend(fontsize=7) + fig.suptitle(title) + fig.tight_layout() + fig.savefig(OUT / fname, dpi=140) + print("saved", OUT / fname) + + +plot_series("A", "serie_a_fixed_budget.png", + "Serie A: fixed total API budget (2.0 CPU / 1024 MiB), 1 vs 2 vs 4 replicas") +plot_series("B", "serie_b_resource_growth.png", + "Serie B: growing API CPU, Postgres fixed") +plot_series("C", "serie_c_keepalive_ab.png", + "Serie C: nginx upstream keepalive A/B (identical resources)") +plot_series("D", "serie_d_pool_saturation.png", + "Serie D: connection-pool saturation at identical CPU (2x1.0)") + +lines = ["| config | replicas | Σcpu API | conc | median RPS | p50 | p95 | p99 | err |", + "|---|---|---|---|---|---|---|---|---|"] +for c in data["configs"]: + agg = {} + for p in c["points"]: + agg.setdefault(p["concurrency"], []).append(p["metrics"]) + for conc in sorted(agg): + ms = agg[conc] + med = lambda f: round(statistics.median([f(m) for m in ms]), 3) + lines.append( + f"| {c['name']} | {c['replicas']} | {c['replicas']*c['api_cpu']:.1f} | {conc} | " + f"{med(lambda m: m['successful_rps'])} | " + f"{med(lambda m: m['successful_latency_ms']['p50'])} | " + f"{med(lambda m: m['successful_latency_ms']['p95'])} | " + f"{med(lambda m: m['successful_latency_ms']['p99'])} | " + f"{med(lambda m: m['error_ratio'])} |") +(OUT / "summary_table.md").write_text("\n".join(lines), encoding="utf-8") +print("saved", OUT / "summary_table.md") \ No newline at end of file diff --git a/scripts/run_migrations.py b/scripts/run_migrations.py new file mode 100644 index 00000000..2fe34a40 --- /dev/null +++ b/scripts/run_migrations.py @@ -0,0 +1,17 @@ +import asyncio +import sys +from src.migrations.runner import run_migrations + + +async def main(): + print("Starting database migration") + try: + await run_migrations() + print("Migrations Success") + except Exception as e: + print(f"Migrations failed: {e}", file=sys.stderr) + sys.exit(1) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/scripts/scaling_benchmark.py b/scripts/scaling_benchmark.py new file mode 100644 index 00000000..ed601f55 --- /dev/null +++ b/scripts/scaling_benchmark.py @@ -0,0 +1,278 @@ +import argparse +import json +import os +import subprocess +import sys +import time +import urllib.error +import urllib.request +from datetime import datetime, timezone +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +RAW = ROOT / "results" / "scaling" +LOAD_DIR = RAW / "load" +STATS_DIR = RAW / "stats" +BASE_URL = os.getenv("BENCH_BASE_URL", "http://localhost:8080") + +CONCURRENCY = [8, 16, 32, 64] +DURATION = 30 +WARMUP = 10 +REPEATS = 2 + +NGINX_BASELINE = { + "KEEPALIVE_DIRECTIVE": "", + "PROXY_HTTP_VERSION_DIRECTIVE": "", + "PROXY_CONNECTION_DIRECTIVE": "", +} +NGINX_KEEPALIVE = { + "KEEPALIVE_DIRECTIVE": "keepalive 64;", + "PROXY_HTTP_VERSION_DIRECTIVE": "proxy_http_version 1.1;", + "PROXY_CONNECTION_DIRECTIVE": 'proxy_set_header Connection "";', +} + + +def series_a(): + return [ + dict(name="A_r1", replicas=1, api_cpu=2.0, api_mem="1024M", pg_cpu=1.0, + pool=10, overflow=20, pool_timeout=30, nginx=NGINX_BASELINE), + dict(name="A_r2", replicas=2, api_cpu=1.0, api_mem="512M", pg_cpu=1.0, + pool=10, overflow=20, pool_timeout=30, nginx=NGINX_BASELINE), + dict(name="A_r4", replicas=4, api_cpu=0.5, api_mem="256M", pg_cpu=1.0, + pool=10, overflow=20, pool_timeout=30, nginx=NGINX_BASELINE), + ] + + +def series_b(): + return [ + dict(name="B_cpu1", replicas=2, api_cpu=0.5, api_mem="512M", pg_cpu=1.0, + pool=10, overflow=20, pool_timeout=30, nginx=NGINX_KEEPALIVE), + dict(name="B_cpu2", replicas=2, api_cpu=1.0, api_mem="512M", pg_cpu=1.0, + pool=10, overflow=20, pool_timeout=30, nginx=NGINX_KEEPALIVE), + dict(name="B_cpu4", replicas=2, api_cpu=2.0, api_mem="512M", pg_cpu=1.0, + pool=10, overflow=20, pool_timeout=30, nginx=NGINX_KEEPALIVE), + dict(name="B_cpu4_db2", replicas=2, api_cpu=2.0, api_mem="512M", pg_cpu=2.0, + pool=10, overflow=20, pool_timeout=30, nginx=NGINX_KEEPALIVE), + ] + + +def series_c(): + base = dict(replicas=2, api_cpu=1.0, api_mem="512M", pg_cpu=1.0, + pool=10, overflow=20, pool_timeout=30) + return [ + dict(name="C_before", **base, nginx=NGINX_BASELINE), + dict(name="C_after", **base, nginx=NGINX_KEEPALIVE), + ] + + +def series_d(): + base = dict(replicas=2, api_cpu=1.0, api_mem="512M", pg_cpu=1.0, + nginx=NGINX_KEEPALIVE) + return [ + dict(name="D_pool_starved", **base, pool=2, overflow=0, pool_timeout=5), + dict(name="D_pool_normal", **base, pool=10, overflow=20, pool_timeout=30), + ] + + +SERIES = {"A": series_a, "B": series_b, "C": series_c, "D": series_d} + + +def build_env(cfg): + env = os.environ.copy() + env["PYTHONUTF8"] = "1" + env.update({ + "API_REPLICAS": str(cfg["replicas"]), + "API_CPU": str(cfg["api_cpu"]), + "API_MEM": cfg["api_mem"], + "PG_CPU": str(cfg["pg_cpu"]), + "DB_POOL_SIZE": str(cfg["pool"]), + "DB_MAX_OVERFLOW": str(cfg["overflow"]), + "DB_POOL_TIMEOUT": str(cfg.get("pool_timeout", 30)), + "DB_POOL_RECYCLE": str(cfg.get("pool_recycle", 3600)), + }) + env.update(cfg["nginx"]) + return env + + +def run(cmd, env, check=True, quiet=False): + return subprocess.run( + cmd, cwd=ROOT, env=env, check=check, + stdout=subprocess.DEVNULL if quiet else None, + stderr=subprocess.STDOUT if quiet else None, + ) + + +def wait_ready(timeout=180): + deadline = time.time() + timeout + while time.time() < deadline: + try: + with urllib.request.urlopen(BASE_URL + "/health/ready", timeout=3) as r: + if r.status == 200: + return True + except (urllib.error.URLError, urllib.error.HTTPError, OSError, TimeoutError): + pass + time.sleep(2) + return False + + +def observe_instances(n=14): + seen = set() + for _ in range(n): + try: + with urllib.request.urlopen(BASE_URL + "/health/ready", timeout=3) as r: + v = r.headers.get("X-Instance-Id") + if v: + seen.add(v) + except Exception: + pass + return sorted(seen) + + +def psql(sql, env): + p = subprocess.run( + ["docker", "compose", "exec", "-T", "postgres", "psql", + "-U", env.get("POSTGRES_USER", "mtusi"), + "-d", env.get("POSTGRES_DB", "mtusi-messenger"), "-At", "-c", sql], + cwd=ROOT, env=env, capture_output=True, text=True, + ) + return p.stdout.strip() if p.returncode == 0 else "" + + +def pg_snapshot(env): + out = { + "numbackends": psql("SELECT count(*) FROM pg_stat_activity WHERE datname IS NOT NULL;", env), + "active": psql("SELECT count(*) FROM pg_stat_activity WHERE state='active';", env), + "waits": psql("SELECT coalesce(wait_event_type,'cpu')||':'||count(*) FROM pg_stat_activity " + "WHERE backend_type='client backend' GROUP BY 1 ORDER BY 2 DESC;", env), + "top_sql": psql("SELECT calls||'|'||round(total_exec_time::numeric,1)||'|'||left(query,70) " + "FROM pg_stat_statements WHERE query ILIKE '%messages%' " + "AND query NOT ILIKE '%pg_stat%' ORDER BY total_exec_time DESC LIMIT 5;", env), + } + return out + + +class StatsSampler: + def __init__(self, path, interval=2.0): + self.path = path + self.interval = interval + self.proc = None + self.fh = None + + def __enter__(self): + self.path.parent.mkdir(parents=True, exist_ok=True) + self.fh = open(self.path, "w", encoding="utf-8") + fmt = '"{{.Name}}","{{.CPUPerc}}","{{.MemUsage}}","{{.NetIO}}","{{.BlockIO}}"' + script = (f'while true; do docker stats --no-stream --format {fmt}; ' + f'echo "---SAMPLE---"; sleep {self.interval}; done') + self.proc = subprocess.Popen(["bash", "-c", script], cwd=ROOT, + stdout=self.fh, stderr=subprocess.DEVNULL) + return self + + def __exit__(self, *a): + if self.proc: + self.proc.terminate() + try: + self.proc.wait(timeout=5) + except subprocess.TimeoutExpired: + self.proc.kill() + if self.fh: + self.fh.close() + + +def load_once(cfg, concurrency, duration, tag, env): + out = LOAD_DIR / f"{cfg['name']}_c{concurrency}_{tag}.json" + out.parent.mkdir(parents=True, exist_ok=True) + run([sys.executable, "-X", "utf8", "tests/load.py", + "--base-url", BASE_URL, + "--duration", str(duration), + "--concurrency", str(concurrency), + "--output", str(out)], env, check=False) + if not out.exists(): + return None + return json.loads(out.read_text(encoding="utf-8")) + + +def apply_config(cfg, env): + print(f"\n\nCONFIG {cfg['name']}: replicas={cfg['replicas']} " + f"cpu/replica={cfg['api_cpu']} Σcpu={cfg['replicas']*cfg['api_cpu']:.1f} " + f"pg_cpu={cfg['pg_cpu']} " + f"pool={cfg['pool']}+{cfg['overflow']} " + f"(max {cfg['replicas']*(cfg['pool']+cfg['overflow'])} conns) " + f"timeout={cfg.get('pool_timeout',30)}s\n") + + run(["docker", "compose", "up", "-d", "--no-deps", "--force-recreate", + "--scale", f"api={cfg['replicas']}", "api"], env, quiet=True) + run(["docker", "compose", "up", "-d", "--no-deps", "--force-recreate", "nginx"], env, quiet=True) + if not wait_ready(): + raise RuntimeError(f"{cfg['name']}: /health/ready not reached") + time.sleep(5) + ids = observe_instances() + print(f"Observed X-Instance-Id ({len(ids)}): {ids}") + return ids + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--series", nargs="+", default=["A"], choices=list(SERIES)) + ap.add_argument("--concurrency", nargs="+", type=int, default=CONCURRENCY) + ap.add_argument("--duration", type=int, default=DURATION) + ap.add_argument("--repeats", type=int, default=REPEATS) + args = ap.parse_args() + + RAW.mkdir(parents=True, exist_ok=True) + results = { + "started_at": datetime.now(timezone.utc).isoformat(), + "base_url": BASE_URL, + "profile": {"duration_s": args.duration, "warmup_s": WARMUP, + "concurrency": args.concurrency, "repeats": args.repeats, + "tool": "tests/load.py (closed-loop, no retries)"}, + "configs": [], + } + + for s in args.series: + for cfg in SERIES[s](): + env = build_env(cfg) + ids = apply_config(cfg, env) + entry = {"series": s, **{k: v for k, v in cfg.items() if k != "nginx"}, + "nginx_mode": "keepalive" if cfg["nginx"]["KEEPALIVE_DIRECTIVE"] else "baseline", + "observed_instance_ids": ids, "points": []} + + print(f"Warmup {WARMUP}s @ c={args.concurrency[0]} ...") + load_once(cfg, args.concurrency[0], WARMUP, "warmup", env) + + for c in args.concurrency: + runs = [] + for r in range(args.repeats): + pg_before = pg_snapshot(env) + with StatsSampler(STATS_DIR / f"{cfg['name']}_c{c}_r{r}.csv"): + m = load_once(cfg, c, args.duration, f"r{r}", env) + pg_after = pg_snapshot(env) + if m is None: + print(f" c={c} r={r}: LOAD FAILED") + continue + runs.append(m) + print(f" c={c} r={r}: rps={m['successful_rps']} " + f"err={m['error_ratio']} p95={m['successful_latency_ms']['p95']}ms " + f"pg_backends={pg_after['numbackends']}") + entry["points"].append({ + "concurrency": c, "repeat": r, "metrics": m, + "pg_before": pg_before, "pg_after": pg_after, + "stats_csv": str(STATS_DIR / f"{cfg['name']}_c{c}_r{r}.csv"), + }) + if runs: + rps = sorted(x["successful_rps"] for x in runs) + entry.setdefault("summary", {})[str(c)] = { + "median_rps": rps[len(rps)//2], + "runs": len(runs), + } + results["configs"].append(entry) + (RAW / "raw.json").write_text(json.dumps(results, ensure_ascii=False, indent=2), + encoding="utf-8") + + results["finished_at"] = datetime.now(timezone.utc).isoformat() + (RAW / "raw.json").write_text(json.dumps(results, ensure_ascii=False, indent=2), encoding="utf-8") + print(f"\nDONE. Raw data: {RAW/'raw.json'}") + + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/scripts/test_idempotency_failover.py b/scripts/test_idempotency_failover.py new file mode 100644 index 00000000..cf1ec7e3 --- /dev/null +++ b/scripts/test_idempotency_failover.py @@ -0,0 +1,66 @@ +import requests +import uuid +import base64 +from concurrent.futures import ThreadPoolExecutor, as_completed + +BASE_URL = "http://localhost:8080" + +def setup_test_data(): + username = f"idem_test_{uuid.uuid4().hex[:8]}" + password = "SecurePassword123!" + + r = requests.post(f"{BASE_URL}/api/v1/users", json={ + "username": username, "display_name": "Test User", "password": password + }) + r.raise_for_status() + + creds = base64.b64encode(f"{username}:{password}".encode()).decode() + r = requests.post(f"{BASE_URL}/api/v1/auth/sessions", headers={"Authorization": f"Basic {creds}"}) + r.raise_for_status() + token = r.json()["token"] + headers = {"Authorization": f"Bearer {token}"} + + r = requests.post(f"{BASE_URL}/api/v1/chats", headers=headers, json={ + "title": "Idempotency Test Chat", + "member_ids": [r.json()["user"]["id"]] + }) + r.raise_for_status() + chat_id = r.json()["id"] + + return headers, chat_id + +def send_message(headers, chat_id, idempotency_key, worker_id): + r = requests.post( + f"{BASE_URL}/api/v1/chats/{chat_id}/messages", + headers={**headers, "Idempotency-Key": idempotency_key}, + json={"text": f"failover test message"} + ) + return r.status_code, r.json().get("id") if r.status_code == 201 else None, r.text + +def main(): + print("Проверка идемпотентности (параллельные запросы с одним ключом)") + headers, chat_id = setup_test_data() + idempotency_key = f"failover-test-key-{uuid.uuid4().hex}" + + print(f"Отправка 5 параллельных запросов с ключом: {idempotency_key}") + + results = [] + with ThreadPoolExecutor(max_workers=5) as executor: + futures = [executor.submit(send_message, headers, chat_id, idempotency_key, i) for i in range(5)] + for future in as_completed(futures): + results.append(future.result()) + + status_codes = [r[0] for r in results] + message_ids = [r[1] for r in results] + + print(f"Полученные статусы: {status_codes}") + print(f"Полученные ID сообщений: {message_ids}") + + if all(code == 201 for code in status_codes) and len(set(message_ids)) == 1: + print(f"PASS: Идемпотентность работает! Создано ровно 1 сообщение (ID: {message_ids[0]}).") + else: + print("FAIL: Ожидалось 5 ответов '201' с одинаковым 'id'.") + print("Детали ответов:", results) + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/src/__init__.py b/src/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/src/api/dependencies.py b/src/api/dependencies.py new file mode 100644 index 00000000..c0d1b7e2 --- /dev/null +++ b/src/api/dependencies.py @@ -0,0 +1,88 @@ +from fastapi import Request, HTTPException, Depends, status +from typing import Annotated +from src.api.repositories.main_repo import Repository +from src.models.users import User +from src.auth.tokens import hash_token +from sqlalchemy.ext.asyncio import AsyncSession +import asyncio +from src.redis_client import get_redis +from src.database import get_db +from src.services.session_cache import invalidate_session, get_cached_user_id, cache_session + + +type DbSession = Annotated[AsyncSession, Depends(get_db)] ##Dependency Injection + +_session_refresh_locks: dict[str, asyncio.Lock] = {} + + +async def get_current_user(request: Request, session: DbSession) -> User: + repo = Repository(session) + + auth_header = request.headers.get("Authorization") + if not auth_header or not auth_header.startswith("Bearer "): + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="missing or invalid Bearer token", + headers={"WWW-Authenticate": 'Bearer realm="messenger"'}, + ) + + raw_token = auth_header[7:] + token_hash = hash_token(raw_token) + + redis_is_alive = get_redis() is not None + + if redis_is_alive: + + cached_user_id = await get_cached_user_id(token_hash) + if cached_user_id is not None: + user = await repo.users.get_by_id(cached_user_id) + if user: + return user + await invalidate_session(token_hash) + + lock = _session_refresh_locks.setdefault(token_hash, asyncio.Lock()) + + async with lock: + cached_user_id = await get_cached_user_id(token_hash) + if cached_user_id is not None: + user = await repo.users.get_by_id(cached_user_id) + if user: + return user + + + current_session = await repo.sessions.get_by_token_hash(token_hash) + if not current_session: + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="invalid or expired token", + headers={"WWW-Authenticate": 'Bearer realm="messenger"'}) + + user = await repo.users.get_by_id(current_session.user_id) + if not user: + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="user not found", + headers={"WWW-Authenticate": 'Bearer realm="messenger"'}) + + await cache_session(token_hash, user.id) + return user + + else: + current_session = await repo.sessions.get_by_token_hash(token_hash) + if not current_session: + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="invalid or expired token", + headers={"WWW-Authenticate": 'Bearer realm="messenger"'}) + + user = await repo.users.get_by_id(current_session.user_id) + if not user: + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="user not found", + headers={"WWW-Authenticate": 'Bearer realm="messenger"'}) + + return user + + +type CurrentUser = Annotated[User, Depends(get_current_user)] \ No newline at end of file diff --git a/src/api/repositories/chat_repo.py b/src/api/repositories/chat_repo.py new file mode 100644 index 00000000..c95ac674 --- /dev/null +++ b/src/api/repositories/chat_repo.py @@ -0,0 +1,96 @@ +import uuid +from datetime import datetime +from typing import Optional, List, Tuple + +from sqlalchemy import select, delete +from sqlalchemy.ext.asyncio import AsyncSession +from sqlalchemy.orm import selectinload + +from src.models.chats import Chat, ChatMember +from src.api.repositories.core import DatabaseManager + + +class ChatRepo(DatabaseManager): + def __init__(self, session: AsyncSession): + super().__init__(session, Chat) + + + async def create_with_members(self, title: str, member_ids: List[uuid.UUID]) -> Optional[Chat]: + try: + chat = Chat(title=title) + self.session.add(chat) + await self.session.flush() + + for user_id in member_ids: + member = ChatMember(chat_id=chat.id, user_id=user_id) + self.session.add(member) + + await self.session.commit() + + await self.session.refresh(chat) + + result = await self.session.execute(select(Chat).options(selectinload(Chat.members)).where(Chat.id == chat.id)) + return result.scalar_one() + + except Exception as e: + await self.session.rollback() + raise + + + async def get_by_id_with_members(self, chat_id: uuid.UUID) -> Optional[Chat]: + result = await self.session.execute(select(Chat).options(selectinload(Chat.members)).where(Chat.id == chat_id)) + return result.scalar_one_or_none() + + + async def get_user_chats(self, user_id: uuid.UUID) -> List[Chat]: + result = await self.session.execute(select(Chat).join(ChatMember, Chat.id == ChatMember.chat_id).options(selectinload(Chat.members)).where(ChatMember.user_id == user_id).order_by(Chat.created_at.asc(), Chat.id.asc())) + return list(result.scalars().all()) + + + async def is_user_member(self, chat_id: uuid.UUID, user_id: uuid.UUID) -> bool: + result = await self.session.execute(select(ChatMember).where(ChatMember.chat_id == chat_id, ChatMember.user_id == user_id,)) + return result.scalar_one_or_none() is not None + + + async def delete_by_id(self, chat_id: uuid.UUID) -> bool: + try: + chat = await self.get_by_id_with_members(chat_id) + if chat: + await self.session.delete(chat) + await self.session.commit() + return True + return False + except Exception as e: + await self.session.rollback() + raise + + + async def get_user_chats_paginated( + self, + user_id: uuid.UUID, + limit: int = 50, + cursor_created_at: Optional[datetime] = None, + cursor_chat_id: Optional[uuid.UUID] = None, + ) -> Tuple[List[Chat], bool]: + + query = (select(Chat).join(ChatMember, Chat.id == ChatMember.chat_id).options(selectinload(Chat.members)).where(ChatMember.user_id == user_id).order_by(Chat.created_at.asc(), Chat.id.asc())) + + if cursor_created_at is not None and cursor_chat_id is not None: + query = query.where( + (Chat.created_at > cursor_created_at) | + ( + (Chat.created_at == cursor_created_at) & + (Chat.id > cursor_chat_id) + ) + ) + + query = query.limit(limit + 1) + + result = await self.session.execute(query) + chats = list(result.scalars().all()) + + has_more = len(chats) > limit + if has_more: + chats = chats[:limit] + + return chats, has_more \ No newline at end of file diff --git a/src/api/repositories/core.py b/src/api/repositories/core.py new file mode 100644 index 00000000..c40a72a9 --- /dev/null +++ b/src/api/repositories/core.py @@ -0,0 +1,130 @@ +from sqlalchemy import select +from sqlalchemy.ext.asyncio import AsyncSession +from sqlalchemy.engine import Result +from typing import List, Optional, Any, Type, TypeVar +from sqlalchemy.exc import IntegrityError +import logging +import uuid + +logger = logging.getLogger(__name__) +ModelType = TypeVar("ModelType") + + +class DatabaseManager: + def __init__(self, session: AsyncSession, model: Type[ModelType]): + self.session = session + self.model = model + + async def execute_query(self, query) -> Result: + return await self.session.execute(query) + + async def get_all(self) -> List[ModelType]: + result = await self.session.execute(select(self.model)) + return result.scalars().all() + + async def get_by_id(self, record_id: uuid.UUID) -> Optional[ModelType]: + result = await self.session.execute(select(self.model).where(self.model.id == record_id)) + return result.scalar_one_or_none() + + async def create(self, **data) -> ModelType: + try: + instance = self.model(**data) + self.session.add(instance) + except Exception as e: + await self.session.rollback() + logger.error(f"Error creating record in {self.model.__name__}: {e}") + raise + + try: + await self.session.commit() + await self.session.refresh(instance) + return instance + except IntegrityError: + await self.session.rollback() + logger.error(f"Error: field value already exist") + raise + + async def bulk_create(self, data_list: List[dict]) -> List[ModelType]: + try: + instances = [self.model(**data) for data in data_list] + self.session.add_all(instances) + await self.session.commit() + + for instance in instances: + await self.session.refresh(instance) + + return instances + except Exception as e: + await self.session.rollback() + logger.error(f"Error bulk creating records in {self.model.__name__}: {e}") + raise + + async def update_by_id(self, record_id: uuid.UUID, **data) -> Optional[ModelType]: + try: + instance = await self.get_by_id(self.model, record_id) + if instance: + for key, value in data.items(): + setattr(instance, key, value) + await self.session.commit() + await self.session.refresh(instance) + return instance + except Exception as e: + await self.session.rollback() + logger.error(f"Error updating record in {self.model.__name__}: {e}") + raise + + async def delete_by_id(self, record_id: uuid.UUID) -> bool: + try: + instance = await self.get_by_id(self.model, record_id) + if instance: + await self.session.delete(instance) + await self.session.commit() + return True + return False + except Exception as e: + await self.session.rollback() + logger.error(f"Error deleting record in {self.model.__name__}: {e}") + raise + + async def get_by_field(self, field_name: str, value: Any) -> Optional[ModelType]: + result = await self.session.execute(select(self.model).where(getattr(self.model, field_name) == value)) + return result.scalar_one_or_none() + + async def delete_by_field(self, field_name: str, value: Any) -> bool: + try: + instance = await self.get_by_field(field_name, value) + if instance: + await self.session.delete(instance) + await self.session.commit() + return True + return False + except Exception as e: + await self.session.rollback() + logger.error(f"Error deleting record in {self.model.__name__}: {e}") + raise + + async def update_by_field(self, field_name: str, value: Any, **data) -> Optional[ModelType]: + try: + instance = await self.get_by_field(field_name, value) + if instance: + for key, value in data.items(): + setattr(instance, key, value) + await self.session.commit() + await self.session.refresh(instance) + return instance + except Exception as e: + self.session.rollback() + logger.error(f"Error in updating record in {self.model.__name__}: {e}") + raise + + async def get_many_by_field(self, field_name: str, value: Any) -> List[ModelType]: + result = await self.session.execute(select(self.model).where(getattr(self.model, field_name) == value)) + return result.scalars().all() + + async def exists(self, record_id: int) -> bool: + instance = await self.get_by_id(self.model, record_id) + return instance is not None + + async def count(self) -> int: + result = await self.session.execute(select(self.model)) + return len(result.scalars().all()) diff --git a/src/api/repositories/main_repo.py b/src/api/repositories/main_repo.py new file mode 100644 index 00000000..66386369 --- /dev/null +++ b/src/api/repositories/main_repo.py @@ -0,0 +1,13 @@ +from src.api.repositories.user_repo import UserRepo +from src.api.repositories.session_repo import SessionRepo +from src.api.repositories.chat_repo import ChatRepo +from src.api.repositories.message_repo import MessageRepo +from sqlalchemy.ext.asyncio import AsyncSession + + +class Repository(): + def __init__(self, session: AsyncSession): + self.users = UserRepo(session) + self.sessions = SessionRepo(session) + self.chats = ChatRepo(session) + self.messages = MessageRepo(session) diff --git a/src/api/repositories/message_repo.py b/src/api/repositories/message_repo.py new file mode 100644 index 00000000..9333674e --- /dev/null +++ b/src/api/repositories/message_repo.py @@ -0,0 +1,37 @@ +import uuid +from datetime import datetime +from typing import Optional, List, Tuple + +from sqlalchemy import select +from sqlalchemy.ext.asyncio import AsyncSession + +from src.models.messages import Message +from src.api.repositories.core import DatabaseManager + + +class MessageRepo(DatabaseManager): + def __init__(self, session: AsyncSession): + super().__init__(session, Message) + + async def create(self, chat_id: uuid.UUID, sender_id: uuid.UUID, text: str) -> Message: + return await super().create(chat_id=chat_id, sender_id=sender_id, text=text) + + async def get_chat_messages(self, chat_id: uuid.UUID, limit: int = 50, cursor_created_at: Optional[datetime] = None, cursor_msg_id: Optional[uuid.UUID] = None) -> Tuple[List[Message], bool]: + query = (select(Message).where(Message.chat_id == chat_id).order_by(Message.created_at.asc(), Message.id.asc()) + ) + + if cursor_created_at is not None and cursor_msg_id is not None: + query = query.where((Message.created_at > cursor_created_at) | + ((Message.created_at == cursor_created_at) & (Message.id > cursor_msg_id)) + ) + + query = query.limit(limit + 1) + + result = await self.session.execute(query) + messages = list(result.scalars().all()) + + has_more = len(messages) > limit + if has_more: + messages = messages[:limit] + + return messages, has_more \ No newline at end of file diff --git a/src/api/repositories/session_repo.py b/src/api/repositories/session_repo.py new file mode 100644 index 00000000..58793c9c --- /dev/null +++ b/src/api/repositories/session_repo.py @@ -0,0 +1,32 @@ +from sqlalchemy.ext.asyncio import AsyncSession +import uuid +from datetime import datetime +from typing import Optional +from src.models.sessions import Session +from src.api.repositories.core import DatabaseManager +from src.models.sessions import Session + + +class SessionRepo(DatabaseManager): + def __init__(self, session: AsyncSession): + super().__init__(session, Session) + + async def create(self, token_hash: str, user_id: uuid.UUID, expires_at: datetime) -> Optional[Session]: + result = await super().create(token_hash=token_hash, user_id=user_id, expires_at=expires_at) + return result + + async def get_by_token_hash(self, token_hash: str) -> Optional[Session]: + result = await super().get_by_field("token_hash", token_hash) + return result + + async def get_by_user_id(self, user_id: uuid.UUID) -> Optional[Session]: + result = await super().get_by_field("user_id", user_id) + return result + + async def delete_by_user_id(self, user_id: uuid.UUID) -> bool: + result = await super().delete_by_field("user_id", user_id) + return result + + async def delete_by_token_hash(self, token_hash: str) -> bool: + result = await super().delete_by_field("token_hash", token_hash) + return result \ No newline at end of file diff --git a/src/api/repositories/user_repo.py b/src/api/repositories/user_repo.py new file mode 100644 index 00000000..6454672c --- /dev/null +++ b/src/api/repositories/user_repo.py @@ -0,0 +1,29 @@ +import uuid +from typing import Optional +from sqlalchemy.ext.asyncio import AsyncSession +from sqlalchemy.exc import IntegrityError +from src.models.users import User +from src.api.repositories.core import DatabaseManager +from src.utils import generate_id + + +class UserRepo(DatabaseManager): + def __init__(self, session: AsyncSession): + super().__init__(session, User) + + async def get_by_username(self, username: str) -> Optional[User]: + result = await super().get_by_field("username", username.lower()) + return result + + async def get_by_id(self, user_id: uuid.UUID) -> Optional[User]: + result = await super().get_by_id(user_id) + return result + + async def create(self, username: str, display_name: str, password_hash: str) -> Optional[User]: + try: + result = await super().create(id=generate_id(), username=username.lower(), display_name=display_name, password_hash=password_hash) + return result + + except IntegrityError: + return None + \ No newline at end of file diff --git a/src/api/routes/auth/auth.py b/src/api/routes/auth/auth.py new file mode 100644 index 00000000..9af5d4e7 --- /dev/null +++ b/src/api/routes/auth/auth.py @@ -0,0 +1,104 @@ +import base64 +from fastapi import APIRouter, HTTPException, Request, Response, status +from src.api.dependencies import DbSession, CurrentUser +from src.pydantic_valid.session import SessionUser, SessionCreateResponse +from src.api.repositories.main_repo import Repository +from src.auth.password import verify_password +from src.auth.tokens import generate_token, hash_token, calculate_expires_at +from src.config import settings +from src.services.session_cache import cache_session, invalidate_session + +router = APIRouter(prefix="/v1/auth") + + +@router.post("/sessions", response_model=SessionCreateResponse, status_code=status.HTTP_201_CREATED) +async def create_session(request: Request, session: DbSession): + repo = Repository(session) + + auth_header = request.headers.get("Authorization") + if not auth_header or not auth_header.startswith("Basic "): + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="missing or invalid Basic auth header", + headers={"WWW-Authenticate": 'Basic realm="messenger", charset="UTF-8"'}, + ) + try: + encoded_credentials = auth_header[6:] + decoded = base64.b64decode(encoded_credentials).decode("utf-8") + username, password = decoded.split(":", 1) + except Exception: + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="invalid credentials format", + headers={"WWW-Authenticate": 'Basic realm="messenger", charset="UTF-8"'}, + ) + + user = await repo.users.get_by_username(username) + if not user: + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="invalid username or password", + headers={"WWW-Authenticate": 'Basic realm="messenger", charset="UTF-8"'}, + ) + + if not verify_password(password, user.password_hash): + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="invalid username or password", + headers={"WWW-Authenticate": 'Basic realm="messenger", charset="UTF-8"'}, + ) + + raw_token, token_hash = generate_token() + expires_at = calculate_expires_at(settings.SESSION_TTL_SECONDS) + + await repo.sessions.create(token_hash=token_hash, user_id=user.id, expires_at=expires_at) + await cache_session(token_hash, user.id) + + return SessionCreateResponse( + token=raw_token, + expires_at=expires_at.strftime("%Y-%m-%dT%H:%M:%S.%f") + "Z", + user=SessionUser( + id=str(user.id), + username=user.username, + display_name=user.display_name, + created_at=user.created_at.strftime("%Y-%m-%dT%H:%M:%S.%f") + "Z", + ), + ) + + +@router.delete("/sessions/current", status_code=status.HTTP_204_NO_CONTENT) +async def delete_current_session(request: Request, session: DbSession, current_user: CurrentUser): + repo = Repository(session) + + auth_header = request.headers.get("Authorization") + if not auth_header or not auth_header.startswith("Bearer "): + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="invalid or missing Bearer token", + headers={"WWW-Authenticate": 'Bearer realm="messenger"'}) + + raw_token = auth_header[7:] + token_hash = hash_token(raw_token) + + user_session = await repo.sessions.get_by_token_hash(token_hash) + if not user_session: + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="invalid token", + headers={"WWW-Authenticate": 'Bearer realm="messenger"'}) + + if user_session.user_id != current_user.id: + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="token in request doesn't align with current_user", + headers={"WWW-Authenticate": 'Bearer realm="messenger"'}) + + await invalidate_session(token_hash) + deleted = await repo.sessions.delete_by_token_hash(token_hash) + if not deleted: + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="invalid or expired token", + headers={"WWW-Authenticate": 'Bearer realm="messenger"'}) + + return Response(status_code=status.HTTP_204_NO_CONTENT) \ No newline at end of file diff --git a/src/api/routes/chats/chat.py b/src/api/routes/chats/chat.py new file mode 100644 index 00000000..87fe4049 --- /dev/null +++ b/src/api/routes/chats/chat.py @@ -0,0 +1,113 @@ +from fastapi import HTTPException, APIRouter, Query +from typing import Optional +from uuid import UUID +from datetime import datetime +from src.pydantic_valid.chat import CreateChat, Chat +from src.pydantic_valid.page_response import PageResponse +from src.api.dependencies import CurrentUser, DbSession +from src.api.repositories.main_repo import Repository +from src.utils import generate_id, get_now_iso +import base64 + + +router = APIRouter() + + +def _encode_chat_cursor(created_at: str, chat_id: str) -> str: + raw = f"c|{created_at}|{chat_id}" + return base64.urlsafe_b64encode(raw.encode("utf-8")).decode("ascii").rstrip("=") + + +def _decode_chat_cursor(cursor: str) -> tuple[str, str]: + try: + padded = cursor + "=" * (-len(cursor) % 4) + raw = base64.urlsafe_b64decode(padded).decode("utf-8") + parts = raw.split("|", 2) + if len(parts) != 3 or parts[0] != "c": + raise ValueError("bad cursor structure") + created_at, chat_id = parts[1], parts[2] + except Exception as e: + raise HTTPException(status_code=400, detail="invalid cursor") from e + + return created_at, chat_id + + +@router.post("/v1/chats", response_model=Chat, status_code=201) +async def create_chat(session: DbSession, current_user: CurrentUser, chat_in: CreateChat) -> Chat: + repo = Repository(session) + + if str(current_user.id) not in chat_in.member_ids: + raise HTTPException(status_code=400, detail="Creator of chat should be in chat member list") + + member_uuids = [UUID(mid) for mid in chat_in.member_ids] + + for member_id in member_uuids: + user = await repo.users.get_by_id(member_id) + if not user: + raise HTTPException(status_code=400, detail="Unexisting user_id in chat member list") + + chat = await repo.chats.create_with_members(title=chat_in.title, member_ids=member_uuids) + + return Chat( + id=str(chat.id), + title=chat.title, + member_ids=[str(m.user_id) for m in chat.members], + created_at = chat.created_at.strftime("%Y-%m-%dT%H:%M:%S.%f") + "Z" + ) + + +@router.get("/v1/chats", response_model=PageResponse) +async def list_chats(current_user: CurrentUser, session: DbSession, limit: int = Query(default=50, ge=1, le=100), cursor: Optional[str] = Query(default=None, min_length=1)) -> PageResponse: + repo = Repository(session) + + cursor_created_at = None + cursor_chat_id = None + if cursor: + created_at_str, chat_id_str = _decode_chat_cursor(cursor) + cursor_created_at = datetime.fromisoformat(created_at_str) + cursor_chat_id = UUID(chat_id_str) + + chats, has_more = await repo.chats.get_user_chats_paginated( + user_id=current_user.id, + limit=limit, + cursor_created_at=cursor_created_at, + cursor_chat_id=cursor_chat_id, + ) + + next_cursor = None + if has_more and chats: + last = chats[-1] + next_cursor = _encode_chat_cursor( + created_at=last.created_at.fromisoformat(), + chat_id=str(last.id), + ) + + return PageResponse(items=[Chat( + id=str(c.id), + title=c.title, + member_ids=[str(m.user_id) for m in c.members], + created_at=c.created_at.strftime("%Y-%m-%dT%H:%M:%S.%f") + "Z") + for c in chats], + next_cursor=next_cursor, + ) + + + +@router.get("/v1/chats/{chat_id}", response_model=Chat) +async def get_chat(current_user: CurrentUser, session: DbSession, chat_id: UUID) -> Chat: + repo = Repository(session) + + chat = await repo.chats.get_by_id_with_members(chat_id) + if not chat: + raise HTTPException(status_code=404, detail="Chat not found") + + member_ids = {str(m.user_id) for m in chat.members} + if str(current_user.id) not in member_ids: + raise HTTPException(status_code=404, detail="Chat not found") + + return Chat( + id=str(chat.id), + title=chat.title, + member_ids=[str(m.user_id) for m in chat.members], + created_at=chat.created_at.strftime("%Y-%m-%dT%H:%M:%S.%f") + "Z", + ) diff --git a/src/api/routes/health/health.py b/src/api/routes/health/health.py new file mode 100644 index 00000000..f41b5b9d --- /dev/null +++ b/src/api/routes/health/health.py @@ -0,0 +1,15 @@ +from fastapi import APIRouter +from src.pydantic_valid.errors import Health + + +router = APIRouter() + + +@router.get("/live", response_model=Health, status_code=200) +async def healh_live(): + return {"status": "ok"} + + +@router.get("/ready", response_model=Health, status_code=200) +async def health_ready(): + return {"status": "ok"} \ No newline at end of file diff --git a/src/api/routes/messages/message.py b/src/api/routes/messages/message.py new file mode 100644 index 00000000..f81a585b --- /dev/null +++ b/src/api/routes/messages/message.py @@ -0,0 +1,129 @@ +import base64 +from fastapi import HTTPException, APIRouter, Query, status, Request +from typing import Optional +from uuid import UUID +from src.pydantic_valid.message import Message, CreateMessage +from src.pydantic_valid.page_response import PageResponse +from src.api.dependencies import DbSession, CurrentUser +from src.api.repositories.main_repo import Repository +from src.services.idempotency import check_idempotency, body_hash, save_idempotency +from src.utils import generate_id, get_now_iso +from datetime import datetime +from src.services.idempotency import release_idempotency + +router = APIRouter() + + +def _encode_msg_cursor(chat_id: str, created_at: str, msg_id: str) -> str: + raw = f"m|{chat_id}|{created_at}|{msg_id}" + return base64.urlsafe_b64encode(raw.encode("utf-8")).decode("ascii").rstrip("=") + + +def _decode_msg_cursor(scope_chat_id: str, cursor: str) -> tuple[str, str]: + try: + padded = cursor + "=" * (-len(cursor) % 4) + raw = base64.urlsafe_b64decode(padded).decode("utf-8") + parts = raw.split("|", 3) + if len(parts) != 4 or parts[0] != "m": + raise ValueError("bad cursor structure") + chat_id, created_at, msg_id = parts[1], parts[2], parts[3] + except Exception as e: + raise HTTPException(status_code=400, detail="invalid cursor") from e + + if scope_chat_id != chat_id: + raise HTTPException(status_code=400, detail="cursor from another chat") + + return created_at, msg_id + + +@router.post("/v1/chats/{chat_id}/messages", response_model=Message, status_code=201) +async def send_message(chat_id: UUID, msg_in: CreateMessage, session: DbSession, current_user: CurrentUser, request: Request): + repo = Repository(session) + + idempotency_key = request.headers.get("Idempotency-Key") + if not idempotency_key: + raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Idempotency-Key is required") + + chat = await repo.chats.get_by_id_with_members(chat_id) + if not chat: + raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="chat not found") + + if not await repo.chats.is_user_member(chat_id, current_user.id): + raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, + detail="chat not found") + + current_hash = body_hash(msg_in.model_dump()) + + is_cached, cached_response = await check_idempotency( + str(current_user.id), + str(chat_id), + idempotency_key, + current_hash + ) + + if is_cached: + return cached_response + + try: + message = await repo.messages.create(chat_id=chat_id, + sender_id=current_user.id, + text=msg_in.text) + + response_data = Message( + id=str(message.id), + chat_id=str(message.chat_id), + sender_id=str(message.sender_id), + text=message.text, + created_at=message.created_at.strftime("%Y-%m-%dT%H:%M:%S.%f") + "Z" + ) + + response_dict = response_data.model_dump() + + except Exception: + await release_idempotency(str(current_user.id), str(chat_id), idempotency_key) + raise + + await save_idempotency( + str(current_user.id), + str(chat_id), + idempotency_key, + current_hash, + response_dict + ) + + return response_dict + + +@router.get("/v1/chats/{chat_id}/messages", response_model=PageResponse, status_code=200) +async def list_messages(session: DbSession, current_user: CurrentUser, chat_id: UUID, limit: int = Query(default=50, ge=1, le=100), cursor: Optional[str] = Query(default=None, min_length=1)): + repo = Repository(session) + + chat = await repo.chats.get_by_id_with_members(chat_id) + if not chat: + raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, + detail="chat not found") + + member_ids = {str(m.user_id) for m in chat.members} + + if str(current_user.id) not in member_ids: + raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, + detail="chat not found") + cursor_created_at = None + cursor_msg_id = None + if cursor: + created_at_str, msg_id_str = _decode_msg_cursor(str(chat_id), cursor) + cursor_created_at = datetime.fromisoformat(created_at_str) + cursor_msg_id = UUID(msg_id_str) + + messages, has_more = await repo.messages.get_chat_messages(chat_id=chat_id, limit=limit, cursor_created_at=cursor_created_at, cursor_msg_id=cursor_msg_id) + + next_cursor = None + if has_more and messages: + last = messages[-1] + next_cursor = _encode_msg_cursor(chat_id=str(chat_id), created_at=last.created_at.isoformat(), msg_id=str(last.id)) + + return PageResponse( + items=[Message(id=str(msg.id), chat_id=str(msg.chat_id), sender_id=str(msg.sender_id), text=msg.text, created_at=msg.created_at.strftime("%Y-%m-%dT%H:%M:%S.%f") + "Z") + for msg in messages], + next_cursor=next_cursor, + ) diff --git a/src/api/routes/users/user.py b/src/api/routes/users/user.py new file mode 100644 index 00000000..5c424553 --- /dev/null +++ b/src/api/routes/users/user.py @@ -0,0 +1,47 @@ +from fastapi import APIRouter, HTTPException, status +from src.pydantic_valid.user import CreateUser, User as UserSchema +from src.models.users import User +from src.api.repositories.main_repo import Repository +from src.auth.password import hash_password +from src.api.dependencies import DbSession, CurrentUser +from src.utils import get_now_iso + + +router = APIRouter(prefix="/v1") + + +@router.post("/users", response_model=UserSchema, status_code=201) +async def register_user(body: CreateUser, session: DbSession) -> UserSchema: + repo = Repository(session) + existing_user = await repo.users.get_by_username(body.username) + if existing_user: + raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail="username already exists") + + password_hash = hash_password(body.password) + + new_user = await repo.users.create( + username = body.username, + display_name = body.display_name, + password_hash = password_hash, + ) + + if not new_user: + raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail="username already exists") + + return UserSchema( + id=str(new_user.id), + username=new_user.username, + display_name=new_user.display_name, + created_at=new_user.created_at.strftime("%Y-%m-%dT%H:%M:%S.%f") + "Z", + ) + + +@router.get("/users/me", response_model=UserSchema, status_code=200) +async def get_me(current_user: CurrentUser) -> UserSchema: + + return UserSchema( + id=str(current_user.id), + username=current_user.username, + display_name=current_user.display_name, + created_at=current_user.created_at.strftime("%Y-%m-%dT%H:%M:%S.%f") + "Z", + ) diff --git a/src/auth/password.py b/src/auth/password.py new file mode 100644 index 00000000..9c99b5eb --- /dev/null +++ b/src/auth/password.py @@ -0,0 +1,18 @@ +from argon2 import PasswordHasher +from argon2.exceptions import VerifyMismatchError + + +ph = PasswordHasher() + + +def hash_password(password: str) -> str: + return ph.hash(password) + + +def verify_password(password: str, _hash: str) -> bool: + try: + ph.verify(_hash, password) + return True + except VerifyMismatchError: + return False + \ No newline at end of file diff --git a/src/auth/tokens.py b/src/auth/tokens.py new file mode 100644 index 00000000..2843b239 --- /dev/null +++ b/src/auth/tokens.py @@ -0,0 +1,17 @@ +import secrets +import hashlib +from datetime import datetime, timezone, timedelta + + +def generate_token() -> tuple[str, str]: + raw_token = secrets.token_urlsafe(32) + token_hash = hashlib.sha256(raw_token.encode()).hexdigest() + return raw_token, token_hash + + +def hash_token(raw_token: str) -> str: + return hashlib.sha256(raw_token.encode()).hexdigest() + + +def calculate_expires_at(ttl_seconds: int) -> datetime: + return datetime.now(timezone.utc) + timedelta(seconds=ttl_seconds) diff --git a/src/config.py b/src/config.py new file mode 100644 index 00000000..9ef93c74 --- /dev/null +++ b/src/config.py @@ -0,0 +1,25 @@ +import os +from pydantic import Field +from pydantic_settings import BaseSettings, SettingsConfigDict + + +class Settings(BaseSettings): + APP_NAME: str = "MTUSI Messenger" + APP_DEBUG: bool = False + + DATABASE_URL: str = Field(..., description="Строка подключения к PostgreSQL. docker_compose перезапишет поле через .env") + SESSION_TTL_SECONDS: int = 3600 + + DB_POOL_SIZE: int = 10 + DB_MAX_OVERFLOW: int = 20 + + DB_POOL_TIMEOUT: int = 30.0 + DB_POOL_RECYCLE: int = 3600 + + RETRY_AFTER_POOL: int = 1 + RETRY_AFTER_DB: int = 5 + + model_config = SettingsConfigDict(env_file=".env", case_sensitive=False, extra="ignore") + + +settings = Settings() \ No newline at end of file diff --git a/src/database.py b/src/database.py new file mode 100644 index 00000000..4aee91ae --- /dev/null +++ b/src/database.py @@ -0,0 +1,44 @@ +from sqlalchemy.orm import DeclarativeBase +from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession, async_sessionmaker +from src.config import settings + + +class Base(DeclarativeBase): + pass + + +engine = create_async_engine( + settings.DATABASE_URL, + echo=settings.APP_DEBUG, + pool_size=settings.DB_POOL_SIZE, + max_overflow=settings.DB_MAX_OVERFLOW, + pool_timeout=settings.DB_POOL_TIMEOUT, + pool_recycle=settings.DB_POOL_RECYCLE, + pool_pre_ping=True, +) + +print( + f"[db] pool_size={settings.DB_POOL_SIZE} " + f"max_overflow={settings.DB_MAX_OVERFLOW} " + f"max_total_per_replica={settings.DB_POOL_SIZE + settings.DB_MAX_OVERFLOW} " + f"pool_timeout={settings.DB_POOL_TIMEOUT}s " + f"pool_recycle={settings.DB_POOL_RECYCLE}s", + flush=True, +) + +AsyncSessionLocal = async_sessionmaker( + engine, + class_=AsyncSession, expire_on_commit=False, autoflush=False +) + + +async def get_db(): + async with AsyncSessionLocal() as session: + try: + yield session + finally: + await session.close() + + +async def close_engine() -> None: + await engine.dispose() diff --git a/src/lifespan.py b/src/lifespan.py new file mode 100644 index 00000000..66f8f7bb --- /dev/null +++ b/src/lifespan.py @@ -0,0 +1,25 @@ +from contextlib import asynccontextmanager +from fastapi import FastAPI +from sqlalchemy import text + +from src.database import engine, close_engine +from src.migrations.runner import run_migrations +from src.redis_client import init_redis, close_redis + +@asynccontextmanager +async def lifespan(app: FastAPI): + + print("[lifespan] startup: initializing Redis cache...") + await init_redis() + + print("lifespan startup: initializing database engine...") + async with engine.connect() as conn: + await conn.execute(text("SELECT 1")) + print("lifespan startup: database ready") + + yield + + print("lifespan shutdown") + await close_redis() + await close_engine() + print("lifespan shutdown: complete") \ No newline at end of file diff --git a/src/main.py b/src/main.py new file mode 100644 index 00000000..40928cc0 --- /dev/null +++ b/src/main.py @@ -0,0 +1,137 @@ +from fastapi import FastAPI, Request, HTTPException +from fastapi.exceptions import RequestValidationError +from fastapi.responses import JSONResponse +import os +import uuid +from src.utils import generate_id, create_error_response +from src.api.routes.health import health +from src.api.routes.users import user +from src.api.routes.chats import chat +from src.api.routes.messages import message +from src.api.routes.auth import auth +from src.lifespan import lifespan +from sqlalchemy.exc import OperationalError as SAOperationalError +from sqlalchemy.exc import TimeoutError as SATimeoutError +from redis.exceptions import RedisError +from src.config import settings + + +INSTANCE_ID = os.getenv("INSTANCE_ID") or f"api-{uuid.uuid4().hex[:8]}" + +application = FastAPI(title="MTUSI Messenger", version="1.0.0", lifespan=lifespan) + + +@application.middleware("http") +async def add_global_headers(request: Request, call_next): + request_id = str(generate_id()) + request.state.request_id = request_id + response = await call_next(request) + response.headers["X-Request-Id"] = request_id + response.headers["X-Instance-Id"] = INSTANCE_ID + + return response + +@application.exception_handler(RequestValidationError) +async def validation_exception_handler(request: Request, exc: RequestValidationError): + messages = [] + for err in exc.errors(): + loc = '.'.join(str(p) for p in err["loc"] if p not in ('body',)) + msg = err.get("msg", "invalid") + if msg.startswith("Value error, "): + msg = msg[len("Value error, "):] + messages.append(f"{loc}: {msg}" if loc else msg) + detail = "; ".join(messages) or "invalid request" + request_id = getattr(request.state, "request_id", "") + return JSONResponse( + status_code=400, + content={"error": { + "code": "invalid_request", + "message": detail, + "request_id": request_id + } + }, + headers={"X-Request-Id": request_id, "X-Instance-Id": INSTANCE_ID}, + ) + + +@application.exception_handler(SATimeoutError) +async def pool_exhausted_handler(request: Request, exc: SATimeoutError): + request_id = getattr(request.state, "request_id", None) or str(generate_id()) + return create_error_response( + message="service temporarily overloaded, retry later", + code="unavailable", + status_code=503, + request_id=request_id, + instance_id=INSTANCE_ID, + extra_headers={"Retry-After": str(settings.RETRY_AFTER_POOL)}, + ) + + +@application.exception_handler(SAOperationalError) +async def db_unavailable_handler(request: Request, exc: SAOperationalError): + request_id = getattr(request.state, "request_id", str(generate_id())) + return JSONResponse( + status_code=503, + content={ + "error": { + "code": "unavailable", + "message": "database unavailable", + "request_id": request_id, + } + }, + headers={"X-Request-Id": request_id, "X-Instance": INSTANCE_ID}, + ) + +@application.exception_handler(HTTPException) +async def http_exception_handler(request: Request, exc: HTTPException): + request_id = getattr(request.state, "request_id", None) + if request_id is None: + request_id = str(generate_id()) + + code_map = { + 400: "invalid_request", + 401: "unauthorized", + 404: "not_found", + 409: "conflict", + 413: "payload_too_large", + 415: "unsupported_media_type", + 429: "rate_limited", + 503: "unavailable" + } + + code = code_map.get(exc.status_code, "internal_error") + response_headers = {"X-Request-Id": request_id, "X-Instance-Id": INSTANCE_ID} + if exc.headers: + response_headers.update(exc.headers) + + return JSONResponse( + status_code=exc.status_code, + content={"error": { + "code": code, + "message": str(exc.detail), + "request_id": request_id} + }, + headers=response_headers) + +@application.exception_handler(Exception) +async def global_exception_handler(request: Request, exc: Exception): + request_id = getattr(request.state, "request_id", None) + if request_id is None: + request_id = str(generate_id()) + print(f'Internal Error: {exc}') + + print( + f"[error] request_id={request_id} " + f"type={type(exc).__module__}.{type(exc).__qualname__} " + f"msg={exc}", + flush=True, + ) + return create_error_response(message="Internal Server Error", code="internal_error", status_code=500, request_id=request_id, instance_id=INSTANCE_ID) + + + +application.include_router(health.router, prefix="/health", tags=["Health"]) +application.include_router(user.router, prefix="/api", tags=["Users"]) +application.include_router(chat.router, prefix="/api", tags=["Chats"]) +application.include_router(message.router, prefix="/api", tags=["Messages"]) +application.include_router(auth.router, prefix="/api", tags=["Auth"]) diff --git a/src/migrations/001_initial.sql b/src/migrations/001_initial.sql new file mode 100644 index 00000000..55686808 --- /dev/null +++ b/src/migrations/001_initial.sql @@ -0,0 +1,63 @@ +BEGIN; + +CREATE TABLE IF NOT EXISTS users ( + id UUID PRIMARY KEY, + username VARCHAR(32) NOT NULL, + display_name VARCHAR(100) NOT NULL, + password_hash TEXT NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + + CONSTRAINT users_username_unique UNIQUE (username), + CONSTRAINT users_username_pattern CHECK (username ~ '^[a-z0-9_]{3,32}$'), + CONSTRAINT users_display_name_length CHECK ( + char_length(display_name) BETWEEN 1 AND 100 + AND trim(display_name) <> '' + ) +); + +CREATE TABLE IF NOT EXISTS sessions ( + token_hash CHAR(64) PRIMARY KEY, + user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, + expires_at TIMESTAMPTZ NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT now() +); + +CREATE INDEX IF NOT EXISTS sessions_user_id_idx ON sessions(user_id); +CREATE INDEX IF NOT EXISTS sessions_expires_at_idx ON sessions(expires_at); + +CREATE TABLE IF NOT EXISTS chats ( + id UUID PRIMARY KEY, + title VARCHAR(100) NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + + CONSTRAINT chats_title_length CHECK ( + char_length(title) BETWEEN 1 AND 100 + AND trim(title) <> '' + ) +); + +CREATE TABLE IF NOT EXISTS chat_members ( + chat_id UUID NOT NULL REFERENCES chats(id) ON DELETE CASCADE, + user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, + PRIMARY KEY (chat_id, user_id) +); + +CREATE INDEX IF NOT EXISTS chat_members_user_id_idx ON chat_members(user_id); + +CREATE TABLE IF NOT EXISTS messages ( + id UUID PRIMARY KEY, + chat_id UUID NOT NULL REFERENCES chats(id) ON DELETE CASCADE, + sender_id UUID NOT NULL REFERENCES users(id) ON DELETE RESTRICT, + text TEXT NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + + CONSTRAINT messages_text_length CHECK ( + char_length(text) BETWEEN 1 AND 4000 + AND trim(text) <> '' + ) +); + +CREATE INDEX IF NOT EXISTS messages_chat_created_id_idx + ON messages(chat_id, created_at, id); + +COMMIT; \ No newline at end of file diff --git a/src/migrations/runner.py b/src/migrations/runner.py new file mode 100644 index 00000000..e9a84e3a --- /dev/null +++ b/src/migrations/runner.py @@ -0,0 +1,37 @@ +import asyncio +import os +from pathlib import Path +import asyncpg + + +MIGRATIONS_DIR = Path(__file__).parent + + +async def run_migrations() -> None: + dsn = os.environ.get("DATABASE_URL") + if not dsn: + raise RuntimeError("DATABASE_URL environment is not set") + + if dsn.startswith("postgresql+asyncpg://"): + dsn = dsn.replace("postgresql+asyncpg://", "postgresql://", 1) + + print(f"Connecting to DB") + conn = await asyncpg.connect(dsn) + try: + sql_files = sorted(MIGRATIONS_DIR.glob("*.sql")) + if not sql_files: + print("no SQl files") + return + for sql_file in sql_files: + print(f"migration applying {sql_file.name}") + sql = sql_file.read_text(encoding="utf-8") + await conn.execute(sql) + print(f"mighration applied succesful to {sql_file.name}") + print(f"All {len(sql_files)} migrations done") + + finally: + await conn.close() + + +if __name__ == "__main__": + asyncio.run(run_migrations()) diff --git a/src/models/__init__.py b/src/models/__init__.py new file mode 100644 index 00000000..e08ae2b8 --- /dev/null +++ b/src/models/__init__.py @@ -0,0 +1,70 @@ +# #in_memory +# from src.models.users import UsersRepository +# from src.models.chats import ChatsRepository +# from src.models.messages import MessagesRepository +# import asyncio +# import uuid +# from src.pydantic_valid.user import User +# from src.pydantic_valid.chat import Chat +# from src.pydantic_valid.message import Message + + +# class Repository(): +# def __init__(self): +# self.users = UsersRepository() +# self.chats = ChatsRepository() +# self.messages = MessagesRepository() +# self.username_index = UsernameIndexRepository() +# #self._lock = asyncio.Lock() #pessimistic locking против race condition +# self._user_lock = asyncio.Lock() +# self._chats_locks_guard = asyncio.Lock() +# self._chat_locks : dict[str, asyncio.Lock] = {} + + +# async def insert_user(self, user: User) -> bool: +# key = user.username.lower() +# async with self._user_lock: #избегания создания дубликатов данных юзера в self.users под разными индексами | в username_index 1 запись на все данные в то же время +# if key in self.username_index.username_index_db: +# return False +# self.username_index.username_index_db[key] = user.id +# self.users.users_db[user.id] = user +# return True + + +# async def get_user(self, uid: uuid.UUID) -> User: +# user_data = self.users.users_db.get(str(uid)) +# if user_data: +# return user_data #"id": str(uid), for User model response else UserOut model +# return None + + +# async def _get_chat_lock(self, chat_id: str) -> asyncio.Lock: +# async with self._chats_locks_guard: +# if chat_id not in self._chat_locks: +# self._chat_locks[chat_id] = asyncio.Lock() +# return self._chat_locks[chat_id] + + +# async def create_chat(self, chat_data: Chat) -> bool: +# chat_id = chat_data.id +# lock = await self._get_chat_lock(chat_id) +# async with lock: +# if chat_id in self.chats.chats_db: +# return False +# else: +# self.chats.chats_db[chat_id] = chat_data.model_dump() +# self.messages.message_db[chat_id] = [] +# return True + + +# async def create_message(self, message_data: Message) -> bool: +# chat_id = message_data.chat_id +# lock = await self._get_chat_lock(chat_id) +# async with lock: +# if chat_id in self.messages.message_db: +# # self.messages.message_db[chat_id].append(message_data.model_dump()) +# await self.messages.append_message(chat_id, message_data.model_dump()) +# return True +# else: +# return False + \ No newline at end of file diff --git a/src/models/chats.py b/src/models/chats.py new file mode 100644 index 00000000..6e4adefa --- /dev/null +++ b/src/models/chats.py @@ -0,0 +1,49 @@ +from sqlalchemy.orm import Mapped, mapped_column, relationship +from sqlalchemy.dialects.postgresql import UUID +from sqlalchemy import String, DateTime, ForeignKey +from sqlalchemy.sql import text as sqltext +import uuid +from datetime import datetime +from src.database import Base +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from src.models.users import User + + +class Chat(Base): + __tablename__ = "chats" + + id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), + primary_key=True, + default=uuid.uuid4) + title: Mapped[str] = mapped_column(String(100), nullable=False) + created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), + nullable=False, + server_default=sqltext("now()")) + members: Mapped[list["ChatMember"]] = relationship("ChatMember", + cascade="all, delete-orphan", + back_populates="chat") + + + def __repr__(self) -> str: + return f"" + + +class ChatMember(Base): + __tablename__ = "chat_members" + + chat_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), + ForeignKey("chats.id", ondelete="CASCADE"), + primary_key=True) + user_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), + ForeignKey("users.id", ondelete="CASCADE"), + primary_key=True) + + user: Mapped["User"] = relationship("User") + chat: Mapped["Chat"] = relationship("Chat", back_populates="members") + + + def __repr__(self) -> str: + return f"" + \ No newline at end of file diff --git a/src/models/messages.py b/src/models/messages.py new file mode 100644 index 00000000..7ab4a23e --- /dev/null +++ b/src/models/messages.py @@ -0,0 +1,45 @@ +import uuid +from datetime import datetime +from sqlalchemy import String, DateTime, ForeignKey, Text +from sqlalchemy.sql import text as sql_text +from sqlalchemy.dialects.postgresql import UUID +from sqlalchemy.orm import Mapped, mapped_column + +from src.database import Base + + +class Message(Base): + __tablename__ = "messages" + + id: Mapped[uuid.UUID] = mapped_column( + UUID(as_uuid=True), + primary_key=True, + default=uuid.uuid4 + ) + + chat_id: Mapped[uuid.UUID] = mapped_column( + UUID(as_uuid=True), + ForeignKey("chats.id", ondelete="CASCADE"), + nullable=False, + index=True + ) + + sender_id: Mapped[uuid.UUID] = mapped_column( + UUID(as_uuid=True), + ForeignKey("users.id", ondelete="RESTRICT"), + nullable=False + ) + + text: Mapped[str] = mapped_column( + Text, + nullable=False + ) + + created_at: Mapped[datetime] = mapped_column( + DateTime(timezone=True), + nullable=False, + server_default=sql_text("now()") + ) + + def __repr__(self) -> str: + return f"" \ No newline at end of file diff --git a/src/models/sessions.py b/src/models/sessions.py new file mode 100644 index 00000000..60316b87 --- /dev/null +++ b/src/models/sessions.py @@ -0,0 +1,31 @@ +import uuid +from datetime import datetime +from sqlalchemy.dialects.postgresql import UUID +from sqlalchemy.orm import Mapped, mapped_column, relationship +from sqlalchemy import String, DateTime, ForeignKey +from sqlalchemy.sql import text as sqltext +from src.database import Base + +class Session(Base): + __tablename__ = "sessions" + + token_hash: Mapped[str] = mapped_column(String(64), primary_key=True, comment="SHA-256 opaque token") + user_id: Mapped[uuid.UUID] = mapped_column( + UUID(as_uuid=True), + ForeignKey("users.id", ondelete="CASCADE",), + nullable=False, + index=True, + comment="Внешний ключ на идентификатор пользователя") + expires_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), + nullable=False, + index=True, + comment="время истечения сессии") + created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), + nullable=False, + server_default=sqltext("now()"), + comment="время создания сессии") + + + def __repr__(self) -> str: + return f"" + \ No newline at end of file diff --git a/src/models/users.py b/src/models/users.py new file mode 100644 index 00000000..7652222f --- /dev/null +++ b/src/models/users.py @@ -0,0 +1,21 @@ +from sqlalchemy import Column, String, DateTime, Text +from sqlalchemy.dialects.postgresql import UUID +from sqlalchemy.orm import Mapped, mapped_column +from sqlalchemy.sql import text as sqltext +import uuid +from datetime import datetime +from src.database import Base + + +class User(Base): + __tablename__ = "users" + + id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4, comment="Первичный ключ как uui4, вероятность коллизии стремится к 0. В будущем лучше переходить к uuid7-время+рандом") + username: Mapped[str] = mapped_column(String(32), unique=True, nullable=False, index=True, comment="Логин пользователя") + display_name: Mapped[str] = mapped_column(String(100), nullable=False) + password_hash: Mapped[str] = mapped_column(String, nullable=False, comment="Argon2id hash пароля") + created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=sqltext("now()"), nullable=False) + + + def __repr__(self) -> str: + return f"" \ No newline at end of file diff --git a/src/pydantic_valid/chat.py b/src/pydantic_valid/chat.py new file mode 100644 index 00000000..f3709174 --- /dev/null +++ b/src/pydantic_valid/chat.py @@ -0,0 +1,38 @@ +import uuid +from pydantic import BaseModel, Field, field_validator, ConfigDict + + +class CreateChat(BaseModel): + model_config = ConfigDict(extra="forbid") + title: str = Field(..., min_length=1, max_length=100) + member_ids: list[str] = Field(..., min_length=1, max_length=100) + + + @field_validator("title") + @classmethod + def title_validate(cls, v: str) -> str: + if not v.strip(): + raise ValueError("title shouldn't have only whitespaces and cannot be blank") + return v + + + @field_validator("member_ids") + @classmethod + def validate_member_ids(cls, v: list[str]) -> list[str]: + if len(v) != len(set(v)): + raise ValueError("Dublicates are prohibitated") + + for ids in v: + try: + uuid.UUID(ids) + except: + raise ValueError(f'invalid UUID format was detected for member_id: {ids}') + return v + + + +class Chat(BaseModel): + id: str + title: str + member_ids: list[str] + created_at: str diff --git a/src/pydantic_valid/errors.py b/src/pydantic_valid/errors.py new file mode 100644 index 00000000..7e4f5ca2 --- /dev/null +++ b/src/pydantic_valid/errors.py @@ -0,0 +1,15 @@ +from pydantic import BaseModel + + +class ErrorDetail(BaseModel): + code: str + message: str + request_id: str + + +class ErrorResponse(BaseModel): + detail: ErrorDetail + + +class Health(BaseModel): + status: str \ No newline at end of file diff --git a/src/pydantic_valid/message.py b/src/pydantic_valid/message.py new file mode 100644 index 00000000..ba1b6e21 --- /dev/null +++ b/src/pydantic_valid/message.py @@ -0,0 +1,22 @@ +from pydantic import BaseModel, Field, field_validator, ConfigDict +from uuid import UUID + + +class CreateMessage(BaseModel): + model_config = ConfigDict(extra="forbid") + text: str = Field(..., min_length=1, max_length=4000) + + @field_validator("text") + @classmethod + def validate_text(cls, v: str) -> str: + if not v.strip(): + raise ValueError("Blank or text consisted only from whitespaces is prohibitated") + return v + + +class Message(BaseModel): + id: str + chat_id: str + sender_id: str + text: str + created_at: str diff --git a/src/pydantic_valid/page_response.py b/src/pydantic_valid/page_response.py new file mode 100644 index 00000000..62f6982d --- /dev/null +++ b/src/pydantic_valid/page_response.py @@ -0,0 +1,7 @@ +from pydantic import BaseModel +from typing import Any, Optional + + +class PageResponse(BaseModel): + items: list[Any] + next_cursor: Optional[str] = None \ No newline at end of file diff --git a/src/pydantic_valid/session.py b/src/pydantic_valid/session.py new file mode 100644 index 00000000..3355f22c --- /dev/null +++ b/src/pydantic_valid/session.py @@ -0,0 +1,16 @@ +from pydantic import Field, BaseModel, ConfigDict + + +class SessionUser(BaseModel): + id: str + username: str + display_name: str + created_at: str + + +class SessionCreateResponse(BaseModel): + model_config = ConfigDict(extra="forbid") + token: str + token_type: str = Field(default="Bearer", pattern="^Bearer$") + expires_at: str + user: SessionUser diff --git a/src/pydantic_valid/user.py b/src/pydantic_valid/user.py new file mode 100644 index 00000000..d12d083e --- /dev/null +++ b/src/pydantic_valid/user.py @@ -0,0 +1,23 @@ +from pydantic import BaseModel, Field, field_validator, ConfigDict + + +class CreateUser(BaseModel): + model_config = ConfigDict(extra="forbid") + username: str = Field(..., pattern=r"^[a-z0-9_]{3,32}$") + display_name: str = Field(..., min_length=1, max_length=100) + password: str = Field(..., min_length=12, max_length=128) + + + @field_validator("display_name") + @classmethod + def validate_display_name(cls, v: str) -> str: + if not v.strip(): + raise ValueError("Name cannot be whitespaces or none") + return v + + +class User(BaseModel): + id: str + username: str + display_name: str + created_at: str diff --git a/src/redis_client.py b/src/redis_client.py new file mode 100644 index 00000000..189e13a6 --- /dev/null +++ b/src/redis_client.py @@ -0,0 +1,27 @@ +import os +import redis.asyncio as aioredis +from redis.exceptions import RedisError + +REDIS_URL = os.getenv("REDIS_URL") +redis_client: aioredis.Redis | None = None + + +async def init_redis() -> aioredis.Redis: + global redis_client + redis_client = aioredis.from_url(REDIS_URL, decode_responses=True, socket_connect_timeout=2, socket_timeout=2) + try: + await redis_client.ping() + except RedisError: + redis_client = None + return redis_client + + +async def close_redis(): + global redis_client + if redis_client: + await redis_client.close() + redis_client = None + + +def get_redis() -> aioredis.Redis | None: + return redis_client \ No newline at end of file diff --git a/src/services/idempotency.py b/src/services/idempotency.py new file mode 100644 index 00000000..91c2791e --- /dev/null +++ b/src/services/idempotency.py @@ -0,0 +1,121 @@ +import hashlib +import json +import asyncio +import time +from redis.exceptions import RedisError +from src.redis_client import get_redis +from fastapi import HTTPException, status +from src.config import settings + +IDEMPOTENCY_PREFIX = "idempotency:" +IDEMPOTENCY_TTL = 86400 +LOCK_TIMEOUT = 10 +CONCURRENT_WAIT_S = 2.0 + + +def _cache_key(user_id: str, chat_id: str, idempotency_key: str) -> str: + return f"{IDEMPOTENCY_PREFIX}{user_id}:{chat_id}:{idempotency_key}" + + +def _lock_key(user_id: str, chat_id: str, idempotency_key: str) -> str: + return f"{_cache_key(user_id, chat_id, idempotency_key)}:lock" + + +def body_hash(body: dict) -> str: + canonical = json.dumps(body, sort_keys=True, ensure_ascii=False, separators=(',', ':')) + return hashlib.sha256(canonical.encode("utf-8")).hexdigest() + + +def _conflict() -> HTTPException: + return HTTPException( + status_code=status.HTTP_409_CONFLICT, + detail="Idempotency-Key already used with different body", + ) + + +def _in_progress() -> HTTPException: + return HTTPException( + status_code=status.HTTP_503_SERVICE_UNAVAILABLE, + detail="concurrent request with the same Idempotency-Key is in progress", + headers={"Retry-After": str(settings.RETRY_AFTER_POOL)}, + ) + + +async def _read_result(r, cache_key: str, current_hash: str): + raw = await r.get(cache_key) + if not raw: + return None + cached = json.loads(raw) + if cached["body_hash"] != current_hash: + raise _conflict() + return cached["response"] + + +async def check_idempotency(user_id: str, chat_id: str, idempotency_key: str, current_hash: str) -> dict | None: + r = get_redis() + if not r: + return False, None + + cache_key = _cache_key(user_id, chat_id, idempotency_key) + lock_key = _lock_key(user_id, chat_id, idempotency_key) + + try: + result = await _read_result(r, cache_key, current_hash) + if result is not None: + return True, result + + lock_acquired = await r.set(lock_key, "1", nx=True, ex=LOCK_TIMEOUT) + + if not lock_acquired: + deadline = time.monotonic() + CONCURRENT_WAIT_S + delay = 0.02 + while time.monotonic() < deadline: + await asyncio.sleep(delay) + result = await _read_result(r, cache_key, current_hash) + if result is not None: + return True, result + delay = min(delay * 2, 0.2) + raise _in_progress() + + raw = await r.get(cache_key) + if raw: + cached = json.loads(raw) + if cached["body_hash"] != current_hash: + await r.delete(lock_key) + raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail="Idempotency-Key already used with different body") + await r.delete(lock_key) + return True, cached["response"] + + return False, None + + except RedisError: + return False, None + + +async def save_idempotency(user_id: str, chat_id: str, idempotency_key: str, current_hash: str, response_data: dict) -> None: + r = get_redis() + if not r: + return + + cache_key = _cache_key(user_id, chat_id, idempotency_key) + lock_key = _lock_key(user_id, chat_id, idempotency_key) + + try: + await r.setex( + cache_key, + IDEMPOTENCY_TTL, + json.dumps({"body_hash": current_hash, "response": response_data}) + ) + finally: + await r.delete(lock_key) + + +async def release_idempotency(user_id: str, chat_id: str, idempotency_key: str) -> None: + r = get_redis() + if r is None: + return + try: + await r.delete(_lock_key(user_id, chat_id, idempotency_key)) + except RedisError: + pass + \ No newline at end of file diff --git a/src/services/session_cache.py b/src/services/session_cache.py new file mode 100644 index 00000000..e15e8ceb --- /dev/null +++ b/src/services/session_cache.py @@ -0,0 +1,78 @@ +import uuid +import random +from src.redis_client import get_redis +from redis.exceptions import RedisError +from src.config import settings + + +SESSION_PREFIX = "session:" +LOCK_PREFIX = "lock:session:" +CACHE_TTL_JITTER = 0.1 + + +def _key(token_hash: str) -> str: + return f"{SESSION_PREFIX}{token_hash}" + + +def _lock_key(token_hash: str) -> str: + return f"{LOCK_PREFIX}{token_hash}" + + +async def cache_session(token_hash: str, user_id: uuid.UUID, ttl: int | None = None) -> None: + r = get_redis() + if not r: + return + + effective_ttl = ttl or settings.SESSION_TTL_SECONDS + jitter = int(effective_ttl * CACHE_TTL_JITTER * (2 * random.random() - 1)) + final_ttl = max(1, effective_ttl + jitter) + + try: + await r.setex(_key(token_hash), final_ttl, str(user_id)) + except RedisError: + pass + + +async def get_cached_user_id(token_hash: str) -> uuid.UUID | None: + r = get_redis() + if not r: + return + + try: + value = await r.get(_key(token_hash)) + return uuid.UUID(value) if value else None + except RedisError: + return None + + +async def invalidate_session(token_hash: str) -> None: + r = get_redis() + if not r: + return + + try: + await r.delete(_key(token_hash)) + except RedisError: + pass + + +async def invalidate_all_user_sessions(user_id: uuid.UUID) -> int: + + r = get_redis() + if not r: + return 0 + + try: + pattern = f"{SESSION_PREFIX}*" + keys = [] + async for key in r.scan_iter(match=pattern, count=100): + value = r.get(key) + if value and uuid.UUID(value) == user_id: + keys.append(key) + + if keys: + await r.delete(*keys) + return len(keys) + + except RedisError: + return 0 \ No newline at end of file diff --git a/src/utils.py b/src/utils.py new file mode 100644 index 00000000..07d4e50b --- /dev/null +++ b/src/utils.py @@ -0,0 +1,21 @@ +import uuid +from datetime import datetime, timezone +from fastapi.responses import JSONResponse + + +def generate_id() -> str: + return uuid.uuid4() + + +def get_now_iso() -> str: + return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") + + +def create_error_response(message: str, code: str, status_code: int, request_id: str, instance_id: str, extra_headers: dict[str, str] | None = None) -> JSONResponse: + body = {"error": {"code": code, "message": message, "request_id": request_id}} + headers = {"X-Request-Id": request_id, "X-Instance-Id": instance_id} + + if extra_headers: + headers.update(extra_headers) + + return JSONResponse(status_code=status_code, content=body, headers=headers) diff --git a/student_tests/conftest.py b/student_tests/conftest.py new file mode 100644 index 00000000..4be3e37e --- /dev/null +++ b/student_tests/conftest.py @@ -0,0 +1,68 @@ +import os +import pytest +import uuid +import requests +import base64 + + +BASE_URL = os.environ.get("BASE_URL", "http://localhost:8080") +TEST_PASSWORD = "SecurePassword7654321" + + +def create_and_login_user(base_url, display_name_prefix): + username = f"st_{display_name_prefix.lower()}_{uuid.uuid4().hex[:8]}" + + registr_response = requests.post(f"{base_url}/api/v1/users", + json={ + "username": username, + "display_name": f"{display_name_prefix} Test", + "password": TEST_PASSWORD}) + assert registr_response.status_code == 201, f"Registration failed: {registr_response.text}" + user_data = registr_response.json() + + credentials = base64.b64encode(f"{username}:{TEST_PASSWORD}".encode()).decode() + login_response = requests.post(f"{base_url}/api/v1/auth/sessions", + headers={"Authorization": f"Basic {credentials}"}) + assert login_response.status_code == 201, f"Login failed: {login_response.text}" + token = login_response.json()["token"] + + return { + "id": user_data["id"], + "username": username, + "user": user_data, + "headers": {"Authorization": f"Bearer {token}"} + } + + +@pytest.fixture(scope="session") +def base_url(): + return BASE_URL + + +@pytest.fixture(scope="session") +def alice(base_url): + return create_and_login_user(base_url, "Alice") + + +@pytest.fixture(scope="session") +def bob(base_url): + return create_and_login_user(base_url, "Bob") + + +@pytest.fixture(scope="session") +def eve(base_url): + return create_and_login_user(base_url, "Eve") + + +@pytest.fixture(scope="session") +def chat(base_url, alice, bob): + + response = requests.post(f"{base_url}/api/v1/chats", headers=alice["headers"], json={ + "title": "Student Test Chat", + "member_ids": [alice["id"], bob["id"]] + }) + assert response.status_code == 201, response.text + return response.json() + +def auth(actor): + return actor["headers"] diff --git a/student_tests/test_access.py b/student_tests/test_access.py new file mode 100644 index 00000000..f4b354b3 --- /dev/null +++ b/student_tests/test_access.py @@ -0,0 +1,48 @@ +import requests +import uuid +from conftest import base_url, auth + + +def test_foreign_chat_get(base_url, eve, chat): + response = requests.get(f"{base_url}/api/v1/chats/{chat['id']}", + headers=auth(eve)) + assert response.status_code == 404 + assert response.json()["error"]["code"] == "not_found" + + +def test_foreign_chat_messages(base_url, eve, chat): + response = requests.get(f"{base_url}/api/v1/chats/{chat['id']}/messages", + headers=auth(eve)) + assert response.status_code == 404 + assert response.json()["error"]["code"] == "not_found" + + +def test_foreign_chat_send_messages(base_url, eve, chat): + response = requests.post(f"{base_url}/api/v1/chats/{chat['id']}/messages", + headers={**auth(eve), "Idempotency-Key": str(uuid.uuid4())}, + json={"text": "Hello, I miss you"}, + ) + assert response.status_code == 404 + assert response.json()["error"]["code"] == "not_found" + + +def test_foreign_chat_not_in_list(base_url, eve, chat): + response = requests.get(f"{base_url}/api/v1/chats?limit=100", headers=auth(eve)) + + assert response.status_code == 200 + chat_ids = [c["id"] for c in response.json()["items"]] + assert chat["id"] not in chat_ids + + +def test_invalid_chat_id_format(base_url, alice): + response = requests.get(f"{base_url}/api/v1/chats/wrong_id", + headers=auth(alice)) + assert response.status_code == 400 + assert response.json()["error"]["code"] == "invalid_request" + + +def test_nonexistent_chat(base_url, alice): + response = requests.get(f"{base_url}/api/v1/chats/00000000-0000-0000-0000-000000000000", + headers=auth(alice)) + assert response.status_code == 404 + assert response.json()["error"]["code"] == "not_found" diff --git a/student_tests/test_pagination.py b/student_tests/test_pagination.py new file mode 100644 index 00000000..5900c63a --- /dev/null +++ b/student_tests/test_pagination.py @@ -0,0 +1,76 @@ +import requests +import uuid +from conftest import base_url, auth + + +def test_multi_page_walktrhough(base_url, alice, chat): + sent = [] + for i in range(7): + response = requests.post(f"{base_url}/api/v1/chats/{chat['id']}/messages", + headers={**auth(alice), "Idempotency-Key": str(uuid.uuid4())}, + json={"text": f"page-test-{i}-{uuid.uuid4().hex[:6]}"}) + assert response.status_code == 201, response.text + sent.append(response.json()) + + all_items = [] + cursor = None + pages_seen = 0 + + while True: + url = f"{base_url}/api/v1/chats/{chat['id']}/messages?limit=2" + if cursor: + url += f"&cursor={cursor}" + response = requests.get(url, headers=auth(alice)) + assert response.status_code == 200 + body = response.json() + + items = body["items"] + assert len(items) <= 2 + all_items.extend(items) + pages_seen +=1 + + next_cursor = body["next_cursor"] + if next_cursor is None: + break + cursor = next_cursor + + assert pages_seen == 4, f"expected 4 pages, got {pages_seen}" + + ids = [m["id"] for m in all_items] + assert len(ids) == len(set(ids)), "duplicate in pages" + + keys = [(m["created_at"], m["id"]) for m in all_items] + assert keys == sorted(keys), "messages not in ascending order (created_at, id)" + + our_ids = {m["id"] for m in sent} + assert our_ids.issubset(set(ids)), "some sent messages are missing from pagination" + + +def test_cursor_from_another_chat_rejected(base_url, alice, eve, chat): + response = requests.post(f"{base_url}/api/v1/chats", + headers=auth(alice), + json={ + "title": "Second Chat", + "member_ids": [alice["id"], eve["id"]], + }) + assert response.status_code == 201 + chat2 = response.json() + + for _ in range(2): + response = requests.post(f"{base_url}/api/v1/chats/{chat2['id']}/messages", + headers={**auth(alice), "Idempotency-Key": str(uuid.uuid4())}, + json={"text": "Hello, I miss you"}) + assert response.status_code == 201 + + response = requests.get(f"{base_url}/api/v1/chats/{chat2['id']}/messages?limit=1", + headers=auth(alice)) + assert response.status_code == 200 + cursor = response.json().get("next_cursor") + + if cursor is None: + return + + response = requests.get(f"{base_url}/api/v1/chats/{chat['id']}/messages?limit=1&cursor={cursor}", + headers=auth(alice)) + assert response.status_code == 400, f"expected 400 for cross-chat cursor, got {response.status_code}" + assert response.json()["error"]["code"] == "invalid_request" \ No newline at end of file diff --git a/student_tests/test_validation.py b/student_tests/test_validation.py new file mode 100644 index 00000000..785d5620 --- /dev/null +++ b/student_tests/test_validation.py @@ -0,0 +1,109 @@ +import requests +from student_tests.conftest import base_url, auth + + +def test_malformed_json(base_url): + response = requests.post(f"{base_url}/api/v1/users", headers={ + "Content-Type": "application/json" + }, + data=b"not valid json") + + assert response.status_code == 400 + body = response.json() + assert body["error"]["code"] == "invalid_request" + assert body["error"]["request_id"] == response.headers["X-Request-Id"] + + +def test_wrong_field(base_url): + response = requests.post(f"{base_url}/api/v1/users", json={ + "username": 1235, + "display_name": "Alice", + }) + + assert response.status_code == 400 + assert response.json()["error"]["code"] == "invalid_request" + + +def test_extra_fields(base_url): + response = requests.post(f"{base_url}/api/v1/users", json={ + "username": "extra_field", + "display_name": "Test", + "Extra": "Should be rejected" + }) + assert response.status_code == 400 + assert response.json()["error"]["code"] == "invalid_request" + + +def test_empty_message(base_url, alice, chat): + response = requests.post(f"{base_url}/api/v1/chats/{chat["id"]}/messages", + headers=auth(alice), + json={"text": ""}) + assert response.status_code == 400 + assert response.json()["error"]["code"] == "invalid_request" + + +def test_whitespaces_message(base_url, alice, chat): + response = requests.post(f"{base_url}/api/v1/chats/{chat["id"]}/messages", + headers=auth(alice), + json={"text": " \t\n \t"}) + assert response.status_code == 400 + assert response.json()["error"]["code"] == "invalid_request" + + +def test_too_large_message(base_url, alice, chat): + response = requests.post(f"{base_url}/api/v1/chats/{chat["id"]}/messages", + headers=auth(alice), + json={"text": "0" * 4001}) + assert response.status_code == 400 + assert response.json()["error"]["code"] == "invalid_request" + + +def test_duplicate_username(base_url, alice): + response = requests.post(f"{base_url}/api/v1/users", json={ + "username": alice["username"], + "display_name": "Another Alice", + "password": "SecurePassword7654321"} + ) + + assert response.status_code == 409 + assert response.json()["error"]["code"] == "conflict" + + +def test_invalid_username_pattern(base_url): + response = requests.post(f"{base_url}/api/v1/users", json={ + "username": "AliceWithCaps", + "display_name": "Test", + }) + + assert response.status_code == 400 + assert response.json()["error"]["code"] == "invalid_request" + + +def test_missing_x_user_id(base_url): + response = requests.get(f"{base_url}/api/v1/users/me") + + assert response.status_code == 401 + assert response.json()["error"]["code"] == "unauthorized" + + +def test_unknown_user_id(base_url): + response = requests.get(f"{base_url}/api/v1/users/me", + headers={"X-User-Id": "00000000-0000-0000-0000-000000000000"}) + assert response.status_code == 401 + assert response.json()["error"]["code"] == "unauthorized" + + +def test_ivalid_limit_zero(base_url, alice, chat): + response = requests.get(f"{base_url}/api/v1/chats/{chat["id"]}/messages?limit=0", + headers=auth(alice), + ) + assert response.status_code == 400 + assert response.json()["error"]["code"] == "invalid_request" + + +def test_invalid_limit_over(base_url, alice, chat): + response = requests.get(f"{base_url}/api/v1/chats/{chat["id"]}/messages?limit=101", + headers=auth(alice), + ) + assert response.status_code == 400 + assert response.json()["error"]["code"] == "invalid_request"