Lab 2: PostgreSQL sessions and recovery experiment

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
2026-11-16 22:33:15 +03:00
co-authored by Copilot
parent 65003b6119
commit c2b9df52df
37 changed files with 2128 additions and 46 deletions
+98
View File
@@ -0,0 +1,98 @@
#!/usr/bin/env python3
"""Exercise registration races, chat transaction rollback, and migration idempotence."""
import json
import os
from pathlib import Path
import sys
from concurrent.futures import ThreadPoolExecutor
from urllib.error import HTTPError
from urllib.request import Request, urlopen
import uuid
from psycopg.errors import ForeignKeyViolation
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from src.messenger.store import create_chat_record, get_conn, init_db
BASE_URL = os.environ.get("BASE_URL", "http://127.0.0.1:8080")
def register(payload):
request = Request(
BASE_URL.rstrip("/") + "/api/v1/users",
data=json.dumps(payload).encode("utf-8"),
headers={"Content-Type": "application/json"},
method="POST",
)
try:
with urlopen(request, timeout=10) as response:
return response.status
except HTTPError as error:
return error.code
def main():
username = "race_" + uuid.uuid4().hex[:16]
body = {
"username": username,
"display_name": "Concurrent registration",
"password": "Concurrent-test-pass-92",
}
with ThreadPoolExecutor(max_workers=2) as executor:
statuses = sorted(executor.map(register, (body, body)))
if statuses != [201, 409]:
raise SystemExit("Expected one 201 and one 409 for concurrent duplicate registration")
conn = get_conn()
try:
before = conn.execute("SELECT count(*) AS count FROM chats").fetchone()["count"]
migration_count = conn.execute(
"SELECT count(*) AS count FROM schema_migrations"
).fetchone()["count"]
finally:
conn.close()
if migration_count != 1:
raise SystemExit("Unexpected migration count before idempotence check")
try:
create_chat_record(str(uuid.uuid4()), "rollback check", [str(uuid.uuid4())])
except ForeignKeyViolation:
pass
else:
raise SystemExit("Expected unknown chat member to violate the foreign key")
conn = get_conn()
try:
after = conn.execute("SELECT count(*) AS count FROM chats").fetchone()["count"]
finally:
conn.close()
if after != before:
raise SystemExit("Chat and membership transaction was not rolled back")
init_db()
conn = get_conn()
try:
migration_count_after = conn.execute(
"SELECT count(*) AS count FROM schema_migrations"
).fetchone()["count"]
finally:
conn.close()
if migration_count_after != migration_count:
raise SystemExit("Rerunning migrations changed the migration ledger")
print(
json.dumps(
{
"duplicate_registration_statuses": statuses,
"chat_rollback": "PASS",
"migration_rerun": "PASS",
"database_driver": "PostgreSQL",
},
indent=2,
)
)
if __name__ == "__main__":
main()
+12
View File
@@ -0,0 +1,12 @@
$ErrorActionPreference = "Stop"
$repo = Split-Path -Parent $PSScriptRoot
Set-Location $repo
if (-not (Test-Path ".env")) {
throw "Copy .env.example to .env and configure local credentials first."
}
docker compose --env-file .env up -d --force-recreate --build postgres redis api
if ($LASTEXITCODE -ne 0) { throw "Compose restart failed" }
docker compose --env-file .env ps
+9
View File
@@ -0,0 +1,9 @@
#!/usr/bin/env bash
set -euo pipefail
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
cd "$ROOT"
docker compose --env-file .env up -d --force-recreate --build postgres redis api
docker compose --env-file .env ps
+66
View File
@@ -0,0 +1,66 @@
$ErrorActionPreference = "Stop"
$repo = Split-Path -Parent $PSScriptRoot
Set-Location $repo
if (-not (Test-Path ".env")) {
throw "Copy .env.example to .env and configure local credentials first."
}
$base = "http://127.0.0.1:8080"
$client = [System.Net.Http.HttpClient]::new()
function Invoke-Api([string]$Method, [string]$Path, [string]$Token = "", $Body = $null, [string]$Authorization = "") {
$request = [System.Net.Http.HttpRequestMessage]::new([System.Net.Http.HttpMethod]::new($Method), "$base$Path")
if ($Token) { $request.Headers.Authorization = [System.Net.Http.Headers.AuthenticationHeaderValue]::new("Bearer", $Token) }
if ($Authorization) { $request.Headers.TryAddWithoutValidation("Authorization", $Authorization) | Out-Null }
if ($null -ne $Body) {
$json = ConvertTo-Json -InputObject $Body -Depth 10 -Compress
$request.Content = [System.Net.Http.StringContent]::new($json, [System.Text.Encoding]::UTF8, "application/json")
}
$response = $client.SendAsync($request).GetAwaiter().GetResult()
$content = $response.Content.ReadAsStringAsync().GetAwaiter().GetResult()
$requestId = $response.Headers.GetValues("X-Request-Id") | Select-Object -First 1
if (-not $requestId) { throw "API response is missing X-Request-Id" }
$data = $null
if ($content) { $data = $content | ConvertFrom-Json }
return [pscustomobject]@{ Status = [int]$response.StatusCode; Data = $data }
}
try {
$password = "Persistence-" + [guid]::NewGuid().ToString("N")
$alicePayload = @{ username = "persist_" + [guid]::NewGuid().ToString("N").Substring(0, 12); display_name = "Persistence Alice"; password = $password }
$bobPayload = @{ username = "persist_" + [guid]::NewGuid().ToString("N").Substring(0, 12); display_name = "Persistence Bob"; password = $password }
$alice = (Invoke-Api "POST" "/api/v1/users" -Body $alicePayload).Data
$bob = (Invoke-Api "POST" "/api/v1/users" -Body $bobPayload).Data
$basic = [Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes("$($alicePayload.username):$password"))
$session = (Invoke-Api "POST" "/api/v1/auth/sessions" -Authorization "Basic $basic").Data
$token = $session.token
$chat = (Invoke-Api "POST" "/api/v1/chats" -Token $token -Body @{ title = "Persistence check"; member_ids = @($alice.id, $bob.id) }).Data
$message = (Invoke-Api "POST" "/api/v1/chats/$($chat.id)/messages" -Token $token -Body @{ text = "persisted synthetic message" }).Data
& (Join-Path $PSScriptRoot "restart.ps1")
if ($LASTEXITCODE -ne 0) { throw "Restart action failed" }
$deadline = (Get-Date).AddSeconds(90)
do {
try {
$health = Invoke-Api "GET" "/health/ready"
$me = Invoke-Api "GET" "/api/v1/users/me" -Token $token
if ($health.Status -eq 200 -and $me.Status -eq 200) { break }
} catch { }
Start-Sleep -Milliseconds 500
} while ((Get-Date) -lt $deadline)
if ($me.Status -ne 200 -or $me.Data.id -ne $alice.id) { throw "Existing session did not survive service restart" }
$history = (Invoke-Api "GET" "/api/v1/chats/$($chat.id)/messages?limit=100" -Token $token).Data
if (-not ($history.items | Where-Object { $_.id -eq $message.id })) { throw "Confirmed message did not survive service restart" }
$logout = Invoke-Api "DELETE" "/api/v1/auth/sessions/current" -Token $token
if ($logout.Status -ne 204) { throw "Logout did not return 204" }
$revoked = Invoke-Api "GET" "/api/v1/users/me" -Token $token
if ($revoked.Status -ne 401) { throw "Revoked session remained usable" }
Write-Output "PASS: PostgreSQL message and existing Redis-backed session survived forced recreation of API, PostgreSQL, and Redis volumes; logout revoked the session."
} finally {
$client.Dispose()
}
+80
View File
@@ -0,0 +1,80 @@
$ErrorActionPreference = "Stop"
$repo = Split-Path -Parent $PSScriptRoot
Set-Location $repo
if (-not (Test-Path ".env")) {
throw "Copy .env.example to .env and set POSTGRES_PASSWORD first."
}
$settings = @{}
Get-Content ".env" | ForEach-Object {
if ($_ -match "^\s*([^#=]+)=(.*)$") {
$settings[$matches[1].Trim()] = $matches[2].Trim()
}
}
if (-not $settings["POSTGRES_PASSWORD"]) {
throw "POSTGRES_PASSWORD is missing from .env."
}
$evidence = Join-Path $repo "evidence"
New-Item -ItemType Directory -Force -Path $evidence | Out-Null
$started = Get-Date
docker compose up -d --build
if ($LASTEXITCODE -ne 0) { throw "Compose startup failed" }
docker compose exec -T api python /app/scripts/track2_experiment.py |
Tee-Object -FilePath (Join-Path $evidence "track2-experiment.json")
if ($LASTEXITCODE -ne 0) { throw "Index experiment failed" }
docker compose --profile track2-restore run --rm backup-volume-init
if ($LASTEXITCODE -ne 0) { throw "Could not prepare backup volume" }
$restoreStarted = Get-Date
docker compose exec -T postgres pg_dump -Fc -U messenger -d messenger `
-n track2_lab -f /backups/track2_lab.dump
if ($LASTEXITCODE -ne 0) { throw "PostgreSQL backup failed" }
docker compose --profile track2-restore up -d --force-recreate postgres-restore
if ($LASTEXITCODE -ne 0) { throw "Restore PostgreSQL startup failed" }
$healthy = $false
for ($i = 0; $i -lt 60; $i++) {
$health = docker inspect --format '{{.State.Health.Status}}' mtusi-lab2-postgres-restore 2>$null
if ($health -eq "healthy") {
$healthy = $true
break
}
Start-Sleep -Seconds 2
}
if (-not $healthy) { throw "Restore PostgreSQL did not become healthy" }
docker compose exec -T postgres-restore pg_restore --clean --if-exists `
-U messenger -d messenger /backups/track2_lab.dump
if ($LASTEXITCODE -ne 0) { throw "PostgreSQL restore failed" }
$database = $settings["POSTGRES_DB"]
if (-not $database) { $database = "messenger" }
$username = $settings["POSTGRES_USER"]
if (-not $username) { $username = "messenger" }
$restoreUrl = "postgresql://{0}:{1}@postgres-restore:5432/{2}" -f $username, $settings["POSTGRES_PASSWORD"], $database
docker compose exec -T -e "DATABASE_URL=$restoreUrl" api `
python /app/scripts/track2_verify.py |
Tee-Object -FilePath (Join-Path $evidence "track2-restore.json")
if ($LASTEXITCODE -ne 0) { throw "Restored data verification failed" }
$restoreSeconds = [math]::Round(((Get-Date) - $restoreStarted).TotalSeconds, 2)
$duration = [math]::Round(((Get-Date) - $started).TotalSeconds, 2)
@"
Track 2 local Docker experiment
Started: $($started.ToString("o"))
Duration seconds (including container startup): $duration
Backup + separate database startup + restore + verification seconds: $restoreSeconds
Benchmark data: 100,000 synthetic rows per index variant, skewed chat distribution
Backup: PostgreSQL custom-format dump to named volume; never committed to Git
Restore target: separate PostgreSQL container and separate named volume
Results: see track2-experiment.json and track2-restore.json
"@ | Set-Content -Encoding utf8 (Join-Path $evidence "track2-run.txt")
docker compose ps
+176
View File
@@ -0,0 +1,176 @@
#!/usr/bin/env python3
"""Reproducible index and write-cost experiment over a skewed 100k-row dataset."""
import hashlib
import json
import os
import statistics
import time
import psycopg
from psycopg.rows import dict_row
DATABASE_URL = os.environ["DATABASE_URL"]
ROWS = int(os.environ.get("TRACK2_ROWS", "100000"))
HOT_CHAT = "md5('hot-chat')::uuid"
def plan_summary(plan):
root = plan[0]["Plan"]
nodes = []
def visit(node):
nodes.append(
{
"node": node.get("Node Type"),
"index": node.get("Index Name"),
"actual_rows": node.get("Actual Rows"),
"actual_ms": node.get("Actual Total Time"),
"shared_hit_blocks": node.get("Shared Hit Blocks", 0),
"shared_read_blocks": node.get("Shared Read Blocks", 0),
"sort_method": node.get("Sort Method"),
}
)
for child in node.get("Plans", []):
visit(child)
visit(root)
return nodes
def insert_dataset(conn, table):
started = time.perf_counter()
conn.execute(
"""
INSERT INTO {} (id, chat_id, created_at, body)
SELECT i,
CASE WHEN i <= %s * 0.8
THEN md5('hot-chat')::uuid
ELSE md5('chat-' || (i %% 20)::text)::uuid
END,
TIMESTAMPTZ '2025-01-01 00:00:00+00' + make_interval(secs => i::double precision),
repeat('x', 64 + (i %% 449))
FROM generate_series(1, %s) AS i
""".format(table),
(ROWS, ROWS),
)
conn.commit()
return round(time.perf_counter() - started, 4)
def table_sample(conn, table):
return conn.execute(
"SELECT id, chat_id::text AS chat_id, created_at::text AS created_at, body "
"FROM {} WHERE id = ANY(%s) ORDER BY id".format(table),
([1, ROWS // 2, ROWS],),
).fetchall()
def main():
if ROWS < 100000:
raise SystemExit("TRACK2_ROWS must be at least 100000")
with psycopg.connect(DATABASE_URL, row_factory=dict_row) as conn:
conn.execute("DROP SCHEMA IF EXISTS track2_lab CASCADE")
conn.execute("CREATE SCHEMA track2_lab")
for table in ("messages_chat_only", "messages_composite"):
conn.execute(
"""
CREATE TABLE track2_lab.{} (
id BIGINT PRIMARY KEY,
chat_id UUID NOT NULL,
created_at TIMESTAMPTZ NOT NULL,
body TEXT NOT NULL
)
""".format(table)
)
conn.execute(
"CREATE INDEX messages_chat_only_idx ON track2_lab.messages_chat_only(chat_id)"
)
conn.execute(
"CREATE INDEX messages_composite_idx "
"ON track2_lab.messages_composite(chat_id, created_at, id)"
)
conn.commit()
write_seconds = {}
for table in ("messages_chat_only", "messages_composite"):
write_seconds[table] = insert_dataset(conn, "track2_lab." + table)
conn.execute("ANALYZE track2_lab.messages_chat_only")
conn.execute("ANALYZE track2_lab.messages_composite")
conn.commit()
plans = {}
for table in ("messages_chat_only", "messages_composite"):
result = conn.execute(
"""
EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON)
SELECT id, created_at, body
FROM track2_lab.{}
WHERE chat_id = {}
ORDER BY created_at, id
LIMIT 50
""".format(table, HOT_CHAT)
).fetchone()
plan_json = result["QUERY PLAN"]
if isinstance(plan_json, str):
plan_json = json.loads(plan_json)
plans[table] = plan_summary(plan_json)
manifest_rows = []
samples = {}
for table in ("messages_chat_only", "messages_composite"):
rows = table_sample(conn, "track2_lab." + table)
encoded = json.dumps(rows, sort_keys=True, default=str).encode("utf-8")
digest = hashlib.sha256(encoded).hexdigest()
samples[table] = {
"sample_ids": [1, ROWS // 2, ROWS],
"sha256": digest,
}
count = conn.execute(
"SELECT count(*) AS count FROM track2_lab.{}".format(table)
).fetchone()["count"]
index_size = conn.execute(
"SELECT pg_relation_size('track2_lab.{}') AS bytes".format(
"messages_chat_only_idx"
if table == "messages_chat_only"
else "messages_composite_idx"
)
).fetchone()["bytes"]
manifest_rows.append((table, count, samples[table]["sample_ids"], digest))
samples[table]["index_bytes"] = index_size
conn.execute(
"""
CREATE TABLE track2_lab.manifest (
table_name TEXT PRIMARY KEY,
row_count BIGINT NOT NULL,
sample_ids BIGINT[] NOT NULL,
sample_sha256 TEXT NOT NULL
)
"""
)
with conn.cursor() as cur:
cur.executemany(
"INSERT INTO track2_lab.manifest VALUES (%s, %s, %s, %s)",
manifest_rows,
)
conn.commit()
result = {
"dataset_rows_per_variant": ROWS,
"distribution": "80% in one hot chat; remaining 20% split across 20 chats",
"body_size_bytes": "64..512, deterministic",
"write_seconds_single_bulk_insert_with_index": write_seconds,
"explain_analyze_buffers": plans,
"index_size_and_restore_manifest": samples,
"limits": [
"single local Docker host and one trial per variant",
"EXPLAIN ANALYZE executes the query and is not a production latency guarantee",
"write times include local cache and container scheduling noise",
],
}
print(json.dumps(result, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
+44
View File
@@ -0,0 +1,44 @@
#!/usr/bin/env python3
"""Verify row counts and sampled content against the manifest restored from backup."""
import hashlib
import json
import os
import psycopg
from psycopg.rows import dict_row
def main():
with psycopg.connect(os.environ["DATABASE_URL"], row_factory=dict_row) as conn:
manifests = conn.execute(
"SELECT table_name, row_count, sample_ids, sample_sha256 "
"FROM track2_lab.manifest ORDER BY table_name"
).fetchall()
if len(manifests) != 2:
raise SystemExit("Expected both benchmark variants in restored manifest")
verified = []
for manifest in manifests:
table = manifest["table_name"]
if table not in {"messages_chat_only", "messages_composite"}:
raise SystemExit("Unexpected table in restore manifest")
count = conn.execute(
"SELECT count(*) AS count FROM track2_lab.{}".format(table)
).fetchone()["count"]
if count != manifest["row_count"]:
raise SystemExit("Row count mismatch for {}".format(table))
rows = conn.execute(
"SELECT id, chat_id::text AS chat_id, created_at::text AS created_at, body "
"FROM track2_lab.{} WHERE id = ANY(%s) ORDER BY id".format(table),
(manifest["sample_ids"],),
).fetchall()
digest = hashlib.sha256(
json.dumps(rows, sort_keys=True, default=str).encode("utf-8")
).hexdigest()
if digest != manifest["sample_sha256"]:
raise SystemExit("Sample checksum mismatch for {}".format(table))
verified.append({"table": table, "rows": count, "sample_sha256": digest})
print(json.dumps({"restored": verified, "result": "PASS"}, indent=2))
if __name__ == "__main__":
main()