From c19d092b63199b5ecf368cbb5a06e8bfdf0ab571 Mon Sep 17 00:00:00 2001 From: Ivan Melnikov Date: Wed, 2 Dec 2026 18:45:01 +0300 Subject: [PATCH] Lab3: atomic one-statement idempotent write, tuned stand, level-4/5 measurement tooling --- .env.example | 6 +- compose.yaml | 12 +- evidence/track1/raw/fixed-r1-rep1.json | 209 ++++++++++++++ infra/haproxy.cfg | 4 + internal/store/store.go | 118 ++++---- scripts/lab3_metrics.py | 59 +++- scripts/track1.py | 365 +++++++++++++++++++++++++ 7 files changed, 701 insertions(+), 72 deletions(-) create mode 100644 evidence/track1/raw/fixed-r1-rep1.json create mode 100755 scripts/track1.py diff --git a/.env.example b/.env.example index e8547e4f..a8418711 100644 --- a/.env.example +++ b/.env.example @@ -20,11 +20,11 @@ API_REPLICAS=2 API_CPU_LIMIT=0.4 API_MEM_LIMIT=256M GOMEMLIMIT=220MiB -POSTGRES_CPU_LIMIT=0.6 +POSTGRES_CPU_LIMIT=0.7 POSTGRES_MEM_LIMIT=512M -VALKEY_CPU_LIMIT=0.15 +VALKEY_CPU_LIMIT=0.1 VALKEY_MEM_LIMIT=128M -LB_CPU_LIMIT=0.1 +LB_CPU_LIMIT=0.2 LB_MEM_LIMIT=64M SESSION_TTL_SECONDS=3600 diff --git a/compose.yaml b/compose.yaml index 3b779953..f6ffc8f1 100644 --- a/compose.yaml +++ b/compose.yaml @@ -39,9 +39,11 @@ services: - -c - maintenance_work_mem=64MB - -c - - max_wal_size=1GB + - max_wal_size=4GB - -c - - checkpoint_timeout=15min + - checkpoint_timeout=30min + - -c + - checkpoint_completion_target=0.9 volumes: - pgdata:/var/lib/postgresql/data networks: @@ -59,7 +61,7 @@ services: deploy: resources: limits: - cpus: "${POSTGRES_CPU_LIMIT:-0.6}" + cpus: "${POSTGRES_CPU_LIMIT:-0.7}" memory: ${POSTGRES_MEM_LIMIT:-512M} valkey: @@ -97,7 +99,7 @@ services: deploy: resources: limits: - cpus: "${VALKEY_CPU_LIMIT:-0.15}" + cpus: "${VALKEY_CPU_LIMIT:-0.1}" memory: ${VALKEY_MEM_LIMIT:-128M} # One-shot migration runner. API replicas depend on this service completing, @@ -210,7 +212,7 @@ services: deploy: resources: limits: - cpus: "${LB_CPU_LIMIT:-0.1}" + cpus: "${LB_CPU_LIMIT:-0.2}" memory: ${LB_MEM_LIMIT:-64M} volumes: diff --git a/evidence/track1/raw/fixed-r1-rep1.json b/evidence/track1/raw/fixed-r1-rep1.json new file mode 100644 index 00000000..7bd70a0a --- /dev/null +++ b/evidence/track1/raw/fixed-r1-rep1.json @@ -0,0 +1,209 @@ +{ + "tool": "mtusi-lab3-loadgen", + "version": "dev", + "started_at": "2026-12-02T15:26:05.520383Z", + "finished_at": "2026-12-02T15:26:25.525989Z", + "measured_seconds": 20.006, + "warmup_seconds": 5, + "concurrency": 32, + "rate_limit_per_second": 0, + "read_ratio": 0, + "retry_uncertain": false, + "profile": "closed-loop", + "successful_requests": 50081, + "failed_requests": 0, + "error_ratio": 0, + "successful_rps": 2503.305, + "offered_rps": 2503.305, + "successful_latency_ms": { + "p50": 9.898, + "p95": 30.124, + "p99": 45.284, + "max": 101.78, + "mean": 12.772 + }, + "status_counts": { + "201": 50081 + }, + "instances": { + "c98d67f83aff": 50081 + }, + "app_versions": { + "1.0.0": 50081 + }, + "kinds": { + "write": 50081 + }, + "series": [ + { + "second": 1796225165, + "success": 1248, + "errors": 0, + "p50_ms": 9.678, + "p95_ms": 28.221, + "p99_ms": 30.453 + }, + { + "second": 1796225166, + "success": 2789, + "errors": 0, + "p50_ms": 9.535, + "p95_ms": 24.788, + "p99_ms": 31.637 + }, + { + "second": 1796225167, + "success": 2730, + "errors": 0, + "p50_ms": 9.585, + "p95_ms": 26.788, + "p99_ms": 33.782 + }, + { + "second": 1796225168, + "success": 2402, + "errors": 0, + "p50_ms": 9.654, + "p95_ms": 34.211, + "p99_ms": 52.39 + }, + { + "second": 1796225169, + "success": 2067, + "errors": 0, + "p50_ms": 11.633, + "p95_ms": 35.307, + "p99_ms": 46.827 + }, + { + "second": 1796225170, + "success": 2741, + "errors": 0, + "p50_ms": 9.431, + "p95_ms": 26.111, + "p99_ms": 38.947 + }, + { + "second": 1796225171, + "success": 2678, + "errors": 0, + "p50_ms": 9.413, + "p95_ms": 28.329, + "p99_ms": 42.157 + }, + { + "second": 1796225172, + "success": 2368, + "errors": 0, + "p50_ms": 10.828, + "p95_ms": 29.231, + "p99_ms": 38.489 + }, + { + "second": 1796225173, + "success": 2294, + "errors": 0, + "p50_ms": 10.463, + "p95_ms": 34.586, + "p99_ms": 44.744 + }, + { + "second": 1796225174, + "success": 2759, + "errors": 0, + "p50_ms": 9.349, + "p95_ms": 26.482, + "p99_ms": 40.701 + }, + { + "second": 1796225175, + "success": 2839, + "errors": 0, + "p50_ms": 9.222, + "p95_ms": 27.333, + "p99_ms": 36.243 + }, + { + "second": 1796225176, + "success": 2696, + "errors": 0, + "p50_ms": 9.674, + "p95_ms": 29.684, + "p99_ms": 35.313 + }, + { + "second": 1796225177, + "success": 2787, + "errors": 0, + "p50_ms": 9.386, + "p95_ms": 25.722, + "p99_ms": 48.056 + }, + { + "second": 1796225178, + "success": 2305, + "errors": 0, + "p50_ms": 10.919, + "p95_ms": 31.339, + "p99_ms": 40.262 + }, + { + "second": 1796225179, + "success": 1493, + "errors": 0, + "p50_ms": 11.568, + "p95_ms": 61.363, + "p99_ms": 68.795 + }, + { + "second": 1796225180, + "success": 2075, + "errors": 0, + "p50_ms": 11.519, + "p95_ms": 40.011, + "p99_ms": 55.483 + }, + { + "second": 1796225181, + "success": 2757, + "errors": 0, + "p50_ms": 9.601, + "p95_ms": 29.591, + "p99_ms": 34.011 + }, + { + "second": 1796225182, + "success": 2689, + "errors": 0, + "p50_ms": 9.915, + "p95_ms": 26.276, + "p99_ms": 35.526 + }, + { + "second": 1796225183, + "success": 2323, + "errors": 0, + "p50_ms": 10.359, + "p95_ms": 30.561, + "p99_ms": 73.07 + }, + { + "second": 1796225184, + "success": 2711, + "errors": 0, + "p50_ms": 9.542, + "p95_ms": 28.308, + "p99_ms": 32.276 + }, + { + "second": 1796225185, + "success": 1330, + "errors": 0, + "p50_ms": 10.098, + "p95_ms": 26.991, + "p99_ms": 37.346 + } + ], + "uncertain_retries": 0, + "note": "track1 fixed-r1-rep1; replicas=1 cpu_per=0.8 mem_per=512M; synthetic messages created by loadgen, no retries unless -retry-uncertain" +} diff --git a/infra/haproxy.cfg b/infra/haproxy.cfg index dfcda6c3..25771410 100644 --- a/infra/haproxy.cfg +++ b/infra/haproxy.cfg @@ -16,6 +16,10 @@ defaults log global option httplog option dontlognull + # Per-request access logging is intentionally disabled: at thousands of + # requests per second it moves the LB bottleneck into stdout and hides the + # component under study. Errors are still logged. + option dontlog-normal option redispatch retries 2 timeout connect 1s diff --git a/internal/store/store.go b/internal/store/store.go index b55272fa..d19b4cc9 100644 --- a/internal/store/store.go +++ b/internal/store/store.go @@ -157,6 +157,12 @@ func isForeignKeyViolation(err error) bool { return errors.As(err, &pgErr) && pgErr.Code == "23503" } +func isIdempotencyViolation(err error) bool { + var pgErr *pgconn.PgError + return errors.As(err, &pgErr) && pgErr.Code == "23505" && + pgErr.ConstraintName == "message_idempotency_pkey" +} + // CreateUser inserts a user and relies on the unique index for both ordinary // duplicates and concurrent registrations of the same username. func (s *Store) CreateUser(ctx context.Context, username, displayName, passwordHash string) (model.User, error) { @@ -459,15 +465,24 @@ func (s *Store) CreateMessage(ctx context.Context, chatID, senderID, text string } // CreateMessageIdempotent appends a message and records the idempotency -// result in one transaction. It is the lab3 replacement for CreateMessage on -// the public POST path. +// result in one PostgreSQL statement. The statement is atomic: if the +// idempotency unique index conflicts, the whole statement aborts and the +// speculative message insert is rolled back by PostgreSQL, so a concurrent +// repeat can never leave an extra row. A committed row therefore always has +// both the message and the key record, satisfying the contract's requirement +// that the side effect and the stored result are atomic. +// +// One round trip replaces the baseline's explicit transaction, message insert +// and idempotency insert (track-1 improvement). The redundant membership +// predicate in the INSERT...SELECT keeps the database-level guarantee even if +// a caller bypasses the handler's earlier access check. // // Behavior derived from contracts/README.md: // - a new (user, method, path, key) creates a message and its record, 201; // - the same semantic body replays the stored message, 201, exactly once; // - a different body with the same key is a conflict, 409; -// - a transient failure rolls both statements back, so the client may -// safely retry the same key and never observe a duplicate side effect. +// - a transient failure touches neither table, so the client may safely +// retry the same key and never observe a duplicate side effect. func (s *Store) CreateMessageIdempotent(ctx context.Context, chatID, senderID, method, path, key string, requestHash []byte, text string) (model.Message, bool, error) { message := model.Message{ ID: uuid.New(), @@ -479,63 +494,56 @@ func (s *Store) CreateMessageIdempotent(ctx context.Context, chatID, senderID, m ctx, cancel := s.opCtx(ctx) defer cancel() - tx, err := s.pool.Begin(ctx) + created := time.Now().UTC() + var stored time.Time + err := s.pool.QueryRow(ctx, ` + WITH inserted AS ( + INSERT INTO messages (id, chat_id, sender_id, text, created_at) + SELECT $1::uuid, $2::uuid, $3::uuid, $4, $5 + WHERE EXISTS ( + SELECT 1 FROM chat_members + WHERE chat_id = $2::uuid AND user_id = $3::uuid + ) + RETURNING id, created_at + ), recorded AS ( + INSERT INTO message_idempotency + (user_id, method, path, key, request_hash, message_id, created_at) + SELECT $3::uuid, $6, $7, $8, $9, inserted.id, $5 + FROM inserted + RETURNING message_id + ) + SELECT inserted.id, inserted.created_at + FROM inserted + JOIN recorded ON recorded.message_id = inserted.id`, + message.ID, chatID, senderID, text, created, + method, path, key, requestHash, + ).Scan(&message.ID, &stored) if err != nil { - return model.Message{}, false, s.classify(err) - } - defer func() { _ = tx.Rollback(context.Background()) }() - - var createdAt time.Time - if err := tx.QueryRow(ctx, ` - INSERT INTO messages (id, chat_id, sender_id, text, created_at) - VALUES ($1::uuid, $2::uuid, $3::uuid, $4, $5) - RETURNING created_at`, - message.ID, chatID, senderID, text, time.Now().UTC(), - ).Scan(&createdAt); err != nil { + if errors.Is(err, pgx.ErrNoRows) { + return model.Message{}, false, ErrNotFound + } + if isIdempotencyViolation(err) { + // The statement aborted, so the speculative message was rolled + // back. Read the committed winner and compare the canonical body. + storedHash, storedMessage, found, replayErr := s.replayIdempotent(ctx, senderID, method, path, key) + if replayErr != nil { + return model.Message{}, false, replayErr + } + if !found { + return model.Message{}, false, fmt.Errorf("%w: idempotency record vanished", ErrUnavailable) + } + if !bytes.Equal(storedHash, requestHash) { + return model.Message{}, false, ErrIdempotencyConflict + } + return storedMessage, true, nil + } if isForeignKeyViolation(err) { return model.Message{}, false, ErrNotFound } return model.Message{}, false, s.classify(err) } - - tag, err := tx.Exec(ctx, ` - INSERT INTO message_idempotency - (user_id, method, path, key, request_hash, message_id, created_at) - VALUES ($1::uuid, $2, $3, $4, $5, $6::uuid, $7) - ON CONFLICT (user_id, method, path, key) DO NOTHING`, - senderID, method, path, key, requestHash, message.ID, time.Now().UTC(), - ) - if err != nil { - return model.Message{}, false, s.classify(err) - } - if tag.RowsAffected() == 1 { - if err := tx.Commit(ctx); err != nil { - return model.Message{}, false, s.classify(err) - } - message.CreatedAt = model.Time{Time: createdAt.UTC()} - return message, false, nil - } - - // Another transaction owns this key. Roll back this speculative message, - // then read the committed record. A concurrent insert waits on the unique - // index inside Exec above, so the conflicting row is already committed - // when RowsAffected reports zero. - _ = tx.Rollback(context.Background()) - - storedHash, storedMessage, found, err := s.replayIdempotent(ctx, senderID, method, path, key) - if err != nil { - return model.Message{}, false, err - } - if !found { - // The conflicting row disappeared between the conflict and this read - // (only a retention prune can do that). Report a bounded transient - // error; no message was committed and the same key is safe to retry. - return model.Message{}, false, fmt.Errorf("%w: idempotency record vanished", ErrUnavailable) - } - if !bytes.Equal(storedHash, requestHash) { - return model.Message{}, false, ErrIdempotencyConflict - } - return storedMessage, true, nil + message.CreatedAt = model.Time{Time: stored.UTC()} + return message, false, nil } func (s *Store) replayIdempotent(ctx context.Context, userID, method, path, key string) ([]byte, model.Message, bool, error) { diff --git a/scripts/lab3_metrics.py b/scripts/lab3_metrics.py index 097507a4..81a684fa 100644 --- a/scripts/lab3_metrics.py +++ b/scripts/lab3_metrics.py @@ -175,13 +175,41 @@ def db_snapshot(): 'max_connections', current_setting('max_connections')::int, 'shared_buffers', current_setting('shared_buffers'), 'synchronous_commit', current_setting('synchronous_commit'));""") + wal = psql_json(""" + SELECT json_build_object( + 'wal_records', wal_records, 'wal_fpi', wal_fpi, 'wal_bytes', wal_bytes, + 'wal_buffers_full', wal_buffers_full, 'wal_write', wal_write, + 'wal_sync', wal_sync, 'wal_write_time', wal_write_time, + 'wal_sync_time', wal_sync_time) FROM pg_stat_wal;""") + bgwriter = psql_json(""" + SELECT json_build_object( + 'checkpoints_timed', checkpoints_timed, 'checkpoints_req', checkpoints_req, + 'buffers_checkpoint', buffers_checkpoint, 'buffers_clean', buffers_clean, + 'maxwritten_clean', maxwritten_clean, 'buffers_backend', buffers_backend, + 'buffers_backend_fsync', buffers_backend_fsync) FROM pg_stat_bgwriter;""") row = activity or {} row['database'] = database or {} row['datasets'] = datasets or {} row['settings'] = settings or {} + row['wal'] = wal or {} + row['bgwriter'] = bgwriter or {} return row +def db_activity_sample(): + return psql_json(""" + SELECT json_build_object( + 'active', count(*) FILTER (WHERE state = 'active'), + 'waiting', count(*) FILTER (WHERE state = 'active' AND wait_event_type IS NOT NULL), + 'waits', coalesce(( + SELECT json_object_agg(key, n) FROM ( + SELECT wait_event_type || ':' || coalesce(wait_event, '') AS key, count(*) AS n + FROM pg_stat_activity + WHERE state = 'active' AND wait_event_type IS NOT NULL + GROUP BY 1) grouped), '{}'::json)) + FROM pg_stat_activity;""") + + def haproxy_snapshot(): container = containers('lb')[0]['container_id'] result = run(['docker', 'exec', container, 'wget', '-qO-', 'http://127.0.0.1:8404/stats;csv']) @@ -259,8 +287,8 @@ def wait_api_running(expected, timeout=90): def set_stack_profile(image, revision, replicas, api_cpu, api_mem, gomemlimit, - postgres_cpu='0.6', postgres_mem='512M', valkey_cpu='0.15', - valkey_mem='128M', lb_cpu='0.1', lb_mem='64M', recreate_state=False): + postgres_cpu='0.7', postgres_mem='512M', valkey_cpu='0.1', + valkey_mem='128M', lb_cpu='0.2', lb_mem='64M', recreate_state=False): env_extra = { 'API_IMAGE': image, 'GIT_REVISION': revision, @@ -288,7 +316,7 @@ def delta(before, after): """Exact deltas for monotonic counters; elapsed is from snapshot times.""" def cg(snapshot_data): return snapshot_data['cgroups'] - result = {'api': {}, 'postgres': {}, 'valkey': {}, 'lb': {}} + result = {'cgroup_api': {}, 'cgroup_postgres': {}, 'cgroup_valkey': {}, 'cgroup_lb': {}} for container_id, item in after['cgroups'].items(): previous = cg(before).get(container_id) if not previous: @@ -300,7 +328,7 @@ def delta(before, after): change[key] = current_values.get(key, 0) - old_values.get(key, 0) change['memory_current_bytes_end'] = current_values.get('memory_current_bytes') change['memory_max'] = current_values.get('memory_max') - result[item['service']][container_id] = change + result['cgroup_' + item['service']][container_id] = change db_before = before['db']; db_after = after['db'] result['db'] = { 'xact_commit': db_after['database']['xact_commit'] - db_before['database']['xact_commit'], @@ -336,6 +364,17 @@ def delta(before, after): 'rtime_ms_after': number(lb_after['backend'], 'rtime'), 'status_after': lb_after['backend'].get('status'), } + def counter_delta(group, keys): + change = {} + for key in keys: + change[key] = (db_after.get(group, {}).get(key, 0) or 0) - (db_before.get(group, {}).get(key, 0) or 0) + return change + result['wal'] = counter_delta('wal', ('wal_records', 'wal_fpi', 'wal_bytes', 'wal_buffers_full', + 'wal_write', 'wal_sync', 'wal_write_time', 'wal_sync_time')) + result['bgwriter'] = counter_delta('bgwriter', ('checkpoints_timed', 'checkpoints_req', + 'buffers_checkpoint', 'buffers_clean', + 'maxwritten_clean', 'buffers_backend', + 'buffers_backend_fsync')) result['api_pool'] = {} for instance, current in after['api'].items(): previous = before['api'].get(instance, {}) @@ -365,13 +404,13 @@ def summarize_run(label, config, before, after, elapsed_seconds, load): api_throttled = 0.0 api_limit = 0.0 for item in after['containers']['api']: - values = change['api'].get(item['container_id'], {}) + values = change['cgroup_api'].get(item['container_id'], {}) api_cpu += values.get('usage_usec', 0) / 1e6 api_throttled += values.get('throttled_usec', 0) / 1e6 api_limit += item['cpu_limit_nano'] / 1e9 - postgres_values = next(iter(change['postgres'].values()), {}) - valkey_values = next(iter(change['valkey'].values()), {}) - lb_values = next(iter(change['lb'].values()), {}) + postgres_values = next(iter(change['cgroup_postgres'].values()), {}) + valkey_values = next(iter(change['cgroup_valkey'].values()), {}) + lb_values = next(iter(change['cgroup_lb'].values()), {}) postgres_limit = next((item['cpu_limit_nano'] / 1e9 for item in after['containers']['postgres']), 0) lb_limit = next((item['cpu_limit_nano'] / 1e9 for item in after['containers']['lb']), 0) valkey_limit = next((item['cpu_limit_nano'] / 1e9 for item in after['containers']['valkey']), 0) @@ -401,7 +440,7 @@ def summarize_run(label, config, before, after, elapsed_seconds, load): 'valkey_limit_cores': round(valkey_limit, 4), 'lb_used_cores': round(lb_values.get('usage_usec', 0) / 1e6 / elapsed_seconds, 4), 'lb_limit_cores': round(lb_limit, 4), - 'api_cgroup_memory_end_bytes': [value.get('memory_current_bytes_end') for value in change['api'].values()], + 'api_cgroup_memory_end_bytes': [value.get('memory_current_bytes_end') for value in change['cgroup_api'].values()], 'postgres_cgroup_memory_end_bytes': postgres_values.get('memory_current_bytes_end'), 'valkey_cgroup_memory_end_bytes': valkey_values.get('memory_current_bytes_end'), 'lb_cgroup_memory_end_bytes': lb_values.get('memory_current_bytes_end'), @@ -426,6 +465,8 @@ def summarize_run(label, config, before, after, elapsed_seconds, load): 'pool_waits_per_acquire': round(pool_waits / pool_acquires, 6) if pool_acquires else 0, }, 'lb': lb, + 'wal': change['wal'], + 'bgwriter': change['bgwriter'], 'snapshot_before_at': before['collected_at'], 'snapshot_after_at': after['collected_at'], } diff --git a/scripts/track1.py b/scripts/track1.py new file mode 100755 index 00000000..d6952cb5 --- /dev/null +++ b/scripts/track1.py @@ -0,0 +1,365 @@ +#!/usr/bin/env python3 +"""Level-5 track 1: the price of scaling. + +Experiment design (documented in evidence/track1/methodology.md): + A. Fix total API CPU/RAM at 0.8 cores / 512 MiB and compare 1, 2 and 4 + replicas on the same closed-loop message-POST profile. DB, Valkey and LB + limits stay fixed. + B. At 4 replicas, grow total API CPU through 0.4 -> 0.7 -> 0.9 cores while + keeping RAM fixed, to find where more HTTP capacity stops helping. + C. At the saturated 4x0.2 profile, compare the baseline image (explicit + transaction + 3 SQL statements per new message) with the final image + (one atomic data-modifying CTE statement). + +Each run records real timestamps, cgroup CPU/throttle, PostgreSQL deltas, +HAProxy queues/errors and pgx pool waits. The VM has only 2 vCPU; the sum of +container CPU limits in every configuration is kept <= 1.9 cores. + +Python 3.9+, standard library only. +""" +import argparse +import datetime as dt +import json +import math +import os +import statistics +import subprocess +import sys +import threading +import time +from collections import Counter +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / 'scripts')) +import lab3_metrics as M # noqa: E402 + +OUT = ROOT / 'evidence/track1' +LOADGEN = Path('/tmp/mtusi-lab3-loadgen-track1') +FINAL_IMAGE = 'mtusi-messenger-lab3-melnikov:local' +BASELINE_IMAGE = 'mtusi-messenger-lab3-melnikov:track-baseline' +DURATION = 20 +WARMUP = 5 +CONCURRENCY = 32 + + +def now(): + return M.iso() + + +def build_loadgen(): + result = subprocess.run(['go', 'build', '-ldflags=-X main.version=lab3-track1', + '-o', str(LOADGEN), './cmd/loadgen'], + cwd=str(ROOT), text=True, capture_output=True, check=False) + if result.returncode != 0: + raise RuntimeError('loadgen build failed: ' + result.stderr[-800:]) + + +def config(replicas, cpu_per, mem_per, cpu_total, mem_total, image, label): + return { + 'replicas': replicas, + 'api_cpu_per_replica': cpu_per, + 'api_cpu_total': cpu_total, + 'api_mem_per_replica': mem_per, + 'api_mem_total': mem_total, + 'image': image, + 'label': label, + } + + +def run_one(label, cfg, revision, raw_dir, run_dir): + M.set_stack_profile(cfg['image'], revision, cfg['replicas'], cfg['api_cpu_per_replica'], + cfg['api_mem_per_replica'], cfg['gomemlimit']) + time.sleep(2) # let HAProxy's resolver drop a removed backend + before = M.snapshot() + activity_samples = [] + sampler_stop = threading.Event() + + def sample_activity(): + while not sampler_stop.is_set(): + try: + activity_samples.append(M.db_activity_sample()) + except Exception: + pass + sampler_stop.wait(0.5) + + sampler = threading.Thread(target=sample_activity, name='db-activity-sampler', daemon=True) + sampler.start() + wall_start = time.monotonic() + wall_start_utc = M.iso() + raw_path = raw_dir / (label + '.json') + load = M.run_loadgen(LOADGEN, raw_path, DURATION, WARMUP, CONCURRENCY, + 'track1 %s; replicas=%d cpu_per=%s mem_per=%s' % ( + label, cfg['replicas'], cfg['api_cpu_per_replica'], + cfg['api_mem_per_replica'])) + wall_end = time.monotonic() + wall_end_utc = M.iso() + sampler_stop.set() + sampler.join(timeout=5) + after = M.snapshot() + elapsed = wall_end - wall_start + record = M.summarize_run(label, cfg, before, after, elapsed, load) + record['wall_window'] = {'started_at': wall_start_utc, 'finished_at': wall_end_utc, + 'seconds': round(elapsed, 3), + 'note': 'cgroup/DB/LB counters are sampled just outside this wall window'} + waits = Counter() + max_active = 0 + max_waiting = 0 + for item in activity_samples: + if not isinstance(item, dict): + continue + max_active = max(max_active, item.get('active', 0)) + max_waiting = max(max_waiting, item.get('waiting', 0)) + for key, value in (item.get('waits') or {}).items(): + waits[key] += value + record['db_activity_sampler'] = { + 'samples': len(activity_samples), + 'interval_seconds': 0.5, + 'max_active_connections': max_active, + 'max_waiting_connections': max_waiting, + 'wait_event_connection_samples': dict(waits.most_common(12)), + 'note': 'counts are active-connection samples, not seconds; the sampler itself is a light DB client', + } + record['containers'] = { + 'api': after['containers']['api'], + 'postgres': after['containers']['postgres'], + 'valkey': after['containers']['valkey'], + 'lb': after['containers']['lb'], + } + record['snapshot_before'] = before + record['snapshot_after'] = after + run_path = run_dir / (label + '.json') + run_path.write_text(json.dumps(record, indent=2, ensure_ascii=False) + '\n') + print('%s: %.1f RPS, p95 %.1f ms, errors %d, api %.3f/%.3f cores, db %.3f/%.3f cores' % ( + label, load['successful_rps'], load['successful_latency_ms']['p95'], + load['failed_requests'], record['resource']['api_used_cores'], + record['resource']['api_limit_cores'], record['resource']['db_used_cores'], + record['resource']['db_limit_cores'])) + return record + + +def medians_for(runs, group_key): + values = {} + for run in runs: + label = run['config'][group_key] + values.setdefault(str(label), []).append(run) + result = {} + for label, items in values.items(): + result[label] = { + 'runs': len(items), + 'successful_rps': M.median([item['loadgen']['successful_rps'] for item in items]), + 'error_ratio': M.median([item['loadgen']['error_ratio'] for item in items]), + 'p50_ms': M.median([item['loadgen']['successful_latency_ms']['p50'] for item in items]), + 'p95_ms': M.median([item['loadgen']['successful_latency_ms']['p95'] for item in items]), + 'p99_ms': M.median([item['loadgen']['successful_latency_ms']['p99'] for item in items]), + 'api_used_cores': M.median([item['resource']['api_used_cores'] for item in items]), + 'api_limit_cores': M.median([item['resource']['api_limit_cores'] for item in items]), + 'api_utilization': M.median([item['resource']['api_utilization'] for item in items]), + 'api_throttled_seconds': M.median([item['resource']['api_throttled_seconds'] for item in items]), + 'db_used_cores': M.median([item['resource']['db_used_cores'] for item in items]), + 'db_limit_cores': M.median([item['resource']['db_limit_cores'] for item in items]), + 'db_utilization': M.median([item['resource']['db_utilization'] for item in items]), + 'db_throttled_seconds': M.median([item['resource']['db_throttled_seconds'] for item in items]), + 'lb_used_cores': M.median([item['resource']['lb_used_cores'] for item in items]), + 'lb_qmax': M.median([item['lb']['qmax_after'] for item in items]), + 'lb_5xx': M.median([item['lb']['hrsp_5xx_delta'] for item in items]), + 'pool_waits_per_acquire': M.median([item['postgres']['pool_waits_per_acquire'] for item in items]), + 'commits_per_second': M.median([item['postgres']['commits_per_second'] for item in items]), + 'wal_bytes': M.median([item['wal']['wal_bytes'] for item in items]), + 'wal_sync_time_ms': M.median([item['wal']['wal_sync_time'] for item in items]), + 'checkpoints_req': M.median([item['bgwriter']['checkpoints_req'] for item in items]), + 'db_throttled_periods': M.median([item['resource']['db_throttled_periods'] for item in items]), + 'buffer_hit_ratio': M.median([item['postgres']['buffer_hit_ratio'] for item in items]), + 'messages_after': M.median([item['postgres']['datasets_after']['messages'] for item in items]), + 'image_ids': sorted({image for item in items for image in + [c['image_id'] for c in item['containers']['api']]}), + 'revision': sorted({item['config'].get('revision') for item in items if item['config'].get('revision')}), + } + return result + + +def main(): + parser = argparse.ArgumentParser(description='Track 1 scaling experiment') + parser.add_argument('--baseline-image', default=BASELINE_IMAGE) + parser.add_argument('--final-image', default=FINAL_IMAGE) + parser.add_argument('--reps', type=int, default=3) + parser.add_argument('--output-dir', default='evidence/track1') + parser.add_argument('--quick', action='store_true', help='one repetition per configuration') + args = parser.parse_args() + global OUT + OUT = (ROOT / args.output_dir).resolve() + raw_dir = OUT / 'raw' + run_dir = OUT / 'runs' + raw_dir.mkdir(parents=True, exist_ok=True) + run_dir.mkdir(parents=True, exist_ok=True) + reps = 1 if args.quick else args.reps + + for image in (args.final_image, args.baseline_image): + result = subprocess.run(['docker', 'image', 'inspect', image], text=True, + capture_output=True, check=False) + if result.returncode != 0: + raise RuntimeError('image not found: %s (build it first)' % image) + build_loadgen() + revision = subprocess.run(['git', 'rev-parse', 'HEAD'], cwd=str(ROOT), text=True, + capture_output=True, check=True).stdout.strip() + + metadata = M.build_metadata(args.final_image) + metadata.update({ + 'experiment_started_at': now(), + 'profile': { + 'load': 'closed-loop POST messages through the LB; unique Idempotency-Key per request', + 'duration_seconds': DURATION, + 'warmup_seconds': WARMUP, + 'concurrency': CONCURRENCY, + 'loadgen': 'cmd/loadgen (Go, HTTP acknowledgement throughput)', + }, + 'vm_capacity_note': 'Colima VM has 2 vCPU / 2 GiB; all API processes, PostgreSQL, Valkey and HAProxy share one kernel and one Docker host. The experiment proves process-level scaling limits, not node-level HA.', + 'limits': { + 'postgres_cpu': 0.7, 'postgres_mem': '512M', + 'valkey_cpu': 0.1, 'valkey_mem': '128M', + 'lb_cpu': 0.2, 'lb_mem': '64M', + 'sum_cpu_fixed_total': 1.8, + 'sum_cpu_growth_max': 1.9, + }, + }) + + # Warm the stack and apply the shared DB/LB limits once, preserving volumes. + M.set_stack_profile(args.final_image, revision, 2, 0.4, '256M', '240MiB', recreate_state=True) + if not M.wait_ready(120): + raise RuntimeError('stack not ready') + + fixed = [] + for rep in range(reps): + for replicas, cpu, mem, gomem in ((1, 0.8, '512M', '480MiB'), + (2, 0.4, '256M', '240MiB'), + (4, 0.2, '128M', '112MiB')): + label = 'fixed-r%d-rep%d' % (replicas, rep + 1) + cfg = config(replicas, cpu, mem, 0.8, '512M', args.final_image, 'r%d' % replicas) + cfg['gomemlimit'] = gomem + cfg['revision'] = revision + fixed.append(run_one(label, cfg, revision, raw_dir, run_dir)) + + growth = [] + for rep in range(reps): + for total, cpu, gomem in ((0.4, 0.1, '112MiB'), (0.7, 0.175, '112MiB'), (0.9, 0.225, '112MiB')): + label = 'growth-cpu%s-rep%d' % (str(total).replace('.', 'p'), rep + 1) + cfg = config(4, cpu, '128M', total, '512M', args.final_image, 'cpu%s' % total) + cfg['gomemlimit'] = gomem + cfg['revision'] = revision + growth.append(run_one(label, cfg, revision, raw_dir, run_dir)) + + improvement = [] + for rep in range(reps): + for image, name in ((args.baseline_image, 'baseline'), (args.final_image, 'optimized')): + label = 'improve-%s-rep%d' % (name, rep + 1) + cfg = config(4, 0.2, '128M', 0.8, '512M', image, name) + cfg['gomemlimit'] = '112MiB' + cfg['revision'] = revision if name == 'optimized' else revision + '+baseline-image' + improvement.append(run_one(label, cfg, revision, raw_dir, run_dir)) + + # Leave the stand in the documented default profile and final image. + M.set_stack_profile(args.final_image, revision, 2, 0.4, '256M', '240MiB') + time.sleep(2) + + summary = { + 'metadata': metadata, + 'finished_at': now(), + 'run_count': len(fixed) + len(growth) + len(improvement), + 'runs': {'fixed_total': fixed, 'resource_growth': growth, 'improvement': improvement}, + 'medians': { + 'fixed_total': medians_for(fixed, 'replicas'), + 'resource_growth': medians_for(growth, 'api_cpu_total'), + 'improvement': medians_for(improvement, 'label'), + }, + } + (OUT / 'summary.json').write_text(json.dumps(summary, indent=2, ensure_ascii=False) + '\n') + methodology = (METHODOLOGY + .replace('__REPS__', str(reps)) + .replace('__DURATION__', str(DURATION)) + .replace('__WARMUP__', str(WARMUP)) + .replace('__CONCURRENCY__', str(CONCURRENCY))) + (OUT / 'methodology.md').write_text(methodology + '\n') + print('wrote', OUT / 'summary.json') + + base = summary['medians']['improvement'].get('baseline', {}).get('successful_rps') + opt = summary['medians']['improvement'].get('optimized', {}).get('successful_rps') + if base and opt: + print('improvement: baseline %.1f RPS -> optimized %.1f RPS (%.1f%%)' % ( + base, opt, (opt - base) / base * 100.0)) + print('fixed medians:', json.dumps(summary['medians']['fixed_total'], indent=1)[:1500]) + print('growth medians:', json.dumps(summary['medians']['resource_growth'], indent=1)[:1500]) + + +METHODOLOGY = """# Track 1 methodology: price of scaling + +## Hypothesis + +At a fixed total API CPU/RAM budget, adding API replicas raises HTTP +acknowledgement throughput only until a shared component saturates. On this +single Docker host the candidate shared bottlenecks are PostgreSQL CPU/WAL, +the pgx pool, HAProxy and the 2-vCPU VM itself. Once DB CPU is throttled, more +replicas add contention rather than throughput. Folding the message insert and +the idempotency record into one atomic statement should reduce DB work per +acknowledged message and raise throughput at the same limits. + +## Fixed profile + +* Load: closed-loop POST /api/v1/chats/{id}/messages through the LB, unique + Idempotency-Key and unique text per request, __CONCURRENCY__ Go workers, + __WARMUP__ s warmup, __DURATION__ s measured. +* Total API budget: 0.8 vCPU and 512 MiB, split 1x0.8 / 2x0.4 / 4x0.2 and + 1x512M / 2x256M / 4x128M. PostgreSQL, Valkey and HAProxy limits are fixed. +* The whole stand runs on one Colima VM with 2 vCPU and 2 GiB RAM. The sum of + CPU limits is 1.8 cores in the fixed profile and 1.9 in the growth profile. + These are process-level replicas on one kernel, not independent nodes. + +## Resource-growth series + +At 4 replicas, total API CPU grows 0.4 -> 0.7 -> 0.9 vCPU (0.1/0.175/0.225 per +replica), RAM stays 512 MiB total, DB/Valkey/LB limits stay fixed. This +separates "HTTP capacity is the limit" from "shared DB is the limit". + +## Improvement + +At the saturated 4x0.2 profile the baseline image uses an explicit transaction, +a message INSERT and an idempotency INSERT (three SQL statements plus +BEGIN/COMMIT). The final image uses one data-modifying CTE that inserts the +message and the idempotency row atomically; a concurrent unique conflict aborts +the whole statement and is replayed. The client, profile and limits are +identical. Reported improvement is the median of __REPS__ alternating runs. + +## Metric sources and units + +| Field | Source | Unit / meaning | +| --- | --- | --- | +| successful_rps | loadgen JSON | HTTP 2xx acknowledgements / measured seconds; not COMMIT count | +| successful_latency_ms | loadgen JSON | per-request wall time for successful requests, p50/p95/p99 | +| api_used_cores | cgroup v2 cpu.stat usage_usec delta / window | cores actually consumed by all API containers | +| api_throttled_seconds | cgroup v2 throttled_usec delta | CPU throttling, not load average | +| db_used_cores | cgroup v2 cpu.stat of PostgreSQL | cores consumed by the DB container | +| db_throttled_seconds | cgroup v2 throttled_usec of PostgreSQL | evidence of the DB CPU quota being hit | +| commits_per_second | pg_stat_database.xact_commit delta / window | DB transactions, includes auth/chat metadata | +| pool_waits_per_acquire | pgxpool.Stat EmptyAcquireCount delta / AcquireCount delta | fraction of pool acquisitions that had to wait | +| lb_qmax, lb_5xx | HAProxy stats CSV | queue maximum and 5xx on the public frontend | +| buffer_hit_ratio | pg_stat_database blks_hit/(hit+read) | shared-buffer locality | +| memory | cgroup v2 memory.current | cgroup working set, not process RSS | + +## Limitations + +* One Docker VM and one DB instance: no node failover, no DB replication. +* Closed-loop load has coordinated omission; the loadgen reports only + successful-request latency and separately counts failures. +* The load generator and the stack share the same 2-vCPU host; client cost is + visible and is part of the measured system. +* Absolute RPS is local and is not a production SLA. +""" + + +if __name__ == '__main__': + try: + main() + except Exception as exc: # noqa: BLE001 + import traceback + traceback.print_exc() + print('FAIL:', exc) + raise SystemExit(1)