diff --git a/.env.example b/.env.example index 714c8076..4b5e63c7 100644 --- a/.env.example +++ b/.env.example @@ -1,11 +1,9 @@ -# Copy to .env for your LOCAL synthetic test environment; never commit .env. -# These are logical interface suggestions; map actual framework names in REPORT.md. -APP_HOST=0.0.0.0 -APP_PORT=8080 -APP_ENV=lab +# Host HTTP port; API listens on 8080 inside its container. +APP_PORT=8082 SESSION_TTL_SECONDS=3600 -# Choose credentials locally. File paths contain no secret values. -DATABASE_URL_FILE=/run/secrets/database_url -# Optional on 3, required use on 4 in lab2; Redis OR Valkey: -SESSION_STORE=postgres -CACHE_URL_FILE=/run/secrets/cache_url +# Generated by make bootstrap, mounted through Compose secrets. +# The actual API environment is declared in compose.yaml: +# DATABASE_URL_FILE=/run/secrets/database_url +# CACHE_URL_FILE=/run/secrets/cache_url +# CURSOR_KEY_FILE=/run/secrets/cursor_key +# SESSION_STORE=postgres (one authoritative session store, no runtime switch) diff --git a/DEFENSE.md b/DEFENSE.md new file mode 100644 index 00000000..5d29b0fb --- /dev/null +++ b/DEFENSE.md @@ -0,0 +1,410 @@ +# Защита лабораторной 2 — разбор своего проекта + +Крайкин Глеб Алексеевич, БВТ2303. Цель — 5, трек 2: SQL-план и восстановление. + +Это материал для понимания и тренировки. Сначала запусти проект и повтори действия сам. Цифры текущего прогона смотри в `evidence/experiment-summary.md`: после нового `make experiment` они могут измениться. + +## 1. Что сказать в начале за 60–90 секунд + +«В первой работе мессенджер хранил пользователей, чаты и сообщения в памяти одного Go-процесса. После рестарта они исчезали. Во второй работе я сохранил функции API, но перенёс данные в PostgreSQL и заменил выбор пользователя через X-User-Id на аутентификацию. + +При регистрации пароль проходит Argon2id. Через Basic клиент один раз получает случайный Bearer-токен. В PostgreSQL хранится SHA-256 токена, пользователь и абсолютное время окончания сессии. Каждый защищённый запрос проверяет эту запись, затем членство пользователя в чате. + +Valkey кэширует неизменяемые публичные профили на 300 секунд. Он помогает избежать повторного SELECT пользователя, но не решает, действителен ли токен. Поэтому logout сразу работает даже при заполненном кэше, а при потере кэша API обращается к БД. + +Я проверил полный рестарт API, PostgreSQL и Valkey с прежним токеном и теми же данными. Для исследования сравнил три индекса на 100 тысячах сообщений в чатах разного размера, измерил чтение, запись и размер индекса. Затем сделал pg_dump, восстановил его в отдельное хранилище и сверил содержимое». + +После этого открой файлы и объясни конкретные операции. Фраза «всё делает Docker» не объясняет реализацию. + +## 2. Карта проекта: где искать ответ + +| Файл / функция | Что показать преподавателю | +|---|---| +| `cmd/server/main.go`, `run` | Настройки, чтение secrets, pool, миграции, HTTP, SIGTERM | +| `internal/database/database.go`, `Open` | 10 соединений, connect/statement/lock timeout | +| `internal/database/database.go`, `Migrate` | Миграции, ledger, checksum, advisory lock | +| `internal/database/migrations/001_initial.sql` | Таблицы, FK, UNIQUE, составной индекс | +| `internal/messenger/server.go`, `ServeHTTP` | Порядок маршрутизации и аутентификации | +| `createUser` и `password.go` | Регистрация и Argon2id | +| `login` | Basic → проверка пароля → постоянная сессия | +| `authenticate` | Bearer → SHA-256 → поиск действительной сессии | +| `profile` | Cache-aside профиля, TTL и fallback | +| `createChat` | BEGIN, чат + участники, COMMIT / ROLLBACK | +| `createMessage` | Блокировка одного чата, время, запись, COMMIT | +| `pagination`, `encodeCursor`, `listMessages` | HMAC, scope, keyset, LIMIT + 1 | +| `compose.yaml`, `Dockerfile` | Процессы, сеть, volumes, версии, non-root | +| `scripts/restart.sh` | Реальный последовательный рестарт всех компонентов | +| `student-tests/integration.py` | Ошибки, конкуренция, отказы, TTL 2 s, persistence | +| `internal/messenger/database_test.go` | Реальные HTTP + PostgreSQL под `-race` | +| `student-tests/experiment.py` | SQL-исследование и backup → restore | + +Читай функции в этом порядке: `ServeHTTP` → `authenticate` → `profile` → `getChat` → `listMessages`. Так прослеживается реальный GET истории. + +## 3. Что запускается и где лежат данные + +```mermaid +flowchart LR + C[Клиент / Postman] -->|localhost:8082| A[Go API :8080] + A -->|сессии, данные, транзакции| P[(PostgreSQL)] + A -->|публичный профиль, TTL 300 s| V[(Valkey)] + P --- D[postgres_data volume] + V --- E[valkey_data volume: кэш можно потерять] +``` + +На хост опубликован только API: `127.0.0.1:8082`. PostgreSQL и Valkey доступны внутри Compose-сети. API stateless относительно обязательных данных. Его остановка уничтожает соединения и локальные объекты, но не содержимое PostgreSQL-volume. + +`make up` делает bootstrap, собирает образ и запускает стенд. Bootstrap создаёт локальные пароли БД/кэша и ключ курсора, никогда не переписывая существующие файлы. `.env` и `secrets/` исключены из Git. Секреты монтируются отдельными файлами; key курсора сохраняется между рестартами. + +`docker compose down` удаляет контейнеры и сеть, сохраняя именованные volumes. `down -v` удаляет volumes и учебные данные; эта команда не входит в проверки сохранности. + +## 4. Сквозной пример: регистрация, вход, чтение + +### Регистрация + +POST `/api/v1/users` с `username`, `display_name`, `password`: + +1. `decode` проверяет media type, размер, UTF-8, ровно ожидаемые ключи, отсутствие null/дублей/второго JSON. +2. `createUser` проверяет username, число Unicode code points имени и пароля. +3. Семафор разрешает максимум два одновременных KDF; каждый использует 64 MiB. +4. `hashPassword` создаёт случайную соль и Argon2id-хеш. +5. Параметризованный INSERT создаёт пользователя. UNIQUE username защищает от гонки. +6. `201 User` не содержит пароль или его хеш. + +Если два клиента одновременно регистрируют `alice`, проверка вида SELECT «свободно?» сама по себе недостаточна: оба могли бы увидеть отсутствие записи. Уникальное ограничение в БД выбирает одного победителя; другим API возвращает 409. + +### Вход + +POST `/api/v1/auth/sessions`, без JSON body: + +```text +Authorization: Basic base64(username:password) +``` + +Basic декодируется через `r.BasicAuth()`. Пароль может содержать двоеточие: первое отделяет username, остальные входят в пароль. Basic не шифрует данные; стенд локальный и с синтетическими паролями. + +`login` читает пользователя и password_hash, выполняет Argon2id с сохранённой солью и сравнивает результат. Для отсутствующего username используется dummy hash, чтобы избежать очевидного пропуска дорогого вычисления. Это не доказательство полной защиты от всех timing attacks. + +Сервер создаёт 32 случайных байта: 256 бит энтропии. Base64url даёт непрозрачную строку-токен. В PostgreSQL записываются: + +```text +token_hash = SHA256(строки token) +user_id = UUID пользователя +expires_at = часы PostgreSQL + SESSION_TTL_SECONDS +``` + +Клиенту возвращаются token, token_type, expires_at и User. Исходный токен в БД не сохраняется. Сессия постоянная, потому что её строка находится в PostgreSQL-volume, а не в Go-map. + +### Защищённый GET + +GET `/api/v1/chats/{id}/messages`: + +1. `ServeHTTP` назначает request_id и контекст с бюджетом 3 секунды. +2. `authenticate` принимает только Bearer, проверяет формат, считает SHA-256. +3. SQL ищет `token_hash` с `expires_at > clock_timestamp()`. +4. Нет строки / срок прошёл → 401. БД недоступна → 503. +5. `profile` получает публичный User из Valkey или из PostgreSQL. +6. `getChat` делает JOIN с `chat_members` для этого пользователя. +7. Нет доступного чата → 404. Существующий чужой чат тоже 404. +8. `pagination` проверяет limit и подписанный cursor. +9. `listMessages` выполняет SQL-чтение страницы через составной индекс. +10. Go кодирует JSON и возвращает страницу с next_cursor. + +`X-User-Id` в этом пути не используется. Если прислать действующий Bearer Алисы и X-User-Id Боба, пользователь останется Алисой. + +## 5. Пароль, токен и курсор: три разных задачи + +| Механизм | Вход | Зачем | Где хранится | +|---|---|---|---| +| Argon2id | Человеческий пароль + случайная соль | Удорожить подбор сравнительно слабого пароля | Строка KDF в users.password_hash | +| SHA-256 токена | Случайный 256-битный token | Поиск сессии без хранения исходного токена | 32 байта в sessions.token_hash | +| HMAC-SHA256 курсора | Payload курсора + секретный ключ | Обнаружить подделку границы и области | Подпись в курсоре, ключ в secrets | + +Нельзя заменять Argon2id обычным SHA-256: быстрый хеш помогает атакующему проверять много догадок. У случайного токена пространство поиска уже огромное, а серверу нужен быстрый lookup на каждом запросе. + +Argon2id: память 65 536 KiB, 3 прохода, 2 lanes, соль 16 байт, результат 32 байта. Соль публичная и уникальная, это не пароль и не ключ шифрования. Один пароль у двух пользователей даёт разные строки KDF. Unicode-пароль до 128 code points не обрезается до 72 байт; есть тест 128 emoji и HTTP-пароля с двоеточием. + +Курсор подписан, но не зашифрован. «Непрозрачный для клиента» означает, что клиент передаёт строку обратно и не строит её сам; конфиденциальность содержимого здесь не обещается. + +Токен не JWT. У него нет самостоятельно проверяемого payload: решение о действительности находится в таблице sessions. Это облегчает немедленный отзыв. + +## 6. Сессии: expiry, logout, рестарт + +`SESSION_TTL_SECONDS=3600` задаёт срок НОВОЙ сессии. Существующая сессия хранит абсолютное expires_at; значение не пересчитывается при каждом GET и не продлевается из-за рестарта. + +Пример: вход в 12:00 с TTL 3600 → expires_at 13:00. Рестарт в 12:20 не сдвигает окончание на 13:20. При 13:00 условие `>` уже не выполнено. + +Logout сначала аутентифицирует запрос, затем делает DELETE строки sessions. Следующий запрос с этим токеном получает 401, даже если профиль всё ещё в Valkey. Повторный logout получает 401. Другая сессия того же пользователя остаётся действующей. + +При одновременном logout и другом запросе запрос, уже прошедший проверку до DELETE, может закончиться. Здесь нет обещания отмены всех находящихся в работе запросов. Запрос после подтверждённого logout проверяет БД заново. + +Expiry логический: наличие истёкшей строки не даёт доступа. Автоматическая очистка истёкших строк пока не реализована; это задача будущего обслуживания. Не путай TTL cache-профиля с TTL сессии. + +## 7. Valkey: объяснение с четырьмя состояниями + +В `profile` используется cache-aside: + +```text +Проверка действительной сессии в PostgreSQL + ↓ +GET profile:v1: + hit → публичный User + miss / ошибка → SELECT users → SET EX 300 → User +``` + +Источник истины — PostgreSQL. В Valkey лежит сериализованный User без password_hash и токена. TTL 300 секунд ограничивает время жизни cache-записи. В обязательном API нет изменения/удаления профиля, поэтому профиль неизменяемый и явная инвалидация не нужна. Если добавить PATCH display_name, понадобится пересмотреть политику. + +| Состояние | Что произойдёт | +|---|---| +| Кэш заполнен, сессия действительна | SQL-проверка sessions + профиль из кэша | +| Кэш пуст / FLUSHDB / рестарт | SQL-проверка sessions + SELECT users + заполнение кэша | +| Valkey выключен | Те же два SQL-чтения, HTTP продолжает работать | +| Сессия удалена, профиль в кэше | 401 до обращения к профилю | + +Кэш здесь экономит SELECT пользователя, а не все SQL-запросы. История сообщений в Valkey не кэшируется: следующий GET читает подтверждённую запись из PostgreSQL и не получает stale history из отдельного кэша. + +У Valkey отключены RDB/AOF, потеря профилей допустима. Это удовлетворяет требованию кэша; если бы Valkey был единственным хранилищем сессий, такой настройки было бы недостаточно. Именованный valkey_data volume не превращает оперативную память в сохранённые данные. + +Бюджет каждого cache вызова 80 ms, socket/pool timeouts 60 ms, автоматических retry нет. После ошибки GET код может потратить ещё один ограниченный SET-бюджет. Circuit breaker и singleflight отсутствуют; при массовом холодном кэше возможны повторные SELECT users. Защита от stampede не заявлена, выбран другой трек исследования. + +## 8. Таблицы и ограничения — пример на Алисе и Бобе + +```text +users: Alice(U1), Bob(U2), Eve(U3) +chats: Chat(C1) +chat_members:(C1,U1), (C1,U2) +messages: M1 → C1, sender U1 +sessions: hash(T1) → U1, expires_at +``` + +PK гарантирует уникальную идентичность строки. UNIQUE username запрещает повтор имён. FK запрещает ссылку на несуществующую сущность. Составной PK `(chat_id,user_id)` запрещает повторное членство. Составной FK сообщения `(chat_id,sender_id)` ссылается на chat_members: отправитель обязан быть участником именно этого чата. + +Это дополнение к проверке HTTP-доступа, не её замена. БД не знает, какой токен передан в HTTP; API выводит uid из сессии и передаёт его в запрос. + +Число code points в Go — `utf8.RuneCountInString`; в UTF-8 PostgreSQL — `char_length`. Это не число байт и не число визуальных символов: emoji с модификаторами может содержать несколько code points. + +## 9. Транзакции — объясни именно границу COMMIT + +### Создать чат с неизвестным участником + +`createChat` проверяет UUID, отсутствие дублей и наличие текущего пользователя в member_ids. Затем: + +```sql +BEGIN; +INSERT INTO chats ...; +INSERT INTO chat_members ...; -- Alice, успешно +INSERT INTO chat_members ...; -- неизвестный UUID, FK violation +ROLLBACK; +``` + +Несмотря на успешный первый INSERT, нет частичного чата и нет частичного списка участников. `defer tx.Rollback(...)` откатывает незавершённую транзакцию. При полностью корректном списке выполняется COMMIT, и лишь затем 201. + +Тест отправляет неизвестный UUID после действительного участника и проверяет отсутствие чата с уникальным title. Поэтому он проверяет реальный rollback, а не только отказ до BEGIN. + +### Отправить сообщение + +`createMessage` делает BEGIN, UPDATE одной строки chats, INSERT messages и COMMIT. UPDATE берёт row lock: одновременно пишущие в один чат ждут друг друга. Чаты разные → строки блокировок разные. Это может стать ограничением горячего чата. + +Время: + +```sql +GREATEST(clock_timestamp(), last_message_at + interval '1 microsecond') +``` + +Значение хранится в БД. Даже если часы откатились, время нового сообщения в этом чате больше предыдущего. Row lock сохраняет эту гарантию для разных Go-процессов. Время не используется как уникальный ID: UUID генерируется отдельно. + +Почему UPDATE и INSERT в одной транзакции? Если INSERT не получится, изменение last_message_at тоже откатится. Если получилось, сообщение и новое значение времени подтверждаются вместе. + +COMMIT означает, что PostgreSQL подтвердил транзакцию. При fsync=on, synchronous_commit=on и full_page_writes=on WAL нужной транзакции сброшен согласно локальным гарантиям БД. Это не гарантия сохранности при потере всего диска/host или неисправном storage. Volume переживает удаление контейнера, но не является backup. + +Если БД успела COMMIT, а сеть оборвалась до 201, клиент не знает результата. В lab2 повтор POST может создать второе сообщение: идемпотентность появляется в следующей лабораторной и здесь не заявлена. + +## 10. Keyset-пагинация на конкретном массиве + +Представь пять сообщений, UUID ниже сокращены только для объяснения: + +| Сообщение | created_at | id | +|---|---|---| +| A | 12:00:00.000001 | 10 | +| B | 12:00:00.000002 | 20 | +| C | 12:00:00.000002 | 30 | +| D | 12:00:00.000003 | 40 | +| E | 12:00:00.000004 | 50 | + +При limit=2 сервер читает **3** строки: A, B, C. Клиент получает A и B. Третья строка показывает, что продолжение существует. Курсор кодирует пару B: `(time=.000002, id=20)` и scope этого чата. + +Следующая страница: + +```sql +WHERE chat_id = $1 + AND (created_at, id) > ($2::timestamptz, $3::uuid) +ORDER BY messages.created_at, messages.id +LIMIT $4; -- limit + 1 +``` + +Сравнение пары означает `time > cursor_time OR (time = cursor_time AND id > cursor_id)`. Поэтому C проходит, B не повторяется. Из C, D, E возвращаются C и D, потом E. Последняя страница имеет next_cursor=null. + +Зачем id, если приложение делает время строго возрастающим в чате? Контракт определяет общий порядок парой; id делает порядок полным и для совпадающих времён, например импортированных данных. В SQL id сравнивается как uuid. ORDER BY квалифицирован именем таблицы, чтобы SELECT `id::text` не заставил сортировать по текстовому alias. + +В cursor есть scope: `messages:` или `chats:`, время и ID. HMAC защищает от изменения scope и границы. Курсор другого чата → 400. Limit можно менять между страницами. + +Это не snapshot всего обхода. Новое сообщение с большей парой может попасть в следующую страницу. После null дальнейшие записи автоматически не приходят: клиент должен сделать новое чтение. Чаты используют серверное created_at, но не глобальный монотонный счётчик; при откате часов новые чаты могут оказаться до уже выданного курсора. Для неизменного набора порядок и отсутствие повторов сохраняются. + +## 11. Индексы: новый аналог темы linear / binary + +В этой работе **нет HISTORY_SEARCH и нет runtime-переключателя linear/binary**. Рабочий API всегда использует SQL keyset и `messages_history_idx(chat_id,created_at,id)`. + +В `experiment.py` три варианта последовательно создаются в ОТДЕЛЬНОЙ исследовательской БД. Индексы рабочего API не меняются. `chat_only`, `composite`, `covering` — названия конфигураций исследования, не три режима аутентификации и не имитация SQL в тесте. + +| Вариант | Структура | Что умеет | Цена | +|---|---|---|---| +| chat_only | B-tree `(chat_id)` | Находит сообщения чата, затем фильтрует пару/сортирует | Малый индекс, много обработанных строк | +| composite | B-tree `(chat_id,created_at,id)` | Равенство по чату, диапазон после cursor, требуемый порядок | Больше chat_only, обслуживается при каждой записи | +| covering | Тот же ключ + INCLUDE(sender_id,text) | Может получить поля без heap fetch | Намного больше, больше WAL и обновлений индекса | + +Почему chat_id первым? Запрос сначала выбирает один чат. Записи других чатов не нужно рассматривать. Затем ключи created_at/id задают границу и порядок именно внутри выбранного чата. + +Индекс с порядком `(created_at,id,chat_id)` сгруппировал бы сначала время всех чатов. Условие chat_id не ограничивало бы непрерывный ведущий диапазон так же эффективно. При иной нагрузке другой порядок может быть полезен, но он не соответствует нашему запросу. + +B-tree — не `sort.Search` Go-массива. PostgreSQL ищет подходящую область дерева, затем читает последовательный диапазон. Работы приблизительно O(log N + K) для границы и страницы, но фактическая стоимость включает I/O, visibility checks, получение строк, блокировки и планировщик. «O(log N)» не объясняет весь HTTP-запрос. + +Покрывающий индекс не гарантирует Index Only Scan без обращений к таблице: видимость строк подтверждается visibility map; после свежих изменений heap fetch может понадобиться. В эксперименте перед чтением выполнен VACUUM ANALYZE, поэтому условия благоприятные. + +## 12. Как читать настоящий EXPLAIN + +Открой `evidence/explain-history.txt` и планы в `experiment.json`. Читай дерево снизу вверх. + +- `Index Cond`: условия, которыми БД ограничила диапазон индекса. +- `Filter`: условия, проверенные уже после чтения кандидатов. +- `Rows Removed by Filter`: сколько кандидатов прочитано и отброшено. +- `Actual Rows`, `Actual Loops`: реально обработанные строки и повторения узла. +- `Sort`: БД пришлось сортировать кандидатов. Наличие LIMIT не гарантирует, что до сортировки прочитали только страницу. +- `Buffers shared hit`: блоки найдены в shared buffers PostgreSQL. +- `Buffers shared read`: блоки загружены в shared buffers; это не обязательно физическое чтение диска, может помочь OS cache. +- `Heap Fetches`: при Index Only Scan, сколько проверок потребовало обращения к heap. +- `cost`: оценки планировщика в условных единицах, не миллисекунды. +- `actual time` и `Execution Time`: измеренное время выполнения с накладными расходами EXPLAIN. + +Для большого чата и поздней страницы chat_only отбрасывает примерно 72 тысячи записей до границы и сортирует оставшихся кандидатов. Composite включает сравнение пары в Index Cond и читает около размера страницы; верхний Limit отдаёт 51 строку без отдельного Sort. + +Не говори «Index Scan всегда быстрее Seq Scan». Для маленькой таблицы или запроса почти всех строк последовательный scan может быть дешевле. Важно, что план подходит нашему WHERE, ORDER BY и LIMIT. + +Не путай p95 HTTP из `http-load-*.json` со средней SQL-latency pgbench. Их нельзя делить друг на друга как одну метрику. + +## 13. Методика и вывод исследования + +100 000 сообщений распределены по чатам 80 000, 15 000, 4900 и 100. У каждого измеряются первая страница и граница около 90% истории, 1 и 4 SQL-клиента, по 3 повтора. Pgbench использует prepared query, делает прогрев и реальные SQL-запросы. Это warm closed-loop исследование SQL, а не доказательство максимального RPS приложения. + +Стоимость записи проверяется отдельно: одинаковая пустая write_probe с PK и выбранным вторичным индексом, batch INSERT 1000 строк и настоящий COMMIT. EXPLAIN дополнительно записывает WAL bytes. Полезно сравнить и latency, и WAL, и размер; по трём коротким batch-прогонам нельзя делать сильный вывод о максимальной скорости постоянного потока одиночных HTTP POST. + +Выбран composite: на большой поздней странице он радикально сокращает работу относительно chat_only. Covering в текущем прогоне не улучшил SQL latency, но занял примерно в 4,2 раза больше места, чем composite. Конкретные числа и CPU/память записаны в отчёте и raw evidence. + +Фиксированный порядок вариантов, тёплые данные, короткие прогоны, Docker Desktop и фоновые процессы ограничивают обобщение результата. Отдельные контрольные HTTP POST-прогоны нужны для API, но не подменяют SQL-сравнение. + +## 14. Backup / restore: рестарт ещё не восстановление + +Рестарт использует прежний volume. Restore создаёт **новую пустую БД на отдельном restore_data volume** и загружает туда dump. Поэтому тест действительно проверяет возможность собрать данные из копии. + +Сценарий: + +1. В research-db создаётся свежая именованная БД с SQL fixture. +2. После исследования возвращается production-индекс. +3. Считаются users/chats/members/messages, fingerprint содержимого всех сообщений и 5 выбранных полных записей. +4. `pg_dump -Fc` создаёт согласованную snapshot-копию. +5. `pg_restore --single-transaction --exit-on-error` восстанавливает в restore-db. +6. Сверки полностью совпадают. +7. В source добавляется подтверждённая запись после backup; в restore её нет. + +Fingerprint MD5 здесь — быстрый тест равенства синтетического набора, не password KDF и не криптографическая гарантия против атакующего. Также сравниваются количества и выбранные поля записей. SHA-256 dump помогает идентифицировать измеренную копию. + +RPO — сколько данных может потеряться. При одном snapshot-backup без WAL archive могут потеряться все изменения после начала snapshot. Проверка показывает конкретно одну отсутствующую позднюю запись; это не обещание «теряем максимум одно сообщение». + +RTO — время до восстановления работоспособности. В evidence измерен только pg_restore; полное RTO включает обнаружение отказа, получение backup, выделение машины, восстановление, проверку и переключение API. В тесте не настроен PITR и не имитируется гибель всего хоста. + +Исследовательская fixture имеет синтетический password_hash `synthetic-no-login`, потому что исследуются таблицы и SQL, а не вход. Это не регистрация рабочего API. Пароли рабочего стенда проходят Argon2id. Сессионную сохранность отдельно проверяет публичный persistence-тест на настоящем API. + +## 15. Живая демонстрация без поиска команд + +Терминал, каталог решения: + +```sh +make up +make check +make test +make test-student +make test-race +make experiment +``` + +`make test` требует уже работающий API. `make test-student` сначала запускает Go-тесты, затем ходит в настоящий стенд и временно останавливает только его зависимости; восстанавливает их, проверяет TTL 2 и возвращает TTL 3600. `make test-race` поднимает одноразовый тестовый контейнер с Go и запускает настоящие PostgreSQL/HTTP-проверки под детектором гонок. `make experiment` запускает две отдельные SQL-БД и не меняет рабочие таблицы. + +Для ручного сценария импортируй `postman/lab2.postman_collection.json` в настольный Postman. Run выполняет 23 запроса; ID и токены сохраняются автоматически. Базовый URL `http://localhost:8082`. + +Чтобы показать сохранность вручную: выполни 01–17; затем в терминале `scripts/restart.sh`. Дождись `curl http://localhost:8082/health/ready`, повтори запросы 09 и 15 **без повторного входа**. Заверши 22 logout и 23 ожидаемый 401. Обычный Run с новым входом после рестарта не доказывает сохранность старой сессии. + +Автоматически то же делает: + +```sh +make test-persistence ACTION_SCRIPT=scripts/restart.sh +``` + +Не сохраняй действующие токены в отчёт, Git или экспорт Postman. Не печатай содержимое secrets. Планы можно читать из файлов evidence без запуска долгого исследования на защите. + +## 16. Вопросы преподавателя: ответ и привязка к коду + +| Вопрос | Ответ своими словами | Где доказать | +|---|---|---| +| Что перенёс из первой лабы? | HTTP-функции пользователей/чатов/сообщений, валидацию, cursor, Docker lifecycle; хранение и auth заменены | server.go, REPORT.md | +| Где теперь источник истины? | PostgreSQL; обязательные данные не зависят от памяти API | SQL migration | +| Для чего нужен Valkey? | Убирает повторный SELECT неизменяемого профиля, TTL 300 | profile | +| После рестарта Valkey нужно войти заново? | Нет, сессия в PostgreSQL; профиль загрузится заново | authenticate → profile | +| Почему не положил сессии только в кэш? | Их потеря нарушила бы контракт; выбрал устойчивую таблицу | sessions | +| TTL и persistence — одно и то же? | TTL ограничивает срок, persistence сохраняет состояние после рестарта | expires_at и volume | +| Чем auth отличается от доступа? | Auth определяет пользователя; membership разрешает конкретный чат | authenticate, getChat | +| Почему чужой чат 404? | Не раскрываем существование чужого объекта | JOIN + missing | +| Почему KDF, а не SHA-256 пароля? | Пароль подбирают из догадок; KDF требует памяти и времени | password.go | +| Почему SHA-256 токена разрешён? | Токен — случайные 256 бит, нужен быстрый серверный lookup | login, authenticate | +| Почему не JWT? | Для opaque токена действительность хранится в БД; простой отзыв | sessions DELETE | +| Что будет с X-User-Id? | Игнорируется; не создаёт и не меняет сессию | ServeHTTP | +| Как победить гонку username? | UNIQUE в БД, 23505 → 409 | createUser | +| Что если третий участник неизвестен? | FK выдаёт ошибку, весь чат rollback | createChat | +| Как не допустить отправителя вне чата? | HTTP membership + составной FK | getChat, SQL migration | +| Где была бы SQL injection? | При конкатенации клиентского input в SQL; у нас параметры $1… | SQL вызовы | +| Чем помогает connection pool? | Переиспользует максимум 10 соединений, ограничивает давление на БД | Open | +| Что будет при падении БД? | Live 200, ready 503, защищённый запрос 503 в пределах budget | интеграционные тесты | +| Почему нет mutex от lab1? | Данные защищены транзакциями и ограничениями БД; pool thread-safe | Server, createMessage | +| Почему LIMIT не решает проблему плохого индекса? | До LIMIT может потребоваться прочитать/отсортировать множество кандидатов | EXPLAIN chat_only | +| Где «optimized» в этой работе? | Composite-индекс production; конфигурации сравниваются в research-db | experiment.py | +| Почему covering не выбрал? | В текущем профиле нет выгоды по latency, индекс и WAL больше | raw results | +| Что гарантирует 201 сообщения? | Успешный COMMIT до ответа; не доставку ответа при сетевом обрыве | createMessage | +| Volume — это backup? | Нет; потеря самого диска уничтожит и volume | restore-сценарий | +| Какие данные теряются при restore? | Изменения после snapshot без WAL archive | post-backup marker | +| Что проверил `-race`? | Исполненные конкурентные обращения Go; не все возможные гонки/SQL-аномалии | race-http.txt | + +## 17. Самопроверка без подсказки + +Закрой предыдущие разделы и устно ответь, затем проверь себя по ним: + +1. Проследи весь GET истории, называя функции и SQL-условия. Почему кэш профиля не может обойти logout? +2. У Алисы два токена. Logout первого: какие строки исчезают, останется ли второй действительным? +3. TTL новой сессии изменили с 3600 до 2. Что будет со старой сессией и почему? +4. В chats INSERT прошёл, в chat_members второй INSERT провалился. Какой результат увидит другое соединение? +5. Два API одновременно пишут в один чат после отката часов. Кто назначает время и кто держит lock? +6. По таблице A–E вручную найди две следующие страницы. Почему используется строгое `>`? +7. Объясни три индекса без слов «baseline быстрее/медленнее». Какие строки обрабатывает каждый? +8. Найди в EXPLAIN Index Cond, Filter и фактические строки. Как доказать, что читается диапазон страницы? +9. Почему Index Only Scan может всё же обращаться к таблице? +10. Как из 1000-row INSERT, WAL bytes и размера индекса сделать осторожный вывод о цене записи? +11. Чем отличаются `make test`, `make test-student`, `make test-race`, `make experiment`? Кто запускает сервер? +12. Backup был в 12:00, последнее сообщение в 12:05, диск погиб в 12:10. Какие данные гарантированно есть в копии? + +Критерий готовности: ответить на каждый вопрос с конкретным примером и открыть нужную функцию за 15–20 секунд. Если можешь только повторить определение, вернись к сквозному примеру и выполни его руками. + +## 18. План подготовки на три подхода + +Первый, 30–40 минут: запусти make up и Postman; проследи регистрацию, вход и GET по коду. Объясни различие KDF/token digest/HMAC без чтения памятки. + +Второй, 40–50 минут: создай чат с неверным участником, прочитай SQL-схему и транзакции; пройди пример A–E; открой планы и сравни число обработанных строк. Вручную объясни, почему chat_id стоит первым в индексе. + +Третий, 30–40 минут: пройди полную демонстрацию restart → старый token → logout. Объясни backup cutoff, ответь на 12 вопросов вслух и запиши места, где ещё путаешься. Затем расскажи весь проект за 5 минут и попроси собеседника прервать тебя уточняющим вопросом. + +Не обещай абсолютную надёжность или универсальное ускорение. На защите сильнее звучит точное объяснение проверенного поведения и его границ. diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 00000000..5ae819c9 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,22 @@ +FROM golang:1.24.4-alpine3.22 AS build +WORKDIR /src +COPY go.mod go.sum ./ +RUN go mod download +COPY cmd/ ./cmd/ +COPY internal/ ./internal/ +RUN CGO_ENABLED=0 go build -trimpath -ldflags="-s -w" -o /out/messenger ./cmd/server + +FROM build AS tests +RUN apk add --no-cache gcc musl-dev +ENV CGO_ENABLED=1 +CMD ["go", "test", "-race", "-count=1", "-v", "./..."] + +FROM alpine:3.22.1 +RUN addgroup -g 10001 app && adduser -D -u 10001 -G app app +COPY --from=build /out/messenger /usr/local/bin/messenger +USER 10001:10001 +ENV APP_HOST=0.0.0.0 APP_PORT=8080 APP_ENV=lab +EXPOSE 8080 +HEALTHCHECK --interval=5s --timeout=4s --start-period=3s --retries=3 CMD ["/usr/local/bin/messenger", "healthcheck"] +STOPSIGNAL SIGTERM +ENTRYPOINT ["/usr/local/bin/messenger"] diff --git a/MERGE_REQUEST.md b/MERGE_REQUEST.md new file mode 100644 index 00000000..98b27d68 --- /dev/null +++ b/MERGE_REQUEST.md @@ -0,0 +1,28 @@ +# ЛР 2 — БВТ2303 — Крайкин — на 5 + +Автор: Крайкин Глеб Алексеевич, БВТ2303. Цель: 5, трек 2 — SQL-план и восстановление. + +Состояние мессенджера lab1 перенесено в PostgreSQL: подтверждённые сообщения, пользователи, чаты, членство и действующие сессии сохраняются при полном рестарте API и хранилищ. Регистрация использует Argon2id; Basic применяется только для входа, бизнес-запросы — Bearer, logout/expiry проверяются в БД. Valkey кэширует неизменяемые публичные профили с TTL300 и fallback, не отменяя отзыв сессии. + +Добавлены транзакции, FK/UNIQUE, миграции с checksum/ledger, connection pool/timeouts, составной keyset-индекс, воспроизводимый Compose, secrets bootstrap и scripts/restart.sh. Собственные проверки включают rollback, гонку username, 100 сообщений от 10 клиентов, реальные HTTP/PG race-тесты, отказы Valkey/PG, TTL2 и сохранность старого token. Контракт и публичные tests не изменены. + +Трек 2: 100000 сообщений в неравномерных чатах, три индекса, SQL-чтение + цена batch-записи/WAL/размер. Составной индекс выбран по измерениям. pg_dump восстановлен в отдельное новое хранилище: counts/fingerprint/выбранные сообщения совпали; отдельно показана потеря post-backup marker без WAL archive. + +Проверка: +```sh +make up +make check test +make test-student test-race test-docker +make test-persistence ACTION_SCRIPT=scripts/restart.sh +make experiment +python3 student-tests/clean_clone.py +``` + +Результаты и ограничения — REPORT.md, evidence/. Подготовка к защите — DEFENSE.md, QUICKSTART.md, Postman collection. Локальный HTTP с синтетическими данными; нет HA/PITR/idempotency и production runtime-role. SQL TPS не объявляется HTTP RPS. Использованы собственная lab1, контракт преподавателя, официальная документация Go/PostgreSQL/Valkey; Codex помог с реализацией и материалами. + +- [x] Весь минимум текущей и прошлой работы сохранён с переходом auth/storage. +- [x] Контракт, README и публичные проверки не ослаблены. +- [x] make check/test и собственные сценарии выполнены, приложен реальный вывод. +- [x] Отказы, expiry/logout, полный restart и backup/restore воспроизведены. +- [x] Secrets, приватные ключи, локальный .env и действующие tokens вне Git. +- [x] REPORT.md описывает запуск из чистой копии и границы результата. diff --git a/Makefile b/Makefile index 9ecb223e..ea81926a 100644 --- a/Makefile +++ b/Makefile @@ -1,5 +1,5 @@ PYTHON ?= python3 -BASE_URL ?= http://localhost:8080 +BASE_URL ?= http://localhost:8082 CA_FILE ?= ACTION_SCRIPT ?= TLS_ARGS = $(if $(CA_FILE),--ca-file "$(CA_FILE)",) @@ -24,3 +24,27 @@ 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: bootstrap up down test-student experiment +bootstrap: + $(PYTHON) scripts/bootstrap.py +up: bootstrap + docker compose --env-file .env up -d --build --wait + +down: + docker compose --env-file .env down + +test-student: + go test -race -count=1 -v ./... + $(PYTHON) student-tests/integration.py --base-url "$(BASE_URL)" + +experiment: + $(PYTHON) student-tests/experiment.py + +.PHONY: test-race +test-race: + docker compose --env-file .env --profile verify run --build --rm tests + +.PHONY: test-docker +test-docker: + $(PYTHON) student-tests/lifecycle.py --base-url "$(BASE_URL)" diff --git a/QUICKSTART.md b/QUICKSTART.md new file mode 100644 index 00000000..9a31a8b4 --- /dev/null +++ b/QUICKSTART.md @@ -0,0 +1,54 @@ +# Быстрый запуск ЛР 2 + +Открой Docker Desktop. Терминал: + +```sh +cd /Users/glebkraykin/Projects/highload-apps-labs/lab2 +make up +curl http://localhost:8082/health/ready +make test +``` + +API доступен на **http://localhost:8082**, внутри контейнера — 8080. Нужны Docker Compose v2, Python 3.9+ и make; Go для обычного запуска не нужен. `make up` сам создаёт локальный `.env` и секреты, собирает API и ждёт готовности. + +Если 8082 занят, поменяй APP_PORT в локальном .env и передай `BASE_URL=http://localhost:НОВЫЙ_ПОРТ` всем make-проверкам; также измени base_url Postman. Изменения пароля PostgreSQL после создания volume требуют отдельной операции смены пароля в самой БД, а не просто нового bootstrap. + +Импортируй `postman/lab2.postman_collection.json` в настольный Postman. Нажми Run: 23 запроса создадут пользователей, войдут, создадут чат, отправят сообщения, проверят страницы и logout. Пароли учебные. ID и Bearer сохраняются автоматически. Expected 400/401/404 в последних проверках — правильные результаты. + +Для демонстрации сохранности выполни запросы 01–17, затем: + +```sh +scripts/restart.sh +curl http://localhost:8082/health/ready +``` + +Повтори 09 и 15 с уже сохранёнными токенами, без новых логинов. Потом 22 и 23 показывают отзыв токена. Если ready ещё 503, повтори curl через секунду; restart hook запускает процессы, готовности тест ждёт отдельно. + +Полные автоматические проверки: + +```sh +make check +make test-student +make test-race +make test-persistence ACTION_SCRIPT=scripts/restart.sh +make experiment +``` + +`test-student` нужен локальный Go 1.24.4 и C compiler; он временно останавливает БД и кэш только этого стенда, проверяет TTL 2 и возвращает стандартный запуск. Альтернатива проверки Go через контейнер — `make test-race`; Python integration можно запустить отдельно: `python3 student-tests/integration.py --base-url http://localhost:8082`. + +`experiment` создаёт отдельные research-db и restore-db, новые БД внутри них и сохраняет результаты в evidence. Повторные прогоны оставляют предыдущие исследовательские БД; рабочие данные не трогают. + +Логи и остановка: + +```sh +docker compose logs --tail 30 api +make down +``` + +`down` сохраняет данные. Для **намеренного удаления всех учебных volumes этого проекта**, когда данные больше не нужны: + +```sh +docker compose --profile research down -v +``` + +Основной материал подготовки — `DEFENSE.md`. Отчёт и реальные доказательства — `REPORT.md` и `evidence/`. diff --git a/REPORT.md b/REPORT.md index e42f2b05..eb822e03 100644 --- a/REPORT.md +++ b/REPORT.md @@ -1,37 +1,191 @@ # Отчёт — лабораторная 2 -- Автор, группа: TODO -- Целевая оценка; выбранный трек 5, если нужен: TODO -- Commit/PR: TODO после публикации -- Использованные источники, библиотеки и помощь ИИ: TODO +- Автор: **Крайкин Глеб Алексеевич, БВТ2303**. +- Цель: **5**, трек 2 — план SQL-запроса и восстановление. +- Skeleton: `65003b61195361aac238f19c9bff0027ca58e09e`. +- Ветка: `solution/bvt2303-kraykin`. Текущий commit: `git rev-parse HEAD`. +- Дата проверок: 02.10.2026; времена в evidence — UTC. +- Исходное [задание](https://gitea.privcloud.tech/mtusi2026/mtusi2026lab2). README, COURSE, contracts и публичные tests сохранены. +- Перенесено собственное решение lab1: структуры ответов, строгий JSON decoder, Unicode-валидация, UUID, подписанные scoped cursors, HTTP lifecycle и non-root multi-stage Docker. Хранение в памяти и X-User-Id заменены PostgreSQL и Basic/Bearer. Linear/binary поиск из lab1 не переносился: здесь поиск выполняет БД по составному индексу. +- Использование ИИ: Codex помог с проектированием, реализацией, проверками, исследованием и материалами защиты. Исходный контракт/публичные тесты — преподавателя; старое приложение — собственное решение первой работы. Чужие студенческие решения не использованы. ## Запуск из чистого clone -TODO: версии runtime/образов, prerequisites, команды создания локальных secrets/.env, build, миграций, запуска, ожидания готовности, тестов и остановки. Указать необходимые действия оператора. Не вставлять секреты. Отдельно указать безопасную остановку и команду намеренного удаления учебных данных. +Нужны Docker Desktop/Linux daemon, Docker Compose v2 с поддержкой `--wait`, Python 3.9+ и make. Для локального `go test -race` нужны Go 1.24.4 и C-компилятор; контейнерная `make test-race` альтернатива не требует Go на хосте. -## Архитектура и решения +```sh +# В каталоге решения: +make up +curl http://localhost:8082/health/ready +make check +make test +make test-student +make test-race +make test-docker +make test-persistence ACTION_SCRIPT=scripts/restart.sh +make experiment +python3 student-tests/clean_clone.py +``` -TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab1, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации. +`make up` вызывает bootstrap (генерирует `.env`, локальные credentials и cursor key), затем build/up с ожиданием готовности. На первом старте пустой PostgreSQL-volume получает схему через версионированную embedded SQL-миграцию. Каждый следующий старт проверяет ledger/checksum и не повторяет создание таблиц/данных. Нет требования иметь заранее установленную БД. -## Доказательства критериев +Порт хоста по умолчанию **8082**, чтобы не конфликтовать с предыдущей лабораторной. Внутри API `APP_PORT=8080`; опубликовано только `127.0.0.1`. `APP_PORT` в .env регулирует host port Compose; при изменении задайте `make test BASE_URL=http://localhost:НОВЫЙ_ПОРТ` и то же значение остальным HTTP-проверкам/Postman. `SESSION_TTL_SECONDS` из .env передаётся API. Для проверки expiry integration временно передаёт 2 через окружение Compose, затем возвращает 3600. -| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства | -| --- | --- | --- | --- | -| Публичный smoke | make test | TODO | TODO | -| Остальные пункты уровня 3 | TODO | TODO | TODO | -| Все пункты уровня 4, если заявлен | TODO | TODO | TODO | -| Выбранный трек 5, если заявлен | TODO | TODO | TODO | +Dockerfile: Go **1.24.4-alpine3.22** build, Alpine **3.22.1** runtime; PostgreSQL **17.6-alpine**, Valkey **8.1.3-alpine**. Конкретные image IDs/digests находятся в `evidence/lifecycle.json`. `go.mod/go.sum` закрепляют pgx **5.7.6**, go-redis **9.12.1**, x/crypto **0.41.0** и транзитивные зависимости. Compiler/source отсутствуют в runtime; `USER 10001:10001`, PID 1 messenger, healthcheck и SIGTERM. -TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены. +Secrets: `secrets/postgres_password`, `database_url`, `cache_url`, `valkey_config`, `cursor_key`. Они генерируются локально, исключены из Git/build context, монтируются как отдельные Compose secrets. Host-directory имеет mode 0700, отдельные mount-файлы — 0444 для чтения container UID. Bootstrap не перезаписывает существующие credentials. API читает `DATABASE_URL_FILE`, `CACHE_URL_FILE`, `CURSOR_KEY_FILE`. Источник сессий фиксирован PostgreSQL; SESSION_STORE — описательная метка, runtime-переключения нет. API host/environment заданы Compose. -## Эксперименты и отказы +Остановка и повторный запуск с сохранением данных: -TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения. +```sh +make down +make up +``` -| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных | -| --- | --- | --- | --- | -| TODO | TODO | TODO | TODO | +**Намеренный сброс учебных данных**, только когда они больше не нужны: -## Ограничения и следующие шаги +```sh +docker compose --profile research down -v +``` -TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза. +Рабочие проверки никогда не выполняют эту команду. Clean-clone проверка удаляет только собственный disposable проект с уникальным именем. Research повторно создаёт новые БД, старые результаты/БД остаются; их дальнейшее обслуживание — действие оператора. + +## Архитектура, таблицы и транзакции + +```text +Postman / HTTP → API → PostgreSQL (users, chats, membership, messages, sessions) + → Valkey (immutable public User cache, TTL 300) +``` + +PostgreSQL — единственный источник истины для обязательных данных и действительности сессий. `postgres_data` — именованный volume. Valkey профили можно потерять: RDB/AOF отключены, после miss/рестарта профиль загрузится из БД. Его `valkey_data` volume не используется как гарантия persistence оперативной памяти. История сообщений кэшом не обслуживается, поэтому read-after-write идёт напрямую в primary PostgreSQL. Будущие API-реплики должны использовать ту же БД и общий persistent cursor key; в принятом стенде одна API-реплика. + +| Таблица | Ограничения / индексы | Назначение | +|---|---|---| +| users | UUID PK; UNIQUE username; CHECK длины/формата | Публичные поля + Argon2id hash | +| chats | UUID PK; title CHECK; `(created_at,id)` index | Чат и persistent last_message_at | +| chat_members | PK `(chat_id,user_id)`; оба FK; `(user_id,chat_id)` index | Членство и доступные чаты пользователя | +| messages | UUID PK; FK chat; составной FK `(chat_id,sender_id)` к membership; text CHECK | Подтверждённые сообщения | +| messages_history_idx | B-tree `(chat_id,created_at,id)` | Диапазон keyset и порядок страницы | +| sessions | PK token_hash 32 bytes; FK user; expiry index | Постоянные opaque сессии | +| schema_migrations | PK version; checksum; applied_at | Однократное применение версионированных миграций | + +Создание чата: BEGIN → INSERT chat → INSERT всех участников → COMMIT; неизвестный user даёт FK violation, весь чат откатывается. Проверки UUID/дублей/наличия вызывающего выполняются до BEGIN, существование участника подтверждается FK внутри транзакции. Гонка username решается UNIQUE, 23505 преобразуется в 409. + +Сообщение: BEGIN → UPDATE строки chat с `last_message_at=GREATEST(clock_timestamp(),last_message_at+1µs)` → INSERT → COMMIT → 201. UPDATE сериализует писателей только одного чата и делает порядок времени устойчивым к откату часов, в том числе между API-процессами. Часы не уникальный ID: используется random UUID. FK дополнительно подтверждает, что sender — участник чата. Горячий чат ограничен одной row-lock очередью писателей. + +SQL значения поступают как параметры `$1…`, динамическая часть строк состоит только из серверного выбора формы запроса/номера placeholder. Pool ограничен **10** соединениями; connect timeout **2 s**, server statement timeout **2 s**, lock timeout **1 s**, HTTP request context **3 s**. Redis budgets **80 ms** на вызов, socket/pool **60 ms**, retry отключён. Это ограничивает ожидание зависимости; KDF не имеет прерывания посередине вычисления, но одновременно допускаются максимум две работы. + +Миграции embedded в binary, выполняются в одной транзакции с ledger и advisory xact lock. Изменённая уже применённая migration не принимается. Startup требует готовую БД; restart hook сначала останавливает API, перезапускает PostgreSQL/Valkey, ждёт ready БД и стартует API. Публичный тест ждёт HTTP readiness отдельно. + +## Аутентификация, cache и pagination + +Регистрация хранит Argon2id: 64 MiB, 3 passes, 2 lanes, случайная соль 16 bytes и результат 32 bytes. Учитывается полный UTF-8 диапазон 12–128 code points без bcrypt truncation; проверены длинные emoji и двоеточие. Basic используется только для создания сессии, body пустой, неверные credentials дают одинаковый 401 и challenge. Неизвестный username проходит dummy KDF, без заявления абсолютной timing-security. + +Opaque token: 32 random bytes, 256 bits, base64url. В sessions хранятся SHA-256 строки токена, user_id и абсолютный expires_at от часов БД. Bearer проверяется через sessions на каждом запросе; expired/revoked/unknown → 401 с Bearer challenge. X-User-Id игнорируется. Logout DELETE подтверждается до 204; кэш профиля не способен отменить отзыв. Входная сессия не JWT. + +Valkey ключ `profile:v1:`, public User JSON, TTL 300 s. Cache-aside: GET hit экономит SELECT users; miss/error читает PostgreSQL и пытается SET с отдельным ограниченным budget. Авторизация сессии всё равно требует SQL. Профиль неизменяемый в обязательном API, поэтому явной инвалидации нет. Будущий update/delete потребует новой политики. Кэш не критичен для ready; PostgreSQL критичен. Live проверяет процесс, ready — остановку и Ping БД. + +Keyset: signed scope + `(created_at,id)`, HMAC-SHA256 со стабильным локальным секретом. Курсор чужого чата/пользователя и повреждённая подпись дают 400. SQL использует `chat_id=$1 AND (created_at,id)>($2,$3) ORDER BY messages.created_at,messages.id LIMIT limit+1`; native UUID указан явно, чтобы текстовый SELECT alias не менял план сортировки. Возвращаются limit элементов, дополнительный определяет next_cursor; последняя запись не повторяется. Snapshot между страницами не обещается. Монотонность времени гарантирована для сообщений одного чата; для нового чата при откате часов возможно появление до уже выданной границы. + +Строгий decoder и business Unicode limits сохранены. При неизвестном или чужом чате одинаковый 404. Каждому ответу соответствует X-Request-Id, у ошибки совпадающий request_id. Structured stdout-логи содержат шаблон route/метод/status/duration/request_id без body, query, паролей и токенов. + +## Доказательства всех критериев + +| Критерий | Команда / наблюдение | Реальное доказательство | +|---|---|---| +| Skeleton/контракт сохранён | make check; git diff исходного SHA по README/COURSE/contracts/tests пуст | evidence/check.txt; Git diff | +| Минимум lab1 с новым auth | make test, Unicode, membership, страницы, ошибки | evidence/public-smoke.txt | +| SQL schema, PK/FK/UNIQUE | Первая migration; работа на новом volume | migration; clean-clone.txt | +| Атомарное создание чата | Неизвестный второй участник после INSERT чата → 400, в БД нет частичного чата | integration.json, student-tests.txt | +| Гонка username | 4 concurrent регистрации: 1×201 + 3×409 | integration.json | +| Argon2id и широкий пароль | Проверка формата KDF в рабочей БД, HTTP emoji/colon, Go negative verification | student-tests.txt; race-http.txt | +| Basic только для входа | Basic на бизнес-пути 401; неверный password 401 | public smoke; integration | +| Bearer, expiry, logout | TTL=2 → 401, DELETE→204→401 при warm profile cache | integration.json | +| X-User-Id не даёт доступа | Один заголовок→401; вместе с Bearer не меняет владельца | public smoke | +| Все данные и сессия переживают рестарт | make test-persistence ACTION_SCRIPT=scripts/restart.sh; same token/message; StartedAt изменился у api/postgres/valkey | integration.json; student-tests.txt | +| Повторная migration без дублей | schema_migrations count=1 после рестартов | integration.json | +| 100 сообщений / 10 клиентов | Проверка counts/IDs/text/order и cursor scope | student-tests.txt | +| Race detector на реальном HTTP/PG | make test-race → 100 уникальных подтверждённых сообщений | race-http.txt | +| Реальное использование Valkey | Key TTL 1..300, FLUSHDB → восстановление профиля с прежней сессией | integration.json | +| Недоступность Valkey | Запросы и POST→GET продолжаются, аноним не получает доступ | integration.json | +| Недоступность PostgreSQL | Live 200, ready 503, protected 503 в ограниченный срок | integration.json | +| Параметры, pool, timeouts | $1…; 10 connections; 2/1/3 s budgets | исходный код | +| Индекс на ≥10k сообщений | 100k total, 80k chat; Index Scan range, 51 строка, без Sort | explain-history.txt; experiment.json | +| Docker/non-root/SIGTERM/secret-free logs | PID1 messenger, UID10001, exit0, old session restored | lifecycle.json | +| Трек 2: три индекса и запись | 3×4 chat sizes×2 positions×2 client levels×3 repetitions | experiment.json, experiment-summary.md | +| Трек 2: новое хранилище restore | 100k сообщений, counts/fingerprint/5 samples совпали | experiment.json backup_restore | +| Сборка из чистого clone | Новые secrets/volumes, uncached build, smoke/persistence/lifecycle | clean-clone.txt | + +`go vet ./...` завершился с кодом 0, stdout пуст. `make check` проверяет skeleton, а не приложение. Go-тест с настоящей БД локально skip без DATABASE_TEST_URL_FILE; make test-race включает его в Compose. PASS не является автоматическим выставлением оценки. + +## Исследование индексов + +**Гипотеза:** индекс только chat_id не позволяет быстро перейти за cursor и выдать упорядоченную страницу; составной ключ включает обе задачи. INCLUDE полей может убрать heap fetch, но увеличит storage/write amplification. Поэтому сравниваются чтение, размер, batch запись и WAL, а не только TPS. + +**Метод:** отдельный research-db, каждый запуск создаёт новую database. 100 000 synthetic сообщений, чаты **80 000 / 15 000 / 4900 / 100**, fixed 128-symbol filler; seed выполняется SQL, без заявления скорости HTTP seed. PostgreSQL **2 CPU, 512 MiB**, Docker Desktop Linux/arm64 на macOS arm64. Конкретный host и version/durability сохранены. Индексы рабочего API не меняются. + +Для каждого варианта: VACUUM ANALYZE после seed, ANALYZE после смены индекса; первая страница и граница около 90%, limit 51; 1/4 pgbench клиентов, prepared запрос, прогрев 20 transactions/client, **100 transactions/client, 3 повтора**. Всего 144 read-прогона + планы. Измеряется средняя transaction latency/TPS каждого прогона; таблица показывает медианы повторов. Это SQL, без auth/cache/HTTP/JSON. EXPLAIN (ANALYZE, BUFFERS, WAL) выполняет настоящий тот же SELECT. + +Запись: одинаковая write_probe (PK + один выбранный secondary index), batch 1000 INSERT + COMMIT, 3 повтора и EXPLAIN/WAL. Между повторами TRUNCATE только write_probe; рабочие/fixture сообщения не удаляются. Это цена batch-транзакции на пустой таблице, а не sustained single-message API writes и не строгая статистическая оценка отличий в несколько миллисекунд. + +Поздняя страница чата 80 000, один SQL-клиент: + +| Индекс | latency ms | TPS | Размер KiB | INSERT1000+COMMIT ms | INSERT WAL bytes | +|---|---:|---:|---:|---:|---:| +| chat_only | 11.053 | 90.5 | 704 | 8.679 | 418474 | +| composite | 0.090 | 11144.5 | 5776 | 5.915 | 448576 | +| covering | 0.096 | 10378.8 | 24416 | 7.541 | 639392 | + +**Вывод:** production использует composite. Большая поздняя страница получает сильное улучшение относительно chat_only. Covering в этом прогоне не дал выигрыша latency, при этом занимает примерно 4,2× места composite и генерирует больше WAL в batch-пробе. Одна установка индекса не гарантирует universal speedup всех запросов. + +Cgroup наблюдения исследовательского PostgreSQL за окно всего варианта (включает setup; не API RSS и не пик памяти): + +| Индекс | CPU % (100%=1 core) | Memory до MiB | Memory после MiB | Окно s | +|---|---:|---:|---:|---:| +| chat_only | 129.4 | 344.1 | 330.6 | 54.5 | +| composite | 16.8 | 329.9 | 335.5 | 18.2 | +| covering | 17.1 | 335.6 | 374.0 | 19.6 | + +Memory включает shared buffers и page cache. Значения на границах окна не доказывают max RSS. Порядок вариантов фиксирован; данные warm, нагрузка closed-loop, прогоны короткие; влияние фоновой нагрузки и SQL-клиента не исключено. + +Отдельная контрольная нагрузка настоящего HTTP API: три прогона POST по 5 s, 4 clients, no retry. Медиана успешных RPS **1456.6**, медианы per-run p50/p95/p99 **2.524 / 4.128 / 6.279 ms**, ошибок **0**. Raw: http-load-1/2/3.json. Это growing history, coordinated omission и percentiles только успешных ответов; не максимальная capacity и не сравнение SQL-индексов через HTTP. + +## Восстановление и отказы + +`pg_dump -Fc --no-owner --no-acl` → `pg_restore --single-transaction --exit-on-error` в **новую пустую БД на отдельном restore-db/restore_data volume**. Сверены counts users/chats/members/messages, MD5 fingerprint всех message fields в детерминированном порядке и 5 выбранных полных записей. MD5 тут только checksum синтетической fixture, не password scheme. После restore выполнен ANALYZE. + +Backup **0.317 s**, pg_restore **0.5 s**, dump **3021508 bytes**. Восстановлены **100 000** сообщений; counts, fingerprint и samples совпали. В source после backup успешно добавлен marker: source 100001, restore 100000, marker отсутствует. Без WAL archive/PITR данные после snapshot могут потеряться; эксперимент не обещает максимум одну потерянную запись. Измерен restore-only RTO, без detection/provisioning/переадресации API. + +Исследовательский SQL fixture использует synthetic-no-login password_hash и не является зарегистрированным API-пользователем. Сохранность настоящих Argon2id пользователей и сессий доказывается отдельным публичным persistence-сценарием. Dump не коммитится, tokens отсутствуют в evidence. + +| Воздействие | Наблюдение | Граница | +|---|---|---| +| API restart | Same token, profile, message | Данные в PostgreSQL, key курсора persistent | +| Full API+PG+Valkey restart | Прежний token работает, данные/курсоры доступны; все StartedAt изменились | Volumes не удаляются | +| Valkey flush/down | Fallback users SELECT, запись сразу видна | Возможны дополнительные SQL и задержка cache budget | +| PG down | Live200, ready503, protected503 | Аноним не становится доверенным; нет HA primary | +| TTL2 | После ~2 s token401, старый long TTL token работает | Срок от БД, не от локального cache TTL | +| Logout | DELETE204, повтор401 при заполненном cache | In-flight запрос до logout может завершиться | +| SIGTERM | 0.208 s, exit0, OOM=false | Shutdown budget5 s, Compose grace7 s | +| Backup cutoff | Полное совпадение snapshot, позже добавленного marker нет | Без WAL archive отсутствует PITR | + +Durability проверена: **fsync=on, synchronous_commit=on, full_page_writes=on**. Эти локальные гарантии не защищают от потери всего host/disk; volume не backup. + +## Ограничения и развитие + +Локальный учебный HTTP, только синтетические credentials; для удалённой демонстрации нужен TLS. Один PostgreSQL primary, один API, нет HA/failover хранилища или PITR. Учебный POSTGRES_USER имеет роль bootstrap-superuser; для production нужно разделить migration owner и минимальную runtime-role. Не реализованы delete/update, periodic session cleanup, rate limiting login, idempotent POST lab3, password parameter migration, circuit breaker/singleflight и внешнее резервное хранение. + +Исчезновение Valkey допускается только потому, что это cache профилей, а не authoritative sessions. Hot-chat row lock ограничивает write concurrency. Request deadlines ограничивают I/O, KDF уже начавшейся работы не прерывается. Курсор HMAC-подписан, но не encrypted. Snapshot между страницами не обещается. Research про SQL и batch INSERT; контрольный HTTP load не даёт универсальной оценки throughput. + +Материалы защиты: `DEFENSE.md` (разбор кода, примеры, 26 вопросов и 12 заданий самопроверки), `QUICKSTART.md`, `postman/lab2.postman_collection.json`. + +## Первичные источники + +- [PostgreSQL multi-column indexes](https://www.postgresql.org/docs/17/indexes-multicolumn.html) +- [PostgreSQL EXPLAIN](https://www.postgresql.org/docs/17/using-explain.html) +- [PostgreSQL SQL dump](https://www.postgresql.org/docs/17/backup-dump.html) +- [PostgreSQL WAL reliability](https://www.postgresql.org/docs/17/wal-reliability.html) +- [Argon2 Go implementation](https://pkg.go.dev/golang.org/x/crypto/argon2) +- [pgx pool](https://pkg.go.dev/github.com/jackc/pgx/v5/pgxpool) +- [Valkey persistence](https://valkey.io/topics/persistence/) +- [RFC 7617 Basic](https://www.rfc-editor.org/rfc/rfc7617) diff --git a/cmd/server/main.go b/cmd/server/main.go new file mode 100644 index 00000000..bcaa74b7 --- /dev/null +++ b/cmd/server/main.go @@ -0,0 +1,139 @@ +package main + +import ( + "context" + "encoding/base64" + "errors" + "fmt" + "github.com/redis/go-redis/v9" + "log/slog" + "mtusi/messenger/internal/database" + "mtusi/messenger/internal/messenger" + "net" + "net/http" + "os" + "os/signal" + "strconv" + "strings" + "syscall" + "time" +) + +func env(key, fallback string) string { + if v := os.Getenv(key); v != "" { + return v + } + return fallback +} +func main() { + if err := run(); err != nil { + slog.Error("server failed", "error", err) + os.Exit(1) + } +} +func run() error { + host := env("APP_HOST", "0.0.0.0") + port := env("APP_PORT", "8080") + p, err := strconv.Atoi(port) + if err != nil || p < 1 || p > 65535 { + return fmt.Errorf("invalid APP_PORT") + } + if len(os.Args) == 2 && os.Args[1] == "healthcheck" { + c := http.Client{Timeout: time.Second} + r, e := c.Get("http://127.0.0.1:" + port + "/health/ready") + if e != nil { + return e + } + defer r.Body.Close() + if r.StatusCode != 200 { + return fmt.Errorf("not ready: %d", r.StatusCode) + } + return nil + } + + log := slog.New(slog.NewJSONHandler(os.Stdout, nil)) + ttl, err := strconv.Atoi(env("SESSION_TTL_SECONDS", "3600")) + if err != nil || ttl < 1 || ttl > 86400 { + return fmt.Errorf("SESSION_TTL_SECONDS must be 1..86400") + } + databaseURL, err := secret("DATABASE_URL_FILE") + if err != nil { + return err + } + cacheURL, err := secret("CACHE_URL_FILE") + if err != nil { + return err + } + cursorKey, err := secret("CURSOR_KEY_FILE") + if err != nil { + return err + } + key, err := base64.RawURLEncoding.DecodeString(cursorKey) + if err != nil || len(key) != 32 { + return fmt.Errorf("invalid cursor key") + } + startup, cancel := context.WithTimeout(context.Background(), 15*time.Second) + defer cancel() + pool, err := database.Open(startup, databaseURL) + if err != nil { + return err + } + defer pool.Close() + if err = database.Migrate(startup, pool); err != nil { + return fmt.Errorf("migration failed") + } + opts, err := redis.ParseURL(cacheURL) + if err != nil { + return fmt.Errorf("invalid cache configuration") + } + opts.DialTimeout = 60 * time.Millisecond + opts.ReadTimeout = 60 * time.Millisecond + opts.WriteTimeout = 60 * time.Millisecond + opts.PoolTimeout = 60 * time.Millisecond + opts.ContextTimeoutEnabled = true + opts.MaxRetries = -1 + opts.PoolSize = 10 + cache := redis.NewClient(opts) + defer cache.Close() + api := messenger.New(pool, cache, key, ttl, log) + srv := &http.Server{Addr: net.JoinHostPort(host, port), Handler: api, ReadHeaderTimeout: 3 * time.Second, ReadTimeout: 5 * time.Second, WriteTimeout: 10 * time.Second, IdleTimeout: 30 * time.Second, MaxHeaderBytes: 16 << 10} + ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM) + defer stop() + done := make(chan error, 1) + go func() { + log.Info("listening", "address", srv.Addr, "session_store", "postgres", "profile_cache", "valkey", "environment", env("APP_ENV", "lab")) + done <- srv.ListenAndServe() + }() + select { + case err := <-done: + return err + case <-ctx.Done(): + } + start := time.Now() + api.Stop() + log.Info("shutdown started") + shutdown, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + if err := srv.Shutdown(shutdown); err != nil { + _ = srv.Close() + return err + } + err = <-done + if !errors.Is(err, http.ErrServerClosed) { + return err + } + log.Info("shutdown completed", "duration_ms", time.Since(start).Milliseconds()) + return nil +} + +func secret(name string) (string, error) { + path := os.Getenv(name) + if path == "" { + return "", fmt.Errorf("missing %s", name) + } + raw, err := os.ReadFile(path) + if err != nil { + return "", fmt.Errorf("cannot read %s", name) + } + return strings.TrimSpace(string(raw)), nil +} diff --git a/compose.yaml b/compose.yaml new file mode 100644 index 00000000..93e4e616 --- /dev/null +++ b/compose.yaml @@ -0,0 +1,86 @@ +name: mtusi-lab2-kraykin +x-postgres: &postgres + image: postgres:17.6-alpine + environment: + POSTGRES_DB: messenger + POSTGRES_USER: messenger + POSTGRES_PASSWORD_FILE: /run/secrets/postgres_password + secrets: [postgres_password] + healthcheck: + test: [CMD-SHELL, 'pg_isready -U messenger -d messenger'] + interval: 2s + timeout: 2s + retries: 20 + cpus: 2 + mem_limit: 512m + shm_size: 128m + stop_grace_period: 10s +services: + postgres: + <<: *postgres + volumes: [postgres_data:/var/lib/postgresql/data] + valkey: + image: valkey/valkey:8.1.3-alpine + command: [valkey-server, /run/secrets/valkey_config] + secrets: [valkey_config] + volumes: [valkey_data:/data] + cpus: 1 + mem_limit: 128m + stop_grace_period: 5s + api: + image: mtusi-messenger:lab2 + build: . + environment: + APP_HOST: 0.0.0.0 + APP_PORT: 8080 + APP_ENV: lab + SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600} + SESSION_STORE: postgres + DATABASE_URL_FILE: /run/secrets/database_url + CACHE_URL_FILE: /run/secrets/cache_url + CURSOR_KEY_FILE: /run/secrets/cursor_key + secrets: [database_url, cache_url, cursor_key] + ports: ['127.0.0.1:${APP_PORT:-8080}:8080'] + depends_on: + postgres: + condition: service_healthy + valkey: + condition: service_started + cpus: 2 + mem_limit: 512m + stop_grace_period: 7s + tests: + profiles: [verify] + build: + context: . + target: tests + environment: + DATABASE_TEST_URL_FILE: /run/secrets/database_url + secrets: [database_url] + depends_on: + postgres: + condition: service_healthy + research-db: + <<: *postgres + profiles: [research] + volumes: [research_data:/var/lib/postgresql/data] + restore-db: + <<: *postgres + profiles: [research] + volumes: [restore_data:/var/lib/postgresql/data] +secrets: + postgres_password: + file: ./secrets/postgres_password + database_url: + file: ./secrets/database_url + cache_url: + file: ./secrets/cache_url + valkey_config: + file: ./secrets/valkey_config + cursor_key: + file: ./secrets/cursor_key +volumes: + postgres_data: + valkey_data: + research_data: + restore_data: diff --git a/evidence/build.txt b/evidence/build.txt new file mode 100644 index 00000000..7c157622 --- /dev/null +++ b/evidence/build.txt @@ -0,0 +1,69 @@ +Compose can now delegate builds to bake for better performance. + To do so, set COMPOSE_BAKE=true. +#0 building with "desktop-linux" instance using docker driver + +#1 [api internal] load build definition from Dockerfile +#1 transferring dockerfile: 782B done +#1 DONE 0.0s + +#2 [api internal] load metadata for docker.io/library/golang:1.24.4-alpine3.22 +#2 DONE 1.4s + +#3 [api internal] load metadata for docker.io/library/alpine:3.22.1 +#3 DONE 1.4s + +#4 [api internal] load .dockerignore +#4 transferring context: 196B done +#4 DONE 0.0s + +#5 [api stage-2 1/3] FROM docker.io/library/alpine:3.22.1@sha256:4bcff63911fcb4448bd4fdacec207030997caf25e9bea4045fa6c8c44de311d1 +#5 resolve docker.io/library/alpine:3.22.1@sha256:4bcff63911fcb4448bd4fdacec207030997caf25e9bea4045fa6c8c44de311d1 done +#5 DONE 0.0s + +#6 [api build 1/7] FROM docker.io/library/golang:1.24.4-alpine3.22@sha256:68932fa6d4d4059845c8f40ad7e654e626f3ebd3706eef7846f319293ab5cb7a +#6 resolve docker.io/library/golang:1.24.4-alpine3.22@sha256:68932fa6d4d4059845c8f40ad7e654e626f3ebd3706eef7846f319293ab5cb7a done +#6 DONE 0.0s + +#7 [api internal] load build context +#7 transferring context: 22.43kB done +#7 DONE 0.0s + +#8 [api build 2/7] WORKDIR /src +#8 CACHED + +#9 [api build 3/7] COPY go.mod go.sum ./ +#9 CACHED + +#10 [api build 4/7] RUN go mod download +#10 CACHED + +#11 [api build 5/7] COPY cmd/ ./cmd/ +#11 CACHED + +#12 [api build 6/7] COPY internal/ ./internal/ +#12 DONE 0.0s + +#13 [api build 7/7] RUN CGO_ENABLED=0 go build -trimpath -ldflags="-s -w" -o /out/messenger ./cmd/server +#13 DONE 5.8s + +#14 [api stage-2 2/3] RUN addgroup -g 10001 app && adduser -D -u 10001 -G app app +#14 CACHED + +#15 [api stage-2 3/3] COPY --from=build /out/messenger /usr/local/bin/messenger +#15 DONE 0.0s + +#16 [api] exporting to image +#16 exporting layers +#16 exporting layers 0.2s done +#16 exporting manifest sha256:96202f5138f44a4a66b406c8fb3102b90d9c6e7005de409f6e2110413f98e8c7 +#16 exporting manifest sha256:96202f5138f44a4a66b406c8fb3102b90d9c6e7005de409f6e2110413f98e8c7 done +#16 exporting config sha256:2b0630b51e8e0691161aaeb84c15b6c5145b1353880c4fb682c0622e9bdaa2c3 done +#16 exporting attestation manifest sha256:b38b86e8e795fcb8db5ec321051e7f9e83ddf405f80d0ccb63f7ed8574334320 done +#16 exporting manifest list sha256:d95606280c8307e47500e4dacd5ab5f9a495e85841260c4c78380ebf565573f1 done +#16 naming to docker.io/library/mtusi-messenger:lab2 done +#16 unpacking to docker.io/library/mtusi-messenger:lab2 0.0s done +#16 DONE 0.3s + +#17 [api] resolving provenance for metadata file +#17 DONE 0.0s + api Built diff --git a/evidence/check.txt b/evidence/check.txt new file mode 100644 index 00000000..9a553306 --- /dev/null +++ b/evidence/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/clean-clone.txt b/evidence/clean-clone.txt new file mode 100644 index 00000000..c1f36414 --- /dev/null +++ b/evidence/clean-clone.txt @@ -0,0 +1,153 @@ +Checked source commit: d97571634f01c53db7a247beea837ab0baa7ab60 + +Isolated Compose project: mtusi-lab2-clean-eafa1442c7 + +$ make bootstrap check +python3 scripts/bootstrap.py +Local secrets ready (values hidden); .env and secrets/ are ignored by Git. +python3 scripts/check_contract.py +PASS: offline skeleton structure, local refs and Python syntax; application NOT tested. + + +$ docker compose --env-file .env build --no-cache api +Compose can now delegate builds to bake for better performance. + To do so, set COMPOSE_BAKE=true. +#0 building with "desktop-linux" instance using docker driver + +#1 [api internal] load build definition from Dockerfile +#1 transferring dockerfile: 782B done +#1 DONE 0.0s + +#2 [api internal] load metadata for docker.io/library/golang:1.24.4-alpine3.22 +#2 DONE 1.2s + +#3 [api internal] load metadata for docker.io/library/alpine:3.22.1 +#3 DONE 1.3s + +#4 [api internal] load .dockerignore +#4 transferring context: 196B done +#4 DONE 0.0s + +#5 [api build 1/7] FROM docker.io/library/golang:1.24.4-alpine3.22@sha256:68932fa6d4d4059845c8f40ad7e654e626f3ebd3706eef7846f319293ab5cb7a +#5 resolve docker.io/library/golang:1.24.4-alpine3.22@sha256:68932fa6d4d4059845c8f40ad7e654e626f3ebd3706eef7846f319293ab5cb7a done +#5 DONE 0.0s + +#6 [api build 2/7] WORKDIR /src +#6 CACHED + +#7 [api stage-2 1/3] FROM docker.io/library/alpine:3.22.1@sha256:4bcff63911fcb4448bd4fdacec207030997caf25e9bea4045fa6c8c44de311d1 +#7 resolve docker.io/library/alpine:3.22.1@sha256:4bcff63911fcb4448bd4fdacec207030997caf25e9bea4045fa6c8c44de311d1 done +#7 CACHED + +#8 [api internal] load build context +#8 transferring context: 36.73kB done +#8 DONE 0.0s + +#9 [api build 3/7] COPY go.mod go.sum ./ +#9 DONE 0.0s + +#10 [api stage-2 2/3] RUN addgroup -g 10001 app && adduser -D -u 10001 -G app app +#10 DONE 0.2s + +#11 [api build 4/7] RUN go mod download +#11 DONE 4.9s + +#12 [api build 5/7] COPY cmd/ ./cmd/ +#12 DONE 0.0s + +#13 [api build 6/7] COPY internal/ ./internal/ +#13 DONE 0.0s + +#14 [api build 7/7] RUN CGO_ENABLED=0 go build -trimpath -ldflags="-s -w" -o /out/messenger ./cmd/server +#14 DONE 5.5s + +#15 [api stage-2 3/3] COPY --from=build /out/messenger /usr/local/bin/messenger +#15 DONE 0.0s + +#16 [api] exporting to image +#16 exporting layers +#16 exporting layers 0.2s done +#16 exporting manifest sha256:46704b7bea0f7970e05c1a0c247c1d7c96bcd3dc660a1606dba3e7392569c41e done +#16 exporting config sha256:8587b3a10738f6330888de254d20bbdfa39462e209d8e4e648753a61d8f3bea7 done +#16 exporting attestation manifest sha256:35924096a36ad76c3d37c696ba464685032b8323da6dafd34b59f5bb6e6b821d done +#16 exporting manifest list sha256:7b6d6caf62f97901015cffb0aaebdf29c05cc1bbfa2c3bb6e6a664926246c7b8 done +#16 naming to docker.io/library/mtusi-messenger:lab2 done +#16 unpacking to docker.io/library/mtusi-messenger:lab2 0.0s done +#16 DONE 0.3s + +#17 [api] resolving provenance for metadata file +#17 DONE 0.0s + api Built + + +$ docker compose --env-file .env up -d --wait api postgres valkey + Network mtusi-lab2-clean-eafa1442c7_default Creating + Network mtusi-lab2-clean-eafa1442c7_default Created + Volume "mtusi-lab2-clean-eafa1442c7_postgres_data" Creating + Volume "mtusi-lab2-clean-eafa1442c7_postgres_data" Created + Volume "mtusi-lab2-clean-eafa1442c7_valkey_data" Creating + Volume "mtusi-lab2-clean-eafa1442c7_valkey_data" Created + Container mtusi-lab2-clean-eafa1442c7-postgres-1 Creating + Container mtusi-lab2-clean-eafa1442c7-valkey-1 Creating + Container mtusi-lab2-clean-eafa1442c7-valkey-1 Created + Container mtusi-lab2-clean-eafa1442c7-postgres-1 Created + Container mtusi-lab2-clean-eafa1442c7-api-1 Creating + Container mtusi-lab2-clean-eafa1442c7-api-1 Created + Container mtusi-lab2-clean-eafa1442c7-valkey-1 Starting + Container mtusi-lab2-clean-eafa1442c7-postgres-1 Starting + Container mtusi-lab2-clean-eafa1442c7-valkey-1 Started + Container mtusi-lab2-clean-eafa1442c7-postgres-1 Started + Container mtusi-lab2-clean-eafa1442c7-postgres-1 Waiting + Container mtusi-lab2-clean-eafa1442c7-postgres-1 Healthy + Container mtusi-lab2-clean-eafa1442c7-api-1 Starting + Container mtusi-lab2-clean-eafa1442c7-api-1 Started + Container mtusi-lab2-clean-eafa1442c7-postgres-1 Waiting + Container mtusi-lab2-clean-eafa1442c7-valkey-1 Waiting + Container mtusi-lab2-clean-eafa1442c7-api-1 Waiting + Container mtusi-lab2-clean-eafa1442c7-valkey-1 Healthy + Container mtusi-lab2-clean-eafa1442c7-postgres-1 Healthy + Container mtusi-lab2-clean-eafa1442c7-api-1 Healthy + + +$ docker compose port api 8080 +127.0.0.1:51634 + + +$ make test BASE_URL=http://127.0.0.1:51634 +python3 tests/smoke.py --base-url "http://127.0.0.1:51634" +PASS: lab2 public API scenario; infrastructure and grading evidence remain separate. + + +$ make test-persistence ACTION_SCRIPT=scripts/restart.sh BASE_URL=http://127.0.0.1:51634 +python3 tests/resilience.py --mode persistence --action-script "scripts/restart.sh" --base-url "http://127.0.0.1:51634" +Executing explicit persistence hook; hook output suppressed to avoid leaking secrets. +PASS: persistence preserved confirmed data and existing session. Hook scope needs operator evidence. + + +$ make test-docker BASE_URL=http://127.0.0.1:51634 +python3 student-tests/lifecycle.py --base-url "http://127.0.0.1:51634" +PASS: non-root, SIGTERM, same-session recovery, log privacy + + +PASS: committed clean clone, uncached image, fresh volumes, smoke, full restart, lifecycle + +$ docker compose --env-file .env down --volumes + Container mtusi-lab2-clean-eafa1442c7-api-1 Stopping + Container mtusi-lab2-clean-eafa1442c7-api-1 Stopped + Container mtusi-lab2-clean-eafa1442c7-api-1 Removing + Container mtusi-lab2-clean-eafa1442c7-api-1 Removed + Container mtusi-lab2-clean-eafa1442c7-valkey-1 Stopping + Container mtusi-lab2-clean-eafa1442c7-postgres-1 Stopping + Container mtusi-lab2-clean-eafa1442c7-postgres-1 Stopped + Container mtusi-lab2-clean-eafa1442c7-postgres-1 Removing + Container mtusi-lab2-clean-eafa1442c7-postgres-1 Removed + Container mtusi-lab2-clean-eafa1442c7-valkey-1 Stopped + Container mtusi-lab2-clean-eafa1442c7-valkey-1 Removing + Container mtusi-lab2-clean-eafa1442c7-valkey-1 Removed + Volume mtusi-lab2-clean-eafa1442c7_valkey_data Removing + Volume mtusi-lab2-clean-eafa1442c7_postgres_data Removing + Network mtusi-lab2-clean-eafa1442c7_default Removing + Volume mtusi-lab2-clean-eafa1442c7_valkey_data Removed + Volume mtusi-lab2-clean-eafa1442c7_postgres_data Removed + Network mtusi-lab2-clean-eafa1442c7_default Removed + diff --git a/evidence/experiment-run.txt b/evidence/experiment-run.txt new file mode 100644 index 00000000..c9b8f7c1 --- /dev/null +++ b/evidence/experiment-run.txt @@ -0,0 +1,5 @@ +python3 student-tests/experiment.py +Measuring chat_only +Measuring composite +Measuring covering +PASS: SQL comparison and restore of 100000 messages diff --git a/evidence/experiment-summary.md b/evidence/experiment-summary.md new file mode 100644 index 00000000..1c82dbf9 --- /dev/null +++ b/evidence/experiment-summary.md @@ -0,0 +1,62 @@ +# SQL-эксперимент: результаты + +100 000 сообщений, чаты 80 000 / 15 000 / 4900 / 100. Медианы 3 повторов; warm SQL, без HTTP. + +| Индекс | Чат | Страница | Клиенты | latency, ms | TPS | EXPLAIN, ms | Ошибки | +|---|---:|---|---:|---:|---:|---:|---:| +| chat_only | 80000 | first | 1 | 11.530 | 86.7 | 13.284 | 0 | +| chat_only | 80000 | first | 4 | 50.676 | 78.9 | 13.284 | 0 | +| chat_only | 80000 | deep | 1 | 11.053 | 90.5 | 12.858 | 0 | +| chat_only | 80000 | deep | 4 | 23.470 | 170.4 | 12.858 | 0 | +| chat_only | 15000 | first | 1 | 3.003 | 333.0 | 4.196 | 0 | +| chat_only | 15000 | first | 4 | 6.240 | 641.0 | 4.196 | 0 | +| chat_only | 15000 | deep | 1 | 1.300 | 769.0 | 2.495 | 0 | +| chat_only | 15000 | deep | 4 | 1.874 | 2134.1 | 2.495 | 0 | +| chat_only | 4900 | first | 1 | 1.066 | 937.9 | 1.417 | 0 | +| chat_only | 4900 | first | 4 | 1.904 | 2100.7 | 1.417 | 0 | +| chat_only | 4900 | deep | 1 | 0.467 | 2140.9 | 0.816 | 0 | +| chat_only | 4900 | deep | 4 | 0.683 | 5860.5 | 0.816 | 0 | +| chat_only | 100 | first | 1 | 0.120 | 8316.7 | 0.130 | 0 | +| chat_only | 100 | first | 4 | 0.181 | 22044.6 | 0.130 | 0 | +| chat_only | 100 | deep | 1 | 0.092 | 10840.1 | 0.084 | 0 | +| chat_only | 100 | deep | 4 | 0.115 | 34858.4 | 0.084 | 0 | +| composite | 80000 | first | 1 | 0.089 | 11188.2 | 0.054 | 0 | +| composite | 80000 | first | 4 | 0.151 | 26470.8 | 0.054 | 0 | +| composite | 80000 | deep | 1 | 0.090 | 11144.5 | 0.060 | 0 | +| composite | 80000 | deep | 4 | 0.158 | 25392.0 | 0.060 | 0 | +| composite | 15000 | first | 1 | 0.090 | 11157.0 | 0.064 | 0 | +| composite | 15000 | first | 4 | 0.158 | 25258.9 | 0.064 | 0 | +| composite | 15000 | deep | 1 | 0.095 | 10549.6 | 0.070 | 0 | +| composite | 15000 | deep | 4 | 0.164 | 24385.8 | 0.070 | 0 | +| composite | 4900 | first | 1 | 0.090 | 11108.6 | 0.079 | 0 | +| composite | 4900 | first | 4 | 0.163 | 24582.1 | 0.079 | 0 | +| composite | 4900 | deep | 1 | 0.092 | 10917.0 | 0.069 | 0 | +| composite | 4900 | deep | 4 | 0.165 | 24188.2 | 0.069 | 0 | +| composite | 100 | first | 1 | 0.091 | 11027.8 | 0.062 | 0 | +| composite | 100 | first | 4 | 0.155 | 25876.6 | 0.062 | 0 | +| composite | 100 | deep | 1 | 0.081 | 12315.3 | 0.051 | 0 | +| composite | 100 | deep | 4 | 0.104 | 38465.2 | 0.051 | 0 | +| covering | 80000 | first | 1 | 0.094 | 10614.6 | 0.077 | 0 | +| covering | 80000 | first | 4 | 0.163 | 24470.8 | 0.077 | 0 | +| covering | 80000 | deep | 1 | 0.096 | 10378.8 | 0.073 | 0 | +| covering | 80000 | deep | 4 | 0.165 | 24227.7 | 0.073 | 0 | +| covering | 15000 | first | 1 | 0.092 | 10831.9 | 0.068 | 0 | +| covering | 15000 | first | 4 | 0.183 | 21889.0 | 0.068 | 0 | +| covering | 15000 | deep | 1 | 0.121 | 8242.0 | 0.064 | 0 | +| covering | 15000 | deep | 4 | 0.235 | 16992.4 | 0.064 | 0 | +| covering | 4900 | first | 1 | 0.095 | 10571.9 | 0.078 | 0 | +| covering | 4900 | first | 4 | 0.163 | 24564.0 | 0.078 | 0 | +| covering | 4900 | deep | 1 | 0.091 | 10948.1 | 0.101 | 0 | +| covering | 4900 | deep | 4 | 0.169 | 23660.2 | 0.101 | 0 | +| covering | 100 | first | 1 | 0.092 | 10874.3 | 0.085 | 0 | +| covering | 100 | first | 4 | 0.166 | 24061.6 | 0.085 | 0 | +| covering | 100 | deep | 1 | 0.085 | 11830.1 | 0.058 | 0 | +| covering | 100 | deep | 4 | 0.107 | 37334.3 | 0.058 | 0 | + +| Индекс | Размер индекса, KiB | INSERT 1000 + COMMIT, ms | +|---|---:|---:| +| chat_only | 704.0 | 8.679 | +| composite | 5776.0 | 5.915 | +| covering | 24416.0 | 7.541 | + +Backup: 0.317s; restore: 0.500s; 3021508 bytes; 100000 сообщений, полный fingerprint и 5 выбранных записей совпали. После backup добавлено 1 сообщение: восстановленная БД его не содержит. diff --git a/evidence/experiment.json b/evidence/experiment.json new file mode 100644 index 00000000..4a922f3c --- /dev/null +++ b/evidence/experiment.json @@ -0,0 +1,9103 @@ +{ + "date_utc": "2026-10-02T09:22:41Z", + "database": "experiment_5ac15e48fdf6", + "method": { + "sizes": [ + 80000, + 15000, + 4900, + 100 + ], + "messages": 100000, + "page_size": 51, + "repeats": 3, + "clients": [ + 1, + 4 + ], + "profile": "warm SQL keyset GET at 90% and first page; pgbench prepared; 100 transactions/client; 20 warmup transactions", + "write_profile": "1000-row INSERT plus real COMMIT, 3 repeats, pgbench single client on separate write_probe table", + "postgres_limits": { + "cpu": 2, + "memory_mib": 512 + }, + "host": "macOS-26.6.2-arm64-arm-64bit", + "clock": "SQL planner execution vs pgbench full transaction latency; excludes HTTP/auth/JSON", + "note": "Closed-loop; warm cache; one batch write transaction, not a maximum-capacity result" + }, + "versions": { + "postgres": "PostgreSQL 17.6 on aarch64-unknown-linux-musl, compiled by gcc (Alpine 14.2.0) 14.2.0, 64-bit", + "durability": "{\"fsync\" : \"on\", \"synchronous_commit\" : \"on\", \"full_page_writes\" : \"on\"}" + }, + "variants": [ + { + "name": "chat_only", + "index": "(chat_id)", + "index_bytes": 720896, + "reads": [ + { + "chat_messages": 80000, + "position": "first", + "clients": 1, + "plans": [ + { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 7349.6, + "Total Cost": 7355.47, + "Plan Rows": 51, + "Plan Width": 266, + "Actual Startup Time": 16.234, + "Actual Total Time": 17.23, + "Actual Rows": 51, + "Actual Loops": 1, + "Shared Hit Blocks": 2413, + "Shared Read Blocks": 70, + "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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0, + "Plans": [ + { + "Node Type": "Gather Merge", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 7349.6, + "Total Cost": 12769.78, + "Plan Rows": 47132, + "Plan Width": 266, + "Actual Startup Time": 16.234, + "Actual Total Time": 17.227, + "Actual Rows": 51, + "Actual Loops": 1, + "Workers Planned": 1, + "Workers Launched": 1, + "Shared Hit Blocks": 2413, + "Shared Read Blocks": 70, + "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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0, + "Plans": [ + { + "Node Type": "Sort", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 6349.59, + "Total Cost": 6467.42, + "Plan Rows": 47132, + "Plan Width": 266, + "Actual Startup Time": 11.186, + "Actual Total Time": 11.189, + "Actual Rows": 51, + "Actual Loops": 2, + "Sort Key": [ + "created_at", + "id" + ], + "Sort Method": "top-N heapsort", + "Sort Space Used": 50, + "Sort Space Type": "Memory", + "Shared Hit Blocks": 2413, + "Shared Read Blocks": 70, + "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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0, + "Workers": [ + { + "Worker Number": 0, + "Sort Method": "top-N heapsort", + "Sort Space Used": 50, + "Sort Space Type": "Memory" + } + ], + "Plans": [ + { + "Node Type": "Index Scan", + "Parent Relationship": "Outer", + "Parallel Aware": true, + "Async Capable": false, + "Scan Direction": "Forward", + "Index Name": "experiment_history_idx", + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.29, + "Total Cost": 4777.17, + "Plan Rows": 47132, + "Plan Width": 266, + "Actual Startup Time": 0.033, + "Actual Total Time": 7.322, + "Actual Rows": 40000, + "Actual Loops": 2, + "Index Cond": "(chat_id = '00000000-0000-4000-8000-000000000001'::uuid)", + "Rows Removed by Index Recheck": 0, + "Filter": "(ROW(created_at, id) > ROW(('2026-01-01 00:00:00+00'::timestamp with time zone + '00:00:00'::interval), '00000000-0000-0000-0000-000000000000'::uuid))", + "Rows Removed by Filter": 0, + "Shared Hit Blocks": 2398, + "Shared Read Blocks": 70, + "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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0, + "Workers": [] + } + ] + } + ] + } + ] + }, + "Planning": { + "Shared Hit Blocks": 102, + "Shared Read Blocks": 1, + "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.892, + "Triggers": [], + "Execution Time": 17.58 + }, + { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 7349.6, + "Total Cost": 7355.47, + "Plan Rows": 51, + "Plan Width": 266, + "Actual Startup Time": 11.525, + "Actual Total Time": 12.614, + "Actual Rows": 51, + "Actual Loops": 1, + "Shared Hit Blocks": 2500, + "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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0, + "Plans": [ + { + "Node Type": "Gather Merge", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 7349.6, + "Total Cost": 12769.78, + "Plan Rows": 47132, + "Plan Width": 266, + "Actual Startup Time": 11.524, + "Actual Total Time": 12.611, + "Actual Rows": 51, + "Actual Loops": 1, + "Workers Planned": 1, + "Workers Launched": 1, + "Shared Hit Blocks": 2500, + "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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0, + "Plans": [ + { + "Node Type": "Sort", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 6349.59, + "Total Cost": 6467.42, + "Plan Rows": 47132, + "Plan Width": 266, + "Actual Startup Time": 10.331, + "Actual Total Time": 10.335, + "Actual Rows": 51, + "Actual Loops": 2, + "Sort Key": [ + "created_at", + "id" + ], + "Sort Method": "top-N heapsort", + "Sort Space Used": 50, + "Sort Space Type": "Memory", + "Shared Hit Blocks": 2500, + "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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0, + "Workers": [ + { + "Worker Number": 0, + "Sort Method": "top-N heapsort", + "Sort Space Used": 50, + "Sort Space Type": "Memory" + } + ], + "Plans": [ + { + "Node Type": "Index Scan", + "Parent Relationship": "Outer", + "Parallel Aware": true, + "Async Capable": false, + "Scan Direction": "Forward", + "Index Name": "experiment_history_idx", + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.29, + "Total Cost": 4777.17, + "Plan Rows": 47132, + "Plan Width": 266, + "Actual Startup Time": 0.014, + "Actual Total Time": 7.029, + "Actual Rows": 40000, + "Actual Loops": 2, + "Index Cond": "(chat_id = '00000000-0000-4000-8000-000000000001'::uuid)", + "Rows Removed by Index Recheck": 0, + "Filter": "(ROW(created_at, id) > ROW(('2026-01-01 00:00:00+00'::timestamp with time zone + '00:00:00'::interval), '00000000-0000-0000-0000-000000000000'::uuid))", + "Rows Removed by Filter": 0, + "Shared Hit Blocks": 2485, + "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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0, + "Workers": [] + } + ] + } + ] + } + ] + }, + "Planning": { + "Shared Hit Blocks": 101, + "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.339, + "Triggers": [], + "Execution Time": 12.671 + }, + { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 7349.6, + "Total Cost": 7355.47, + "Plan Rows": 51, + "Plan Width": 266, + "Actual Startup Time": 11.862, + "Actual Total Time": 13.228, + "Actual Rows": 51, + "Actual Loops": 1, + "Shared Hit Blocks": 2499, + "Shared Read Blocks": 1, + "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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0, + "Plans": [ + { + "Node Type": "Gather Merge", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 7349.6, + "Total Cost": 12769.78, + "Plan Rows": 47132, + "Plan Width": 266, + "Actual Startup Time": 11.861, + "Actual Total Time": 13.224, + "Actual Rows": 51, + "Actual Loops": 1, + "Workers Planned": 1, + "Workers Launched": 1, + "Shared Hit Blocks": 2499, + "Shared Read Blocks": 1, + "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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0, + "Plans": [ + { + "Node Type": "Sort", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 6349.59, + "Total Cost": 6467.42, + "Plan Rows": 47132, + "Plan Width": 266, + "Actual Startup Time": 10.765, + "Actual Total Time": 10.767, + "Actual Rows": 51, + "Actual Loops": 2, + "Sort Key": [ + "created_at", + "id" + ], + "Sort Method": "top-N heapsort", + "Sort Space Used": 50, + "Sort Space Type": "Memory", + "Shared Hit Blocks": 2499, + "Shared Read Blocks": 1, + "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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0, + "Workers": [ + { + "Worker Number": 0, + "Sort Method": "top-N heapsort", + "Sort Space Used": 50, + "Sort Space Type": "Memory" + } + ], + "Plans": [ + { + "Node Type": "Index Scan", + "Parent Relationship": "Outer", + "Parallel Aware": true, + "Async Capable": false, + "Scan Direction": "Forward", + "Index Name": "experiment_history_idx", + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.29, + "Total Cost": 4777.17, + "Plan Rows": 47132, + "Plan Width": 266, + "Actual Startup Time": 0.013, + "Actual Total Time": 7.323, + "Actual Rows": 40000, + "Actual Loops": 2, + "Index Cond": "(chat_id = '00000000-0000-4000-8000-000000000001'::uuid)", + "Rows Removed by Index Recheck": 0, + "Filter": "(ROW(created_at, id) > ROW(('2026-01-01 00:00:00+00'::timestamp with time zone + '00:00:00'::interval), '00000000-0000-0000-0000-000000000000'::uuid))", + "Rows Removed by Filter": 0, + "Shared Hit Blocks": 2484, + "Shared Read Blocks": 1, + "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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0, + "Workers": [] + } + ] + } + ] + } + ] + }, + "Planning": { + "Shared Hit Blocks": 101, + "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.282, + "Triggers": [], + "Execution Time": 13.284 + } + ], + "runs": [ + { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 1\nnumber of threads: 1\nmaximum number of tries: 1\nnumber of transactions per client: 100\nnumber of transactions actually processed: 100/100\nnumber of failed transactions: 0 (0.000%)\nlatency average = 11.537 ms\ninitial connection time = 0.965 ms\ntps = 86.678021 (without initial connection time)\n", + "latency_avg_ms": 11.537, + "tps": 86.678021, + "errors": 0 + }, + { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 1\nnumber of threads: 1\nmaximum number of tries: 1\nnumber of transactions per client: 100\nnumber of transactions actually processed: 100/100\nnumber of failed transactions: 0 (0.000%)\nlatency average = 11.137 ms\ninitial connection time = 1.170 ms\ntps = 89.791997 (without initial connection time)\n", + "latency_avg_ms": 11.137, + "tps": 89.791997, + "errors": 0 + }, + { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 1\nnumber of threads: 1\nmaximum number of tries: 1\nnumber of transactions per client: 100\nnumber of transactions actually processed: 100/100\nnumber of failed transactions: 0 (0.000%)\nlatency average = 11.530 ms\ninitial connection time = 2.035 ms\ntps = 86.734030 (without initial connection time)\n", + "latency_avg_ms": 11.53, + "tps": 86.73403, + "errors": 0 + } + ], + "median_execution_ms": 13.284, + "median_latency_ms": 11.53, + "median_tps": 86.73403, + "errors": 0 + }, + { + "chat_messages": 80000, + "position": "first", + "clients": 4, + "plans": [], + "runs": [ + { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 4\nnumber of threads: 4\nmaximum number of tries: 1\nnumber of transactions per client: 100\nnumber of transactions actually processed: 400/400\nnumber of failed transactions: 0 (0.000%)\nlatency average = 49.011 ms\ninitial connection time = 1.787 ms\ntps = 81.614931 (without initial connection time)\n", + "latency_avg_ms": 49.011, + "tps": 81.614931, + "errors": 0 + }, + { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 4\nnumber of threads: 4\nmaximum number of tries: 1\nnumber of transactions per client: 100\nnumber of transactions actually processed: 400/400\nnumber of failed transactions: 0 (0.000%)\nlatency average = 50.676 ms\ninitial connection time = 1.884 ms\ntps = 78.933046 (without initial connection time)\n", + "latency_avg_ms": 50.676, + "tps": 78.933046, + "errors": 0 + }, + { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 4\nnumber of threads: 4\nmaximum number of tries: 1\nnumber of transactions per client: 100\nnumber of transactions actually processed: 400/400\nnumber of failed transactions: 0 (0.000%)\nlatency average = 52.002 ms\ninitial connection time = 1.798 ms\ntps = 76.919438 (without initial connection time)\n", + "latency_avg_ms": 52.002, + "tps": 76.919438, + "errors": 0 + } + ], + "median_execution_ms": 13.284, + "median_latency_ms": 50.676, + "median_tps": 78.933046, + "errors": 0 + }, + { + "chat_messages": 80000, + "position": "deep", + "clients": 1, + "plans": [ + { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 4954.19, + "Total Cost": 4954.31, + "Plan Rows": 51, + "Plan Width": 266, + "Actual Startup Time": 12.499, + "Actual Total Time": 12.504, + "Actual Rows": 51, + "Actual Loops": 1, + "Shared Hit Blocks": 2429, + "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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0, + "Plans": [ + { + "Node Type": "Sort", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 4954.19, + "Total Cost": 4970.03, + "Plan Rows": 6339, + "Plan Width": 266, + "Actual Startup Time": 12.498, + "Actual Total Time": 12.5, + "Actual Rows": 51, + "Actual Loops": 1, + "Sort Key": [ + "created_at", + "id" + ], + "Sort Method": "top-N heapsort", + "Sort Space Used": 50, + "Sort Space Type": "Memory", + "Shared Hit Blocks": 2429, + "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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0, + "Plans": [ + { + "Node Type": "Index Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Scan Direction": "Forward", + "Index Name": "experiment_history_idx", + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.29, + "Total Cost": 4742.7, + "Plan Rows": 6339, + "Plan Width": 266, + "Actual Startup Time": 10.264, + "Actual Total Time": 11.71, + "Actual Rows": 8001, + "Actual Loops": 1, + "Index Cond": "(chat_id = '00000000-0000-4000-8000-000000000001'::uuid)", + "Rows Removed by Index Recheck": 0, + "Filter": "(ROW(created_at, id) > ROW(('2026-01-01 00:00:00+00'::timestamp with time zone + '00:00:00.072'::interval), '00000000-0000-0000-0000-000000000000'::uuid))", + "Rows Removed by Filter": 71999, + "Shared Hit Blocks": 2423, + "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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0 + } + ] + } + ] + }, + "Planning": { + "Shared Hit Blocks": 101, + "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.361, + "Triggers": [], + "Execution Time": 12.561 + }, + { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 4954.19, + "Total Cost": 4954.31, + "Plan Rows": 51, + "Plan Width": 266, + "Actual Startup Time": 12.812, + "Actual Total Time": 12.816, + "Actual Rows": 51, + "Actual Loops": 1, + "Shared Hit Blocks": 2429, + "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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0, + "Plans": [ + { + "Node Type": "Sort", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 4954.19, + "Total Cost": 4970.03, + "Plan Rows": 6339, + "Plan Width": 266, + "Actual Startup Time": 12.81, + "Actual Total Time": 12.812, + "Actual Rows": 51, + "Actual Loops": 1, + "Sort Key": [ + "created_at", + "id" + ], + "Sort Method": "top-N heapsort", + "Sort Space Used": 50, + "Sort Space Type": "Memory", + "Shared Hit Blocks": 2429, + "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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0, + "Plans": [ + { + "Node Type": "Index Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Scan Direction": "Forward", + "Index Name": "experiment_history_idx", + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.29, + "Total Cost": 4742.7, + "Plan Rows": 6339, + "Plan Width": 266, + "Actual Startup Time": 10.631, + "Actual Total Time": 12.105, + "Actual Rows": 8001, + "Actual Loops": 1, + "Index Cond": "(chat_id = '00000000-0000-4000-8000-000000000001'::uuid)", + "Rows Removed by Index Recheck": 0, + "Filter": "(ROW(created_at, id) > ROW(('2026-01-01 00:00:00+00'::timestamp with time zone + '00:00:00.072'::interval), '00000000-0000-0000-0000-000000000000'::uuid))", + "Rows Removed by Filter": 71999, + "Shared Hit Blocks": 2423, + "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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0 + } + ] + } + ] + }, + "Planning": { + "Shared Hit Blocks": 101, + "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.309, + "Triggers": [], + "Execution Time": 12.858 + }, + { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 4954.19, + "Total Cost": 4954.31, + "Plan Rows": 51, + "Plan Width": 266, + "Actual Startup Time": 13.026, + "Actual Total Time": 13.03, + "Actual Rows": 51, + "Actual Loops": 1, + "Shared Hit Blocks": 2429, + "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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0, + "Plans": [ + { + "Node Type": "Sort", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 4954.19, + "Total Cost": 4970.03, + "Plan Rows": 6339, + "Plan Width": 266, + "Actual Startup Time": 13.025, + "Actual Total Time": 13.026, + "Actual Rows": 51, + "Actual Loops": 1, + "Sort Key": [ + "created_at", + "id" + ], + "Sort Method": "top-N heapsort", + "Sort Space Used": 50, + "Sort Space Type": "Memory", + "Shared Hit Blocks": 2429, + "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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0, + "Plans": [ + { + "Node Type": "Index Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Scan Direction": "Forward", + "Index Name": "experiment_history_idx", + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.29, + "Total Cost": 4742.7, + "Plan Rows": 6339, + "Plan Width": 266, + "Actual Startup Time": 10.795, + "Actual Total Time": 12.3, + "Actual Rows": 8001, + "Actual Loops": 1, + "Index Cond": "(chat_id = '00000000-0000-4000-8000-000000000001'::uuid)", + "Rows Removed by Index Recheck": 0, + "Filter": "(ROW(created_at, id) > ROW(('2026-01-01 00:00:00+00'::timestamp with time zone + '00:00:00.072'::interval), '00000000-0000-0000-0000-000000000000'::uuid))", + "Rows Removed by Filter": 71999, + "Shared Hit Blocks": 2423, + "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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0 + } + ] + } + ] + }, + "Planning": { + "Shared Hit Blocks": 101, + "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.322, + "Triggers": [], + "Execution Time": 13.082 + } + ], + "runs": [ + { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 1\nnumber of threads: 1\nmaximum number of tries: 1\nnumber of transactions per client: 100\nnumber of transactions actually processed: 100/100\nnumber of failed transactions: 0 (0.000%)\nlatency average = 11.053 ms\ninitial connection time = 1.015 ms\ntps = 90.469655 (without initial connection time)\n", + "latency_avg_ms": 11.053, + "tps": 90.469655, + "errors": 0 + }, + { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 1\nnumber of threads: 1\nmaximum number of tries: 1\nnumber of transactions per client: 100\nnumber of transactions actually processed: 100/100\nnumber of failed transactions: 0 (0.000%)\nlatency average = 12.449 ms\ninitial connection time = 1.076 ms\ntps = 80.325543 (without initial connection time)\n", + "latency_avg_ms": 12.449, + "tps": 80.325543, + "errors": 0 + }, + { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 1\nnumber of threads: 1\nmaximum number of tries: 1\nnumber of transactions per client: 100\nnumber of transactions actually processed: 100/100\nnumber of failed transactions: 0 (0.000%)\nlatency average = 11.030 ms\ninitial connection time = 1.085 ms\ntps = 90.665530 (without initial connection time)\n", + "latency_avg_ms": 11.03, + "tps": 90.66553, + "errors": 0 + } + ], + "median_execution_ms": 12.858, + "median_latency_ms": 11.053, + "median_tps": 90.469655, + "errors": 0 + }, + { + "chat_messages": 80000, + "position": "deep", + "clients": 4, + "plans": [], + "runs": [ + { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 4\nnumber of threads: 4\nmaximum number of tries: 1\nnumber of transactions per client: 100\nnumber of transactions actually processed: 400/400\nnumber of failed transactions: 0 (0.000%)\nlatency average = 23.470 ms\ninitial connection time = 1.980 ms\ntps = 170.427432 (without initial connection time)\n", + "latency_avg_ms": 23.47, + "tps": 170.427432, + "errors": 0 + }, + { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 4\nnumber of threads: 4\nmaximum number of tries: 1\nnumber of transactions per client: 100\nnumber of transactions actually processed: 400/400\nnumber of failed transactions: 0 (0.000%)\nlatency average = 23.482 ms\ninitial connection time = 1.966 ms\ntps = 170.346434 (without initial connection time)\n", + "latency_avg_ms": 23.482, + "tps": 170.346434, + "errors": 0 + }, + { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 4\nnumber of threads: 4\nmaximum number of tries: 1\nnumber of transactions per client: 100\nnumber of transactions actually processed: 400/400\nnumber of failed transactions: 0 (0.000%)\nlatency average = 22.995 ms\ninitial connection time = 2.079 ms\ntps = 173.952372 (without initial connection time)\n", + "latency_avg_ms": 22.995, + "tps": 173.952372, + "errors": 0 + } + ], + "median_execution_ms": 12.858, + "median_latency_ms": 23.47, + "median_tps": 170.427432, + "errors": 0 + }, + { + "chat_messages": 15000, + "position": "first", + "clients": 1, + "plans": [ + { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 1584.94, + "Total Cost": 1585.07, + "Plan Rows": 51, + "Plan Width": 266, + "Actual Startup Time": 9.799, + "Actual Total Time": 9.804, + "Actual Rows": 51, + "Actual Loops": 1, + "Shared Hit Blocks": 451, + "Shared Read Blocks": 12, + "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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0, + "Plans": [ + { + "Node Type": "Sort", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 1584.94, + "Total Cost": 1622.04, + "Plan Rows": 14839, + "Plan Width": 266, + "Actual Startup Time": 9.798, + "Actual Total Time": 9.8, + "Actual Rows": 51, + "Actual Loops": 1, + "Sort Key": [ + "created_at", + "id" + ], + "Sort Method": "top-N heapsort", + "Sort Space Used": 50, + "Sort Space Type": "Memory", + "Shared Hit Blocks": 451, + "Shared Read Blocks": 12, + "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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0, + "Plans": [ + { + "Node Type": "Index Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Scan Direction": "Forward", + "Index Name": "experiment_history_idx", + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.29, + "Total Cost": 1089.88, + "Plan Rows": 14839, + "Plan Width": 266, + "Actual Startup Time": 0.019, + "Actual Total Time": 8.375, + "Actual Rows": 15000, + "Actual Loops": 1, + "Index Cond": "(chat_id = '00000000-0000-4000-8000-000000000002'::uuid)", + "Rows Removed by Index Recheck": 0, + "Filter": "(ROW(created_at, id) > ROW(('2026-01-01 00:00:00+00'::timestamp with time zone + '00:00:00'::interval), '00000000-0000-0000-0000-000000000000'::uuid))", + "Rows Removed by Filter": 0, + "Shared Hit Blocks": 445, + "Shared Read Blocks": 12, + "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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0 + } + ] + } + ] + }, + "Planning": { + "Shared Hit Blocks": 101, + "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.266, + "Triggers": [], + "Execution Time": 9.853 + }, + { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 1584.94, + "Total Cost": 1585.07, + "Plan Rows": 51, + "Plan Width": 266, + "Actual Startup Time": 4.026, + "Actual Total Time": 4.03, + "Actual Rows": 51, + "Actual Loops": 1, + "Shared Hit Blocks": 463, + "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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0, + "Plans": [ + { + "Node Type": "Sort", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 1584.94, + "Total Cost": 1622.04, + "Plan Rows": 14839, + "Plan Width": 266, + "Actual Startup Time": 4.025, + "Actual Total Time": 4.027, + "Actual Rows": 51, + "Actual Loops": 1, + "Sort Key": [ + "created_at", + "id" + ], + "Sort Method": "top-N heapsort", + "Sort Space Used": 50, + "Sort Space Type": "Memory", + "Shared Hit Blocks": 463, + "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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0, + "Plans": [ + { + "Node Type": "Index Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Scan Direction": "Forward", + "Index Name": "experiment_history_idx", + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.29, + "Total Cost": 1089.88, + "Plan Rows": 14839, + "Plan Width": 266, + "Actual Startup Time": 0.024, + "Actual Total Time": 2.737, + "Actual Rows": 15000, + "Actual Loops": 1, + "Index Cond": "(chat_id = '00000000-0000-4000-8000-000000000002'::uuid)", + "Rows Removed by Index Recheck": 0, + "Filter": "(ROW(created_at, id) > ROW(('2026-01-01 00:00:00+00'::timestamp with time zone + '00:00:00'::interval), '00000000-0000-0000-0000-000000000000'::uuid))", + "Rows Removed by Filter": 0, + "Shared Hit Blocks": 457, + "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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0 + } + ] + } + ] + }, + "Planning": { + "Shared Hit Blocks": 101, + "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.296, + "Triggers": [], + "Execution Time": 4.074 + }, + { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 1584.94, + "Total Cost": 1585.07, + "Plan Rows": 51, + "Plan Width": 266, + "Actual Startup Time": 4.135, + "Actual Total Time": 4.145, + "Actual Rows": 51, + "Actual Loops": 1, + "Shared Hit Blocks": 463, + "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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0, + "Plans": [ + { + "Node Type": "Sort", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 1584.94, + "Total Cost": 1622.04, + "Plan Rows": 14839, + "Plan Width": 266, + "Actual Startup Time": 4.133, + "Actual Total Time": 4.141, + "Actual Rows": 51, + "Actual Loops": 1, + "Sort Key": [ + "created_at", + "id" + ], + "Sort Method": "top-N heapsort", + "Sort Space Used": 50, + "Sort Space Type": "Memory", + "Shared Hit Blocks": 463, + "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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0, + "Plans": [ + { + "Node Type": "Index Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Scan Direction": "Forward", + "Index Name": "experiment_history_idx", + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.29, + "Total Cost": 1089.88, + "Plan Rows": 14839, + "Plan Width": 266, + "Actual Startup Time": 0.02, + "Actual Total Time": 2.821, + "Actual Rows": 15000, + "Actual Loops": 1, + "Index Cond": "(chat_id = '00000000-0000-4000-8000-000000000002'::uuid)", + "Rows Removed by Index Recheck": 0, + "Filter": "(ROW(created_at, id) > ROW(('2026-01-01 00:00:00+00'::timestamp with time zone + '00:00:00'::interval), '00000000-0000-0000-0000-000000000000'::uuid))", + "Rows Removed by Filter": 0, + "Shared Hit Blocks": 457, + "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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0 + } + ] + } + ] + }, + "Planning": { + "Shared Hit Blocks": 101, + "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.278, + "Triggers": [], + "Execution Time": 4.196 + } + ], + "runs": [ + { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 1\nnumber of threads: 1\nmaximum number of tries: 1\nnumber of transactions per client: 100\nnumber of transactions actually processed: 100/100\nnumber of failed transactions: 0 (0.000%)\nlatency average = 2.989 ms\ninitial connection time = 1.266 ms\ntps = 334.616028 (without initial connection time)\n", + "latency_avg_ms": 2.989, + "tps": 334.616028, + "errors": 0 + }, + { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 1\nnumber of threads: 1\nmaximum number of tries: 1\nnumber of transactions per client: 100\nnumber of transactions actually processed: 100/100\nnumber of failed transactions: 0 (0.000%)\nlatency average = 3.050 ms\ninitial connection time = 1.143 ms\ntps = 327.897879 (without initial connection time)\n", + "latency_avg_ms": 3.05, + "tps": 327.897879, + "errors": 0 + }, + { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 1\nnumber of threads: 1\nmaximum number of tries: 1\nnumber of transactions per client: 100\nnumber of transactions actually processed: 100/100\nnumber of failed transactions: 0 (0.000%)\nlatency average = 3.003 ms\ninitial connection time = 1.029 ms\ntps = 332.968178 (without initial connection time)\n", + "latency_avg_ms": 3.003, + "tps": 332.968178, + "errors": 0 + } + ], + "median_execution_ms": 4.196, + "median_latency_ms": 3.003, + "median_tps": 332.968178, + "errors": 0 + }, + { + "chat_messages": 15000, + "position": "first", + "clients": 4, + "plans": [], + "runs": [ + { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 4\nnumber of threads: 4\nmaximum number of tries: 1\nnumber of transactions per client: 100\nnumber of transactions actually processed: 400/400\nnumber of failed transactions: 0 (0.000%)\nlatency average = 6.663 ms\ninitial connection time = 1.632 ms\ntps = 600.316667 (without initial connection time)\n", + "latency_avg_ms": 6.663, + "tps": 600.316667, + "errors": 0 + }, + { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 4\nnumber of threads: 4\nmaximum number of tries: 1\nnumber of transactions per client: 100\nnumber of transactions actually processed: 400/400\nnumber of failed transactions: 0 (0.000%)\nlatency average = 6.240 ms\ninitial connection time = 1.944 ms\ntps = 641.002014 (without initial connection time)\n", + "latency_avg_ms": 6.24, + "tps": 641.002014, + "errors": 0 + }, + { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 4\nnumber of threads: 4\nmaximum number of tries: 1\nnumber of transactions per client: 100\nnumber of transactions actually processed: 400/400\nnumber of failed transactions: 0 (0.000%)\nlatency average = 5.873 ms\ninitial connection time = 1.669 ms\ntps = 681.106116 (without initial connection time)\n", + "latency_avg_ms": 5.873, + "tps": 681.106116, + "errors": 0 + } + ], + "median_execution_ms": 4.196, + "median_latency_ms": 6.24, + "median_tps": 641.002014, + "errors": 0 + }, + { + "chat_messages": 15000, + "position": "deep", + "clients": 1, + "plans": [ + { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 1356.96, + "Total Cost": 1357.09, + "Plan Rows": 51, + "Plan Width": 266, + "Actual Startup Time": 2.663, + "Actual Total Time": 2.667, + "Actual Rows": 51, + "Actual Loops": 1, + "Shared Hit Blocks": 463, + "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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0, + "Plans": [ + { + "Node Type": "Sort", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 1356.96, + "Total Cost": 1382.27, + "Plan Rows": 10125, + "Plan Width": 266, + "Actual Startup Time": 2.662, + "Actual Total Time": 2.664, + "Actual Rows": 51, + "Actual Loops": 1, + "Sort Key": [ + "created_at", + "id" + ], + "Sort Method": "top-N heapsort", + "Sort Space Used": 50, + "Sort Space Type": "Memory", + "Shared Hit Blocks": 463, + "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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0, + "Plans": [ + { + "Node Type": "Index Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Scan Direction": "Forward", + "Index Name": "experiment_history_idx", + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.29, + "Total Cost": 1019.17, + "Plan Rows": 10125, + "Plan Width": 266, + "Actual Startup Time": 2.12, + "Actual Total Time": 2.453, + "Actual Rows": 1501, + "Actual Loops": 1, + "Index Cond": "(chat_id = '00000000-0000-4000-8000-000000000002'::uuid)", + "Rows Removed by Index Recheck": 0, + "Filter": "(ROW(created_at, id) > ROW(('2026-01-01 00:00:00+00'::timestamp with time zone + '00:00:00.0135'::interval), '00000000-0000-0000-0000-000000000000'::uuid))", + "Rows Removed by Filter": 13499, + "Shared Hit Blocks": 457, + "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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0 + } + ] + } + ] + }, + "Planning": { + "Shared Hit Blocks": 101, + "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.323, + "Triggers": [], + "Execution Time": 2.716 + }, + { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 1356.96, + "Total Cost": 1357.09, + "Plan Rows": 51, + "Plan Width": 266, + "Actual Startup Time": 2.453, + "Actual Total Time": 2.457, + "Actual Rows": 51, + "Actual Loops": 1, + "Shared Hit Blocks": 463, + "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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0, + "Plans": [ + { + "Node Type": "Sort", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 1356.96, + "Total Cost": 1382.27, + "Plan Rows": 10125, + "Plan Width": 266, + "Actual Startup Time": 2.452, + "Actual Total Time": 2.454, + "Actual Rows": 51, + "Actual Loops": 1, + "Sort Key": [ + "created_at", + "id" + ], + "Sort Method": "top-N heapsort", + "Sort Space Used": 50, + "Sort Space Type": "Memory", + "Shared Hit Blocks": 463, + "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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0, + "Plans": [ + { + "Node Type": "Index Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Scan Direction": "Forward", + "Index Name": "experiment_history_idx", + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.29, + "Total Cost": 1019.17, + "Plan Rows": 10125, + "Plan Width": 266, + "Actual Startup Time": 1.967, + "Actual Total Time": 2.261, + "Actual Rows": 1501, + "Actual Loops": 1, + "Index Cond": "(chat_id = '00000000-0000-4000-8000-000000000002'::uuid)", + "Rows Removed by Index Recheck": 0, + "Filter": "(ROW(created_at, id) > ROW(('2026-01-01 00:00:00+00'::timestamp with time zone + '00:00:00.0135'::interval), '00000000-0000-0000-0000-000000000000'::uuid))", + "Rows Removed by Filter": 13499, + "Shared Hit Blocks": 457, + "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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0 + } + ] + } + ] + }, + "Planning": { + "Shared Hit Blocks": 101, + "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.311, + "Triggers": [], + "Execution Time": 2.495 + }, + { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 1356.96, + "Total Cost": 1357.09, + "Plan Rows": 51, + "Plan Width": 266, + "Actual Startup Time": 2.393, + "Actual Total Time": 2.397, + "Actual Rows": 51, + "Actual Loops": 1, + "Shared Hit Blocks": 463, + "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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0, + "Plans": [ + { + "Node Type": "Sort", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 1356.96, + "Total Cost": 1382.27, + "Plan Rows": 10125, + "Plan Width": 266, + "Actual Startup Time": 2.392, + "Actual Total Time": 2.394, + "Actual Rows": 51, + "Actual Loops": 1, + "Sort Key": [ + "created_at", + "id" + ], + "Sort Method": "top-N heapsort", + "Sort Space Used": 50, + "Sort Space Type": "Memory", + "Shared Hit Blocks": 463, + "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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0, + "Plans": [ + { + "Node Type": "Index Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Scan Direction": "Forward", + "Index Name": "experiment_history_idx", + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.29, + "Total Cost": 1019.17, + "Plan Rows": 10125, + "Plan Width": 266, + "Actual Startup Time": 1.908, + "Actual Total Time": 2.199, + "Actual Rows": 1501, + "Actual Loops": 1, + "Index Cond": "(chat_id = '00000000-0000-4000-8000-000000000002'::uuid)", + "Rows Removed by Index Recheck": 0, + "Filter": "(ROW(created_at, id) > ROW(('2026-01-01 00:00:00+00'::timestamp with time zone + '00:00:00.0135'::interval), '00000000-0000-0000-0000-000000000000'::uuid))", + "Rows Removed by Filter": 13499, + "Shared Hit Blocks": 457, + "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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0 + } + ] + } + ] + }, + "Planning": { + "Shared Hit Blocks": 101, + "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.299, + "Triggers": [], + "Execution Time": 2.434 + } + ], + "runs": [ + { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 1\nnumber of threads: 1\nmaximum number of tries: 1\nnumber of transactions per client: 100\nnumber of transactions actually processed: 100/100\nnumber of failed transactions: 0 (0.000%)\nlatency average = 1.300 ms\ninitial connection time = 1.291 ms\ntps = 768.964589 (without initial connection time)\n", + "latency_avg_ms": 1.3, + "tps": 768.964589, + "errors": 0 + }, + { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 1\nnumber of threads: 1\nmaximum number of tries: 1\nnumber of transactions per client: 100\nnumber of transactions actually processed: 100/100\nnumber of failed transactions: 0 (0.000%)\nlatency average = 1.105 ms\ninitial connection time = 1.200 ms\ntps = 904.584434 (without initial connection time)\n", + "latency_avg_ms": 1.105, + "tps": 904.584434, + "errors": 0 + }, + { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 1\nnumber of threads: 1\nmaximum number of tries: 1\nnumber of transactions per client: 100\nnumber of transactions actually processed: 100/100\nnumber of failed transactions: 0 (0.000%)\nlatency average = 1.309 ms\ninitial connection time = 1.220 ms\ntps = 763.831071 (without initial connection time)\n", + "latency_avg_ms": 1.309, + "tps": 763.831071, + "errors": 0 + } + ], + "median_execution_ms": 2.495, + "median_latency_ms": 1.3, + "median_tps": 768.964589, + "errors": 0 + }, + { + "chat_messages": 15000, + "position": "deep", + "clients": 4, + "plans": [], + "runs": [ + { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 4\nnumber of threads: 4\nmaximum number of tries: 1\nnumber of transactions per client: 100\nnumber of transactions actually processed: 400/400\nnumber of failed transactions: 0 (0.000%)\nlatency average = 1.829 ms\ninitial connection time = 1.749 ms\ntps = 2186.497286 (without initial connection time)\n", + "latency_avg_ms": 1.829, + "tps": 2186.497286, + "errors": 0 + }, + { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 4\nnumber of threads: 4\nmaximum number of tries: 1\nnumber of transactions per client: 100\nnumber of transactions actually processed: 400/400\nnumber of failed transactions: 0 (0.000%)\nlatency average = 1.874 ms\ninitial connection time = 1.850 ms\ntps = 2134.095917 (without initial connection time)\n", + "latency_avg_ms": 1.874, + "tps": 2134.095917, + "errors": 0 + }, + { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 4\nnumber of threads: 4\nmaximum number of tries: 1\nnumber of transactions per client: 100\nnumber of transactions actually processed: 400/400\nnumber of failed transactions: 0 (0.000%)\nlatency average = 1.938 ms\ninitial connection time = 1.688 ms\ntps = 2063.642742 (without initial connection time)\n", + "latency_avg_ms": 1.938, + "tps": 2063.642742, + "errors": 0 + } + ], + "median_execution_ms": 2.495, + "median_latency_ms": 1.874, + "median_tps": 2134.095917, + "errors": 0 + }, + { + "chat_messages": 4900, + "position": "first", + "clients": 1, + "plans": [ + { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 528.97, + "Total Cost": 529.09, + "Plan Rows": 51, + "Plan Width": 266, + "Actual Startup Time": 1.977, + "Actual Total Time": 1.981, + "Actual Rows": 51, + "Actual Loops": 1, + "Shared Hit Blocks": 153, + "Shared Read Blocks": 4, + "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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0, + "Plans": [ + { + "Node Type": "Sort", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 528.97, + "Total Cost": 541.26, + "Plan Rows": 4916, + "Plan Width": 266, + "Actual Startup Time": 1.976, + "Actual Total Time": 1.978, + "Actual Rows": 51, + "Actual Loops": 1, + "Sort Key": [ + "created_at", + "id" + ], + "Sort Method": "top-N heapsort", + "Sort Space Used": 50, + "Sort Space Type": "Memory", + "Shared Hit Blocks": 153, + "Shared Read Blocks": 4, + "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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0, + "Plans": [ + { + "Node Type": "Index Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Scan Direction": "Forward", + "Index Name": "experiment_history_idx", + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.29, + "Total Cost": 364.96, + "Plan Rows": 4916, + "Plan Width": 266, + "Actual Startup Time": 0.022, + "Actual Total Time": 1.518, + "Actual Rows": 4900, + "Actual Loops": 1, + "Index Cond": "(chat_id = '00000000-0000-4000-8000-000000000003'::uuid)", + "Rows Removed by Index Recheck": 0, + "Filter": "(ROW(created_at, id) > ROW(('2026-01-01 00:00:00+00'::timestamp with time zone + '00:00:00'::interval), '00000000-0000-0000-0000-000000000000'::uuid))", + "Rows Removed by Filter": 0, + "Shared Hit Blocks": 147, + "Shared Read Blocks": 4, + "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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0 + } + ] + } + ] + }, + "Planning": { + "Shared Hit Blocks": 101, + "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.294, + "Triggers": [], + "Execution Time": 2.023 + }, + { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 528.97, + "Total Cost": 529.09, + "Plan Rows": 51, + "Plan Width": 266, + "Actual Startup Time": 1.237, + "Actual Total Time": 1.24, + "Actual Rows": 51, + "Actual Loops": 1, + "Shared Hit Blocks": 157, + "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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0, + "Plans": [ + { + "Node Type": "Sort", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 528.97, + "Total Cost": 541.26, + "Plan Rows": 4916, + "Plan Width": 266, + "Actual Startup Time": 1.236, + "Actual Total Time": 1.238, + "Actual Rows": 51, + "Actual Loops": 1, + "Sort Key": [ + "created_at", + "id" + ], + "Sort Method": "top-N heapsort", + "Sort Space Used": 50, + "Sort Space Type": "Memory", + "Shared Hit Blocks": 157, + "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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0, + "Plans": [ + { + "Node Type": "Index Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Scan Direction": "Forward", + "Index Name": "experiment_history_idx", + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.29, + "Total Cost": 364.96, + "Plan Rows": 4916, + "Plan Width": 266, + "Actual Startup Time": 0.018, + "Actual Total Time": 0.815, + "Actual Rows": 4900, + "Actual Loops": 1, + "Index Cond": "(chat_id = '00000000-0000-4000-8000-000000000003'::uuid)", + "Rows Removed by Index Recheck": 0, + "Filter": "(ROW(created_at, id) > ROW(('2026-01-01 00:00:00+00'::timestamp with time zone + '00:00:00'::interval), '00000000-0000-0000-0000-000000000000'::uuid))", + "Rows Removed by Filter": 0, + "Shared Hit Blocks": 151, + "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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0 + } + ] + } + ] + }, + "Planning": { + "Shared Hit Blocks": 101, + "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.309, + "Triggers": [], + "Execution Time": 1.275 + }, + { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 528.97, + "Total Cost": 529.09, + "Plan Rows": 51, + "Plan Width": 266, + "Actual Startup Time": 1.369, + "Actual Total Time": 1.375, + "Actual Rows": 51, + "Actual Loops": 1, + "Shared Hit Blocks": 157, + "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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0, + "Plans": [ + { + "Node Type": "Sort", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 528.97, + "Total Cost": 541.26, + "Plan Rows": 4916, + "Plan Width": 266, + "Actual Startup Time": 1.369, + "Actual Total Time": 1.372, + "Actual Rows": 51, + "Actual Loops": 1, + "Sort Key": [ + "created_at", + "id" + ], + "Sort Method": "top-N heapsort", + "Sort Space Used": 50, + "Sort Space Type": "Memory", + "Shared Hit Blocks": 157, + "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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0, + "Plans": [ + { + "Node Type": "Index Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Scan Direction": "Forward", + "Index Name": "experiment_history_idx", + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.29, + "Total Cost": 364.96, + "Plan Rows": 4916, + "Plan Width": 266, + "Actual Startup Time": 0.023, + "Actual Total Time": 0.902, + "Actual Rows": 4900, + "Actual Loops": 1, + "Index Cond": "(chat_id = '00000000-0000-4000-8000-000000000003'::uuid)", + "Rows Removed by Index Recheck": 0, + "Filter": "(ROW(created_at, id) > ROW(('2026-01-01 00:00:00+00'::timestamp with time zone + '00:00:00'::interval), '00000000-0000-0000-0000-000000000000'::uuid))", + "Rows Removed by Filter": 0, + "Shared Hit Blocks": 151, + "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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0 + } + ] + } + ] + }, + "Planning": { + "Shared Hit Blocks": 101, + "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.377, + "Triggers": [], + "Execution Time": 1.417 + } + ], + "runs": [ + { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 1\nnumber of threads: 1\nmaximum number of tries: 1\nnumber of transactions per client: 100\nnumber of transactions actually processed: 100/100\nnumber of failed transactions: 0 (0.000%)\nlatency average = 1.066 ms\ninitial connection time = 1.357 ms\ntps = 937.901539 (without initial connection time)\n", + "latency_avg_ms": 1.066, + "tps": 937.901539, + "errors": 0 + }, + { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 1\nnumber of threads: 1\nmaximum number of tries: 1\nnumber of transactions per client: 100\nnumber of transactions actually processed: 100/100\nnumber of failed transactions: 0 (0.000%)\nlatency average = 1.116 ms\ninitial connection time = 1.556 ms\ntps = 896.041290 (without initial connection time)\n", + "latency_avg_ms": 1.116, + "tps": 896.04129, + "errors": 0 + }, + { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 1\nnumber of threads: 1\nmaximum number of tries: 1\nnumber of transactions per client: 100\nnumber of transactions actually processed: 100/100\nnumber of failed transactions: 0 (0.000%)\nlatency average = 1.052 ms\ninitial connection time = 1.386 ms\ntps = 950.507096 (without initial connection time)\n", + "latency_avg_ms": 1.052, + "tps": 950.507096, + "errors": 0 + } + ], + "median_execution_ms": 1.417, + "median_latency_ms": 1.066, + "median_tps": 937.901539, + "errors": 0 + }, + { + "chat_messages": 4900, + "position": "first", + "clients": 4, + "plans": [], + "runs": [ + { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 4\nnumber of threads: 4\nmaximum number of tries: 1\nnumber of transactions per client: 100\nnumber of transactions actually processed: 400/400\nnumber of failed transactions: 0 (0.000%)\nlatency average = 1.904 ms\ninitial connection time = 2.061 ms\ntps = 2100.696906 (without initial connection time)\n", + "latency_avg_ms": 1.904, + "tps": 2100.696906, + "errors": 0 + }, + { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 4\nnumber of threads: 4\nmaximum number of tries: 1\nnumber of transactions per client: 100\nnumber of transactions actually processed: 400/400\nnumber of failed transactions: 0 (0.000%)\nlatency average = 2.095 ms\ninitial connection time = 1.757 ms\ntps = 1909.180293 (without initial connection time)\n", + "latency_avg_ms": 2.095, + "tps": 1909.180293, + "errors": 0 + }, + { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 4\nnumber of threads: 4\nmaximum number of tries: 1\nnumber of transactions per client: 100\nnumber of transactions actually processed: 400/400\nnumber of failed transactions: 0 (0.000%)\nlatency average = 1.827 ms\ninitial connection time = 2.291 ms\ntps = 2189.657154 (without initial connection time)\n", + "latency_avg_ms": 1.827, + "tps": 2189.657154, + "errors": 0 + } + ], + "median_execution_ms": 1.417, + "median_latency_ms": 1.904, + "median_tps": 2100.696906, + "errors": 0 + }, + { + "chat_messages": 4900, + "position": "deep", + "clients": 1, + "plans": [ + { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 497.63, + "Total Cost": 497.75, + "Plan Rows": 51, + "Plan Width": 266, + "Actual Startup Time": 0.832, + "Actual Total Time": 0.836, + "Actual Rows": 51, + "Actual Loops": 1, + "Shared Hit Blocks": 157, + "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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0, + "Plans": [ + { + "Node Type": "Sort", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 497.63, + "Total Cost": 508.3, + "Plan Rows": 4268, + "Plan Width": 266, + "Actual Startup Time": 0.831, + "Actual Total Time": 0.833, + "Actual Rows": 51, + "Actual Loops": 1, + "Sort Key": [ + "created_at", + "id" + ], + "Sort Method": "top-N heapsort", + "Sort Space Used": 50, + "Sort Space Type": "Memory", + "Shared Hit Blocks": 157, + "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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0, + "Plans": [ + { + "Node Type": "Index Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Scan Direction": "Forward", + "Index Name": "experiment_history_idx", + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.29, + "Total Cost": 355.24, + "Plan Rows": 4268, + "Plan Width": 266, + "Actual Startup Time": 0.659, + "Actual Total Time": 0.748, + "Actual Rows": 491, + "Actual Loops": 1, + "Index Cond": "(chat_id = '00000000-0000-4000-8000-000000000003'::uuid)", + "Rows Removed by Index Recheck": 0, + "Filter": "(ROW(created_at, id) > ROW(('2026-01-01 00:00:00+00'::timestamp with time zone + '00:00:00.00441'::interval), '00000000-0000-0000-0000-000000000000'::uuid))", + "Rows Removed by Filter": 4409, + "Shared Hit Blocks": 151, + "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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0 + } + ] + } + ] + }, + "Planning": { + "Shared Hit Blocks": 101, + "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.255, + "Triggers": [], + "Execution Time": 0.873 + }, + { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 497.63, + "Total Cost": 497.75, + "Plan Rows": 51, + "Plan Width": 266, + "Actual Startup Time": 0.775, + "Actual Total Time": 0.78, + "Actual Rows": 51, + "Actual Loops": 1, + "Shared Hit Blocks": 157, + "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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0, + "Plans": [ + { + "Node Type": "Sort", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 497.63, + "Total Cost": 508.3, + "Plan Rows": 4268, + "Plan Width": 266, + "Actual Startup Time": 0.774, + "Actual Total Time": 0.776, + "Actual Rows": 51, + "Actual Loops": 1, + "Sort Key": [ + "created_at", + "id" + ], + "Sort Method": "top-N heapsort", + "Sort Space Used": 50, + "Sort Space Type": "Memory", + "Shared Hit Blocks": 157, + "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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0, + "Plans": [ + { + "Node Type": "Index Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Scan Direction": "Forward", + "Index Name": "experiment_history_idx", + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.29, + "Total Cost": 355.24, + "Plan Rows": 4268, + "Plan Width": 266, + "Actual Startup Time": 0.604, + "Actual Total Time": 0.694, + "Actual Rows": 491, + "Actual Loops": 1, + "Index Cond": "(chat_id = '00000000-0000-4000-8000-000000000003'::uuid)", + "Rows Removed by Index Recheck": 0, + "Filter": "(ROW(created_at, id) > ROW(('2026-01-01 00:00:00+00'::timestamp with time zone + '00:00:00.00441'::interval), '00000000-0000-0000-0000-000000000000'::uuid))", + "Rows Removed by Filter": 4409, + "Shared Hit Blocks": 151, + "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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0 + } + ] + } + ] + }, + "Planning": { + "Shared Hit Blocks": 101, + "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.281, + "Triggers": [], + "Execution Time": 0.816 + }, + { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 497.63, + "Total Cost": 497.75, + "Plan Rows": 51, + "Plan Width": 266, + "Actual Startup Time": 0.776, + "Actual Total Time": 0.78, + "Actual Rows": 51, + "Actual Loops": 1, + "Shared Hit Blocks": 157, + "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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0, + "Plans": [ + { + "Node Type": "Sort", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 497.63, + "Total Cost": 508.3, + "Plan Rows": 4268, + "Plan Width": 266, + "Actual Startup Time": 0.775, + "Actual Total Time": 0.777, + "Actual Rows": 51, + "Actual Loops": 1, + "Sort Key": [ + "created_at", + "id" + ], + "Sort Method": "top-N heapsort", + "Sort Space Used": 50, + "Sort Space Type": "Memory", + "Shared Hit Blocks": 157, + "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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0, + "Plans": [ + { + "Node Type": "Index Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Scan Direction": "Forward", + "Index Name": "experiment_history_idx", + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.29, + "Total Cost": 355.24, + "Plan Rows": 4268, + "Plan Width": 266, + "Actual Startup Time": 0.623, + "Actual Total Time": 0.698, + "Actual Rows": 491, + "Actual Loops": 1, + "Index Cond": "(chat_id = '00000000-0000-4000-8000-000000000003'::uuid)", + "Rows Removed by Index Recheck": 0, + "Filter": "(ROW(created_at, id) > ROW(('2026-01-01 00:00:00+00'::timestamp with time zone + '00:00:00.00441'::interval), '00000000-0000-0000-0000-000000000000'::uuid))", + "Rows Removed by Filter": 4409, + "Shared Hit Blocks": 151, + "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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0 + } + ] + } + ] + }, + "Planning": { + "Shared Hit Blocks": 101, + "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.268, + "Triggers": [], + "Execution Time": 0.816 + } + ], + "runs": [ + { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 1\nnumber of threads: 1\nmaximum number of tries: 1\nnumber of transactions per client: 100\nnumber of transactions actually processed: 100/100\nnumber of failed transactions: 0 (0.000%)\nlatency average = 0.472 ms\ninitial connection time = 0.957 ms\ntps = 2119.856698 (without initial connection time)\n", + "latency_avg_ms": 0.472, + "tps": 2119.856698, + "errors": 0 + }, + { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 1\nnumber of threads: 1\nmaximum number of tries: 1\nnumber of transactions per client: 100\nnumber of transactions actually processed: 100/100\nnumber of failed transactions: 0 (0.000%)\nlatency average = 0.467 ms\ninitial connection time = 0.919 ms\ntps = 2140.915027 (without initial connection time)\n", + "latency_avg_ms": 0.467, + "tps": 2140.915027, + "errors": 0 + }, + { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 1\nnumber of threads: 1\nmaximum number of tries: 1\nnumber of transactions per client: 100\nnumber of transactions actually processed: 100/100\nnumber of failed transactions: 0 (0.000%)\nlatency average = 0.417 ms\ninitial connection time = 1.274 ms\ntps = 2397.564075 (without initial connection time)\n", + "latency_avg_ms": 0.417, + "tps": 2397.564075, + "errors": 0 + } + ], + "median_execution_ms": 0.816, + "median_latency_ms": 0.467, + "median_tps": 2140.915027, + "errors": 0 + }, + { + "chat_messages": 4900, + "position": "deep", + "clients": 4, + "plans": [], + "runs": [ + { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 4\nnumber of threads: 4\nmaximum number of tries: 1\nnumber of transactions per client: 100\nnumber of transactions actually processed: 400/400\nnumber of failed transactions: 0 (0.000%)\nlatency average = 0.683 ms\ninitial connection time = 1.796 ms\ntps = 5860.462390 (without initial connection time)\n", + "latency_avg_ms": 0.683, + "tps": 5860.46239, + "errors": 0 + }, + { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 4\nnumber of threads: 4\nmaximum number of tries: 1\nnumber of transactions per client: 100\nnumber of transactions actually processed: 400/400\nnumber of failed transactions: 0 (0.000%)\nlatency average = 0.999 ms\ninitial connection time = 1.635 ms\ntps = 4005.848539 (without initial connection time)\n", + "latency_avg_ms": 0.999, + "tps": 4005.848539, + "errors": 0 + }, + { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 4\nnumber of threads: 4\nmaximum number of tries: 1\nnumber of transactions per client: 100\nnumber of transactions actually processed: 400/400\nnumber of failed transactions: 0 (0.000%)\nlatency average = 0.510 ms\ninitial connection time = 1.755 ms\ntps = 7836.529985 (without initial connection time)\n", + "latency_avg_ms": 0.51, + "tps": 7836.529985, + "errors": 0 + } + ], + "median_execution_ms": 0.816, + "median_latency_ms": 0.683, + "median_tps": 5860.46239, + "errors": 0 + }, + { + "chat_messages": 100, + "position": "first", + "clients": 1, + "plans": [ + { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 19.36, + "Total Cost": 19.49, + "Plan Rows": 51, + "Plan Width": 266, + "Actual Startup Time": 0.113, + "Actual Total Time": 0.117, + "Actual Rows": 51, + "Actual Loops": 1, + "Shared Hit Blocks": 12, + "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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0, + "Plans": [ + { + "Node Type": "Sort", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 19.36, + "Total Cost": 19.64, + "Plan Rows": 110, + "Plan Width": 266, + "Actual Startup Time": 0.112, + "Actual Total Time": 0.114, + "Actual Rows": 51, + "Actual Loops": 1, + "Sort Key": [ + "created_at", + "id" + ], + "Sort Method": "quicksort", + "Sort Space Used": 75, + "Sort Space Type": "Memory", + "Shared Hit Blocks": 12, + "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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0, + "Plans": [ + { + "Node Type": "Index Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Scan Direction": "Forward", + "Index Name": "experiment_history_idx", + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.29, + "Total Cost": 15.69, + "Plan Rows": 110, + "Plan Width": 266, + "Actual Startup Time": 0.015, + "Actual Total Time": 0.055, + "Actual Rows": 100, + "Actual Loops": 1, + "Index Cond": "(chat_id = '00000000-0000-4000-8000-000000000004'::uuid)", + "Rows Removed by Index Recheck": 0, + "Filter": "(ROW(created_at, id) > ROW(('2026-01-01 00:00:00+00'::timestamp with time zone + '00:00:00'::interval), '00000000-0000-0000-0000-000000000000'::uuid))", + "Rows Removed by Filter": 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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0 + } + ] + } + ] + }, + "Planning": { + "Shared Hit Blocks": 101, + "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.281, + "Triggers": [], + "Execution Time": 0.16 + }, + { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 19.36, + "Total Cost": 19.49, + "Plan Rows": 51, + "Plan Width": 266, + "Actual Startup Time": 0.082, + "Actual Total Time": 0.086, + "Actual Rows": 51, + "Actual Loops": 1, + "Shared Hit Blocks": 12, + "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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0, + "Plans": [ + { + "Node Type": "Sort", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 19.36, + "Total Cost": 19.64, + "Plan Rows": 110, + "Plan Width": 266, + "Actual Startup Time": 0.081, + "Actual Total Time": 0.083, + "Actual Rows": 51, + "Actual Loops": 1, + "Sort Key": [ + "created_at", + "id" + ], + "Sort Method": "quicksort", + "Sort Space Used": 75, + "Sort Space Type": "Memory", + "Shared Hit Blocks": 12, + "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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0, + "Plans": [ + { + "Node Type": "Index Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Scan Direction": "Forward", + "Index Name": "experiment_history_idx", + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.29, + "Total Cost": 15.69, + "Plan Rows": 110, + "Plan Width": 266, + "Actual Startup Time": 0.015, + "Actual Total Time": 0.032, + "Actual Rows": 100, + "Actual Loops": 1, + "Index Cond": "(chat_id = '00000000-0000-4000-8000-000000000004'::uuid)", + "Rows Removed by Index Recheck": 0, + "Filter": "(ROW(created_at, id) > ROW(('2026-01-01 00:00:00+00'::timestamp with time zone + '00:00:00'::interval), '00000000-0000-0000-0000-000000000000'::uuid))", + "Rows Removed by Filter": 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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0 + } + ] + } + ] + }, + "Planning": { + "Shared Hit Blocks": 101, + "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.306, + "Triggers": [], + "Execution Time": 0.123 + }, + { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 19.36, + "Total Cost": 19.49, + "Plan Rows": 51, + "Plan Width": 266, + "Actual Startup Time": 0.082, + "Actual Total Time": 0.087, + "Actual Rows": 51, + "Actual Loops": 1, + "Shared Hit Blocks": 12, + "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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0, + "Plans": [ + { + "Node Type": "Sort", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 19.36, + "Total Cost": 19.64, + "Plan Rows": 110, + "Plan Width": 266, + "Actual Startup Time": 0.082, + "Actual Total Time": 0.084, + "Actual Rows": 51, + "Actual Loops": 1, + "Sort Key": [ + "created_at", + "id" + ], + "Sort Method": "quicksort", + "Sort Space Used": 75, + "Sort Space Type": "Memory", + "Shared Hit Blocks": 12, + "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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0, + "Plans": [ + { + "Node Type": "Index Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Scan Direction": "Forward", + "Index Name": "experiment_history_idx", + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.29, + "Total Cost": 15.69, + "Plan Rows": 110, + "Plan Width": 266, + "Actual Startup Time": 0.016, + "Actual Total Time": 0.036, + "Actual Rows": 100, + "Actual Loops": 1, + "Index Cond": "(chat_id = '00000000-0000-4000-8000-000000000004'::uuid)", + "Rows Removed by Index Recheck": 0, + "Filter": "(ROW(created_at, id) > ROW(('2026-01-01 00:00:00+00'::timestamp with time zone + '00:00:00'::interval), '00000000-0000-0000-0000-000000000000'::uuid))", + "Rows Removed by Filter": 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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0 + } + ] + } + ] + }, + "Planning": { + "Shared Hit Blocks": 101, + "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.341, + "Triggers": [], + "Execution Time": 0.13 + } + ], + "runs": [ + { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 1\nnumber of threads: 1\nmaximum number of tries: 1\nnumber of transactions per client: 100\nnumber of transactions actually processed: 100/100\nnumber of failed transactions: 0 (0.000%)\nlatency average = 0.120 ms\ninitial connection time = 1.245 ms\ntps = 8316.699933 (without initial connection time)\n", + "latency_avg_ms": 0.12, + "tps": 8316.699933, + "errors": 0 + }, + { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 1\nnumber of threads: 1\nmaximum number of tries: 1\nnumber of transactions per client: 100\nnumber of transactions actually processed: 100/100\nnumber of failed transactions: 0 (0.000%)\nlatency average = 0.117 ms\ninitial connection time = 1.276 ms\ntps = 8534.607835 (without initial connection time)\n", + "latency_avg_ms": 0.117, + "tps": 8534.607835, + "errors": 0 + }, + { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 1\nnumber of threads: 1\nmaximum number of tries: 1\nnumber of transactions per client: 100\nnumber of transactions actually processed: 100/100\nnumber of failed transactions: 0 (0.000%)\nlatency average = 0.121 ms\ninitial connection time = 1.209 ms\ntps = 8260.366760 (without initial connection time)\n", + "latency_avg_ms": 0.121, + "tps": 8260.36676, + "errors": 0 + } + ], + "median_execution_ms": 0.13, + "median_latency_ms": 0.12, + "median_tps": 8316.699933, + "errors": 0 + }, + { + "chat_messages": 100, + "position": "first", + "clients": 4, + "plans": [], + "runs": [ + { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 4\nnumber of threads: 4\nmaximum number of tries: 1\nnumber of transactions per client: 100\nnumber of transactions actually processed: 400/400\nnumber of failed transactions: 0 (0.000%)\nlatency average = 0.181 ms\ninitial connection time = 1.846 ms\ntps = 22107.997568 (without initial connection time)\n", + "latency_avg_ms": 0.181, + "tps": 22107.997568, + "errors": 0 + }, + { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 4\nnumber of threads: 4\nmaximum number of tries: 1\nnumber of transactions per client: 100\nnumber of transactions actually processed: 400/400\nnumber of failed transactions: 0 (0.000%)\nlatency average = 0.181 ms\ninitial connection time = 1.652 ms\ntps = 22044.640397 (without initial connection time)\n", + "latency_avg_ms": 0.181, + "tps": 22044.640397, + "errors": 0 + }, + { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 4\nnumber of threads: 4\nmaximum number of tries: 1\nnumber of transactions per client: 100\nnumber of transactions actually processed: 400/400\nnumber of failed transactions: 0 (0.000%)\nlatency average = 0.183 ms\ninitial connection time = 1.808 ms\ntps = 21801.929471 (without initial connection time)\n", + "latency_avg_ms": 0.183, + "tps": 21801.929471, + "errors": 0 + } + ], + "median_execution_ms": 0.13, + "median_latency_ms": 0.181, + "median_tps": 22044.640397, + "errors": 0 + }, + { + "chat_messages": 100, + "position": "deep", + "clients": 1, + "plans": [ + { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 19.36, + "Total Cost": 19.49, + "Plan Rows": 51, + "Plan Width": 266, + "Actual Startup Time": 0.043, + "Actual Total Time": 0.044, + "Actual Rows": 11, + "Actual Loops": 1, + "Shared Hit Blocks": 12, + "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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0, + "Plans": [ + { + "Node Type": "Sort", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 19.36, + "Total Cost": 19.64, + "Plan Rows": 110, + "Plan Width": 266, + "Actual Startup Time": 0.043, + "Actual Total Time": 0.043, + "Actual Rows": 11, + "Actual Loops": 1, + "Sort Key": [ + "created_at", + "id" + ], + "Sort Method": "quicksort", + "Sort Space Used": 30, + "Sort Space Type": "Memory", + "Shared Hit Blocks": 12, + "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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0, + "Plans": [ + { + "Node Type": "Index Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Scan Direction": "Forward", + "Index Name": "experiment_history_idx", + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.29, + "Total Cost": 15.69, + "Plan Rows": 110, + "Plan Width": 266, + "Actual Startup Time": 0.022, + "Actual Total Time": 0.024, + "Actual Rows": 11, + "Actual Loops": 1, + "Index Cond": "(chat_id = '00000000-0000-4000-8000-000000000004'::uuid)", + "Rows Removed by Index Recheck": 0, + "Filter": "(ROW(created_at, id) > ROW(('2026-01-01 00:00:00+00'::timestamp with time zone + '00:00:00.00009'::interval), '00000000-0000-0000-0000-000000000000'::uuid))", + "Rows Removed by Filter": 89, + "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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0 + } + ] + } + ] + }, + "Planning": { + "Shared Hit Blocks": 101, + "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.27, + "Triggers": [], + "Execution Time": 0.073 + }, + { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 19.36, + "Total Cost": 19.49, + "Plan Rows": 51, + "Plan Width": 266, + "Actual Startup Time": 0.049, + "Actual Total Time": 0.05, + "Actual Rows": 11, + "Actual Loops": 1, + "Shared Hit Blocks": 12, + "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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0, + "Plans": [ + { + "Node Type": "Sort", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 19.36, + "Total Cost": 19.64, + "Plan Rows": 110, + "Plan Width": 266, + "Actual Startup Time": 0.048, + "Actual Total Time": 0.048, + "Actual Rows": 11, + "Actual Loops": 1, + "Sort Key": [ + "created_at", + "id" + ], + "Sort Method": "quicksort", + "Sort Space Used": 30, + "Sort Space Type": "Memory", + "Shared Hit Blocks": 12, + "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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0, + "Plans": [ + { + "Node Type": "Index Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Scan Direction": "Forward", + "Index Name": "experiment_history_idx", + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.29, + "Total Cost": 15.69, + "Plan Rows": 110, + "Plan Width": 266, + "Actual Startup Time": 0.023, + "Actual Total Time": 0.025, + "Actual Rows": 11, + "Actual Loops": 1, + "Index Cond": "(chat_id = '00000000-0000-4000-8000-000000000004'::uuid)", + "Rows Removed by Index Recheck": 0, + "Filter": "(ROW(created_at, id) > ROW(('2026-01-01 00:00:00+00'::timestamp with time zone + '00:00:00.00009'::interval), '00000000-0000-0000-0000-000000000000'::uuid))", + "Rows Removed by Filter": 89, + "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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0 + } + ] + } + ] + }, + "Planning": { + "Shared Hit Blocks": 101, + "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.29, + "Triggers": [], + "Execution Time": 0.084 + }, + { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 19.36, + "Total Cost": 19.49, + "Plan Rows": 51, + "Plan Width": 266, + "Actual Startup Time": 0.05, + "Actual Total Time": 0.052, + "Actual Rows": 11, + "Actual Loops": 1, + "Shared Hit Blocks": 12, + "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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0, + "Plans": [ + { + "Node Type": "Sort", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 19.36, + "Total Cost": 19.64, + "Plan Rows": 110, + "Plan Width": 266, + "Actual Startup Time": 0.05, + "Actual Total Time": 0.05, + "Actual Rows": 11, + "Actual Loops": 1, + "Sort Key": [ + "created_at", + "id" + ], + "Sort Method": "quicksort", + "Sort Space Used": 30, + "Sort Space Type": "Memory", + "Shared Hit Blocks": 12, + "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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0, + "Plans": [ + { + "Node Type": "Index Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Scan Direction": "Forward", + "Index Name": "experiment_history_idx", + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.29, + "Total Cost": 15.69, + "Plan Rows": 110, + "Plan Width": 266, + "Actual Startup Time": 0.024, + "Actual Total Time": 0.026, + "Actual Rows": 11, + "Actual Loops": 1, + "Index Cond": "(chat_id = '00000000-0000-4000-8000-000000000004'::uuid)", + "Rows Removed by Index Recheck": 0, + "Filter": "(ROW(created_at, id) > ROW(('2026-01-01 00:00:00+00'::timestamp with time zone + '00:00:00.00009'::interval), '00000000-0000-0000-0000-000000000000'::uuid))", + "Rows Removed by Filter": 89, + "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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0 + } + ] + } + ] + }, + "Planning": { + "Shared Hit Blocks": 101, + "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.303, + "Triggers": [], + "Execution Time": 0.094 + } + ], + "runs": [ + { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 1\nnumber of threads: 1\nmaximum number of tries: 1\nnumber of transactions per client: 100\nnumber of transactions actually processed: 100/100\nnumber of failed transactions: 0 (0.000%)\nlatency average = 0.092 ms\ninitial connection time = 1.208 ms\ntps = 10840.108401 (without initial connection time)\n", + "latency_avg_ms": 0.092, + "tps": 10840.108401, + "errors": 0 + }, + { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 1\nnumber of threads: 1\nmaximum number of tries: 1\nnumber of transactions per client: 100\nnumber of transactions actually processed: 100/100\nnumber of failed transactions: 0 (0.000%)\nlatency average = 0.087 ms\ninitial connection time = 1.012 ms\ntps = 11550.011550 (without initial connection time)\n", + "latency_avg_ms": 0.087, + "tps": 11550.01155, + "errors": 0 + }, + { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 1\nnumber of threads: 1\nmaximum number of tries: 1\nnumber of transactions per client: 100\nnumber of transactions actually processed: 100/100\nnumber of failed transactions: 0 (0.000%)\nlatency average = 0.094 ms\ninitial connection time = 1.015 ms\ntps = 10590.976488 (without initial connection time)\n", + "latency_avg_ms": 0.094, + "tps": 10590.976488, + "errors": 0 + } + ], + "median_execution_ms": 0.084, + "median_latency_ms": 0.092, + "median_tps": 10840.108401, + "errors": 0 + }, + { + "chat_messages": 100, + "position": "deep", + "clients": 4, + "plans": [], + "runs": [ + { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 4\nnumber of threads: 4\nmaximum number of tries: 1\nnumber of transactions per client: 100\nnumber of transactions actually processed: 400/400\nnumber of failed transactions: 0 (0.000%)\nlatency average = 0.113 ms\ninitial connection time = 1.652 ms\ntps = 35401.362952 (without initial connection time)\n", + "latency_avg_ms": 0.113, + "tps": 35401.362952, + "errors": 0 + }, + { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 4\nnumber of threads: 4\nmaximum number of tries: 1\nnumber of transactions per client: 100\nnumber of transactions actually processed: 400/400\nnumber of failed transactions: 0 (0.000%)\nlatency average = 0.119 ms\ninitial connection time = 1.979 ms\ntps = 33500.837521 (without initial connection time)\n", + "latency_avg_ms": 0.119, + "tps": 33500.837521, + "errors": 0 + }, + { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 4\nnumber of threads: 4\nmaximum number of tries: 1\nnumber of transactions per client: 100\nnumber of transactions actually processed: 400/400\nnumber of failed transactions: 0 (0.000%)\nlatency average = 0.115 ms\ninitial connection time = 1.632 ms\ntps = 34858.387800 (without initial connection time)\n", + "latency_avg_ms": 0.115, + "tps": 34858.3878, + "errors": 0 + } + ], + "median_execution_ms": 0.084, + "median_latency_ms": 0.115, + "median_tps": 34858.3878, + "errors": 0 + } + ], + "writes": [ + { + "repeat": 1, + "plan": { + "Plan": { + "Node Type": "ModifyTable", + "Operation": "Insert", + "Parallel Aware": false, + "Async Capable": false, + "Relation Name": "write_probe", + "Alias": "write_probe", + "Startup Cost": 0.0, + "Total Cost": 42.5, + "Plan Rows": 0, + "Plan Width": 0, + "Actual Startup Time": 6.224, + "Actual Total Time": 6.225, + "Actual Rows": 0, + "Actual Loops": 1, + "Shared Hit Blocks": 3821, + "Shared Read Blocks": 2, + "Shared Dirtied Blocks": 40, + "Shared Written Blocks": 40, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "WAL Records": 3011, + "WAL FPI": 0, + "WAL Bytes": 418474, + "Plans": [ + { + "Node Type": "Function Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Function Name": "generate_series", + "Alias": "i", + "Startup Cost": 0.0, + "Total Cost": 42.5, + "Plan Rows": 1000, + "Plan Width": 88, + "Actual Startup Time": 0.355, + "Actual Total Time": 1.384, + "Actual Rows": 1000, + "Actual Loops": 1, + "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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0 + } + ] + }, + "Planning": { + "Shared Hit Blocks": 15, + "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.127, + "Triggers": [], + "Execution Time": 6.268 + }, + "transaction": { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 1\nnumber of threads: 1\nmaximum number of tries: 1\nnumber of transactions per client: 1\nnumber of transactions actually processed: 1/1\nnumber of failed transactions: 0 (0.000%)\nlatency average = 5.155 ms\ninitial connection time = 1.173 ms\ntps = 193.986421 (without initial connection time)\n", + "latency_avg_ms": 5.155, + "tps": 193.986421, + "errors": 0 + }, + "table_bytes": 352256 + }, + { + "repeat": 2, + "plan": { + "Plan": { + "Node Type": "ModifyTable", + "Operation": "Insert", + "Parallel Aware": false, + "Async Capable": false, + "Relation Name": "write_probe", + "Alias": "write_probe", + "Startup Cost": 0.0, + "Total Cost": 42.5, + "Plan Rows": 0, + "Plan Width": 0, + "Actual Startup Time": 3.557, + "Actual Total Time": 3.557, + "Actual Rows": 0, + "Actual Loops": 1, + "Shared Hit Blocks": 3819, + "Shared Read Blocks": 2, + "Shared Dirtied Blocks": 40, + "Shared Written Blocks": 40, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "WAL Records": 3011, + "WAL FPI": 0, + "WAL Bytes": 418474, + "Plans": [ + { + "Node Type": "Function Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Function Name": "generate_series", + "Alias": "i", + "Startup Cost": 0.0, + "Total Cost": 42.5, + "Plan Rows": 1000, + "Plan Width": 88, + "Actual Startup Time": 0.141, + "Actual Total Time": 1.154, + "Actual Rows": 1000, + "Actual Loops": 1, + "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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0 + } + ] + }, + "Planning": { + "Shared Hit Blocks": 15, + "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.101, + "Triggers": [], + "Execution Time": 3.583 + }, + "transaction": { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 1\nnumber of threads: 1\nmaximum number of tries: 1\nnumber of transactions per client: 1\nnumber of transactions actually processed: 1/1\nnumber of failed transactions: 0 (0.000%)\nlatency average = 8.679 ms\ninitial connection time = 1.174 ms\ntps = 115.220648 (without initial connection time)\n", + "latency_avg_ms": 8.679, + "tps": 115.220648, + "errors": 0 + }, + "table_bytes": 352256 + }, + { + "repeat": 3, + "plan": { + "Plan": { + "Node Type": "ModifyTable", + "Operation": "Insert", + "Parallel Aware": false, + "Async Capable": false, + "Relation Name": "write_probe", + "Alias": "write_probe", + "Startup Cost": 0.0, + "Total Cost": 42.5, + "Plan Rows": 0, + "Plan Width": 0, + "Actual Startup Time": 3.448, + "Actual Total Time": 3.448, + "Actual Rows": 0, + "Actual Loops": 1, + "Shared Hit Blocks": 3819, + "Shared Read Blocks": 2, + "Shared Dirtied Blocks": 40, + "Shared Written Blocks": 40, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "WAL Records": 3011, + "WAL FPI": 0, + "WAL Bytes": 418474, + "Plans": [ + { + "Node Type": "Function Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Function Name": "generate_series", + "Alias": "i", + "Startup Cost": 0.0, + "Total Cost": 42.5, + "Plan Rows": 1000, + "Plan Width": 88, + "Actual Startup Time": 0.161, + "Actual Total Time": 1.109, + "Actual Rows": 1000, + "Actual Loops": 1, + "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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0 + } + ] + }, + "Planning": { + "Shared Hit Blocks": 15, + "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.116, + "Triggers": [], + "Execution Time": 3.483 + }, + "transaction": { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 1\nnumber of threads: 1\nmaximum number of tries: 1\nnumber of transactions per client: 1\nnumber of transactions actually processed: 1/1\nnumber of failed transactions: 0 (0.000%)\nlatency average = 11.787 ms\ninitial connection time = 1.242 ms\ntps = 84.839230 (without initial connection time)\n", + "latency_avg_ms": 11.787, + "tps": 84.83923, + "errors": 0 + }, + "table_bytes": 352256 + } + ], + "resources": { + "measurement_seconds": 54.458, + "cpu_percent": 129.429, + "memory_before_bytes": 360783872, + "memory_after_bytes": 346648576, + "note": "cgroup memory includes shared buffers/page cache, not API RSS; CPU window includes setup and SQL trials" + } + }, + { + "name": "composite", + "index": "(chat_id,created_at,id)", + "index_bytes": 5914624, + "reads": [ + { + "chat_messages": 80000, + "position": "first", + "clients": 1, + "plans": [ + { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 0.42, + "Total Cost": 7.83, + "Plan Rows": 51, + "Plan Width": 266, + "Actual Startup Time": 0.027, + "Actual Total Time": 0.04, + "Actual Rows": 51, + "Actual Loops": 1, + "Shared Hit Blocks": 2, + "Shared Read Blocks": 3, + "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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0, + "Plans": [ + { + "Node Type": "Index Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Scan Direction": "Forward", + "Index Name": "experiment_history_idx", + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.42, + "Total Cost": 11541.96, + "Plan Rows": 79485, + "Plan Width": 266, + "Actual Startup Time": 0.026, + "Actual Total Time": 0.037, + "Actual Rows": 51, + "Actual Loops": 1, + "Index Cond": "((chat_id = '00000000-0000-4000-8000-000000000001'::uuid) AND (ROW(created_at, id) > ROW(('2026-01-01 00:00:00+00'::timestamp with time zone + '00:00:00'::interval), '00000000-0000-0000-0000-000000000000'::uuid)))", + "Rows Removed by Index Recheck": 0, + "Shared Hit Blocks": 2, + "Shared Read Blocks": 3, + "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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0 + } + ] + }, + "Planning": { + "Shared Hit Blocks": 112, + "Shared Read Blocks": 1, + "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.407, + "Triggers": [], + "Execution Time": 0.081 + }, + { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 0.42, + "Total Cost": 7.83, + "Plan Rows": 51, + "Plan Width": 266, + "Actual Startup Time": 0.014, + "Actual Total Time": 0.025, + "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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0, + "Plans": [ + { + "Node Type": "Index Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Scan Direction": "Forward", + "Index Name": "experiment_history_idx", + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.42, + "Total Cost": 11541.96, + "Plan Rows": 79485, + "Plan Width": 266, + "Actual Startup Time": 0.013, + "Actual Total Time": 0.023, + "Actual Rows": 51, + "Actual Loops": 1, + "Index Cond": "((chat_id = '00000000-0000-4000-8000-000000000001'::uuid) AND (ROW(created_at, id) > ROW(('2026-01-01 00:00:00+00'::timestamp with time zone + '00:00:00'::interval), '00000000-0000-0000-0000-000000000000'::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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0 + } + ] + }, + "Planning": { + "Shared Hit Blocks": 113, + "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.336, + "Triggers": [], + "Execution Time": 0.053 + }, + { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 0.42, + "Total Cost": 7.83, + "Plan Rows": 51, + "Plan Width": 266, + "Actual Startup Time": 0.014, + "Actual Total Time": 0.026, + "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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0, + "Plans": [ + { + "Node Type": "Index Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Scan Direction": "Forward", + "Index Name": "experiment_history_idx", + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.42, + "Total Cost": 11541.96, + "Plan Rows": 79485, + "Plan Width": 266, + "Actual Startup Time": 0.014, + "Actual Total Time": 0.024, + "Actual Rows": 51, + "Actual Loops": 1, + "Index Cond": "((chat_id = '00000000-0000-4000-8000-000000000001'::uuid) AND (ROW(created_at, id) > ROW(('2026-01-01 00:00:00+00'::timestamp with time zone + '00:00:00'::interval), '00000000-0000-0000-0000-000000000000'::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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0 + } + ] + }, + "Planning": { + "Shared Hit Blocks": 113, + "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.324, + "Triggers": [], + "Execution Time": 0.054 + } + ], + "runs": [ + { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 1\nnumber of threads: 1\nmaximum number of tries: 1\nnumber of transactions per client: 100\nnumber of transactions actually processed: 100/100\nnumber of failed transactions: 0 (0.000%)\nlatency average = 0.089 ms\ninitial connection time = 1.137 ms\ntps = 11188.185276 (without initial connection time)\n", + "latency_avg_ms": 0.089, + "tps": 11188.185276, + "errors": 0 + }, + { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 1\nnumber of threads: 1\nmaximum number of tries: 1\nnumber of transactions per client: 100\nnumber of transactions actually processed: 100/100\nnumber of failed transactions: 0 (0.000%)\nlatency average = 0.089 ms\ninitial connection time = 1.395 ms\ntps = 11294.330246 (without initial connection time)\n", + "latency_avg_ms": 0.089, + "tps": 11294.330246, + "errors": 0 + }, + { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 1\nnumber of threads: 1\nmaximum number of tries: 1\nnumber of transactions per client: 100\nnumber of transactions actually processed: 100/100\nnumber of failed transactions: 0 (0.000%)\nlatency average = 0.091 ms\ninitial connection time = 1.179 ms\ntps = 10942.116205 (without initial connection time)\n", + "latency_avg_ms": 0.091, + "tps": 10942.116205, + "errors": 0 + } + ], + "median_execution_ms": 0.054, + "median_latency_ms": 0.089, + "median_tps": 11188.185276, + "errors": 0 + }, + { + "chat_messages": 80000, + "position": "first", + "clients": 4, + "plans": [], + "runs": [ + { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 4\nnumber of threads: 4\nmaximum number of tries: 1\nnumber of transactions per client: 100\nnumber of transactions actually processed: 400/400\nnumber of failed transactions: 0 (0.000%)\nlatency average = 0.150 ms\ninitial connection time = 1.858 ms\ntps = 26650.676261 (without initial connection time)\n", + "latency_avg_ms": 0.15, + "tps": 26650.676261, + "errors": 0 + }, + { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 4\nnumber of threads: 4\nmaximum number of tries: 1\nnumber of transactions per client: 100\nnumber of transactions actually processed: 400/400\nnumber of failed transactions: 0 (0.000%)\nlatency average = 0.159 ms\ninitial connection time = 1.658 ms\ntps = 25128.785023 (without initial connection time)\n", + "latency_avg_ms": 0.159, + "tps": 25128.785023, + "errors": 0 + }, + { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 4\nnumber of threads: 4\nmaximum number of tries: 1\nnumber of transactions per client: 100\nnumber of transactions actually processed: 400/400\nnumber of failed transactions: 0 (0.000%)\nlatency average = 0.151 ms\ninitial connection time = 1.791 ms\ntps = 26470.782873 (without initial connection time)\n", + "latency_avg_ms": 0.151, + "tps": 26470.782873, + "errors": 0 + } + ], + "median_execution_ms": 0.054, + "median_latency_ms": 0.151, + "median_tps": 26470.782873, + "errors": 0 + }, + { + "chat_messages": 80000, + "position": "deep", + "clients": 1, + "plans": [ + { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 0.42, + "Total Cost": 47.2, + "Plan Rows": 51, + "Plan Width": 266, + "Actual Startup Time": 0.039, + "Actual Total Time": 0.052, + "Actual Rows": 51, + "Actual Loops": 1, + "Shared Hit Blocks": 4, + "Shared Read Blocks": 2, + "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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0, + "Plans": [ + { + "Node Type": "Index Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Scan Direction": "Forward", + "Index Name": "experiment_history_idx", + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.42, + "Total Cost": 5646.66, + "Plan Rows": 6155, + "Plan Width": 266, + "Actual Startup Time": 0.039, + "Actual Total Time": 0.049, + "Actual Rows": 51, + "Actual Loops": 1, + "Index Cond": "((chat_id = '00000000-0000-4000-8000-000000000001'::uuid) AND (ROW(created_at, id) > ROW(('2026-01-01 00:00:00+00'::timestamp with time zone + '00:00:00.072'::interval), '00000000-0000-0000-0000-000000000000'::uuid)))", + "Rows Removed by Index Recheck": 0, + "Shared Hit Blocks": 4, + "Shared Read Blocks": 2, + "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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0 + } + ] + }, + "Planning": { + "Shared Hit Blocks": 113, + "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.298, + "Triggers": [], + "Execution Time": 0.08 + }, + { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 0.42, + "Total Cost": 47.2, + "Plan Rows": 51, + "Plan Width": 266, + "Actual Startup Time": 0.021, + "Actual Total Time": 0.031, + "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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0, + "Plans": [ + { + "Node Type": "Index Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Scan Direction": "Forward", + "Index Name": "experiment_history_idx", + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.42, + "Total Cost": 5646.66, + "Plan Rows": 6155, + "Plan Width": 266, + "Actual Startup Time": 0.02, + "Actual Total Time": 0.029, + "Actual Rows": 51, + "Actual Loops": 1, + "Index Cond": "((chat_id = '00000000-0000-4000-8000-000000000001'::uuid) AND (ROW(created_at, id) > ROW(('2026-01-01 00:00:00+00'::timestamp with time zone + '00:00:00.072'::interval), '00000000-0000-0000-0000-000000000000'::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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0 + } + ] + }, + "Planning": { + "Shared Hit Blocks": 113, + "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.312, + "Triggers": [], + "Execution Time": 0.057 + }, + { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 0.42, + "Total Cost": 47.2, + "Plan Rows": 51, + "Plan Width": 266, + "Actual Startup Time": 0.022, + "Actual Total Time": 0.034, + "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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0, + "Plans": [ + { + "Node Type": "Index Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Scan Direction": "Forward", + "Index Name": "experiment_history_idx", + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.42, + "Total Cost": 5646.66, + "Plan Rows": 6155, + "Plan Width": 266, + "Actual Startup Time": 0.021, + "Actual Total Time": 0.032, + "Actual Rows": 51, + "Actual Loops": 1, + "Index Cond": "((chat_id = '00000000-0000-4000-8000-000000000001'::uuid) AND (ROW(created_at, id) > ROW(('2026-01-01 00:00:00+00'::timestamp with time zone + '00:00:00.072'::interval), '00000000-0000-0000-0000-000000000000'::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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0 + } + ] + }, + "Planning": { + "Shared Hit Blocks": 113, + "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.281, + "Triggers": [], + "Execution Time": 0.06 + } + ], + "runs": [ + { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 1\nnumber of threads: 1\nmaximum number of tries: 1\nnumber of transactions per client: 100\nnumber of transactions actually processed: 100/100\nnumber of failed transactions: 0 (0.000%)\nlatency average = 0.091 ms\ninitial connection time = 1.064 ms\ntps = 10990.218705 (without initial connection time)\n", + "latency_avg_ms": 0.091, + "tps": 10990.218705, + "errors": 0 + }, + { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 1\nnumber of threads: 1\nmaximum number of tries: 1\nnumber of transactions per client: 100\nnumber of transactions actually processed: 100/100\nnumber of failed transactions: 0 (0.000%)\nlatency average = 0.090 ms\ninitial connection time = 1.377 ms\ntps = 11144.544745 (without initial connection time)\n", + "latency_avg_ms": 0.09, + "tps": 11144.544745, + "errors": 0 + }, + { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 1\nnumber of threads: 1\nmaximum number of tries: 1\nnumber of transactions per client: 100\nnumber of transactions actually processed: 100/100\nnumber of failed transactions: 0 (0.000%)\nlatency average = 0.088 ms\ninitial connection time = 1.066 ms\ntps = 11380.448390 (without initial connection time)\n", + "latency_avg_ms": 0.088, + "tps": 11380.44839, + "errors": 0 + } + ], + "median_execution_ms": 0.06, + "median_latency_ms": 0.09, + "median_tps": 11144.544745, + "errors": 0 + }, + { + "chat_messages": 80000, + "position": "deep", + "clients": 4, + "plans": [], + "runs": [ + { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 4\nnumber of threads: 4\nmaximum number of tries: 1\nnumber of transactions per client: 100\nnumber of transactions actually processed: 400/400\nnumber of failed transactions: 0 (0.000%)\nlatency average = 0.155 ms\ninitial connection time = 1.570 ms\ntps = 25769.875016 (without initial connection time)\n", + "latency_avg_ms": 0.155, + "tps": 25769.875016, + "errors": 0 + }, + { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 4\nnumber of threads: 4\nmaximum number of tries: 1\nnumber of transactions per client: 100\nnumber of transactions actually processed: 400/400\nnumber of failed transactions: 0 (0.000%)\nlatency average = 0.158 ms\ninitial connection time = 1.834 ms\ntps = 25391.988828 (without initial connection time)\n", + "latency_avg_ms": 0.158, + "tps": 25391.988828, + "errors": 0 + }, + { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 4\nnumber of threads: 4\nmaximum number of tries: 1\nnumber of transactions per client: 100\nnumber of transactions actually processed: 400/400\nnumber of failed transactions: 0 (0.000%)\nlatency average = 0.171 ms\ninitial connection time = 1.751 ms\ntps = 23421.946364 (without initial connection time)\n", + "latency_avg_ms": 0.171, + "tps": 23421.946364, + "errors": 0 + } + ], + "median_execution_ms": 0.06, + "median_latency_ms": 0.158, + "median_tps": 25391.988828, + "errors": 0 + }, + { + "chat_messages": 15000, + "position": "first", + "clients": 1, + "plans": [ + { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 0.42, + "Total Cost": 21.61, + "Plan Rows": 51, + "Plan Width": 266, + "Actual Startup Time": 0.044, + "Actual Total Time": 0.055, + "Actual Rows": 51, + "Actual Loops": 1, + "Shared Hit Blocks": 5, + "Shared Read Blocks": 1, + "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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0, + "Plans": [ + { + "Node Type": "Index Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Scan Direction": "Forward", + "Index Name": "experiment_history_idx", + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.42, + "Total Cost": 6390.04, + "Plan Rows": 15382, + "Plan Width": 266, + "Actual Startup Time": 0.042, + "Actual Total Time": 0.052, + "Actual Rows": 51, + "Actual Loops": 1, + "Index Cond": "((chat_id = '00000000-0000-4000-8000-000000000002'::uuid) AND (ROW(created_at, id) > ROW(('2026-01-01 00:00:00+00'::timestamp with time zone + '00:00:00'::interval), '00000000-0000-0000-0000-000000000000'::uuid)))", + "Rows Removed by Index Recheck": 0, + "Shared Hit Blocks": 5, + "Shared Read Blocks": 1, + "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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0 + } + ] + }, + "Planning": { + "Shared Hit Blocks": 113, + "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.312, + "Triggers": [], + "Execution Time": 0.081 + }, + { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 0.42, + "Total Cost": 21.61, + "Plan Rows": 51, + "Plan Width": 266, + "Actual Startup Time": 0.019, + "Actual Total Time": 0.03, + "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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0, + "Plans": [ + { + "Node Type": "Index Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Scan Direction": "Forward", + "Index Name": "experiment_history_idx", + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.42, + "Total Cost": 6390.04, + "Plan Rows": 15382, + "Plan Width": 266, + "Actual Startup Time": 0.019, + "Actual Total Time": 0.027, + "Actual Rows": 51, + "Actual Loops": 1, + "Index Cond": "((chat_id = '00000000-0000-4000-8000-000000000002'::uuid) AND (ROW(created_at, id) > ROW(('2026-01-01 00:00:00+00'::timestamp with time zone + '00:00:00'::interval), '00000000-0000-0000-0000-000000000000'::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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0 + } + ] + }, + "Planning": { + "Shared Hit Blocks": 113, + "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.302, + "Triggers": [], + "Execution Time": 0.063 + }, + { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 0.42, + "Total Cost": 21.61, + "Plan Rows": 51, + "Plan Width": 266, + "Actual Startup Time": 0.024, + "Actual Total Time": 0.036, + "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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0, + "Plans": [ + { + "Node Type": "Index Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Scan Direction": "Forward", + "Index Name": "experiment_history_idx", + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.42, + "Total Cost": 6390.04, + "Plan Rows": 15382, + "Plan Width": 266, + "Actual Startup Time": 0.023, + "Actual Total Time": 0.033, + "Actual Rows": 51, + "Actual Loops": 1, + "Index Cond": "((chat_id = '00000000-0000-4000-8000-000000000002'::uuid) AND (ROW(created_at, id) > ROW(('2026-01-01 00:00:00+00'::timestamp with time zone + '00:00:00'::interval), '00000000-0000-0000-0000-000000000000'::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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0 + } + ] + }, + "Planning": { + "Shared Hit Blocks": 113, + "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.346, + "Triggers": [], + "Execution Time": 0.064 + } + ], + "runs": [ + { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 1\nnumber of threads: 1\nmaximum number of tries: 1\nnumber of transactions per client: 100\nnumber of transactions actually processed: 100/100\nnumber of failed transactions: 0 (0.000%)\nlatency average = 0.090 ms\ninitial connection time = 1.206 ms\ntps = 11156.978690 (without initial connection time)\n", + "latency_avg_ms": 0.09, + "tps": 11156.97869, + "errors": 0 + }, + { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 1\nnumber of threads: 1\nmaximum number of tries: 1\nnumber of transactions per client: 100\nnumber of transactions actually processed: 100/100\nnumber of failed transactions: 0 (0.000%)\nlatency average = 0.093 ms\ninitial connection time = 1.271 ms\ntps = 10770.059235 (without initial connection time)\n", + "latency_avg_ms": 0.093, + "tps": 10770.059235, + "errors": 0 + }, + { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 1\nnumber of threads: 1\nmaximum number of tries: 1\nnumber of transactions per client: 100\nnumber of transactions actually processed: 100/100\nnumber of failed transactions: 0 (0.000%)\nlatency average = 0.089 ms\ninitial connection time = 1.169 ms\ntps = 11227.124733 (without initial connection time)\n", + "latency_avg_ms": 0.089, + "tps": 11227.124733, + "errors": 0 + } + ], + "median_execution_ms": 0.064, + "median_latency_ms": 0.09, + "median_tps": 11156.97869, + "errors": 0 + }, + { + "chat_messages": 15000, + "position": "first", + "clients": 4, + "plans": [], + "runs": [ + { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 4\nnumber of threads: 4\nmaximum number of tries: 1\nnumber of transactions per client: 100\nnumber of transactions actually processed: 400/400\nnumber of failed transactions: 0 (0.000%)\nlatency average = 0.153 ms\ninitial connection time = 1.821 ms\ntps = 26079.019429 (without initial connection time)\n", + "latency_avg_ms": 0.153, + "tps": 26079.019429, + "errors": 0 + }, + { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 4\nnumber of threads: 4\nmaximum number of tries: 1\nnumber of transactions per client: 100\nnumber of transactions actually processed: 400/400\nnumber of failed transactions: 0 (0.000%)\nlatency average = 0.163 ms\ninitial connection time = 1.720 ms\ntps = 24545.900835 (without initial connection time)\n", + "latency_avg_ms": 0.163, + "tps": 24545.900835, + "errors": 0 + }, + { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 4\nnumber of threads: 4\nmaximum number of tries: 1\nnumber of transactions per client: 100\nnumber of transactions actually processed: 400/400\nnumber of failed transactions: 0 (0.000%)\nlatency average = 0.158 ms\ninitial connection time = 1.829 ms\ntps = 25258.903764 (without initial connection time)\n", + "latency_avg_ms": 0.158, + "tps": 25258.903764, + "errors": 0 + } + ], + "median_execution_ms": 0.064, + "median_latency_ms": 0.158, + "median_tps": 25258.903764, + "errors": 0 + }, + { + "chat_messages": 15000, + "position": "deep", + "clients": 1, + "plans": [ + { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 0.42, + "Total Cost": 29.86, + "Plan Rows": 51, + "Plan Width": 266, + "Actual Startup Time": 0.049, + "Actual Total Time": 0.069, + "Actual Rows": 51, + "Actual Loops": 1, + "Shared Hit Blocks": 4, + "Shared Read Blocks": 3, + "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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0, + "Plans": [ + { + "Node Type": "Index Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Scan Direction": "Forward", + "Index Name": "experiment_history_idx", + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.42, + "Total Cost": 5983.12, + "Plan Rows": 10363, + "Plan Width": 266, + "Actual Startup Time": 0.048, + "Actual Total Time": 0.066, + "Actual Rows": 51, + "Actual Loops": 1, + "Index Cond": "((chat_id = '00000000-0000-4000-8000-000000000002'::uuid) AND (ROW(created_at, id) > ROW(('2026-01-01 00:00:00+00'::timestamp with time zone + '00:00:00.0135'::interval), '00000000-0000-0000-0000-000000000000'::uuid)))", + "Rows Removed by Index Recheck": 0, + "Shared Hit Blocks": 4, + "Shared Read Blocks": 3, + "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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0 + } + ] + }, + "Planning": { + "Shared Hit Blocks": 113, + "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.321, + "Triggers": [], + "Execution Time": 0.096 + }, + { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 0.42, + "Total Cost": 29.86, + "Plan Rows": 51, + "Plan Width": 266, + "Actual Startup Time": 0.016, + "Actual Total Time": 0.033, + "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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0, + "Plans": [ + { + "Node Type": "Index Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Scan Direction": "Forward", + "Index Name": "experiment_history_idx", + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.42, + "Total Cost": 5983.12, + "Plan Rows": 10363, + "Plan Width": 266, + "Actual Startup Time": 0.015, + "Actual Total Time": 0.03, + "Actual Rows": 51, + "Actual Loops": 1, + "Index Cond": "((chat_id = '00000000-0000-4000-8000-000000000002'::uuid) AND (ROW(created_at, id) > ROW(('2026-01-01 00:00:00+00'::timestamp with time zone + '00:00:00.0135'::interval), '00000000-0000-0000-0000-000000000000'::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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0 + } + ] + }, + "Planning": { + "Shared Hit Blocks": 113, + "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.321, + "Triggers": [], + "Execution Time": 0.059 + }, + { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 0.42, + "Total Cost": 29.86, + "Plan Rows": 51, + "Plan Width": 266, + "Actual Startup Time": 0.019, + "Actual Total Time": 0.04, + "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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0, + "Plans": [ + { + "Node Type": "Index Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Scan Direction": "Forward", + "Index Name": "experiment_history_idx", + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.42, + "Total Cost": 5983.12, + "Plan Rows": 10363, + "Plan Width": 266, + "Actual Startup Time": 0.019, + "Actual Total Time": 0.037, + "Actual Rows": 51, + "Actual Loops": 1, + "Index Cond": "((chat_id = '00000000-0000-4000-8000-000000000002'::uuid) AND (ROW(created_at, id) > ROW(('2026-01-01 00:00:00+00'::timestamp with time zone + '00:00:00.0135'::interval), '00000000-0000-0000-0000-000000000000'::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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0 + } + ] + }, + "Planning": { + "Shared Hit Blocks": 113, + "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.388, + "Triggers": [], + "Execution Time": 0.07 + } + ], + "runs": [ + { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 1\nnumber of threads: 1\nmaximum number of tries: 1\nnumber of transactions per client: 100\nnumber of transactions actually processed: 100/100\nnumber of failed transactions: 0 (0.000%)\nlatency average = 0.093 ms\ninitial connection time = 1.317 ms\ntps = 10697.475396 (without initial connection time)\n", + "latency_avg_ms": 0.093, + "tps": 10697.475396, + "errors": 0 + }, + { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 1\nnumber of threads: 1\nmaximum number of tries: 1\nnumber of transactions per client: 100\nnumber of transactions actually processed: 100/100\nnumber of failed transactions: 0 (0.000%)\nlatency average = 0.095 ms\ninitial connection time = 1.332 ms\ntps = 10493.179433 (without initial connection time)\n", + "latency_avg_ms": 0.095, + "tps": 10493.179433, + "errors": 0 + }, + { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 1\nnumber of threads: 1\nmaximum number of tries: 1\nnumber of transactions per client: 100\nnumber of transactions actually processed: 100/100\nnumber of failed transactions: 0 (0.000%)\nlatency average = 0.095 ms\ninitial connection time = 1.396 ms\ntps = 10549.636038 (without initial connection time)\n", + "latency_avg_ms": 0.095, + "tps": 10549.636038, + "errors": 0 + } + ], + "median_execution_ms": 0.07, + "median_latency_ms": 0.095, + "median_tps": 10549.636038, + "errors": 0 + }, + { + "chat_messages": 15000, + "position": "deep", + "clients": 4, + "plans": [], + "runs": [ + { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 4\nnumber of threads: 4\nmaximum number of tries: 1\nnumber of transactions per client: 100\nnumber of transactions actually processed: 400/400\nnumber of failed transactions: 0 (0.000%)\nlatency average = 0.179 ms\ninitial connection time = 1.867 ms\ntps = 22355.110937 (without initial connection time)\n", + "latency_avg_ms": 0.179, + "tps": 22355.110937, + "errors": 0 + }, + { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 4\nnumber of threads: 4\nmaximum number of tries: 1\nnumber of transactions per client: 100\nnumber of transactions actually processed: 400/400\nnumber of failed transactions: 0 (0.000%)\nlatency average = 0.164 ms\ninitial connection time = 2.036 ms\ntps = 24385.783088 (without initial connection time)\n", + "latency_avg_ms": 0.164, + "tps": 24385.783088, + "errors": 0 + }, + { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 4\nnumber of threads: 4\nmaximum number of tries: 1\nnumber of transactions per client: 100\nnumber of transactions actually processed: 400/400\nnumber of failed transactions: 0 (0.000%)\nlatency average = 0.161 ms\ninitial connection time = 1.868 ms\ntps = 24823.135162 (without initial connection time)\n", + "latency_avg_ms": 0.161, + "tps": 24823.135162, + "errors": 0 + } + ], + "median_execution_ms": 0.07, + "median_latency_ms": 0.164, + "median_tps": 24385.783088, + "errors": 0 + }, + { + "chat_messages": 4900, + "position": "first", + "clients": 1, + "plans": [ + { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 0.42, + "Total Cost": 52.76, + "Plan Rows": 51, + "Plan Width": 266, + "Actual Startup Time": 0.042, + "Actual Total Time": 0.051, + "Actual Rows": 51, + "Actual Loops": 1, + "Shared Hit Blocks": 5, + "Shared Read Blocks": 1, + "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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0, + "Plans": [ + { + "Node Type": "Index Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Scan Direction": "Forward", + "Index Name": "experiment_history_idx", + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.42, + "Total Cost": 5147.92, + "Plan Rows": 5016, + "Plan Width": 266, + "Actual Startup Time": 0.041, + "Actual Total Time": 0.049, + "Actual Rows": 51, + "Actual Loops": 1, + "Index Cond": "((chat_id = '00000000-0000-4000-8000-000000000003'::uuid) AND (ROW(created_at, id) > ROW(('2026-01-01 00:00:00+00'::timestamp with time zone + '00:00:00'::interval), '00000000-0000-0000-0000-000000000000'::uuid)))", + "Rows Removed by Index Recheck": 0, + "Shared Hit Blocks": 5, + "Shared Read Blocks": 1, + "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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0 + } + ] + }, + "Planning": { + "Shared Hit Blocks": 113, + "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.347, + "Triggers": [], + "Execution Time": 0.079 + }, + { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 0.42, + "Total Cost": 52.76, + "Plan Rows": 51, + "Plan Width": 266, + "Actual Startup Time": 0.03, + "Actual Total Time": 0.039, + "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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0, + "Plans": [ + { + "Node Type": "Index Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Scan Direction": "Forward", + "Index Name": "experiment_history_idx", + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.42, + "Total Cost": 5147.92, + "Plan Rows": 5016, + "Plan Width": 266, + "Actual Startup Time": 0.029, + "Actual Total Time": 0.037, + "Actual Rows": 51, + "Actual Loops": 1, + "Index Cond": "((chat_id = '00000000-0000-4000-8000-000000000003'::uuid) AND (ROW(created_at, id) > ROW(('2026-01-01 00:00:00+00'::timestamp with time zone + '00:00:00'::interval), '00000000-0000-0000-0000-000000000000'::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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0 + } + ] + }, + "Planning": { + "Shared Hit Blocks": 113, + "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.368, + "Triggers": [], + "Execution Time": 0.086 + }, + { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 0.42, + "Total Cost": 52.76, + "Plan Rows": 51, + "Plan Width": 266, + "Actual Startup Time": 0.02, + "Actual Total Time": 0.032, + "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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0, + "Plans": [ + { + "Node Type": "Index Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Scan Direction": "Forward", + "Index Name": "experiment_history_idx", + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.42, + "Total Cost": 5147.92, + "Plan Rows": 5016, + "Plan Width": 266, + "Actual Startup Time": 0.02, + "Actual Total Time": 0.029, + "Actual Rows": 51, + "Actual Loops": 1, + "Index Cond": "((chat_id = '00000000-0000-4000-8000-000000000003'::uuid) AND (ROW(created_at, id) > ROW(('2026-01-01 00:00:00+00'::timestamp with time zone + '00:00:00'::interval), '00000000-0000-0000-0000-000000000000'::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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0 + } + ] + }, + "Planning": { + "Shared Hit Blocks": 113, + "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.372, + "Triggers": [], + "Execution Time": 0.062 + } + ], + "runs": [ + { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 1\nnumber of threads: 1\nmaximum number of tries: 1\nnumber of transactions per client: 100\nnumber of transactions actually processed: 100/100\nnumber of failed transactions: 0 (0.000%)\nlatency average = 0.093 ms\ninitial connection time = 0.939 ms\ntps = 10775.862069 (without initial connection time)\n", + "latency_avg_ms": 0.093, + "tps": 10775.862069, + "errors": 0 + }, + { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 1\nnumber of threads: 1\nmaximum number of tries: 1\nnumber of transactions per client: 100\nnumber of transactions actually processed: 100/100\nnumber of failed transactions: 0 (0.000%)\nlatency average = 0.088 ms\ninitial connection time = 1.090 ms\ntps = 11424.654404 (without initial connection time)\n", + "latency_avg_ms": 0.088, + "tps": 11424.654404, + "errors": 0 + }, + { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 1\nnumber of threads: 1\nmaximum number of tries: 1\nnumber of transactions per client: 100\nnumber of transactions actually processed: 100/100\nnumber of failed transactions: 0 (0.000%)\nlatency average = 0.090 ms\ninitial connection time = 1.063 ms\ntps = 11108.642524 (without initial connection time)\n", + "latency_avg_ms": 0.09, + "tps": 11108.642524, + "errors": 0 + } + ], + "median_execution_ms": 0.079, + "median_latency_ms": 0.09, + "median_tps": 11108.642524, + "errors": 0 + }, + { + "chat_messages": 4900, + "position": "first", + "clients": 4, + "plans": [], + "runs": [ + { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 4\nnumber of threads: 4\nmaximum number of tries: 1\nnumber of transactions per client: 100\nnumber of transactions actually processed: 400/400\nnumber of failed transactions: 0 (0.000%)\nlatency average = 0.160 ms\ninitial connection time = 2.093 ms\ntps = 25023.459493 (without initial connection time)\n", + "latency_avg_ms": 0.16, + "tps": 25023.459493, + "errors": 0 + }, + { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 4\nnumber of threads: 4\nmaximum number of tries: 1\nnumber of transactions per client: 100\nnumber of transactions actually processed: 400/400\nnumber of failed transactions: 0 (0.000%)\nlatency average = 0.163 ms\ninitial connection time = 1.981 ms\ntps = 24582.104228 (without initial connection time)\n", + "latency_avg_ms": 0.163, + "tps": 24582.104228, + "errors": 0 + }, + { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 4\nnumber of threads: 4\nmaximum number of tries: 1\nnumber of transactions per client: 100\nnumber of transactions actually processed: 400/400\nnumber of failed transactions: 0 (0.000%)\nlatency average = 0.164 ms\ninitial connection time = 2.621 ms\ntps = 24327.940640 (without initial connection time)\n", + "latency_avg_ms": 0.164, + "tps": 24327.94064, + "errors": 0 + } + ], + "median_execution_ms": 0.079, + "median_latency_ms": 0.163, + "median_tps": 24582.104228, + "errors": 0 + }, + { + "chat_messages": 4900, + "position": "deep", + "clients": 1, + "plans": [ + { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 0.42, + "Total Cost": 55.93, + "Plan Rows": 51, + "Plan Width": 266, + "Actual Startup Time": 0.043, + "Actual Total Time": 0.068, + "Actual Rows": 51, + "Actual Loops": 1, + "Shared Hit Blocks": 5, + "Shared Read Blocks": 1, + "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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0, + "Plans": [ + { + "Node Type": "Index Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Scan Direction": "Forward", + "Index Name": "experiment_history_idx", + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.42, + "Total Cost": 4725.54, + "Plan Rows": 4341, + "Plan Width": 266, + "Actual Startup Time": 0.042, + "Actual Total Time": 0.064, + "Actual Rows": 51, + "Actual Loops": 1, + "Index Cond": "((chat_id = '00000000-0000-4000-8000-000000000003'::uuid) AND (ROW(created_at, id) > ROW(('2026-01-01 00:00:00+00'::timestamp with time zone + '00:00:00.00441'::interval), '00000000-0000-0000-0000-000000000000'::uuid)))", + "Rows Removed by Index Recheck": 0, + "Shared Hit Blocks": 5, + "Shared Read Blocks": 1, + "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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0 + } + ] + }, + "Planning": { + "Shared Hit Blocks": 113, + "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.37, + "Triggers": [], + "Execution Time": 0.095 + }, + { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 0.42, + "Total Cost": 55.93, + "Plan Rows": 51, + "Plan Width": 266, + "Actual Startup Time": 0.022, + "Actual Total Time": 0.036, + "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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0, + "Plans": [ + { + "Node Type": "Index Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Scan Direction": "Forward", + "Index Name": "experiment_history_idx", + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.42, + "Total Cost": 4725.54, + "Plan Rows": 4341, + "Plan Width": 266, + "Actual Startup Time": 0.021, + "Actual Total Time": 0.032, + "Actual Rows": 51, + "Actual Loops": 1, + "Index Cond": "((chat_id = '00000000-0000-4000-8000-000000000003'::uuid) AND (ROW(created_at, id) > ROW(('2026-01-01 00:00:00+00'::timestamp with time zone + '00:00:00.00441'::interval), '00000000-0000-0000-0000-000000000000'::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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0 + } + ] + }, + "Planning": { + "Shared Hit Blocks": 113, + "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.351, + "Triggers": [], + "Execution Time": 0.069 + }, + { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 0.42, + "Total Cost": 55.93, + "Plan Rows": 51, + "Plan Width": 266, + "Actual Startup Time": 0.025, + "Actual Total Time": 0.039, + "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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0, + "Plans": [ + { + "Node Type": "Index Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Scan Direction": "Forward", + "Index Name": "experiment_history_idx", + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.42, + "Total Cost": 4725.54, + "Plan Rows": 4341, + "Plan Width": 266, + "Actual Startup Time": 0.024, + "Actual Total Time": 0.037, + "Actual Rows": 51, + "Actual Loops": 1, + "Index Cond": "((chat_id = '00000000-0000-4000-8000-000000000003'::uuid) AND (ROW(created_at, id) > ROW(('2026-01-01 00:00:00+00'::timestamp with time zone + '00:00:00.00441'::interval), '00000000-0000-0000-0000-000000000000'::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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0 + } + ] + }, + "Planning": { + "Shared Hit Blocks": 113, + "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.328, + "Triggers": [], + "Execution Time": 0.067 + } + ], + "runs": [ + { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 1\nnumber of threads: 1\nmaximum number of tries: 1\nnumber of transactions per client: 100\nnumber of transactions actually processed: 100/100\nnumber of failed transactions: 0 (0.000%)\nlatency average = 0.096 ms\ninitial connection time = 1.255 ms\ntps = 10444.955087 (without initial connection time)\n", + "latency_avg_ms": 0.096, + "tps": 10444.955087, + "errors": 0 + }, + { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 1\nnumber of threads: 1\nmaximum number of tries: 1\nnumber of transactions per client: 100\nnumber of transactions actually processed: 100/100\nnumber of failed transactions: 0 (0.000%)\nlatency average = 0.089 ms\ninitial connection time = 1.140 ms\ntps = 11223.344557 (without initial connection time)\n", + "latency_avg_ms": 0.089, + "tps": 11223.344557, + "errors": 0 + }, + { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 1\nnumber of threads: 1\nmaximum number of tries: 1\nnumber of transactions per client: 100\nnumber of transactions actually processed: 100/100\nnumber of failed transactions: 0 (0.000%)\nlatency average = 0.092 ms\ninitial connection time = 1.174 ms\ntps = 10917.030568 (without initial connection time)\n", + "latency_avg_ms": 0.092, + "tps": 10917.030568, + "errors": 0 + } + ], + "median_execution_ms": 0.069, + "median_latency_ms": 0.092, + "median_tps": 10917.030568, + "errors": 0 + }, + { + "chat_messages": 4900, + "position": "deep", + "clients": 4, + "plans": [], + "runs": [ + { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 4\nnumber of threads: 4\nmaximum number of tries: 1\nnumber of transactions per client: 100\nnumber of transactions actually processed: 400/400\nnumber of failed transactions: 0 (0.000%)\nlatency average = 0.165 ms\ninitial connection time = 1.928 ms\ntps = 24188.184072 (without initial connection time)\n", + "latency_avg_ms": 0.165, + "tps": 24188.184072, + "errors": 0 + }, + { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 4\nnumber of threads: 4\nmaximum number of tries: 1\nnumber of transactions per client: 100\nnumber of transactions actually processed: 400/400\nnumber of failed transactions: 0 (0.000%)\nlatency average = 0.166 ms\ninitial connection time = 2.037 ms\ntps = 24087.679152 (without initial connection time)\n", + "latency_avg_ms": 0.166, + "tps": 24087.679152, + "errors": 0 + }, + { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 4\nnumber of threads: 4\nmaximum number of tries: 1\nnumber of transactions per client: 100\nnumber of transactions actually processed: 400/400\nnumber of failed transactions: 0 (0.000%)\nlatency average = 0.161 ms\ninitial connection time = 2.101 ms\ntps = 24775.472282 (without initial connection time)\n", + "latency_avg_ms": 0.161, + "tps": 24775.472282, + "errors": 0 + } + ], + "median_execution_ms": 0.069, + "median_latency_ms": 0.165, + "median_tps": 24188.184072, + "errors": 0 + }, + { + "chat_messages": 100, + "position": "first", + "clients": 1, + "plans": [ + { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 0.42, + "Total Cost": 94.4, + "Plan Rows": 51, + "Plan Width": 266, + "Actual Startup Time": 0.033, + "Actual Total Time": 0.046, + "Actual Rows": 51, + "Actual Loops": 1, + "Shared Hit Blocks": 5, + "Shared Read Blocks": 1, + "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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0, + "Plans": [ + { + "Node Type": "Index Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Scan Direction": "Forward", + "Index Name": "experiment_history_idx", + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.42, + "Total Cost": 197.6, + "Plan Rows": 107, + "Plan Width": 266, + "Actual Startup Time": 0.032, + "Actual Total Time": 0.043, + "Actual Rows": 51, + "Actual Loops": 1, + "Index Cond": "((chat_id = '00000000-0000-4000-8000-000000000004'::uuid) AND (ROW(created_at, id) > ROW(('2026-01-01 00:00:00+00'::timestamp with time zone + '00:00:00'::interval), '00000000-0000-0000-0000-000000000000'::uuid)))", + "Rows Removed by Index Recheck": 0, + "Shared Hit Blocks": 5, + "Shared Read Blocks": 1, + "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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0 + } + ] + }, + "Planning": { + "Shared Hit Blocks": 113, + "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.283, + "Triggers": [], + "Execution Time": 0.076 + }, + { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 0.42, + "Total Cost": 94.4, + "Plan Rows": 51, + "Plan Width": 266, + "Actual Startup Time": 0.022, + "Actual Total Time": 0.034, + "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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0, + "Plans": [ + { + "Node Type": "Index Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Scan Direction": "Forward", + "Index Name": "experiment_history_idx", + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.42, + "Total Cost": 197.6, + "Plan Rows": 107, + "Plan Width": 266, + "Actual Startup Time": 0.021, + "Actual Total Time": 0.031, + "Actual Rows": 51, + "Actual Loops": 1, + "Index Cond": "((chat_id = '00000000-0000-4000-8000-000000000004'::uuid) AND (ROW(created_at, id) > ROW(('2026-01-01 00:00:00+00'::timestamp with time zone + '00:00:00'::interval), '00000000-0000-0000-0000-000000000000'::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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0 + } + ] + }, + "Planning": { + "Shared Hit Blocks": 113, + "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.287, + "Triggers": [], + "Execution Time": 0.062 + }, + { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 0.42, + "Total Cost": 94.4, + "Plan Rows": 51, + "Plan Width": 266, + "Actual Startup Time": 0.017, + "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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0, + "Plans": [ + { + "Node Type": "Index Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Scan Direction": "Forward", + "Index Name": "experiment_history_idx", + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.42, + "Total Cost": 197.6, + "Plan Rows": 107, + "Plan Width": 266, + "Actual Startup Time": 0.017, + "Actual Total Time": 0.024, + "Actual Rows": 51, + "Actual Loops": 1, + "Index Cond": "((chat_id = '00000000-0000-4000-8000-000000000004'::uuid) AND (ROW(created_at, id) > ROW(('2026-01-01 00:00:00+00'::timestamp with time zone + '00:00:00'::interval), '00000000-0000-0000-0000-000000000000'::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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0 + } + ] + }, + "Planning": { + "Shared Hit Blocks": 113, + "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.306, + "Triggers": [], + "Execution Time": 0.053 + } + ], + "runs": [ + { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 1\nnumber of threads: 1\nmaximum number of tries: 1\nnumber of transactions per client: 100\nnumber of transactions actually processed: 100/100\nnumber of failed transactions: 0 (0.000%)\nlatency average = 0.088 ms\ninitial connection time = 1.320 ms\ntps = 11335.298118 (without initial connection time)\n", + "latency_avg_ms": 0.088, + "tps": 11335.298118, + "errors": 0 + }, + { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 1\nnumber of threads: 1\nmaximum number of tries: 1\nnumber of transactions per client: 100\nnumber of transactions actually processed: 100/100\nnumber of failed transactions: 0 (0.000%)\nlatency average = 0.095 ms\ninitial connection time = 1.246 ms\ntps = 10509.721492 (without initial connection time)\n", + "latency_avg_ms": 0.095, + "tps": 10509.721492, + "errors": 0 + }, + { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 1\nnumber of threads: 1\nmaximum number of tries: 1\nnumber of transactions per client: 100\nnumber of transactions actually processed: 100/100\nnumber of failed transactions: 0 (0.000%)\nlatency average = 0.091 ms\ninitial connection time = 0.939 ms\ntps = 11027.790031 (without initial connection time)\n", + "latency_avg_ms": 0.091, + "tps": 11027.790031, + "errors": 0 + } + ], + "median_execution_ms": 0.062, + "median_latency_ms": 0.091, + "median_tps": 11027.790031, + "errors": 0 + }, + { + "chat_messages": 100, + "position": "first", + "clients": 4, + "plans": [], + "runs": [ + { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 4\nnumber of threads: 4\nmaximum number of tries: 1\nnumber of transactions per client: 100\nnumber of transactions actually processed: 400/400\nnumber of failed transactions: 0 (0.000%)\nlatency average = 0.162 ms\ninitial connection time = 1.886 ms\ntps = 24712.714692 (without initial connection time)\n", + "latency_avg_ms": 0.162, + "tps": 24712.714692, + "errors": 0 + }, + { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 4\nnumber of threads: 4\nmaximum number of tries: 1\nnumber of transactions per client: 100\nnumber of transactions actually processed: 400/400\nnumber of failed transactions: 0 (0.000%)\nlatency average = 0.151 ms\ninitial connection time = 1.835 ms\ntps = 26556.898154 (without initial connection time)\n", + "latency_avg_ms": 0.151, + "tps": 26556.898154, + "errors": 0 + }, + { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 4\nnumber of threads: 4\nmaximum number of tries: 1\nnumber of transactions per client: 100\nnumber of transactions actually processed: 400/400\nnumber of failed transactions: 0 (0.000%)\nlatency average = 0.155 ms\ninitial connection time = 1.772 ms\ntps = 25876.568767 (without initial connection time)\n", + "latency_avg_ms": 0.155, + "tps": 25876.568767, + "errors": 0 + } + ], + "median_execution_ms": 0.062, + "median_latency_ms": 0.155, + "median_tps": 25876.568767, + "errors": 0 + }, + { + "chat_messages": 100, + "position": "deep", + "clients": 1, + "plans": [ + { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 0.42, + "Total Cost": 94.43, + "Plan Rows": 51, + "Plan Width": 266, + "Actual Startup Time": 0.041, + "Actual Total Time": 0.043, + "Actual Rows": 11, + "Actual Loops": 1, + "Shared Hit Blocks": 3, + "Shared Read Blocks": 1, + "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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0, + "Plans": [ + { + "Node Type": "Index Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Scan Direction": "Forward", + "Index Name": "experiment_history_idx", + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.42, + "Total Cost": 195.82, + "Plan Rows": 106, + "Plan Width": 266, + "Actual Startup Time": 0.04, + "Actual Total Time": 0.042, + "Actual Rows": 11, + "Actual Loops": 1, + "Index Cond": "((chat_id = '00000000-0000-4000-8000-000000000004'::uuid) AND (ROW(created_at, id) > ROW(('2026-01-01 00:00:00+00'::timestamp with time zone + '00:00:00.00009'::interval), '00000000-0000-0000-0000-000000000000'::uuid)))", + "Rows Removed by Index Recheck": 0, + "Shared Hit Blocks": 3, + "Shared Read Blocks": 1, + "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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0 + } + ] + }, + "Planning": { + "Shared Hit Blocks": 113, + "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.31, + "Triggers": [], + "Execution Time": 0.071 + }, + { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 0.42, + "Total Cost": 94.43, + "Plan Rows": 51, + "Plan Width": 266, + "Actual Startup Time": 0.018, + "Actual Total Time": 0.021, + "Actual Rows": 11, + "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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0, + "Plans": [ + { + "Node Type": "Index Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Scan Direction": "Forward", + "Index Name": "experiment_history_idx", + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.42, + "Total Cost": 195.82, + "Plan Rows": 106, + "Plan Width": 266, + "Actual Startup Time": 0.017, + "Actual Total Time": 0.02, + "Actual Rows": 11, + "Actual Loops": 1, + "Index Cond": "((chat_id = '00000000-0000-4000-8000-000000000004'::uuid) AND (ROW(created_at, id) > ROW(('2026-01-01 00:00:00+00'::timestamp with time zone + '00:00:00.00009'::interval), '00000000-0000-0000-0000-000000000000'::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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0 + } + ] + }, + "Planning": { + "Shared Hit Blocks": 113, + "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.346, + "Triggers": [], + "Execution Time": 0.051 + }, + { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 0.42, + "Total Cost": 94.43, + "Plan Rows": 51, + "Plan Width": 266, + "Actual Startup Time": 0.016, + "Actual Total Time": 0.018, + "Actual Rows": 11, + "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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0, + "Plans": [ + { + "Node Type": "Index Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Scan Direction": "Forward", + "Index Name": "experiment_history_idx", + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.42, + "Total Cost": 195.82, + "Plan Rows": 106, + "Plan Width": 266, + "Actual Startup Time": 0.015, + "Actual Total Time": 0.017, + "Actual Rows": 11, + "Actual Loops": 1, + "Index Cond": "((chat_id = '00000000-0000-4000-8000-000000000004'::uuid) AND (ROW(created_at, id) > ROW(('2026-01-01 00:00:00+00'::timestamp with time zone + '00:00:00.00009'::interval), '00000000-0000-0000-0000-000000000000'::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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0 + } + ] + }, + "Planning": { + "Shared Hit Blocks": 113, + "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.378, + "Triggers": [], + "Execution Time": 0.043 + } + ], + "runs": [ + { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 1\nnumber of threads: 1\nmaximum number of tries: 1\nnumber of transactions per client: 100\nnumber of transactions actually processed: 100/100\nnumber of failed transactions: 0 (0.000%)\nlatency average = 0.077 ms\ninitial connection time = 1.254 ms\ntps = 12995.451592 (without initial connection time)\n", + "latency_avg_ms": 0.077, + "tps": 12995.451592, + "errors": 0 + }, + { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 1\nnumber of threads: 1\nmaximum number of tries: 1\nnumber of transactions per client: 100\nnumber of transactions actually processed: 100/100\nnumber of failed transactions: 0 (0.000%)\nlatency average = 0.081 ms\ninitial connection time = 1.450 ms\ntps = 12315.270936 (without initial connection time)\n", + "latency_avg_ms": 0.081, + "tps": 12315.270936, + "errors": 0 + }, + { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 1\nnumber of threads: 1\nmaximum number of tries: 1\nnumber of transactions per client: 100\nnumber of transactions actually processed: 100/100\nnumber of failed transactions: 0 (0.000%)\nlatency average = 0.081 ms\ninitial connection time = 1.014 ms\ntps = 12289.541600 (without initial connection time)\n", + "latency_avg_ms": 0.081, + "tps": 12289.5416, + "errors": 0 + } + ], + "median_execution_ms": 0.051, + "median_latency_ms": 0.081, + "median_tps": 12315.270936, + "errors": 0 + }, + { + "chat_messages": 100, + "position": "deep", + "clients": 4, + "plans": [], + "runs": [ + { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 4\nnumber of threads: 4\nmaximum number of tries: 1\nnumber of transactions per client: 100\nnumber of transactions actually processed: 400/400\nnumber of failed transactions: 0 (0.000%)\nlatency average = 0.104 ms\ninitial connection time = 1.559 ms\ntps = 38465.237042 (without initial connection time)\n", + "latency_avg_ms": 0.104, + "tps": 38465.237042, + "errors": 0 + }, + { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 4\nnumber of threads: 4\nmaximum number of tries: 1\nnumber of transactions per client: 100\nnumber of transactions actually processed: 400/400\nnumber of failed transactions: 0 (0.000%)\nlatency average = 0.102 ms\ninitial connection time = 1.975 ms\ntps = 39300.451955 (without initial connection time)\n", + "latency_avg_ms": 0.102, + "tps": 39300.451955, + "errors": 0 + }, + { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 4\nnumber of threads: 4\nmaximum number of tries: 1\nnumber of transactions per client: 100\nnumber of transactions actually processed: 400/400\nnumber of failed transactions: 0 (0.000%)\nlatency average = 0.106 ms\ninitial connection time = 1.770 ms\ntps = 37792.894936 (without initial connection time)\n", + "latency_avg_ms": 0.106, + "tps": 37792.894936, + "errors": 0 + } + ], + "median_execution_ms": 0.051, + "median_latency_ms": 0.104, + "median_tps": 38465.237042, + "errors": 0 + } + ], + "writes": [ + { + "repeat": 1, + "plan": { + "Plan": { + "Node Type": "ModifyTable", + "Operation": "Insert", + "Parallel Aware": false, + "Async Capable": false, + "Relation Name": "write_probe", + "Alias": "write_probe", + "Startup Cost": 0.0, + "Total Cost": 42.5, + "Plan Rows": 0, + "Plan Width": 0, + "Actual Startup Time": 3.203, + "Actual Total Time": 3.203, + "Actual Rows": 0, + "Actual Loops": 1, + "Shared Hit Blocks": 4680, + "Shared Read Blocks": 2, + "Shared Dirtied Blocks": 48, + "Shared Written Blocks": 48, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "WAL Records": 3013, + "WAL FPI": 0, + "WAL Bytes": 448576, + "Plans": [ + { + "Node Type": "Function Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Function Name": "generate_series", + "Alias": "i", + "Startup Cost": 0.0, + "Total Cost": 42.5, + "Plan Rows": 1000, + "Plan Width": 88, + "Actual Startup Time": 0.17, + "Actual Total Time": 1.091, + "Actual Rows": 1000, + "Actual Loops": 1, + "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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0 + } + ] + }, + "Planning": { + "Shared Hit Blocks": 15, + "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.127, + "Triggers": [], + "Execution Time": 3.235 + }, + "transaction": { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 1\nnumber of threads: 1\nmaximum number of tries: 1\nnumber of transactions per client: 1\nnumber of transactions actually processed: 1/1\nnumber of failed transactions: 0 (0.000%)\nlatency average = 5.672 ms\ninitial connection time = 1.309 ms\ntps = 176.304654 (without initial connection time)\n", + "latency_avg_ms": 5.672, + "tps": 176.304654, + "errors": 0 + }, + "table_bytes": 417792 + }, + { + "repeat": 2, + "plan": { + "Plan": { + "Node Type": "ModifyTable", + "Operation": "Insert", + "Parallel Aware": false, + "Async Capable": false, + "Relation Name": "write_probe", + "Alias": "write_probe", + "Startup Cost": 0.0, + "Total Cost": 42.5, + "Plan Rows": 0, + "Plan Width": 0, + "Actual Startup Time": 3.162, + "Actual Total Time": 3.162, + "Actual Rows": 0, + "Actual Loops": 1, + "Shared Hit Blocks": 4681, + "Shared Read Blocks": 2, + "Shared Dirtied Blocks": 48, + "Shared Written Blocks": 48, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "WAL Records": 3013, + "WAL FPI": 0, + "WAL Bytes": 448576, + "Plans": [ + { + "Node Type": "Function Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Function Name": "generate_series", + "Alias": "i", + "Startup Cost": 0.0, + "Total Cost": 42.5, + "Plan Rows": 1000, + "Plan Width": 88, + "Actual Startup Time": 0.169, + "Actual Total Time": 1.071, + "Actual Rows": 1000, + "Actual Loops": 1, + "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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0 + } + ] + }, + "Planning": { + "Shared Hit Blocks": 15, + "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": 3.19 + }, + "transaction": { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 1\nnumber of threads: 1\nmaximum number of tries: 1\nnumber of transactions per client: 1\nnumber of transactions actually processed: 1/1\nnumber of failed transactions: 0 (0.000%)\nlatency average = 6.118 ms\ninitial connection time = 1.299 ms\ntps = 163.452109 (without initial connection time)\n", + "latency_avg_ms": 6.118, + "tps": 163.452109, + "errors": 0 + }, + "table_bytes": 417792 + }, + { + "repeat": 3, + "plan": { + "Plan": { + "Node Type": "ModifyTable", + "Operation": "Insert", + "Parallel Aware": false, + "Async Capable": false, + "Relation Name": "write_probe", + "Alias": "write_probe", + "Startup Cost": 0.0, + "Total Cost": 42.5, + "Plan Rows": 0, + "Plan Width": 0, + "Actual Startup Time": 3.159, + "Actual Total Time": 3.159, + "Actual Rows": 0, + "Actual Loops": 1, + "Shared Hit Blocks": 4681, + "Shared Read Blocks": 2, + "Shared Dirtied Blocks": 48, + "Shared Written Blocks": 48, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "WAL Records": 3013, + "WAL FPI": 0, + "WAL Bytes": 448576, + "Plans": [ + { + "Node Type": "Function Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Function Name": "generate_series", + "Alias": "i", + "Startup Cost": 0.0, + "Total Cost": 42.5, + "Plan Rows": 1000, + "Plan Width": 88, + "Actual Startup Time": 0.166, + "Actual Total Time": 1.094, + "Actual Rows": 1000, + "Actual Loops": 1, + "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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0 + } + ] + }, + "Planning": { + "Shared Hit Blocks": 15, + "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": 3.193 + }, + "transaction": { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 1\nnumber of threads: 1\nmaximum number of tries: 1\nnumber of transactions per client: 1\nnumber of transactions actually processed: 1/1\nnumber of failed transactions: 0 (0.000%)\nlatency average = 5.915 ms\ninitial connection time = 1.189 ms\ntps = 169.061708 (without initial connection time)\n", + "latency_avg_ms": 5.915, + "tps": 169.061708, + "errors": 0 + }, + "table_bytes": 417792 + } + ], + "resources": { + "measurement_seconds": 18.197, + "cpu_percent": 16.827, + "memory_before_bytes": 345976832, + "memory_after_bytes": 351805440, + "note": "cgroup memory includes shared buffers/page cache, not API RSS; CPU window includes setup and SQL trials" + } + }, + { + "name": "covering", + "index": "(chat_id,created_at,id) INCLUDE(sender_id,text)", + "index_bytes": 25001984, + "reads": [ + { + "chat_messages": 80000, + "position": "first", + "clients": 1, + "plans": [ + { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 0.42, + "Total Cost": 8.43, + "Plan Rows": 51, + "Plan Width": 266, + "Actual Startup Time": 0.043, + "Actual Total Time": 0.058, + "Actual Rows": 51, + "Actual Loops": 1, + "Shared Hit Blocks": 1, + "Shared Read Blocks": 4, + "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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0, + "Plans": [ + { + "Node Type": "Index Only Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Scan Direction": "Forward", + "Index Name": "experiment_history_idx", + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.42, + "Total Cost": 12562.84, + "Plan Rows": 79955, + "Plan Width": 266, + "Actual Startup Time": 0.042, + "Actual Total Time": 0.054, + "Actual Rows": 51, + "Actual Loops": 1, + "Index Cond": "((chat_id = '00000000-0000-4000-8000-000000000001'::uuid) AND (ROW(created_at, id) > ROW(('2026-01-01 00:00:00+00'::timestamp with time zone + '00:00:00'::interval), '00000000-0000-0000-0000-000000000000'::uuid)))", + "Rows Removed by Index Recheck": 0, + "Heap Fetches": 0, + "Shared Hit Blocks": 1, + "Shared Read Blocks": 4, + "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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0 + } + ] + }, + "Planning": { + "Shared Hit Blocks": 120, + "Shared Read Blocks": 1, + "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.395, + "Triggers": [], + "Execution Time": 0.105 + }, + { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 0.42, + "Total Cost": 8.43, + "Plan Rows": 51, + "Plan Width": 266, + "Actual Startup Time": 0.035, + "Actual Total Time": 0.048, + "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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0, + "Plans": [ + { + "Node Type": "Index Only Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Scan Direction": "Forward", + "Index Name": "experiment_history_idx", + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.42, + "Total Cost": 12562.84, + "Plan Rows": 79955, + "Plan Width": 266, + "Actual Startup Time": 0.034, + "Actual Total Time": 0.045, + "Actual Rows": 51, + "Actual Loops": 1, + "Index Cond": "((chat_id = '00000000-0000-4000-8000-000000000001'::uuid) AND (ROW(created_at, id) > ROW(('2026-01-01 00:00:00+00'::timestamp with time zone + '00:00:00'::interval), '00000000-0000-0000-0000-000000000000'::uuid)))", + "Rows Removed by Index Recheck": 0, + "Heap Fetches": 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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0 + } + ] + }, + "Planning": { + "Shared Hit Blocks": 119, + "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.364, + "Triggers": [], + "Execution Time": 0.077 + }, + { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 0.42, + "Total Cost": 8.43, + "Plan Rows": 51, + "Plan Width": 266, + "Actual Startup Time": 0.022, + "Actual Total Time": 0.039, + "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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0, + "Plans": [ + { + "Node Type": "Index Only Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Scan Direction": "Forward", + "Index Name": "experiment_history_idx", + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.42, + "Total Cost": 12562.84, + "Plan Rows": 79955, + "Plan Width": 266, + "Actual Startup Time": 0.021, + "Actual Total Time": 0.036, + "Actual Rows": 51, + "Actual Loops": 1, + "Index Cond": "((chat_id = '00000000-0000-4000-8000-000000000001'::uuid) AND (ROW(created_at, id) > ROW(('2026-01-01 00:00:00+00'::timestamp with time zone + '00:00:00'::interval), '00000000-0000-0000-0000-000000000000'::uuid)))", + "Rows Removed by Index Recheck": 0, + "Heap Fetches": 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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0 + } + ] + }, + "Planning": { + "Shared Hit Blocks": 119, + "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.441, + "Triggers": [], + "Execution Time": 0.077 + } + ], + "runs": [ + { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 1\nnumber of threads: 1\nmaximum number of tries: 1\nnumber of transactions per client: 100\nnumber of transactions actually processed: 100/100\nnumber of failed transactions: 0 (0.000%)\nlatency average = 0.098 ms\ninitial connection time = 1.113 ms\ntps = 10158.472166 (without initial connection time)\n", + "latency_avg_ms": 0.098, + "tps": 10158.472166, + "errors": 0 + }, + { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 1\nnumber of threads: 1\nmaximum number of tries: 1\nnumber of transactions per client: 100\nnumber of transactions actually processed: 100/100\nnumber of failed transactions: 0 (0.000%)\nlatency average = 0.094 ms\ninitial connection time = 1.300 ms\ntps = 10614.584439 (without initial connection time)\n", + "latency_avg_ms": 0.094, + "tps": 10614.584439, + "errors": 0 + }, + { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 1\nnumber of threads: 1\nmaximum number of tries: 1\nnumber of transactions per client: 100\nnumber of transactions actually processed: 100/100\nnumber of failed transactions: 0 (0.000%)\nlatency average = 0.079 ms\ninitial connection time = 1.334 ms\ntps = 12605.571663 (without initial connection time)\n", + "latency_avg_ms": 0.079, + "tps": 12605.571663, + "errors": 0 + } + ], + "median_execution_ms": 0.077, + "median_latency_ms": 0.094, + "median_tps": 10614.584439, + "errors": 0 + }, + { + "chat_messages": 80000, + "position": "first", + "clients": 4, + "plans": [], + "runs": [ + { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 4\nnumber of threads: 4\nmaximum number of tries: 1\nnumber of transactions per client: 100\nnumber of transactions actually processed: 400/400\nnumber of failed transactions: 0 (0.000%)\nlatency average = 0.170 ms\ninitial connection time = 1.984 ms\ntps = 23528.027763 (without initial connection time)\n", + "latency_avg_ms": 0.17, + "tps": 23528.027763, + "errors": 0 + }, + { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 4\nnumber of threads: 4\nmaximum number of tries: 1\nnumber of transactions per client: 100\nnumber of transactions actually processed: 400/400\nnumber of failed transactions: 0 (0.000%)\nlatency average = 0.159 ms\ninitial connection time = 1.784 ms\ntps = 25160.397534 (without initial connection time)\n", + "latency_avg_ms": 0.159, + "tps": 25160.397534, + "errors": 0 + }, + { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 4\nnumber of threads: 4\nmaximum number of tries: 1\nnumber of transactions per client: 100\nnumber of transactions actually processed: 400/400\nnumber of failed transactions: 0 (0.000%)\nlatency average = 0.163 ms\ninitial connection time = 1.774 ms\ntps = 24470.818549 (without initial connection time)\n", + "latency_avg_ms": 0.163, + "tps": 24470.818549, + "errors": 0 + } + ], + "median_execution_ms": 0.077, + "median_latency_ms": 0.163, + "median_tps": 24470.818549, + "errors": 0 + }, + { + "chat_messages": 80000, + "position": "deep", + "clients": 1, + "plans": [ + { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 0.42, + "Total Cost": 8.43, + "Plan Rows": 51, + "Plan Width": 266, + "Actual Startup Time": 0.055, + "Actual Total Time": 0.087, + "Actual Rows": 51, + "Actual Loops": 1, + "Shared Hit Blocks": 2, + "Shared Read Blocks": 4, + "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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0, + "Plans": [ + { + "Node Type": "Index Only Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Scan Direction": "Forward", + "Index Name": "experiment_history_idx", + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.42, + "Total Cost": 988.47, + "Plan Rows": 6287, + "Plan Width": 266, + "Actual Startup Time": 0.054, + "Actual Total Time": 0.084, + "Actual Rows": 51, + "Actual Loops": 1, + "Index Cond": "((chat_id = '00000000-0000-4000-8000-000000000001'::uuid) AND (ROW(created_at, id) > ROW(('2026-01-01 00:00:00+00'::timestamp with time zone + '00:00:00.072'::interval), '00000000-0000-0000-0000-000000000000'::uuid)))", + "Rows Removed by Index Recheck": 0, + "Heap Fetches": 0, + "Shared Hit Blocks": 2, + "Shared Read Blocks": 4, + "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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0 + } + ] + }, + "Planning": { + "Shared Hit Blocks": 119, + "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.312, + "Triggers": [], + "Execution Time": 0.114 + }, + { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 0.42, + "Total Cost": 8.43, + "Plan Rows": 51, + "Plan Width": 266, + "Actual Startup Time": 0.02, + "Actual Total Time": 0.033, + "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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0, + "Plans": [ + { + "Node Type": "Index Only Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Scan Direction": "Forward", + "Index Name": "experiment_history_idx", + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.42, + "Total Cost": 988.47, + "Plan Rows": 6287, + "Plan Width": 266, + "Actual Startup Time": 0.02, + "Actual Total Time": 0.031, + "Actual Rows": 51, + "Actual Loops": 1, + "Index Cond": "((chat_id = '00000000-0000-4000-8000-000000000001'::uuid) AND (ROW(created_at, id) > ROW(('2026-01-01 00:00:00+00'::timestamp with time zone + '00:00:00.072'::interval), '00000000-0000-0000-0000-000000000000'::uuid)))", + "Rows Removed by Index Recheck": 0, + "Heap Fetches": 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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0 + } + ] + }, + "Planning": { + "Shared Hit Blocks": 119, + "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.316, + "Triggers": [], + "Execution Time": 0.068 + }, + { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 0.42, + "Total Cost": 8.43, + "Plan Rows": 51, + "Plan Width": 266, + "Actual Startup Time": 0.025, + "Actual Total Time": 0.041, + "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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0, + "Plans": [ + { + "Node Type": "Index Only Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Scan Direction": "Forward", + "Index Name": "experiment_history_idx", + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.42, + "Total Cost": 988.47, + "Plan Rows": 6287, + "Plan Width": 266, + "Actual Startup Time": 0.024, + "Actual Total Time": 0.038, + "Actual Rows": 51, + "Actual Loops": 1, + "Index Cond": "((chat_id = '00000000-0000-4000-8000-000000000001'::uuid) AND (ROW(created_at, id) > ROW(('2026-01-01 00:00:00+00'::timestamp with time zone + '00:00:00.072'::interval), '00000000-0000-0000-0000-000000000000'::uuid)))", + "Rows Removed by Index Recheck": 0, + "Heap Fetches": 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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0 + } + ] + }, + "Planning": { + "Shared Hit Blocks": 119, + "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.384, + "Triggers": [], + "Execution Time": 0.073 + } + ], + "runs": [ + { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 1\nnumber of threads: 1\nmaximum number of tries: 1\nnumber of transactions per client: 100\nnumber of transactions actually processed: 100/100\nnumber of failed transactions: 0 (0.000%)\nlatency average = 0.096 ms\ninitial connection time = 0.991 ms\ntps = 10378.827193 (without initial connection time)\n", + "latency_avg_ms": 0.096, + "tps": 10378.827193, + "errors": 0 + }, + { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 1\nnumber of threads: 1\nmaximum number of tries: 1\nnumber of transactions per client: 100\nnumber of transactions actually processed: 100/100\nnumber of failed transactions: 0 (0.000%)\nlatency average = 0.098 ms\ninitial connection time = 0.973 ms\ntps = 10225.994478 (without initial connection time)\n", + "latency_avg_ms": 0.098, + "tps": 10225.994478, + "errors": 0 + }, + { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 1\nnumber of threads: 1\nmaximum number of tries: 1\nnumber of transactions per client: 100\nnumber of transactions actually processed: 100/100\nnumber of failed transactions: 0 (0.000%)\nlatency average = 0.088 ms\ninitial connection time = 1.238 ms\ntps = 11336.583154 (without initial connection time)\n", + "latency_avg_ms": 0.088, + "tps": 11336.583154, + "errors": 0 + } + ], + "median_execution_ms": 0.073, + "median_latency_ms": 0.096, + "median_tps": 10378.827193, + "errors": 0 + }, + { + "chat_messages": 80000, + "position": "deep", + "clients": 4, + "plans": [], + "runs": [ + { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 4\nnumber of threads: 4\nmaximum number of tries: 1\nnumber of transactions per client: 100\nnumber of transactions actually processed: 400/400\nnumber of failed transactions: 0 (0.000%)\nlatency average = 0.165 ms\ninitial connection time = 1.737 ms\ntps = 24227.740763 (without initial connection time)\n", + "latency_avg_ms": 0.165, + "tps": 24227.740763, + "errors": 0 + }, + { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 4\nnumber of threads: 4\nmaximum number of tries: 1\nnumber of transactions per client: 100\nnumber of transactions actually processed: 400/400\nnumber of failed transactions: 0 (0.000%)\nlatency average = 0.165 ms\ninitial connection time = 1.671 ms\ntps = 24205.748865 (without initial connection time)\n", + "latency_avg_ms": 0.165, + "tps": 24205.748865, + "errors": 0 + }, + { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 4\nnumber of threads: 4\nmaximum number of tries: 1\nnumber of transactions per client: 100\nnumber of transactions actually processed: 400/400\nnumber of failed transactions: 0 (0.000%)\nlatency average = 0.157 ms\ninitial connection time = 1.832 ms\ntps = 25541.153183 (without initial connection time)\n", + "latency_avg_ms": 0.157, + "tps": 25541.153183, + "errors": 0 + } + ], + "median_execution_ms": 0.073, + "median_latency_ms": 0.165, + "median_tps": 24227.740763, + "errors": 0 + }, + { + "chat_messages": 15000, + "position": "first", + "clients": 1, + "plans": [ + { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 0.42, + "Total Cost": 8.44, + "Plan Rows": 51, + "Plan Width": 266, + "Actual Startup Time": 0.061, + "Actual Total Time": 0.075, + "Actual Rows": 51, + "Actual Loops": 1, + "Shared Hit Blocks": 2, + "Shared Read Blocks": 3, + "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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0, + "Plans": [ + { + "Node Type": "Index Only Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Scan Direction": "Forward", + "Index Name": "experiment_history_idx", + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.42, + "Total Cost": 2341.29, + "Plan Rows": 14882, + "Plan Width": 266, + "Actual Startup Time": 0.06, + "Actual Total Time": 0.072, + "Actual Rows": 51, + "Actual Loops": 1, + "Index Cond": "((chat_id = '00000000-0000-4000-8000-000000000002'::uuid) AND (ROW(created_at, id) > ROW(('2026-01-01 00:00:00+00'::timestamp with time zone + '00:00:00'::interval), '00000000-0000-0000-0000-000000000000'::uuid)))", + "Rows Removed by Index Recheck": 0, + "Heap Fetches": 0, + "Shared Hit Blocks": 2, + "Shared Read Blocks": 3, + "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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0 + } + ] + }, + "Planning": { + "Shared Hit Blocks": 119, + "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.325, + "Triggers": [], + "Execution Time": 0.104 + }, + { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 0.42, + "Total Cost": 8.44, + "Plan Rows": 51, + "Plan Width": 266, + "Actual Startup Time": 0.028, + "Actual Total Time": 0.038, + "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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0, + "Plans": [ + { + "Node Type": "Index Only Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Scan Direction": "Forward", + "Index Name": "experiment_history_idx", + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.42, + "Total Cost": 2341.29, + "Plan Rows": 14882, + "Plan Width": 266, + "Actual Startup Time": 0.027, + "Actual Total Time": 0.034, + "Actual Rows": 51, + "Actual Loops": 1, + "Index Cond": "((chat_id = '00000000-0000-4000-8000-000000000002'::uuid) AND (ROW(created_at, id) > ROW(('2026-01-01 00:00:00+00'::timestamp with time zone + '00:00:00'::interval), '00000000-0000-0000-0000-000000000000'::uuid)))", + "Rows Removed by Index Recheck": 0, + "Heap Fetches": 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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0 + } + ] + }, + "Planning": { + "Shared Hit Blocks": 119, + "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.313, + "Triggers": [], + "Execution Time": 0.068 + }, + { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 0.42, + "Total Cost": 8.44, + "Plan Rows": 51, + "Plan Width": 266, + "Actual Startup Time": 0.03, + "Actual Total Time": 0.038, + "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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0, + "Plans": [ + { + "Node Type": "Index Only Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Scan Direction": "Forward", + "Index Name": "experiment_history_idx", + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.42, + "Total Cost": 2341.29, + "Plan Rows": 14882, + "Plan Width": 266, + "Actual Startup Time": 0.029, + "Actual Total Time": 0.035, + "Actual Rows": 51, + "Actual Loops": 1, + "Index Cond": "((chat_id = '00000000-0000-4000-8000-000000000002'::uuid) AND (ROW(created_at, id) > ROW(('2026-01-01 00:00:00+00'::timestamp with time zone + '00:00:00'::interval), '00000000-0000-0000-0000-000000000000'::uuid)))", + "Rows Removed by Index Recheck": 0, + "Heap Fetches": 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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0 + } + ] + }, + "Planning": { + "Shared Hit Blocks": 119, + "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.448, + "Triggers": [], + "Execution Time": 0.064 + } + ], + "runs": [ + { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 1\nnumber of threads: 1\nmaximum number of tries: 1\nnumber of transactions per client: 100\nnumber of transactions actually processed: 100/100\nnumber of failed transactions: 0 (0.000%)\nlatency average = 0.096 ms\ninitial connection time = 1.252 ms\ntps = 10447.137484 (without initial connection time)\n", + "latency_avg_ms": 0.096, + "tps": 10447.137484, + "errors": 0 + }, + { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 1\nnumber of threads: 1\nmaximum number of tries: 1\nnumber of transactions per client: 100\nnumber of transactions actually processed: 100/100\nnumber of failed transactions: 0 (0.000%)\nlatency average = 0.091 ms\ninitial connection time = 1.000 ms\ntps = 10969.723563 (without initial connection time)\n", + "latency_avg_ms": 0.091, + "tps": 10969.723563, + "errors": 0 + }, + { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 1\nnumber of threads: 1\nmaximum number of tries: 1\nnumber of transactions per client: 100\nnumber of transactions actually processed: 100/100\nnumber of failed transactions: 0 (0.000%)\nlatency average = 0.092 ms\ninitial connection time = 1.209 ms\ntps = 10831.889081 (without initial connection time)\n", + "latency_avg_ms": 0.092, + "tps": 10831.889081, + "errors": 0 + } + ], + "median_execution_ms": 0.068, + "median_latency_ms": 0.092, + "median_tps": 10831.889081, + "errors": 0 + }, + { + "chat_messages": 15000, + "position": "first", + "clients": 4, + "plans": [], + "runs": [ + { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 4\nnumber of threads: 4\nmaximum number of tries: 1\nnumber of transactions per client: 100\nnumber of transactions actually processed: 400/400\nnumber of failed transactions: 0 (0.000%)\nlatency average = 0.160 ms\ninitial connection time = 2.082 ms\ntps = 25057.946501 (without initial connection time)\n", + "latency_avg_ms": 0.16, + "tps": 25057.946501, + "errors": 0 + }, + { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 4\nnumber of threads: 4\nmaximum number of tries: 1\nnumber of transactions per client: 100\nnumber of transactions actually processed: 400/400\nnumber of failed transactions: 0 (0.000%)\nlatency average = 0.183 ms\ninitial connection time = 1.894 ms\ntps = 21889.022655 (without initial connection time)\n", + "latency_avg_ms": 0.183, + "tps": 21889.022655, + "errors": 0 + }, + { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 4\nnumber of threads: 4\nmaximum number of tries: 1\nnumber of transactions per client: 100\nnumber of transactions actually processed: 400/400\nnumber of failed transactions: 0 (0.000%)\nlatency average = 0.264 ms\ninitial connection time = 5.867 ms\ntps = 15168.177164 (without initial connection time)\n", + "latency_avg_ms": 0.264, + "tps": 15168.177164, + "errors": 0 + } + ], + "median_execution_ms": 0.068, + "median_latency_ms": 0.183, + "median_tps": 21889.022655, + "errors": 0 + }, + { + "chat_messages": 15000, + "position": "deep", + "clients": 1, + "plans": [ + { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 0.42, + "Total Cost": 8.44, + "Plan Rows": 51, + "Plan Width": 266, + "Actual Startup Time": 0.071, + "Actual Total Time": 0.084, + "Actual Rows": 51, + "Actual Loops": 1, + "Shared Hit Blocks": 2, + "Shared Read Blocks": 3, + "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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0, + "Plans": [ + { + "Node Type": "Index Only Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Scan Direction": "Forward", + "Index Name": "experiment_history_idx", + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.42, + "Total Cost": 1595.39, + "Plan Rows": 10142, + "Plan Width": 266, + "Actual Startup Time": 0.07, + "Actual Total Time": 0.081, + "Actual Rows": 51, + "Actual Loops": 1, + "Index Cond": "((chat_id = '00000000-0000-4000-8000-000000000002'::uuid) AND (ROW(created_at, id) > ROW(('2026-01-01 00:00:00+00'::timestamp with time zone + '00:00:00.0135'::interval), '00000000-0000-0000-0000-000000000000'::uuid)))", + "Rows Removed by Index Recheck": 0, + "Heap Fetches": 0, + "Shared Hit Blocks": 2, + "Shared Read Blocks": 3, + "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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0 + } + ] + }, + "Planning": { + "Shared Hit Blocks": 119, + "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.305, + "Triggers": [], + "Execution Time": 0.113 + }, + { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 0.42, + "Total Cost": 8.44, + "Plan Rows": 51, + "Plan Width": 266, + "Actual Startup Time": 0.021, + "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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0, + "Plans": [ + { + "Node Type": "Index Only Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Scan Direction": "Forward", + "Index Name": "experiment_history_idx", + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.42, + "Total Cost": 1595.39, + "Plan Rows": 10142, + "Plan Width": 266, + "Actual Startup Time": 0.02, + "Actual Total Time": 0.028, + "Actual Rows": 51, + "Actual Loops": 1, + "Index Cond": "((chat_id = '00000000-0000-4000-8000-000000000002'::uuid) AND (ROW(created_at, id) > ROW(('2026-01-01 00:00:00+00'::timestamp with time zone + '00:00:00.0135'::interval), '00000000-0000-0000-0000-000000000000'::uuid)))", + "Rows Removed by Index Recheck": 0, + "Heap Fetches": 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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0 + } + ] + }, + "Planning": { + "Shared Hit Blocks": 119, + "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.377, + "Triggers": [], + "Execution Time": 0.056 + }, + { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 0.42, + "Total Cost": 8.44, + "Plan Rows": 51, + "Plan Width": 266, + "Actual Startup Time": 0.023, + "Actual Total Time": 0.034, + "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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0, + "Plans": [ + { + "Node Type": "Index Only Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Scan Direction": "Forward", + "Index Name": "experiment_history_idx", + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.42, + "Total Cost": 1595.39, + "Plan Rows": 10142, + "Plan Width": 266, + "Actual Startup Time": 0.023, + "Actual Total Time": 0.032, + "Actual Rows": 51, + "Actual Loops": 1, + "Index Cond": "((chat_id = '00000000-0000-4000-8000-000000000002'::uuid) AND (ROW(created_at, id) > ROW(('2026-01-01 00:00:00+00'::timestamp with time zone + '00:00:00.0135'::interval), '00000000-0000-0000-0000-000000000000'::uuid)))", + "Rows Removed by Index Recheck": 0, + "Heap Fetches": 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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0 + } + ] + }, + "Planning": { + "Shared Hit Blocks": 119, + "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.317, + "Triggers": [], + "Execution Time": 0.064 + } + ], + "runs": [ + { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 1\nnumber of threads: 1\nmaximum number of tries: 1\nnumber of transactions per client: 100\nnumber of transactions actually processed: 100/100\nnumber of failed transactions: 0 (0.000%)\nlatency average = 0.170 ms\ninitial connection time = 1.134 ms\ntps = 5886.854654 (without initial connection time)\n", + "latency_avg_ms": 0.17, + "tps": 5886.854654, + "errors": 0 + }, + { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 1\nnumber of threads: 1\nmaximum number of tries: 1\nnumber of transactions per client: 100\nnumber of transactions actually processed: 100/100\nnumber of failed transactions: 0 (0.000%)\nlatency average = 0.104 ms\ninitial connection time = 1.236 ms\ntps = 9654.373431 (without initial connection time)\n", + "latency_avg_ms": 0.104, + "tps": 9654.373431, + "errors": 0 + }, + { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 1\nnumber of threads: 1\nmaximum number of tries: 1\nnumber of transactions per client: 100\nnumber of transactions actually processed: 100/100\nnumber of failed transactions: 0 (0.000%)\nlatency average = 0.121 ms\ninitial connection time = 2.360 ms\ntps = 8241.984670 (without initial connection time)\n", + "latency_avg_ms": 0.121, + "tps": 8241.98467, + "errors": 0 + } + ], + "median_execution_ms": 0.064, + "median_latency_ms": 0.121, + "median_tps": 8241.98467, + "errors": 0 + }, + { + "chat_messages": 15000, + "position": "deep", + "clients": 4, + "plans": [], + "runs": [ + { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 4\nnumber of threads: 4\nmaximum number of tries: 1\nnumber of transactions per client: 100\nnumber of transactions actually processed: 400/400\nnumber of failed transactions: 0 (0.000%)\nlatency average = 0.281 ms\ninitial connection time = 12.186 ms\ntps = 14243.999715 (without initial connection time)\n", + "latency_avg_ms": 0.281, + "tps": 14243.999715, + "errors": 0 + }, + { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 4\nnumber of threads: 4\nmaximum number of tries: 1\nnumber of transactions per client: 100\nnumber of transactions actually processed: 400/400\nnumber of failed transactions: 0 (0.000%)\nlatency average = 0.168 ms\ninitial connection time = 2.012 ms\ntps = 23762.846789 (without initial connection time)\n", + "latency_avg_ms": 0.168, + "tps": 23762.846789, + "errors": 0 + }, + { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 4\nnumber of threads: 4\nmaximum number of tries: 1\nnumber of transactions per client: 100\nnumber of transactions actually processed: 400/400\nnumber of failed transactions: 0 (0.000%)\nlatency average = 0.235 ms\ninitial connection time = 2.181 ms\ntps = 16992.353441 (without initial connection time)\n", + "latency_avg_ms": 0.235, + "tps": 16992.353441, + "errors": 0 + } + ], + "median_execution_ms": 0.064, + "median_latency_ms": 0.235, + "median_tps": 16992.353441, + "errors": 0 + }, + { + "chat_messages": 4900, + "position": "first", + "clients": 1, + "plans": [ + { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 0.42, + "Total Cost": 8.46, + "Plan Rows": 51, + "Plan Width": 266, + "Actual Startup Time": 0.062, + "Actual Total Time": 0.1, + "Actual Rows": 51, + "Actual Loops": 1, + "Shared Hit Blocks": 2, + "Shared Read Blocks": 4, + "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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0, + "Plans": [ + { + "Node Type": "Index Only Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Scan Direction": "Forward", + "Index Name": "experiment_history_idx", + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.42, + "Total Cost": 797.38, + "Plan Rows": 5056, + "Plan Width": 266, + "Actual Startup Time": 0.061, + "Actual Total Time": 0.097, + "Actual Rows": 51, + "Actual Loops": 1, + "Index Cond": "((chat_id = '00000000-0000-4000-8000-000000000003'::uuid) AND (ROW(created_at, id) > ROW(('2026-01-01 00:00:00+00'::timestamp with time zone + '00:00:00'::interval), '00000000-0000-0000-0000-000000000000'::uuid)))", + "Rows Removed by Index Recheck": 0, + "Heap Fetches": 0, + "Shared Hit Blocks": 2, + "Shared Read Blocks": 4, + "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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0 + } + ] + }, + "Planning": { + "Shared Hit Blocks": 119, + "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.556, + "Triggers": [], + "Execution Time": 0.138 + }, + { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 0.42, + "Total Cost": 8.46, + "Plan Rows": 51, + "Plan Width": 266, + "Actual Startup Time": 0.024, + "Actual Total Time": 0.042, + "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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0, + "Plans": [ + { + "Node Type": "Index Only Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Scan Direction": "Forward", + "Index Name": "experiment_history_idx", + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.42, + "Total Cost": 797.38, + "Plan Rows": 5056, + "Plan Width": 266, + "Actual Startup Time": 0.023, + "Actual Total Time": 0.039, + "Actual Rows": 51, + "Actual Loops": 1, + "Index Cond": "((chat_id = '00000000-0000-4000-8000-000000000003'::uuid) AND (ROW(created_at, id) > ROW(('2026-01-01 00:00:00+00'::timestamp with time zone + '00:00:00'::interval), '00000000-0000-0000-0000-000000000000'::uuid)))", + "Rows Removed by Index Recheck": 0, + "Heap Fetches": 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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0 + } + ] + }, + "Planning": { + "Shared Hit Blocks": 119, + "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.409, + "Triggers": [], + "Execution Time": 0.078 + }, + { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 0.42, + "Total Cost": 8.46, + "Plan Rows": 51, + "Plan Width": 266, + "Actual Startup Time": 0.02, + "Actual Total Time": 0.035, + "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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0, + "Plans": [ + { + "Node Type": "Index Only Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Scan Direction": "Forward", + "Index Name": "experiment_history_idx", + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.42, + "Total Cost": 797.38, + "Plan Rows": 5056, + "Plan Width": 266, + "Actual Startup Time": 0.019, + "Actual Total Time": 0.032, + "Actual Rows": 51, + "Actual Loops": 1, + "Index Cond": "((chat_id = '00000000-0000-4000-8000-000000000003'::uuid) AND (ROW(created_at, id) > ROW(('2026-01-01 00:00:00+00'::timestamp with time zone + '00:00:00'::interval), '00000000-0000-0000-0000-000000000000'::uuid)))", + "Rows Removed by Index Recheck": 0, + "Heap Fetches": 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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0 + } + ] + }, + "Planning": { + "Shared Hit Blocks": 119, + "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.336, + "Triggers": [], + "Execution Time": 0.061 + } + ], + "runs": [ + { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 1\nnumber of threads: 1\nmaximum number of tries: 1\nnumber of transactions per client: 100\nnumber of transactions actually processed: 100/100\nnumber of failed transactions: 0 (0.000%)\nlatency average = 0.088 ms\ninitial connection time = 1.117 ms\ntps = 11319.900385 (without initial connection time)\n", + "latency_avg_ms": 0.088, + "tps": 11319.900385, + "errors": 0 + }, + { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 1\nnumber of threads: 1\nmaximum number of tries: 1\nnumber of transactions per client: 100\nnumber of transactions actually processed: 100/100\nnumber of failed transactions: 0 (0.000%)\nlatency average = 0.098 ms\ninitial connection time = 1.029 ms\ntps = 10254.306809 (without initial connection time)\n", + "latency_avg_ms": 0.098, + "tps": 10254.306809, + "errors": 0 + }, + { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 1\nnumber of threads: 1\nmaximum number of tries: 1\nnumber of transactions per client: 100\nnumber of transactions actually processed: 100/100\nnumber of failed transactions: 0 (0.000%)\nlatency average = 0.095 ms\ninitial connection time = 1.257 ms\ntps = 10571.942066 (without initial connection time)\n", + "latency_avg_ms": 0.095, + "tps": 10571.942066, + "errors": 0 + } + ], + "median_execution_ms": 0.078, + "median_latency_ms": 0.095, + "median_tps": 10571.942066, + "errors": 0 + }, + { + "chat_messages": 4900, + "position": "first", + "clients": 4, + "plans": [], + "runs": [ + { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 4\nnumber of threads: 4\nmaximum number of tries: 1\nnumber of transactions per client: 100\nnumber of transactions actually processed: 400/400\nnumber of failed transactions: 0 (0.000%)\nlatency average = 0.175 ms\ninitial connection time = 1.790 ms\ntps = 22857.142857 (without initial connection time)\n", + "latency_avg_ms": 0.175, + "tps": 22857.142857, + "errors": 0 + }, + { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 4\nnumber of threads: 4\nmaximum number of tries: 1\nnumber of transactions per client: 100\nnumber of transactions actually processed: 400/400\nnumber of failed transactions: 0 (0.000%)\nlatency average = 0.163 ms\ninitial connection time = 1.948 ms\ntps = 24563.989192 (without initial connection time)\n", + "latency_avg_ms": 0.163, + "tps": 24563.989192, + "errors": 0 + }, + { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 4\nnumber of threads: 4\nmaximum number of tries: 1\nnumber of transactions per client: 100\nnumber of transactions actually processed: 400/400\nnumber of failed transactions: 0 (0.000%)\nlatency average = 0.153 ms\ninitial connection time = 2.982 ms\ntps = 26085.822356 (without initial connection time)\n", + "latency_avg_ms": 0.153, + "tps": 26085.822356, + "errors": 0 + } + ], + "median_execution_ms": 0.078, + "median_latency_ms": 0.163, + "median_tps": 24563.989192, + "errors": 0 + }, + { + "chat_messages": 4900, + "position": "deep", + "clients": 1, + "plans": [ + { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 0.42, + "Total Cost": 8.45, + "Plan Rows": 51, + "Plan Width": 266, + "Actual Startup Time": 0.093, + "Actual Total Time": 0.106, + "Actual Rows": 51, + "Actual Loops": 1, + "Shared Hit Blocks": 2, + "Shared Read Blocks": 3, + "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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0, + "Plans": [ + { + "Node Type": "Index Only Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Scan Direction": "Forward", + "Index Name": "experiment_history_idx", + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.42, + "Total Cost": 689.65, + "Plan Rows": 4378, + "Plan Width": 266, + "Actual Startup Time": 0.092, + "Actual Total Time": 0.104, + "Actual Rows": 51, + "Actual Loops": 1, + "Index Cond": "((chat_id = '00000000-0000-4000-8000-000000000003'::uuid) AND (ROW(created_at, id) > ROW(('2026-01-01 00:00:00+00'::timestamp with time zone + '00:00:00.00441'::interval), '00000000-0000-0000-0000-000000000000'::uuid)))", + "Rows Removed by Index Recheck": 0, + "Heap Fetches": 0, + "Shared Hit Blocks": 2, + "Shared Read Blocks": 3, + "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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0 + } + ] + }, + "Planning": { + "Shared Hit Blocks": 119, + "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.391, + "Triggers": [], + "Execution Time": 0.605 + }, + { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 0.42, + "Total Cost": 8.45, + "Plan Rows": 51, + "Plan Width": 266, + "Actual Startup Time": 0.028, + "Actual Total Time": 0.038, + "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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0, + "Plans": [ + { + "Node Type": "Index Only Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Scan Direction": "Forward", + "Index Name": "experiment_history_idx", + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.42, + "Total Cost": 689.65, + "Plan Rows": 4378, + "Plan Width": 266, + "Actual Startup Time": 0.028, + "Actual Total Time": 0.036, + "Actual Rows": 51, + "Actual Loops": 1, + "Index Cond": "((chat_id = '00000000-0000-4000-8000-000000000003'::uuid) AND (ROW(created_at, id) > ROW(('2026-01-01 00:00:00+00'::timestamp with time zone + '00:00:00.00441'::interval), '00000000-0000-0000-0000-000000000000'::uuid)))", + "Rows Removed by Index Recheck": 0, + "Heap Fetches": 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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0 + } + ] + }, + "Planning": { + "Shared Hit Blocks": 119, + "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.316, + "Triggers": [], + "Execution Time": 0.065 + }, + { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 0.42, + "Total Cost": 8.45, + "Plan Rows": 51, + "Plan Width": 266, + "Actual Startup Time": 0.048, + "Actual Total Time": 0.057, + "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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0, + "Plans": [ + { + "Node Type": "Index Only Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Scan Direction": "Forward", + "Index Name": "experiment_history_idx", + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.42, + "Total Cost": 689.65, + "Plan Rows": 4378, + "Plan Width": 266, + "Actual Startup Time": 0.047, + "Actual Total Time": 0.055, + "Actual Rows": 51, + "Actual Loops": 1, + "Index Cond": "((chat_id = '00000000-0000-4000-8000-000000000003'::uuid) AND (ROW(created_at, id) > ROW(('2026-01-01 00:00:00+00'::timestamp with time zone + '00:00:00.00441'::interval), '00000000-0000-0000-0000-000000000000'::uuid)))", + "Rows Removed by Index Recheck": 0, + "Heap Fetches": 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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0 + } + ] + }, + "Planning": { + "Shared Hit Blocks": 119, + "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.337, + "Triggers": [], + "Execution Time": 0.101 + } + ], + "runs": [ + { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 1\nnumber of threads: 1\nmaximum number of tries: 1\nnumber of transactions per client: 100\nnumber of transactions actually processed: 100/100\nnumber of failed transactions: 0 (0.000%)\nlatency average = 0.091 ms\ninitial connection time = 1.326 ms\ntps = 10948.105978 (without initial connection time)\n", + "latency_avg_ms": 0.091, + "tps": 10948.105978, + "errors": 0 + }, + { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 1\nnumber of threads: 1\nmaximum number of tries: 1\nnumber of transactions per client: 100\nnumber of transactions actually processed: 100/100\nnumber of failed transactions: 0 (0.000%)\nlatency average = 0.106 ms\ninitial connection time = 1.279 ms\ntps = 9466.111321 (without initial connection time)\n", + "latency_avg_ms": 0.106, + "tps": 9466.111321, + "errors": 0 + }, + { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 1\nnumber of threads: 1\nmaximum number of tries: 1\nnumber of transactions per client: 100\nnumber of transactions actually processed: 100/100\nnumber of failed transactions: 0 (0.000%)\nlatency average = 0.091 ms\ninitial connection time = 1.218 ms\ntps = 10958.904110 (without initial connection time)\n", + "latency_avg_ms": 0.091, + "tps": 10958.90411, + "errors": 0 + } + ], + "median_execution_ms": 0.101, + "median_latency_ms": 0.091, + "median_tps": 10948.105978, + "errors": 0 + }, + { + "chat_messages": 4900, + "position": "deep", + "clients": 4, + "plans": [], + "runs": [ + { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 4\nnumber of threads: 4\nmaximum number of tries: 1\nnumber of transactions per client: 100\nnumber of transactions actually processed: 400/400\nnumber of failed transactions: 0 (0.000%)\nlatency average = 0.161 ms\ninitial connection time = 1.878 ms\ntps = 24787.754849 (without initial connection time)\n", + "latency_avg_ms": 0.161, + "tps": 24787.754849, + "errors": 0 + }, + { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 4\nnumber of threads: 4\nmaximum number of tries: 1\nnumber of transactions per client: 100\nnumber of transactions actually processed: 400/400\nnumber of failed transactions: 0 (0.000%)\nlatency average = 0.230 ms\ninitial connection time = 4.650 ms\ntps = 17400.382808 (without initial connection time)\n", + "latency_avg_ms": 0.23, + "tps": 17400.382808, + "errors": 0 + }, + { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 4\nnumber of threads: 4\nmaximum number of tries: 1\nnumber of transactions per client: 100\nnumber of transactions actually processed: 400/400\nnumber of failed transactions: 0 (0.000%)\nlatency average = 0.169 ms\ninitial connection time = 2.123 ms\ntps = 23660.238968 (without initial connection time)\n", + "latency_avg_ms": 0.169, + "tps": 23660.238968, + "errors": 0 + } + ], + "median_execution_ms": 0.101, + "median_latency_ms": 0.169, + "median_tps": 23660.238968, + "errors": 0 + }, + { + "chat_messages": 100, + "position": "first", + "clients": 1, + "plans": [ + { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 0.42, + "Total Cost": 8.51, + "Plan Rows": 51, + "Plan Width": 266, + "Actual Startup Time": 0.072, + "Actual Total Time": 0.094, + "Actual Rows": 51, + "Actual Loops": 1, + "Shared Hit Blocks": 3, + "Shared Read Blocks": 2, + "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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0, + "Plans": [ + { + "Node Type": "Index Only Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Scan Direction": "Forward", + "Index Name": "experiment_history_idx", + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.42, + "Total Cost": 15.82, + "Plan Rows": 97, + "Plan Width": 266, + "Actual Startup Time": 0.071, + "Actual Total Time": 0.09, + "Actual Rows": 51, + "Actual Loops": 1, + "Index Cond": "((chat_id = '00000000-0000-4000-8000-000000000004'::uuid) AND (ROW(created_at, id) > ROW(('2026-01-01 00:00:00+00'::timestamp with time zone + '00:00:00'::interval), '00000000-0000-0000-0000-000000000000'::uuid)))", + "Rows Removed by Index Recheck": 0, + "Heap Fetches": 0, + "Shared Hit Blocks": 3, + "Shared Read Blocks": 2, + "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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0 + } + ] + }, + "Planning": { + "Shared Hit Blocks": 119, + "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.352, + "Triggers": [], + "Execution Time": 0.132 + }, + { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 0.42, + "Total Cost": 8.51, + "Plan Rows": 51, + "Plan Width": 266, + "Actual Startup Time": 0.036, + "Actual Total Time": 0.049, + "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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0, + "Plans": [ + { + "Node Type": "Index Only Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Scan Direction": "Forward", + "Index Name": "experiment_history_idx", + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.42, + "Total Cost": 15.82, + "Plan Rows": 97, + "Plan Width": 266, + "Actual Startup Time": 0.035, + "Actual Total Time": 0.046, + "Actual Rows": 51, + "Actual Loops": 1, + "Index Cond": "((chat_id = '00000000-0000-4000-8000-000000000004'::uuid) AND (ROW(created_at, id) > ROW(('2026-01-01 00:00:00+00'::timestamp with time zone + '00:00:00'::interval), '00000000-0000-0000-0000-000000000000'::uuid)))", + "Rows Removed by Index Recheck": 0, + "Heap Fetches": 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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0 + } + ] + }, + "Planning": { + "Shared Hit Blocks": 119, + "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.324, + "Triggers": [], + "Execution Time": 0.084 + }, + { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 0.42, + "Total Cost": 8.51, + "Plan Rows": 51, + "Plan Width": 266, + "Actual Startup Time": 0.029, + "Actual Total Time": 0.042, + "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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0, + "Plans": [ + { + "Node Type": "Index Only Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Scan Direction": "Forward", + "Index Name": "experiment_history_idx", + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.42, + "Total Cost": 15.82, + "Plan Rows": 97, + "Plan Width": 266, + "Actual Startup Time": 0.029, + "Actual Total Time": 0.039, + "Actual Rows": 51, + "Actual Loops": 1, + "Index Cond": "((chat_id = '00000000-0000-4000-8000-000000000004'::uuid) AND (ROW(created_at, id) > ROW(('2026-01-01 00:00:00+00'::timestamp with time zone + '00:00:00'::interval), '00000000-0000-0000-0000-000000000000'::uuid)))", + "Rows Removed by Index Recheck": 0, + "Heap Fetches": 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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0 + } + ] + }, + "Planning": { + "Shared Hit Blocks": 119, + "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.375, + "Triggers": [], + "Execution Time": 0.085 + } + ], + "runs": [ + { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 1\nnumber of threads: 1\nmaximum number of tries: 1\nnumber of transactions per client: 100\nnumber of transactions actually processed: 100/100\nnumber of failed transactions: 0 (0.000%)\nlatency average = 0.094 ms\ninitial connection time = 1.433 ms\ntps = 10632.642212 (without initial connection time)\n", + "latency_avg_ms": 0.094, + "tps": 10632.642212, + "errors": 0 + }, + { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 1\nnumber of threads: 1\nmaximum number of tries: 1\nnumber of transactions per client: 100\nnumber of transactions actually processed: 100/100\nnumber of failed transactions: 0 (0.000%)\nlatency average = 0.086 ms\ninitial connection time = 1.233 ms\ntps = 11584.800741 (without initial connection time)\n", + "latency_avg_ms": 0.086, + "tps": 11584.800741, + "errors": 0 + }, + { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 1\nnumber of threads: 1\nmaximum number of tries: 1\nnumber of transactions per client: 100\nnumber of transactions actually processed: 100/100\nnumber of failed transactions: 0 (0.000%)\nlatency average = 0.092 ms\ninitial connection time = 1.338 ms\ntps = 10874.293171 (without initial connection time)\n", + "latency_avg_ms": 0.092, + "tps": 10874.293171, + "errors": 0 + } + ], + "median_execution_ms": 0.085, + "median_latency_ms": 0.092, + "median_tps": 10874.293171, + "errors": 0 + }, + { + "chat_messages": 100, + "position": "first", + "clients": 4, + "plans": [], + "runs": [ + { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 4\nnumber of threads: 4\nmaximum number of tries: 1\nnumber of transactions per client: 100\nnumber of transactions actually processed: 400/400\nnumber of failed transactions: 0 (0.000%)\nlatency average = 0.166 ms\ninitial connection time = 1.688 ms\ntps = 24061.597690 (without initial connection time)\n", + "latency_avg_ms": 0.166, + "tps": 24061.59769, + "errors": 0 + }, + { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 4\nnumber of threads: 4\nmaximum number of tries: 1\nnumber of transactions per client: 100\nnumber of transactions actually processed: 400/400\nnumber of failed transactions: 0 (0.000%)\nlatency average = 0.169 ms\ninitial connection time = 1.770 ms\ntps = 23665.838362 (without initial connection time)\n", + "latency_avg_ms": 0.169, + "tps": 23665.838362, + "errors": 0 + }, + { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 4\nnumber of threads: 4\nmaximum number of tries: 1\nnumber of transactions per client: 100\nnumber of transactions actually processed: 400/400\nnumber of failed transactions: 0 (0.000%)\nlatency average = 0.152 ms\ninitial connection time = 1.640 ms\ntps = 26239.832065 (without initial connection time)\n", + "latency_avg_ms": 0.152, + "tps": 26239.832065, + "errors": 0 + } + ], + "median_execution_ms": 0.085, + "median_latency_ms": 0.166, + "median_tps": 24061.59769, + "errors": 0 + }, + { + "chat_messages": 100, + "position": "deep", + "clients": 1, + "plans": [ + { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 0.42, + "Total Cost": 8.58, + "Plan Rows": 51, + "Plan Width": 266, + "Actual Startup Time": 0.055, + "Actual Total Time": 0.057, + "Actual Rows": 11, + "Actual Loops": 1, + "Shared Hit Blocks": 3, + "Shared Read Blocks": 1, + "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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0, + "Plans": [ + { + "Node Type": "Index Only Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Scan Direction": "Forward", + "Index Name": "experiment_history_idx", + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.42, + "Total Cost": 15.78, + "Plan Rows": 96, + "Plan Width": 266, + "Actual Startup Time": 0.054, + "Actual Total Time": 0.056, + "Actual Rows": 11, + "Actual Loops": 1, + "Index Cond": "((chat_id = '00000000-0000-4000-8000-000000000004'::uuid) AND (ROW(created_at, id) > ROW(('2026-01-01 00:00:00+00'::timestamp with time zone + '00:00:00.00009'::interval), '00000000-0000-0000-0000-000000000000'::uuid)))", + "Rows Removed by Index Recheck": 0, + "Heap Fetches": 0, + "Shared Hit Blocks": 3, + "Shared Read Blocks": 1, + "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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0 + } + ] + }, + "Planning": { + "Shared Hit Blocks": 119, + "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.322, + "Triggers": [], + "Execution Time": 0.085 + }, + { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 0.42, + "Total Cost": 8.58, + "Plan Rows": 51, + "Plan Width": 266, + "Actual Startup Time": 0.024, + "Actual Total Time": 0.026, + "Actual Rows": 11, + "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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0, + "Plans": [ + { + "Node Type": "Index Only Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Scan Direction": "Forward", + "Index Name": "experiment_history_idx", + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.42, + "Total Cost": 15.78, + "Plan Rows": 96, + "Plan Width": 266, + "Actual Startup Time": 0.023, + "Actual Total Time": 0.025, + "Actual Rows": 11, + "Actual Loops": 1, + "Index Cond": "((chat_id = '00000000-0000-4000-8000-000000000004'::uuid) AND (ROW(created_at, id) > ROW(('2026-01-01 00:00:00+00'::timestamp with time zone + '00:00:00.00009'::interval), '00000000-0000-0000-0000-000000000000'::uuid)))", + "Rows Removed by Index Recheck": 0, + "Heap Fetches": 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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0 + } + ] + }, + "Planning": { + "Shared Hit Blocks": 119, + "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.342, + "Triggers": [], + "Execution Time": 0.058 + }, + { + "Plan": { + "Node Type": "Limit", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 0.42, + "Total Cost": 8.58, + "Plan Rows": 51, + "Plan Width": 266, + "Actual Startup Time": 0.024, + "Actual Total Time": 0.026, + "Actual Rows": 11, + "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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0, + "Plans": [ + { + "Node Type": "Index Only Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Scan Direction": "Forward", + "Index Name": "experiment_history_idx", + "Relation Name": "messages", + "Alias": "messages", + "Startup Cost": 0.42, + "Total Cost": 15.78, + "Plan Rows": 96, + "Plan Width": 266, + "Actual Startup Time": 0.023, + "Actual Total Time": 0.025, + "Actual Rows": 11, + "Actual Loops": 1, + "Index Cond": "((chat_id = '00000000-0000-4000-8000-000000000004'::uuid) AND (ROW(created_at, id) > ROW(('2026-01-01 00:00:00+00'::timestamp with time zone + '00:00:00.00009'::interval), '00000000-0000-0000-0000-000000000000'::uuid)))", + "Rows Removed by Index Recheck": 0, + "Heap Fetches": 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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0 + } + ] + }, + "Planning": { + "Shared Hit Blocks": 119, + "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.355, + "Triggers": [], + "Execution Time": 0.053 + } + ], + "runs": [ + { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 1\nnumber of threads: 1\nmaximum number of tries: 1\nnumber of transactions per client: 100\nnumber of transactions actually processed: 100/100\nnumber of failed transactions: 0 (0.000%)\nlatency average = 0.082 ms\ninitial connection time = 1.096 ms\ntps = 12257.906350 (without initial connection time)\n", + "latency_avg_ms": 0.082, + "tps": 12257.90635, + "errors": 0 + }, + { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 1\nnumber of threads: 1\nmaximum number of tries: 1\nnumber of transactions per client: 100\nnumber of transactions actually processed: 100/100\nnumber of failed transactions: 0 (0.000%)\nlatency average = 0.085 ms\ninitial connection time = 1.145 ms\ntps = 11830.119484 (without initial connection time)\n", + "latency_avg_ms": 0.085, + "tps": 11830.119484, + "errors": 0 + }, + { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 1\nnumber of threads: 1\nmaximum number of tries: 1\nnumber of transactions per client: 100\nnumber of transactions actually processed: 100/100\nnumber of failed transactions: 0 (0.000%)\nlatency average = 0.085 ms\ninitial connection time = 1.250 ms\ntps = 11717.834544 (without initial connection time)\n", + "latency_avg_ms": 0.085, + "tps": 11717.834544, + "errors": 0 + } + ], + "median_execution_ms": 0.058, + "median_latency_ms": 0.085, + "median_tps": 11830.119484, + "errors": 0 + }, + { + "chat_messages": 100, + "position": "deep", + "clients": 4, + "plans": [], + "runs": [ + { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 4\nnumber of threads: 4\nmaximum number of tries: 1\nnumber of transactions per client: 100\nnumber of transactions actually processed: 400/400\nnumber of failed transactions: 0 (0.000%)\nlatency average = 0.110 ms\ninitial connection time = 1.863 ms\ntps = 36426.554959 (without initial connection time)\n", + "latency_avg_ms": 0.11, + "tps": 36426.554959, + "errors": 0 + }, + { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 4\nnumber of threads: 4\nmaximum number of tries: 1\nnumber of transactions per client: 100\nnumber of transactions actually processed: 400/400\nnumber of failed transactions: 0 (0.000%)\nlatency average = 0.107 ms\ninitial connection time = 1.774 ms\ntps = 37334.328915 (without initial connection time)\n", + "latency_avg_ms": 0.107, + "tps": 37334.328915, + "errors": 0 + }, + { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 4\nnumber of threads: 4\nmaximum number of tries: 1\nnumber of transactions per client: 100\nnumber of transactions actually processed: 400/400\nnumber of failed transactions: 0 (0.000%)\nlatency average = 0.104 ms\ninitial connection time = 1.768 ms\ntps = 38339.883063 (without initial connection time)\n", + "latency_avg_ms": 0.104, + "tps": 38339.883063, + "errors": 0 + } + ], + "median_execution_ms": 0.058, + "median_latency_ms": 0.107, + "median_tps": 37334.328915, + "errors": 0 + } + ], + "writes": [ + { + "repeat": 1, + "plan": { + "Plan": { + "Node Type": "ModifyTable", + "Operation": "Insert", + "Parallel Aware": false, + "Async Capable": false, + "Relation Name": "write_probe", + "Alias": "write_probe", + "Startup Cost": 0.0, + "Total Cost": 42.5, + "Plan Rows": 0, + "Plan Width": 0, + "Actual Startup Time": 4.464, + "Actual Total Time": 4.464, + "Actual Rows": 0, + "Actual Loops": 1, + "Shared Hit Blocks": 4828, + "Shared Read Blocks": 2, + "Shared Dirtied Blocks": 71, + "Shared Written Blocks": 71, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "WAL Records": 3036, + "WAL FPI": 0, + "WAL Bytes": 639392, + "Plans": [ + { + "Node Type": "Function Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Function Name": "generate_series", + "Alias": "i", + "Startup Cost": 0.0, + "Total Cost": 42.5, + "Plan Rows": 1000, + "Plan Width": 88, + "Actual Startup Time": 0.27, + "Actual Total Time": 1.371, + "Actual Rows": 1000, + "Actual Loops": 1, + "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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0 + } + ] + }, + "Planning": { + "Shared Hit Blocks": 15, + "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.133, + "Triggers": [], + "Execution Time": 4.5 + }, + "transaction": { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 1\nnumber of threads: 1\nmaximum number of tries: 1\nnumber of transactions per client: 1\nnumber of transactions actually processed: 1/1\nnumber of failed transactions: 0 (0.000%)\nlatency average = 6.416 ms\ninitial connection time = 1.421 ms\ntps = 155.860349 (without initial connection time)\n", + "latency_avg_ms": 6.416, + "tps": 155.860349, + "errors": 0 + }, + "table_bytes": 606208 + }, + { + "repeat": 2, + "plan": { + "Plan": { + "Node Type": "ModifyTable", + "Operation": "Insert", + "Parallel Aware": false, + "Async Capable": false, + "Relation Name": "write_probe", + "Alias": "write_probe", + "Startup Cost": 0.0, + "Total Cost": 42.5, + "Plan Rows": 0, + "Plan Width": 0, + "Actual Startup Time": 4.167, + "Actual Total Time": 4.167, + "Actual Rows": 0, + "Actual Loops": 1, + "Shared Hit Blocks": 4828, + "Shared Read Blocks": 2, + "Shared Dirtied Blocks": 71, + "Shared Written Blocks": 71, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "WAL Records": 3036, + "WAL FPI": 0, + "WAL Bytes": 639392, + "Plans": [ + { + "Node Type": "Function Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Function Name": "generate_series", + "Alias": "i", + "Startup Cost": 0.0, + "Total Cost": 42.5, + "Plan Rows": 1000, + "Plan Width": 88, + "Actual Startup Time": 0.182, + "Actual Total Time": 1.196, + "Actual Rows": 1000, + "Actual Loops": 1, + "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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0 + } + ] + }, + "Planning": { + "Shared Hit Blocks": 15, + "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": 4.214 + }, + "transaction": { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 1\nnumber of threads: 1\nmaximum number of tries: 1\nnumber of transactions per client: 1\nnumber of transactions actually processed: 1/1\nnumber of failed transactions: 0 (0.000%)\nlatency average = 7.627 ms\ninitial connection time = 1.266 ms\ntps = 131.113151 (without initial connection time)\n", + "latency_avg_ms": 7.627, + "tps": 131.113151, + "errors": 0 + }, + "table_bytes": 606208 + }, + { + "repeat": 3, + "plan": { + "Plan": { + "Node Type": "ModifyTable", + "Operation": "Insert", + "Parallel Aware": false, + "Async Capable": false, + "Relation Name": "write_probe", + "Alias": "write_probe", + "Startup Cost": 0.0, + "Total Cost": 42.5, + "Plan Rows": 0, + "Plan Width": 0, + "Actual Startup Time": 3.86, + "Actual Total Time": 3.861, + "Actual Rows": 0, + "Actual Loops": 1, + "Shared Hit Blocks": 4827, + "Shared Read Blocks": 2, + "Shared Dirtied Blocks": 71, + "Shared Written Blocks": 71, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "WAL Records": 3036, + "WAL FPI": 0, + "WAL Bytes": 639392, + "Plans": [ + { + "Node Type": "Function Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Function Name": "generate_series", + "Alias": "i", + "Startup Cost": 0.0, + "Total Cost": 42.5, + "Plan Rows": 1000, + "Plan Width": 88, + "Actual Startup Time": 0.166, + "Actual Total Time": 1.092, + "Actual Rows": 1000, + "Actual Loops": 1, + "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, + "WAL Records": 0, + "WAL FPI": 0, + "WAL Bytes": 0 + } + ] + }, + "Planning": { + "Shared Hit Blocks": 15, + "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.148, + "Triggers": [], + "Execution Time": 3.889 + }, + "transaction": { + "raw": "pgbench (17.6)\ntransaction type: /tmp/lab2-bench.sql\nscaling factor: 1\nquery mode: prepared\nnumber of clients: 1\nnumber of threads: 1\nmaximum number of tries: 1\nnumber of transactions per client: 1\nnumber of transactions actually processed: 1/1\nnumber of failed transactions: 0 (0.000%)\nlatency average = 7.541 ms\ninitial connection time = 1.358 ms\ntps = 132.608407 (without initial connection time)\n", + "latency_avg_ms": 7.541, + "tps": 132.608407, + "errors": 0 + }, + "table_bytes": 606208 + } + ], + "resources": { + "measurement_seconds": 19.615, + "cpu_percent": 17.127, + "memory_before_bytes": 351948800, + "memory_after_bytes": 392208384, + "note": "cgroup memory includes shared buffers/page cache, not API RSS; CPU window includes setup and SQL trials" + } + } + ], + "backup_restore": { + "backup_seconds": 0.317, + "restore_seconds": 0.5, + "dump_bytes": 3021508, + "dump_sha256": "3634df322742b06aa892077bd094c881efcf3aae117d8450ae7da00753a66fd5", + "before": { + "users": 1, + "chats": 4, + "members": 4, + "messages": 100000, + "fingerprint": "1ffe686336b1693b25867f7bc2a823bf", + "samples": [ + { + "id": "00009263-a452-c704-35ab-2b606a67bb4a", + "chat_id": "00000000-0000-4000-8000-000000000001", + "sender_id": "00000000-0000-4000-8000-000000000001", + "text": "synthetic-27788xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", + "created_at": "2026-01-01T00:00:00.027788+00:00" + }, + { + "id": "0001adc0-ae70-10c3-41e9-1f3081e67502", + "chat_id": "00000000-0000-4000-8000-000000000001", + "sender_id": "00000000-0000-4000-8000-000000000001", + "text": "synthetic-31865xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", + "created_at": "2026-01-01T00:00:00.031865+00:00" + }, + { + "id": "0003b9d6-a698-d6b9-fd22-00dff7a0a44a", + "chat_id": "00000000-0000-4000-8000-000000000003", + "sender_id": "00000000-0000-4000-8000-000000000001", + "text": "synthetic-2806xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", + "created_at": "2026-01-01T00:00:00.002806+00:00" + }, + { + "id": "0003c03f-0f35-2b54-26ff-72deec99a8d9", + "chat_id": "00000000-0000-4000-8000-000000000002", + "sender_id": "00000000-0000-4000-8000-000000000001", + "text": "synthetic-4745xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", + "created_at": "2026-01-01T00:00:00.004745+00:00" + }, + { + "id": "0004be48-f98f-f451-423e-0fb67cb17566", + "chat_id": "00000000-0000-4000-8000-000000000001", + "sender_id": "00000000-0000-4000-8000-000000000001", + "text": "synthetic-47439xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", + "created_at": "2026-01-01T00:00:00.047439+00:00" + } + ] + }, + "after": { + "users": 1, + "chats": 4, + "members": 4, + "messages": 100000, + "fingerprint": "1ffe686336b1693b25867f7bc2a823bf", + "samples": [ + { + "id": "00009263-a452-c704-35ab-2b606a67bb4a", + "chat_id": "00000000-0000-4000-8000-000000000001", + "sender_id": "00000000-0000-4000-8000-000000000001", + "text": "synthetic-27788xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", + "created_at": "2026-01-01T00:00:00.027788+00:00" + }, + { + "id": "0001adc0-ae70-10c3-41e9-1f3081e67502", + "chat_id": "00000000-0000-4000-8000-000000000001", + "sender_id": "00000000-0000-4000-8000-000000000001", + "text": "synthetic-31865xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", + "created_at": "2026-01-01T00:00:00.031865+00:00" + }, + { + "id": "0003b9d6-a698-d6b9-fd22-00dff7a0a44a", + "chat_id": "00000000-0000-4000-8000-000000000003", + "sender_id": "00000000-0000-4000-8000-000000000001", + "text": "synthetic-2806xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", + "created_at": "2026-01-01T00:00:00.002806+00:00" + }, + { + "id": "0003c03f-0f35-2b54-26ff-72deec99a8d9", + "chat_id": "00000000-0000-4000-8000-000000000002", + "sender_id": "00000000-0000-4000-8000-000000000001", + "text": "synthetic-4745xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", + "created_at": "2026-01-01T00:00:00.004745+00:00" + }, + { + "id": "0004be48-f98f-f451-423e-0fb67cb17566", + "chat_id": "00000000-0000-4000-8000-000000000001", + "sender_id": "00000000-0000-4000-8000-000000000001", + "text": "synthetic-47439xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", + "created_at": "2026-01-01T00:00:00.047439+00:00" + } + ] + }, + "equal": true, + "source_after_backup_messages": 100001, + "restored_messages": 100000, + "post_backup_marker_present": false, + "new_storage": "restore-db, separate named restore_data volume, new empty database", + "rpo": "snapshot cutoff; demonstrated 1 later committed message absent, no WAL archive/PITR", + "rto": "restore only; excludes incident detection/provisioning/API switchover" + }, + "result": "PASS" +} diff --git a/evidence/explain-history.txt b/evidence/explain-history.txt new file mode 100644 index 00000000..c01b0b19 --- /dev/null +++ b/evidence/explain-history.txt @@ -0,0 +1,15 @@ +EXPLAIN (ANALYZE,BUFFERS) SELECT id::text,chat_id::text,sender_id::text,text,created_at FROM messages WHERE chat_id='00000000-0000-4000-8000-000000000001'::uuid AND (created_at,id)>('2026-01-01T00:00:00.072000Z'::timestamptz,'00000000-0000-0000-0000-000000000000'::uuid) ORDER BY messages.created_at,messages.id LIMIT 51; + + QUERY PLAN +---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + Limit (cost=0.42..46.30 rows=51 width=266) (actual time=0.088..0.118 rows=51 loops=1) + Buffers: shared hit=5 read=1 + -> Index Scan using messages_history_idx on messages (cost=0.42..5657.00 rows=6288 width=266) (actual time=0.088..0.114 rows=51 loops=1) + Index Cond: ((chat_id = '00000000-0000-4000-8000-000000000001'::uuid) AND (ROW(created_at, id) > ROW('2026-01-01 00:00:00.072+00'::timestamp with time zone, '00000000-0000-0000-0000-000000000000'::uuid))) + Buffers: shared hit=5 read=1 + Planning: + Buffers: shared hit=113 + Planning Time: 0.745 ms + Execution Time: 0.172 ms +(9 rows) + diff --git a/evidence/go-vet.txt b/evidence/go-vet.txt new file mode 100644 index 00000000..e69de29b diff --git a/evidence/http-load-1.json b/evidence/http-load-1.json new file mode 100644 index 00000000..204662e3 --- /dev/null +++ b/evidence/http-load-1.json @@ -0,0 +1,17 @@ +{ + "lab": 2, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 5.0, + "elapsed_seconds": 5.016, + "concurrency": 4, + "successful_requests": 7444, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 1484.098, + "successful_latency_ms": { + "p50": 2.48, + "p95": 4.003, + "p99": 5.947 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/evidence/http-load-2.json b/evidence/http-load-2.json new file mode 100644 index 00000000..12af1e02 --- /dev/null +++ b/evidence/http-load-2.json @@ -0,0 +1,17 @@ +{ + "lab": 2, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 5.0, + "elapsed_seconds": 5.029, + "concurrency": 4, + "successful_requests": 6949, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 1381.845, + "successful_latency_ms": { + "p50": 2.571, + "p95": 4.508, + "p99": 7.954 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/evidence/http-load-3.json b/evidence/http-load-3.json new file mode 100644 index 00000000..f2c533e8 --- /dev/null +++ b/evidence/http-load-3.json @@ -0,0 +1,17 @@ +{ + "lab": 2, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 5.0, + "elapsed_seconds": 5.018, + "concurrency": 4, + "successful_requests": 7309, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 1456.586, + "successful_latency_ms": { + "p50": 2.524, + "p95": 4.128, + "p99": 6.279 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/evidence/http-load-run.txt b/evidence/http-load-run.txt new file mode 100644 index 00000000..947b65fc --- /dev/null +++ b/evidence/http-load-run.txt @@ -0,0 +1,51 @@ +{ + "lab": 2, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 5.0, + "elapsed_seconds": 5.016, + "concurrency": 4, + "successful_requests": 7444, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 1484.098, + "successful_latency_ms": { + "p50": 2.48, + "p95": 4.003, + "p99": 5.947 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} +{ + "lab": 2, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 5.0, + "elapsed_seconds": 5.029, + "concurrency": 4, + "successful_requests": 6949, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 1381.845, + "successful_latency_ms": { + "p50": 2.571, + "p95": 4.508, + "p99": 7.954 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} +{ + "lab": 2, + "workload": "closed-loop POST messages; no automatic retries", + "requested_duration_seconds": 5.0, + "elapsed_seconds": 5.018, + "concurrency": 4, + "successful_requests": 7309, + "failed_requests": 0, + "error_ratio": 0.0, + "successful_rps": 1456.586, + "successful_latency_ms": { + "p50": 2.524, + "p95": 4.128, + "p99": 6.279 + }, + "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." +} diff --git a/evidence/integration.json b/evidence/integration.json new file mode 100644 index 00000000..9386f528 --- /dev/null +++ b/evidence/integration.json @@ -0,0 +1,43 @@ +{ + "checks": { + "strict_json_unicode_body_limits": true, + "username_race": [ + 409, + 201, + 409, + 409 + ], + "chat_rollback_after_fk_failure": true, + "100_concurrent_messages_and_keyset_scope": true, + "monotonic_chat_clock": true, + "authentication_and_chat_authorization": true, + "password_kdf_and_token_digest_storage": true, + "valkey_real_profile_cache_ttl": 299, + "cache_flush_repopulates_with_same_session": true, + "cache_down_fallback_and_read_after_write": true, + "database_down_fails_closed": { + "live": 200, + "ready": 503, + "request_seconds": 0.073 + }, + "logout_with_warm_cache": true, + "full_stack_restart_and_cursor": { + "before": { + "api": "2026-10-02T09:42:14.201023758Z", + "postgres": "2026-10-02T09:42:27.938008958Z", + "valkey": "2026-10-02T09:42:27.537210625Z" + }, + "after": { + "api": "2026-10-02T09:42:32.330163294Z", + "postgres": "2026-10-02T09:42:29.527737917Z", + "valkey": "2026-10-02T09:42:29.541207376Z" + }, + "counts_before": "52|20|22334|40|1", + "counts_after": "55|21|22335|43|1" + }, + "session_expiry_ttl_2_seconds": true, + "restart_does_not_shorten_existing_session": true + }, + "date_utc": "2026-10-02T09:42:24Z", + "result": "PASS" +} diff --git a/evidence/lifecycle-run.txt b/evidence/lifecycle-run.txt new file mode 100644 index 00000000..a7a38b2c --- /dev/null +++ b/evidence/lifecycle-run.txt @@ -0,0 +1,2 @@ +python3 student-tests/lifecycle.py --base-url "http://localhost:8082" +PASS: non-root, SIGTERM, same-session recovery, log privacy diff --git a/evidence/lifecycle.json b/evidence/lifecycle.json new file mode 100644 index 00000000..1c9292bd --- /dev/null +++ b/evidence/lifecycle.json @@ -0,0 +1,59 @@ +{ + "result": "PASS", + "date_utc": "2026-10-02T09:43:36Z", + "non_root_user": "10001:10001", + "pid1": "messenger", + "health": "healthy", + "sigterm_seconds": 0.208, + "exit_code": 0, + "oom_killed": false, + "same_session_and_message_after_api_restart": true, + "sensitive_body_password_token_absent_from_logs": true, + "shutdown_logs": [ + { + "time": "2026-10-02T09:43:35.682791128Z", + "level": "INFO", + "msg": "shutdown completed", + "duration_ms": 0 + } + ], + "images": [ + { + "id": "sha256:d95606280c8307e47500e4dacd5ab5f9a495e85841260c4c78380ebf565573f1", + "digests": [ + "mtusi-messenger@sha256:d95606280c8307e47500e4dacd5ab5f9a495e85841260c4c78380ebf565573f1" + ], + "tags": [ + "mtusi-messenger:lab2" + ] + }, + { + "id": "sha256:ef257d85f76e48da1c64832459b59fcaba1a4dac97bf5d7450c77753542eee94", + "digests": [ + "postgres@sha256:ef257d85f76e48da1c64832459b59fcaba1a4dac97bf5d7450c77753542eee94" + ], + "tags": [ + "postgres:17.6-alpine" + ] + }, + { + "id": "sha256:d827e7f7552cdee40cc7482dbae9da020f42bc47669af6f71182a4ef76a22773", + "digests": [ + "valkey/valkey@sha256:d827e7f7552cdee40cc7482dbae9da020f42bc47669af6f71182a4ef76a22773" + ], + "tags": [ + "valkey/valkey:8.1.3-alpine" + ] + } + ], + "durability": { + "fsync": "on", + "synchronous_commit": "on", + "full_page_writes": "on" + }, + "host": "macOS-26.6.2-arm64-arm-64bit", + "docker_vm": { + "cpus": 14, + "memory_bytes": 8217473024 + } +} diff --git a/evidence/public-smoke.txt b/evidence/public-smoke.txt new file mode 100644 index 00000000..88765c80 --- /dev/null +++ b/evidence/public-smoke.txt @@ -0,0 +1,2 @@ +python3 tests/smoke.py --base-url "http://localhost:8082" +PASS: lab2 public API scenario; infrastructure and grading evidence remain separate. diff --git a/evidence/race-http.txt b/evidence/race-http.txt new file mode 100644 index 00000000..758ef1ce --- /dev/null +++ b/evidence/race-http.txt @@ -0,0 +1,88 @@ +docker compose --env-file .env --profile verify run --build --rm tests + Container mtusi-lab2-kraykin-postgres-1 Running +Compose can now delegate builds to bake for better performance. + To do so, set COMPOSE_BAKE=true. +#0 building with "desktop-linux" instance using docker driver + +#1 [tests internal] load build definition from Dockerfile +#1 transferring dockerfile: 782B done +#1 DONE 0.0s + +#2 [tests internal] load metadata for docker.io/library/golang:1.24.4-alpine3.22 +#2 DONE 0.7s + +#3 [tests internal] load .dockerignore +#3 transferring context: 196B done +#3 DONE 0.0s + +#4 [tests build 1/7] FROM docker.io/library/golang:1.24.4-alpine3.22@sha256:68932fa6d4d4059845c8f40ad7e654e626f3ebd3706eef7846f319293ab5cb7a +#4 resolve docker.io/library/golang:1.24.4-alpine3.22@sha256:68932fa6d4d4059845c8f40ad7e654e626f3ebd3706eef7846f319293ab5cb7a done +#4 DONE 0.0s + +#5 [tests internal] load build context +#5 transferring context: 618B done +#5 DONE 0.0s + +#6 [tests build 6/7] COPY internal/ ./internal/ +#6 CACHED + +#7 [tests build 5/7] COPY cmd/ ./cmd/ +#7 CACHED + +#8 [tests build 3/7] COPY go.mod go.sum ./ +#8 CACHED + +#9 [tests build 2/7] WORKDIR /src +#9 CACHED + +#10 [tests build 4/7] RUN go mod download +#10 CACHED + +#11 [tests build 7/7] RUN CGO_ENABLED=0 go build -trimpath -ldflags="-s -w" -o /out/messenger ./cmd/server +#11 CACHED + +#12 [tests tests 1/1] RUN apk add --no-cache gcc musl-dev +#12 0.103 fetch https://dl-cdn.alpinelinux.org/alpine/v3.22/main/aarch64/APKINDEX.tar.gz +#12 1.303 fetch https://dl-cdn.alpinelinux.org/alpine/v3.22/community/aarch64/APKINDEX.tar.gz +#12 3.740 (1/14) Upgrading musl (1.2.5-r10 -> 1.2.5-r12) +#12 4.071 (2/14) Installing libgcc (14.2.0-r6) +#12 4.168 (3/14) Installing jansson (2.14.1-r0) +#12 4.242 (4/14) Installing libstdc++ (14.2.0-r6) +#12 4.889 (5/14) Installing zstd-libs (1.5.7-r0) +#12 5.156 (6/14) Installing binutils (2.44-r3) +#12 7.022 (7/14) Installing libgomp (14.2.0-r6) +#12 7.162 (8/14) Installing libatomic (14.2.0-r6) +#12 7.365 (9/14) Installing gmp (6.3.0-r3) +#12 7.531 (10/14) Installing isl26 (0.26-r1) +#12 8.107 (11/14) Installing mpfr4 (4.2.1_p1-r0) +#12 8.672 (12/14) Installing mpc1 (1.3.1-r1) +#12 8.772 (13/14) Installing gcc (14.2.0-r6) +#12 34.78 (14/14) Installing musl-dev (1.2.5-r12) +#12 35.52 Executing busybox-1.37.0-r18.trigger +#12 35.53 OK: 163 MiB in 30 packages +#12 DONE 35.7s + +#13 [tests] exporting to image +#13 exporting layers +#13 exporting layers 3.7s done +#13 exporting manifest sha256:623b75c2be9321b73ddfcd975dc96154ad76f3479b9957fe2c470536b5e30e45 +#13 exporting manifest sha256:623b75c2be9321b73ddfcd975dc96154ad76f3479b9957fe2c470536b5e30e45 done +#13 exporting config sha256:08ba6251faeb9acb4bc701d282a653337653dfba10e48980f21e42f3a188c648 done +#13 exporting attestation manifest sha256:f3e64072d1e6e17c83c1e60b5a7141f210a34107b747bb004b2a10186ff90cf2 done +#13 exporting manifest list sha256:929b7c668c3e0d3e7c73a8e303503541f2202bddc0b481699450bc20f8a87c8e done +#13 naming to docker.io/library/mtusi-lab2-kraykin-tests:latest done +#13 unpacking to docker.io/library/mtusi-lab2-kraykin-tests:latest +#13 unpacking to docker.io/library/mtusi-lab2-kraykin-tests:latest 1.1s done +#13 DONE 4.9s + +#14 [tests] resolving provenance for metadata file +#14 DONE 0.0s +? mtusi/messenger/cmd/server [no test files] +? mtusi/messenger/internal/database [no test files] +=== RUN TestDatabaseConcurrentHTTP + database_test.go:119: 100 confirmed messages from 10 clients through real HTTP and PostgreSQL; race detector enabled +--- PASS: TestDatabaseConcurrentHTTP (1.77s) +=== RUN TestPasswordFullUnicodeRange +--- PASS: TestPasswordFullUnicodeRange (2.20s) +PASS +ok mtusi/messenger/internal/messenger 5.009s diff --git a/evidence/startup.txt b/evidence/startup.txt new file mode 100644 index 00000000..102e60f5 --- /dev/null +++ b/evidence/startup.txt @@ -0,0 +1,14 @@ + Container mtusi-lab2-kraykin-valkey-1 Running + Container mtusi-lab2-kraykin-postgres-1 Running + Container mtusi-lab2-kraykin-api-1 Recreate + Container mtusi-lab2-kraykin-api-1 Recreated + Container mtusi-lab2-kraykin-postgres-1 Waiting + Container mtusi-lab2-kraykin-postgres-1 Healthy + Container mtusi-lab2-kraykin-api-1 Starting + Container mtusi-lab2-kraykin-api-1 Started + Container mtusi-lab2-kraykin-valkey-1 Waiting + Container mtusi-lab2-kraykin-api-1 Waiting + Container mtusi-lab2-kraykin-postgres-1 Waiting + Container mtusi-lab2-kraykin-valkey-1 Healthy + Container mtusi-lab2-kraykin-postgres-1 Healthy + Container mtusi-lab2-kraykin-api-1 Healthy diff --git a/evidence/student-tests.txt b/evidence/student-tests.txt new file mode 100644 index 00000000..3ed29f12 --- /dev/null +++ b/evidence/student-tests.txt @@ -0,0 +1,30 @@ +go test -race -count=1 -v ./... +? mtusi/messenger/cmd/server [no test files] +? mtusi/messenger/internal/database [no test files] +=== RUN TestDatabaseConcurrentHTTP + database_test.go:24: run make test-race for real PostgreSQL HTTP integration +--- SKIP: TestDatabaseConcurrentHTTP (0.00s) +=== RUN TestPasswordFullUnicodeRange +--- PASS: TestPasswordFullUnicodeRange (2.02s) +PASS +ok mtusi/messenger/internal/messenger 3.054s +python3 student-tests/integration.py --base-url "http://localhost:8082" +PASS: strict_json_unicode_body_limits +PASS: username_race +PASS: chat_rollback_after_fk_failure +PASS: 100_concurrent_messages_and_keyset_scope +PASS: monotonic_chat_clock +PASS: authentication_and_chat_authorization +PASS: password_kdf_and_token_digest_storage +PASS: valkey_real_profile_cache_ttl +PASS: cache_flush_repopulates_with_same_session +PASS: cache_down_fallback_and_read_after_write +PASS: database_down_fails_closed +PASS: logout_with_warm_cache +python3 tests/resilience.py --mode persistence --action-script "scripts/restart.sh" --base-url "http://localhost:8082" +Executing explicit persistence hook; hook output suppressed to avoid leaking secrets. +PASS: persistence preserved confirmed data and existing session. Hook scope needs operator evidence. +PASS: full_stack_restart_and_cursor +PASS: session_expiry_ttl_2_seconds +PASS: restart_does_not_shorten_existing_session +PASS: all student integration checks diff --git a/go.mod b/go.mod new file mode 100644 index 00000000..9f31dd11 --- /dev/null +++ b/go.mod @@ -0,0 +1,20 @@ +module mtusi/messenger + +go 1.24.0 + +require ( + github.com/jackc/pgx/v5 v5.7.6 + github.com/redis/go-redis/v9 v9.12.1 + golang.org/x/crypto v0.41.0 +) + +require ( + github.com/cespare/xxhash/v2 v2.3.0 // indirect + github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect + github.com/jackc/pgpassfile v1.0.0 // indirect + github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect + github.com/jackc/puddle/v2 v2.2.2 // indirect + golang.org/x/sync v0.16.0 // indirect + golang.org/x/sys v0.35.0 // indirect + golang.org/x/text v0.28.0 // indirect +) diff --git a/go.sum b/go.sum new file mode 100644 index 00000000..aa7cb204 --- /dev/null +++ b/go.sum @@ -0,0 +1,40 @@ +github.com/bsm/ginkgo/v2 v2.12.0 h1:Ny8MWAHyOepLGlLKYmXG4IEkioBysk6GpaRTLC8zwWs= +github.com/bsm/ginkgo/v2 v2.12.0/go.mod h1:SwYbGRRDovPVboqFv0tPTcG1sN61LM1Z4ARdbAV9g4c= +github.com/bsm/gomega v1.27.10 h1:yeMWxP2pV2fG3FgAODIY8EiRE3dy0aeFYt4l7wh6yKA= +github.com/bsm/gomega v1.27.10/go.mod h1:JyEr/xRbxbtgWNi8tIEVPUYZ5Dzef52k01W3YH0H+O0= +github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs= +github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78= +github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc= +github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM= +github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg= +github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo= +github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM= +github.com/jackc/pgx/v5 v5.7.6 h1:rWQc5FwZSPX58r1OQmkuaNicxdmExaEz5A2DO2hUuTk= +github.com/jackc/pgx/v5 v5.7.6/go.mod h1:aruU7o91Tc2q2cFp5h4uP3f6ztExVpyVv88Xl/8Vl8M= +github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo= +github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/redis/go-redis/v9 v9.12.1 h1:k5iquqv27aBtnTm2tIkROUDp8JBXhXZIVu1InSgvovg= +github.com/redis/go-redis/v9 v9.12.1/go.mod h1:huWgSWd8mW6+m0VPhJjSSQ+d6Nh1VICQ6Q5lHuCH/Iw= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= +github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.8.1 h1:w7B6lhMri9wdJUVmEZPGGhZzrYTPvgJArz7wNPgYKsk= +github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= +golang.org/x/crypto v0.41.0 h1:WKYxWedPGCTVVl5+WHSSrOBT0O8lx32+zxmHxijgXp4= +golang.org/x/crypto v0.41.0/go.mod h1:pO5AFd7FA68rFak7rOAGVuygIISepHftHnr8dr6+sUc= +golang.org/x/sync v0.16.0 h1:ycBJEhp9p4vXvUZNszeOq0kGTPghopOL8q0fq3vstxw= +golang.org/x/sync v0.16.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA= +golang.org/x/sys v0.35.0 h1:vz1N37gP5bs89s7He8XuIYXpyY0+QlsKmzipCbUtyxI= +golang.org/x/sys v0.35.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k= +golang.org/x/text v0.28.0 h1:rhazDwis8INMIwQ4tpjLDzUhx6RlXqZNPEM0huQojng= +golang.org/x/text v0.28.0/go.mod h1:U8nCwOR8jO/marOQ0QbDiOngZVEBB7MAiitBuMjXiNU= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/internal/database/database.go b/internal/database/database.go new file mode 100644 index 00000000..c96447f8 --- /dev/null +++ b/internal/database/database.go @@ -0,0 +1,94 @@ +package database + +import ( + "context" + "crypto/sha256" + "embed" + "fmt" + "github.com/jackc/pgx/v5/pgxpool" + "sort" + "time" +) + +//go:embed migrations/*.sql +var migrations embed.FS + +func Open(ctx context.Context, url string) (*pgxpool.Pool, error) { + cfg, err := pgxpool.ParseConfig(url) + if err != nil { + return nil, fmt.Errorf("invalid database configuration") + } + cfg.MaxConns = 10 + cfg.MinConns = 0 + cfg.MaxConnLifetime = 30 * time.Minute + cfg.MaxConnIdleTime = 5 * time.Minute + cfg.ConnConfig.ConnectTimeout = 2 * time.Second + cfg.ConnConfig.RuntimeParams["statement_timeout"] = "2000" + cfg.ConnConfig.RuntimeParams["lock_timeout"] = "1000" + pool, err := pgxpool.NewWithConfig(ctx, cfg) + if err != nil { + return nil, fmt.Errorf("cannot create database pool") + } + if err = pool.Ping(ctx); err != nil { + pool.Close() + return nil, fmt.Errorf("database unavailable") + } + return pool, nil +} + +// All migrations and the version ledger commit together. An advisory lock also +// serializes bootstrap across API instances; edited applied migrations fail. +func Migrate(ctx context.Context, pool *pgxpool.Pool) error { + tx, err := pool.Begin(ctx) + if err != nil { + return err + } + defer tx.Rollback(context.Background()) + if _, err = tx.Exec(ctx, "SELECT pg_advisory_xact_lock(2026002)"); err != nil { + return err + } + if _, err = tx.Exec(ctx, `CREATE TABLE IF NOT EXISTS schema_migrations(version text PRIMARY KEY, checksum text NOT NULL, applied_at timestamptz NOT NULL DEFAULT clock_timestamp())`); err != nil { + return err + } + entries, err := migrations.ReadDir("migrations") + if err != nil { + return err + } + sort.Slice(entries, func(i, j int) bool { return entries[i].Name() < entries[j].Name() }) + for _, entry := range entries { + body, err := migrations.ReadFile("migrations/" + entry.Name()) + if err != nil { + return err + } + checksum := fmt.Sprintf("%x", sha256.Sum256(body)) + var stored string + rows, err := tx.Query(ctx, "SELECT checksum FROM schema_migrations WHERE version=$1", entry.Name()) + if err != nil { + return err + } + found := rows.Next() + if found { + err = rows.Scan(&stored) + } + if err == nil { + err = rows.Err() + } + rows.Close() + if err != nil { + return err + } + if found { + if stored != checksum { + return fmt.Errorf("applied migration changed: %s", entry.Name()) + } + continue + } + if _, err = tx.Exec(ctx, string(body)); err != nil { + return err + } + if _, err = tx.Exec(ctx, "INSERT INTO schema_migrations(version,checksum) VALUES($1,$2)", entry.Name(), checksum); err != nil { + return err + } + } + return tx.Commit(ctx) +} diff --git a/internal/database/migrations/001_initial.sql b/internal/database/migrations/001_initial.sql new file mode 100644 index 00000000..005476d2 --- /dev/null +++ b/internal/database/migrations/001_initial.sql @@ -0,0 +1,36 @@ +CREATE TABLE users ( + id uuid PRIMARY KEY, + username text NOT NULL UNIQUE CHECK (username ~ '^[a-z0-9_]{3,32}$'), + display_name text NOT NULL CHECK (char_length(display_name) BETWEEN 1 AND 100), + password_hash text NOT NULL, + created_at timestamptz NOT NULL DEFAULT clock_timestamp() +); +CREATE TABLE chats ( + id uuid PRIMARY KEY, + title text NOT NULL CHECK (char_length(title) BETWEEN 1 AND 100), + created_at timestamptz NOT NULL DEFAULT clock_timestamp(), + last_message_at timestamptz NOT NULL DEFAULT '-infinity' +); +CREATE TABLE chat_members ( + chat_id uuid NOT NULL REFERENCES chats(id), + 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 TABLE messages ( + id uuid PRIMARY KEY, + chat_id uuid NOT NULL REFERENCES chats(id), + sender_id uuid NOT NULL, + text text NOT NULL CHECK (char_length(text) BETWEEN 1 AND 4000), + created_at timestamptz NOT NULL, + FOREIGN KEY (chat_id, sender_id) REFERENCES chat_members(chat_id, user_id) +); +CREATE INDEX messages_history_idx ON messages(chat_id, created_at, id); +CREATE INDEX chats_order_idx ON chats(created_at, id); +CREATE TABLE sessions ( + token_hash bytea PRIMARY KEY CHECK (octet_length(token_hash) = 32), + user_id uuid NOT NULL REFERENCES users(id), + expires_at timestamptz NOT NULL, + created_at timestamptz NOT NULL DEFAULT clock_timestamp() +); +CREATE INDEX sessions_expiry_idx ON sessions(expires_at); diff --git a/internal/messenger/database_test.go b/internal/messenger/database_test.go new file mode 100644 index 00000000..8a8325c3 --- /dev/null +++ b/internal/messenger/database_test.go @@ -0,0 +1,120 @@ +package messenger + +import ( + "context" + "encoding/base64" + "encoding/json" + "fmt" + "io" + "mtusi/messenger/internal/database" + "net/http" + "net/http/httptest" + "os" + "strings" + "sync" + "testing" + "time" +) + +// Real PostgreSQL + HTTP + the race detector, in the optional Compose tests +// service. Local go test skips this test unless the DB secret path is supplied. +func TestDatabaseConcurrentHTTP(t *testing.T) { + path := os.Getenv("DATABASE_TEST_URL_FILE") + if path == "" { + t.Skip("run make test-race for real PostgreSQL HTTP integration") + } + raw, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + pool, err := database.Open(ctx, strings.TrimSpace(string(raw))) + if err != nil { + t.Fatal(err) + } + defer pool.Close() + if err = database.Migrate(ctx, pool); err != nil { + t.Fatal(err) + } + api := New(pool, nil, make([]byte, 32), 3600, nil) + ts := httptest.NewServer(api) + defer ts.Close() + call := func(method, path, body, auth string, status int) map[string]any { + t.Helper() + r, err := http.NewRequest(method, ts.URL+path, strings.NewReader(body)) + if err != nil { + t.Error(err) + return nil + } + if body != "" { + r.Header.Set("Content-Type", "application/json") + } + r.Header.Set("Authorization", auth) + response, err := ts.Client().Do(r) + if err != nil { + t.Error(err) + return nil + } + defer response.Body.Close() + b, err := io.ReadAll(response.Body) + if err != nil { + t.Error(err) + return nil + } + if response.StatusCode != status { + t.Errorf("%s %s: want %d got %d", method, path, status, response.StatusCode) + return nil + } + var v map[string]any + if err = json.Unmarshal(b, &v); err != nil { + t.Error(err) + } + return v + } + username := "go_" + strings.ReplaceAll(uuid(), "-", "")[:20] + user := call("POST", "/api/v1/users", fmt.Sprintf(`{"username":%q,"display_name":"Race","password":"Synthetic-Go-Test-123"}`, username), "", 201) + if user == nil { + t.Fatal("create failed") + } + basic := "Basic " + base64.StdEncoding.EncodeToString([]byte(username+":Synthetic-Go-Test-123")) + session := call("POST", "/api/v1/auth/sessions", "", basic, 201) + if session == nil { + t.Fatal("login failed") + } + bearer := "Bearer " + session["token"].(string) + chat := call("POST", "/api/v1/chats", fmt.Sprintf(`{"title":"Race","member_ids":[%q]}`, user["id"]), bearer, 201) + if chat == nil { + t.Fatal("chat failed") + } + messages := "/api/v1/chats/" + chat["id"].(string) + "/messages" + var wg sync.WaitGroup + for worker := 0; worker < 10; worker++ { + wg.Add(1) + go func(worker int) { + defer wg.Done() + for j := 0; j < 10; j++ { + call("POST", messages, fmt.Sprintf(`{"text":"worker-%d-message-%d"}`, worker, j), bearer, 201) + } + }(worker) + } + wg.Wait() + page := call("GET", messages+"?limit=100", "", bearer, 200) + if page == nil { + t.Fatal("history failed") + } + items := page["items"].([]any) + if len(items) != 100 { + t.Fatalf("expected 100 messages, got %d", len(items)) + } + seen := map[string]bool{} + for _, v := range items { + m := v.(map[string]any) + id := m["id"].(string) + if seen[id] { + t.Fatal("duplicate ID") + } + seen[id] = true + } + t.Log("100 confirmed messages from 10 clients through real HTTP and PostgreSQL; race detector enabled") +} diff --git a/internal/messenger/password.go b/internal/messenger/password.go new file mode 100644 index 00000000..925705d8 --- /dev/null +++ b/internal/messenger/password.go @@ -0,0 +1,33 @@ +package messenger + +import ( + "crypto/rand" + "crypto/subtle" + "encoding/base64" + "golang.org/x/crypto/argon2" + "strings" +) + +// Fixed, bounded parameters: 64 MiB, 3 passes, 2 lanes, 16-byte salt, +// 32-byte result. The HTTP layer bounds simultaneous KDF work to 2 calls. +func hashPassword(password string) string { + salt := make([]byte, 16) + if _, err := rand.Read(salt); err != nil { + panic(err) + } + hash := argon2.IDKey([]byte(password), salt, 3, 64*1024, 2, 32) + return "$argon2id$v=19$m=65536,t=3,p=2$" + base64.RawStdEncoding.EncodeToString(salt) + "$" + base64.RawStdEncoding.EncodeToString(hash) +} +func verifyPassword(password, encoded string) bool { + parts := strings.Split(encoded, "$") + if len(parts) != 6 || strings.Join(parts[:4], "$") != "$argon2id$v=19$m=65536,t=3,p=2" { + return false + } + salt, e1 := base64.RawStdEncoding.DecodeString(parts[4]) + want, e2 := base64.RawStdEncoding.DecodeString(parts[5]) + if e1 != nil || e2 != nil || len(salt) != 16 || len(want) != 32 { + return false + } + got := argon2.IDKey([]byte(password), salt, 3, 64*1024, 2, 32) + return subtle.ConstantTimeCompare(got, want) == 1 +} diff --git a/internal/messenger/password_test.go b/internal/messenger/password_test.go new file mode 100644 index 00000000..a24a668c --- /dev/null +++ b/internal/messenger/password_test.go @@ -0,0 +1,20 @@ +package messenger + +import ( + "strings" + "testing" +) + +func TestPasswordFullUnicodeRange(t *testing.T) { + password := strings.Repeat("🙂", 128) // 512 bytes: exceeds bcrypt's 72-byte limit. + hash := hashPassword(password) + if !verifyPassword(password, hash) || verifyPassword(password+"x", hash) { + t.Fatal("password mismatch") + } + if hash == hashPassword(password) { + t.Fatal("salt reused") + } + if verifyPassword(password, "$argon2id$v=19$m=999999999,t=3,p=2$abc$def") { + t.Fatal("unbounded parameters accepted") + } +} diff --git a/internal/messenger/server.go b/internal/messenger/server.go new file mode 100644 index 00000000..6eb1b35d --- /dev/null +++ b/internal/messenger/server.go @@ -0,0 +1,693 @@ +// Package messenger implements the lab2 contract. PostgreSQL is authoritative. +package messenger + +import ( + "bytes" + "context" + "crypto/hmac" + "crypto/rand" + "crypto/sha256" + "encoding/base64" + "encoding/json" + "errors" + "fmt" + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgconn" + "github.com/jackc/pgx/v5/pgxpool" + "github.com/redis/go-redis/v9" + "io" + "log/slog" + "mime" + "net/http" + "net/url" + "regexp" + "strconv" + "strings" + "sync/atomic" + "time" + "unicode/utf8" +) + +type User struct { + ID string `json:"id"` + Username string `json:"username"` + DisplayName string `json:"display_name"` + CreatedAt string `json:"created_at"` +} +type Chat struct { + ID string `json:"id"` + Title string `json:"title"` + MemberIDs []string `json:"member_ids"` + CreatedAt string `json:"created_at"` +} +type Message struct { + ID string `json:"id"` + ChatID string `json:"chat_id"` + SenderID string `json:"sender_id"` + Text string `json:"text"` + CreatedAt string `json:"created_at"` +} +type Page[T any] struct { + Items []T `json:"items"` + NextCursor *string `json:"next_cursor"` +} + +func uuid() string { + b := make([]byte, 16) + if _, err := rand.Read(b); err != nil { + panic(err) + } + b[6] = (b[6] & 15) | 64 + b[8] = (b[8] & 63) | 128 + return fmt.Sprintf("%x-%x-%x-%x-%x", b[:4], b[4:6], b[6:8], b[8:10], b[10:]) +} + +var uuidRE = regexp.MustCompile(`^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$`) +var usernameRE = regexp.MustCompile(`^[a-z0-9_]{3,32}$`) + +func validText(v string, max int) bool { + return utf8.ValidString(v) && strings.TrimSpace(v) != "" && utf8.RuneCountInString(v) <= max +} +func reply(w http.ResponseWriter, status int, v any) { + w.WriteHeader(status) + _ = json.NewEncoder(w).Encode(v) +} +func fail(w http.ResponseWriter, status int, code, msg string) { + reply(w, status, map[string]any{"error": map[string]string{"code": code, "message": msg, "request_id": w.Header().Get("X-Request-Id")}}) +} +func bad(w http.ResponseWriter) { fail(w, 400, "invalid_request", "Invalid request") } +func missing(w http.ResponseWriter) { fail(w, 404, "not_found", "Object not found") } + +// Decode exact object keys (encoding/json structs alone accept case variants). +// Reject null, duplicate keys, trailing documents and invalid UTF-8 as well. +func decode(w http.ResponseWriter, r *http.Request, dst any, fields ...string) bool { + media, _, err := mime.ParseMediaType(r.Header.Get("Content-Type")) + if err != nil || media != "application/json" { + fail(w, 415, "unsupported_media_type", "Expected application/json") + return false + } + b, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 1<<20)) + if err != nil { + if _, ok := err.(*http.MaxBytesError); ok { + fail(w, 413, "payload_too_large", "Body exceeds 1 MiB") + } else { + bad(w) + } + return false + } + if !utf8.Valid(b) { + bad(w) + return false + } + d := json.NewDecoder(bytes.NewReader(b)) + token, err := d.Token() + if err != nil || token != json.Delim('{') { + bad(w) + return false + } + allowed := map[string]bool{} + for _, f := range fields { + allowed[f] = true + } + seen := map[string]bool{} + for d.More() { + t, e := d.Token() + k, ok := t.(string) + if e != nil || !ok || !allowed[k] || seen[k] { + bad(w) + return false + } + seen[k] = true + var raw json.RawMessage + if d.Decode(&raw) != nil || bytes.Equal(raw, []byte("null")) { + bad(w) + return false + } + } + if _, err = d.Token(); err != nil { + bad(w) + return false + } + if _, err = d.Token(); err != io.EOF { + bad(w) + return false + } + if len(seen) != len(allowed) || json.Unmarshal(b, dst) != nil { + bad(w) + return false + } + return true +} + +type cursor struct { + Scope string `json:"scope"` + Time string `json:"time"` + ID string `json:"id"` +} + +func (s *Server) encodeCursor(c cursor) *string { + b, _ := json.Marshal(c) + mac := hmac.New(sha256.New, s.secret) + mac.Write(b) + v := base64.RawURLEncoding.EncodeToString(b) + "." + base64.RawURLEncoding.EncodeToString(mac.Sum(nil)) + return &v +} +func (s *Server) pagination(w http.ResponseWriter, r *http.Request, scope string) (int, cursor, bool) { + var c cursor + limit := 50 + // ParseQuery explicitly reports malformed escaping, unlike URL.Query. + values, e := url.ParseQuery(r.URL.RawQuery) + if e != nil { + bad(w) + return 0, c, false + } + if v, ok := values["limit"]; ok { + if len(v) != 1 || v[0] == "" || strings.Trim(v[0], "0123456789") != "" { + bad(w) + return 0, c, false + } + limit, e = strconv.Atoi(v[0]) + if e != nil || limit < 1 || limit > 100 { + bad(w) + return 0, c, false + } + } + if v, ok := values["cursor"]; ok { + if len(v) != 1 || len(v[0]) > 2048 { + bad(w) + return 0, c, false + } + parts := strings.Split(v[0], ".") + if len(parts) != 2 { + bad(w) + return 0, c, false + } + b, e1 := base64.RawURLEncoding.DecodeString(parts[0]) + sig, e2 := base64.RawURLEncoding.DecodeString(parts[1]) + mac := hmac.New(sha256.New, s.secret) + mac.Write(b) + if e1 != nil || e2 != nil || !hmac.Equal(sig, mac.Sum(nil)) || json.Unmarshal(b, &c) != nil || c.Scope != scope || !uuidRE.MatchString(c.ID) { + bad(w) + return 0, c, false + } + } + if c.ID != "" { + if _, err := time.Parse(time.RFC3339Nano, c.Time); err != nil { + bad(w) + return 0, c, false + } + } + return limit, c, true +} + +type Server struct { + db *pgxpool.Pool + cache *redis.Client + secret []byte + ttl int + log *slog.Logger + stopping atomic.Bool + kdf chan struct{} + dummyHash string +} + +func New(db *pgxpool.Pool, cache *redis.Client, secret []byte, ttl int, logger *slog.Logger) *Server { + return &Server{db: db, cache: cache, secret: secret, ttl: ttl, log: logger, kdf: make(chan struct{}, 2), dummyHash: hashPassword("dummy-not-a-real-password")} +} +func (s *Server) Stop() { s.stopping.Store(true) } +func (s *Server) acquireKDF(ctx context.Context, w http.ResponseWriter) bool { + select { + case s.kdf <- struct{}{}: + return true + case <-ctx.Done(): + unavailable(w) + return false + } +} +func unavailable(w http.ResponseWriter) { + fail(w, 503, "unavailable", "Dependency temporarily unavailable") +} +func unauthorized(w http.ResponseWriter, scheme string) { + challenge := scheme + ` realm="messenger"` + if scheme == "Basic" { + challenge += `, charset="UTF-8"` + } + w.Header().Set("WWW-Authenticate", challenge) + fail(w, 401, "unauthorized", "Invalid or missing credentials") +} +func stamp(t time.Time) string { return t.UTC().Format("2006-01-02T15:04:05.000000Z") } + +const userColumns = "id::text, username, display_name, created_at" + +type scanner interface{ Scan(...any) error } + +func scanUser(row scanner) (User, error) { + var u User + var t time.Time + err := row.Scan(&u.ID, &u.Username, &u.DisplayName, &t) + u.CreatedAt = stamp(t) + return u, err +} +func scanMessage(row scanner) (Message, error) { + var m Message + var t time.Time + err := row.Scan(&m.ID, &m.ChatID, &m.SenderID, &m.Text, &t) + m.CreatedAt = stamp(t) + return m, err +} + +func (s *Server) profile(ctx context.Context, uid string) (User, error) { + // Valkey caches ONLY immutable User JSON. Session validity is always read + // from PostgreSQL first; cache loss never permits anonymous access. + key := "profile:v1:" + uid + if s.cache != nil { + c, cancel := context.WithTimeout(ctx, 80*time.Millisecond) + raw, err := s.cache.Get(c, key).Bytes() + cancel() + var u User + if err == nil && json.Unmarshal(raw, &u) == nil && u.ID == uid { + return u, nil + } + } + u, err := scanUser(s.db.QueryRow(ctx, "SELECT "+userColumns+" FROM users WHERE id=$1", uid)) + if err != nil { + return u, err + } + if s.cache != nil { + raw, _ := json.Marshal(u) + c, cancel := context.WithTimeout(ctx, 80*time.Millisecond) + _ = s.cache.Set(c, key, raw, 300*time.Second).Err() + cancel() + } + return u, nil +} +func (s *Server) authenticate(w http.ResponseWriter, r *http.Request) (User, []byte, bool) { + parts := strings.Fields(r.Header.Get("Authorization")) + if len(parts) != 2 || !strings.EqualFold(parts[0], "Bearer") { + unauthorized(w, "Bearer") + return User{}, nil, false + } + raw, err := base64.RawURLEncoding.DecodeString(parts[1]) + if err != nil || len(raw) != 32 { + unauthorized(w, "Bearer") + return User{}, nil, false + } + digest := sha256.Sum256([]byte(parts[1])) + var uid string + err = s.db.QueryRow(r.Context(), "SELECT user_id::text FROM sessions WHERE token_hash=$1 AND expires_at>clock_timestamp()", digest[:]).Scan(&uid) + if errors.Is(err, pgx.ErrNoRows) { + unauthorized(w, "Bearer") + return User{}, nil, false + } + if err != nil { + unavailable(w) + return User{}, nil, false + } + u, err := s.profile(r.Context(), uid) + if err != nil { + unavailable(w) + return User{}, nil, false + } + return u, digest[:], true +} + +type recorder struct { + http.ResponseWriter + status int +} + +func (w *recorder) WriteHeader(status int) { w.status = status; w.ResponseWriter.WriteHeader(status) } +func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { + start := time.Now() + out := &recorder{w, 200} + w = out + w.Header().Set("Content-Type", "application/json; charset=utf-8") + w.Header().Set("X-Request-Id", uuid()) + ctx, cancel := context.WithTimeout(r.Context(), 3*time.Second) + defer cancel() + r = r.WithContext(ctx) + route := "unknown" + defer func() { + if recover() != nil { + fail(w, 500, "internal_error", "Internal server error") + } + if s.log != nil { + s.log.Info("request", "method", r.Method, "route", route, "status", out.status, "duration_us", time.Since(start).Microseconds(), "request_id", w.Header().Get("X-Request-Id")) + } + }() + if r.Method == "GET" && (r.URL.Path == "/health/live" || r.URL.Path == "/health/ready") { + route = r.URL.Path + if r.URL.Path == "/health/ready" && (s.stopping.Load() || s.db.Ping(ctx) != nil) { + unavailable(w) + } else { + reply(w, 200, map[string]string{"status": "ok"}) + } + return + } + if s.stopping.Load() { + unavailable(w) + return + } + if r.Method == "POST" && r.URL.Path == "/api/v1/users" { + route = "/users" + s.createUser(w, r) + return + } + if r.Method == "POST" && r.URL.Path == "/api/v1/auth/sessions" { + route = "/auth/sessions" + s.login(w, r) + return + } + user, digest, ok := s.authenticate(w, r) + if !ok { + return + } + if r.Method == "DELETE" && r.URL.Path == "/api/v1/auth/sessions/current" { + route = "/auth/sessions/current" + tag, err := s.db.Exec(ctx, "DELETE FROM sessions WHERE token_hash=$1", digest) + if err != nil { + unavailable(w) + } else if tag.RowsAffected() == 0 { + unauthorized(w, "Bearer") + } else { + w.WriteHeader(204) + } + return + } + if r.Method == "GET" && r.URL.Path == "/api/v1/users/me" { + route = "/users/me" + reply(w, 200, user) + return + } + if r.URL.Path == "/api/v1/chats" { + route = "/chats" + switch r.Method { + case "POST": + s.createChat(w, r, user.ID) + case "GET": + s.listChats(w, r, user.ID) + default: + missing(w) + } + return + } + parts := strings.Split(strings.TrimPrefix(r.URL.Path, "/"), "/") + if len(parts) < 4 || len(parts) > 5 || parts[0] != "api" || parts[1] != "v1" || parts[2] != "chats" { + missing(w) + return + } + cid := strings.ToLower(parts[3]) + route = "/chats/{id}" + if !uuidRE.MatchString(cid) { + bad(w) + return + } + chat, err := s.getChat(ctx, cid, user.ID) + if errors.Is(err, pgx.ErrNoRows) { + missing(w) + return + } + if err != nil { + unavailable(w) + return + } + if len(parts) == 4 && r.Method == "GET" { + reply(w, 200, chat) + return + } + if len(parts) == 5 && parts[4] == "messages" { + route = "/chats/{id}/messages" + switch r.Method { + case "POST": + s.createMessage(w, r, user.ID, cid) + case "GET": + s.listMessages(w, r, cid) + default: + missing(w) + } + return + } + missing(w) +} +func (s *Server) createUser(w http.ResponseWriter, r *http.Request) { + var input struct { + Username string `json:"username"` + DisplayName string `json:"display_name"` + Password string `json:"password"` + } + if !decode(w, r, &input, "username", "display_name", "password") { + return + } + if !usernameRE.MatchString(input.Username) || !validText(input.DisplayName, 100) || !validText(input.Password, 128) || utf8.RuneCountInString(input.Password) < 12 { + bad(w) + return + } + if !s.acquireKDF(r.Context(), w) { + return + } + hash := hashPassword(input.Password) + <-s.kdf + u, err := scanUser(s.db.QueryRow(r.Context(), "INSERT INTO users(id,username,display_name,password_hash) VALUES($1,$2,$3,$4) RETURNING "+userColumns, uuid(), input.Username, input.DisplayName, hash)) + var pgerr *pgconn.PgError + if errors.As(err, &pgerr) && pgerr.Code == "23505" { + fail(w, 409, "conflict", "Username already exists") + return + } + if err != nil { + unavailable(w) + return + } + reply(w, 201, u) +} +func (s *Server) login(w http.ResponseWriter, r *http.Request) { + body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 1)) + if err != nil || len(body) != 0 { + bad(w) + return + } + username, password, ok := r.BasicAuth() + if !ok || !usernameRE.MatchString(username) || !validText(password, 128) || utf8.RuneCountInString(password) < 12 { + unauthorized(w, "Basic") + return + } + var u User + var hash string + var t time.Time + err = s.db.QueryRow(r.Context(), "SELECT "+userColumns+", password_hash FROM users WHERE username=$1", username).Scan(&u.ID, &u.Username, &u.DisplayName, &t, &hash) + absent := errors.Is(err, pgx.ErrNoRows) + if err != nil && !absent { + unavailable(w) + return + } + if absent { + hash = s.dummyHash + } + if !s.acquireKDF(r.Context(), w) { + return + } + valid := verifyPassword(password, hash) + <-s.kdf + if !valid || absent { + unauthorized(w, "Basic") + return + } + raw := make([]byte, 32) + if _, err = rand.Read(raw); err != nil { + panic(err) + } + token := base64.RawURLEncoding.EncodeToString(raw) + digest := sha256.Sum256([]byte(token)) + var expires time.Time + err = s.db.QueryRow(r.Context(), "INSERT INTO sessions(token_hash,user_id,expires_at) VALUES($1,$2,clock_timestamp()+make_interval(secs=>$3)) RETURNING expires_at", digest[:], u.ID, s.ttl).Scan(&expires) + if err != nil { + unavailable(w) + return + } + u.CreatedAt = stamp(t) + reply(w, 201, map[string]any{"token": token, "token_type": "Bearer", "expires_at": stamp(expires), "user": u}) +} +func (s *Server) createChat(w http.ResponseWriter, r *http.Request, uid string) { + var input struct { + Title string `json:"title"` + MemberIDs []string `json:"member_ids"` + } + if !decode(w, r, &input, "title", "member_ids") { + return + } + if !validText(input.Title, 100) || len(input.MemberIDs) < 1 || len(input.MemberIDs) > 100 { + bad(w) + return + } + seen := map[string]bool{} + for i, id := range input.MemberIDs { + id = strings.ToLower(id) + if !uuidRE.MatchString(id) || seen[id] { + bad(w) + return + } + seen[id] = true + input.MemberIDs[i] = id + } + if !seen[uid] { + bad(w) + return + } + tx, err := s.db.Begin(r.Context()) + if err != nil { + unavailable(w) + return + } + defer tx.Rollback(context.Background()) + chat := Chat{ID: uuid(), Title: input.Title, MemberIDs: input.MemberIDs} + var t time.Time + err = tx.QueryRow(r.Context(), "INSERT INTO chats(id,title) VALUES($1,$2) RETURNING created_at", chat.ID, chat.Title).Scan(&t) + if err != nil { + unavailable(w) + return + } + for _, id := range input.MemberIDs { + _, err = tx.Exec(r.Context(), "INSERT INTO chat_members(chat_id,user_id) VALUES($1,$2)", chat.ID, id) + var pgerr *pgconn.PgError + if errors.As(err, &pgerr) && pgerr.Code == "23503" { + bad(w) + return + } + if err != nil { + unavailable(w) + return + } + } + if tx.Commit(r.Context()) != nil { + unavailable(w) + return + } + chat.CreatedAt = stamp(t) + reply(w, 201, chat) +} + +const chatColumns = `c.id::text,c.title,c.created_at,ARRAY(SELECT m.user_id::text FROM chat_members m WHERE m.chat_id=c.id ORDER BY m.user_id)` + +func scanChat(row scanner) (Chat, error) { + var c Chat + var t time.Time + err := row.Scan(&c.ID, &c.Title, &t, &c.MemberIDs) + c.CreatedAt = stamp(t) + return c, err +} +func (s *Server) getChat(ctx context.Context, cid, uid string) (Chat, error) { + return scanChat(s.db.QueryRow(ctx, "SELECT "+chatColumns+" FROM chats c JOIN chat_members a ON a.chat_id=c.id AND a.user_id=$2 WHERE c.id=$1", cid, uid)) +} +func (s *Server) createMessage(w http.ResponseWriter, r *http.Request, uid, cid string) { + var input struct { + Text string `json:"text"` + } + if !decode(w, r, &input, "text") { + return + } + if !validText(input.Text, 4000) { + bad(w) + return + } + // One transaction serializes writers only within this chat. Timestamp is + // monotonic even after clock rollback; commit precedes the HTTP confirmation. + tx, err := s.db.Begin(r.Context()) + if err != nil { + unavailable(w) + return + } + defer tx.Rollback(context.Background()) + var t time.Time + err = tx.QueryRow(r.Context(), "UPDATE chats SET last_message_at=GREATEST(clock_timestamp(),last_message_at+interval '1 microsecond') WHERE id=$1 RETURNING last_message_at", cid).Scan(&t) + if err != nil { + unavailable(w) + return + } + m, err := scanMessage(tx.QueryRow(r.Context(), "INSERT INTO messages(id,chat_id,sender_id,text,created_at) VALUES($1,$2,$3,$4,$5) RETURNING id::text,chat_id::text,sender_id::text,text,created_at", uuid(), cid, uid, input.Text, t)) + if err != nil || tx.Commit(r.Context()) != nil { + unavailable(w) + return + } + reply(w, 201, m) +} +func (s *Server) listMessages(w http.ResponseWriter, r *http.Request, cid string) { + scope := "messages:" + cid + limit, c, ok := s.pagination(w, r, scope) + if !ok { + return + } + query := `SELECT id::text,chat_id::text,sender_id::text,text,created_at FROM messages WHERE chat_id=$1` + args := []any{cid} + if c.ID != "" { + query += ` AND (created_at,id)>($2::timestamptz,$3::uuid)` + args = append(args, c.Time, c.ID) + } + query += fmt.Sprintf(" ORDER BY messages.created_at,messages.id LIMIT $%d", len(args)+1) + args = append(args, limit+1) + rows, err := s.db.Query(r.Context(), query, args...) + if err != nil { + unavailable(w) + return + } + defer rows.Close() + items := []Message{} + for rows.Next() { + m, err := scanMessage(rows) + if err != nil { + unavailable(w) + return + } + items = append(items, m) + } + if rows.Err() != nil { + unavailable(w) + return + } + var next *string + if len(items) > limit { + items = items[:limit] + last := items[limit-1] + next = s.encodeCursor(cursor{scope, last.CreatedAt, last.ID}) + } + reply(w, 200, Page[Message]{items, next}) +} +func (s *Server) listChats(w http.ResponseWriter, r *http.Request, uid string) { + scope := "chats:" + uid + limit, c, ok := s.pagination(w, r, scope) + if !ok { + return + } + query := "SELECT " + chatColumns + " FROM chats c JOIN chat_members a ON a.chat_id=c.id AND a.user_id=$1" + args := []any{uid} + if c.ID != "" { + query += " WHERE (c.created_at,c.id)>($2::timestamptz,$3::uuid)" + args = append(args, c.Time, c.ID) + } + query += fmt.Sprintf(" ORDER BY c.created_at,c.id LIMIT $%d", len(args)+1) + args = append(args, limit+1) + rows, err := s.db.Query(r.Context(), query, args...) + if err != nil { + unavailable(w) + return + } + defer rows.Close() + items := []Chat{} + for rows.Next() { + chat, err := scanChat(rows) + if err != nil { + unavailable(w) + return + } + items = append(items, chat) + } + if rows.Err() != nil { + unavailable(w) + return + } + var next *string + if len(items) > limit { + items = items[:limit] + last := items[limit-1] + next = s.encodeCursor(cursor{scope, last.CreatedAt, last.ID}) + } + reply(w, 200, Page[Chat]{items, next}) +} diff --git a/postman/lab2.postman_collection.json b/postman/lab2.postman_collection.json new file mode 100644 index 00000000..2fc9e5d4 --- /dev/null +++ b/postman/lab2.postman_collection.json @@ -0,0 +1,860 @@ +{ + "info": { + "name": "ЛР 2 — Крайкин БВТ2303 — PostgreSQL и сессии", + "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json", + "description": "Запустите make up. Run выполняет 23 запроса сверху вниз, сохраняет ID и токены только в локальные переменные Postman. Новый run_id позволяет повторять сценарий. Для ручной проверки persistence остановитесь после 17, выполните scripts/restart.sh, повторите 09 и 15 с прежним Bearer, затем 22 и 23. Никаких реальных паролей; demo_password синтетический. Для localhost нужен настольный Postman/Desktop Agent. Перед экспортом коллекции очистите значения токенов." + }, + "variable": [ + { + "key": "base_url", + "value": "http://localhost:8082", + "type": "string" + }, + { + "key": "demo_password", + "value": "Synthetic-Postman-Demo-123", + "type": "string" + }, + { + "key": "run_id", + "value": "", + "type": "string" + }, + { + "key": "alice_id", + "value": "", + "type": "string" + }, + { + "key": "bob_id", + "value": "", + "type": "string" + }, + { + "key": "eve_id", + "value": "", + "type": "string" + }, + { + "key": "alice_token", + "value": "", + "type": "string" + }, + { + "key": "bob_token", + "value": "", + "type": "string" + }, + { + "key": "eve_token", + "value": "", + "type": "string" + }, + { + "key": "alice_expires_at", + "value": "", + "type": "string" + }, + { + "key": "bob_expires_at", + "value": "", + "type": "string" + }, + { + "key": "eve_expires_at", + "value": "", + "type": "string" + }, + { + "key": "chat_id", + "value": "", + "type": "string" + }, + { + "key": "next_cursor", + "value": "", + "type": "string" + } + ], + "item": [ + { + "name": "01 — Процесс жив", + "request": { + "method": "GET", + "header": [], + "url": "{{base_url}}/health/live" + }, + "event": [ + { + "listen": "test", + "script": { + "type": "text/javascript", + "exec": [ + "pm.test(\"HTTP 200\", () => pm.response.to.have.status(200));" + ] + } + } + ], + "response": [] + }, + { + "name": "02 — БД готова", + "request": { + "method": "GET", + "header": [], + "url": "{{base_url}}/health/ready" + }, + "event": [ + { + "listen": "test", + "script": { + "type": "text/javascript", + "exec": [ + "pm.test(\"HTTP 200\", () => pm.response.to.have.status(200));" + ] + } + } + ], + "response": [] + }, + { + "name": "03 — Создать Глеб", + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + } + ], + "url": "{{base_url}}/api/v1/users", + "body": { + "mode": "raw", + "raw": "{\n \"username\": \"alice_{{run_id}}\",\n \"display_name\": \"Глеб\",\n \"password\": \"{{demo_password}}\"\n}", + "options": { + "raw": { + "language": "json" + } + } + } + }, + "event": [ + { + "listen": "prerequest", + "script": { + "type": "text/javascript", + "exec": [ + "pm.collectionVariables.set(\"run_id\", pm.variables.replaceIn(\"{{$guid}}\").replace(/-/g, \"\").slice(0,16));", + "[\"alice_token\",\"bob_token\",\"eve_token\",\"chat_id\",\"next_cursor\"].forEach(k => pm.collectionVariables.set(k, \"\"));" + ] + } + }, + { + "listen": "test", + "script": { + "type": "text/javascript", + "exec": [ + "pm.test(\"HTTP 201\", () => pm.response.to.have.status(201));", + "if (pm.response.code === 201) pm.collectionVariables.set(\"alice_id\", pm.response.json().id);" + ] + } + } + ], + "response": [] + }, + { + "name": "04 — Создать Боб", + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + } + ], + "url": "{{base_url}}/api/v1/users", + "body": { + "mode": "raw", + "raw": "{\n \"username\": \"bob_{{run_id}}\",\n \"display_name\": \"Боб\",\n \"password\": \"{{demo_password}}\"\n}", + "options": { + "raw": { + "language": "json" + } + } + } + }, + "event": [ + { + "listen": "test", + "script": { + "type": "text/javascript", + "exec": [ + "pm.test(\"HTTP 201\", () => pm.response.to.have.status(201));", + "if (pm.response.code === 201) pm.collectionVariables.set(\"bob_id\", pm.response.json().id);" + ] + } + } + ], + "response": [] + }, + { + "name": "05 — Создать Посторонний", + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + } + ], + "url": "{{base_url}}/api/v1/users", + "body": { + "mode": "raw", + "raw": "{\n \"username\": \"eve_{{run_id}}\",\n \"display_name\": \"Посторонний\",\n \"password\": \"{{demo_password}}\"\n}", + "options": { + "raw": { + "language": "json" + } + } + } + }, + "event": [ + { + "listen": "test", + "script": { + "type": "text/javascript", + "exec": [ + "pm.test(\"HTTP 201\", () => pm.response.to.have.status(201));", + "if (pm.response.code === 201) pm.collectionVariables.set(\"eve_id\", pm.response.json().id);" + ] + } + } + ], + "response": [] + }, + { + "name": "06 — Вход alice через Basic", + "request": { + "method": "POST", + "header": [], + "url": "{{base_url}}/api/v1/auth/sessions", + "auth": { + "type": "basic", + "basic": [ + { + "key": "username", + "value": "alice_{{run_id}}", + "type": "string" + }, + { + "key": "password", + "value": "{{demo_password}}", + "type": "string" + } + ] + } + }, + "event": [ + { + "listen": "test", + "script": { + "type": "text/javascript", + "exec": [ + "pm.test(\"HTTP 201\", () => pm.response.to.have.status(201));", + "if (pm.response.code === 201) {", + " pm.collectionVariables.set(\"alice_token\", pm.response.json().token);", + " pm.collectionVariables.set(\"alice_expires_at\", pm.response.json().expires_at);", + "}" + ] + } + } + ], + "response": [] + }, + { + "name": "07 — Вход bob через Basic", + "request": { + "method": "POST", + "header": [], + "url": "{{base_url}}/api/v1/auth/sessions", + "auth": { + "type": "basic", + "basic": [ + { + "key": "username", + "value": "bob_{{run_id}}", + "type": "string" + }, + { + "key": "password", + "value": "{{demo_password}}", + "type": "string" + } + ] + } + }, + "event": [ + { + "listen": "test", + "script": { + "type": "text/javascript", + "exec": [ + "pm.test(\"HTTP 201\", () => pm.response.to.have.status(201));", + "if (pm.response.code === 201) {", + " pm.collectionVariables.set(\"bob_token\", pm.response.json().token);", + " pm.collectionVariables.set(\"bob_expires_at\", pm.response.json().expires_at);", + "}" + ] + } + } + ], + "response": [] + }, + { + "name": "08 — Вход eve через Basic", + "request": { + "method": "POST", + "header": [], + "url": "{{base_url}}/api/v1/auth/sessions", + "auth": { + "type": "basic", + "basic": [ + { + "key": "username", + "value": "eve_{{run_id}}", + "type": "string" + }, + { + "key": "password", + "value": "{{demo_password}}", + "type": "string" + } + ] + } + }, + "event": [ + { + "listen": "test", + "script": { + "type": "text/javascript", + "exec": [ + "pm.test(\"HTTP 201\", () => pm.response.to.have.status(201));", + "if (pm.response.code === 201) {", + " pm.collectionVariables.set(\"eve_token\", pm.response.json().token);", + " pm.collectionVariables.set(\"eve_expires_at\", pm.response.json().expires_at);", + "}" + ] + } + } + ], + "response": [] + }, + { + "name": "09 — Кто я через Bearer", + "request": { + "method": "GET", + "header": [], + "url": "{{base_url}}/api/v1/users/me", + "auth": { + "type": "bearer", + "bearer": [ + { + "key": "token", + "value": "{{alice_token}}", + "type": "string" + } + ] + } + }, + "event": [ + { + "listen": "test", + "script": { + "type": "text/javascript", + "exec": [ + "pm.test(\"HTTP 200\", () => pm.response.to.have.status(200));" + ] + } + } + ], + "response": [] + }, + { + "name": "10 — Создать чат", + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + } + ], + "url": "{{base_url}}/api/v1/chats", + "auth": { + "type": "bearer", + "bearer": [ + { + "key": "token", + "value": "{{alice_token}}", + "type": "string" + } + ] + }, + "body": { + "mode": "raw", + "raw": "{\n \"title\": \"Защита лабораторной 2\",\n \"member_ids\": [\n \"{{alice_id}}\",\n \"{{bob_id}}\"\n ]\n}", + "options": { + "raw": { + "language": "json" + } + } + } + }, + "event": [ + { + "listen": "test", + "script": { + "type": "text/javascript", + "exec": [ + "pm.test(\"HTTP 201\", () => pm.response.to.have.status(201));", + "if (pm.response.code === 201) pm.collectionVariables.set(\"chat_id\", pm.response.json().id);" + ] + } + } + ], + "response": [] + }, + { + "name": "11 — Мои чаты", + "request": { + "method": "GET", + "header": [], + "url": "{{base_url}}/api/v1/chats?limit=50", + "auth": { + "type": "bearer", + "bearer": [ + { + "key": "token", + "value": "{{bob_token}}", + "type": "string" + } + ] + } + }, + "event": [ + { + "listen": "test", + "script": { + "type": "text/javascript", + "exec": [ + "pm.test(\"HTTP 200\", () => pm.response.to.have.status(200));" + ] + } + } + ], + "response": [] + }, + { + "name": "12 — Чат участника", + "request": { + "method": "GET", + "header": [], + "url": "{{base_url}}/api/v1/chats/{{chat_id}}", + "auth": { + "type": "bearer", + "bearer": [ + { + "key": "token", + "value": "{{bob_token}}", + "type": "string" + } + ] + } + }, + "event": [ + { + "listen": "test", + "script": { + "type": "text/javascript", + "exec": [ + "pm.test(\"HTTP 200\", () => pm.response.to.have.status(200));" + ] + } + } + ], + "response": [] + }, + { + "name": "13 — Сообщение Глеба", + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + } + ], + "url": "{{base_url}}/api/v1/chats/{{chat_id}}/messages", + "auth": { + "type": "bearer", + "bearer": [ + { + "key": "token", + "value": "{{alice_token}}", + "type": "string" + } + ] + }, + "body": { + "mode": "raw", + "raw": "{\n \"text\": \"Привет, мир 👋\"\n}", + "options": { + "raw": { + "language": "json" + } + } + } + }, + "event": [ + { + "listen": "test", + "script": { + "type": "text/javascript", + "exec": [ + "pm.test(\"HTTP 201\", () => pm.response.to.have.status(201));" + ] + } + } + ], + "response": [] + }, + { + "name": "14 — Сообщение Боба", + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + } + ], + "url": "{{base_url}}/api/v1/chats/{{chat_id}}/messages", + "auth": { + "type": "bearer", + "bearer": [ + { + "key": "token", + "value": "{{bob_token}}", + "type": "string" + } + ] + }, + "body": { + "mode": "raw", + "raw": "{\n \"text\": \"Данные теперь в PostgreSQL\"\n}", + "options": { + "raw": { + "language": "json" + } + } + } + }, + "event": [ + { + "listen": "test", + "script": { + "type": "text/javascript", + "exec": [ + "pm.test(\"HTTP 201\", () => pm.response.to.have.status(201));" + ] + } + } + ], + "response": [] + }, + { + "name": "15 — История", + "request": { + "method": "GET", + "header": [], + "url": "{{base_url}}/api/v1/chats/{{chat_id}}/messages?limit=50", + "auth": { + "type": "bearer", + "bearer": [ + { + "key": "token", + "value": "{{alice_token}}", + "type": "string" + } + ] + } + }, + "event": [ + { + "listen": "test", + "script": { + "type": "text/javascript", + "exec": [ + "pm.test(\"HTTP 200\", () => pm.response.to.have.status(200));" + ] + } + } + ], + "response": [] + }, + { + "name": "16 — Первая страница", + "request": { + "method": "GET", + "header": [], + "url": "{{base_url}}/api/v1/chats/{{chat_id}}/messages?limit=1", + "auth": { + "type": "bearer", + "bearer": [ + { + "key": "token", + "value": "{{alice_token}}", + "type": "string" + } + ] + } + }, + "event": [ + { + "listen": "test", + "script": { + "type": "text/javascript", + "exec": [ + "pm.test(\"HTTP 200\", () => pm.response.to.have.status(200));", + "if (pm.response.code === 200) {", + " pm.test(\"Есть следующая страница\", () => pm.expect(pm.response.json().next_cursor).to.be.a(\"string\"));", + " pm.collectionVariables.set(\"next_cursor\", encodeURIComponent(pm.response.json().next_cursor || \"\"));", + "}" + ] + } + } + ], + "response": [] + }, + { + "name": "17 — Следующая страница", + "request": { + "method": "GET", + "header": [], + "url": "{{base_url}}/api/v1/chats/{{chat_id}}/messages?limit=1&cursor={{next_cursor}}", + "auth": { + "type": "bearer", + "bearer": [ + { + "key": "token", + "value": "{{bob_token}}", + "type": "string" + } + ] + } + }, + "event": [ + { + "listen": "test", + "script": { + "type": "text/javascript", + "exec": [ + "pm.test(\"HTTP 200\", () => pm.response.to.have.status(200));", + "if (pm.response.code === 200) pm.test(\"История закончилась\", () => pm.expect(pm.response.json().next_cursor).to.equal(null));" + ] + } + } + ], + "response": [] + }, + { + "name": "18 — Посторонний получает 404", + "request": { + "method": "GET", + "header": [], + "url": "{{base_url}}/api/v1/chats/{{chat_id}}/messages", + "auth": { + "type": "bearer", + "bearer": [ + { + "key": "token", + "value": "{{eve_token}}", + "type": "string" + } + ] + } + }, + "event": [ + { + "listen": "test", + "script": { + "type": "text/javascript", + "exec": [ + "pm.test(\"HTTP 404\", () => pm.response.to.have.status(404));" + ] + } + } + ], + "response": [] + }, + { + "name": "19 — Аноним получает 401", + "request": { + "method": "GET", + "header": [], + "url": "{{base_url}}/api/v1/users/me" + }, + "event": [ + { + "listen": "test", + "script": { + "type": "text/javascript", + "exec": [ + "pm.test(\"HTTP 401\", () => pm.response.to.have.status(401));" + ] + } + } + ], + "response": [] + }, + { + "name": "20 — Basic не подходит для бизнес-запроса", + "request": { + "method": "GET", + "header": [], + "url": "{{base_url}}/api/v1/users/me", + "auth": { + "type": "basic", + "basic": [ + { + "key": "username", + "value": "alice_{{run_id}}", + "type": "string" + }, + { + "key": "password", + "value": "{{demo_password}}", + "type": "string" + } + ] + } + }, + "event": [ + { + "listen": "test", + "script": { + "type": "text/javascript", + "exec": [ + "pm.test(\"HTTP 401\", () => pm.response.to.have.status(401));" + ] + } + } + ], + "response": [] + }, + { + "name": "21 — Пустое сообщение получает 400", + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + } + ], + "url": "{{base_url}}/api/v1/chats/{{chat_id}}/messages", + "auth": { + "type": "bearer", + "bearer": [ + { + "key": "token", + "value": "{{alice_token}}", + "type": "string" + } + ] + }, + "body": { + "mode": "raw", + "raw": "{\n \"text\": \"\"\n}", + "options": { + "raw": { + "language": "json" + } + } + } + }, + "event": [ + { + "listen": "test", + "script": { + "type": "text/javascript", + "exec": [ + "pm.test(\"HTTP 400\", () => pm.response.to.have.status(400));" + ] + } + } + ], + "response": [] + }, + { + "name": "22 — Logout текущего токена", + "request": { + "method": "DELETE", + "header": [], + "url": "{{base_url}}/api/v1/auth/sessions/current", + "auth": { + "type": "bearer", + "bearer": [ + { + "key": "token", + "value": "{{alice_token}}", + "type": "string" + } + ] + } + }, + "event": [ + { + "listen": "test", + "script": { + "type": "text/javascript", + "exec": [ + "pm.test(\"HTTP 204\", () => pm.response.to.have.status(204));" + ] + } + } + ], + "response": [] + }, + { + "name": "23 — Отозванный токен получает 401", + "request": { + "method": "GET", + "header": [], + "url": "{{base_url}}/api/v1/users/me", + "auth": { + "type": "bearer", + "bearer": [ + { + "key": "token", + "value": "{{alice_token}}", + "type": "string" + } + ] + } + }, + "event": [ + { + "listen": "test", + "script": { + "type": "text/javascript", + "exec": [ + "pm.test(\"HTTP 401\", () => pm.response.to.have.status(401));" + ] + } + } + ], + "response": [] + } + ] +} diff --git a/scripts/bootstrap.py b/scripts/bootstrap.py new file mode 100644 index 00000000..6d534322 --- /dev/null +++ b/scripts/bootstrap.py @@ -0,0 +1,32 @@ +#!/usr/bin/env python3 +"""Generate local-only credentials. Existing credentials are never overwritten.""" +import base64 +import os +from pathlib import Path +import secrets +root=Path(__file__).resolve().parents[1] +directory=root/'secrets' +directory.mkdir(mode=0o700,exist_ok=True) +password_file=directory/'postgres_password' +if not password_file.exists(): + password=secrets.token_hex(24) + password_file.write_text(password+'\n') +else: + password=password_file.read_text().strip() +cache_file=directory/'valkey_config' +if not cache_file.exists(): + cache_password=secrets.token_hex(24) + cache_file.write_text('bind 0.0.0.0\nprotected-mode yes\nport 6379\ndir /data\nsave ""\nappendonly no\nrequirepass '+cache_password+'\n') +else: + cache_password=next(line.split()[1] for line in cache_file.read_text().splitlines() if line.startswith('requirepass ')) +values={'database_url':f'postgres://messenger:{password}@postgres:5432/messenger?sslmode=disable', + 'cache_url':f'redis://:{cache_password}@valkey:6379/0', + 'cursor_key':base64.urlsafe_b64encode(secrets.token_bytes(32)).decode().rstrip('=')} +for name,value in values.items(): + p=directory/name + if not p.exists():p.write_text(value+'\n') +# Compose mounts individual files. Readable by container UID 10001; host +# directory 0700 prevents traversal by other local users. +for p in directory.iterdir():os.chmod(p,0o444) +if not (root/'.env').exists():(root/'.env').write_text('APP_PORT=8082\nSESSION_TTL_SECONDS=3600\n') +print('Local secrets ready (values hidden); .env and secrets/ are ignored by Git.') diff --git a/scripts/create_postman.py b/scripts/create_postman.py new file mode 100644 index 00000000..3584c926 --- /dev/null +++ b/scripts/create_postman.py @@ -0,0 +1,43 @@ +#!/usr/bin/env python3 +"""Generate a repeatable Postman scenario with synthetic credentials only.""" +import json +from pathlib import Path +ROOT=Path(__file__).resolve().parents[1] +items=[] +def req(name,method,path,status=200,actor=None,body=None,save=None,pre=None,extra=None,basic=None): + r={'method':method,'header':[],'url':'{{base_url}}'+path} + if actor:r['auth']={'type':'bearer','bearer':[{'key':'token','value':'{{'+actor+'_token}}','type':'string'}]} + if basic:r['auth']={'type':'basic','basic':[{'key':'username','value':basic+'_{{run_id}}','type':'string'},{'key':'password','value':'{{demo_password}}','type':'string'}]} + if body is not None: + r['header'].append({'key':'Content-Type','value':'application/json'}) + r['body']={'mode':'raw','raw':json.dumps(body,ensure_ascii=False,indent=2),'options':{'raw':{'language':'json'}}} + tests=[f'pm.test("HTTP {status}", () => pm.response.to.have.status({status}));'] + if save:tests.append(f'if (pm.response.code === {status}) pm.collectionVariables.set("{save}", pm.response.json().id);') + if extra:tests+=extra + events=[{'listen':'test','script':{'type':'text/javascript','exec':tests}}] + if pre:events.insert(0,{'listen':'prerequest','script':{'type':'text/javascript','exec':pre}}) + items.append({'name':name,'request':r,'event':events,'response':[]}) +req('01 — Процесс жив','GET','/health/live') +req('02 — БД готова','GET','/health/ready') +for index,who,title in [(3,'alice','Глеб'),(4,'bob','Боб'),(5,'eve','Посторонний')]: + req(f'{index:02} — Создать {title}','POST','/api/v1/users',201,body={'username':who+'_{{run_id}}','display_name':title,'password':'{{demo_password}}'},save=who+'_id',pre=['pm.collectionVariables.set("run_id", pm.variables.replaceIn("{{$guid}}").replace(/-/g, "").slice(0,16));','["alice_token","bob_token","eve_token","chat_id","next_cursor"].forEach(k => pm.collectionVariables.set(k, ""));'] if who=='alice' else None) +for index,who in [(6,'alice'),(7,'bob'),(8,'eve')]: + req(f'{index:02} — Вход {who} через Basic','POST','/api/v1/auth/sessions',201,basic=who,extra=['if (pm.response.code === 201) {',f' pm.collectionVariables.set("{who}_token", pm.response.json().token);',f' pm.collectionVariables.set("{who}_expires_at", pm.response.json().expires_at);','}']) +req('09 — Кто я через Bearer','GET','/api/v1/users/me',actor='alice') +req('10 — Создать чат','POST','/api/v1/chats',201,'alice',{'title':'Защита лабораторной 2','member_ids':['{{alice_id}}','{{bob_id}}']},'chat_id') +req('11 — Мои чаты','GET','/api/v1/chats?limit=50',actor='bob') +req('12 — Чат участника','GET','/api/v1/chats/{{chat_id}}',actor='bob') +req('13 — Сообщение Глеба','POST','/api/v1/chats/{{chat_id}}/messages',201,'alice',{'text':'Привет, мир 👋'}) +req('14 — Сообщение Боба','POST','/api/v1/chats/{{chat_id}}/messages',201,'bob',{'text':'Данные теперь в PostgreSQL'}) +req('15 — История','GET','/api/v1/chats/{{chat_id}}/messages?limit=50',actor='alice') +req('16 — Первая страница','GET','/api/v1/chats/{{chat_id}}/messages?limit=1',actor='alice',extra=['if (pm.response.code === 200) {',' pm.test("Есть следующая страница", () => pm.expect(pm.response.json().next_cursor).to.be.a("string"));',' pm.collectionVariables.set("next_cursor", encodeURIComponent(pm.response.json().next_cursor || ""));','}']) +req('17 — Следующая страница','GET','/api/v1/chats/{{chat_id}}/messages?limit=1&cursor={{next_cursor}}',actor='bob',extra=['if (pm.response.code === 200) pm.test("История закончилась", () => pm.expect(pm.response.json().next_cursor).to.equal(null));']) +req('18 — Посторонний получает 404','GET','/api/v1/chats/{{chat_id}}/messages',404,'eve') +req('19 — Аноним получает 401','GET','/api/v1/users/me',401) +req('20 — Basic не подходит для бизнес-запроса','GET','/api/v1/users/me',401,basic='alice') +req('21 — Пустое сообщение получает 400','POST','/api/v1/chats/{{chat_id}}/messages',400,'alice',{'text':''}) +req('22 — Logout текущего токена','DELETE','/api/v1/auth/sessions/current',204,'alice') +req('23 — Отозванный токен получает 401','GET','/api/v1/users/me',401,'alice') +collection={'info':{'name':'ЛР 2 — Крайкин БВТ2303 — PostgreSQL и сессии','schema':'https://schema.getpostman.com/json/collection/v2.1.0/collection.json','description':'Запустите make up. Run выполняет 23 запроса сверху вниз, сохраняет ID и токены только в локальные переменные Postman. Новый run_id позволяет повторять сценарий. Для ручной проверки persistence остановитесь после 17, выполните scripts/restart.sh, повторите 09 и 15 с прежним Bearer, затем 22 и 23. Никаких реальных паролей; demo_password синтетический. Для localhost нужен настольный Postman/Desktop Agent. Перед экспортом коллекции очистите значения токенов.'},'variable':[{'key':'base_url','value':'http://localhost:8082','type':'string'},{'key':'demo_password','value':'Synthetic-Postman-Demo-123','type':'string'}]+[{'key':k,'value':'','type':'string'} for k in ['run_id','alice_id','bob_id','eve_id','alice_token','bob_token','eve_token','alice_expires_at','bob_expires_at','eve_expires_at','chat_id','next_cursor']],'item':items} +(ROOT/'postman/lab2.postman_collection.json').write_text(json.dumps(collection,ensure_ascii=False,indent=2)+'\n') +print('Postman collection: 23 requests; no live credentials/tokens') diff --git a/scripts/restart.sh b/scripts/restart.sh new file mode 100755 index 00000000..b0adb1e8 --- /dev/null +++ b/scripts/restart.sh @@ -0,0 +1,9 @@ +#!/bin/sh +set -eu +cd "$(dirname "$0")/.." +# Dependency order matters: API bootstrap needs a ready database. +# Restart EVERY runtime service; named volumes and expiry stay unchanged. +docker compose --env-file .env stop api +docker compose --env-file .env restart postgres valkey +docker compose --env-file .env up -d --wait postgres valkey +docker compose --env-file .env start api diff --git a/student-tests/clean_clone.py b/student-tests/clean_clone.py new file mode 100644 index 00000000..2c209b34 --- /dev/null +++ b/student-tests/clean_clone.py @@ -0,0 +1,43 @@ +#!/usr/bin/env python3 +"""Verify committed files against fresh credentials, containers and volumes.""" +import json +import os +from pathlib import Path +import subprocess +import socket +import tempfile +import uuid +ROOT=Path(__file__).resolve().parents[1] +project='mtusi-lab2-clean-'+uuid.uuid4().hex[:10] +commit=subprocess.check_output(['git','rev-parse','HEAD'],cwd=ROOT,text=True).strip() +lines=['Checked source commit: '+commit,'Isolated Compose project: '+project] +with tempfile.TemporaryDirectory(prefix='mtusi-lab2-clean-') as directory: + clone=Path(directory)/'repo' + subprocess.run(['git','clone','--quiet','--local',str(ROOT),str(clone)],check=True) + # A dynamically published port 0 may change on container stop/start. + # Select a free numeric port so persistence keeps the same base URL. + with socket.socket() as listener: + listener.bind(('127.0.0.1',0)) + host_port=listener.getsockname()[1] + env=dict(os.environ,COMPOSE_PROJECT_NAME=project,APP_PORT=str(host_port),SESSION_TTL_SECONDS='3600') + def run(args): + p=subprocess.run(args,cwd=clone,env=env,text=True,stdout=subprocess.PIPE,stderr=subprocess.STDOUT) + lines.append('$ '+' '.join(args)+'\n'+p.stdout) + if p.returncode:raise RuntimeError('clean clone command failed: '+args[0]) + return p.stdout + try: + run(['make','bootstrap','check']) + run(['docker','compose','--env-file','.env','build','--no-cache','api']) + run(['docker','compose','--env-file','.env','up','-d','--wait','api','postgres','valkey']) + port=run(['docker','compose','port','api','8080']).strip().rsplit(':',1)[1] + base='http://127.0.0.1:'+port + run(['make','test','BASE_URL='+base]) + run(['make','test-persistence','ACTION_SCRIPT=scripts/restart.sh','BASE_URL='+base]) + run(['make','test-docker','BASE_URL='+base]) + lines.append('PASS: committed clean clone, uncached image, fresh volumes, smoke, full restart, lifecycle') + print(lines[-1]) + finally: + # Only the disposable, uniquely named clean-clone project is removed. + # Primary API/research volumes are not part of this project. + run(['docker','compose','--env-file','.env','down','--volumes']) + (ROOT/'evidence/clean-clone.txt').write_text('\n\n'.join(lines)+'\n') diff --git a/student-tests/experiment.py b/student-tests/experiment.py new file mode 100644 index 00000000..75544dbe --- /dev/null +++ b/student-tests/experiment.py @@ -0,0 +1,125 @@ +#!/usr/bin/env python3 +"""Track 2: skewed data, real planner, read/write cost, pg_dump/restore. +Isolated research/restore volumes; the API database is never altered. +""" +import hashlib +import json +import os +from pathlib import Path +import platform +import re +import statistics +import subprocess +import time +import uuid +ROOT=Path(__file__).resolve().parents[1] +COMPOSE=['docker','compose','--env-file','.env'] +DBNAME='messenger' + +def command(args,data=None): + p=subprocess.run(args,cwd=ROOT,input=data,stdout=subprocess.PIPE,stderr=subprocess.PIPE) + if p.returncode:raise RuntimeError('Experiment command failed: '+args[0]+' '+p.stderr.decode()[-1000:]) + return p.stdout + +def sql(query,service='research-db',database=None): + return command(COMPOSE+['exec','-T',service,'psql','-X','-q','-U','messenger','-d',database or DBNAME,'-At','-v','ON_ERROR_STOP=1'],query.encode()).decode().strip() +def explain(query,service='research-db'): + return json.loads(sql('EXPLAIN (ANALYZE,BUFFERS,WAL,FORMAT JSON) '+query,service))[0] +def pgbench(script,clients=1,transactions=100): + command(COMPOSE+['exec','-T','research-db','sh','-c','cat > /tmp/lab2-bench.sql'],script.encode()) + raw=command(COMPOSE+['exec','-T','research-db','pgbench','-U','messenger','-d',DBNAME,'-n','-M','prepared','-c',str(clients),'-j',str(clients),'-t',str(transactions),'-f','/tmp/lab2-bench.sql']).decode() + failure=re.search(r'number of failed transactions:\s*(\d+)',raw) + assert failure is None or int(failure[1])==0 + return {'raw':raw,'latency_avg_ms':float(re.search(r'latency average = ([\d.]+)',raw)[1]),'tps':float(re.search(r'tps = ([\d.]+)',raw)[1]),'errors':int(failure[1]) if failure else 0} +def signature(service): + q="""SELECT json_build_object('users',(SELECT count(*) FROM users),'chats',(SELECT count(*) FROM chats),'members',(SELECT count(*) FROM chat_members),'messages',(SELECT count(*) FROM messages),'fingerprint',(SELECT md5(string_agg(id::text||chat_id::text||sender_id::text||text||created_at::text,'' ORDER BY id)) FROM messages),'samples',(SELECT json_agg(m) FROM (SELECT id,chat_id,sender_id,text,created_at FROM messages ORDER BY id LIMIT 5) m))""" + return json.loads(sql(q,service)) + +def metrics(): + raw=command(COMPOSE+['exec','-T','research-db','sh','-c','cat /sys/fs/cgroup/memory.current /sys/fs/cgroup/cpu.stat']).decode().splitlines() + return int(raw[0]),int(next(line.split()[1] for line in raw if line.startswith('usage_usec '))) + +def main(): + # A fresh pair of databases per run inside dedicated services; previous + # experiment databases/volumes are retained, not destroyed. + command(COMPOSE+['--profile','research','up','-d','--wait','research-db','restore-db']) + # Create a new database name per run: never DROP or overwrite old data. + global DBNAME + DBNAME='experiment_'+uuid.uuid4().hex[:12] + for service in ['research-db','restore-db']:sql('CREATE DATABASE '+DBNAME,service,database='messenger') + sql((ROOT/'internal/database/migrations/001_initial.sql').read_text()) + sizes=[80000,15000,4900,100] + # Synthetic fixtures use SQL for fast deterministic seeding; read/write + # measurements are SQL, not claimed to be full HTTP measurements. + sql("INSERT INTO users(id,username,display_name,password_hash) VALUES('00000000-0000-4000-8000-000000000001','research','Research','synthetic-no-login')") + chat_ids=[] + for j,n in enumerate(sizes,1): + cid=f'00000000-0000-4000-8000-{j:012d}';chat_ids.append(cid) + sql(f"INSERT INTO chats(id,title) VALUES('{cid}','Chat {n}'); INSERT INTO chat_members VALUES('{cid}','00000000-0000-4000-8000-000000000001'); INSERT INTO messages SELECT md5('{j}:'||i::text)::uuid,'{cid}'::uuid,'00000000-0000-4000-8000-000000000001'::uuid,'synthetic-'||i||repeat('x',128),'2026-01-01T00:00:00Z'::timestamptz+i*interval '1 microsecond' FROM generate_series(1,{n}) i;") + assert sql('SELECT count(*) FROM messages')=='100000' + sql('VACUUM ANALYZE messages') + result={'date_utc':time.strftime('%Y-%m-%dT%H:%M:%SZ',time.gmtime()),'database':DBNAME, + 'method':{'sizes':sizes,'messages':100000,'page_size':51,'repeats':3,'clients':[1,4], + 'profile':'warm SQL keyset GET at 90% and first page; pgbench prepared; 100 transactions/client; 20 warmup transactions', + 'write_profile':'1000-row INSERT plus real COMMIT, 3 repeats, pgbench single client on separate write_probe table', + 'postgres_limits':{'cpu':2,'memory_mib':512},'host':platform.platform(), + 'clock':'SQL planner execution vs pgbench full transaction latency; excludes HTTP/auth/JSON', + 'note':'Closed-loop; warm cache; one batch write transaction, not a maximum-capacity result'}, + 'versions':{'postgres':sql('SELECT version()'),'durability':sql("SELECT json_build_object('fsync',current_setting('fsync'),'synchronous_commit',current_setting('synchronous_commit'),'full_page_writes',current_setting('full_page_writes'))")}, + 'variants':[]} + variants=[('chat_only','(chat_id)'),('composite','(chat_id,created_at,id)'),('covering','(chat_id,created_at,id) INCLUDE(sender_id,text)')] + for name,index in variants: + print('Measuring '+name,flush=True) + measured_start=time.monotonic() + memory_before,cpu_before=metrics() + sql('DROP INDEX IF EXISTS messages_history_idx; DROP INDEX IF EXISTS experiment_history_idx; CREATE INDEX experiment_history_idx ON messages '+index+'; ANALYZE messages;') + trial={'name':name,'index':index,'index_bytes':int(sql("SELECT pg_relation_size('experiment_history_idx')")),'reads':[],'writes':[]} + for n,cid in zip(sizes,chat_ids): + for position,fraction in [('first',0),('deep',.9)]: + offset=int(n*fraction) + query=f"SELECT id::text,chat_id::text,sender_id::text,text,created_at FROM messages WHERE chat_id='{cid}'::uuid AND (created_at,id)>('2026-01-01T00:00:00Z'::timestamptz+{offset}*interval '1 microsecond','00000000-0000-0000-0000-000000000000'::uuid) ORDER BY messages.created_at,messages.id LIMIT 51" + plans=[explain(query) for _ in range(3)] + # EXPLAIN actual executes the exact API row tuple boundary SQL. + for clients in [1,4]: + pgbench(query+';\n',clients,20) + runs=[pgbench(query+';\n',clients,100) for _ in range(3)] + trial['reads'].append({'chat_messages':n,'position':position,'clients':clients,'plans':plans if clients==1 else [],'runs':runs, + 'median_execution_ms':statistics.median(p['Execution Time'] for p in plans), + 'median_latency_ms':statistics.median(r['latency_avg_ms'] for r in runs), + 'median_tps':statistics.median(r['tps'] for r in runs),'errors':sum(r['errors'] for r in runs)}) + # Independent identical heap and PK: only the secondary index differs. + # Counts in messages stay fixed; write_probe is not part of the backup. + sql("CREATE TABLE write_probe(id uuid PRIMARY KEY,chat_id uuid NOT NULL,sender_id uuid NOT NULL,text text NOT NULL,created_at timestamptz NOT NULL); CREATE INDEX write_probe_idx ON write_probe "+index) + for repeat in range(3): + sql('TRUNCATE write_probe') + query="INSERT INTO write_probe SELECT md5('write:'||i)::uuid,'00000000-0000-4000-8000-000000000001'::uuid,'00000000-0000-4000-8000-000000000001'::uuid,'synthetic-'||i||repeat('x',128),'2026-01-01'::timestamptz+i*interval '1 microsecond' FROM generate_series(1,1000) i" + plan=explain(query);sql('TRUNCATE write_probe') + run=pgbench('BEGIN;\n'+query+';\nCOMMIT;\n',1,1) + trial['writes'].append({'repeat':repeat+1,'plan':plan,'transaction':run,'table_bytes':int(sql("SELECT pg_total_relation_size('write_probe')"))}) + sql('DROP TABLE write_probe') + memory_after,cpu_after=metrics() + elapsed=time.monotonic()-measured_start + trial['resources']={'measurement_seconds':round(elapsed,3),'cpu_percent':round((cpu_after-cpu_before)/1e6/elapsed*100,3),'memory_before_bytes':memory_before,'memory_after_bytes':memory_after,'note':'cgroup memory includes shared buffers/page cache, not API RSS; CPU window includes setup and SQL trials'} + result['variants'].append(trial) + # Return to chosen production schema before backup. + sql('DROP INDEX experiment_history_idx; CREATE INDEX messages_history_idx ON messages(chat_id,created_at,id); ANALYZE messages') + before=signature('research-db') + # Binary custom dump is temporary container-external bytes, never committed. + start=time.monotonic();dump=command(COMPOSE+['exec','-T','research-db','pg_dump','-U','messenger','-d',DBNAME,'-Fc','--no-owner','--no-acl']);backup_seconds=time.monotonic()-start + start=time.monotonic();command(COMPOSE+['exec','-T','restore-db','pg_restore','-U','messenger','-d',DBNAME,'--no-owner','--no-acl','--exit-on-error','--single-transaction'],dump);restore_seconds=time.monotonic()-start + sql('ANALYZE','restore-db');after=signature('restore-db');assert before==after + # Prove the backup cutoff using one acknowledged, post-backup INSERT. + sql("INSERT INTO messages VALUES('ffffffff-ffff-4fff-8fff-ffffffffffff','00000000-0000-4000-8000-000000000001','00000000-0000-4000-8000-000000000001','after-backup-marker',clock_timestamp())") + assert sql("SELECT count(*) FROM messages WHERE id='ffffffff-ffff-4fff-8fff-ffffffffffff'",'restore-db')=='0' + result['backup_restore']={'backup_seconds':round(backup_seconds,3),'restore_seconds':round(restore_seconds,3),'dump_bytes':len(dump),'dump_sha256':hashlib.sha256(dump).hexdigest(),'before':before,'after':after,'equal':True,'source_after_backup_messages':100001,'restored_messages':100000,'post_backup_marker_present':False,'new_storage':'restore-db, separate named restore_data volume, new empty database', 'rpo':'snapshot cutoff; demonstrated 1 later committed message absent, no WAL archive/PITR','rto':'restore only; excludes incident detection/provisioning/API switchover'} + result['result']='PASS' + evidence=ROOT/'evidence';(evidence/'experiment.json').write_text(json.dumps(result,ensure_ascii=False,indent=2)+'\n') + lines=['# SQL-эксперимент: результаты','', '100 000 сообщений, чаты 80 000 / 15 000 / 4900 / 100. Медианы 3 повторов; warm SQL, без HTTP.','', '| Индекс | Чат | Страница | Клиенты | latency, ms | TPS | EXPLAIN, ms | Ошибки |','|---|---:|---|---:|---:|---:|---:|---:|'] + for v in result['variants']: + for r in v['reads']:lines.append(f"| {v['name']} | {r['chat_messages']} | {r['position']} | {r['clients']} | {r['median_latency_ms']:.3f} | {r['median_tps']:.1f} | {r['median_execution_ms']:.3f} | {r['errors']} |") + lines+=['','| Индекс | Размер индекса, KiB | INSERT 1000 + COMMIT, ms |','|---|---:|---:|'] + for v in result['variants']:lines.append(f"| {v['name']} | {v['index_bytes']/1024:.1f} | {statistics.median(w['transaction']['latency_avg_ms'] for w in v['writes']):.3f} |") + lines+=['',f"Backup: {backup_seconds:.3f}s; restore: {restore_seconds:.3f}s; {len(dump)} bytes; 100000 сообщений, полный fingerprint и 5 выбранных записей совпали. После backup добавлено 1 сообщение: восстановленная БД его не содержит."] + (evidence/'experiment-summary.md').write_text('\n'.join(lines)+'\n') + print('PASS: SQL comparison and restore of 100000 messages',flush=True) +if __name__=='__main__':main() diff --git a/student-tests/integration.py b/student-tests/integration.py new file mode 100644 index 00000000..8585f119 --- /dev/null +++ b/student-tests/integration.py @@ -0,0 +1,132 @@ +#!/usr/bin/env python3 +"""HTTP, SQL atomicity, dependency failures, persistence, and short TTL checks. +Only this lab's Compose services and synthetic users are affected. +""" +import argparse +import base64 +from concurrent.futures import ThreadPoolExecutor +import json +import os +from pathlib import Path +import subprocess +import sys +import time +import uuid +from urllib.parse import quote +ROOT=Path(__file__).resolve().parents[1] +sys.path.insert(0,str(ROOT/'tests')) +from client import Client + +def compose(*args,env=None): + r=subprocess.run(['docker','compose','--env-file','.env',*args],cwd=ROOT,env=env,text=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE) + if r.returncode:raise RuntimeError('Compose command failed: '+args[0]) + return r.stdout.strip() +def sql(q):return compose('exec','-T','postgres','psql','-X','-U','messenger','-d','messenger','-At','-v','ON_ERROR_STOP=1','-c',q) +def cache(*args): + # Password is read only inside container; never printed or put on host argv. + return compose('exec','-T','valkey','sh','-c','export REDISCLI_AUTH="$(sed -n \'s/^requirepass //p\' /run/secrets/valkey_config)"; exec valkey-cli "$@"','sh',*args) +def ready(c): + until=time.monotonic()+40 + while time.monotonic()future['created_at'];passed('monotonic_chat_clock') + good=base64.b64encode((a['registration']['username']+':'+a['registration']['password']).encode()).decode() + bad=base64.b64encode((a['registration']['username']+':Synthetic-wrong-password').encode()).decode() + c.call('POST','/api/v1/auth/sessions',401,headers={'Authorization':'Basic '+bad}) + c.call('GET','/api/v1/users/me',401,headers={'Authorization':'Basic '+good}) + c.call('GET','/api/v1/users/me',401,headers={'X-User-Id':a['id']}) + assert c.call('GET','/api/v1/users/me',actor=a,headers={'X-User-Id':e['id']},schema='User')['json']['id']==a['id'] + c.call('GET',path,404,actor=e);passed('authentication_and_chat_authorization') + assert sql("SELECT bool_and(password_hash LIKE '$argon2id$%') FROM users")=='t' + assert sql('SELECT bool_and(octet_length(token_hash)=32) FROM sessions')=='t';passed('password_kdf_and_token_digest_storage') + c.call('GET','/api/v1/users/me',actor=a,schema='User') + ttl=int(cache('TTL','profile:v1:'+a['id']));assert 00 + passed('cache_flush_repopulates_with_same_session') + compose('stop','valkey') + try: + c.call('GET','/health/ready',schema='Health');c.call('GET','/api/v1/users/me',actor=a,schema='User') + msg=c.message(a,chat,'cache-off-read-after-write')['json'] + # Explicit small chat keeps complete post-write comparison unambiguous. + msg=c.message(a,other,'must-be-visible')['json'];assert msg in c.call('GET','/api/v1/chats/'+other['id']+'/messages',actor=a,schema='MessagePage')['json']['items'] + c.call('GET','/api/v1/users/me',401,headers={'X-User-Id':a['id']}) + passed('cache_down_fallback_and_read_after_write') + finally:compose('start','valkey') + compose('stop','postgres') + try: + live=c.call('GET','/health/live',schema='Health');ready_result=c.call('GET','/health/ready',503) + begin=time.monotonic();c.call('GET','/api/v1/users/me',503,actor=a);elapsed=time.monotonic()-begin + assert elapsed<4;passed('database_down_fails_closed',{'live':live['status'],'ready':ready_result['status'],'request_seconds':round(elapsed,3)}) + finally:compose('start','postgres');ready(c) + # Revoke while profile remains cached, then retry with the exact token. + c.call('DELETE','/api/v1/auth/sessions/current',204,actor=a) + c.call('GET','/api/v1/users/me',401,actor=a);c.call('DELETE','/api/v1/auth/sessions/current',401,actor=a) + passed('logout_with_warm_cache') + before_containers=containers();before_counts=sql('SELECT (SELECT count(*) FROM users),(SELECT count(*) FROM chats),(SELECT count(*) FROM messages),(SELECT count(*) FROM sessions),(SELECT count(*) FROM schema_migrations)') + subprocess.run(['make','test-persistence','ACTION_SCRIPT=scripts/restart.sh','BASE_URL='+args.base_url],cwd=ROOT,check=True) + after_containers=containers();assert all(before_containers[x]!=after_containers[x] for x in before_containers) + after_counts=sql('SELECT (SELECT count(*) FROM users),(SELECT count(*) FROM chats),(SELECT count(*) FROM messages),(SELECT count(*) FROM sessions),(SELECT count(*) FROM schema_migrations)') + assert sql('SELECT count(*) FROM schema_migrations')=='1' + c.call('GET','/api/v1/users/me',actor=b,schema='User') + # A cursor created before restart retains its HMAC key. + c.call('GET',path+'?limit=1&cursor='+quote(cursor,safe=''),actor=b,schema='MessagePage') + passed('full_stack_restart_and_cursor',{'before':before_containers,'after':after_containers,'counts_before':before_counts,'counts_after':after_counts}) + # Separate short TTL configuration, no global DB edits and no token saved. + short_env=dict(os.environ,SESSION_TTL_SECONDS='2');compose('up','-d','--no-deps','--force-recreate','api',env=short_env);ready(c) + try: + short=c.user('expiry');c.call('GET','/api/v1/users/me',actor=short,schema='User');time.sleep(2.2) + c.call('GET','/api/v1/users/me',401,actor=short);passed('session_expiry_ttl_2_seconds') + # Existing long-lived session's expiry is not recomputed at API restart. + c.call('GET','/api/v1/users/me',actor=b,schema='User');passed('restart_does_not_shorten_existing_session') + finally:compose('up','-d','--no-deps','--force-recreate','api');ready(c) + evidence['result']='PASS';(ROOT/'evidence/integration.json').write_text(json.dumps(evidence,ensure_ascii=False,indent=2)+'\n') + print('PASS: all student integration checks') +if __name__=='__main__':main() diff --git a/student-tests/lifecycle.py b/student-tests/lifecycle.py new file mode 100644 index 00000000..17ec322b --- /dev/null +++ b/student-tests/lifecycle.py @@ -0,0 +1,36 @@ +#!/usr/bin/env python3 +"""Non-root, readiness, graceful stop, old-session recovery, and log privacy.""" +import argparse +import json +from pathlib import Path +import platform +import subprocess +import sys +import time +ROOT=Path(__file__).resolve().parents[1] +sys.path.insert(0,str(ROOT/'tests')) +from client import Client +from integration import compose, ready, sql +p=argparse.ArgumentParser();p.add_argument('--base-url',default='http://localhost:8082');args=p.parse_args() +c=Client(args.base_url);ready(c);a=c.user('lifecycle') +chat=c.call('POST','/api/v1/chats',201,actor=a,body={'title':'Lifecycle','member_ids':[a['id']]},schema='Chat')['json'] +marker='synthetic-private-body-marker';msg=c.message(a,chat,marker)['json'] +container=compose('ps','-q','api') +inspect=lambda:json.loads(subprocess.check_output(['docker','inspect',container],text=True))[0] +before=inspect() +# HTTP readiness can precede Docker's next periodic healthcheck after restart. +deadline=time.monotonic()+20 +while before['State']['Health']['Status']!='healthy' and time.monotonic()