diff --git a/.dockerignore b/.dockerignore index bc16e556..46289fc6 100644 --- a/.dockerignore +++ b/.dockerignore @@ -18,3 +18,6 @@ __pycache__ node_modules evidence .DS_Store + +.secrets +*.zip diff --git a/.gitignore b/.gitignore index b5a71896..5aea4113 100644 --- a/.gitignore +++ b/.gitignore @@ -30,3 +30,6 @@ coverage/ .vscode/ # Keep small, sanitized evidence summaries in evidence/ under version control. # Inspect git diff --cached: ignore rules are not a secret scanner. + +.secrets/ +*.dump diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 00000000..b6881174 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,30 @@ +FROM python:3.12.10-slim-bookworm + +ENV PYTHONDONTWRITEBYTECODE=1 \ + PYTHONUNBUFFERED=1 \ + APP_HOST=0.0.0.0 \ + APP_PORT=8080 + +WORKDIR /app + +COPY requirements.txt . +RUN pip install --no-cache-dir --requirement requirements.txt \ + && groupadd --system --gid 10001 app \ + && useradd --system --uid 10001 --gid app --home-dir /nonexistent --shell /usr/sbin/nologin app + +COPY --chown=app:app src ./src +COPY --chown=app:app migrations ./migrations +COPY --chown=app:app scripts ./scripts +COPY --chown=app:app student-tests ./student-tests +COPY --chown=app:app tests ./tests +COPY --chown=app:app contracts ./contracts +COPY --chown=app:app lab.json ./lab.json +RUN mkdir -p evidence && chown app:app evidence + +USER 10001:10001 +EXPOSE 8080 + +HEALTHCHECK --interval=10s --timeout=3s --start-period=3s --retries=3 \ + CMD ["python", "/app/scripts/healthcheck.py"] + +CMD ["sh", "-c", "exec uvicorn src.main:app --host \"${APP_HOST}\" --port \"${APP_PORT}\" --workers 1 --timeout-graceful-shutdown 10"] diff --git a/Makefile b/Makefile index 9ecb223e..9b8e4a67 100644 --- a/Makefile +++ b/Makefile @@ -24,3 +24,23 @@ load: test-persistence: @test -n "$(ACTION_SCRIPT)" || (echo "Set ACTION_SCRIPT to your implemented executable restart hook"; exit 2) $(PYTHON) tests/resilience.py --mode persistence --action-script "$(ACTION_SCRIPT)" --base-url "$(BASE_URL)" $(TLS_ARGS) + +.PHONY: setup ready student-checks experiment backup-restore test-dependencies test-expiry +setup: + bash scripts/setup.sh +ready: + BASE_URL="$(BASE_URL)" $(PYTHON) scripts/wait_ready.py +student-checks: + $(PYTHON) student-tests/checks.py --base-url "$(BASE_URL)" + $(PYTHON) student-tests/test_api.py --base-url "$(BASE_URL)" + docker compose exec -T api python student-tests/database.py + docker compose exec -T api python student-tests/test_lifecycle.py +experiment: + @mkdir -p evidence + docker compose run --rm -T --no-deps --user "$(shell id -u):$(shell id -g)" -v "$(CURDIR)/evidence:/app/evidence" api python -m scripts.experiment +backup-restore: + bash scripts/backup_restore.sh +test-dependencies: + $(PYTHON) student-tests/dependencies.py --base-url "$(BASE_URL)" --stop-cache scripts/stop-cache.sh --start-cache scripts/start-cache.sh --stop-db scripts/stop-db.sh --start-db scripts/start-db.sh +test-expiry: + bash scripts/test_expiry.sh diff --git a/REPORT.md b/REPORT.md index e42f2b05..3a040e46 100644 --- a/REPORT.md +++ b/REPORT.md @@ -1,37 +1,232 @@ -# Отчёт — лабораторная 2 +# Лабораторная работа № 2 — постоянное хранение и сессии -- Автор, группа: TODO -- Целевая оценка; выбранный трек 5, если нужен: TODO -- Commit/PR: TODO после публикации -- Использованные источники, библиотеки и помощь ИИ: TODO +- Автор: Максим Шептунов, группа БВТ2301. +- Целевая оценка: 5. +- Выбранный трек: 2, «План запроса и восстановление». +- Дата проверки: 02.10.2026. +- Исходный skeleton: `65003b61195361aac238f19c9bff0027ca58e09e`. +- Commit решения и ссылка на PR: заполнить после публикации. +- Помощь ИИ: помощь с реализацией, тестами и разбором результатов. +- Все численные результаты ниже получены на моём стенде. Доказательства — файлы `evidence/local_*` и JSON текущего эксперимента. -## Запуск из чистого clone +## 1. Переход от первой лабораторной -TODO: версии runtime/образов, prerequisites, команды создания локальных secrets/.env, build, миграций, запуска, ожидания готовности, тестов и остановки. Указать необходимые действия оператора. Не вставлять секреты. Отдельно указать безопасную остановку и команду намеренного удаления учебных данных. +За основу взят мой итоговый вариант lab1. Сохранены операции с пользователями, чатами и сообщениями, проверки входных данных, доступ только участникам, единый формат ошибок и курсорная пагинация. -## Архитектура и решения +Хранение в памяти заменено PostgreSQL. Вместо доверия заголовку X-User-Id добавлены пароль и сессии. Redis используется для кеширования публичного профиля пользователя. Добавлены миграции, ограничения базы, проверки транзакций, перезапуска и отказов. Обязательные контракты и публичные тесты lab2 не изменялись. -TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab1, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации. +## 2. Окружение и запуск -## Доказательства критериев +| Параметр | Значение | +|---|---| +| Система | Windows 11, WSL2/Ubuntu; ядро 5.15.146.1-microsoft-standard-WSL2 | +| CPU | Intel Core i5-1240P; WSL видит 16 логических CPU | +| Память, видимая WSL | около 7,6 GiB; swap 2,0 GiB | +| Python хоста / API | 3.10.12 / 3.12.10 | +| Docker | 28.0.1 | +| Docker Compose | v2.27.0-desktop.2 | +| PostgreSQL | 16.9, образ postgres:16.9-bookworm | +| Redis | 7.4.3, образ redis:7.4.3-bookworm | +| PostgreSQL shared_buffers / work_mem | 128MB / 4MB | +| PostgreSQL fsync / synchronous_commit | on / on | -| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства | -| --- | --- | --- | --- | -| Публичный smoke | make test | TODO | TODO | -| Остальные пункты уровня 3 | TODO | TODO | TODO | -| Все пункты уровня 4, если заявлен | TODO | TODO | TODO | -| Выбранный трек 5, если заявлен | TODO | TODO | TODO | +Окружение зафиксировано в `evidence/local_environment.txt`. Это параметры виртуальной среды, а не измерение потребления CPU и памяти процессами. Образы закреплены тегами; зависимости API перечислены в requirements.txt. -TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены. +Запуск из каталога проекта: -## Эксперименты и отказы +```bash +python3 -m venv .venv +source .venv/bin/activate +python -m pip install -r requirements-dev.txt +chmod +x scripts/*.sh +make setup +docker compose config --quiet +docker compose up -d --build --wait +make ready +``` -TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения. +На хост устанавливаются зависимости проверки OpenAPI; зависимости API устанавливаются в Docker-образе. -| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных | -| --- | --- | --- | --- | -| TODO | TODO | TODO | TODO | +setup создаёт пароль и строку подключения в .secrets, а также .env. Каталог .secrets имеет права 700; db_password — 600; database_url — 644, чтобы непривилегированный пользователь API мог прочитать файл, смонтированный через Compose secrets. Закрытый родительский каталог ограничивает доступ других пользователей хоста. .secrets и .env исключены из Git и контекста сборки. -## Ограничения и следующие шаги +Первый запуск выявил ошибку прав чтения database_url; права и setup.sh исправлены. Успешная готовность и работа после исправления подтверждены local_ready.txt, local_services.txt и local_smoke.txt. + +Обычная остановка: `docker compose down`. Именованные volumes сохраняются. `docker compose down -v` удаляет данные и не используется для проверки перезапуска. Пароль не следует заменять отдельно от существующего PostgreSQL volume. + +## 3. Архитектура, схема и транзакции + +FastAPI выполняет валидацию, аутентификацию и проверку доступа. PostgreSQL — источник истины для users, chats, chat_members, messages и sessions. У PostgreSQL постоянный volume. Redis хранит публичные профили с TTL 60 секунд; его данные также находятся в volume, включён AOF с appendfsync everysec. + +Схема задана в migrations/001_initial.sql: +- UUID — первичные ключи основных объектов; +- users.username имеет UNIQUE и проверку формата; +- chat_members имеет составной PRIMARY KEY (chat_id, user_id); +- внешние ключи запрещают ссылки на отсутствующих пользователей и чаты; +- messages(chat_id, sender_id) ссылается на членство (chat_id, user_id); +- CHECK ограничивает допустимость текстовых полей; +- индекс messages(chat_id, created_at, id) соответствует чтению истории; +- индекс chat_members(user_id, chat_id) помогает искать чаты пользователя; +- sessions содержит хеш токена, пользователя и expires_at. + +Создание чата и всех участников выполняется в одной транзакции. В тесте ошибка внешнего ключа возникает после частичных вставок; после rollback отсутствуют и чат, и членство. INSERT сообщения фиксируется до ответа 201. + +Конкурентная регистрация защищена UNIQUE: из восьми запросов с одинаковым username один успешен, остальные получают 409. SQL-параметры передаются отдельно через psycopg, без конкатенации пользовательских значений. + +Миграции применяются при запуске. schema_migrations хранит версии; изменение схемы и запись версии атомарны. Advisory lock сериализует одновременное применение миграций. Повторное применение проверено тестом. + +Пул PostgreSQL: 1–8 соединений, ожидание соединения 2 секунды, connect_timeout 2 секунды, statement_timeout 3 секунды, lock_timeout 2 секунды. Это пределы отдельных стадий, а не единый deadline всего HTTP-запроса. + +## 4. Аутентификация и кеш + +Пароли хешируются Argon2id: time_cost=2, memory_cost=19456 KiB, parallelism=1, случайная соль библиотеки. Basic разрешён только для POST /api/v1/auth/sessions. Для операций с чатами и сообщениями нужен Bearer; X-User-Id не предоставляет доступ. + +Токен генерируется из 32 случайных байтов. Клиент получает исходный токен, PostgreSQL хранит только SHA-256. Быстрый хеш подходит для случайного токена высокой энтропии; для человеческого пароля используется медленный KDF. + +Сессия имеет абсолютный срок: момент выдачи плюс TTL, по умолчанию 3600 секунд. На каждом защищённом запросе PostgreSQL проверяет токен и expires_at. Logout удаляет сессию; перезапуск не продлевает её срок. Уже начатый запрос может завершиться после logout. + +Redis не кеширует действительность сессии: после проверки в PostgreSQL он заменяет повторное SQL-чтение публичного профиля. При отказе Redis профиль читается из PostgreSQL. Профиль не редактируется обязательным API; при добавлении редактирования понадобится инвалидация кеша. + +В Docker-прогоне первоначально обнаружена задержка fallback более восьми секунд. Добавлены dns_opt timeout:1/attempts:1 для API и пропуск записи в кеш после ошибки его чтения. Повторный тест отказов прошёл. Socket timeout Redis равен 0,25 секунды, но не является общим пределом времени с учётом DNS. Весь сценарий Redis offline занял 3,065 секунды, а не один запрос. + +При отказе PostgreSQL приложение не доверяет данным клиента: защищённый запрос получает 503. /health/live не требует базы; /health/ready проверяет PostgreSQL. Пустой Redis не препятствует готовности. + +Локальный API опубликован только на 127.0.0.1:8080. При удалённом использовании нужен TLS: Basic/Base64 не шифрует пароль. Пароли и токены не добавляются в evidence. + +## 5. Выполненные проверки + +| Проверка | Результат | Доказательство в evidence | +|---|---|---| +| make check | PASS, структура и синтаксис; не проверяет работающий API | local_check.txt | +| make validate | PASS, OpenAPI и JSON Schema; не проверяет работающий API | local_validate.txt | +| make ready, docker compose ps | API готов, три сервиса healthy | local_ready.txt, local_services.txt | +| make test | PASS публичного сценария API | local_smoke.txt | +| make student-checks | PASS гонки регистрации, валидации, cursor scope, read-after-write и logout | local_student_checks.txt | +| Тест API из lab1 | 10 клиентов создали ровно 100 уникальных сообщений; пагинация прошла | local_student_checks.txt | +| Тест БД | PASS rollback чата и участников, повтор миграций | local_student_checks.txt | +| SIGTERM и перезапуск API | завершение за 0,166 с, старый пользователь и токен сохранились | local_student_checks.txt | +| make test-persistence ACTION_SCRIPT=scripts/restart.sh | PASS сохранности подтверждённых данных и старой сессии | local_persistence.txt | +| make test-dependencies | PASS отказов, восстановления и запрета анонимного доступа | local_dependencies.txt, dependency_failures.json | +| make test-expiry | PASS срока сессии с TTL=2 | local_expiry.txt | +| make test после отказов | PASS | local_smoke_after_failures.txt | +| make experiment | PASS 100000 сообщений, двух индексов, запросов и записи | local_experiment.txt, track2_raw.json | +| make backup-restore | PASS отдельного PostgreSQL/volume и сверки данных | local_backup_restore.txt, backup_restore.json, restore_verification.json | +| Финальный make test | PASS после эксперимента и восстановления | local_final_smoke.txt | + +scripts/restart.sh останавливает API, Redis и PostgreSQL, затем запускает хранилища и API с ожиданием готовности. Тест persistence использует прежний токен и ранее подтверждённые данные, без повторной регистрации. В выводе теста scope hook не раскрывается; его объём определяется указанным скриптом. + +Команды воспроизведения: + +```bash +make check +make validate +make test +make student-checks +make test-persistence ACTION_SCRIPT=scripts/restart.sh +make test-dependencies +make test-expiry +make ready +make test +make experiment +make backup-restore +make test +``` + +## 6. Исследование трека 2 + +### Гипотеза и методика + +Гипотеза: составной индекс (chat_id, created_at, id) вместе с keyset-пагинацией уменьшает работу при чтении глубокой страницы. OFFSET даже при наличии индекса должен пройти пропускаемые строки. Более широкий индекс требует дополнительного места и может увеличить стоимость записи. + +Эксперимент изолирован в схеме research_07e953c76ff9 внутри основной БД. Это не отдельное физическое хранилище. Структура таблиц и ограничения соответствуют приложению. + +Создано 100000 сообщений: пять чатов на 70000, 20000, 9000, 900 и 100 сообщений. Использованы случайные UUID, текст переменной длины и время с интервалом 1 микросекунда. Seed=42 задаёт порядок измерений, но не делает UUID детерминированными. + +Сравниваются индексы (chat_id) и (chat_id, created_at, id), запросы OFFSET и keyset, три позиции в каждом чате: около начала, середины и 90% истории. Всего 60 комбинаций. Каждый запрос возвращает до 51 строки, соответствуя странице API на 50 сообщений с дополнительной строкой для определения продолжения. + +Для сравнения выбирается одна граница, после которой оба запроса возвращают одну и ту же страницу. Позиция около начала означает чтение после первой выбранной строки, а не первый запрос без курсора. + +Для каждой комбинации выполнены 5 прогревов и 30 измерений, concurrency=1. Перед измерением обновлена статистика ANALYZE. Планировщик не принуждается использовать индекс. Client latency включает SQL, передачу результата и работу драйвера; это не HTTP latency. EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON) выполнен отдельно. p50 — медиана, p95/p99 вычислены методом ближайшего ранга; при 30 измерениях p99 фактически максимум. + +### Результат глубокой страницы большого чата + +Чат: 70000 сообщений. Курсор после позиции 62999; OFFSET пропускает 63000 строк. + +| Индекс | Запрос | p50, мс | p95, мс | +|---|---|---:|---:| +| chat_id | OFFSET | 39,608 | 46,870 | +| chat_id | keyset | 12,574 | 16,630 | +| chat_id, created_at, id | OFFSET | 10,017 | 14,338 | +| chat_id, created_at, id | keyset | 0,741 | 0,982 | + +Keyset с составным индексом примерно в 13,5 раза быстрее по медиане, чем OFFSET с тем же индексом. Это результат конкретной страницы и стенда. + +У начала большого чата медианы составного индекса: OFFSET 0,375 мс, keyset 0,508 мс. Преимущество keyset не универсально: при малом числе пропускаемых строк различие невелико. Полные результаты находятся в track2_summary.md и track2_raw.json. + +### Объяснение планами + +Для глубокого OFFSET с составным индексом план содержит Limit → Index Scan. Сканирование отдаёт 63051 строку; Limit пропускает 63000. Shared hit blocks — 2447. + +Для keyset с составным индексом: Limit → Index Scan с границей пары (created_at, id) в Index Cond. Сканирование отдаёт 51 строку, shared hit blocks — 6. Отдельная сортировка не нужна. Server Execution Time этого отдельного EXPLAIN — 0,068 мс; это не клиентская медиана 0,741 мс. + +При индексе только chat_id глубокий OFFSET использует Seq Scan → Sort → Limit, сортировка external merge с временными блоками. Для keyset с простым индексом в этом прогоне выбран Index Scan и top-N heapsort; отобрано 7000 строк до ограничения страницы. Один курсор без соответствующего составного индекса не обеспечивает столь же дешёвое чтение. + +### Размер индекса и запись + +После каждой конфигурации выполнено пять транзакций COPY по 1000 строк с COMMIT. Текст партии одинаковой длины; сообщения распределены по чатам равномерно. Удаление дополнительных строк находится вне таймера. Это пакетная SQL-вставка, не время HTTP POST. + +| Индекс | Размер, байт | Медиана партии, мс | +|---|---:|---:| +| chat_id | 720896 | 29,870 | +| chat_id, created_at, id | 5914624 | 33,735 | + +Составной индекс примерно в 8,2 раза больше. Медиана пакетной записи выше примерно на 12,9%. В этом прогоне ускорение чтения сопровождалось увеличением размера и наблюдаемым замедлением записи. Пять партий и фиксированный порядок конфигураций не позволяют заявлять статистически устойчивую величину накладных расходов. + +Ограничения: прогретые кеши, один клиент SQL, виртуальная среда, отсутствие исследования холодного диска и максимальной нагрузки. Тридцать повторов недостаточны для надёжной оценки редкого хвоста задержек. Вариант без дополнительного индекса не измерялся. Повтор эксперимента создаёт новую схему и не удаляет старые. + +## 7. Backup, восстановление и границы потери данных + +scripts/backup_restore.sh выполняет pg_dump -Fc всей БД, создаёт отдельный Compose project и новый PostgreSQL volume, восстанавливает архив через pg_restore и проверяет данные исследовательской схемы. Рабочее хранилище не заменяется. + +| Показатель | Результат | +|---|---:| +| Создание backup | 1,033 с | +| Запуск нового PostgreSQL | 5,770 с | +| pg_restore | 1,109 с | +| Размер архива | 3208212 байт | +| Проект восстановления | lab2-restore-1790966246-29166 | +| Полных выбранных сообщений совпало | 5 | + +Сверка после восстановления: users=1, chats=5, chat_members=5, messages=100000, sessions=0 в исследовательской схеме. Сравниваются id, chat_id, sender_id, text и created_at пяти сообщений. Это проверка количества и выборочных полных строк, не полный checksum базы. Сохранность сессий проверяется отдельно тестом persistence. + +Дамп содержит всю БД, включая рабочие тестовые данные, а 100000 — количество сообщений текущей исследовательской схемы. Raw dump хранится в backups и не публикуется. + +pg_dump создаёт согласованный снимок. Более поздние записи не гарантируются в копии. RPO зависит от возраста и периодичности backup; нулевой RPO не заявляется. PITR и архивирование WAL не настроены. + +RTO включает подготовку хранилища, передачу backup, восстановление, проверки и переключение приложения. Измеренные 1,109 с — только pg_restore; запуск нового сервера измерен отдельно, время проверки и полного переключения не включено. + +При fsync=on и synchronous_commit=on COMMIT подтверждает локальную фиксацию WAL. Volume сохраняет данные при обычном restart, но не защищает от физической потери диска или хоста. + +## 8. Отказы и ограничения реализации + +| Воздействие | Факт проверки | Граница результата | +|---|---|---| +| Перезапуск API и хранилищ | прежние данные и токен сохранились | volumes сохранены; это не потеря диска | +| Redis offline | fallback, чтение/запись и logout работают; сценарий 3,065 с | время всего набора операций, не одного GET | +| PostgreSQL offline | 503 защищённого запроса, live=200, без токена=401; сценарий 0,024 с | конкретный отказ в этом прогоне, не общий предел | +| Restore в новый volume | количество и пять полных сообщений совпали | более поздние записи могут отсутствовать | + +Один API и одна PostgreSQL primary, без HA и репликации. Курсор задаёт устойчивый порядок (created_at, id), но отдельные страницы не образуют единый снимок: конкурентная поздняя фиксация строки с ключом до курсора может привести к её пропуску при обходе. UUID не является порядком COMMIT. + +Профиль и членство не редактируются обязательным API. Истёкшие сессии отвергаются по expires_at; периодическая очистка таблицы отдельно не реализована. Нет отдельного механизма идемпотентности отправки сообщений. Требуются дополнительные измерения перед масштабированием пула и количества API. + +## 9. Источники + +- README.md, COURSE.md и contracts/ текущей лабораторной. +- PostgreSQL 16: https://www.postgresql.org/docs/16/indexes-multicolumn.html +- EXPLAIN: https://www.postgresql.org/docs/16/using-explain.html +- Backup: https://www.postgresql.org/docs/16/app-pgdump.html +- Restore: https://www.postgresql.org/docs/16/app-pgrestore.html +- psycopg: https://www.psycopg.org/psycopg3/docs/ +- Argon2: https://argon2-cffi.readthedocs.io/ +- HTTP Basic: https://www.rfc-editor.org/rfc/rfc7617 -TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза. diff --git a/compose.restore.yaml b/compose.restore.yaml new file mode 100644 index 00000000..54128ad2 --- /dev/null +++ b/compose.restore.yaml @@ -0,0 +1,17 @@ +# Отдельный сервер и новый volume, основной db не затрагивается. +services: + restored: + image: postgres:16.9-bookworm + environment: + POSTGRES_DB: restored + POSTGRES_USER: messenger + POSTGRES_PASSWORD_FILE: /run/secrets/db_password + secrets: [db_password] + volumes: [restored_data:/var/lib/postgresql/data] + healthcheck: + test: [CMD-SHELL, 'pg_isready -U messenger -d restored'] + interval: 2s + timeout: 3s + retries: 30 +volumes: + restored_data: diff --git a/compose.yaml b/compose.yaml new file mode 100644 index 00000000..683eae3d --- /dev/null +++ b/compose.yaml @@ -0,0 +1,51 @@ +services: + db: + image: postgres:16.9-bookworm + environment: + POSTGRES_DB: messenger + POSTGRES_USER: messenger + POSTGRES_PASSWORD_FILE: /run/secrets/db_password + secrets: [db_password] + volumes: [postgres_data:/var/lib/postgresql/data] + healthcheck: + test: [CMD-SHELL, 'pg_isready -U messenger -d messenger'] + interval: 2s + timeout: 3s + retries: 30 + cache: + image: redis:7.4.3-bookworm + command: [redis-server, --appendonly, 'yes', --appendfsync, everysec] + volumes: [redis_data:/data] + healthcheck: + test: [CMD, redis-cli, ping] + interval: 2s + timeout: 3s + retries: 30 + api: + build: . + dns_opt: + - "timeout:1" + - "attempts:1" + environment: + DATABASE_URL_FILE: /run/secrets/database_url + CACHE_URL: redis://cache:6379/0 + SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600} + DB_POOL_MAX: ${DB_POOL_MAX:-8} + secrets: [database_url] + ports: ['127.0.0.1:${APP_PORT:-8080}:8080'] + depends_on: + db: {condition: service_healthy} + cache: {condition: service_healthy} + healthcheck: + test: [CMD, python, -c, "import urllib.request; urllib.request.urlopen('http://localhost:8080/health/ready', timeout=4)"] + interval: 2s + timeout: 5s + retries: 30 +volumes: + postgres_data: + redis_data: +secrets: + db_password: + file: .secrets/db_password + database_url: + file: .secrets/database_url diff --git a/evidence/backup_restore.json b/evidence/backup_restore.json new file mode 100644 index 00000000..e36edc40 --- /dev/null +++ b/evidence/backup_restore.json @@ -0,0 +1,8 @@ +{ + "backup_seconds": 1.032968691, + "new_server_start_seconds": 5.76950239, + "restore_seconds": 1.109244704, + "restore_project": "lab2-restore-1790966246-29166", + "backup_bytes": 3208212, + "stand": "Docker Compose, PostgreSQL 16.9" +} \ No newline at end of file diff --git a/evidence/dependency_failures.json b/evidence/dependency_failures.json new file mode 100644 index 00000000..db82bde4 --- /dev/null +++ b/evidence/dependency_failures.json @@ -0,0 +1,5 @@ +{ + "redis_offline_scenario_seconds": 3.0654408010013867, + "db_offline_scenario_seconds": 0.023503273994720075, + "status": "PASS" +} \ No newline at end of file diff --git a/evidence/local_backup_restore.txt b/evidence/local_backup_restore.txt new file mode 100644 index 00000000..ec7837ad --- /dev/null +++ b/evidence/local_backup_restore.txt @@ -0,0 +1,77 @@ +bash scripts/backup_restore.sh + Network lab2-restore-1790966246-29166_default Creating + Network lab2-restore-1790966246-29166_default Created + Volume "lab2-restore-1790966246-29166_redis_data" Creating + Volume "lab2-restore-1790966246-29166_redis_data" Created + Volume "lab2-restore-1790966246-29166_restored_data" Creating + Volume "lab2-restore-1790966246-29166_restored_data" Created + Volume "lab2-restore-1790966246-29166_postgres_data" Creating + Volume "lab2-restore-1790966246-29166_postgres_data" Created + Container lab2-restore-1790966246-29166-restored-1 Creating + Container lab2-restore-1790966246-29166-restored-1 Created + Container lab2-restore-1790966246-29166-restored-1 Starting + Container lab2-restore-1790966246-29166-restored-1 Started + Container lab2-restore-1790966246-29166-restored-1 Waiting + Container lab2-restore-1790966246-29166-restored-1 Healthy +#0 building with "default" instance using docker driver + +#1 [api internal] load build definition from Dockerfile +#1 transferring dockerfile: 1.04kB done +#1 DONE 0.0s + +#2 [api internal] load metadata for docker.io/library/python:3.12.10-slim-bookworm +#2 DONE 0.7s + +#3 [api internal] load .dockerignore +#3 transferring context: 212B done +#3 DONE 0.0s + +#4 [api 1/12] FROM docker.io/library/python:3.12.10-slim-bookworm@sha256:fd95fa221297a88e1cf49c55ec1828edd7c5a428187e67b5d1805692d11588db +#4 DONE 0.0s + +#5 [api internal] load build context +#5 transferring context: 1.72kB done +#5 DONE 0.0s + +#6 [api 8/12] COPY --chown=app:app student-tests ./student-tests +#6 CACHED + +#7 [api 11/12] COPY --chown=app:app lab.json ./lab.json +#7 CACHED + +#8 [api 6/12] COPY --chown=app:app migrations ./migrations +#8 CACHED + +#9 [api 9/12] COPY --chown=app:app tests ./tests +#9 CACHED + +#10 [api 3/12] COPY requirements.txt . +#10 CACHED + +#11 [api 2/12] WORKDIR /app +#11 CACHED + +#12 [api 7/12] COPY --chown=app:app scripts ./scripts +#12 CACHED + +#13 [api 10/12] COPY --chown=app:app contracts ./contracts +#13 CACHED + +#14 [api 4/12] RUN pip install --no-cache-dir --requirement requirements.txt && groupadd --system --gid 10001 app && useradd --system --uid 10001 --gid app --home-dir /nonexistent --shell /usr/sbin/nologin app +#14 CACHED + +#15 [api 5/12] COPY --chown=app:app src ./src +#15 CACHED + +#16 [api 12/12] RUN mkdir -p evidence && chown app:app evidence +#16 CACHED + +#17 [api] exporting to image +#17 exporting layers done +#17 writing image sha256:f76f54e85211d83d610b5efc29d630111b5c3ad92f5d76edbce24a7b39d9ba94 done +#17 naming to docker.io/library/lab2-restore-1790966246-29166-api done +#17 DONE 0.0s +PASS: restored row counts and selected full messages match backup dataset + Container lab2-restore-1790966246-29166-restored-1 Stopping + Container lab2-restore-1790966246-29166-restored-1 Stopped +PASS: restored into separate PostgreSQL and volume; project=lab2-restore-1790966246-29166 diff --git a/evidence/local_check.txt b/evidence/local_check.txt new file mode 100644 index 00000000..9a553306 --- /dev/null +++ b/evidence/local_check.txt @@ -0,0 +1,2 @@ +python3 scripts/check_contract.py +PASS: offline skeleton structure, local refs and Python syntax; application NOT tested. diff --git a/evidence/local_dependencies.txt b/evidence/local_dependencies.txt new file mode 100644 index 00000000..aab99c6f --- /dev/null +++ b/evidence/local_dependencies.txt @@ -0,0 +1,2 @@ +python3 student-tests/dependencies.py --base-url "http://localhost:8080" --stop-cache scripts/stop-cache.sh --start-cache scripts/start-cache.sh --stop-db scripts/stop-db.sh --start-db scripts/start-db.sh +PASS: Redis fallback + restart + logout; DB bounded 503 + recovery; anonymous rejected diff --git a/evidence/local_environment.txt b/evidence/local_environment.txt new file mode 100644 index 00000000..0d764f46 --- /dev/null +++ b/evidence/local_environment.txt @@ -0,0 +1,75 @@ +2026-10-02T21:38:57+03:00 +Linux LAPTOP-66HKAM8B 5.15.146.1-microsoft-standard-WSL2 #1 SMP Thu Jan 11 04:09:03 UTC 2024 x86_64 x86_64 x86_64 GNU/Linux +Architecture: x86_64 +CPU op-mode(s): 32-bit, 64-bit +Address sizes: 39 bits physical, 48 bits virtual +Byte Order: Little Endian +CPU(s): 16 +On-line CPU(s) list: 0-15 +Vendor ID: GenuineIntel +Model name: 12th Gen Intel(R) Core(TM) i5-1240P +CPU family: 6 +Model: 154 +Thread(s) per core: 2 +Core(s) per socket: 8 +Socket(s): 1 +Stepping: 3 +BogoMIPS: 4224.01 +Flags: fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ss ht syscall nx pdpe1gb rdtscp lm constant_tsc rep_good nopl xtopology tsc_reliable nonstop_tsc cpuid pni pclmulqdq vmx ssse3 fma cx16 sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand hypervisor lahf_lm abm 3dnowprefetch ssbd ibrs ibpb stibp ibrs_enhanced tpr_shadow vnmi ept vpid ept_ad fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid rdseed adx smap clflushopt clwb sha_ni xsaveopt xsavec xgetbv1 xsaves avx_vnni umip waitpkg gfni vaes vpclmulqdq rdpid movdiri movdir64b fsrm md_clear serialize flush_l1d arch_capabilities +Virtualization: VT-x +Hypervisor vendor: Microsoft +Virtualization type: full +L1d cache: 384 KiB (8 instances) +L1i cache: 256 KiB (8 instances) +L2 cache: 10 MiB (8 instances) +L3 cache: 12 MiB (1 instance) +Vulnerability Gather data sampling: Not affected +Vulnerability Itlb multihit: Not affected +Vulnerability L1tf: Not affected +Vulnerability Mds: Not affected +Vulnerability Meltdown: Not affected +Vulnerability Mmio stale data: Not affected +Vulnerability Retbleed: Mitigation; Enhanced IBRS +Vulnerability Spec rstack overflow: Not affected +Vulnerability Spec store bypass: Mitigation; Speculative Store Bypass disabled via prctl and seccomp +Vulnerability Spectre v1: Mitigation; usercopy/swapgs barriers and __user pointer sanitization +Vulnerability Spectre v2: Mitigation; Enhanced IBRS, IBPB conditional, RSB filling, PBRSB-eIBRS SW sequence +Vulnerability Srbds: Not affected +Vulnerability Tsx async abort: Not affected + total used free shared buff/cache available +Mem: 7.6Gi 1.0Gi 2.7Gi 49Mi 3.9Gi 6.3Gi +Swap: 2.0Gi 0B 2.0Gi +Python 3.10.12 +Docker version 28.0.1, build 068a01e +Docker Compose version v2.27.0-desktop.2 +NAME IMAGE COMMAND SERVICE CREATED STATUS PORTS +mtusi2026lab2-api-1 mtusi2026lab2-api "sh -c 'exec uvicorn…" api 2 minutes ago Up 2 minutes (healthy) 127.0.0.1:8080->8080/tcp +mtusi2026lab2-cache-1 redis:7.4.3-bookworm "docker-entrypoint.s…" cache 16 minutes ago Up 3 minutes (healthy) 6379/tcp +mtusi2026lab2-db-1 postgres:16.9-bookworm "docker-entrypoint.s…" db 16 minutes ago Up 3 minutes (healthy) 5432/tcp +Python 3.12.10 + version +--------------------------------------------------------------------------------------------------------------------- + PostgreSQL 16.9 (Debian 16.9-1.pgdg120+1) on x86_64-pc-linux-gnu, compiled by gcc (Debian 12.2.0-14) 12.2.0, 64-bit +(1 row) + + shared_buffers +---------------- + 128MB +(1 row) + + work_mem +---------- + 4MB +(1 row) + + fsync +------- + on +(1 row) + + synchronous_commit +-------------------- + on +(1 row) + +Redis server v=7.4.3 sha=00000000:0 malloc=jemalloc-5.3.0 bits=64 build=33b32145ce3464c9 diff --git a/evidence/local_experiment.txt b/evidence/local_experiment.txt new file mode 100644 index 00000000..c18adf96 --- /dev/null +++ b/evidence/local_experiment.txt @@ -0,0 +1,2 @@ +docker compose run --rm -T --no-deps --user "1000:1000" -v "/home/kitsune/visotka/mtusi2026lab2/evidence:/app/evidence" api python -m scripts.experiment +PASS: measured two indexes, two queries, write cost; raw evidence saved diff --git a/evidence/local_expiry.txt b/evidence/local_expiry.txt new file mode 100644 index 00000000..6915c44f --- /dev/null +++ b/evidence/local_expiry.txt @@ -0,0 +1,11 @@ +bash scripts/test_expiry.sh + Container mtusi2026lab2-api-1 Recreate + Container mtusi2026lab2-api-1 Recreated + Container mtusi2026lab2-api-1 Starting + Container mtusi2026lab2-api-1 Started +API ready +PASS: short TTL expiry + Container mtusi2026lab2-api-1 Recreate + Container mtusi2026lab2-api-1 Recreated + Container mtusi2026lab2-api-1 Starting + Container mtusi2026lab2-api-1 Started diff --git a/evidence/local_final_smoke.txt b/evidence/local_final_smoke.txt new file mode 100644 index 00000000..404a2c60 --- /dev/null +++ b/evidence/local_final_smoke.txt @@ -0,0 +1,2 @@ +python3 tests/smoke.py --base-url "http://localhost:8080" +PASS: lab2 public API scenario; infrastructure and grading evidence remain separate. diff --git a/evidence/local_persistence.txt b/evidence/local_persistence.txt new file mode 100644 index 00000000..793b001d --- /dev/null +++ b/evidence/local_persistence.txt @@ -0,0 +1,3 @@ +python3 tests/resilience.py --mode persistence --action-script "scripts/restart.sh" --base-url "http://localhost:8080" +Executing explicit persistence hook; hook output suppressed to avoid leaking secrets. +PASS: persistence preserved confirmed data and existing session. Hook scope needs operator evidence. diff --git a/evidence/local_ready.txt b/evidence/local_ready.txt new file mode 100644 index 00000000..4589e0a9 --- /dev/null +++ b/evidence/local_ready.txt @@ -0,0 +1,2 @@ +BASE_URL="http://localhost:8080" python3 scripts/wait_ready.py +API ready diff --git a/evidence/local_services.txt b/evidence/local_services.txt new file mode 100644 index 00000000..36befc79 --- /dev/null +++ b/evidence/local_services.txt @@ -0,0 +1,4 @@ +NAME IMAGE COMMAND SERVICE CREATED STATUS PORTS +mtusi2026lab2-api-1 mtusi2026lab2-api "sh -c 'exec uvicorn…" api 10 seconds ago Up 8 seconds (healthy) 127.0.0.1:8080->8080/tcp +mtusi2026lab2-cache-1 redis:7.4.3-bookworm "docker-entrypoint.s…" cache 4 minutes ago Up 4 minutes (healthy) 6379/tcp +mtusi2026lab2-db-1 postgres:16.9-bookworm "docker-entrypoint.s…" db 4 minutes ago Up 4 minutes (healthy) 5432/tcp diff --git a/evidence/local_smoke.txt b/evidence/local_smoke.txt new file mode 100644 index 00000000..404a2c60 --- /dev/null +++ b/evidence/local_smoke.txt @@ -0,0 +1,2 @@ +python3 tests/smoke.py --base-url "http://localhost:8080" +PASS: lab2 public API scenario; infrastructure and grading evidence remain separate. diff --git a/evidence/local_smoke_after_failures.txt b/evidence/local_smoke_after_failures.txt new file mode 100644 index 00000000..404a2c60 --- /dev/null +++ b/evidence/local_smoke_after_failures.txt @@ -0,0 +1,2 @@ +python3 tests/smoke.py --base-url "http://localhost:8080" +PASS: lab2 public API scenario; infrastructure and grading evidence remain separate. diff --git a/evidence/local_student_checks.txt b/evidence/local_student_checks.txt new file mode 100644 index 00000000..f8833221 --- /dev/null +++ b/evidence/local_student_checks.txt @@ -0,0 +1,10 @@ +python3 student-tests/checks.py --base-url "http://localhost:8080" +PASS: registration race, invalid input, cursor scope, read-after-write, logout +python3 student-tests/test_api.py --base-url "http://localhost:8080" +PASS: malformed JSON/media type, duplicate username, blank message, outsider access, pagination +PASS: 10 clients created exactly 100 unique messages +docker compose exec -T api python student-tests/database.py +PASS: rollback of chat + members; migration reapplied twice +docker compose exec -T api python student-tests/test_lifecycle.py +PASS: SIGTERM completed in 0.166s (limit 10s); listener closed +PASS: user and existing Bearer session survived API process restart diff --git a/evidence/local_validate.txt b/evidence/local_validate.txt new file mode 100644 index 00000000..683be253 --- /dev/null +++ b/evidence/local_validate.txt @@ -0,0 +1,2 @@ +python3 scripts/validate_openapi.py +PASS: full OpenAPI 3.1 and JSON Schema validation; application NOT tested. diff --git a/evidence/restore_verification.json b/evidence/restore_verification.json new file mode 100644 index 00000000..99420990 --- /dev/null +++ b/evidence/restore_verification.json @@ -0,0 +1,11 @@ +{ + "counts": { + "users": 1, + "chats": 5, + "chat_members": 5, + "messages": 100000, + "sessions": 0 + }, + "sample_messages_matched": 5, + "status": "PASS" +} \ No newline at end of file diff --git a/evidence/track2_raw.json b/evidence/track2_raw.json new file mode 100644 index 00000000..f2632cfe --- /dev/null +++ b/evidence/track2_raw.json @@ -0,0 +1,8179 @@ +{ + "seed": 42, + "schema": "research_07e953c76ff9", + "message_count": 100000, + "sizes": [ + 70000, + 20000, + 9000, + 900, + 100 + ], + "repeats": 30, + "warmup": 5, + "concurrency": 1, + "platform": "Linux-5.15.146.1-microsoft-standard-WSL2-x86_64-with-glibc2.36", + "cpu_count": 16, + "results": [ + { + "latency_ms": [ + 2.9332960039027967, + 2.492156003427226, + 2.44496399682248, + 2.793653999106027, + 2.6591190035105683, + 2.498509995348286, + 2.3607940020156093, + 2.461465999658685, + 2.4835180010995828, + 2.8308539986028336, + 2.55062899668701, + 4.168685001786798, + 2.5676609948277473, + 2.392063004663214, + 2.454034998663701, + 2.5502139978925698, + 2.468002996465657, + 2.4023549995035864, + 2.2554099996341392, + 2.3462629978894256, + 2.2298859985312447, + 2.104266000969801, + 2.0256669959053397, + 2.440279997244943, + 2.396321993728634, + 2.5454530041315593, + 2.686854997591581, + 2.7375880017643794, + 2.991597000800539, + 3.2986019941745326 + ], + "p50_ms": 2.4878370022634044, + "p95_ms": 3.2986019941745326, + "p99_ms": 4.168685001786798, + "plan": { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 1605.65, + "Total Cost": 1605.77, + "Plan Rows": 51, + "Plan Width": 149, + "Actual Startup Time": 4.235, + "Actual Total Time": 4.245, + "Actual Rows": 51, + "Actual Loops": 1, + "Shared Hit Blocks": 268, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Sort", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 1585.4, + "Total Cost": 1607.24, + "Plan Rows": 8737, + "Plan Width": 149, + "Actual Startup Time": 3.261, + "Actual Total Time": 3.827, + "Actual Rows": 8151, + "Actual Loops": 1, + "Sort Key": [ + "created_at", + "id" + ], + "Sort Method": "quicksort", + "Sort Space Used": 2392, + "Sort Space Type": "Memory", + "Shared Hit Blocks": 268, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Index Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Scan Direction": "Forward", + "Index Name": "research_candidate", + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.29, + "Total Cost": 1013.43, + "Plan Rows": 8737, + "Plan Width": 149, + "Actual Startup Time": 0.008, + "Actual Total Time": 1.635, + "Actual Rows": 9000, + "Actual Loops": 1, + "Index Cond": "(chat_id = 'ba3c8454-879e-462b-be13-9d28f9fa80e3'::uuid)", + "Rows Removed by Index Recheck": 0, + "Shared Hit Blocks": 268, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + } + ] + } + ] + }, + "Planning": { + "Shared Hit Blocks": 0, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + }, + "Planning Time": 0.088, + "Triggers": [], + "Execution Time": 4.269 + }, + "index": "chat_only", + "method": "offset", + "chat_size": 9000, + "offset": 8099, + "index_bytes": 720896 + }, + { + "latency_ms": [ + 2.4778470033197664, + 2.3187690021586604, + 2.54048499482451, + 2.4636189991724677, + 2.334319993678946, + 3.2363580030505545, + 3.257050004322082, + 2.9444480023812503, + 3.19432499964023, + 3.238133002014365, + 3.107691998593509, + 3.3777090065996163, + 3.1378690036945045, + 2.8416499990271404, + 2.5984639942180365, + 2.39966600202024, + 2.747189995716326, + 2.727849998336751, + 2.3192259977804497, + 2.671109999937471, + 2.7719119971152395, + 2.5913600038620643, + 2.706035003939178, + 2.687302003323566, + 2.5829779988271184, + 2.665343003172893, + 2.3642390005989, + 2.3797159956302494, + 2.84601999737788, + 3.0608090019086376 + ], + "p50_ms": 2.696668503631372, + "p95_ms": 3.257050004322082, + "p99_ms": 3.3777090065996163, + "plan": { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 1275.07, + "Total Cost": 1275.2, + "Plan Rows": 51, + "Plan Width": 149, + "Actual Startup Time": 1.689, + "Actual Total Time": 1.697, + "Actual Rows": 51, + "Actual Loops": 1, + "Shared Hit Blocks": 268, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Sort", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 1275.07, + "Total Cost": 1291.4, + "Plan Rows": 6533, + "Plan Width": 149, + "Actual Startup Time": 1.688, + "Actual Total Time": 1.692, + "Actual Rows": 51, + "Actual Loops": 1, + "Sort Key": [ + "created_at", + "id" + ], + "Sort Method": "top-N heapsort", + "Sort Space Used": 40, + "Sort Space Type": "Memory", + "Shared Hit Blocks": 268, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Index Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Scan Direction": "Forward", + "Index Name": "research_candidate", + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.29, + "Total Cost": 1057.12, + "Plan Rows": 6533, + "Plan Width": 149, + "Actual Startup Time": 0.692, + "Actual Total Time": 1.591, + "Actual Rows": 900, + "Actual Loops": 1, + "Index Cond": "(chat_id = 'ba3c8454-879e-462b-be13-9d28f9fa80e3'::uuid)", + "Rows Removed by Index Recheck": 0, + "Filter": "(ROW(created_at, id) > ROW('2026-01-01 00:00:00.008099+00'::timestamp with time zone, 'dd696626-2777-4e36-86e3-a7247b012df2'::uuid))", + "Rows Removed by Filter": 8100, + "Shared Hit Blocks": 268, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + } + ] + } + ] + }, + "Planning": { + "Shared Hit Blocks": 0, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + }, + "Planning Time": 0.085, + "Triggers": [], + "Execution Time": 1.718 + }, + "index": "chat_only", + "method": "keyset", + "chat_size": 9000, + "offset": 8099, + "index_bytes": 720896 + }, + { + "latency_ms": [ + 0.4274239981896244, + 0.42965199827449396, + 0.44327700015855953, + 0.4323089960962534, + 0.43474900303408504, + 0.4515789987635799, + 0.45777400373481214, + 0.4501649964367971, + 0.4437379975570366, + 0.45906499872216955, + 0.45523799781221896, + 0.4629749964806251, + 0.53218499670038, + 0.4948010027874261, + 0.6942469990462996, + 0.6770530017092824, + 0.74962800135836, + 0.5685740034095943, + 0.5847460051882081, + 1.138405998062808, + 0.7588689986732788, + 0.7481490029022098, + 0.8184710022760555, + 0.8500039984937757, + 0.781280999945011, + 0.7839059981051832, + 0.7531359951826744, + 0.7285250030690804, + 0.8905529975891113, + 0.6722360049025156 + ], + "p50_ms": 0.5766600042989012, + "p95_ms": 0.8905529975891113, + "p99_ms": 1.138405998062808, + "plan": { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 49.39, + "Total Cost": 49.51, + "Plan Rows": 51, + "Plan Width": 149, + "Actual Startup Time": 0.047, + "Actual Total Time": 0.056, + "Actual Rows": 50, + "Actual Loops": 1, + "Shared Hit Blocks": 6, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Sort", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 49.26, + "Total Cost": 49.56, + "Plan Rows": 120, + "Plan Width": 149, + "Actual Startup Time": 0.04, + "Actual Total Time": 0.047, + "Actual Rows": 100, + "Actual Loops": 1, + "Sort Key": [ + "created_at", + "id" + ], + "Sort Method": "quicksort", + "Sort Space Used": 45, + "Sort Space Type": "Memory", + "Shared Hit Blocks": 6, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Index Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Scan Direction": "Forward", + "Index Name": "research_candidate", + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.29, + "Total Cost": 45.12, + "Plan Rows": 120, + "Plan Width": 149, + "Actual Startup Time": 0.007, + "Actual Total Time": 0.024, + "Actual Rows": 100, + "Actual Loops": 1, + "Index Cond": "(chat_id = '91d2ecd0-11c0-472f-a67a-c678efc87df1'::uuid)", + "Rows Removed by Index Recheck": 0, + "Shared Hit Blocks": 6, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + } + ] + } + ] + }, + "Planning": { + "Shared Hit Blocks": 0, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + }, + "Planning Time": 0.048, + "Triggers": [], + "Execution Time": 0.071 + }, + "index": "chat_only", + "method": "offset", + "chat_size": 100, + "offset": 49, + "index_bytes": 720896 + }, + { + "latency_ms": [ + 0.7678610054426827, + 0.7712570004514419, + 0.7741439985693432, + 0.6772380002075806, + 0.6534919957630336, + 0.7898530020611361, + 0.8402800012845546, + 0.8437039941782132, + 0.8286559968837537, + 0.711382002918981, + 0.670166002237238, + 0.6444460013881326, + 0.6193040026118979, + 0.6110510003054515, + 0.6106130022089928, + 0.6508020014734939, + 0.6121089973021299, + 0.5770580028183758, + 0.5734530059271492, + 0.5541209975490347, + 0.9045359984156676, + 0.8367720001842827, + 0.6702710015815683, + 0.6050559968571179, + 0.6048360010026954, + 0.5914320063311607, + 0.5780350038548931, + 0.579988001845777, + 0.5587679988821037, + 0.5799729988211766 + ], + "p50_ms": 0.6476240014308132, + "p95_ms": 0.8437039941782132, + "p99_ms": 0.9045359984156676, + "plan": { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 49.72, + "Total Cost": 49.85, + "Plan Rows": 51, + "Plan Width": 149, + "Actual Startup Time": 0.047, + "Actual Total Time": 0.056, + "Actual Rows": 50, + "Actual Loops": 1, + "Shared Hit Blocks": 6, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Sort", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 49.72, + "Total Cost": 50.02, + "Plan Rows": 120, + "Plan Width": 149, + "Actual Startup Time": 0.046, + "Actual Total Time": 0.05, + "Actual Rows": 50, + "Actual Loops": 1, + "Sort Key": [ + "created_at", + "id" + ], + "Sort Method": "quicksort", + "Sort Space Used": 35, + "Sort Space Type": "Memory", + "Shared Hit Blocks": 6, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Index Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Scan Direction": "Forward", + "Index Name": "research_candidate", + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.29, + "Total Cost": 45.72, + "Plan Rows": 120, + "Plan Width": 149, + "Actual Startup Time": 0.022, + "Actual Total Time": 0.035, + "Actual Rows": 50, + "Actual Loops": 1, + "Index Cond": "(chat_id = '91d2ecd0-11c0-472f-a67a-c678efc87df1'::uuid)", + "Rows Removed by Index Recheck": 0, + "Filter": "(ROW(created_at, id) > ROW('2026-01-01 00:00:00.000049+00'::timestamp with time zone, '9d89ca28-6a7d-47bd-b745-ab58b7af585f'::uuid))", + "Rows Removed by Filter": 50, + "Shared Hit Blocks": 6, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + } + ] + } + ] + }, + "Planning": { + "Shared Hit Blocks": 0, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + }, + "Planning Time": 0.074, + "Triggers": [], + "Execution Time": 0.074 + }, + "index": "chat_only", + "method": "keyset", + "chat_size": 100, + "offset": 49, + "index_bytes": 720896 + }, + { + "latency_ms": [ + 2.184376004152, + 2.467106001859065, + 2.765254001133144, + 2.2942930008866824, + 2.2308010011329316, + 2.0747399976244196, + 1.940392998221796, + 1.9317900005262345, + 2.82547899405472, + 2.6025749975815415, + 2.1823779970873147, + 2.0438869978534058, + 2.09984699904453, + 2.5092019932344556, + 2.582421999250073, + 3.4791040015988983, + 3.094586994848214, + 2.871755001251586, + 2.56603099842323, + 2.2859320015413687, + 2.233109997177962, + 2.77393600117648, + 2.590948002762161, + 3.3019449983839877, + 2.8339370037429035, + 2.384875995630864, + 2.164200006518513, + 2.0150260024820454, + 2.445530997647438, + 2.6879159995587543 + ], + "p50_ms": 2.4563184997532517, + "p95_ms": 3.3019449983839877, + "p99_ms": 3.4791040015988983, + "plan": { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 1596.65, + "Total Cost": 1596.77, + "Plan Rows": 51, + "Plan Width": 149, + "Actual Startup Time": 2.785, + "Actual Total Time": 2.792, + "Actual Rows": 51, + "Actual Loops": 1, + "Shared Hit Blocks": 268, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Sort", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 1585.4, + "Total Cost": 1607.24, + "Plan Rows": 8737, + "Plan Width": 149, + "Actual Startup Time": 2.369, + "Actual Total Time": 2.612, + "Actual Rows": 4551, + "Actual Loops": 1, + "Sort Key": [ + "created_at", + "id" + ], + "Sort Method": "quicksort", + "Sort Space Used": 2392, + "Sort Space Type": "Memory", + "Shared Hit Blocks": 268, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Index Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Scan Direction": "Forward", + "Index Name": "research_candidate", + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.29, + "Total Cost": 1013.43, + "Plan Rows": 8737, + "Plan Width": 149, + "Actual Startup Time": 0.009, + "Actual Total Time": 1.225, + "Actual Rows": 9000, + "Actual Loops": 1, + "Index Cond": "(chat_id = 'ba3c8454-879e-462b-be13-9d28f9fa80e3'::uuid)", + "Rows Removed by Index Recheck": 0, + "Shared Hit Blocks": 268, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + } + ] + } + ] + }, + "Planning": { + "Shared Hit Blocks": 0, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + }, + "Planning Time": 0.062, + "Triggers": [], + "Execution Time": 2.807 + }, + "index": "chat_only", + "method": "offset", + "chat_size": 9000, + "offset": 4499, + "index_bytes": 720896 + }, + { + "latency_ms": [ + 3.937052999390289, + 2.4274569950648583, + 2.1901060026721098, + 2.030636998824775, + 2.01285800721962, + 2.0070820028195158, + 2.2034900030121207, + 2.2334789973683655, + 2.263075999508146, + 2.1068540008855052, + 2.260754001326859, + 2.5655930003267713, + 2.6175140010309406, + 3.9761329971952364, + 3.508714995405171, + 3.6120270015089773, + 3.0497920015477575, + 2.78778700158, + 3.090464000706561, + 2.7495140020619147, + 2.6568190005491488, + 2.31048100249609, + 2.1982850012136623, + 2.0989770055166446, + 2.2383090035873465, + 3.050692001124844, + 2.2530459973495454, + 2.1362909974413924, + 2.165146994229872, + 2.1631729978253134 + ], + "p50_ms": 2.2619150004175026, + "p95_ms": 3.937052999390289, + "p99_ms": 3.9761329971952364, + "plan": { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 1306.1, + "Total Cost": 1306.23, + "Plan Rows": 51, + "Plan Width": 149, + "Actual Startup Time": 2.313, + "Actual Total Time": 2.323, + "Actual Rows": 51, + "Actual Loops": 1, + "Shared Hit Blocks": 268, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Sort", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 1306.1, + "Total Cost": 1324.76, + "Plan Rows": 7463, + "Plan Width": 149, + "Actual Startup Time": 2.312, + "Actual Total Time": 2.317, + "Actual Rows": 51, + "Actual Loops": 1, + "Sort Key": [ + "created_at", + "id" + ], + "Sort Method": "top-N heapsort", + "Sort Space Used": 38, + "Sort Space Type": "Memory", + "Shared Hit Blocks": 268, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Index Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Scan Direction": "Forward", + "Index Name": "research_candidate", + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.29, + "Total Cost": 1057.12, + "Plan Rows": 7463, + "Plan Width": 149, + "Actual Startup Time": 0.654, + "Actual Total Time": 1.814, + "Actual Rows": 4500, + "Actual Loops": 1, + "Index Cond": "(chat_id = 'ba3c8454-879e-462b-be13-9d28f9fa80e3'::uuid)", + "Rows Removed by Index Recheck": 0, + "Filter": "(ROW(created_at, id) > ROW('2026-01-01 00:00:00.004499+00'::timestamp with time zone, 'fcd4a921-64ed-4ba5-a738-4de99f71a77f'::uuid))", + "Rows Removed by Filter": 4500, + "Shared Hit Blocks": 268, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + } + ] + } + ] + }, + "Planning": { + "Shared Hit Blocks": 0, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + }, + "Planning Time": 0.048, + "Triggers": [], + "Execution Time": 2.339 + }, + "index": "chat_only", + "method": "keyset", + "chat_size": 9000, + "offset": 4499, + "index_bytes": 720896 + }, + { + "latency_ms": [ + 1.9612719988799654, + 2.0425369948497973, + 2.38005600112956, + 2.4075300025288016, + 2.5829809965216555, + 2.6166379975620657, + 2.3579650005558506, + 2.412736001133453, + 2.4307220010086894, + 2.4215310040744953, + 2.6278110017301515, + 2.5948719994630665, + 2.5293189974036068, + 2.6123700008611195, + 2.2664039934170432, + 2.013825003814418, + 1.9491260027280077, + 2.4281649966724217, + 2.001050001126714, + 2.223586998297833, + 2.320088002306875, + 2.42902799800504, + 2.4165129943867214, + 2.4270379944937304, + 3.888979998009745, + 2.7157609947607853, + 2.561713001341559, + 1.8977340005221777, + 1.6882609997992404, + 1.5956689967424609 + ], + "p50_ms": 2.4146244977600873, + "p95_ms": 2.7157609947607853, + "p99_ms": 3.888979998009745, + "plan": { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 1306.14, + "Total Cost": 1306.27, + "Plan Rows": 51, + "Plan Width": 149, + "Actual Startup Time": 1.837, + "Actual Total Time": 1.845, + "Actual Rows": 51, + "Actual Loops": 1, + "Shared Hit Blocks": 268, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Sort", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 1306.14, + "Total Cost": 1327.98, + "Plan Rows": 8737, + "Plan Width": 149, + "Actual Startup Time": 1.836, + "Actual Total Time": 1.84, + "Actual Rows": 52, + "Actual Loops": 1, + "Sort Key": [ + "created_at", + "id" + ], + "Sort Method": "top-N heapsort", + "Sort Space Used": 41, + "Sort Space Type": "Memory", + "Shared Hit Blocks": 268, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Index Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Scan Direction": "Forward", + "Index Name": "research_candidate", + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.29, + "Total Cost": 1013.43, + "Plan Rows": 8737, + "Plan Width": 149, + "Actual Startup Time": 0.006, + "Actual Total Time": 1.085, + "Actual Rows": 9000, + "Actual Loops": 1, + "Index Cond": "(chat_id = 'ba3c8454-879e-462b-be13-9d28f9fa80e3'::uuid)", + "Rows Removed by Index Recheck": 0, + "Shared Hit Blocks": 268, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + } + ] + } + ] + }, + "Planning": { + "Shared Hit Blocks": 0, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + }, + "Planning Time": 0.036, + "Triggers": [], + "Execution Time": 1.856 + }, + "index": "chat_only", + "method": "offset", + "chat_size": 9000, + "offset": 0, + "index_bytes": 720896 + }, + { + "latency_ms": [ + 2.862296998500824, + 2.6339129981352016, + 2.6631979999365285, + 2.4217790050897747, + 2.2242790000746027, + 2.24591600272106, + 2.1885589958401397, + 2.158871997380629, + 2.6353560024290346, + 2.536463005526457, + 2.291873999638483, + 2.352342002268415, + 2.4089060025289655, + 2.869002004445065, + 3.8515539999934845, + 2.4792569965939038, + 2.3092429983080365, + 2.3735689974273555, + 2.355088996409904, + 2.2720369961461984, + 3.2767029988463037, + 2.7617329978966154, + 2.4195139994844794, + 2.351659000851214, + 2.3141959973145276, + 2.252075995784253, + 2.3372510040644556, + 3.6258679974707775, + 2.6100090035470203, + 2.7271009967080317 + ], + "p50_ms": 2.4142100010067225, + "p95_ms": 3.6258679974707775, + "p99_ms": 3.8515539999934845, + "plan": { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 1348.57, + "Total Cost": 1348.7, + "Plan Rows": 51, + "Plan Width": 149, + "Actual Startup Time": 2.552, + "Actual Total Time": 2.561, + "Actual Rows": 51, + "Actual Loops": 1, + "Shared Hit Blocks": 268, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Sort", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 1348.57, + "Total Cost": 1370.41, + "Plan Rows": 8736, + "Plan Width": 149, + "Actual Startup Time": 2.551, + "Actual Total Time": 2.556, + "Actual Rows": 51, + "Actual Loops": 1, + "Sort Key": [ + "created_at", + "id" + ], + "Sort Method": "top-N heapsort", + "Sort Space Used": 41, + "Sort Space Type": "Memory", + "Shared Hit Blocks": 268, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Index Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Scan Direction": "Forward", + "Index Name": "research_candidate", + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.29, + "Total Cost": 1057.12, + "Plan Rows": 8736, + "Plan Width": 149, + "Actual Startup Time": 0.008, + "Actual Total Time": 1.696, + "Actual Rows": 8999, + "Actual Loops": 1, + "Index Cond": "(chat_id = 'ba3c8454-879e-462b-be13-9d28f9fa80e3'::uuid)", + "Rows Removed by Index Recheck": 0, + "Filter": "(ROW(created_at, id) > ROW('2026-01-01 00:00:00+00'::timestamp with time zone, 'cab44f87-4a3f-4d22-80f4-c4d283331a8c'::uuid))", + "Rows Removed by Filter": 1, + "Shared Hit Blocks": 268, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + } + ] + } + ] + }, + "Planning": { + "Shared Hit Blocks": 0, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + }, + "Planning Time": 0.052, + "Triggers": [], + "Execution Time": 2.575 + }, + "index": "chat_only", + "method": "keyset", + "chat_size": 9000, + "offset": 0, + "index_bytes": 720896 + }, + { + "latency_ms": [ + 0.3005420003319159, + 0.2765460012597032, + 0.28789199859602377, + 0.30523700115736574, + 0.29766100487904623, + 0.2954359952127561, + 0.29591299971798435, + 0.2917159945354797, + 0.42377199861221015, + 0.380418001441285, + 0.3417900006752461, + 0.4774609988089651, + 0.591322997934185, + 0.49278999358648434, + 0.4626260051736608, + 0.6013419988448732, + 0.5835349948029034, + 0.5065060031483881, + 0.4603460038197227, + 0.5845170016982593, + 0.48272599815391004, + 0.39905699668452144, + 0.4478510018088855, + 0.3506760040181689, + 0.31925200164550915, + 0.3150080010527745, + 0.31581399525748566, + 0.3623259981395677, + 0.6282929971348494, + 0.3989249962614849 + ], + "p50_ms": 0.38967149885138497, + "p95_ms": 0.6013419988448732, + "p99_ms": 0.6282929971348494, + "plan": { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 49.49, + "Total Cost": 49.56, + "Plan Rows": 30, + "Plan Width": 149, + "Actual Startup Time": 0.053, + "Actual Total Time": 0.056, + "Actual Rows": 10, + "Actual Loops": 1, + "Shared Hit Blocks": 6, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Sort", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 49.26, + "Total Cost": 49.56, + "Plan Rows": 120, + "Plan Width": 149, + "Actual Startup Time": 0.041, + "Actual Total Time": 0.049, + "Actual Rows": 100, + "Actual Loops": 1, + "Sort Key": [ + "created_at", + "id" + ], + "Sort Method": "quicksort", + "Sort Space Used": 45, + "Sort Space Type": "Memory", + "Shared Hit Blocks": 6, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Index Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Scan Direction": "Forward", + "Index Name": "research_candidate", + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.29, + "Total Cost": 45.12, + "Plan Rows": 120, + "Plan Width": 149, + "Actual Startup Time": 0.006, + "Actual Total Time": 0.024, + "Actual Rows": 100, + "Actual Loops": 1, + "Index Cond": "(chat_id = '91d2ecd0-11c0-472f-a67a-c678efc87df1'::uuid)", + "Rows Removed by Index Recheck": 0, + "Shared Hit Blocks": 6, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + } + ] + } + ] + }, + "Planning": { + "Shared Hit Blocks": 0, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + }, + "Planning Time": 0.072, + "Triggers": [], + "Execution Time": 0.069 + }, + "index": "chat_only", + "method": "offset", + "chat_size": 100, + "offset": 89, + "index_bytes": 720896 + }, + { + "latency_ms": [ + 0.3370869962964207, + 0.35407699760980904, + 0.33449899638071656, + 0.35753300471697, + 0.3333390050102025, + 0.38239800051087514, + 0.3555429939297028, + 0.3360859991516918, + 0.35625899909064174, + 0.36017200181959197, + 0.3596519964048639, + 0.3360129994689487, + 0.3232320013921708, + 0.32094599737320095, + 0.42273000144632533, + 0.6362549975165166, + 0.9846550019574352, + 1.0097960039274767, + 0.9949430022970773, + 0.9992179984692484, + 0.8156199983204715, + 0.907034998817835, + 0.8735890005482361, + 0.561731998459436, + 0.4822990013053641, + 0.6594070000573993, + 0.556507999135647, + 0.46771299821557477, + 0.5485630026669241, + 0.45453000348061323 + ], + "p50_ms": 0.4386300024634693, + "p95_ms": 0.9992179984692484, + "p99_ms": 1.0097960039274767, + "plan": { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 49.72, + "Total Cost": 49.85, + "Plan Rows": 51, + "Plan Width": 149, + "Actual Startup Time": 0.032, + "Actual Total Time": 0.034, + "Actual Rows": 10, + "Actual Loops": 1, + "Shared Hit Blocks": 6, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Sort", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 49.72, + "Total Cost": 50.02, + "Plan Rows": 120, + "Plan Width": 149, + "Actual Startup Time": 0.031, + "Actual Total Time": 0.033, + "Actual Rows": 10, + "Actual Loops": 1, + "Sort Key": [ + "created_at", + "id" + ], + "Sort Method": "quicksort", + "Sort Space Used": 26, + "Sort Space Type": "Memory", + "Shared Hit Blocks": 6, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Index Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Scan Direction": "Forward", + "Index Name": "research_candidate", + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.29, + "Total Cost": 45.72, + "Plan Rows": 120, + "Plan Width": 149, + "Actual Startup Time": 0.024, + "Actual Total Time": 0.027, + "Actual Rows": 10, + "Actual Loops": 1, + "Index Cond": "(chat_id = '91d2ecd0-11c0-472f-a67a-c678efc87df1'::uuid)", + "Rows Removed by Index Recheck": 0, + "Filter": "(ROW(created_at, id) > ROW('2026-01-01 00:00:00.000089+00'::timestamp with time zone, '5146cf63-b19e-468e-9b3e-499c00b728e5'::uuid))", + "Rows Removed by Filter": 90, + "Shared Hit Blocks": 6, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + } + ] + } + ] + }, + "Planning": { + "Shared Hit Blocks": 0, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + }, + "Planning Time": 0.074, + "Triggers": [], + "Execution Time": 0.048 + }, + "index": "chat_only", + "method": "keyset", + "chat_size": 100, + "offset": 89, + "index_bytes": 720896 + }, + { + "latency_ms": [ + 0.598823004111182, + 0.5698740060324781, + 0.6699920049868524, + 5.059312999946997, + 0.8844800031511113, + 0.6572950005647726, + 0.5874439957551658, + 0.516135994985234, + 0.546401999599766, + 0.5560040008276701, + 0.5941260023973882, + 0.583496002946049, + 0.596083998971153, + 0.5589850043179467, + 0.4958829958923161, + 0.5575680042966269, + 0.9109619932132773, + 1.6229650063905865, + 0.6353210046654567, + 1.596647998667322, + 3.030762993148528, + 1.0368110015406273, + 0.6908180002938025, + 0.5997519983793609, + 0.5697189990314655, + 0.559097999939695, + 0.5273599963402376, + 0.506404998304788, + 0.7197630038717762, + 0.5530940034077503 + ], + "p50_ms": 0.5951050006842706, + "p95_ms": 3.030762993148528, + "p99_ms": 5.059312999946997, + "plan": { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 49.14, + "Total Cost": 49.27, + "Plan Rows": 51, + "Plan Width": 149, + "Actual Startup Time": 0.035, + "Actual Total Time": 0.043, + "Actual Rows": 51, + "Actual Loops": 1, + "Shared Hit Blocks": 6, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Sort", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 49.14, + "Total Cost": 49.44, + "Plan Rows": 120, + "Plan Width": 149, + "Actual Startup Time": 0.035, + "Actual Total Time": 0.038, + "Actual Rows": 52, + "Actual Loops": 1, + "Sort Key": [ + "created_at", + "id" + ], + "Sort Method": "quicksort", + "Sort Space Used": 45, + "Sort Space Type": "Memory", + "Shared Hit Blocks": 6, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Index Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Scan Direction": "Forward", + "Index Name": "research_candidate", + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.29, + "Total Cost": 45.12, + "Plan Rows": 120, + "Plan Width": 149, + "Actual Startup Time": 0.008, + "Actual Total Time": 0.022, + "Actual Rows": 100, + "Actual Loops": 1, + "Index Cond": "(chat_id = '91d2ecd0-11c0-472f-a67a-c678efc87df1'::uuid)", + "Rows Removed by Index Recheck": 0, + "Shared Hit Blocks": 6, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + } + ] + } + ] + }, + "Planning": { + "Shared Hit Blocks": 0, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + }, + "Planning Time": 0.051, + "Triggers": [], + "Execution Time": 0.056 + }, + "index": "chat_only", + "method": "offset", + "chat_size": 100, + "offset": 0, + "index_bytes": 720896 + }, + { + "latency_ms": [ + 1.0329880024073645, + 0.6586539966519922, + 0.6629119961871766, + 0.664334002067335, + 0.6466880004154518, + 0.6301419998635538, + 0.8638819999760017, + 0.6049889998394065, + 1.113318998250179, + 0.8014380000531673, + 0.61811700288672, + 0.4745400001411326, + 0.4576089995680377, + 0.4293239981052466, + 0.45016800140729174, + 0.4528939971351065, + 0.5772750009782612, + 0.5759390041930601, + 0.45857900113333017, + 0.4279080021660775, + 0.4195990040898323, + 0.4135189956286922, + 0.4206259982311167, + 0.40929500391939655, + 0.40624199755256996, + 0.40589700074633583, + 0.403496997023467, + 0.4066239998792298, + 0.4073939999216236, + 0.4310119984438643 + ], + "p50_ms": 0.4580940003506839, + "p95_ms": 1.0329880024073645, + "p99_ms": 1.113318998250179, + "plan": { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 49.72, + "Total Cost": 49.85, + "Plan Rows": 51, + "Plan Width": 149, + "Actual Startup Time": 0.045, + "Actual Total Time": 0.052, + "Actual Rows": 51, + "Actual Loops": 1, + "Shared Hit Blocks": 6, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Sort", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 49.72, + "Total Cost": 50.02, + "Plan Rows": 120, + "Plan Width": 149, + "Actual Startup Time": 0.044, + "Actual Total Time": 0.047, + "Actual Rows": 51, + "Actual Loops": 1, + "Sort Key": [ + "created_at", + "id" + ], + "Sort Method": "quicksort", + "Sort Space Used": 45, + "Sort Space Type": "Memory", + "Shared Hit Blocks": 6, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Index Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Scan Direction": "Forward", + "Index Name": "research_candidate", + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.29, + "Total Cost": 45.72, + "Plan Rows": 120, + "Plan Width": 149, + "Actual Startup Time": 0.011, + "Actual Total Time": 0.031, + "Actual Rows": 99, + "Actual Loops": 1, + "Index Cond": "(chat_id = '91d2ecd0-11c0-472f-a67a-c678efc87df1'::uuid)", + "Rows Removed by Index Recheck": 0, + "Filter": "(ROW(created_at, id) > ROW('2026-01-01 00:00:00+00'::timestamp with time zone, '04e85f58-1262-43bd-b37b-6df8662de82a'::uuid))", + "Rows Removed by Filter": 1, + "Shared Hit Blocks": 6, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + } + ] + } + ] + }, + "Planning": { + "Shared Hit Blocks": 0, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + }, + "Planning Time": 0.066, + "Triggers": [], + "Execution Time": 0.066 + }, + "index": "chat_only", + "method": "keyset", + "chat_size": 100, + "offset": 0, + "index_bytes": 720896 + }, + { + "latency_ms": [ + 9.4205069981399, + 9.249729999282863, + 9.472175996052101, + 10.428160996525548, + 9.501301996351685, + 10.364886999013834, + 9.76448500296101, + 10.93680600024527, + 10.002451999753248, + 10.970152005029377, + 10.209026004304178, + 9.259946004021913, + 9.370835003210232, + 9.404868993442506, + 9.476088001974858, + 11.565658998733852, + 9.71719999506604, + 9.961191004549619, + 10.346868002670817, + 9.764066002389882, + 11.534651996043976, + 9.910617001878563, + 9.01110700215213, + 9.837010999035556, + 9.273150004446507, + 9.872804002952762, + 10.084624998853542, + 12.10824399458943, + 9.547705994918942, + 10.086039001180325 + ], + "p50_ms": 9.854907500994159, + "p95_ms": 11.565658998733852, + "p99_ms": 12.10824399458943, + "plan": { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 2985.13, + "Total Cost": 2985.25, + "Plan Rows": 51, + "Plan Width": 149, + "Actual Startup Time": 15.188, + "Actual Total Time": 15.199, + "Actual Rows": 51, + "Actual Loops": 1, + "Shared Hit Blocks": 535, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 399, + "Temp Written Blocks": 400, + "Plans": [ + { + "Node Type": "Sort", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 2940.13, + "Total Cost": 2990.63, + "Plan Rows": 20200, + "Plan Width": 149, + "Actual Startup Time": 11.953, + "Actual Total Time": 14.299, + "Actual Rows": 18051, + "Actual Loops": 1, + "Sort Key": [ + "created_at", + "id" + ], + "Sort Method": "external merge", + "Sort Space Used": 3192, + "Sort Space Type": "Disk", + "Shared Hit Blocks": 535, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 399, + "Temp Written Blocks": 400, + "Plans": [ + { + "Node Type": "Index Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Scan Direction": "Forward", + "Index Name": "research_candidate", + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.29, + "Total Cost": 1495.62, + "Plan Rows": 20200, + "Plan Width": 149, + "Actual Startup Time": 0.017, + "Actual Total Time": 4.047, + "Actual Rows": 20000, + "Actual Loops": 1, + "Index Cond": "(chat_id = 'f8028b31-6ab5-45df-9cea-f4737a46ecf7'::uuid)", + "Rows Removed by Index Recheck": 0, + "Shared Hit Blocks": 535, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + } + ] + } + ] + }, + "Planning": { + "Shared Hit Blocks": 0, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + }, + "Planning Time": 0.106, + "Triggers": [], + "Execution Time": 15.707 + }, + "index": "chat_only", + "method": "offset", + "chat_size": 20000, + "offset": 17999, + "index_bytes": 720896 + }, + { + "latency_ms": [ + 4.261314003088046, + 4.648350004572421, + 4.014530997665133, + 3.658133005956188, + 4.231592996802647, + 4.727395004010759, + 4.7754400002304465, + 4.8091040007420816, + 5.315185997460503, + 4.88438500178745, + 6.1111729955882765, + 5.44852799794171, + 5.477778002386913, + 8.23163000313798, + 5.321203003404662, + 4.824996001843829, + 5.38713200512575, + 4.416215997480322, + 3.925759003323037, + 3.8890720024937764, + 3.8805280055385083, + 3.6985109982197173, + 4.067078996740747, + 3.8766770012443885, + 3.9095530009944923, + 3.688568001962267, + 3.735730002517812, + 3.904292003426235, + 4.480981995584443, + 4.051017000165302 + ], + "p50_ms": 4.338765000284184, + "p95_ms": 6.1111729955882765, + "p99_ms": 8.23163000313798, + "plan": { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 1961.77, + "Total Cost": 1961.89, + "Plan Rows": 51, + "Plan Width": 149, + "Actual Startup Time": 3.43, + "Actual Total Time": 3.438, + "Actual Rows": 51, + "Actual Loops": 1, + "Shared Hit Blocks": 535, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Sort", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 1961.77, + "Total Cost": 1989.13, + "Plan Rows": 10945, + "Plan Width": 149, + "Actual Startup Time": 3.429, + "Actual Total Time": 3.432, + "Actual Rows": 51, + "Actual Loops": 1, + "Sort Key": [ + "created_at", + "id" + ], + "Sort Method": "top-N heapsort", + "Sort Space Used": 42, + "Sort Space Type": "Memory", + "Shared Hit Blocks": 535, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Index Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Scan Direction": "Forward", + "Index Name": "research_candidate", + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.29, + "Total Cost": 1596.62, + "Plan Rows": 10945, + "Plan Width": 149, + "Actual Startup Time": 0.012, + "Actual Total Time": 3.241, + "Actual Rows": 2000, + "Actual Loops": 1, + "Index Cond": "(chat_id = 'f8028b31-6ab5-45df-9cea-f4737a46ecf7'::uuid)", + "Rows Removed by Index Recheck": 0, + "Filter": "(ROW(created_at, id) > ROW('2026-01-01 00:00:00.017999+00'::timestamp with time zone, '9c0bfcbc-8dae-4753-8262-16d0bb97d8b3'::uuid))", + "Rows Removed by Filter": 18000, + "Shared Hit Blocks": 535, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + } + ] + } + ] + }, + "Planning": { + "Shared Hit Blocks": 0, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + }, + "Planning Time": 0.067, + "Triggers": [], + "Execution Time": 3.455 + }, + "index": "chat_only", + "method": "keyset", + "chat_size": 20000, + "offset": 17999, + "index_bytes": 720896 + }, + { + "latency_ms": [ + 34.63713500241283, + 34.43487200274831, + 34.153469001466874, + 35.80431499722181, + 39.33017100644065, + 40.16801300167572, + 41.81278000032762, + 35.6716559981578, + 37.57531200244557, + 33.01551599724917, + 36.881690997688565, + 37.0182400001795, + 42.53737199906027, + 42.63752699625911, + 38.08565300278133, + 44.60074700182304, + 46.87009500048589, + 47.10983899713028, + 34.76915500505129, + 36.33114800322801, + 37.0659850013908, + 43.20292700140271, + 40.137877003871836, + 40.0669239970739, + 43.25593399698846, + 44.53200800344348, + 37.9095940006664, + 39.885926998977084, + 40.99661199870752, + 44.01303899794584 + ], + "p50_ms": 39.60804900270887, + "p95_ms": 46.87009500048589, + "p99_ms": 47.10983899713028, + "plan": { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 14573.41, + "Total Cost": 14573.54, + "Plan Rows": 51, + "Plan Width": 149, + "Actual Startup Time": 45.476, + "Actual Total Time": 45.491, + "Actual Rows": 51, + "Actual Loops": 1, + "Shared Hit Blocks": 2264, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 1369, + "Temp Written Blocks": 1403, + "Plans": [ + { + "Node Type": "Sort", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 14415.91, + "Total Cost": 14590.95, + "Plan Rows": 70013, + "Plan Width": 149, + "Actual Startup Time": 34.137, + "Actual Total Time": 42.748, + "Actual Rows": 63051, + "Actual Loops": 1, + "Sort Key": [ + "created_at", + "id" + ], + "Sort Method": "external merge", + "Sort Space Used": 11192, + "Sort Space Type": "Disk", + "Shared Hit Blocks": 2264, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 1369, + "Temp Written Blocks": 1403, + "Plans": [ + { + "Node Type": "Seq Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.0, + "Total Cost": 3514.0, + "Plan Rows": 70013, + "Plan Width": 149, + "Actual Startup Time": 0.009, + "Actual Total Time": 12.79, + "Actual Rows": 70000, + "Actual Loops": 1, + "Filter": "(chat_id = '48c201d1-9d95-4ce9-90f7-019e28b812ba'::uuid)", + "Rows Removed by Filter": 30000, + "Shared Hit Blocks": 2264, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + } + ] + } + ] + }, + "Planning": { + "Shared Hit Blocks": 0, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + }, + "Planning Time": 0.087, + "Triggers": [], + "Execution Time": 47.173 + }, + "index": "chat_only", + "method": "offset", + "chat_size": 70000, + "offset": 62999, + "index_bytes": 720896 + }, + { + "latency_ms": [ + 12.058059000992216, + 12.951470002008136, + 11.591551003220957, + 15.607344001182355, + 15.993441003956832, + 16.390892000345048, + 18.424710993713234, + 13.648268999531865, + 12.271364001207985, + 12.186852996819653, + 11.533498000062536, + 12.640101995202713, + 12.5121959936223, + 11.346266001055483, + 12.252035005076323, + 11.058803000196349, + 13.08500499726506, + 12.173347000498325, + 13.00131699827034, + 12.636254999961238, + 14.020114002050832, + 15.603750005539041, + 16.630414997052867, + 16.37586400465807, + 15.494658997340593, + 11.186244002601597, + 12.428333997377194, + 11.986921999778133, + 11.732787999790162, + 11.64040999719873 + ], + "p50_ms": 12.574225496791769, + "p95_ms": 16.630414997052867, + "p99_ms": 18.424710993713234, + "plan": { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 4098.71, + "Total Cost": 4098.84, + "Plan Rows": 51, + "Plan Width": 149, + "Actual Startup Time": 11.822, + "Actual Total Time": 11.831, + "Actual Rows": 51, + "Actual Loops": 1, + "Shared Hit Blocks": 1622, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Sort", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 4098.71, + "Total Cost": 4110.49, + "Plan Rows": 4712, + "Plan Width": 149, + "Actual Startup Time": 11.821, + "Actual Total Time": 11.825, + "Actual Rows": 51, + "Actual Loops": 1, + "Sort Key": [ + "created_at", + "id" + ], + "Sort Method": "top-N heapsort", + "Sort Space Used": 43, + "Sort Space Type": "Memory", + "Shared Hit Blocks": 1622, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Index Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Scan Direction": "Forward", + "Index Name": "research_candidate", + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.29, + "Total Cost": 3941.51, + "Plan Rows": 4712, + "Plan Width": 149, + "Actual Startup Time": 8.648, + "Actual Total Time": 11.19, + "Actual Rows": 7000, + "Actual Loops": 1, + "Index Cond": "(chat_id = '48c201d1-9d95-4ce9-90f7-019e28b812ba'::uuid)", + "Rows Removed by Index Recheck": 0, + "Filter": "(ROW(created_at, id) > ROW('2026-01-01 00:00:00.062999+00'::timestamp with time zone, 'ae27a533-b7cc-47a6-bc0d-a2e0d963649e'::uuid))", + "Rows Removed by Filter": 63000, + "Shared Hit Blocks": 1622, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + } + ] + } + ] + }, + "Planning": { + "Shared Hit Blocks": 0, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + }, + "Planning Time": 0.089, + "Triggers": [], + "Execution Time": 11.852 + }, + "index": "chat_only", + "method": "keyset", + "chat_size": 70000, + "offset": 62999, + "index_bytes": 720896 + }, + { + "latency_ms": [ + 0.7881920028012246, + 0.6049770017853007, + 0.5350309947971255, + 0.4945290056639351, + 0.5171439988771453, + 0.5596119954134338, + 0.5148639975232072, + 0.5024729980505072, + 0.5102330032968894, + 0.5019460004405119, + 0.6239799986360595, + 0.7843969942769036, + 0.7025629965937696, + 0.6618939951295033, + 0.7479399937437847, + 0.6962549960007891, + 0.5681449983967468, + 0.5500029947143048, + 0.5194170007598586, + 0.5440219974843785, + 0.5076630041003227, + 0.6095860007917508, + 0.6360440020216629, + 0.5146050025359727, + 0.5152049998287112, + 0.5007959989598021, + 0.49014599790098146, + 0.541631001397036, + 0.5172059973119758, + 0.5251959955785424 + ], + "p50_ms": 0.5383309980970807, + "p95_ms": 0.7843969942769036, + "p99_ms": 0.7881920028012246, + "plan": { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 293.69, + "Total Cost": 293.82, + "Plan Rows": 51, + "Plan Width": 149, + "Actual Startup Time": 0.213, + "Actual Total Time": 0.22, + "Actual Rows": 51, + "Actual Loops": 1, + "Shared Hit Blocks": 23, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Sort", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 293.69, + "Total Cost": 296.02, + "Plan Rows": 930, + "Plan Width": 149, + "Actual Startup Time": 0.212, + "Actual Total Time": 0.215, + "Actual Rows": 52, + "Actual Loops": 1, + "Sort Key": [ + "created_at", + "id" + ], + "Sort Method": "top-N heapsort", + "Sort Space Used": 35, + "Sort Space Type": "Memory", + "Shared Hit Blocks": 23, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Index Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Scan Direction": "Forward", + "Index Name": "research_candidate", + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.29, + "Total Cost": 262.53, + "Plan Rows": 930, + "Plan Width": 149, + "Actual Startup Time": 0.004, + "Actual Total Time": 0.129, + "Actual Rows": 900, + "Actual Loops": 1, + "Index Cond": "(chat_id = '7d62628c-5194-4dea-ae35-be479edde556'::uuid)", + "Rows Removed by Index Recheck": 0, + "Shared Hit Blocks": 23, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + } + ] + } + ] + }, + "Planning": { + "Shared Hit Blocks": 0, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + }, + "Planning Time": 0.029, + "Triggers": [], + "Execution Time": 0.231 + }, + "index": "chat_only", + "method": "offset", + "chat_size": 900, + "offset": 0, + "index_bytes": 720896 + }, + { + "latency_ms": [ + 0.5986210016999394, + 1.2027099946863018, + 0.9663570017437451, + 0.815681996755302, + 0.6662640007562004, + 0.5978590052109212, + 0.5742170033045113, + 0.562761997571215, + 0.5399729998316616, + 0.5649309969157912, + 0.5609760046354495, + 0.8648570001241751, + 0.5941330018686131, + 0.5893549969187006, + 0.5828490029671229, + 0.5862600010004826, + 0.7054849993437529, + 0.7623250057804398, + 0.7116299966583028, + 0.5859060038346797, + 0.5818280042149127, + 0.5854359988006763, + 0.5564630046137609, + 0.5763490044046193, + 0.5651929968735203, + 0.5440200038719922, + 0.5444920025183819, + 0.8659800005261786, + 0.7897570030763745, + 0.9748839947860688 + ], + "p50_ms": 0.5878074989595916, + "p95_ms": 0.9748839947860688, + "p99_ms": 1.2027099946863018, + "plan": { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 298.21, + "Total Cost": 298.34, + "Plan Rows": 51, + "Plan Width": 149, + "Actual Startup Time": 0.265, + "Actual Total Time": 0.272, + "Actual Rows": 51, + "Actual Loops": 1, + "Shared Hit Blocks": 23, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Sort", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 298.21, + "Total Cost": 300.54, + "Plan Rows": 930, + "Plan Width": 149, + "Actual Startup Time": 0.265, + "Actual Total Time": 0.267, + "Actual Rows": 51, + "Actual Loops": 1, + "Sort Key": [ + "created_at", + "id" + ], + "Sort Method": "top-N heapsort", + "Sort Space Used": 35, + "Sort Space Type": "Memory", + "Shared Hit Blocks": 23, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Index Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Scan Direction": "Forward", + "Index Name": "research_candidate", + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.29, + "Total Cost": 267.18, + "Plan Rows": 930, + "Plan Width": 149, + "Actual Startup Time": 0.008, + "Actual Total Time": 0.181, + "Actual Rows": 899, + "Actual Loops": 1, + "Index Cond": "(chat_id = '7d62628c-5194-4dea-ae35-be479edde556'::uuid)", + "Rows Removed by Index Recheck": 0, + "Filter": "(ROW(created_at, id) > ROW('2026-01-01 00:00:00+00'::timestamp with time zone, '616770c4-a850-44a9-9076-e9cacdd4f80e'::uuid))", + "Rows Removed by Filter": 1, + "Shared Hit Blocks": 23, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + } + ] + } + ] + }, + "Planning": { + "Shared Hit Blocks": 0, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + }, + "Planning Time": 0.051, + "Triggers": [], + "Execution Time": 0.285 + }, + "index": "chat_only", + "method": "keyset", + "chat_size": 900, + "offset": 0, + "index_bytes": 720896 + }, + { + "latency_ms": [ + 3.6396709983819164, + 3.315843001473695, + 3.1500420009251684, + 3.5604270015028305, + 3.4831789962481707, + 3.25658600195311, + 3.1612569946446456, + 3.241995997086633, + 3.7312929998734035, + 3.7026499994681217, + 3.3170360038639046, + 3.0655770024168305, + 3.166844995575957, + 3.7430660013342276, + 3.461174994299654, + 3.464847002760507, + 3.253312002925668, + 3.2097980001708493, + 3.3909799967659637, + 3.2880680009839125, + 3.1127780021051876, + 3.2819410043885, + 4.021925997221842, + 3.6003139975946397, + 3.404111004783772, + 3.481105995888356, + 3.5078629953204654, + 4.06567299796734, + 3.5096330029773526, + 3.337009002279956 + ], + "p50_ms": 3.397545500774868, + "p95_ms": 4.021925997221842, + "p99_ms": 4.06567299796734, + "plan": { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 2172.36, + "Total Cost": 2172.49, + "Plan Rows": 51, + "Plan Width": 149, + "Actual Startup Time": 4.073, + "Actual Total Time": 4.081, + "Actual Rows": 51, + "Actual Loops": 1, + "Shared Hit Blocks": 535, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Sort", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 2172.36, + "Total Cost": 2222.86, + "Plan Rows": 20200, + "Plan Width": 149, + "Actual Startup Time": 4.071, + "Actual Total Time": 4.076, + "Actual Rows": 52, + "Actual Loops": 1, + "Sort Key": [ + "created_at", + "id" + ], + "Sort Method": "top-N heapsort", + "Sort Space Used": 46, + "Sort Space Type": "Memory", + "Shared Hit Blocks": 535, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Index Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Scan Direction": "Forward", + "Index Name": "research_candidate", + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.29, + "Total Cost": 1495.62, + "Plan Rows": 20200, + "Plan Width": 149, + "Actual Startup Time": 0.008, + "Actual Total Time": 2.422, + "Actual Rows": 20000, + "Actual Loops": 1, + "Index Cond": "(chat_id = 'f8028b31-6ab5-45df-9cea-f4737a46ecf7'::uuid)", + "Rows Removed by Index Recheck": 0, + "Shared Hit Blocks": 535, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + } + ] + } + ] + }, + "Planning": { + "Shared Hit Blocks": 0, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + }, + "Planning Time": 0.051, + "Triggers": [], + "Execution Time": 4.097 + }, + "index": "chat_only", + "method": "offset", + "chat_size": 20000, + "offset": 0, + "index_bytes": 720896 + }, + { + "latency_ms": [ + 4.510425998887513, + 4.31799900252372, + 4.85684000159381, + 4.573904006974772, + 4.381462000310421, + 4.3565740052144974, + 4.396270000142977, + 4.2843369956244715, + 4.301326000131667, + 4.440339995198883, + 4.530594000243582, + 4.301628003304359, + 4.355962999397889, + 4.611142001522239, + 4.388927001855336, + 4.8510959968552925, + 6.5365219998057, + 4.9541619955562055, + 4.699940996943042, + 5.050960004155058, + 5.059185998106841, + 4.704730003140867, + 4.52292499539908, + 5.80235799861839, + 6.389116002537776, + 6.721976998960599, + 6.946608998987358, + 6.394019997969735, + 6.505327997729182, + 6.5736059987102635 + ], + "p50_ms": 4.6555414992326405, + "p95_ms": 6.721976998960599, + "p99_ms": 6.946608998987358, + "plan": { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 2270.46, + "Total Cost": 2270.59, + "Plan Rows": 51, + "Plan Width": 149, + "Actual Startup Time": 8.668, + "Actual Total Time": 8.681, + "Actual Rows": 51, + "Actual Loops": 1, + "Shared Hit Blocks": 535, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Sort", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 2270.46, + "Total Cost": 2320.96, + "Plan Rows": 20198, + "Plan Width": 149, + "Actual Startup Time": 8.666, + "Actual Total Time": 8.672, + "Actual Rows": 51, + "Actual Loops": 1, + "Sort Key": [ + "created_at", + "id" + ], + "Sort Method": "top-N heapsort", + "Sort Space Used": 45, + "Sort Space Type": "Memory", + "Shared Hit Blocks": 535, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Index Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Scan Direction": "Forward", + "Index Name": "research_candidate", + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.29, + "Total Cost": 1596.62, + "Plan Rows": 20198, + "Plan Width": 149, + "Actual Startup Time": 0.019, + "Actual Total Time": 6.13, + "Actual Rows": 19999, + "Actual Loops": 1, + "Index Cond": "(chat_id = 'f8028b31-6ab5-45df-9cea-f4737a46ecf7'::uuid)", + "Rows Removed by Index Recheck": 0, + "Filter": "(ROW(created_at, id) > ROW('2026-01-01 00:00:00+00'::timestamp with time zone, 'b40ef452-0402-40ff-8ff4-c321419228d3'::uuid))", + "Rows Removed by Filter": 1, + "Shared Hit Blocks": 535, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + } + ] + } + ] + }, + "Planning": { + "Shared Hit Blocks": 0, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + }, + "Planning Time": 0.096, + "Triggers": [], + "Execution Time": 8.709 + }, + "index": "chat_only", + "method": "keyset", + "chat_size": 20000, + "offset": 0, + "index_bytes": 720896 + }, + { + "latency_ms": [ + 10.648266004864126, + 11.56237100076396, + 8.729918001336046, + 9.956839996448252, + 10.013567996793427, + 10.035166000307072, + 10.114019001775887, + 9.63052200677339, + 9.62559199979296, + 9.26304099994013, + 9.001956001156941, + 9.68837400432676, + 9.387826998136006, + 9.794992001843639, + 8.795802998065483, + 9.199259999149945, + 8.510036997904535, + 10.369052004534751, + 8.818776994303335, + 8.338295003341045, + 9.260972001357004, + 8.96537000517128, + 8.857132997945882, + 9.059452997462358, + 8.979184996860567, + 9.052551999047864, + 8.455221002805047, + 8.65195199730806, + 8.900633998564444, + 9.433266997803003 + ], + "p50_ms": 9.230116000253474, + "p95_ms": 10.648266004864126, + "p99_ms": 11.56237100076396, + "plan": { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 2964.42, + "Total Cost": 2964.54, + "Plan Rows": 51, + "Plan Width": 149, + "Actual Startup Time": 9.845, + "Actual Total Time": 9.855, + "Actual Rows": 51, + "Actual Loops": 1, + "Shared Hit Blocks": 535, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 315, + "Temp Written Blocks": 400, + "Plans": [ + { + "Node Type": "Sort", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 2939.42, + "Total Cost": 2989.92, + "Plan Rows": 20200, + "Plan Width": 149, + "Actual Startup Time": 8.436, + "Actual Total Time": 9.465, + "Actual Rows": 10051, + "Actual Loops": 1, + "Sort Key": [ + "created_at", + "id" + ], + "Sort Method": "external merge", + "Sort Space Used": 3192, + "Sort Space Type": "Disk", + "Shared Hit Blocks": 535, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 315, + "Temp Written Blocks": 400, + "Plans": [ + { + "Node Type": "Index Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Scan Direction": "Forward", + "Index Name": "research_candidate", + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.29, + "Total Cost": 1495.62, + "Plan Rows": 20200, + "Plan Width": 149, + "Actual Startup Time": 0.016, + "Actual Total Time": 2.822, + "Actual Rows": 20000, + "Actual Loops": 1, + "Index Cond": "(chat_id = 'f8028b31-6ab5-45df-9cea-f4737a46ecf7'::uuid)", + "Rows Removed by Index Recheck": 0, + "Shared Hit Blocks": 535, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + } + ] + } + ] + }, + "Planning": { + "Shared Hit Blocks": 0, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + }, + "Planning Time": 0.087, + "Triggers": [], + "Execution Time": 10.353 + }, + "index": "chat_only", + "method": "offset", + "chat_size": 20000, + "offset": 9999, + "index_bytes": 720896 + }, + { + "latency_ms": [ + 4.151321001700126, + 4.0036549980868585, + 3.9418400046997704, + 4.550733996438794, + 4.614767000020947, + 4.487386002438143, + 4.574496000714134, + 5.459138999867719, + 4.669715999625623, + 4.226073004247155, + 4.147751998971216, + 4.302236993680708, + 4.7717039997223765, + 4.209546001220588, + 4.11989900021581, + 4.05995699838968, + 3.9884400030132383, + 3.772071999264881, + 3.775700999540277, + 4.703452999820001, + 4.218481000862084, + 3.7898349983152, + 3.9697450047242455, + 4.18052299937699, + 4.103152998141013, + 4.783489006513264, + 6.597168998268899, + 5.625703000987414, + 4.801691000466235, + 5.398822999268305 + ], + "p50_ms": 4.22227700255462, + "p95_ms": 5.625703000987414, + "p99_ms": 6.597168998268899, + "plan": { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 2069.59, + "Total Cost": 2069.72, + "Plan Rows": 51, + "Plan Width": 149, + "Actual Startup Time": 5.822, + "Actual Total Time": 5.833, + "Actual Rows": 51, + "Actual Loops": 1, + "Shared Hit Blocks": 535, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Sort", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 2069.59, + "Total Cost": 2105.03, + "Plan Rows": 14177, + "Plan Width": 149, + "Actual Startup Time": 5.821, + "Actual Total Time": 5.826, + "Actual Rows": 51, + "Actual Loops": 1, + "Sort Key": [ + "created_at", + "id" + ], + "Sort Method": "top-N heapsort", + "Sort Space Used": 43, + "Sort Space Type": "Memory", + "Shared Hit Blocks": 535, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Index Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Scan Direction": "Forward", + "Index Name": "research_candidate", + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.29, + "Total Cost": 1596.62, + "Plan Rows": 14177, + "Plan Width": 149, + "Actual Startup Time": 0.018, + "Actual Total Time": 4.624, + "Actual Rows": 10000, + "Actual Loops": 1, + "Index Cond": "(chat_id = 'f8028b31-6ab5-45df-9cea-f4737a46ecf7'::uuid)", + "Rows Removed by Index Recheck": 0, + "Filter": "(ROW(created_at, id) > ROW('2026-01-01 00:00:00.009999+00'::timestamp with time zone, '0d7dd609-3ecd-44a4-96d5-e97cadf683e1'::uuid))", + "Rows Removed by Filter": 10000, + "Shared Hit Blocks": 535, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + } + ] + } + ] + }, + "Planning": { + "Shared Hit Blocks": 0, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + }, + "Planning Time": 0.136, + "Triggers": [], + "Execution Time": 5.857 + }, + "index": "chat_only", + "method": "keyset", + "chat_size": 20000, + "offset": 9999, + "index_bytes": 720896 + }, + { + "latency_ms": [ + 0.9769219977897592, + 1.0176720024901442, + 0.9619690026738681, + 0.963849997788202, + 0.9464469985687174, + 0.9871119982562959, + 1.0148509973078035, + 1.0565689954091795, + 0.9729640005389228, + 1.0220969998044893, + 1.0210480031673796, + 1.0045009985333309, + 0.9600909979781136, + 1.0189580061705783, + 0.9298490040237084, + 0.8247469959314913, + 0.7292740046977997, + 0.7068039994919673, + 0.6964269996387884, + 0.6792909989599138, + 0.771400002122391, + 1.025815996399615, + 0.9573189963703044, + 1.1455549974925816, + 1.111968005716335, + 1.1041580000892282, + 1.0866770026041195, + 0.9269899965147488, + 0.7903180012363009, + 0.6956989964237437 + ], + "p50_ms": 0.9684069991635624, + "p95_ms": 1.111968005716335, + "p99_ms": 1.1455549974925816, + "plan": { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 310.41, + "Total Cost": 310.54, + "Plan Rows": 51, + "Plan Width": 149, + "Actual Startup Time": 0.347, + "Actual Total Time": 0.357, + "Actual Rows": 51, + "Actual Loops": 1, + "Shared Hit Blocks": 23, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Sort", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 308.39, + "Total Cost": 310.71, + "Plan Rows": 930, + "Plan Width": 149, + "Actual Startup Time": 0.254, + "Actual Total Time": 0.309, + "Actual Rows": 861, + "Actual Loops": 1, + "Sort Key": [ + "created_at", + "id" + ], + "Sort Method": "quicksort", + "Sort Space Used": 222, + "Sort Space Type": "Memory", + "Shared Hit Blocks": 23, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Index Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Scan Direction": "Forward", + "Index Name": "research_candidate", + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.29, + "Total Cost": 262.53, + "Plan Rows": 930, + "Plan Width": 149, + "Actual Startup Time": 0.005, + "Actual Total Time": 0.147, + "Actual Rows": 900, + "Actual Loops": 1, + "Index Cond": "(chat_id = '7d62628c-5194-4dea-ae35-be479edde556'::uuid)", + "Rows Removed by Index Recheck": 0, + "Shared Hit Blocks": 23, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + } + ] + } + ] + }, + "Planning": { + "Shared Hit Blocks": 0, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + }, + "Planning Time": 0.041, + "Triggers": [], + "Execution Time": 0.371 + }, + "index": "chat_only", + "method": "offset", + "chat_size": 900, + "offset": 809, + "index_bytes": 720896 + }, + { + "latency_ms": [ + 1.0245059966109693, + 0.9967459991457872, + 0.9673280001152307, + 1.0600469977362081, + 0.9191969948005863, + 0.9332129993708804, + 0.9149500037892722, + 0.9023429956869222, + 0.8954010045272298, + 0.8483940036967397, + 0.9668990023783408, + 0.991068001894746, + 0.8253020059783012, + 1.0633999991114251, + 1.1413639949751087, + 1.161212996521499, + 0.9657420014264062, + 1.1282460036454722, + 0.9207859984599054, + 0.9491009986959398, + 0.9042860037880018, + 0.803770002676174, + 0.9022130034281872, + 1.0037880056188442, + 0.9093409971683286, + 1.099052999052219, + 0.93910499708727, + 1.1639689982985146, + 1.2149890026194043, + 1.0168959997827187 + ], + "p50_ms": 0.9663205019023735, + "p95_ms": 1.1639689982985146, + "p99_ms": 1.2149890026194043, + "plan": { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 297.18, + "Total Cost": 297.3, + "Plan Rows": 51, + "Plan Width": 149, + "Actual Startup Time": 0.212, + "Actual Total Time": 0.222, + "Actual Rows": 51, + "Actual Loops": 1, + "Shared Hit Blocks": 23, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Sort", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 297.18, + "Total Cost": 299.42, + "Plan Rows": 899, + "Plan Width": 149, + "Actual Startup Time": 0.212, + "Actual Total Time": 0.216, + "Actual Rows": 51, + "Actual Loops": 1, + "Sort Key": [ + "created_at", + "id" + ], + "Sort Method": "quicksort", + "Sort Space Used": 44, + "Sort Space Type": "Memory", + "Shared Hit Blocks": 23, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Index Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Scan Direction": "Forward", + "Index Name": "research_candidate", + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.29, + "Total Cost": 267.18, + "Plan Rows": 899, + "Plan Width": 149, + "Actual Startup Time": 0.174, + "Actual Total Time": 0.196, + "Actual Rows": 90, + "Actual Loops": 1, + "Index Cond": "(chat_id = '7d62628c-5194-4dea-ae35-be479edde556'::uuid)", + "Rows Removed by Index Recheck": 0, + "Filter": "(ROW(created_at, id) > ROW('2026-01-01 00:00:00.000809+00'::timestamp with time zone, 'bf3aad6a-a237-41ef-986f-1ab253e8bb90'::uuid))", + "Rows Removed by Filter": 810, + "Shared Hit Blocks": 23, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + } + ] + } + ] + }, + "Planning": { + "Shared Hit Blocks": 0, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + }, + "Planning Time": 0.075, + "Triggers": [], + "Execution Time": 0.241 + }, + "index": "chat_only", + "method": "keyset", + "chat_size": 900, + "offset": 809, + "index_bytes": 720896 + }, + { + "latency_ms": [ + 11.10773300024448, + 11.110049999842886, + 11.12112700502621, + 13.350799003092106, + 11.173193001013715, + 11.56337699649157, + 11.589732996071689, + 11.129817001346964, + 11.375999005394988, + 11.077601004217286, + 10.791127999254968, + 10.858640001970343, + 11.315045005176216, + 11.13799699669471, + 11.529151997820009, + 11.581361999560613, + 11.107165999419522, + 11.232174001634121, + 12.819007002690341, + 11.913618000107817, + 10.812911998073105, + 11.009442001522984, + 11.499191001348663, + 10.605406001559459, + 11.344279999320861, + 11.135966000438202, + 10.698652993596625, + 11.398499002098106, + 11.251616997469682, + 10.912682002526708 + ], + "p50_ms": 11.155594998854212, + "p95_ms": 12.819007002690341, + "p99_ms": 13.350799003092106, + "plan": { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 5379.17, + "Total Cost": 5385.04, + "Plan Rows": 51, + "Plan Width": 149, + "Actual Startup Time": 10.52, + "Actual Total Time": 12.836, + "Actual Rows": 51, + "Actual Loops": 1, + "Shared Hit Blocks": 2308, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Gather Merge", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 5379.06, + "Total Cost": 10115.22, + "Plan Rows": 41184, + "Plan Width": 149, + "Actual Startup Time": 10.518, + "Actual Total Time": 12.829, + "Actual Rows": 52, + "Actual Loops": 1, + "Workers Planned": 1, + "Workers Launched": 1, + "Shared Hit Blocks": 2308, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Sort", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 4379.05, + "Total Cost": 4482.01, + "Plan Rows": 41184, + "Plan Width": 149, + "Actual Startup Time": 8.894, + "Actual Total Time": 8.898, + "Actual Rows": 52, + "Actual Loops": 2, + "Sort Key": [ + "created_at", + "id" + ], + "Sort Method": "top-N heapsort", + "Sort Space Used": 35, + "Sort Space Type": "Memory", + "Shared Hit Blocks": 2308, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Workers": [ + { + "Worker Number": 0, + "Sort Method": "top-N heapsort", + "Sort Space Used": 35, + "Sort Space Type": "Memory" + } + ], + "Plans": [ + { + "Node Type": "Seq Scan", + "Parent Relationship": "Outer", + "Parallel Aware": true, + "Async Capable": false, + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.0, + "Total Cost": 2999.29, + "Plan Rows": 41184, + "Plan Width": 149, + "Actual Startup Time": 0.007, + "Actual Total Time": 5.933, + "Actual Rows": 35000, + "Actual Loops": 2, + "Filter": "(chat_id = '48c201d1-9d95-4ce9-90f7-019e28b812ba'::uuid)", + "Rows Removed by Filter": 15000, + "Shared Hit Blocks": 2264, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Workers": [] + } + ] + } + ] + } + ] + }, + "Planning": { + "Shared Hit Blocks": 0, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + }, + "Planning Time": 0.083, + "Triggers": [], + "Execution Time": 12.86 + }, + "index": "chat_only", + "method": "offset", + "chat_size": 70000, + "offset": 0, + "index_bytes": 720896 + }, + { + "latency_ms": [ + 12.735338998027146, + 12.439466998330317, + 12.426728004356846, + 12.683680994086899, + 12.397030004649423, + 12.349773998721503, + 12.281652001547627, + 13.294394004333299, + 13.19811400026083, + 12.926179995702114, + 12.153726995165925, + 11.990859005891252, + 16.031273000407964, + 14.295099004812073, + 12.979595005162992, + 12.56593700236408, + 12.69771899387706, + 12.798921998182777, + 12.520861993834842, + 12.605223004356958, + 12.751082998875063, + 12.512414999946486, + 12.162988998170476, + 12.438097000995185, + 12.251371001184452, + 12.614422004844528, + 13.09835600113729, + 13.961823002318852, + 14.819174000876956, + 12.724047002848238 + ], + "p50_ms": 12.649051499465713, + "p95_ms": 14.819174000876956, + "p99_ms": 16.031273000407964, + "plan": { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 5667.27, + "Total Cost": 5673.14, + "Plan Rows": 51, + "Plan Width": 149, + "Actual Startup Time": 12.993, + "Actual Total Time": 15.303, + "Actual Rows": 51, + "Actual Loops": 1, + "Shared Hit Blocks": 2279, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Gather Merge", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 5667.27, + "Total Cost": 10402.97, + "Plan Rows": 41180, + "Plan Width": 149, + "Actual Startup Time": 12.991, + "Actual Total Time": 15.297, + "Actual Rows": 51, + "Actual Loops": 1, + "Workers Planned": 1, + "Workers Launched": 1, + "Shared Hit Blocks": 2279, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Sort", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 4667.26, + "Total Cost": 4770.21, + "Plan Rows": 41180, + "Plan Width": 149, + "Actual Startup Time": 11.317, + "Actual Total Time": 11.321, + "Actual Rows": 51, + "Actual Loops": 2, + "Sort Key": [ + "created_at", + "id" + ], + "Sort Method": "top-N heapsort", + "Sort Space Used": 35, + "Sort Space Type": "Memory", + "Shared Hit Blocks": 2279, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Workers": [ + { + "Worker Number": 0, + "Sort Method": "top-N heapsort", + "Sort Space Used": 37, + "Sort Space Type": "Memory" + } + ], + "Plans": [ + { + "Node Type": "Seq Scan", + "Parent Relationship": "Outer", + "Parallel Aware": true, + "Async Capable": false, + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.0, + "Total Cost": 3293.41, + "Plan Rows": 41180, + "Plan Width": 149, + "Actual Startup Time": 0.008, + "Actual Total Time": 8.001, + "Actual Rows": 35000, + "Actual Loops": 2, + "Filter": "((chat_id = '48c201d1-9d95-4ce9-90f7-019e28b812ba'::uuid) AND (ROW(created_at, id) > ROW('2026-01-01 00:00:00+00'::timestamp with time zone, '936f77f5-d513-4297-8056-dccd57ca90a6'::uuid)))", + "Rows Removed by Filter": 15000, + "Shared Hit Blocks": 2264, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Workers": [] + } + ] + } + ] + } + ] + }, + "Planning": { + "Shared Hit Blocks": 0, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + }, + "Planning Time": 0.086, + "Triggers": [], + "Execution Time": 15.326 + }, + "index": "chat_only", + "method": "keyset", + "chat_size": 70000, + "offset": 0, + "index_bytes": 720896 + }, + { + "latency_ms": [ + 35.633592000522185, + 36.75084800488548, + 38.265739000053145, + 39.52649800339714, + 35.46764199563768, + 33.83352299715625, + 39.27907400066033, + 32.31692500412464, + 28.656861002673395, + 29.116396995959803, + 29.76218100229744, + 30.051424000703264, + 29.572523999377154, + 28.733811996062286, + 28.087154001696035, + 28.457811000407673, + 49.010014001396485, + 32.31078200042248, + 42.46446600154741, + 34.086042003764305, + 30.278546997578815, + 27.8400370007148, + 116.2690580022172, + 221.4701539996895, + 187.73364200023934, + 145.94532000046456, + 290.3320579935098, + 279.05769999779295, + 163.88604300300358, + 185.88825699407607 + ], + "p50_ms": 35.55061699807993, + "p95_ms": 279.05769999779295, + "p99_ms": 290.3320579935098, + "plan": { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 14278.52, + "Total Cost": 14284.38, + "Plan Rows": 51, + "Plan Width": 149, + "Actual Startup Time": 210.195, + "Actual Total Time": 230.385, + "Actual Rows": 51, + "Actual Loops": 1, + "Shared Hit Blocks": 2308, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 1228, + "Temp Written Blocks": 1401, + "Plans": [ + { + "Node Type": "Gather Merge", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 10253.52, + "Total Cost": 14989.68, + "Plan Rows": 41184, + "Plan Width": 149, + "Actual Startup Time": 140.39, + "Actual Total Time": 219.198, + "Actual Rows": 35051, + "Actual Loops": 1, + "Workers Planned": 1, + "Workers Launched": 1, + "Shared Hit Blocks": 2308, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 1228, + "Temp Written Blocks": 1401, + "Plans": [ + { + "Node Type": "Sort", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 9253.51, + "Total Cost": 9356.47, + "Plan Rows": 41184, + "Plan Width": 149, + "Actual Startup Time": 125.074, + "Actual Total Time": 139.099, + "Actual Rows": 17706, + "Actual Loops": 2, + "Sort Key": [ + "created_at", + "id" + ], + "Sort Method": "external merge", + "Sort Space Used": 6432, + "Sort Space Type": "Disk", + "Shared Hit Blocks": 2308, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 1228, + "Temp Written Blocks": 1401, + "Workers": [ + { + "Worker Number": 0, + "Sort Method": "external merge", + "Sort Space Used": 4752, + "Sort Space Type": "Disk" + } + ], + "Plans": [ + { + "Node Type": "Seq Scan", + "Parent Relationship": "Outer", + "Parallel Aware": true, + "Async Capable": false, + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.0, + "Total Cost": 2999.29, + "Plan Rows": 41184, + "Plan Width": 149, + "Actual Startup Time": 0.055, + "Actual Total Time": 42.859, + "Actual Rows": 35000, + "Actual Loops": 2, + "Filter": "(chat_id = '48c201d1-9d95-4ce9-90f7-019e28b812ba'::uuid)", + "Rows Removed by Filter": 15000, + "Shared Hit Blocks": 2264, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Workers": [] + } + ] + } + ] + } + ] + }, + "Planning": { + "Shared Hit Blocks": 0, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + }, + "Planning Time": 0.936, + "Triggers": [], + "Execution Time": 236.584 + }, + "index": "chat_only", + "method": "offset", + "chat_size": 70000, + "offset": 34999, + "index_bytes": 720896 + }, + { + "latency_ms": [ + 13.951136999821756, + 12.758494995068759, + 13.167744000384118, + 13.186985001084395, + 13.78156800637953, + 14.821024997218046, + 12.719259000732563, + 12.597265005751979, + 13.001571998756845, + 12.998635000258218, + 13.535375001083594, + 12.773058006132487, + 12.904299997899216, + 12.282242001674604, + 12.312354003370274, + 12.254150002263486, + 13.11823799915146, + 13.608913002826739, + 13.6983800039161, + 12.74043699959293, + 13.27428800141206, + 14.100981003139168, + 13.048815999354701, + 16.114999998535495, + 13.207943993620574, + 14.467606000835076, + 16.96718000312103, + 15.421773001435213, + 14.845710000372492, + 13.299810998432804 + ], + "p50_ms": 13.197464497352485, + "p95_ms": 16.114999998535495, + "p99_ms": 16.96718000312103, + "plan": { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 4760.65, + "Total Cost": 4760.78, + "Plan Rows": 51, + "Plan Width": 149, + "Actual Startup Time": 15.67, + "Actual Total Time": 15.679, + "Actual Rows": 51, + "Actual Loops": 1, + "Shared Hit Blocks": 1622, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Sort", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 4760.65, + "Total Cost": 4822.03, + "Plan Rows": 24553, + "Plan Width": 149, + "Actual Startup Time": 15.667, + "Actual Total Time": 15.672, + "Actual Rows": 51, + "Actual Loops": 1, + "Sort Key": [ + "created_at", + "id" + ], + "Sort Method": "top-N heapsort", + "Sort Space Used": 44, + "Sort Space Type": "Memory", + "Shared Hit Blocks": 1622, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Index Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Scan Direction": "Forward", + "Index Name": "research_candidate", + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.29, + "Total Cost": 3941.51, + "Plan Rows": 24553, + "Plan Width": 149, + "Actual Startup Time": 4.176, + "Actual Total Time": 12.557, + "Actual Rows": 35000, + "Actual Loops": 1, + "Index Cond": "(chat_id = '48c201d1-9d95-4ce9-90f7-019e28b812ba'::uuid)", + "Rows Removed by Index Recheck": 0, + "Filter": "(ROW(created_at, id) > ROW('2026-01-01 00:00:00.034999+00'::timestamp with time zone, 'bcaf6f3b-bf59-429c-9ccd-d8363212746d'::uuid))", + "Rows Removed by Filter": 35000, + "Shared Hit Blocks": 1622, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + } + ] + } + ] + }, + "Planning": { + "Shared Hit Blocks": 0, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + }, + "Planning Time": 0.111, + "Triggers": [], + "Execution Time": 15.705 + }, + "index": "chat_only", + "method": "keyset", + "chat_size": 70000, + "offset": 34999, + "index_bytes": 720896 + }, + { + "latency_ms": [ + 0.8090049959719181, + 0.7163190020946786, + 0.6924600020283833, + 0.7411929982481524, + 0.7138529981602915, + 0.7678250040044077, + 0.6082999971113168, + 0.5548249973799102, + 0.5545309977605939, + 0.5545429958146997, + 0.5462640037876554, + 0.5523869986063801, + 0.5218879960011691, + 0.5273270071484149, + 0.5105200034449808, + 1.520427998912055, + 0.9655019966885448, + 0.8971400020527653, + 0.9955069981515408, + 0.7371210012934171, + 0.6305350034381263, + 0.9338910022052005, + 0.9094209963222966, + 0.7396859946311451, + 0.5709879987989552, + 0.5528280016733333, + 0.7822099942131899, + 0.6186019963934086, + 0.5950390041107312, + 0.5411910024122335 + ], + "p50_ms": 0.6614975027332548, + "p95_ms": 0.9955069981515408, + "p99_ms": 1.520427998912055, + "plan": { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 309.51, + "Total Cost": 309.64, + "Plan Rows": 51, + "Plan Width": 149, + "Actual Startup Time": 0.23, + "Actual Total Time": 0.237, + "Actual Rows": 51, + "Actual Loops": 1, + "Shared Hit Blocks": 23, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Sort", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 308.39, + "Total Cost": 310.71, + "Plan Rows": 930, + "Plan Width": 149, + "Actual Startup Time": 0.19, + "Actual Total Time": 0.215, + "Actual Rows": 501, + "Actual Loops": 1, + "Sort Key": [ + "created_at", + "id" + ], + "Sort Method": "quicksort", + "Sort Space Used": 222, + "Sort Space Type": "Memory", + "Shared Hit Blocks": 23, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Index Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Scan Direction": "Forward", + "Index Name": "research_candidate", + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.29, + "Total Cost": 262.53, + "Plan Rows": 930, + "Plan Width": 149, + "Actual Startup Time": 0.004, + "Actual Total Time": 0.111, + "Actual Rows": 900, + "Actual Loops": 1, + "Index Cond": "(chat_id = '7d62628c-5194-4dea-ae35-be479edde556'::uuid)", + "Rows Removed by Index Recheck": 0, + "Shared Hit Blocks": 23, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + } + ] + } + ] + }, + "Planning": { + "Shared Hit Blocks": 0, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + }, + "Planning Time": 0.031, + "Triggers": [], + "Execution Time": 0.248 + }, + "index": "chat_only", + "method": "offset", + "chat_size": 900, + "offset": 449, + "index_bytes": 720896 + }, + { + "latency_ms": [ + 0.4979939985787496, + 0.6044679976184852, + 1.5087700012372807, + 0.7872010028222576, + 0.7968650024849921, + 0.756456000090111, + 0.81017600314226, + 1.1165209944010712, + 0.848683004733175, + 0.7248250039992854, + 0.6633119992329739, + 0.6192030050442554, + 0.7453860016539693, + 0.5456520011648536, + 0.5584300015470944, + 0.6701700040139258, + 0.7033869987935759, + 0.6236949993763119, + 0.5319710035109892, + 0.5226240027695894, + 0.5166519986232743, + 0.5205509951338172, + 0.5385670010582544, + 0.5222229956416413, + 0.528096999914851, + 0.5118129993206821, + 0.5609090003417805, + 0.6958779995329678, + 0.6037479979568161, + 0.7416199950966984 + ], + "p50_ms": 0.6214490022102837, + "p95_ms": 1.1165209944010712, + "p99_ms": 1.5087700012372807, + "plan": { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 297.61, + "Total Cost": 297.74, + "Plan Rows": 51, + "Plan Width": 149, + "Actual Startup Time": 0.212, + "Actual Total Time": 0.219, + "Actual Rows": 51, + "Actual Loops": 1, + "Shared Hit Blocks": 23, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Sort", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 297.61, + "Total Cost": 299.89, + "Plan Rows": 912, + "Plan Width": 149, + "Actual Startup Time": 0.211, + "Actual Total Time": 0.214, + "Actual Rows": 51, + "Actual Loops": 1, + "Sort Key": [ + "created_at", + "id" + ], + "Sort Method": "top-N heapsort", + "Sort Space Used": 35, + "Sort Space Type": "Memory", + "Shared Hit Blocks": 23, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Index Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Scan Direction": "Forward", + "Index Name": "research_candidate", + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.29, + "Total Cost": 267.18, + "Plan Rows": 912, + "Plan Width": 149, + "Actual Startup Time": 0.083, + "Actual Total Time": 0.162, + "Actual Rows": 450, + "Actual Loops": 1, + "Index Cond": "(chat_id = '7d62628c-5194-4dea-ae35-be479edde556'::uuid)", + "Rows Removed by Index Recheck": 0, + "Filter": "(ROW(created_at, id) > ROW('2026-01-01 00:00:00.000449+00'::timestamp with time zone, '7a97433e-635e-437a-98d0-544cf1b1628c'::uuid))", + "Rows Removed by Filter": 450, + "Shared Hit Blocks": 23, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + } + ] + } + ] + }, + "Planning": { + "Shared Hit Blocks": 0, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + }, + "Planning Time": 0.103, + "Triggers": [], + "Execution Time": 0.236 + }, + "index": "chat_only", + "method": "keyset", + "chat_size": 900, + "offset": 449, + "index_bytes": 720896 + }, + { + "latency_ms": [ + 9.316002993728034, + 9.819066006457433, + 14.568933998816647, + 11.131191997264978, + 9.901240999170113, + 9.42685900372453, + 9.77829800103791, + 13.050916997599415, + 9.268319001421332, + 12.918332999106497, + 11.675169997033663, + 9.275415999582037, + 9.627147002902348, + 8.86779999564169, + 9.110705999773927, + 9.951829997589812, + 9.490777003520634, + 9.762631998455618, + 13.302705003297888, + 11.009664005541708, + 9.760887005541008, + 10.66144399374025, + 10.75005199527368, + 10.08309199823998, + 12.022893002722412, + 11.49867799540516, + 12.890384001366328, + 14.338114997372031, + 10.385082998254802, + 8.004907002032269 + ], + "p50_ms": 10.017460997914895, + "p95_ms": 14.338114997372031, + "p99_ms": 14.568933998816647, + "plan": { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 7478.93, + "Total Cost": 7484.98, + "Plan Rows": 51, + "Plan Width": 149, + "Actual Startup Time": 11.657, + "Actual Total Time": 11.668, + "Actual Rows": 51, + "Actual Loops": 1, + "Shared Hit Blocks": 2447, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Index Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Scan Direction": "Forward", + "Index Name": "research_candidate", + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.42, + "Total Cost": 8326.49, + "Plan Rows": 70140, + "Plan Width": 149, + "Actual Startup Time": 0.013, + "Actual Total Time": 9.213, + "Actual Rows": 63051, + "Actual Loops": 1, + "Index Cond": "(chat_id = '48c201d1-9d95-4ce9-90f7-019e28b812ba'::uuid)", + "Rows Removed by Index Recheck": 0, + "Shared Hit Blocks": 2447, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + } + ] + }, + "Planning": { + "Shared Hit Blocks": 0, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + }, + "Planning Time": 0.075, + "Triggers": [], + "Execution Time": 11.686 + }, + "index": "history", + "method": "offset", + "chat_size": 70000, + "offset": 62999, + "index_bytes": 5914624 + }, + { + "latency_ms": [ + 0.9977209992939606, + 0.6121789992903359, + 0.6900169973960146, + 0.6312369951047003, + 0.6854050006950274, + 0.6065470006433316, + 0.4517720008152537, + 0.4465969977900386, + 0.43481000466272235, + 0.5242699990049005, + 0.5396479973569512, + 0.585255998885259, + 0.683320002281107, + 0.7763059984426945, + 0.6745389982825145, + 0.7680929993512109, + 0.7775870035402477, + 0.7184969945228659, + 0.7643070057383738, + 0.6900619991938584, + 0.8410869995714165, + 0.9174750011879951, + 0.8623449975857511, + 0.8767629988142289, + 0.8242859985330142, + 0.7640850017196499, + 0.8426709973718971, + 0.9397070025443099, + 0.9822889987844974, + 0.8505040023010224 + ], + "p50_ms": 0.7412909981212579, + "p95_ms": 0.9822889987844974, + "p99_ms": 0.9977209992939606, + "plan": { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 0.42, + "Total Cost": 47.74, + "Plan Rows": 51, + "Plan Width": 149, + "Actual Startup Time": 0.024, + "Actual Total Time": 0.047, + "Actual Rows": 51, + "Actual Loops": 1, + "Shared Hit Blocks": 6, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Index Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Scan Direction": "Forward", + "Index Name": "research_candidate", + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.42, + "Total Cost": 4553.38, + "Plan Rows": 4907, + "Plan Width": 149, + "Actual Startup Time": 0.023, + "Actual Total Time": 0.038, + "Actual Rows": 51, + "Actual Loops": 1, + "Index Cond": "((chat_id = '48c201d1-9d95-4ce9-90f7-019e28b812ba'::uuid) AND (ROW(created_at, id) > ROW('2026-01-01 00:00:00.062999+00'::timestamp with time zone, 'ae27a533-b7cc-47a6-bc0d-a2e0d963649e'::uuid)))", + "Rows Removed by Index Recheck": 0, + "Shared Hit Blocks": 6, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + } + ] + }, + "Planning": { + "Shared Hit Blocks": 0, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + }, + "Planning Time": 0.119, + "Triggers": [], + "Execution Time": 0.068 + }, + "index": "history", + "method": "keyset", + "chat_size": 70000, + "offset": 62999, + "index_bytes": 5914624 + }, + { + "latency_ms": [ + 1.4476639989879914, + 0.9921989985741675, + 0.9280609956476837, + 0.8945869994931854, + 0.9179850021610036, + 0.9446280018892139, + 1.0067969997180626, + 1.0714340023696423, + 0.9139480025623925, + 0.9243179956683889, + 0.9315229981439188, + 0.8169309949153103, + 0.8311950005008839, + 2.0517030061455444, + 0.9752999976626597, + 0.8804209937807173, + 0.8585149989812635, + 0.8585899995523505, + 0.7951419975142926, + 0.8622609966550954, + 0.8769019987084903, + 0.9003660015878268, + 1.0516010006540455, + 1.6162690008059144, + 0.8215479974751361, + 0.908633999642916, + 0.8683350024512038, + 0.8063770001172088, + 1.026840996928513, + 0.9363560020574369 + ], + "p50_ms": 0.9159665023616981, + "p95_ms": 1.6162690008059144, + "p99_ms": 2.0517030061455444, + "plan": { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 2.4, + "Total Cost": 103.51, + "Plan Rows": 51, + "Plan Width": 149, + "Actual Startup Time": 0.015, + "Actual Total Time": 0.031, + "Actual Rows": 51, + "Actual Loops": 1, + "Shared Hit Blocks": 5, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Index Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Scan Direction": "Forward", + "Index Name": "research_candidate", + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.42, + "Total Cost": 164.97, + "Plan Rows": 83, + "Plan Width": 149, + "Actual Startup Time": 0.013, + "Actual Total Time": 0.023, + "Actual Rows": 52, + "Actual Loops": 1, + "Index Cond": "(chat_id = '91d2ecd0-11c0-472f-a67a-c678efc87df1'::uuid)", + "Rows Removed by Index Recheck": 0, + "Shared Hit Blocks": 5, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + } + ] + }, + "Planning": { + "Shared Hit Blocks": 0, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + }, + "Planning Time": 0.072, + "Triggers": [], + "Execution Time": 0.048 + }, + "index": "history", + "method": "offset", + "chat_size": 100, + "offset": 0, + "index_bytes": 5914624 + }, + { + "latency_ms": [ + 0.8355710015166551, + 0.8740210032556206, + 0.8217619979404844, + 0.9269160000258125, + 0.8320509950863197, + 1.12720799370436, + 0.7919689960544929, + 0.7697819964960217, + 0.7720510038780048, + 0.7550950031145476, + 0.8086480011115782, + 0.9017569973366335, + 0.7633470013388433, + 0.9061419987119734, + 0.633842995739542, + 0.8886349969543517, + 0.9504979971097782, + 0.865467001858633, + 0.8408970024902374, + 0.8151139991241507, + 0.8118639962049201, + 0.8892979967640713, + 0.8006459975149482, + 0.9357899980386719, + 0.7830780014046468, + 0.8629029980511405, + 0.8097049940261059, + 0.7362949982052669, + 0.7201670014183037, + 0.9880430006887764 + ], + "p50_ms": 0.8269064965134021, + "p95_ms": 0.9880430006887764, + "p99_ms": 1.12720799370436, + "plan": { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 0.42, + "Total Cost": 101.65, + "Plan Rows": 51, + "Plan Width": 149, + "Actual Startup Time": 0.015, + "Actual Total Time": 0.031, + "Actual Rows": 51, + "Actual Loops": 1, + "Shared Hit Blocks": 5, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Index Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Scan Direction": "Forward", + "Index Name": "research_candidate", + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.42, + "Total Cost": 165.17, + "Plan Rows": 83, + "Plan Width": 149, + "Actual Startup Time": 0.014, + "Actual Total Time": 0.023, + "Actual Rows": 51, + "Actual Loops": 1, + "Index Cond": "((chat_id = '91d2ecd0-11c0-472f-a67a-c678efc87df1'::uuid) AND (ROW(created_at, id) > ROW('2026-01-01 00:00:00+00'::timestamp with time zone, '04e85f58-1262-43bd-b37b-6df8662de82a'::uuid)))", + "Rows Removed by Index Recheck": 0, + "Shared Hit Blocks": 5, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + } + ] + }, + "Planning": { + "Shared Hit Blocks": 0, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + }, + "Planning Time": 0.105, + "Triggers": [], + "Execution Time": 0.07 + }, + "index": "history", + "method": "keyset", + "chat_size": 100, + "offset": 0, + "index_bytes": 5914624 + }, + { + "latency_ms": [ + 0.7357649956247769, + 0.7479129999410361, + 0.8190160006051883, + 0.8181059965863824, + 0.8396469929721206, + 0.9645989994169213, + 0.9502640023129061, + 0.8989919952000491, + 0.9118800007854588, + 0.9453040038351901, + 0.9217780025210232, + 1.0112149975611828, + 0.8842009992804378, + 0.8727439999347553, + 0.8095520024653524, + 0.7839370009605773, + 0.7761410015518777, + 0.8712769995327108, + 0.781557995651383, + 0.9212780059897341, + 0.8476779985358007, + 0.8711050031706691, + 0.9188059993903153, + 0.8454220005660318, + 0.7956200061016716, + 0.7912270011729561, + 0.7600369935971685, + 0.7409850004478358, + 0.7333350004046224, + 0.8600950022810139 + ], + "p50_ms": 0.8465499995509163, + "p95_ms": 0.9645989994169213, + "p99_ms": 1.0112149975611828, + "plan": { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 2.09, + "Total Cost": 87.42, + "Plan Rows": 51, + "Plan Width": 149, + "Actual Startup Time": 0.017, + "Actual Total Time": 0.032, + "Actual Rows": 51, + "Actual Loops": 1, + "Shared Hit Blocks": 5, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Index Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Scan Direction": "Forward", + "Index Name": "research_candidate", + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.42, + "Total Cost": 1394.14, + "Plan Rows": 833, + "Plan Width": 149, + "Actual Startup Time": 0.015, + "Actual Total Time": 0.025, + "Actual Rows": 52, + "Actual Loops": 1, + "Index Cond": "(chat_id = '7d62628c-5194-4dea-ae35-be479edde556'::uuid)", + "Rows Removed by Index Recheck": 0, + "Shared Hit Blocks": 5, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + } + ] + }, + "Planning": { + "Shared Hit Blocks": 0, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + }, + "Planning Time": 0.071, + "Triggers": [], + "Execution Time": 0.047 + }, + "index": "history", + "method": "offset", + "chat_size": 900, + "offset": 0, + "index_bytes": 5914624 + }, + { + "latency_ms": [ + 0.6962480038055219, + 0.7535099939559586, + 0.7179960011853836, + 0.6950379975023679, + 0.721183001587633, + 0.7726930052740499, + 0.6968169982428662, + 0.6685079933959059, + 0.6288610020419583, + 0.6190510030137375, + 0.8403930041822605, + 0.665703002596274, + 0.795888998254668, + 0.6922390020918101, + 0.7138910004869103, + 0.7596969953738153, + 0.6105830034357496, + 0.6640970022999682, + 0.6967610024730675, + 0.6746999933966435, + 0.706468999851495, + 0.6612459983443841, + 0.8335399979841895, + 0.7450270059052855, + 0.7528179994551465, + 0.6546769945998676, + 0.7032430003164336, + 0.7491430005757138, + 0.6055150006432086, + 0.5563740051002242 + ], + "p50_ms": 0.6967890003579669, + "p95_ms": 0.8335399979841895, + "p99_ms": 0.8403930041822605, + "plan": { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 0.42, + "Total Cost": 85.87, + "Plan Rows": 51, + "Plan Width": 149, + "Actual Startup Time": 0.017, + "Actual Total Time": 0.03, + "Actual Rows": 51, + "Actual Loops": 1, + "Shared Hit Blocks": 5, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Index Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Scan Direction": "Forward", + "Index Name": "research_candidate", + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.42, + "Total Cost": 1396.22, + "Plan Rows": 833, + "Plan Width": 149, + "Actual Startup Time": 0.017, + "Actual Total Time": 0.024, + "Actual Rows": 51, + "Actual Loops": 1, + "Index Cond": "((chat_id = '7d62628c-5194-4dea-ae35-be479edde556'::uuid) AND (ROW(created_at, id) > ROW('2026-01-01 00:00:00+00'::timestamp with time zone, '616770c4-a850-44a9-9076-e9cacdd4f80e'::uuid)))", + "Rows Removed by Index Recheck": 0, + "Shared Hit Blocks": 5, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + } + ] + }, + "Planning": { + "Shared Hit Blocks": 0, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + }, + "Planning Time": 0.095, + "Triggers": [], + "Execution Time": 0.046 + }, + "index": "history", + "method": "keyset", + "chat_size": 900, + "offset": 0, + "index_bytes": 5914624 + }, + { + "latency_ms": [ + 1.4810689972364344, + 1.3946639955975115, + 1.325928998994641, + 3.2757269946159795, + 1.6024579963413998, + 1.2725910055451095, + 1.175740995677188, + 1.5027490007923916, + 1.2787809973815456, + 1.3538310013245791, + 1.0733240051195025, + 1.0697140023694374, + 1.1071580011048354, + 1.1448489967733622, + 1.098788998206146, + 1.0495889946469106, + 1.2060419976478443, + 0.9863409941317514, + 1.0138970028492622, + 0.9352289998787455, + 0.845413000206463, + 1.7247720024897717, + 1.5241269938996993, + 0.9874829993350431, + 1.4887549987179227, + 1.0887870012084022, + 0.9409079939359799, + 0.8257610024884343, + 0.8158380005625077, + 0.8052900011534803 + ], + "p50_ms": 1.1260034989390988, + "p95_ms": 1.7247720024897717, + "p99_ms": 3.2757269946159795, + "plan": { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 2399.2, + "Total Cost": 2426.38, + "Plan Rows": 51, + "Plan Width": 149, + "Actual Startup Time": 0.839, + "Actual Total Time": 0.849, + "Actual Rows": 51, + "Actual Loops": 1, + "Shared Hit Blocks": 200, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Index Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Scan Direction": "Forward", + "Index Name": "research_candidate", + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.42, + "Total Cost": 4775.05, + "Plan Rows": 8957, + "Plan Width": 149, + "Actual Startup Time": 0.01, + "Actual Total Time": 0.676, + "Actual Rows": 4551, + "Actual Loops": 1, + "Index Cond": "(chat_id = 'ba3c8454-879e-462b-be13-9d28f9fa80e3'::uuid)", + "Rows Removed by Index Recheck": 0, + "Shared Hit Blocks": 200, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + } + ] + }, + "Planning": { + "Shared Hit Blocks": 0, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + }, + "Planning Time": 0.076, + "Triggers": [], + "Execution Time": 0.863 + }, + "index": "history", + "method": "offset", + "chat_size": 9000, + "offset": 4499, + "index_bytes": 5914624 + }, + { + "latency_ms": [ + 0.3816450043814257, + 0.3788839967455715, + 0.3954679996240884, + 0.8452399997622706, + 0.6021760054863989, + 1.2634950035135262, + 0.473734995466657, + 0.391890003811568, + 0.3807079992839135, + 0.3770120019908063, + 0.36614900454878807, + 0.3664010000647977, + 0.5625910052913241, + 0.5033919951529242, + 0.5236270008026622, + 0.4096709963050671, + 0.37215399788692594, + 0.3675960033433512, + 0.36558300053002313, + 0.47505499969702214, + 0.5149569988134317, + 0.37991000135662034, + 0.36235400330042467, + 0.4014730002381839, + 0.43812100193463266, + 0.36362199898576364, + 0.3607659964472987, + 0.36653599818237126, + 0.3999519976787269, + 0.5351040017558262 + ], + "p50_ms": 0.3936790017178282, + "p95_ms": 0.8452399997622706, + "p99_ms": 1.2634950035135262, + "plan": { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 0.42, + "Total Cost": 31.8, + "Plan Rows": 51, + "Plan Width": 149, + "Actual Startup Time": 0.014, + "Actual Total Time": 0.029, + "Actual Rows": 51, + "Actual Loops": 1, + "Shared Hit Blocks": 6, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Index Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Scan Direction": "Forward", + "Index Name": "research_candidate", + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.42, + "Total Cost": 4720.56, + "Plan Rows": 7671, + "Plan Width": 149, + "Actual Startup Time": 0.014, + "Actual Total Time": 0.024, + "Actual Rows": 51, + "Actual Loops": 1, + "Index Cond": "((chat_id = 'ba3c8454-879e-462b-be13-9d28f9fa80e3'::uuid) AND (ROW(created_at, id) > ROW('2026-01-01 00:00:00.004499+00'::timestamp with time zone, 'fcd4a921-64ed-4ba5-a738-4de99f71a77f'::uuid)))", + "Rows Removed by Index Recheck": 0, + "Shared Hit Blocks": 6, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + } + ] + }, + "Planning": { + "Shared Hit Blocks": 0, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + }, + "Planning Time": 0.085, + "Triggers": [], + "Execution Time": 0.044 + }, + "index": "history", + "method": "keyset", + "chat_size": 9000, + "offset": 4499, + "index_bytes": 5914624 + }, + { + "latency_ms": [ + 1.6135600017150864, + 1.3720969946007244, + 1.3007110028411262, + 1.4731219998793676, + 1.474826000048779, + 1.4664629998151213, + 1.5317079960368574, + 1.3993489992571995, + 1.3513660014723428, + 1.316319998295512, + 1.3253950019134209, + 1.5030659997137263, + 1.5418350012623705, + 1.5974620037013665, + 1.505892003478948, + 1.395471001160331, + 1.4900679962011054, + 2.203759999247268, + 1.5337020013248548, + 1.4091090051806532, + 1.3321339938556775, + 1.342365998425521, + 1.286195001739543, + 1.4643109971075319, + 1.5734549961052835, + 1.5296869969461113, + 1.3815769998473115, + 1.3627119988086633, + 1.4383329980773851, + 1.4449529990088195 + ], + "p50_ms": 1.4546319980581757, + "p95_ms": 1.6135600017150864, + "p99_ms": 2.203759999247268, + "plan": { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 2710.33, + "Total Cost": 2724.15, + "Plan Rows": 51, + "Plan Width": 149, + "Actual Startup Time": 2.088, + "Actual Total Time": 2.102, + "Actual Rows": 51, + "Actual Loops": 1, + "Shared Hit Blocks": 332, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Index Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Scan Direction": "Forward", + "Index Name": "research_candidate", + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.42, + "Total Cost": 5416.72, + "Plan Rows": 19987, + "Plan Width": 149, + "Actual Startup Time": 0.008, + "Actual Total Time": 1.643, + "Actual Rows": 10051, + "Actual Loops": 1, + "Index Cond": "(chat_id = 'f8028b31-6ab5-45df-9cea-f4737a46ecf7'::uuid)", + "Rows Removed by Index Recheck": 0, + "Shared Hit Blocks": 332, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + } + ] + }, + "Planning": { + "Shared Hit Blocks": 0, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + }, + "Planning Time": 0.082, + "Triggers": [], + "Execution Time": 2.116 + }, + "index": "history", + "method": "offset", + "chat_size": 20000, + "offset": 9999, + "index_bytes": 5914624 + }, + { + "latency_ms": [ + 0.4454769950825721, + 0.4440670018084347, + 0.4423589998623356, + 0.6235500040929765, + 0.633379997452721, + 0.5034019995946437, + 0.503736999235116, + 0.6207639962667599, + 0.7563820036011748, + 0.5722540008719079, + 0.5040280011598952, + 0.48639099986758083, + 0.45730199781246483, + 0.4483440061449073, + 0.662647005810868, + 0.5345090030459687, + 0.5657180008711293, + 0.7100899965735152, + 0.6299060041783378, + 0.6707499996991828, + 0.611139003012795, + 0.6649110000580549, + 0.6576969972229563, + 0.6205929967109114, + 0.5646540012094192, + 0.555209000594914, + 0.5271549962344579, + 0.5759659979958087, + 0.5268459935905412, + 0.504037001519464 + ], + "p50_ms": 0.5651860010402743, + "p95_ms": 0.7100899965735152, + "p99_ms": 0.7563820036011748, + "plan": { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 0.42, + "Total Cost": 18.97, + "Plan Rows": 51, + "Plan Width": 149, + "Actual Startup Time": 0.008, + "Actual Total Time": 0.026, + "Actual Rows": 51, + "Actual Loops": 1, + "Shared Hit Blocks": 7, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Index Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Scan Direction": "Forward", + "Index Name": "research_candidate", + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.42, + "Total Cost": 5106.03, + "Plan Rows": 14032, + "Plan Width": 149, + "Actual Startup Time": 0.008, + "Actual Total Time": 0.02, + "Actual Rows": 51, + "Actual Loops": 1, + "Index Cond": "((chat_id = 'f8028b31-6ab5-45df-9cea-f4737a46ecf7'::uuid) AND (ROW(created_at, id) > ROW('2026-01-01 00:00:00.009999+00'::timestamp with time zone, '0d7dd609-3ecd-44a4-96d5-e97cadf683e1'::uuid)))", + "Rows Removed by Index Recheck": 0, + "Shared Hit Blocks": 7, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + } + ] + }, + "Planning": { + "Shared Hit Blocks": 0, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + }, + "Planning Time": 0.097, + "Triggers": [], + "Execution Time": 0.04 + }, + "index": "history", + "method": "keyset", + "chat_size": 20000, + "offset": 9999, + "index_bytes": 5914624 + }, + { + "latency_ms": [ + 0.587778995395638, + 0.5401719972724095, + 0.6006889962009154, + 0.7159189990488812, + 0.8219809969887137, + 0.6876290062791668, + 0.673684997309465, + 0.5503259963006712, + 0.5787960035377182, + 0.8246959987445734, + 0.7575409981654957, + 0.677413001540117, + 0.5723159993067384, + 0.5589860011241399, + 0.5469190000439994, + 0.5478349994518794, + 0.5478720049723051, + 0.5385210024542175, + 0.5334509987733327, + 0.5100069975014776, + 0.5364219978218898, + 0.5668480007443577, + 1.0376889986218885, + 0.7240350023494102, + 0.7216230005724356, + 0.6526760043925606, + 0.7018780015641823, + 0.634223993984051, + 0.7675010056118481, + 0.676235998980701 + ], + "p50_ms": 0.6174564950924832, + "p95_ms": 0.8246959987445734, + "p99_ms": 1.0376889986218885, + "plan": { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 0.95, + "Total Cost": 28.14, + "Plan Rows": 51, + "Plan Width": 149, + "Actual Startup Time": 0.011, + "Actual Total Time": 0.032, + "Actual Rows": 51, + "Actual Loops": 1, + "Shared Hit Blocks": 30, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Index Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Scan Direction": "Forward", + "Index Name": "research_candidate", + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.42, + "Total Cost": 4775.05, + "Plan Rows": 8957, + "Plan Width": 149, + "Actual Startup Time": 0.01, + "Actual Total Time": 0.026, + "Actual Rows": 52, + "Actual Loops": 1, + "Index Cond": "(chat_id = 'ba3c8454-879e-462b-be13-9d28f9fa80e3'::uuid)", + "Rows Removed by Index Recheck": 0, + "Shared Hit Blocks": 30, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + } + ] + }, + "Planning": { + "Shared Hit Blocks": 0, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + }, + "Planning Time": 0.09, + "Triggers": [], + "Execution Time": 0.046 + }, + "index": "history", + "method": "offset", + "chat_size": 9000, + "offset": 0, + "index_bytes": 5914624 + }, + { + "latency_ms": [ + 0.7358930015470833, + 0.6108699963078834, + 0.5796999976155348, + 0.5602970049949363, + 0.5543419974856079, + 0.5502990024979226, + 0.5616819980787113, + 0.5658470035996288, + 0.552246994629968, + 0.5456409999169409, + 0.6876430052216165, + 0.6681029990431853, + 0.5880600001546554, + 0.5898849994991906, + 0.6654960016021505, + 0.6986789958318695, + 0.757785004680045, + 0.6630470015807077, + 0.5274169961921871, + 0.6367399982991628, + 0.5508809990715235, + 0.5003100013709627, + 0.5159509964869358, + 0.4944179963786155, + 0.47282200102927163, + 0.5000770033802837, + 0.5181279993848875, + 0.9690329970908351, + 1.1400029979995452, + 0.6755619979230687 + ], + "p50_ms": 0.5727735006075818, + "p95_ms": 0.9690329970908351, + "p99_ms": 1.1400029979995452, + "plan": { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 0.42, + "Total Cost": 27.73, + "Plan Rows": 51, + "Plan Width": 149, + "Actual Startup Time": 0.016, + "Actual Total Time": 0.042, + "Actual Rows": 51, + "Actual Loops": 1, + "Shared Hit Blocks": 30, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Index Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Scan Direction": "Forward", + "Index Name": "research_candidate", + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.42, + "Total Cost": 4797.42, + "Plan Rows": 8956, + "Plan Width": 149, + "Actual Startup Time": 0.015, + "Actual Total Time": 0.035, + "Actual Rows": 51, + "Actual Loops": 1, + "Index Cond": "((chat_id = 'ba3c8454-879e-462b-be13-9d28f9fa80e3'::uuid) AND (ROW(created_at, id) > ROW('2026-01-01 00:00:00+00'::timestamp with time zone, 'cab44f87-4a3f-4d22-80f4-c4d283331a8c'::uuid)))", + "Rows Removed by Index Recheck": 0, + "Shared Hit Blocks": 30, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + } + ] + }, + "Planning": { + "Shared Hit Blocks": 0, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + }, + "Planning Time": 0.098, + "Triggers": [], + "Execution Time": 0.059 + }, + "index": "history", + "method": "keyset", + "chat_size": 9000, + "offset": 0, + "index_bytes": 5914624 + }, + { + "latency_ms": [ + 2.1597859959001653, + 2.143054000043776, + 3.385504001926165, + 2.3759769974276423, + 2.238868997665122, + 2.1535420019063167, + 2.2312660003080964, + 2.212485000200104, + 2.288028998009395, + 2.3606489994563162, + 2.405157996690832, + 2.438130999507848, + 9.213953999278601, + 2.710089996980969, + 2.750518004177138, + 2.6832950024981983, + 3.027013000973966, + 2.8203190013300627, + 5.871207002201118, + 2.6829939961316995, + 2.6806999958353117, + 2.4041729993768968, + 2.8797390041290782, + 2.3533929997938685, + 3.159093997965101, + 2.7677780017256737, + 2.5333340017823502, + 2.4722589951124974, + 2.6218359998892993, + 2.7011210040654987 + ], + "p50_ms": 2.5775850008358248, + "p95_ms": 5.871207002201118, + "p99_ms": 9.213953999278601, + "plan": { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 4685.9, + "Total Cost": 4686.03, + "Plan Rows": 51, + "Plan Width": 149, + "Actual Startup Time": 12.994, + "Actual Total Time": 13.005, + "Actual Rows": 51, + "Actual Loops": 1, + "Shared Hit Blocks": 648, + "Shared Read Blocks": 14, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 399, + "Temp Written Blocks": 400, + "Plans": [ + { + "Node Type": "Sort", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 4640.9, + "Total Cost": 4690.87, + "Plan Rows": 19987, + "Plan Width": 149, + "Actual Startup Time": 10.251, + "Actual Total Time": 12.287, + "Actual Rows": 18051, + "Actual Loops": 1, + "Sort Key": [ + "created_at", + "id" + ], + "Sort Method": "external merge", + "Sort Space Used": 3192, + "Sort Space Type": "Disk", + "Shared Hit Blocks": 648, + "Shared Read Blocks": 14, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 399, + "Temp Written Blocks": 400, + "Plans": [ + { + "Node Type": "Bitmap Heap Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 735.32, + "Total Cost": 3213.15, + "Plan Rows": 19987, + "Plan Width": 149, + "Actual Startup Time": 1.35, + "Actual Total Time": 3.607, + "Actual Rows": 20000, + "Actual Loops": 1, + "Recheck Cond": "(chat_id = 'f8028b31-6ab5-45df-9cea-f4737a46ecf7'::uuid)", + "Rows Removed by Index Recheck": 0, + "Exact Heap Blocks": 516, + "Lossy Heap Blocks": 0, + "Shared Hit Blocks": 648, + "Shared Read Blocks": 14, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Bitmap Index Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Index Name": "research_candidate", + "Startup Cost": 0.0, + "Total Cost": 730.32, + "Plan Rows": 19987, + "Plan Width": 0, + "Actual Startup Time": 0.815, + "Actual Total Time": 0.816, + "Actual Rows": 20000, + "Actual Loops": 1, + "Index Cond": "(chat_id = 'f8028b31-6ab5-45df-9cea-f4737a46ecf7'::uuid)", + "Shared Hit Blocks": 132, + "Shared Read Blocks": 14, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + } + ] + } + ] + } + ] + }, + "Planning": { + "Shared Hit Blocks": 0, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + }, + "Planning Time": 0.08, + "Triggers": [], + "Execution Time": 13.511 + }, + "index": "history", + "method": "offset", + "chat_size": 20000, + "offset": 17999, + "index_bytes": 5914624 + }, + { + "latency_ms": [ + 0.5198670041863807, + 1.3132999956724234, + 0.5704319992219098, + 0.5275380026432686, + 0.659563003864605, + 0.5366629993659444, + 0.5489780014613643, + 0.5181110027479008, + 0.5179820000194013, + 0.42722600483102724, + 0.44683099986286834, + 0.5417330030468293, + 0.48727499961387366, + 0.4780469971592538, + 0.41588800377212465, + 0.398335003410466, + 0.3914159970008768, + 0.4089659996679984, + 0.39342699892586097, + 0.45234400022309273, + 0.4025570015073754, + 0.4003149952040985, + 0.5059100003563799, + 0.5105719974380918, + 0.4458640032680705, + 0.40681500104255974, + 0.39093200030038133, + 0.3923299955204129, + 0.46272799954749644, + 0.5015220012865029 + ], + "p50_ms": 0.4703874983533751, + "p95_ms": 0.659563003864605, + "p99_ms": 1.3132999956724234, + "plan": { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 0.42, + "Total Cost": 23.57, + "Plan Rows": 51, + "Plan Width": 149, + "Actual Startup Time": 0.013, + "Actual Total Time": 0.027, + "Actual Rows": 51, + "Actual Loops": 1, + "Shared Hit Blocks": 6, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Index Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Scan Direction": "Forward", + "Index Name": "research_candidate", + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.42, + "Total Cost": 4912.71, + "Plan Rows": 10822, + "Plan Width": 149, + "Actual Startup Time": 0.012, + "Actual Total Time": 0.021, + "Actual Rows": 51, + "Actual Loops": 1, + "Index Cond": "((chat_id = 'f8028b31-6ab5-45df-9cea-f4737a46ecf7'::uuid) AND (ROW(created_at, id) > ROW('2026-01-01 00:00:00.017999+00'::timestamp with time zone, '9c0bfcbc-8dae-4753-8262-16d0bb97d8b3'::uuid)))", + "Rows Removed by Index Recheck": 0, + "Shared Hit Blocks": 6, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + } + ] + }, + "Planning": { + "Shared Hit Blocks": 0, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + }, + "Planning Time": 0.088, + "Triggers": [], + "Execution Time": 0.04 + }, + "index": "history", + "method": "keyset", + "chat_size": 20000, + "offset": 17999, + "index_bytes": 5914624 + }, + { + "latency_ms": [ + 0.479512003948912, + 0.4271770012564957, + 0.5309779953677207, + 0.5216400022618473, + 0.5825429980177432, + 0.5045520010753535, + 0.6988210006966256, + 0.523556002008263, + 0.5369650025386363, + 0.5156600018381141, + 0.5214760021772236, + 0.5255680007394403, + 0.5086640012450516, + 0.6311659963103011, + 1.7127210012404248, + 0.5502459971467033, + 0.44020999484928325, + 0.41120399691862985, + 0.40665899723535404, + 0.402146004489623, + 0.40476499998476356, + 0.4043590015498921, + 0.4059269995195791, + 0.48876400251174346, + 0.5792929950985126, + 0.5830469963257201, + 0.5412110040197149, + 0.5422649992397055, + 0.5245139982434921, + 0.4948679998051375 + ], + "p50_ms": 0.5215580022195354, + "p95_ms": 0.6988210006966256, + "p99_ms": 1.7127210012404248, + "plan": { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 753.33, + "Total Cost": 838.66, + "Plan Rows": 51, + "Plan Width": 149, + "Actual Startup Time": 0.089, + "Actual Total Time": 0.1, + "Actual Rows": 51, + "Actual Loops": 1, + "Shared Hit Blocks": 18, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Index Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Scan Direction": "Forward", + "Index Name": "research_candidate", + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.42, + "Total Cost": 1394.14, + "Plan Rows": 833, + "Plan Width": 149, + "Actual Startup Time": 0.01, + "Actual Total Time": 0.077, + "Actual Rows": 501, + "Actual Loops": 1, + "Index Cond": "(chat_id = '7d62628c-5194-4dea-ae35-be479edde556'::uuid)", + "Rows Removed by Index Recheck": 0, + "Shared Hit Blocks": 18, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + } + ] + }, + "Planning": { + "Shared Hit Blocks": 0, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + }, + "Planning Time": 0.079, + "Triggers": [], + "Execution Time": 0.111 + }, + "index": "history", + "method": "offset", + "chat_size": 900, + "offset": 449, + "index_bytes": 5914624 + }, + { + "latency_ms": [ + 0.49041699821827933, + 0.504267998621799, + 0.4886880051344633, + 0.4677639954024926, + 0.4878740001004189, + 0.45970300561748445, + 0.42051399941556156, + 0.5275559960864484, + 0.5016069990233518, + 0.48549000348430127, + 0.48262500058626756, + 0.49103899800684303, + 0.46016099804546684, + 0.4431300039868802, + 0.4447979954420589, + 0.4257340042386204, + 0.4143350015510805, + 0.419921001594048, + 0.42088299960596487, + 0.4277059997548349, + 0.44513100147014484, + 0.4173649940639734, + 0.5165850016055629, + 0.41053500171983615, + 0.4118290016776882, + 0.4168640007264912, + 0.4080239959876053, + 0.40423800237476826, + 0.7842170016374439, + 0.6439930002670735 + ], + "p50_ms": 0.45241700354381464, + "p95_ms": 0.6439930002670735, + "p99_ms": 0.7842170016374439, + "plan": { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 0.42, + "Total Cost": 85.97, + "Plan Rows": 51, + "Plan Width": 149, + "Actual Startup Time": 0.009, + "Actual Total Time": 0.019, + "Actual Rows": 51, + "Actual Loops": 1, + "Shared Hit Blocks": 6, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Index Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Scan Direction": "Forward", + "Index Name": "research_candidate", + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.42, + "Total Cost": 1370.91, + "Plan Rows": 817, + "Plan Width": 149, + "Actual Startup Time": 0.008, + "Actual Total Time": 0.015, + "Actual Rows": 51, + "Actual Loops": 1, + "Index Cond": "((chat_id = '7d62628c-5194-4dea-ae35-be479edde556'::uuid) AND (ROW(created_at, id) > ROW('2026-01-01 00:00:00.000449+00'::timestamp with time zone, '7a97433e-635e-437a-98d0-544cf1b1628c'::uuid)))", + "Rows Removed by Index Recheck": 0, + "Shared Hit Blocks": 6, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + } + ] + }, + "Planning": { + "Shared Hit Blocks": 0, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + }, + "Planning Time": 0.086, + "Triggers": [], + "Execution Time": 0.032 + }, + "index": "history", + "method": "keyset", + "chat_size": 900, + "offset": 449, + "index_bytes": 5914624 + }, + { + "latency_ms": [ + 0.42121299338759854, + 0.42246899829478934, + 0.4123359976802021, + 0.41455799510004, + 0.4102570019313134, + 0.5021010001655668, + 0.48958499974105507, + 0.5113530060043558, + 0.51451800391078, + 0.5305909944581799, + 0.4293120000511408, + 0.3775389996008016, + 0.3636760011431761, + 0.37370999780250713, + 0.3532880000420846, + 0.39362100505968556, + 0.4173519992036745, + 0.44219900155439973, + 0.45486900489777327, + 0.42671999835874885, + 0.4159050004091114, + 0.4297010018490255, + 0.4163859994150698, + 0.4225980010232888, + 0.42709700210252777, + 0.43029800144722685, + 0.4499499991652556, + 0.4185700017842464, + 0.41439499909756705, + 0.9611779969418421 + ], + "p50_ms": 0.4225334996590391, + "p95_ms": 0.5305909944581799, + "p99_ms": 0.9611779969418421, + "plan": { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 99.54, + "Total Cost": 164.97, + "Plan Rows": 33, + "Plan Width": 149, + "Actual Startup Time": 0.021, + "Actual Total Time": 0.033, + "Actual Rows": 50, + "Actual Loops": 1, + "Shared Hit Blocks": 8, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Index Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Scan Direction": "Forward", + "Index Name": "research_candidate", + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.42, + "Total Cost": 164.97, + "Plan Rows": 83, + "Plan Width": 149, + "Actual Startup Time": 0.012, + "Actual Total Time": 0.026, + "Actual Rows": 100, + "Actual Loops": 1, + "Index Cond": "(chat_id = '91d2ecd0-11c0-472f-a67a-c678efc87df1'::uuid)", + "Rows Removed by Index Recheck": 0, + "Shared Hit Blocks": 8, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + } + ] + }, + "Planning": { + "Shared Hit Blocks": 0, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + }, + "Planning Time": 0.094, + "Triggers": [], + "Execution Time": 0.047 + }, + "index": "history", + "method": "offset", + "chat_size": 100, + "offset": 49, + "index_bytes": 5914624 + }, + { + "latency_ms": [ + 0.5377440029405989, + 0.4241989954607561, + 0.4240359994582832, + 0.4877989995293319, + 0.4747299972223118, + 0.49635599862085655, + 0.5120909991092049, + 0.49541200132807717, + 0.49829499766929075, + 0.4871849960181862, + 0.47803999768802896, + 0.4896600003121421, + 0.48341899673687294, + 0.4846800002269447, + 0.5136089966981672, + 0.48540900024818256, + 0.49439699796494097, + 0.4910870047751814, + 0.46302799455588683, + 0.4310750009608455, + 0.4516459957812913, + 0.5191829986870289, + 0.37041599716758355, + 0.35645600291900337, + 0.35448000562610105, + 0.36524899769574404, + 0.3613199951360002, + 0.36737899790750816, + 0.4147520012338646, + 0.44369299575919285 + ], + "p50_ms": 0.48072949721245095, + "p95_ms": 0.5191829986870289, + "p99_ms": 0.5377440029405989, + "plan": { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 0.42, + "Total Cost": 101.65, + "Plan Rows": 51, + "Plan Width": 149, + "Actual Startup Time": 0.009, + "Actual Total Time": 0.022, + "Actual Rows": 50, + "Actual Loops": 1, + "Shared Hit Blocks": 7, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Index Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Scan Direction": "Forward", + "Index Name": "research_candidate", + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.42, + "Total Cost": 165.17, + "Plan Rows": 83, + "Plan Width": 149, + "Actual Startup Time": 0.009, + "Actual Total Time": 0.017, + "Actual Rows": 50, + "Actual Loops": 1, + "Index Cond": "((chat_id = '91d2ecd0-11c0-472f-a67a-c678efc87df1'::uuid) AND (ROW(created_at, id) > ROW('2026-01-01 00:00:00.000049+00'::timestamp with time zone, '9d89ca28-6a7d-47bd-b745-ab58b7af585f'::uuid)))", + "Rows Removed by Index Recheck": 0, + "Shared Hit Blocks": 7, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + } + ] + }, + "Planning": { + "Shared Hit Blocks": 0, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + }, + "Planning Time": 0.107, + "Triggers": [], + "Execution Time": 0.036 + }, + "index": "history", + "method": "keyset", + "chat_size": 100, + "offset": 49, + "index_bytes": 5914624 + }, + { + "latency_ms": [ + 1.3470960038830526, + 1.3188960001571104, + 1.354751002509147, + 1.3650910041178577, + 1.2905709954793565, + 1.2459930003387854, + 1.339727001322899, + 1.3273889999254607, + 1.5528190051554702, + 1.4218529977370054, + 1.3030339978286065, + 1.255778995982837, + 1.2515130001702346, + 1.4766909953323193, + 1.3791259989375249, + 1.3940909993834794, + 1.2950219970662147, + 1.277344003028702, + 1.3180400055716746, + 1.4221480014384724, + 1.4403599998331629, + 1.5944490005495027, + 1.4019449954503216, + 1.335167995421216, + 1.3165069976821542, + 1.2968919982085936, + 1.2453949966584332, + 1.272229004825931, + 1.3589800000772811, + 1.3784010006929748 + ], + "p50_ms": 1.3374474983720575, + "p95_ms": 1.5528190051554702, + "p99_ms": 1.5944490005495027, + "plan": { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 3278.02, + "Total Cost": 3278.15, + "Plan Rows": 51, + "Plan Width": 149, + "Actual Startup Time": 4.414, + "Actual Total Time": 4.423, + "Actual Rows": 51, + "Actual Loops": 1, + "Shared Hit Blocks": 320, + "Shared Read Blocks": 5, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Sort", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 3257.77, + "Total Cost": 3280.16, + "Plan Rows": 8957, + "Plan Width": 149, + "Actual Startup Time": 3.602, + "Actual Total Time": 4.102, + "Actual Rows": 8151, + "Actual Loops": 1, + "Sort Key": [ + "created_at", + "id" + ], + "Sort Method": "quicksort", + "Sort Space Used": 2392, + "Sort Space Type": "Memory", + "Shared Hit Blocks": 320, + "Shared Read Blocks": 5, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Bitmap Heap Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 329.83, + "Total Cost": 2669.8, + "Plan Rows": 8957, + "Plan Width": 149, + "Actual Startup Time": 0.384, + "Actual Total Time": 1.807, + "Actual Rows": 9000, + "Actual Loops": 1, + "Recheck Cond": "(chat_id = 'ba3c8454-879e-462b-be13-9d28f9fa80e3'::uuid)", + "Rows Removed by Index Recheck": 0, + "Exact Heap Blocks": 258, + "Lossy Heap Blocks": 0, + "Shared Hit Blocks": 320, + "Shared Read Blocks": 5, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Bitmap Index Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Index Name": "research_candidate", + "Startup Cost": 0.0, + "Total Cost": 327.6, + "Plan Rows": 8957, + "Plan Width": 0, + "Actual Startup Time": 0.349, + "Actual Total Time": 0.35, + "Actual Rows": 9000, + "Actual Loops": 1, + "Index Cond": "(chat_id = 'ba3c8454-879e-462b-be13-9d28f9fa80e3'::uuid)", + "Shared Hit Blocks": 62, + "Shared Read Blocks": 5, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + } + ] + } + ] + } + ] + }, + "Planning": { + "Shared Hit Blocks": 0, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + }, + "Planning Time": 0.078, + "Triggers": [], + "Execution Time": 4.448 + }, + "index": "history", + "method": "offset", + "chat_size": 9000, + "offset": 8099, + "index_bytes": 5914624 + }, + { + "latency_ms": [ + 0.485843003843911, + 0.40160999924410135, + 0.3997849998995662, + 0.3740069951163605, + 0.38725299964426085, + 0.37270299799274653, + 0.37195999902905896, + 0.3712050020112656, + 0.37339799746405333, + 0.37152599543333054, + 0.37882200558669865, + 0.3672680031741038, + 0.36675899900728837, + 0.37784100277349353, + 0.3706310017150827, + 0.36329599970486015, + 0.4495670000324026, + 0.4634569995687343, + 0.38394400326069444, + 0.37144099769648165, + 0.3670450023491867, + 0.37656300264643505, + 0.5218310034251772, + 0.6349469986162148, + 0.8042379995458759, + 0.4866679955739528, + 0.42457199742784724, + 0.3963549970649183, + 0.4441319979378022, + 0.5182579989195801 + ], + "p50_ms": 0.38138300442369655, + "p95_ms": 0.6349469986162148, + "p99_ms": 0.8042379995458759, + "plan": { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 0.42, + "Total Cost": 35.83, + "Plan Rows": 51, + "Plan Width": 149, + "Actual Startup Time": 0.011, + "Actual Total Time": 0.022, + "Actual Rows": 51, + "Actual Loops": 1, + "Shared Hit Blocks": 6, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Index Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Scan Direction": "Forward", + "Index Name": "research_candidate", + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.42, + "Total Cost": 4662.44, + "Plan Rows": 6714, + "Plan Width": 149, + "Actual Startup Time": 0.011, + "Actual Total Time": 0.017, + "Actual Rows": 51, + "Actual Loops": 1, + "Index Cond": "((chat_id = 'ba3c8454-879e-462b-be13-9d28f9fa80e3'::uuid) AND (ROW(created_at, id) > ROW('2026-01-01 00:00:00.008099+00'::timestamp with time zone, 'dd696626-2777-4e36-86e3-a7247b012df2'::uuid)))", + "Rows Removed by Index Recheck": 0, + "Shared Hit Blocks": 6, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + } + ] + }, + "Planning": { + "Shared Hit Blocks": 0, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + }, + "Planning Time": 0.091, + "Triggers": [], + "Execution Time": 0.034 + }, + "index": "history", + "method": "keyset", + "chat_size": 9000, + "offset": 8099, + "index_bytes": 5914624 + }, + { + "latency_ms": [ + 0.43511799594853073, + 0.4351440002210438, + 0.45624499762197956, + 0.43671500316122547, + 0.7427520031342283, + 8.007318996533286, + 1.4893420011503622, + 0.8681710023665801, + 0.7813890042598359, + 0.6063280015951023, + 0.5674210042343475, + 0.6395879972842522, + 0.5428110016509891, + 0.5881210017832927, + 0.5943120049778372, + 0.5981670037726872, + 0.6328579984256066, + 0.5855819981661625, + 0.5974519954179414, + 0.6280779998633079, + 1.8231220019515604, + 0.8399840007768944, + 0.5655889981426299, + 0.5761639986303635, + 0.9924699988914654, + 1.185000997793395, + 2.982277001137845, + 0.7016410017968155, + 0.5976609973004088, + 0.5401550006354228 + ], + "p50_ms": 0.6022475026838947, + "p95_ms": 2.982277001137845, + "p99_ms": 8.007318996533286, + "plan": { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 1355.66, + "Total Cost": 1394.14, + "Plan Rows": 23, + "Plan Width": 149, + "Actual Startup Time": 0.167, + "Actual Total Time": 0.179, + "Actual Rows": 51, + "Actual Loops": 1, + "Shared Hit Blocks": 29, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Index Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Scan Direction": "Forward", + "Index Name": "research_candidate", + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.42, + "Total Cost": 1394.14, + "Plan Rows": 833, + "Plan Width": 149, + "Actual Startup Time": 0.008, + "Actual Total Time": 0.143, + "Actual Rows": 861, + "Actual Loops": 1, + "Index Cond": "(chat_id = '7d62628c-5194-4dea-ae35-be479edde556'::uuid)", + "Rows Removed by Index Recheck": 0, + "Shared Hit Blocks": 29, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + } + ] + }, + "Planning": { + "Shared Hit Blocks": 0, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + }, + "Planning Time": 0.077, + "Triggers": [], + "Execution Time": 0.19 + }, + "index": "history", + "method": "offset", + "chat_size": 900, + "offset": 809, + "index_bytes": 5914624 + }, + { + "latency_ms": [ + 0.4282500012777746, + 0.38997999945422634, + 0.382511003408581, + 0.3562459969543852, + 0.3871689987136051, + 0.6670260045211762, + 0.7668449979973957, + 0.7706949982093647, + 0.5243959967629053, + 0.3951519975089468, + 0.409628999477718, + 0.3816349999397062, + 0.3717479994520545, + 0.3570850021787919, + 0.36206399818183854, + 0.3713570040417835, + 0.36530999932438135, + 0.36276700120652094, + 0.37293599598342553, + 0.39776499761501327, + 0.4116100026294589, + 0.5272990019875579, + 0.503426999785006, + 0.5707700038328767, + 0.49904899788089097, + 0.477237997984048, + 0.49295200005872175, + 0.4303720052121207, + 0.388777996704448, + 0.38011500146239996 + ], + "p50_ms": 0.39645849756198004, + "p95_ms": 0.7668449979973957, + "p99_ms": 0.7706949982093647, + "plan": { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 0.42, + "Total Cost": 86.14, + "Plan Rows": 51, + "Plan Width": 149, + "Actual Startup Time": 0.007, + "Actual Total Time": 0.019, + "Actual Rows": 51, + "Actual Loops": 1, + "Shared Hit Blocks": 6, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Index Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Scan Direction": "Forward", + "Index Name": "research_candidate", + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.42, + "Total Cost": 1356.83, + "Plan Rows": 807, + "Plan Width": 149, + "Actual Startup Time": 0.006, + "Actual Total Time": 0.014, + "Actual Rows": 51, + "Actual Loops": 1, + "Index Cond": "((chat_id = '7d62628c-5194-4dea-ae35-be479edde556'::uuid) AND (ROW(created_at, id) > ROW('2026-01-01 00:00:00.000809+00'::timestamp with time zone, 'bf3aad6a-a237-41ef-986f-1ab253e8bb90'::uuid)))", + "Rows Removed by Index Recheck": 0, + "Shared Hit Blocks": 6, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + } + ] + }, + "Planning": { + "Shared Hit Blocks": 0, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + }, + "Planning Time": 0.088, + "Triggers": [], + "Execution Time": 0.029 + }, + "index": "history", + "method": "keyset", + "chat_size": 900, + "offset": 809, + "index_bytes": 5914624 + }, + { + "latency_ms": [ + 0.3981509944424033, + 0.4005519949714653, + 0.36950000503566116, + 0.3636879991972819, + 0.3594510053517297, + 0.3624140008469112, + 0.3613169974414632, + 0.38401100027840585, + 0.6519860035041347, + 0.4900249987258576, + 0.38204200245672837, + 0.38628200127277523, + 0.4489479979383759, + 0.4066520050400868, + 0.3720860040630214, + 0.3633680025814101, + 0.36067800101591274, + 0.35699099680641666, + 0.3793180003412999, + 0.3590459964470938, + 0.3663179959403351, + 0.36044699663762003, + 0.3569489999790676, + 0.3582010031095706, + 0.9552379997330718, + 0.5923539938521571, + 0.5007420040783472, + 0.5134250022820197, + 0.391476001823321, + 0.37311099731596187 + ], + "p50_ms": 0.3762144988286309, + "p95_ms": 0.6519860035041347, + "p99_ms": 0.9552379997330718, + "plan": { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 0.69, + "Total Cost": 14.51, + "Plan Rows": 51, + "Plan Width": 149, + "Actual Startup Time": 0.006, + "Actual Total Time": 0.019, + "Actual Rows": 51, + "Actual Loops": 1, + "Shared Hit Blocks": 17, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Index Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Scan Direction": "Forward", + "Index Name": "research_candidate", + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.42, + "Total Cost": 5416.72, + "Plan Rows": 19987, + "Plan Width": 149, + "Actual Startup Time": 0.005, + "Actual Total Time": 0.014, + "Actual Rows": 52, + "Actual Loops": 1, + "Index Cond": "(chat_id = 'f8028b31-6ab5-45df-9cea-f4737a46ecf7'::uuid)", + "Rows Removed by Index Recheck": 0, + "Shared Hit Blocks": 17, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + } + ] + }, + "Planning": { + "Shared Hit Blocks": 0, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + }, + "Planning Time": 0.08, + "Triggers": [], + "Execution Time": 0.029 + }, + "index": "history", + "method": "offset", + "chat_size": 20000, + "offset": 0, + "index_bytes": 5914624 + }, + { + "latency_ms": [ + 0.3559949982445687, + 0.35943200055044144, + 0.35922100505558774, + 0.35753200063481927, + 0.37605899706250057, + 0.36733999877469614, + 0.37973000144120306, + 0.36284200177760795, + 0.3583249999792315, + 0.3626020043157041, + 0.3597590039134957, + 0.3577610041247681, + 0.3562640049494803, + 0.3561100020306185, + 0.3569129985407926, + 0.5082389980088919, + 0.4783159965882078, + 0.40960699698189273, + 0.36045299930265173, + 0.37476400029845536, + 0.7482000000891276, + 0.5258859964669682, + 0.444060999143403, + 0.3779840044444427, + 0.35997699887957424, + 0.35963700065622106, + 0.5653120024362579, + 0.6478579962276854, + 0.5221190003794618, + 0.7255419986904599 + ], + "p50_ms": 0.36509100027615204, + "p95_ms": 0.7255419986904599, + "p99_ms": 0.7482000000891276, + "plan": { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 0.42, + "Total Cost": 14.37, + "Plan Rows": 51, + "Plan Width": 149, + "Actual Startup Time": 0.013, + "Actual Total Time": 0.031, + "Actual Rows": 51, + "Actual Loops": 1, + "Shared Hit Blocks": 17, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Index Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Scan Direction": "Forward", + "Index Name": "research_candidate", + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.42, + "Total Cost": 5466.64, + "Plan Rows": 19985, + "Plan Width": 149, + "Actual Startup Time": 0.012, + "Actual Total Time": 0.025, + "Actual Rows": 51, + "Actual Loops": 1, + "Index Cond": "((chat_id = 'f8028b31-6ab5-45df-9cea-f4737a46ecf7'::uuid) AND (ROW(created_at, id) > ROW('2026-01-01 00:00:00+00'::timestamp with time zone, 'b40ef452-0402-40ff-8ff4-c321419228d3'::uuid)))", + "Rows Removed by Index Recheck": 0, + "Shared Hit Blocks": 17, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + } + ] + }, + "Planning": { + "Shared Hit Blocks": 0, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + }, + "Planning Time": 0.09, + "Triggers": [], + "Execution Time": 0.045 + }, + "index": "history", + "method": "keyset", + "chat_size": 20000, + "offset": 0, + "index_bytes": 5914624 + }, + { + "latency_ms": [ + 4.144758000620641, + 3.941021997889038, + 4.739017997053452, + 4.267783995601349, + 4.156882998358924, + 4.786900994076859, + 4.454741996596567, + 4.535530002613086, + 4.246249001880642, + 4.698350996477529, + 7.185652997577563, + 4.623253997124266, + 4.441967997991014, + 4.440188000444323, + 4.244376999849919, + 4.024957997899037, + 4.0530590049456805, + 4.219534996082075, + 4.4594179998966865, + 4.180941003141925, + 4.262390997610055, + 4.4450760033214465, + 4.396593998535536, + 4.151025001192465, + 4.518964000453707, + 5.365469005482737, + 4.557530999591108, + 4.605492002156097, + 4.486855999857653, + 4.561180998280179 + ], + "p50_ms": 4.44352200065623, + "p95_ms": 5.365469005482737, + "p99_ms": 7.185652997577563, + "plan": { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 4155.15, + "Total Cost": 4161.2, + "Plan Rows": 51, + "Plan Width": 149, + "Actual Startup Time": 6.55, + "Actual Total Time": 6.561, + "Actual Rows": 51, + "Actual Loops": 1, + "Shared Hit Blocks": 1301, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Index Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Scan Direction": "Forward", + "Index Name": "research_candidate", + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.42, + "Total Cost": 8326.49, + "Plan Rows": 70140, + "Plan Width": 149, + "Actual Startup Time": 0.011, + "Actual Total Time": 5.145, + "Actual Rows": 35051, + "Actual Loops": 1, + "Index Cond": "(chat_id = '48c201d1-9d95-4ce9-90f7-019e28b812ba'::uuid)", + "Rows Removed by Index Recheck": 0, + "Shared Hit Blocks": 1301, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + } + ] + }, + "Planning": { + "Shared Hit Blocks": 0, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + }, + "Planning Time": 0.074, + "Triggers": [], + "Execution Time": 6.576 + }, + "index": "history", + "method": "offset", + "chat_size": 70000, + "offset": 34999, + "index_bytes": 5914624 + }, + { + "latency_ms": [ + 0.39975000254344195, + 0.3998620013589971, + 0.37713000347139314, + 0.3706199931912124, + 0.37248000444378704, + 0.37317300302674994, + 0.36979799915570766, + 0.3711640019901097, + 0.43262600229354575, + 0.4351679963292554, + 0.4605880021699704, + 0.3702440008055419, + 0.36284000088926405, + 0.3592350039980374, + 0.36197099689161405, + 0.3612119980971329, + 0.36012900091009215, + 0.392091998946853, + 0.38925099943298846, + 0.3678499997477047, + 0.3613400040194392, + 0.3611229985835962, + 0.3605660022003576, + 0.3811209971900098, + 0.3665959957288578, + 0.36957699921913445, + 0.3612260043155402, + 0.3652280065580271, + 0.361090998922009, + 0.3609340055845678 + ], + "p50_ms": 0.36968749918742105, + "p95_ms": 0.4351679963292554, + "p99_ms": 0.4605880021699704, + "plan": { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 0.42, + "Total Cost": 12.32, + "Plan Rows": 51, + "Plan Width": 149, + "Actual Startup Time": 0.009, + "Actual Total Time": 0.019, + "Actual Rows": 51, + "Actual Loops": 1, + "Shared Hit Blocks": 6, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Index Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Scan Direction": "Forward", + "Index Name": "research_candidate", + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.42, + "Total Cost": 5745.04, + "Plan Rows": 24612, + "Plan Width": 149, + "Actual Startup Time": 0.008, + "Actual Total Time": 0.014, + "Actual Rows": 51, + "Actual Loops": 1, + "Index Cond": "((chat_id = '48c201d1-9d95-4ce9-90f7-019e28b812ba'::uuid) AND (ROW(created_at, id) > ROW('2026-01-01 00:00:00.034999+00'::timestamp with time zone, 'bcaf6f3b-bf59-429c-9ccd-d8363212746d'::uuid)))", + "Rows Removed by Index Recheck": 0, + "Shared Hit Blocks": 6, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + } + ] + }, + "Planning": { + "Shared Hit Blocks": 0, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + }, + "Planning Time": 0.088, + "Triggers": [], + "Execution Time": 0.03 + }, + "index": "history", + "method": "keyset", + "chat_size": 70000, + "offset": 34999, + "index_bytes": 5914624 + }, + { + "latency_ms": [ + 0.1895380046335049, + 0.2043779968516901, + 1.120195993280504, + 0.7044019948807545, + 0.5977519977022894, + 0.37819000135641545, + 0.32187600299948826, + 0.2932249990408309, + 0.3925019991584122, + 0.3028229984920472, + 0.32050200388766825, + 0.22731100034434348, + 0.20883200340904295, + 0.20468699949560687, + 0.2027629961958155, + 0.20203700114507228, + 0.20266699721105397, + 0.20272700203349814, + 0.20283400226617232, + 0.2128870037267916, + 0.2020479951170273, + 0.19813999824691564, + 0.1992679972318001, + 0.1974990009330213, + 0.19749400235014036, + 0.2619239967316389, + 0.28918200405314565, + 0.22190099844010547, + 0.2070179980364628, + 0.2048070018645376 + ], + "p50_ms": 0.20792500072275288, + "p95_ms": 0.7044019948807545, + "p99_ms": 1.120195993280504, + "plan": { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 164.97, + "Total Cost": 166.95, + "Plan Rows": 1, + "Plan Width": 149, + "Actual Startup Time": 0.02, + "Actual Total Time": 0.023, + "Actual Rows": 10, + "Actual Loops": 1, + "Shared Hit Blocks": 8, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Index Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Scan Direction": "Forward", + "Index Name": "research_candidate", + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.42, + "Total Cost": 164.97, + "Plan Rows": 83, + "Plan Width": 149, + "Actual Startup Time": 0.005, + "Actual Total Time": 0.018, + "Actual Rows": 100, + "Actual Loops": 1, + "Index Cond": "(chat_id = '91d2ecd0-11c0-472f-a67a-c678efc87df1'::uuid)", + "Rows Removed by Index Recheck": 0, + "Shared Hit Blocks": 8, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + } + ] + }, + "Planning": { + "Shared Hit Blocks": 0, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + }, + "Planning Time": 0.074, + "Triggers": [], + "Execution Time": 0.031 + }, + "index": "history", + "method": "offset", + "chat_size": 100, + "offset": 89, + "index_bytes": 5914624 + }, + { + "latency_ms": [ + 0.1863650031737052, + 0.18498000281397253, + 0.18992699915543199, + 0.21769700106233358, + 0.18662399816093966, + 0.18757999350782484, + 0.19487200188450515, + 0.27643999783322215, + 0.23694600531598553, + 0.19789499492617324, + 0.18886999896494672, + 0.1886429963633418, + 0.18864199955714867, + 0.187443001777865, + 0.18586999794933945, + 0.18696000188356265, + 0.1861529963207431, + 0.18678199558053166, + 0.19959900237154216, + 0.27591300022322685, + 0.2104660015902482, + 0.19087999680778012, + 0.18730799638433382, + 0.18653099687071517, + 0.20731599943246692, + 0.18864300363929942, + 0.18676499894354492, + 0.44316799903754145, + 0.26997099485015497, + 0.20712200057459995 + ], + "p50_ms": 0.18875650130212307, + "p95_ms": 0.27643999783322215, + "p99_ms": 0.44316799903754145, + "plan": { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 0.42, + "Total Cost": 101.65, + "Plan Rows": 51, + "Plan Width": 149, + "Actual Startup Time": 0.006, + "Actual Total Time": 0.009, + "Actual Rows": 10, + "Actual Loops": 1, + "Shared Hit Blocks": 5, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Index Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Scan Direction": "Forward", + "Index Name": "research_candidate", + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.42, + "Total Cost": 165.17, + "Plan Rows": 83, + "Plan Width": 149, + "Actual Startup Time": 0.005, + "Actual Total Time": 0.008, + "Actual Rows": 10, + "Actual Loops": 1, + "Index Cond": "((chat_id = '91d2ecd0-11c0-472f-a67a-c678efc87df1'::uuid) AND (ROW(created_at, id) > ROW('2026-01-01 00:00:00.000089+00'::timestamp with time zone, '5146cf63-b19e-468e-9b3e-499c00b728e5'::uuid)))", + "Rows Removed by Index Recheck": 0, + "Shared Hit Blocks": 5, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + } + ] + }, + "Planning": { + "Shared Hit Blocks": 0, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + }, + "Planning Time": 0.077, + "Triggers": [], + "Execution Time": 0.018 + }, + "index": "history", + "method": "keyset", + "chat_size": 100, + "offset": 89, + "index_bytes": 5914624 + }, + { + "latency_ms": [ + 0.5535230011446401, + 0.4391710026538931, + 0.3751799958990887, + 0.36142200406175107, + 0.3610319981817156, + 0.5201120002311654, + 0.41536399658070877, + 0.37611900188494474, + 0.3668550052680075, + 0.3647620033007115, + 0.38747399958083406, + 0.37152800359763205, + 0.36764799733646214, + 0.35877800110029057, + 0.35709800431504846, + 0.35408899566391483, + 0.35719500010600314, + 0.35636000393424183, + 0.35532099718693644, + 0.37555599556071684, + 0.3795620068558492, + 0.36280399945098907, + 0.35671099612955004, + 0.5877490038983524, + 0.7080259965732694, + 0.583736997214146, + 0.594406999880448, + 0.5454599959193729, + 0.49302700062980875, + 0.481276998471003 + ], + "p50_ms": 0.37536799572990276, + "p95_ms": 0.594406999880448, + "p99_ms": 0.7080259965732694, + "plan": { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 0.54, + "Total Cost": 6.59, + "Plan Rows": 51, + "Plan Width": 149, + "Actual Startup Time": 0.011, + "Actual Total Time": 0.021, + "Actual Rows": 51, + "Actual Loops": 1, + "Shared Hit Blocks": 4, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Index Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Scan Direction": "Forward", + "Index Name": "research_candidate", + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.42, + "Total Cost": 8326.49, + "Plan Rows": 70140, + "Plan Width": 149, + "Actual Startup Time": 0.01, + "Actual Total Time": 0.016, + "Actual Rows": 52, + "Actual Loops": 1, + "Index Cond": "(chat_id = '48c201d1-9d95-4ce9-90f7-019e28b812ba'::uuid)", + "Rows Removed by Index Recheck": 0, + "Shared Hit Blocks": 4, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + } + ] + }, + "Planning": { + "Shared Hit Blocks": 0, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + }, + "Planning Time": 0.109, + "Triggers": [], + "Execution Time": 0.033 + }, + "index": "history", + "method": "offset", + "chat_size": 70000, + "offset": 0, + "index_bytes": 5914624 + }, + { + "latency_ms": [ + 0.6324729984044097, + 0.5795600009150803, + 0.5606800041277893, + 0.5329880004865117, + 0.48253799468511716, + 0.8914009958971292, + 0.6468110004789196, + 0.8698279998498037, + 0.6285540002863854, + 0.4742300006910227, + 0.5748289986513555, + 0.4604010027833283, + 0.7608310042996891, + 0.43794200610136613, + 0.3880720032611862, + 0.4123879989492707, + 0.5198559956625104, + 0.48604499897919595, + 0.4622429987648502, + 0.37876799615332857, + 0.4570599994622171, + 0.5583249949268065, + 0.4685380044975318, + 0.4489330021897331, + 0.4177880036877468, + 0.4257850014255382, + 2.5335070022265427, + 0.693169997248333, + 1.2044379982398823, + 0.49589000263949856 + ], + "p50_ms": 0.5078729991510045, + "p95_ms": 1.2044379982398823, + "p99_ms": 2.5335070022265427, + "plan": { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 0.42, + "Total Cost": 6.6, + "Plan Rows": 51, + "Plan Width": 149, + "Actual Startup Time": 0.011, + "Actual Total Time": 0.024, + "Actual Rows": 51, + "Actual Loops": 1, + "Shared Hit Blocks": 4, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Index Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Scan Direction": "Forward", + "Index Name": "research_candidate", + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.42, + "Total Cost": 8501.7, + "Plan Rows": 70133, + "Plan Width": 149, + "Actual Startup Time": 0.01, + "Actual Total Time": 0.018, + "Actual Rows": 51, + "Actual Loops": 1, + "Index Cond": "((chat_id = '48c201d1-9d95-4ce9-90f7-019e28b812ba'::uuid) AND (ROW(created_at, id) > ROW('2026-01-01 00:00:00+00'::timestamp with time zone, '936f77f5-d513-4297-8056-dccd57ca90a6'::uuid)))", + "Rows Removed by Index Recheck": 0, + "Shared Hit Blocks": 4, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + } + ] + }, + "Planning": { + "Shared Hit Blocks": 0, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + }, + "Planning Time": 0.09, + "Triggers": [], + "Execution Time": 0.037 + }, + "index": "history", + "method": "keyset", + "chat_size": 70000, + "offset": 0, + "index_bytes": 5914624 + } + ], + "postgres_version": "16.9 (Debian 16.9-1.pgdg120+1)", + "settings": { + "shared_buffers": "128MB", + "work_mem": "4MB", + "fsync": "on", + "synchronous_commit": "on" + }, + "writes": { + "chat_only": { + "batch_rows": 1000, + "batch_ms": [ + 29.2557749999105, + 37.38267100561643, + 22.848890999739524, + 31.510209999396466, + 29.870389997086022 + ], + "median_ms": 29.870389997086022, + "index_bytes": 720896 + }, + "history": { + "batch_rows": 1000, + "batch_ms": [ + 32.31218899600208, + 31.76951800560346, + 33.734912001818884, + 35.8419190015411, + 39.70592699624831 + ], + "median_ms": 33.734912001818884, + "index_bytes": 5914624 + } + }, + "counts": { + "users": 1, + "chats": 5, + "chat_members": 5, + "messages": 100000, + "sessions": 0 + }, + "sample_messages": [ + { + "id": "04e85f58-1262-43bd-b37b-6df8662de82a", + "chat_id": "91d2ecd0-11c0-472f-a67a-c678efc87df1", + "sender_id": "77200e3b-c860-42f8-8674-2fe555f1a553", + "text": "message 0", + "created_at": "2026-01-01 00:00:00+00:00" + }, + { + "id": "616770c4-a850-44a9-9076-e9cacdd4f80e", + "chat_id": "7d62628c-5194-4dea-ae35-be479edde556", + "sender_id": "77200e3b-c860-42f8-8674-2fe555f1a553", + "text": "message 0", + "created_at": "2026-01-01 00:00:00+00:00" + }, + { + "id": "936f77f5-d513-4297-8056-dccd57ca90a6", + "chat_id": "48c201d1-9d95-4ce9-90f7-019e28b812ba", + "sender_id": "77200e3b-c860-42f8-8674-2fe555f1a553", + "text": "message 0", + "created_at": "2026-01-01 00:00:00+00:00" + }, + { + "id": "b40ef452-0402-40ff-8ff4-c321419228d3", + "chat_id": "f8028b31-6ab5-45df-9cea-f4737a46ecf7", + "sender_id": "77200e3b-c860-42f8-8674-2fe555f1a553", + "text": "message 0", + "created_at": "2026-01-01 00:00:00+00:00" + }, + { + "id": "cab44f87-4a3f-4d22-80f4-c4d283331a8c", + "chat_id": "ba3c8454-879e-462b-be13-9d28f9fa80e3", + "sender_id": "77200e3b-c860-42f8-8674-2fe555f1a553", + "text": "message 0", + "created_at": "2026-01-01 00:00:00+00:00" + } + ] +} \ No newline at end of file diff --git a/evidence/track2_summary.md b/evidence/track2_summary.md new file mode 100644 index 00000000..d625cff5 --- /dev/null +++ b/evidence/track2_summary.md @@ -0,0 +1,73 @@ +# Трек 2: измерения + +Исходных сообщений: 100000. Прогрев: 5; повторов: 30. + +| Чат | Позиция | Индекс | Запрос | p50, мс | p95, мс | +|---:|---:|---|---|---:|---:| +| 100 | 0 | chat_only | keyset | 0.458 | 1.033 | +| 100 | 0 | chat_only | offset | 0.595 | 3.031 | +| 100 | 0 | history | keyset | 0.827 | 0.988 | +| 100 | 0 | history | offset | 0.916 | 1.616 | +| 100 | 49 | chat_only | keyset | 0.648 | 0.844 | +| 100 | 49 | chat_only | offset | 0.577 | 0.891 | +| 100 | 49 | history | keyset | 0.481 | 0.519 | +| 100 | 49 | history | offset | 0.423 | 0.531 | +| 100 | 89 | chat_only | keyset | 0.439 | 0.999 | +| 100 | 89 | chat_only | offset | 0.390 | 0.601 | +| 100 | 89 | history | keyset | 0.189 | 0.276 | +| 100 | 89 | history | offset | 0.208 | 0.704 | +| 900 | 0 | chat_only | keyset | 0.588 | 0.975 | +| 900 | 0 | chat_only | offset | 0.538 | 0.784 | +| 900 | 0 | history | keyset | 0.697 | 0.834 | +| 900 | 0 | history | offset | 0.847 | 0.965 | +| 900 | 449 | chat_only | keyset | 0.621 | 1.117 | +| 900 | 449 | chat_only | offset | 0.661 | 0.996 | +| 900 | 449 | history | keyset | 0.452 | 0.644 | +| 900 | 449 | history | offset | 0.522 | 0.699 | +| 900 | 809 | chat_only | keyset | 0.966 | 1.164 | +| 900 | 809 | chat_only | offset | 0.968 | 1.112 | +| 900 | 809 | history | keyset | 0.396 | 0.767 | +| 900 | 809 | history | offset | 0.602 | 2.982 | +| 9000 | 0 | chat_only | keyset | 2.414 | 3.626 | +| 9000 | 0 | chat_only | offset | 2.415 | 2.716 | +| 9000 | 0 | history | keyset | 0.573 | 0.969 | +| 9000 | 0 | history | offset | 0.617 | 0.825 | +| 9000 | 4499 | chat_only | keyset | 2.262 | 3.937 | +| 9000 | 4499 | chat_only | offset | 2.456 | 3.302 | +| 9000 | 4499 | history | keyset | 0.394 | 0.845 | +| 9000 | 4499 | history | offset | 1.126 | 1.725 | +| 9000 | 8099 | chat_only | keyset | 2.697 | 3.257 | +| 9000 | 8099 | chat_only | offset | 2.488 | 3.299 | +| 9000 | 8099 | history | keyset | 0.381 | 0.635 | +| 9000 | 8099 | history | offset | 1.337 | 1.553 | +| 20000 | 0 | chat_only | keyset | 4.656 | 6.722 | +| 20000 | 0 | chat_only | offset | 3.398 | 4.022 | +| 20000 | 0 | history | keyset | 0.365 | 0.726 | +| 20000 | 0 | history | offset | 0.376 | 0.652 | +| 20000 | 9999 | chat_only | keyset | 4.222 | 5.626 | +| 20000 | 9999 | chat_only | offset | 9.230 | 10.648 | +| 20000 | 9999 | history | keyset | 0.565 | 0.710 | +| 20000 | 9999 | history | offset | 1.455 | 1.614 | +| 20000 | 17999 | chat_only | keyset | 4.339 | 6.111 | +| 20000 | 17999 | chat_only | offset | 9.855 | 11.566 | +| 20000 | 17999 | history | keyset | 0.470 | 0.660 | +| 20000 | 17999 | history | offset | 2.578 | 5.871 | +| 70000 | 0 | chat_only | keyset | 12.649 | 14.819 | +| 70000 | 0 | chat_only | offset | 11.156 | 12.819 | +| 70000 | 0 | history | keyset | 0.508 | 1.204 | +| 70000 | 0 | history | offset | 0.375 | 0.594 | +| 70000 | 34999 | chat_only | keyset | 13.197 | 16.115 | +| 70000 | 34999 | chat_only | offset | 35.551 | 279.058 | +| 70000 | 34999 | history | keyset | 0.370 | 0.435 | +| 70000 | 34999 | history | offset | 4.444 | 5.365 | +| 70000 | 62999 | chat_only | keyset | 12.574 | 16.630 | +| 70000 | 62999 | chat_only | offset | 39.608 | 46.870 | +| 70000 | 62999 | history | keyset | 0.741 | 0.982 | +| 70000 | 62999 | history | offset | 10.017 | 14.338 | + +Цена записи: 5 транзакций по 1000 строк (COPY + COMMIT). + +| Индекс | Медиана партии, мс | Размер, байт | +|---|---:|---:| +| chat_only | 29.870 | 720896 | +| history | 33.735 | 5914624 | diff --git a/migrations/001_initial.sql b/migrations/001_initial.sql new file mode 100644 index 00000000..b3b63288 --- /dev/null +++ b/migrations/001_initial.sql @@ -0,0 +1,36 @@ +-- Сначала схема и ограничения, затем запросы приложения. +CREATE TABLE users ( + id uuid PRIMARY KEY, + username varchar(32) NOT NULL UNIQUE CHECK (username ~ '^[a-z0-9_]{3,32}$'), + display_name varchar(100) NOT NULL CHECK (length(btrim(display_name)) > 0), + password_hash text NOT NULL, + created_at timestamptz NOT NULL DEFAULT clock_timestamp() +); +CREATE TABLE chats ( + id uuid PRIMARY KEY, + title varchar(100) NOT NULL CHECK (length(btrim(title)) > 0), + created_at timestamptz NOT NULL DEFAULT clock_timestamp() +); +CREATE TABLE chat_members ( + chat_id uuid NOT NULL REFERENCES chats(id) ON DELETE CASCADE, + user_id uuid NOT NULL REFERENCES users(id), + PRIMARY KEY (chat_id, user_id) +); +CREATE INDEX chat_members_user_idx ON chat_members(user_id, chat_id); +CREATE INDEX chats_order_idx ON chats(created_at, id); +CREATE TABLE messages ( + id uuid PRIMARY KEY, + chat_id uuid NOT NULL REFERENCES chats(id), + sender_id uuid NOT NULL, + text varchar(4000) NOT NULL CHECK (length(btrim(text)) > 0), + created_at timestamptz NOT NULL DEFAULT clock_timestamp(), + FOREIGN KEY (chat_id, sender_id) REFERENCES chat_members(chat_id, user_id) +); +-- Equality по chat_id и range/order по двум полям курсора. +CREATE INDEX messages_history_idx ON messages(chat_id, created_at, id); +CREATE TABLE sessions ( + token_hash char(64) PRIMARY KEY, + user_id uuid NOT NULL REFERENCES users(id), + expires_at timestamptz NOT NULL +); +CREATE INDEX sessions_expiry_idx ON sessions(expires_at); diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 00000000..a60b4f8a --- /dev/null +++ b/requirements.txt @@ -0,0 +1,16 @@ +annotated-types==0.8.0 +anyio==4.15.1 +click==8.5.0 +fastapi==0.115.12 +h11==0.16.0 +idna==3.20 +pydantic==2.11.5 +pydantic_core==2.33.2 +starlette==0.46.2 +typing-inspection==0.4.4 +typing_extensions==4.16.0 +uvicorn==0.34.2 +psycopg[binary]==3.2.9 +psycopg-pool==3.3.3 +redis==5.2.1 +argon2-cffi==23.1.0 diff --git a/scripts/backup_restore.sh b/scripts/backup_restore.sh new file mode 100755 index 00000000..bd85114c --- /dev/null +++ b/scripts/backup_restore.sh @@ -0,0 +1,40 @@ +#!/usr/bin/env bash +set -euo pipefail +cd "$(dirname "$0")/.." +# Каждое восстановление использует новый project/volume, без drop основной БД. +project="lab2-restore-$(date +%s)-$$" +mkdir -p backups evidence +start=$(date +%s%N) +docker compose exec -T db pg_dump -U messenger -d messenger -Fc > backups/lab2.dump +backed=$(date +%s%N) +docker compose -p "$project" -f compose.yaml -f compose.restore.yaml up -d --wait restored +up=$(date +%s%N) +docker compose -p "$project" -f compose.yaml -f compose.restore.yaml exec -T restored \ + pg_restore -U messenger -d restored --no-owner --exit-on-error < backups/lab2.dump +restored=$(date +%s%N) +# Вычисляем URL из существующего secret, не выводя пароль в команду/журнал. +docker compose -p "$project" -f compose.yaml -f compose.restore.yaml run --build --rm -T --no-deps --user "$(id -u):$(id -g)" \ + -v "$PWD/evidence:/app/evidence" api python -c ' +from pathlib import Path +from psycopg.conninfo import make_conninfo +from src.config import DATABASE_URL +import os, runpy +os.environ.pop("DATABASE_URL_FILE", None) +os.environ["DATABASE_URL"] = make_conninfo(DATABASE_URL, host="restored", dbname="restored") +# config уже импортирован, обновляем значение для сценария сверки. +import src.config +src.config.DATABASE_URL = os.environ["DATABASE_URL"] +runpy.run_module("scripts.verify_restore", run_name="__main__")' +python3 - "$start" "$backed" "$up" "$restored" "$project" <<'PY' +import sys, json +from pathlib import Path +start, backed, up, restored = map(int, sys.argv[1:5]) +result = {'backup_seconds': (backed-start)/1e9, 'new_server_start_seconds': (up-backed)/1e9, + 'restore_seconds': (restored-up)/1e9, 'restore_project': sys.argv[5], + 'backup_bytes': Path('backups/lab2.dump').stat().st_size, + 'stand': 'Docker Compose, PostgreSQL 16.9'} +Path('evidence/backup_restore.json').write_text(json.dumps(result, indent=2)) +PY +# Сервер останавливаем, volume остаётся доступным для проверки преподавателем. +docker compose -p "$project" -f compose.yaml -f compose.restore.yaml stop restored +printf 'PASS: restored into separate PostgreSQL and volume; project=%s\n' "$project" diff --git a/scripts/experiment.py b/scripts/experiment.py new file mode 100644 index 00000000..8495d104 --- /dev/null +++ b/scripts/experiment.py @@ -0,0 +1,141 @@ +"""Трек 2: два индекса и OFFSET/keyset на 100 000 сообщений. + +Только синтетические данные в отдельной схеме. Не меняет таблицы API. +EXPLAIN включает BUFFERS, планировщику не навязывается тип плана. +""" +import json +import os +import platform +import random +import statistics +import time +from datetime import datetime, timedelta, timezone +from pathlib import Path +from uuid import uuid4 + +import psycopg +from psycopg import sql +from psycopg.rows import dict_row +from src.config import DATABASE_URL + +SEED = 42 +SIZES = [70000, 20000, 9000, 900, 100] +REPEATS = 30 + + +def percentile(values, p): + return sorted(values)[max(0, int(len(values) * p + 0.9999) - 1)] + + +def measure(db, query, params): + for _ in range(5): + db.execute(query, params).fetchall() + raw = [] + for _ in range(REPEATS): + start = time.perf_counter() + db.execute(query, params).fetchall() + raw.append((time.perf_counter() - start) * 1000) + plan = db.execute('EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON) ' + query, params).fetchone()[0][0] + return {'latency_ms': raw, 'p50_ms': statistics.median(raw), + 'p95_ms': percentile(raw, .95), 'p99_ms': percentile(raw, .99), 'plan': plan} + + +def main(): + schema = 'research_' + uuid4().hex[:12] + rng = random.Random(SEED) + out = {'seed': SEED, 'schema': schema, 'message_count': sum(SIZES), 'sizes': SIZES, + 'repeats': REPEATS, 'warmup': 5, 'concurrency': 1, + 'platform': platform.platform(), 'cpu_count': os.cpu_count(), 'results': []} + Path('evidence').mkdir(exist_ok=True) + with psycopg.connect(DATABASE_URL, autocommit=True) as db: + out['postgres_version'] = db.execute('SHOW server_version').fetchone()[0] + out['settings'] = {k: db.execute('SHOW ' + k).fetchone()[0] for k in + ['shared_buffers', 'work_mem', 'fsync', 'synchronous_commit']} + db.execute(sql.SQL('CREATE SCHEMA {}').format(sql.Identifier(schema))) + db.execute(sql.SQL('SET search_path TO {}').format(sql.Identifier(schema))) + # Точная схема приложения; другой search_path изолирует эксперимент. + db.execute(Path('migrations/001_initial.sql').read_text()) + user = uuid4() + db.execute('INSERT INTO users(id,username,display_name,password_hash) VALUES (%s,%s,%s,%s)', + (user, 'research_user', 'Synthetic research', 'not-a-login-account')) + chats = [uuid4() for _ in SIZES] + start_date = datetime(2026, 1, 1, tzinfo=timezone.utc) + for chat, size in zip(chats, SIZES): + db.execute('INSERT INTO chats(id,title) VALUES (%s,%s)', (chat, 'Synthetic ' + str(size))) + db.execute('INSERT INTO chat_members VALUES (%s,%s)', (chat, user)) + with db.cursor().copy('COPY messages(id,chat_id,sender_id,text,created_at) FROM STDIN') as copy: + for n in range(size): + copy.write_row((uuid4(), chat, user, 'message ' + str(n) + ' x' * (n % 80), + start_date + timedelta(microseconds=n))) + samples = [] + for chat in chats: + for fraction in [0, .5, .9]: + count = db.execute('SELECT count(*) FROM messages WHERE chat_id=%s', (chat,)).fetchone()[0] + offset = int((count - 1) * fraction) + cursor = db.execute('SELECT created_at,id FROM messages WHERE chat_id=%s ' + 'ORDER BY created_at,id OFFSET %s LIMIT 1', (chat, offset)).fetchone() + samples.append((chat, offset, cursor)) + db.execute('DROP INDEX messages_history_idx') + # Порядок фиксирован, но обе конфигурации прогреваются и имеют 30 повторов. + for name, columns in [('chat_only', 'chat_id'), ('history', 'chat_id,created_at,id')]: + db.execute('CREATE INDEX research_candidate ON messages(' + columns + ')') + db.execute('ANALYZE messages') + index_bytes = db.execute("SELECT pg_relation_size('research_candidate')").fetchone()[0] + queries = list(samples) + rng.shuffle(queries) + for chat, offset, cursor in queries: + for method in ['offset', 'keyset']: + query = 'SELECT * FROM messages WHERE chat_id=%s' + if method == 'keyset': + query += ' AND (created_at,id)>(%s,%s) ORDER BY created_at,id LIMIT 51' + params = (chat, *cursor) + else: + # Cursor указывает последнюю уже прочитанную строку. + query += ' ORDER BY created_at,id OFFSET %s LIMIT 51' + params = (chat, offset + 1) + result = measure(db, query, params) + result.update(index=name, method=method, chat_size=SIZES[chats.index(chat)], + offset=offset, index_bytes=index_bytes) + out['results'].append(result) + write_ms = [] + for batch in range(5): + # Цена 1000 записей + COMMIT; затем откат данных отдельной очисткой. + # Исходная история остаётся 100 000 для следующего индекса. + batch_ids = [uuid4() for _ in range(1000)] + begin = time.perf_counter() + with db.transaction(): + with db.cursor().copy('COPY messages(id,chat_id,sender_id,text,created_at) FROM STDIN') as copy: + for n, mid in enumerate(batch_ids): + copy.write_row((mid, chats[n % len(chats)], user, 'write-cost ' + 'x' * 128, + start_date + timedelta(days=1, microseconds=n))) + write_ms.append((time.perf_counter() - begin) * 1000) + db.execute('DELETE FROM messages WHERE id=ANY(%s)', (batch_ids,)) + out.setdefault('writes', {})[name] = {'batch_rows': 1000, 'batch_ms': write_ms, + 'median_ms': statistics.median(write_ms), + 'index_bytes': index_bytes} + db.execute('DROP INDEX research_candidate') + db.execute('VACUUM ANALYZE messages') + db.execute('CREATE INDEX messages_history_idx ON messages(chat_id,created_at,id)') + with db.cursor(row_factory=dict_row) as cur: + out['counts'] = {} + for table in ['users', 'chats', 'chat_members', 'messages', 'sessions']: + out['counts'][table] = db.execute('SELECT count(*) FROM ' + table).fetchone()[0] + cur.execute('SELECT * FROM messages ORDER BY created_at,id LIMIT 5') + out['sample_messages'] = [dict(row) for row in cur.fetchall()] + Path('evidence/track2_raw.json').write_text(json.dumps(out, ensure_ascii=False, indent=2, default=str)) + lines = ['# Трек 2: измерения', '', 'Исходных сообщений: 100000. Прогрев: 5; повторов: 30.', '', + '| Чат | Позиция | Индекс | Запрос | p50, мс | p95, мс |', + '|---:|---:|---|---|---:|---:|'] + for row in sorted(out['results'], key=lambda r: (r['chat_size'], r['offset'], r['index'], r['method'])): + lines.append(f"| {row['chat_size']} | {row['offset']} | {row['index']} | {row['method']} | " + f"{row['p50_ms']:.3f} | {row['p95_ms']:.3f} |") + lines.extend(['', 'Цена записи: 5 транзакций по 1000 строк (COPY + COMMIT).', '', + '| Индекс | Медиана партии, мс | Размер, байт |', '|---|---:|---:|']) + for name, row in out['writes'].items(): + lines.append(f"| {name} | {row['median_ms']:.3f} | {row['index_bytes']} |") + Path('evidence/track2_summary.md').write_text('\n'.join(lines) + '\n') + print('PASS: measured two indexes, two queries, write cost; raw evidence saved') + + +if __name__ == '__main__': + main() diff --git a/scripts/healthcheck.py b/scripts/healthcheck.py new file mode 100644 index 00000000..45a6b771 --- /dev/null +++ b/scripts/healthcheck.py @@ -0,0 +1,12 @@ +#!/usr/bin/env python3 +import json +import os +import urllib.request + + +host = "127.0.0.1" +port = os.getenv("APP_PORT", "8080") +with urllib.request.urlopen(f"http://{host}:{port}/health/ready", timeout=2) as response: + payload = json.load(response) + if response.status != 200 or payload != {"status": "ok"}: + raise SystemExit(1) diff --git a/scripts/restart.sh b/scripts/restart.sh new file mode 100755 index 00000000..cbd46a84 --- /dev/null +++ b/scripts/restart.sh @@ -0,0 +1,8 @@ +#!/usr/bin/env bash +set -euo pipefail +cd "$(dirname "$0")/.." +# Остановка/запуск всех сервисов; именованные volumes остаются. +# API запускаем после готовности хранилищ, иначе миграции могут не подключиться. +docker compose stop api cache db +docker compose up -d --wait db cache +docker compose up -d --wait api diff --git a/scripts/setup.sh b/scripts/setup.sh new file mode 100755 index 00000000..e26e9640 --- /dev/null +++ b/scripts/setup.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +set -euo pipefail +cd "$(dirname "$0")/.." +mkdir -p .secrets +chmod 700 .secrets +python3 - <<'PY' +from pathlib import Path +import secrets +password_file = Path('.secrets/db_password') +if not password_file.exists(): + password_file.write_text(secrets.token_hex(24)) +password = password_file.read_text().strip() +Path('.secrets/database_url').write_text(f'postgresql://messenger:{password}@db:5432/messenger') +for file in Path('.secrets').iterdir(): + file.chmod(0o644 if file.name == "database_url" else 0o600) +if not Path('.env').exists(): + Path('.env').write_text('APP_PORT=8080\nSESSION_TTL_SECONDS=3600\nDB_POOL_MAX=8\n') +print('Локальные настройки подготовлены; секреты не выводятся.') +PY diff --git a/scripts/start-cache.sh b/scripts/start-cache.sh new file mode 100755 index 00000000..880815e7 --- /dev/null +++ b/scripts/start-cache.sh @@ -0,0 +1,4 @@ +#!/usr/bin/env bash +set -euo pipefail +cd "$(dirname "$0")/.." +docker compose start cache diff --git a/scripts/start-db.sh b/scripts/start-db.sh new file mode 100755 index 00000000..d498d06a --- /dev/null +++ b/scripts/start-db.sh @@ -0,0 +1,4 @@ +#!/usr/bin/env bash +set -euo pipefail +cd "$(dirname "$0")/.." +docker compose start db diff --git a/scripts/stop-cache.sh b/scripts/stop-cache.sh new file mode 100755 index 00000000..62e063b4 --- /dev/null +++ b/scripts/stop-cache.sh @@ -0,0 +1,4 @@ +#!/usr/bin/env bash +set -euo pipefail +cd "$(dirname "$0")/.." +docker compose stop cache diff --git a/scripts/stop-db.sh b/scripts/stop-db.sh new file mode 100755 index 00000000..0a4d2e06 --- /dev/null +++ b/scripts/stop-db.sh @@ -0,0 +1,4 @@ +#!/usr/bin/env bash +set -euo pipefail +cd "$(dirname "$0")/.." +docker compose stop db diff --git a/scripts/test_expiry.sh b/scripts/test_expiry.sh new file mode 100755 index 00000000..d80ad7c4 --- /dev/null +++ b/scripts/test_expiry.sh @@ -0,0 +1,11 @@ +#!/usr/bin/env bash +set -euo pipefail +cd "$(dirname "$0")/.." +# Меняем только конфигурацию процесса; сессии и БД остаются на месте. +restore() { + docker compose up -d --no-deps --force-recreate api +} +trap restore EXIT +SESSION_TTL_SECONDS=2 docker compose up -d --no-deps --force-recreate api +python3 scripts/wait_ready.py +python3 student-tests/checks.py --expiry diff --git a/scripts/verify_restore.py b/scripts/verify_restore.py new file mode 100644 index 00000000..705d3ba5 --- /dev/null +++ b/scripts/verify_restore.py @@ -0,0 +1,25 @@ +"""Сверка восстановленной БД с counts и пятью полными строками из эксперимента.""" +import json +from pathlib import Path +import psycopg +from psycopg import sql +from psycopg.rows import dict_row +from src.config import DATABASE_URL + +expected = json.loads(Path('evidence/track2_raw.json').read_text()) +with psycopg.connect(DATABASE_URL, row_factory=dict_row) as db: + db.execute(sql.SQL('SET search_path TO {}').format(sql.Identifier(expected['schema']))) + counts = {} + for table, count in expected['counts'].items(): + actual = db.execute(sql.SQL('SELECT count(*) AS n FROM {}').format(sql.Identifier(table))).fetchone()['n'] + assert actual == count, (table, actual, count) + counts[table] = actual + actual_samples = [] + for sample in expected['sample_messages']: + row = db.execute('SELECT * FROM messages WHERE id=%s', (sample['id'],)).fetchone() + actual = json.loads(json.dumps(row, default=str)) + assert actual == sample, 'Restored message differs' + actual_samples.append(actual) +result = {'counts': counts, 'sample_messages_matched': len(actual_samples), 'status': 'PASS'} +Path('evidence/restore_verification.json').write_text(json.dumps(result, indent=2)) +print('PASS: restored row counts and selected full messages match backup dataset') diff --git a/scripts/wait_ready.py b/scripts/wait_ready.py new file mode 100644 index 00000000..529a4831 --- /dev/null +++ b/scripts/wait_ready.py @@ -0,0 +1,17 @@ +"""Ожидание готовности API без сторонних библиотек.""" +import os +import time +import urllib.request + +url = os.getenv('BASE_URL', 'http://localhost:8080') + '/health/ready' +for attempt in range(90): + try: + with urllib.request.urlopen(url, timeout=2) as response: + if response.status == 200: + print('API ready') + break + except OSError: + pass + time.sleep(1) +else: + raise SystemExit('API не стал готов за 90 попыток') diff --git a/src/__init__.py b/src/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/src/config.py b/src/config.py new file mode 100644 index 00000000..4afd1483 --- /dev/null +++ b/src/config.py @@ -0,0 +1,14 @@ +"""Настройки из окружения или Docker secrets; секреты не печатаем.""" +import os +from pathlib import Path + + +def setting(name, default=None): + file = os.getenv(name + '_FILE') + return Path(file).read_text().strip() if file else os.getenv(name, default) + + +DATABASE_URL = setting('DATABASE_URL') +CACHE_URL = setting('CACHE_URL', 'redis://localhost:6379/0') +SESSION_TTL = int(os.getenv('SESSION_TTL_SECONDS', '3600')) +POOL_MAX = int(os.getenv('DB_POOL_MAX', '8')) diff --git a/src/main.py b/src/main.py new file mode 100644 index 00000000..49a63691 --- /dev/null +++ b/src/main.py @@ -0,0 +1,521 @@ +from __future__ import annotations + +import base64 +import json +import logging +import os +import re +import time +import uuid +from datetime import datetime, timedelta, timezone +from contextlib import asynccontextmanager +import hashlib +import secrets +import psycopg +from psycopg.rows import dict_row +from psycopg_pool import ConnectionPool, PoolTimeout +import redis +from argon2 import PasswordHasher +from argon2.exceptions import VerificationError, InvalidHashError +from starlette.exceptions import HTTPException +from src.config import DATABASE_URL, CACHE_URL, SESSION_TTL, POOL_MAX +from src.migrate import migrate +from typing import Annotated + +from fastapi import Depends, FastAPI, Header, Query, Request +from fastapi.exceptions import RequestValidationError +from fastapi.responses import JSONResponse, Response +from pydantic import BaseModel, ConfigDict, Field, field_validator + + +logging.basicConfig( + level=os.getenv("LOG_LEVEL", "INFO").upper(), + format="%(asctime)s %(levelname)s %(message)s", +) +logger = logging.getLogger("messenger") + + +def utc_now() -> datetime: + return datetime.now(timezone.utc) + + +def as_json(value: BaseModel) -> dict: + return value.model_dump(mode="json") + + +class StrictModel(BaseModel): + model_config = ConfigDict(extra="forbid") + + +class User(StrictModel): + id: uuid.UUID + username: str + display_name: str + created_at: datetime + + +class CreateUser(StrictModel): + 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("password") + @classmethod + def password_has_visible_characters(cls, value: str) -> str: + if not value.strip(): + raise ValueError("password must not contain only whitespace") + return value + + @field_validator("display_name") + @classmethod + def display_name_has_visible_characters(cls, value: str) -> str: + if not value.strip(): + raise ValueError("display_name must not contain only whitespace") + return value + + +class Chat(StrictModel): + id: uuid.UUID + title: str + member_ids: list[uuid.UUID] + created_at: datetime + + +class CreateChat(StrictModel): + title: str = Field(min_length=1, max_length=100) + member_ids: list[uuid.UUID] = Field(min_length=1, max_length=100) + + @field_validator("title") + @classmethod + def title_has_visible_characters(cls, value: str) -> str: + if not value.strip(): + raise ValueError("title must not contain only whitespace") + return value + + @field_validator("member_ids") + @classmethod + def member_ids_are_unique(cls, value: list[uuid.UUID]) -> list[uuid.UUID]: + if len(value) != len(set(value)): + raise ValueError("member_ids must be unique") + return value + + +class Message(StrictModel): + id: uuid.UUID + chat_id: uuid.UUID + sender_id: uuid.UUID + text: str + created_at: datetime + + +class CreateMessage(StrictModel): + text: str = Field(min_length=1, max_length=4000) + + @field_validator("text") + @classmethod + def text_has_visible_characters(cls, value: str) -> str: + if not value.strip(): + raise ValueError("text must not contain only whitespace") + return value + + +class ApiProblem(Exception): + def __init__(self, status: int, code: str, message: str, challenge: str | None = None): + self.status = status + self.code = code + self.message = message + self.challenge = challenge + + +class Store: + """Источник истины теперь PostgreSQL. Redis — только кэш профилей.""" + + def __init__(self) -> None: + self.pool = ConnectionPool( + DATABASE_URL, min_size=1, max_size=POOL_MAX, timeout=2, open=False, + kwargs={"row_factory": dict_row, "connect_timeout": 2, + "options": "-c statement_timeout=3000 -c lock_timeout=2000 -c timezone=UTC"}, + ) + self.cache = redis.Redis.from_url( + CACHE_URL, decode_responses=True, socket_connect_timeout=0.25, socket_timeout=0.25, + ) + + def start(self) -> None: + migrate() + self.pool.open() + self.pool.wait(timeout=10) + + def close(self) -> None: + self.pool.close() + self.cache.close() + + def chat(self, db, chat_id: uuid.UUID) -> Chat | None: + row = db.execute("SELECT * FROM chats WHERE id=%s", (chat_id,)).fetchone() + if row is None: + return None + members = db.execute("SELECT user_id FROM chat_members WHERE chat_id=%s ORDER BY user_id", + (chat_id,)).fetchall() + return Chat(**row, member_ids=[member["user_id"] for member in members]) + + def chat_messages(self, db, chat_id: uuid.UUID, limit: int, after) -> list[Message]: + # В lab1 здесь были общий список/список чата и bisect_right. + # Теперь границу ищет B-tree PostgreSQL (chat_id, created_at, id). + query = "SELECT * FROM messages WHERE chat_id=%s" + params = [chat_id] + if after is not None: + query += " AND (created_at,id)>(%s,%s)" + params.extend(after) + rows = db.execute(query + " ORDER BY created_at,id LIMIT %s", params + [limit + 1]).fetchall() + return [Message(**row) for row in rows] + + +store = Store() +passwords = PasswordHasher(time_cost=2, memory_cost=19456, parallelism=1) +dummy_hash = passwords.hash(secrets.token_urlsafe(32)) + + +@asynccontextmanager +async def lifespan(app): + store.start() + yield + store.close() + + +app = FastAPI(title="MTUCI PostgreSQL messenger", version="2.0.0", lifespan=lifespan, + docs_url=None, redoc_url=None, openapi_url=None) + + +def request_id(request: Request) -> str: + return request.state.request_id + + +def error_response(request: Request, status: int, code: str, message: str, challenge: str | None = None) -> JSONResponse: + rid = getattr(request.state, "request_id", str(uuid.uuid4())) + headers = {"X-Request-Id": rid} + if challenge: + headers["WWW-Authenticate"] = challenge + return JSONResponse( + status_code=status, + content={"error": {"code": code, "message": message, "request_id": rid}}, + headers=headers, + ) + + +@app.middleware("http") +async def request_context(request: Request, call_next): + request.state.request_id = str(uuid.uuid4()) + started = time.perf_counter() + status = 500 + try: + # Без токена отказываем ДО обращения к БД и проверки JSON. + if request.url.path.startswith("/api/v1/") and request.url.path not in { + "/api/v1/users", "/api/v1/auth/sessions" + }: + scheme, _, token = request.headers.get("authorization", "").partition(" ") + if scheme.lower() != "bearer" or not token or len(token) > 256: + status = 401 + return error_response(request, 401, "unauthorized", "Требуется Bearer", + 'Bearer realm="messenger"') + json_endpoints = { + "/api/v1/users", + "/api/v1/chats", + } + requires_json = request.method == "POST" and ( + request.url.path in json_endpoints + or re.fullmatch(r"/api/v1/chats/[^/]+/messages", request.url.path) is not None + ) + media_type = request.headers.get("content-type", "").split(";", 1)[0].strip().lower() + if requires_json and media_type != "application/json": + status = 415 + return error_response( + request, + 415, + "unsupported_media_type", + "Требуется Content-Type: application/json", + ) + if requires_json: + # Ограниченный JSON; после body() Starlette повторно отдаёт его маршруту. + raw = await request.body() + if len(raw) > 65536: + status = 413 + return error_response(request, 413, "payload_too_large", "Запрос слишком большой") + response = await call_next(request) + status = response.status_code + response.headers["X-Request-Id"] = request.state.request_id + return response + finally: + logger.info( + "request method=%s path=%s status=%s duration_ms=%.3f request_id=%s", + request.method, + request.url.path, + status, + (time.perf_counter() - started) * 1000, + request.state.request_id, + ) + + +@app.exception_handler(ApiProblem) +async def api_problem_handler(request: Request, exc: ApiProblem): + return error_response(request, exc.status, exc.code, exc.message, exc.challenge) + + +@app.exception_handler(RequestValidationError) +async def validation_handler(request: Request, exc: RequestValidationError): + return error_response(request, 400, "invalid_request", "Запрос не соответствует контракту") + + +@app.exception_handler(Exception) +async def unexpected_error_handler(request: Request, exc: Exception): + logger.error("unexpected_error request_id=%s", request_id(request)) + return error_response(request, 500, "internal_error", "Внутренняя ошибка сервера") + + +@app.exception_handler(psycopg.Error) +@app.exception_handler(PoolTimeout) +async def database_error_handler(request: Request, exc: Exception): + return error_response(request, 503, "unavailable", "Хранилище временно недоступно") + + +@app.exception_handler(HTTPException) +async def http_error_handler(request: Request, exc: HTTPException): + code = "not_found" if exc.status_code == 404 else "invalid_request" + return error_response(request, exc.status_code, code, "Неверный маршрут или метод") + + +def unauthorized(basic=False): + challenge = 'Basic realm="messenger", charset="UTF-8"' if basic else 'Bearer realm="messenger"' + raise ApiProblem(401, "unauthorized", "Нужна действительная идентификация", challenge) + + +def token_hash(token: str) -> str: + return hashlib.sha256(token.encode()).hexdigest() + + +def current_user(authorization: Annotated[str | None, Header()] = None) -> User: + scheme, _, token = (authorization or "").partition(" ") + if scheme.lower() != "bearer" or not token or len(token) > 256: + unauthorized() + with store.pool.connection() as db: + session = db.execute("SELECT user_id FROM sessions WHERE token_hash=%s AND expires_at>now()", + (token_hash(token),)).fetchone() + if session is None: + unauthorized() + key = "user:" + str(session["user_id"]) + cache_available = True + try: + cached = store.cache.get(key) + if cached: + user = User.model_validate_json(cached) + if user.id == session["user_id"]: + return user + except (redis.RedisError, ValueError): + cache_available = False + row = db.execute("SELECT id,username,display_name,created_at FROM users WHERE id=%s", + (session["user_id"],)).fetchone() + user = User(**row) + if cache_available: + try: + store.cache.setex(key, 60, user.model_dump_json()) + except redis.RedisError: + pass + return user + + +def decode_cursor(cursor: str, expected_scope: str) -> tuple[datetime, uuid.UUID]: + try: + if not cursor or len(cursor) > 1024: + raise ValueError + padded = cursor + "=" * (-len(cursor) % 4) + payload = json.loads(base64.b64decode(padded.encode(), altchars=b"-_", validate=True).decode()) + if set(payload) != {"scope", "created_at", "id"} or payload["scope"] != expected_scope: + raise ValueError + created_at = datetime.fromisoformat(payload["created_at"].replace("Z", "+00:00")) + item_id = uuid.UUID(payload["id"]) + if created_at.tzinfo is None: + raise ValueError + return created_at, item_id + except (ValueError, TypeError, KeyError, json.JSONDecodeError, UnicodeError): + raise ApiProblem(400, "invalid_request", "Некорректный cursor") from None + + +def encode_cursor(scope: str, created_at: datetime, item_id: uuid.UUID) -> str: + payload = { + "scope": scope, + "created_at": created_at.isoformat().replace("+00:00", "Z"), + "id": str(item_id), + } + return base64.urlsafe_b64encode(json.dumps(payload, separators=(",", ":")).encode()).decode().rstrip("=") + + +def page(items: list, limit: int, scope: str) -> dict: + # SQL уже выбрал limit+1 строк после курсора; весь список не загружаем. + selected = items[:limit] + next_cursor = None + if len(items) > limit and selected: + last = selected[-1] + next_cursor = encode_cursor(scope, last.created_at, last.id) + return {"items": [as_json(item) for item in selected], "next_cursor": next_cursor} + + +def visible_chat(chat_id: uuid.UUID, user: User) -> Chat: + with store.pool.connection() as db: + member = db.execute("SELECT 1 FROM chat_members WHERE chat_id=%s AND user_id=%s", + (chat_id, user.id)).fetchone() + if member is None: + raise ApiProblem(404, "not_found", "Объект не найден") + return store.chat(db, chat_id) + + +def page_parameters(request: Request, scope: str, limit: int, cursor: str | None): + # Query(ge/le) сохранён из lab1, добавлена проверка дублей и формы limit. + if set(request.query_params) - {"limit", "cursor"} or any( + len(request.query_params.getlist(k)) > 1 for k in request.query_params + ): + raise ApiProblem(400, "invalid_request", "Некорректные параметры страницы") + if not re.fullmatch(r"[0-9]{1,3}", request.query_params.get("limit", "50")): + raise ApiProblem(400, "invalid_request", "Некорректный limit") + return decode_cursor(cursor, scope) if cursor is not None else None + + +@app.get("/health/live") +def liveness(): + return {"status": "ok"} + + +@app.get("/health/ready") +def readiness(): + with store.pool.connection() as db: + db.execute("SELECT 1") + return {"status": "ok"} + + +@app.post("/api/v1/users", status_code=201) +def register_user(body: CreateUser): + # Синхронные маршруты FastAPI исполняет в worker thread, не в event loop. + hashed = passwords.hash(body.password) + try: + with store.pool.connection() as db: + row = db.execute( + "INSERT INTO users(id,username,display_name,password_hash) VALUES (%s,%s,%s,%s) " + "RETURNING id,username,display_name,created_at", + (uuid.uuid4(), body.username, body.display_name, hashed), + ).fetchone() + except psycopg.errors.UniqueViolation: + raise ApiProblem(409, "conflict", "Username уже занят") from None + return as_json(User(**row)) + + +@app.post("/api/v1/auth/sessions", status_code=201) +def create_session(request: Request, authorization: Annotated[str | None, Header()] = None): + if request.headers.get("content-length", "0") != "0" or "transfer-encoding" in request.headers: + raise ApiProblem(400, "invalid_request", "Вход не принимает тело запроса") + scheme, _, encoded = (authorization or "").partition(" ") + try: + if scheme.lower() != "basic" or len(encoded) > 2048: + raise ValueError + username, password = base64.b64decode(encoded, validate=True).decode("utf-8").split(":", 1) + if not re.fullmatch(r"[a-z0-9_]{3,32}", username) or not 12 <= len(password) <= 128: + raise ValueError + except (ValueError, UnicodeError): + unauthorized(basic=True) + with store.pool.connection() as db: + row = db.execute("SELECT * FROM users WHERE username=%s", (username,)).fetchone() + try: + passwords.verify(row["password_hash"] if row else dummy_hash, password) + except (VerificationError, InvalidHashError): + unauthorized(basic=True) + if row is None: + unauthorized(basic=True) + token = secrets.token_urlsafe(32) + expires_at = utc_now() + timedelta(seconds=SESSION_TTL) + with store.pool.connection() as db: + db.execute("INSERT INTO sessions(token_hash,user_id,expires_at) VALUES (%s,%s,%s)", + (token_hash(token), row["id"], expires_at)) + user = User(**{k: row[k] for k in ("id", "username", "display_name", "created_at")}) + return {"token": token, "token_type": "Bearer", "user": as_json(user), + "expires_at": expires_at.isoformat().replace("+00:00", "Z")} + + +@app.delete("/api/v1/auth/sessions/current", status_code=204) +def delete_session(user: Annotated[User, Depends(current_user)], + authorization: Annotated[str, Header()]): + token = authorization.partition(" ")[2] + with store.pool.connection() as db: + db.execute("DELETE FROM sessions WHERE token_hash=%s", (token_hash(token),)) + return Response(status_code=204) + + +@app.get("/api/v1/users/me") +def get_current_user(user: Annotated[User, Depends(current_user)]): + return as_json(user) + + +@app.post("/api/v1/chats", status_code=201) +def create_chat(body: CreateChat, user: Annotated[User, Depends(current_user)]): + if user.id not in body.member_ids: + raise ApiProblem(400, "invalid_request", "Текущий пользователь должен быть участником") + with store.pool.connection() as db: + found = db.execute("SELECT id FROM users WHERE id=ANY(%s)", (body.member_ids,)).fetchall() + if len(found) != len(body.member_ids): + raise ApiProblem(400, "invalid_request", "Указан неизвестный участник") + row = db.execute("INSERT INTO chats(id,title) VALUES (%s,%s) RETURNING *", + (uuid.uuid4(), body.title)).fetchone() + with db.cursor() as cur: + cur.executemany("INSERT INTO chat_members(chat_id,user_id) VALUES (%s,%s)", + [(row["id"], member) for member in body.member_ids]) + chat = store.chat(db, row["id"]) + return as_json(chat) # COMMIT уже выполнен для чата и всех участников. + + +@app.get("/api/v1/chats") +def list_chats( + request: Request, + user: Annotated[User, Depends(current_user)], + limit: Annotated[int, Query(ge=1, le=100)] = 50, + cursor: Annotated[str | None, Query(min_length=1)] = None, +): + scope = f"chats:{user.id}" + after = page_parameters(request, scope, limit, cursor) + query = "SELECT c.* FROM chats c JOIN chat_members m ON m.chat_id=c.id WHERE m.user_id=%s" + params = [user.id] + if after is not None: + query += " AND (c.created_at,c.id)>(%s,%s)" + params.extend(after) + with store.pool.connection() as db: + rows = db.execute(query + " ORDER BY c.created_at,c.id LIMIT %s", params + [limit + 1]).fetchall() + chats = [store.chat(db, row["id"]) for row in rows] + return page(chats, limit, scope) + + +@app.get("/api/v1/chats/{chat_id}") +def get_chat(chat_id: uuid.UUID, user: Annotated[User, Depends(current_user)]): + return as_json(visible_chat(chat_id, user)) + + +@app.post("/api/v1/chats/{chat_id}/messages", status_code=201) +def create_message( + chat_id: uuid.UUID, + body: CreateMessage, + user: Annotated[User, Depends(current_user)], +): + chat = visible_chat(chat_id, user) + with store.pool.connection() as db: + row = db.execute("INSERT INTO messages(id,chat_id,sender_id,text) VALUES (%s,%s,%s,%s) RETURNING *", + (uuid.uuid4(), chat.id, user.id, body.text)).fetchone() + return as_json(Message(**row)) + + +@app.get("/api/v1/chats/{chat_id}/messages") +def list_messages( + request: Request, + chat_id: uuid.UUID, + user: Annotated[User, Depends(current_user)], + limit: Annotated[int, Query(ge=1, le=100)] = 50, + cursor: Annotated[str | None, Query(min_length=1)] = None, +): + visible_chat(chat_id, user) + scope = f"messages:{chat_id}" + after = page_parameters(request, scope, limit, cursor) + with store.pool.connection() as db: + messages = store.chat_messages(db, chat_id, limit, after) + return page(messages, limit, scope) diff --git a/src/migrate.py b/src/migrate.py new file mode 100644 index 00000000..4f125aae --- /dev/null +++ b/src/migrate.py @@ -0,0 +1,26 @@ +"""Версионируемые миграции: один файл = одна атомарная транзакция.""" +from pathlib import Path +import psycopg +from src.config import DATABASE_URL + + +def migrate(): + with psycopg.connect(DATABASE_URL) as db: + # Не даём двум API одновременно применить одну миграцию. + db.execute('SELECT pg_advisory_lock(20260002)') + db.execute('CREATE TABLE IF NOT EXISTS schema_migrations ' + '(version text PRIMARY KEY, applied_at timestamptz DEFAULT now())') + db.commit() + for file in sorted(Path('migrations').glob('*.sql')): + with db.transaction(): + applied = db.execute('SELECT 1 FROM schema_migrations WHERE version=%s', + (file.name,)).fetchone() + if not applied: + db.execute(file.read_text()) + db.execute('INSERT INTO schema_migrations(version) VALUES (%s)', (file.name,)) + print('Applied', file.name) + db.execute('SELECT pg_advisory_unlock(20260002)') + + +if __name__ == '__main__': + migrate() diff --git a/student-tests/checks.py b/student-tests/checks.py new file mode 100644 index 00000000..7bd8b0e2 --- /dev/null +++ b/student-tests/checks.py @@ -0,0 +1,64 @@ +"""Дополнения к публичному smoke. Не печатает и не сохраняет tokens.""" +import concurrent.futures +import json +import sys +import time +from pathlib import Path +from uuid import uuid4 + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests')) +from client import Client, arguments, check, run + + +def main(): + def configure(p): + p.add_argument('--expiry', action='store_true', help='API must run with TTL=2') + args = arguments('Student API checks', configure) + c = Client(args.base_url) + alice, bob, eve, chat = c.bootstrap() + if args.expiry: + time.sleep(2.2) + c.call('GET', '/api/v1/users/me', 401, actor=alice) + print('PASS: short TTL expiry') + return + registration = {'username': 'race_' + uuid4().hex[:12], 'display_name': 'Гонка', + 'password': 'Synthetic-password-42'} + # Для гонки регистрируем оба допустимых исхода через urllib. + import urllib.request + import urllib.error + def register(_): + req = urllib.request.Request(c.base + '/api/v1/users', + data=json.dumps(registration).encode(), + headers={'Content-Type': 'application/json'}) + try: + with urllib.request.urlopen(req, timeout=10) as response: + return response.status + except urllib.error.HTTPError as error: + return error.code + with concurrent.futures.ThreadPoolExecutor(max_workers=8) as executor: + codes = list(executor.map(register, range(8))) + check(codes.count(201) == 1 and codes.count(409) == 7, 'username race failed') + path = '/api/v1/chats/' + chat['id'] + c.call('POST', '/api/v1/chats', 400, actor=alice, + body={'title': 'unknown member', 'member_ids': [alice['id'], str(uuid4())]}) + for body in [{'text': 'x', 'sender_id': eve['id']}, {'text': 4}, {'text': ' '}]: + c.call('POST', path + '/messages', 400, actor=alice, body=body) + c.call('GET', path + '/messages?limit=true', 400, actor=alice) + c.call('GET', path + '/messages?cursor=not-a-cursor', 400, actor=alice) + for n in range(3): + c.message(alice, chat, 'read-after-write ' + str(n)) + page = c.call('GET', path + '/messages?limit=1', actor=alice, schema='MessagePage')['json'] + other = c.call('POST', '/api/v1/chats', 201, actor=alice, + body={'title': 'other', 'member_ids': [alice['id']]}, schema='Chat')['json'] + from urllib.parse import quote + c.call('GET', '/api/v1/chats/' + other['id'] + '/messages?cursor=' + + quote(page['next_cursor'], safe=''), 400, actor=alice) + history = c.call('GET', path + '/messages', actor=bob, schema='MessagePage')['json']['items'] + check(len(history) == 3 and history[-1]['text'] == 'read-after-write 2', 'read-after-write failed') + c.call('DELETE', '/api/v1/auth/sessions/current', 204, actor=alice) + c.call('GET', '/api/v1/users/me', 401, actor=alice) + print('PASS: registration race, invalid input, cursor scope, read-after-write, logout') + + +if __name__ == '__main__': + run(main) diff --git a/student-tests/database.py b/student-tests/database.py new file mode 100644 index 00000000..2907df33 --- /dev/null +++ b/student-tests/database.py @@ -0,0 +1,29 @@ +"""Проверка реального rollback после вставки чата и первого участника.""" +import sys +from pathlib import Path +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +from uuid import uuid4 +import psycopg +from src.config import DATABASE_URL +from src.migrate import migrate + +migrate() +migrate() # Повтор миграции не создаёт дубликаты. +with psycopg.connect(DATABASE_URL) as db: + user = db.execute('SELECT id FROM users LIMIT 1').fetchone() + assert user, 'Сначала выполните smoke, чтобы создать синтетического пользователя' + chat = uuid4() + try: + with db.transaction(): + db.execute('INSERT INTO chats(id,title) VALUES (%s,%s)', (chat, 'rollback test')) + db.execute('INSERT INTO chat_members VALUES (%s,%s)', (chat, user[0])) + # FK прерывает составную операцию ПОСЛЕ двух успешных INSERT. + db.execute('INSERT INTO chat_members VALUES (%s,%s)', (chat, uuid4())) + except psycopg.errors.ForeignKeyViolation: + pass + else: + raise AssertionError('Expected foreign-key failure') + assert db.execute('SELECT count(*) FROM chats WHERE id=%s', (chat,)).fetchone()[0] == 0 + assert db.execute('SELECT count(*) FROM chat_members WHERE chat_id=%s', (chat,)).fetchone()[0] == 0 + assert db.execute('SELECT count(*) FROM schema_migrations').fetchone()[0] == 1 +print('PASS: rollback of chat + members; migration reapplied twice') diff --git a/student-tests/dependencies.py b/student-tests/dependencies.py new file mode 100644 index 00000000..12b7af3a --- /dev/null +++ b/student-tests/dependencies.py @@ -0,0 +1,67 @@ +"""Проверяет отказ Redis/БД. Hook выбирает явно оператор, токен только в памяти.""" +import subprocess +import sys +import time +from pathlib import Path +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests')) +from client import Client, arguments, check, run + + +def main(): + def configure(p): + p.add_argument('--stop-cache', required=True) + p.add_argument('--start-cache', required=True) + p.add_argument('--stop-db', required=True) + p.add_argument('--start-db', required=True) + args = arguments('Dependency failures', configure) + c = Client(args.base_url, timeout=8) + alice, bob, eve, chat = c.bootstrap() + def hook(path): + subprocess.run([str(Path(path).resolve())], check=True, + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=40) + def wait(): + for _ in range(90): + try: + c.call('GET', '/health/ready', schema='Health') + return + except AssertionError: + time.sleep(.5) + raise AssertionError('DB did not recover') + result = {} + try: + hook(args.stop_cache) + start = time.monotonic() + c.call('GET', '/api/v1/users/me', actor=alice, schema='User') + c.call('GET', '/api/v1/users/me', 401) + c.call('GET', '/health/ready', schema='Health') + confirmed = c.message(alice, chat, 'Redis offline')['json'] + messages = c.call('GET', '/api/v1/chats/' + chat['id'] + '/messages', + actor=bob, schema='MessagePage')['json']['items'] + check(confirmed in messages, 'read-after-write failed without Redis') + result['redis_offline_scenario_seconds'] = time.monotonic() - start + finally: + hook(args.start_cache) + # Тот же токен работает после восстановления Redis, logout сразу действует. + c.call('GET', '/api/v1/users/me', actor=alice, schema='User') + c.call('DELETE', '/api/v1/auth/sessions/current', 204, actor=alice) + c.call('GET', '/api/v1/users/me', 401, actor=alice) + try: + hook(args.stop_db) + start = time.monotonic() + c.call('GET', '/health/ready', 503) + c.call('GET', '/health/live', schema='Health') + c.call('GET', '/api/v1/users/me', 503, actor=bob) + c.call('GET', '/api/v1/users/me', 401) + result['db_offline_scenario_seconds'] = time.monotonic() - start + finally: + hook(args.start_db) + wait() + c.call('GET', '/api/v1/users/me', actor=bob, schema='User') + import json + result['status'] = 'PASS' + Path('evidence/dependency_failures.json').write_text(json.dumps(result, indent=2)) + print('PASS: Redis fallback + restart + logout; DB bounded 503 + recovery; anonymous rejected') + + +if __name__ == '__main__': + run(main) diff --git a/student-tests/test_api.py b/student-tests/test_api.py new file mode 100644 index 00000000..19ee622e --- /dev/null +++ b/student-tests/test_api.py @@ -0,0 +1,87 @@ +#!/usr/bin/env python3 +"""Black-box grading evidence beyond the public smoke test.""" +from concurrent.futures import ThreadPoolExecutor +import json +import sys +import uuid +from pathlib import Path +from urllib.parse import quote + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / "tests")) +from client import Client, arguments, check, run # noqa: E402 + + +def collect_messages(client, actor, chat, page_size=17): + items = [] + cursor = None + while True: + path = f"/api/v1/chats/{chat['id']}/messages?limit={page_size}" + if cursor: + path += "&cursor=" + quote(cursor, safe="") + page = client.call("GET", path, actor=actor, schema="MessagePage")["json"] + items.extend(page["items"]) + cursor = page["next_cursor"] + if cursor is None: + return items + + +def main(): + args = arguments("Student negative, pagination and concurrency tests") + client = Client(args.base_url, args.ca_file) + alice, bob, outsider, chat = client.bootstrap() + + client.call( + "POST", + "/api/v1/users", + 400, + raw=b'{"username":', + headers={"Content-Type": "application/json"}, + ) + client.call( + "POST", + "/api/v1/users", + 415, + raw=b'{"username":"wrong_media","display_name":"Wrong"}', + headers={"Content-Type": "text/plain"}, + ) + client.call("POST", "/api/v1/users", 409, body=alice["registration"]) + client.call( + "POST", + f"/api/v1/chats/{chat['id']}/messages", + 400, + actor=alice, + body={"text": " \t"}, + ) + client.call("GET", f"/api/v1/chats/{chat['id']}", 404, actor=outsider) + + prefix = "race-" + uuid.uuid4().hex + "-" + + def send(worker_id): + local = Client(args.base_url, args.ca_file) + return [ + local.message(alice, chat, f"{prefix}{worker_id}-{index}")["json"] + for index in range(10) + ] + + with ThreadPoolExecutor(max_workers=10) as pool: + created = [message for batch in pool.map(send, range(10)) for message in batch] + + check(len(created) == 100, "not all concurrent requests succeeded") + check(len({message["id"] for message in created}) == 100, "duplicate message ids returned") + + history = collect_messages(client, bob, chat) + concurrent_history = [message for message in history if message["text"].startswith(prefix)] + check(len(concurrent_history) == 100, "history does not contain exactly 100 concurrent messages") + check(len({message["id"] for message in concurrent_history}) == 100, "history contains duplicates") + check( + history == sorted(history, key=lambda message: (message["created_at"], uuid.UUID(message["id"]).int)), + "multi-page history is out of order", + ) + + print("PASS: malformed JSON/media type, duplicate username, blank message, outsider access, pagination") + print("PASS: 10 clients created exactly 100 unique messages") + + +if __name__ == "__main__": + run(main) diff --git a/student-tests/test_lifecycle.py b/student-tests/test_lifecycle.py new file mode 100644 index 00000000..bc463ace --- /dev/null +++ b/student-tests/test_lifecycle.py @@ -0,0 +1,103 @@ +#!/usr/bin/env python3 +"""Из lab1: SIGTERM. Для lab2 проверяем сохранность вместо потери состояния.""" +import json +import base64 +import os +from pathlib import Path +import signal +import subprocess +import sys +import time +import urllib.error +import urllib.request +import uuid + + +ROOT = Path(__file__).resolve().parents[1] +BASE = "http://127.0.0.1:18080" + + +def request(method, path, body=None, token=None, expected=200, extra_headers=None): + headers = {"Accept": "application/json"} + data = None + if body is not None: + data = json.dumps(body, ensure_ascii=False).encode() + headers["Content-Type"] = "application/json" + if token: + headers["Authorization"] = "Bearer " + token + headers.update(extra_headers or {}) + req = urllib.request.Request(BASE + path, data=data, headers=headers, method=method) + try: + response = urllib.request.urlopen(req, timeout=2) + except urllib.error.HTTPError as exc: + response = exc + with response: + payload = json.loads(response.read()) + if response.status != expected: + raise AssertionError(f"expected {expected}, received {response.status}: {payload}") + return payload + + +def start_server(): + env = os.environ.copy() + env["LOG_LEVEL"] = "WARNING" + process = subprocess.Popen( + [sys.executable, "-m", "uvicorn", "src.main:app", "--host", "127.0.0.1", "--port", "18080", "--timeout-graceful-shutdown", "10"], + cwd=ROOT, + env=env, + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + ) + deadline = time.monotonic() + 10 + while time.monotonic() < deadline: + if process.poll() is not None: + raise AssertionError("server exited during startup") + try: + request("GET", "/health/ready") + return process + except (OSError, urllib.error.URLError): + time.sleep(0.1) + process.kill() + raise AssertionError("server did not become ready") + + +def stop_server(process): + started = time.monotonic() + process.send_signal(signal.SIGTERM) + process.wait(timeout=10) + elapsed = time.monotonic() - started + try: + request("GET", "/health/live") + except (OSError, urllib.error.URLError): + pass + else: + raise AssertionError("server still accepts requests after shutdown") + return elapsed + + +def main(): + username = "restart_" + uuid.uuid4().hex[:12] + password = "Synthetic-password-42" + first = start_server() + try: + user = request("POST", "/api/v1/users", { + "username": username, "display_name": "До перезапуска", "password": password, + }, expected=201) + basic = base64.b64encode((username + ":" + password).encode()).decode() + session = request("POST", "/api/v1/auth/sessions", expected=201, + extra_headers={"Authorization": "Basic " + basic}) + request("GET", "/api/v1/users/me", token=session["token"]) + finally: + elapsed = stop_server(first) + second = start_server() + try: + restored = request("GET", "/api/v1/users/me", token=session["token"]) + assert restored == user, "User changed after API restart" + finally: + stop_server(second) + print(f"PASS: SIGTERM completed in {elapsed:.3f}s (limit 10s); listener closed") + print("PASS: user and existing Bearer session survived API process restart") + + +if __name__ == "__main__": + main()