Add lab 3 scaling research and database bottleneck evidence
This commit is contained in:
@@ -0,0 +1,32 @@
|
||||
# Lab 3, track 1: scaling experiment
|
||||
|
||||
The experiment starts a unique `lab3-grade5-*` Compose project, uses a free loopback LB port, removes the PostgreSQL host port, and deletes only that project's containers and volumes in `finally`. The normal project is not modified. API credentials and the experiment-specific database URL exist only in a temporary directory. Compose 2.24.4+, Go matching go.mod, Python 3.9+, Docker and the normal local `.env`/`secrets/` bootstrap are required.
|
||||
|
||||
Run from the repository root:
|
||||
|
||||
```sh
|
||||
python3 student-tests/lab3/grade5/run.py --plan student-tests/lab3/grade5/plan.controlled.json --output evidence/my-scaling-run
|
||||
python3 student-tests/lab3/grade5/run.py --plan student-tests/lab3/grade5/plan.pool-screen.json --output evidence/my-pool-screen
|
||||
python3 student-tests/lab3/grade5/run.py --plan student-tests/lab3/grade5/plan.confirm.json --output evidence/my-group-commit
|
||||
python3 student-tests/lab3/grade5/run.py --plan student-tests/lab3/grade5/plan.db-cpu.json --output evidence/my-db-cpu
|
||||
python3 student-tests/lab3/grade5/analyze.py evidence/my-scaling-run evidence/my-pool-screen evidence/my-group-commit --output evidence/my-analysis
|
||||
python3 student-tests/lab3/grade5/verify_evidence.py evidence/my-db-cpu
|
||||
```
|
||||
|
||||
Output directories must be empty. Plans contain all resource and workload parameters. `plan.fixed.json` is the initial exploratory method (cap 256 in its historical saved run); the current runner defaults to cap 1024, so consult each saved `load.json` for the actual cap rather than attributing old measurements to current code. `plan.controlled.json` fixes the total pool at 32 (32/16/8 connections per API for 1/2/4 replicas) and total API CPU/RAM at 4 vCPU/1024 MiB. Its growth series uses two replicas and 2/3/4 vCPU with 512/768/1024 MiB. PostgreSQL remains at 2 vCPU/512 MiB, LB at 1 vCPU/256 MiB, Redis at 0.5 vCPU/128 MiB.
|
||||
|
||||
Before each point, only the experiment's `messages` and `message_idempotency` are truncated, and 100,000 synthetic messages are inserted and analyzed. The pool screening and confirmation plans warm the server at the target rate for 10 s, reset to the same dataset, issue CHECKPOINT and wait 3 s. The measured Go process starts with a fresh HTTP transport; cold client connection establishment is part of this finite workload. The initial two series used only a 3 s / 200 RPS warmup and have stronger startup effects.
|
||||
|
||||
The Go client schedules independent POSTs at a fixed rate, uses unique keys, keeps HTTP connections, and does not retry. If the scheduler is over 250 ms late, or all in-flight slots are occupied, it counts the attempt as dropped. This bounded open-loop workload prevents unbounded memory use; its drops are client admission failures, not HTTP server responses. Requests have a 5 s network timeout. The primary completed throughput is `successful_rps_wall`, including the drain tail. `successful_rps_window` is also retained but must not be presented as steady completed throughput. `success_latency_ms` covers HTTP 201 only; the revised meter additionally records `completed_full_latency_ms` from planned departure to completion for all sent requests, including failed responses, and measures dispatch lag inside the goroutine. Drops have no completed latency and remain in the denominator of success ratio.
|
||||
|
||||
Record `messages_added - successful_requests` as unconfirmed committed writes. A timeout/503 does not imply a rolled-back operation. No mutation is retried under a different key. All experiments count this difference instead of silently equating HTTP acknowledgements with inserted rows.
|
||||
|
||||
Samples include CPU/RAM, PostgreSQL active/waiting connections, HAProxy queue/errors and individual collection timestamps. They are discrete observations, not continuous maxima. New confirmation runs also save before/after cgroup CPU throttling, PostgreSQL 18 `pg_stat_io` WAL timings, `pg_stat_wal`, effective durability settings and `pg_stat_statements`. In PostgreSQL 18 WAL timing moved to `pg_stat_io`; the old `pg_stat_wal.wal_sync_time` field does not exist. Snapshot boundaries include small instrumentation overhead.
|
||||
|
||||
`plan.confirm.json` changes only `commit_delay` between 0 and 1000 microseconds in ABBAAB order, with three points per setting. `fsync=on` and `synchronous_commit=on` must be verified in each diagnostic snapshot. This is a group commit latency/throughput tradeoff, not permission to weaken durability. Keep failed candidates and all raw results. A single laptop's Docker Desktop VM, thermal state, filesystem and competing host work limit generalization; the measured saturation belongs to this workload and resource envelope.
|
||||
|
||||
Optional charts use matplotlib. The original chart environment used matplotlib 3.11.2; install it in a separate virtual environment, then add `--charts` to analyze.py. Avoid installation, builds or unrelated benchmarks during measured intervals.
|
||||
|
||||
`PG_POOL_DIAGNOSTICS=1` enables one-second aggregate pgxpool counters in the API logs. The experiment override sets it; the normal deployment does not. The first pool-causal run used an incorrect log filter (`msg=pg_pool_stats` instead of the actual default slog text format); its empty pool snapshots are missing evidence, not zero waiting. Subsequent runs accept both formats.
|
||||
|
||||
`plan.wal-diagnostic.json` is a causal diagnostic, not a deployable optimization: it compares synchronous_commit on/off/on on synthetic data in the disposable project, with fixed API/pool/resources. The off point weakens commit acknowledgement guarantees and cannot satisfy the lab's durability contract. It is used only to test whether waiting for WAL flush is limiting throughput. The final point restores on, effective settings are saved, public smoke follows the measured intervals, and the project is deleted. Never apply that diagnostic setting to the normal Compose project. The optional group-commit profile retains synchronous_commit=on and fsync=on.
|
||||
@@ -0,0 +1,188 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Aggregate saved measurements; optional charts require matplotlib."""
|
||||
import argparse
|
||||
import csv
|
||||
import json
|
||||
import re
|
||||
import statistics
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def aggregate(directory):
|
||||
summary = json.loads((directory / 'summary.json').read_text())
|
||||
rows = []
|
||||
for index, run in enumerate(summary['runs'], 1):
|
||||
samples = [json.loads(line) for line in
|
||||
(directory / ('%02d-%s' % (index, run['name'])) / 'samples.jsonl').read_text().splitlines()]
|
||||
cpu = {service: [] for service in ('api', 'postgres', 'lb', 'redis')}
|
||||
memory = {service: [] for service in cpu}
|
||||
connections, locks, io_wait = [], [], []
|
||||
for sample in samples:
|
||||
totals = {service: 0 for service in cpu}
|
||||
mem_totals = {service: 0 for service in cpu}
|
||||
for item in sample.get('docker_stats', []):
|
||||
for service in cpu:
|
||||
if '-%s-' % service in item['Name']:
|
||||
totals[service] += float(item['CPUPerc'].strip('%'))
|
||||
match = re.match(r'([\d.]+)([A-Za-z]+)', item['MemUsage'])
|
||||
if match:
|
||||
factors = {'B':1/1048576, 'KiB':1/1024, 'MiB':1, 'GiB':1024,
|
||||
'kB':1000/1048576, 'MB':1000000/1048576, 'GB':1000000000/1048576}
|
||||
mem_totals[service] += float(match[1])*factors.get(match[2],1)
|
||||
if sample.get('docker_stats'):
|
||||
for service in cpu:
|
||||
cpu[service].append(totals[service])
|
||||
memory[service].append(mem_totals[service])
|
||||
db = sample.get('postgres_activity', {})
|
||||
connections.append(db.get('connections', 0))
|
||||
locks.append(db.get('lock_wait', 0))
|
||||
io_wait.append(db.get('io_wait', 0))
|
||||
load = run['load']
|
||||
row = {key: run.get(key) for key in ('name', 'phase', 'replicas', 'api_total_cpus',
|
||||
'api_total_memory_mib', 'postgres_cpus', 'pool_max_conns_per_replica', 'commit_delay_us', 'diagnostic_async_commit', 'rate')}
|
||||
row.update(source=str(directory), successful_rps=load['successful_rps_wall'],
|
||||
scheduled_window_rps=load['successful_rps_window'],
|
||||
wall_rps=load['successful_rps_wall'], success_ratio=load['success_ratio'],
|
||||
p50_ms=load['success_latency_ms']['p50'], p95_ms=load['success_latency_ms']['p95'],
|
||||
p99_ms=load['success_latency_ms']['p99'], schedule_p99_ms=load['schedule_lag_ms']['p99'],
|
||||
completed_full_p99_ms=load.get('completed_full_latency_ms',{}).get('p99'),
|
||||
failures=json.dumps(load['failure_counts'], sort_keys=True),
|
||||
messages_added=run['messages_added'], confirmed=load['successful_requests'],
|
||||
samples=len(samples), db_connections_max=max(connections, default=0),
|
||||
lock_wait_max=max(locks, default=0), io_wait_max=max(io_wait, default=0))
|
||||
for service, values in cpu.items():
|
||||
row[service + '_cpu_mean_pct'] = round(statistics.mean(values), 2) if values else None
|
||||
row[service + '_cpu_max_pct'] = round(max(values), 2) if values else None
|
||||
row[service + '_memory_max_mib'] = round(max(memory[service]),2) if memory[service] else None
|
||||
diagnostics = directory / ('%02d-%s' % (index, run['name']))
|
||||
if (diagnostics/'pool-stats.json').exists():
|
||||
pools=json.loads((diagnostics/'pool-stats.json').read_text())
|
||||
acquired, wait_ns, canceled, full, points = 0, 0, 0, 0, 0
|
||||
for values in pools.values():
|
||||
counters=[value['counters'] for value in values if value.get('counters')]
|
||||
if len(counters)>1:
|
||||
acquired+=counters[-1]['acquire_count']-counters[0]['acquire_count']
|
||||
wait_ns+=counters[-1]['empty_wait_ns']-counters[0]['empty_wait_ns']
|
||||
canceled+=counters[-1]['canceled_count']-counters[0]['canceled_count']
|
||||
full+=sum(value['acquired']==value['max_conns'] for value in counters)
|
||||
points+=len(counters)
|
||||
row['pool_wait_per_acquire_ms']=round(wait_ns/acquired/1e6,3) if acquired else None
|
||||
row['pool_canceled_acquires']=canceled
|
||||
row['pool_full_sample_ratio']=round(full/points,4) if points else None
|
||||
row['pool_sample_points']=points
|
||||
if (diagnostics/'diagnostics-before.json').exists():
|
||||
before=json.loads((diagnostics/'diagnostics-before.json').read_text())
|
||||
after=json.loads((diagnostics/'diagnostics-after.json').read_text())
|
||||
for service in cpu:
|
||||
ids=[key for key,value in before['cgroups'].items() if value['service']==service]
|
||||
row[service+'_throttled_usec']=sum(after['cgroups'][key].get('throttled_usec',0)-before['cgroups'][key].get('throttled_usec',0) for key in ids)
|
||||
for key in ('wal_bytes','wal_buffers_full'):
|
||||
row[key+'_delta']=float(after['wal'][key])-float(before['wal'][key])
|
||||
for key in ('write_time','fsync_time','writes','fsyncs'):
|
||||
row['wal_'+key+'_delta']=sum(float(x.get(key) or 0) for x in after['wal_io'])-sum(float(x.get(key) or 0) for x in before['wal_io'])
|
||||
rows.append(row)
|
||||
return rows
|
||||
|
||||
|
||||
def charts(rows, output):
|
||||
import matplotlib
|
||||
matplotlib.use('Agg')
|
||||
import matplotlib.pyplot as plt
|
||||
plt.rcParams.update({'font.size': 10, 'axes.grid': True, 'grid.alpha': .25})
|
||||
for phase in sorted({row['phase'] for row in rows}):
|
||||
selected = [row for row in rows if row['phase'] == phase]
|
||||
if phase not in ('fixed_pool32', 'resource_growth', 'pool_improvement'):
|
||||
continue
|
||||
group_key = {'fixed_pool32': 'replicas', 'resource_growth': 'api_total_cpus',
|
||||
'pool_improvement': 'pool_max_conns_per_replica'}[phase]
|
||||
fig, axes = plt.subplots(1, 3, figsize=(13, 3.6))
|
||||
for group in sorted({str(row[group_key]) for row in selected}):
|
||||
points = sorted([row for row in selected if str(row[group_key]) == group], key=lambda x: x['rate'])
|
||||
label = '%s=%s' % (group_key, group)
|
||||
for ax, metric in zip(axes, ('successful_rps', 'p99_ms', 'success_ratio')):
|
||||
ax.plot([p['rate'] for p in points], [p[metric] for p in points], 'o-', label=label)
|
||||
axes[0].set_ylabel('Successful POST/s')
|
||||
axes[1].set_ylabel('p99 successful requests, ms')
|
||||
axes[2].set_ylabel('Success / scheduled requests')
|
||||
for ax in axes:
|
||||
ax.set_xlabel('Scheduled POST/s')
|
||||
axes[0].legend(fontsize=8)
|
||||
fig.suptitle(phase + ' — 100,000 seed messages; fixed-rate workload')
|
||||
fig.tight_layout()
|
||||
fig.savefig(output / (phase + '.svg'))
|
||||
fig.savefig(output / (phase + '.png'), dpi=150)
|
||||
plt.close(fig)
|
||||
selected = [row for row in rows if row['phase'] == 'wal_ablation']
|
||||
if selected:
|
||||
fig, axes = plt.subplots(1, 2, figsize=(9, 3.5))
|
||||
labels = ['ON (before)', 'OFF (diagnostic)', 'ON (after)']
|
||||
for ax, metric, ylabel in zip(axes, ('successful_rps','pool_wait_per_acquire_ms'),
|
||||
('Completed POST/s (wall)', 'Pool wait / acquire, ms')):
|
||||
ax.bar(range(len(selected)), [row[metric] for row in selected],
|
||||
color=['#64748b','#b45309','#64748b'])
|
||||
ax.set_xticks(range(len(selected)),labels,rotation=10)
|
||||
ax.set_ylabel(ylabel)
|
||||
fig.suptitle('Causal WAL diagnostic: OFF weakens durability and is not a deployment option')
|
||||
fig.tight_layout()
|
||||
fig.savefig(output/'wal-ablation.png',dpi=150)
|
||||
fig.savefig(output/'wal-ablation.svg')
|
||||
plt.close(fig)
|
||||
selected = [row for row in rows if row['phase'] == 'db_cpu_causal']
|
||||
if selected:
|
||||
fig, axes = plt.subplots(1, 3, figsize=(13, 4))
|
||||
labels = ['%d API / PG %s' % (row['replicas'],row['postgres_cpus']) for row in selected]
|
||||
colors = ['#64748b' if row['postgres_cpus']==.5 else '#0f766e' for row in selected]
|
||||
for ax, metric, ylabel in zip(axes, ('successful_rps','postgres_cpu_mean_pct','pool_wait_per_acquire_ms'),
|
||||
('Completed POST/s (wall)', 'PostgreSQL CPU, 100%=one core', 'Pool wait / acquire, ms')):
|
||||
ax.bar(range(len(selected)), [row[metric] for row in selected], color=colors)
|
||||
ax.set_xticks(range(len(selected)),labels,rotation=40,ha='right')
|
||||
ax.set_ylabel(ylabel)
|
||||
axes[1].plot(range(len(selected)),[row['postgres_cpus']*100 for row in selected], 'k--', label='CPU quota')
|
||||
axes[1].legend()
|
||||
fig.suptitle('Controlled database CPU budget; 2000 scheduled POST/s, fixed total API budget and pool')
|
||||
fig.tight_layout()
|
||||
fig.savefig(output/'db-cpu-causal.png',dpi=150)
|
||||
fig.savefig(output/'db-cpu-causal.svg')
|
||||
plt.close(fig)
|
||||
selected = [row for row in rows if row['phase'] == 'wal_group_commit']
|
||||
if selected:
|
||||
groups = sorted({row['commit_delay_us'] for row in selected})
|
||||
fig, axes = plt.subplots(1, 3, figsize=(12, 3.6))
|
||||
for ax, metric, label in zip(axes, ('successful_rps', 'p99_ms', 'wal_fsyncs_delta'),
|
||||
('Completed POST/s (wall time)', 'p99 HTTP 201, ms', 'WAL fsync count')):
|
||||
for index, group in enumerate(groups):
|
||||
values = [row[metric] for row in selected if row['commit_delay_us'] == group]
|
||||
ax.bar(index, statistics.median(values), color=('#64748b', '#0f766e')[index % 2], alpha=.65)
|
||||
ax.scatter([index]*len(values), values, color='black', s=25, zorder=3)
|
||||
ax.set_xticks(range(len(groups)), [str(group) + ' us' for group in groups])
|
||||
ax.set_ylabel(label)
|
||||
fig.suptitle('Group commit: median bars and three raw repeats; 3000 scheduled POST/s')
|
||||
fig.tight_layout()
|
||||
fig.savefig(output / 'group-commit.svg')
|
||||
fig.savefig(output / 'group-commit.png', dpi=150)
|
||||
plt.close(fig)
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('directories', nargs='+', type=Path)
|
||||
parser.add_argument('--output', required=True, type=Path)
|
||||
parser.add_argument('--charts', action='store_true')
|
||||
args = parser.parse_args()
|
||||
rows = [row for directory in args.directories for row in aggregate(directory)]
|
||||
args.output.mkdir(parents=True, exist_ok=True)
|
||||
(args.output / 'results.json').write_text(json.dumps(rows, indent=2) + '\n')
|
||||
with (args.output / 'results.csv').open('w', newline='') as stream:
|
||||
writer = csv.DictWriter(stream, fieldnames=list(dict.fromkeys(key for row in rows for key in row)))
|
||||
writer.writeheader()
|
||||
writer.writerows(rows)
|
||||
if args.charts:
|
||||
charts(rows, args.output)
|
||||
for row in rows:
|
||||
print('%-30s %7.1f RPS %6.2f%% p99=%7.1f ms CPU api/pg/lb=%5.1f/%5.1f/%5.1f' %
|
||||
(row['name'], row['successful_rps'], row['success_ratio']*100, row['p99_ms'],
|
||||
row['api_cpu_mean_pct'], row['postgres_cpu_mean_pct'], row['lb_cpu_mean_pct']))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,204 @@
|
||||
// A fixed-rate HTTP workload for the lab 3 scaling experiment.
|
||||
// Credentials are read from a local file and never written to output.
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
"math"
|
||||
"net"
|
||||
"net/http"
|
||||
"os"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
type credentials struct {
|
||||
Token string `json:"token"`
|
||||
ChatID string `json:"chat_id"`
|
||||
}
|
||||
|
||||
type result struct {
|
||||
kind string
|
||||
status int
|
||||
latency time.Duration
|
||||
lag time.Duration
|
||||
full time.Duration
|
||||
instanceID string
|
||||
}
|
||||
|
||||
type percentiles struct {
|
||||
P50 float64 `json:"p50"`
|
||||
P95 float64 `json:"p95"`
|
||||
P99 float64 `json:"p99"`
|
||||
}
|
||||
|
||||
func quantiles(values []float64) percentiles {
|
||||
if len(values) == 0 {
|
||||
return percentiles{}
|
||||
}
|
||||
sort.Float64s(values)
|
||||
get := func(p float64) float64 {
|
||||
index := int(math.Ceil(p*float64(len(values)))) - 1
|
||||
return math.Round(values[index]*1000) / 1000
|
||||
}
|
||||
return percentiles{P50: get(.50), P95: get(.95), P99: get(.99)}
|
||||
}
|
||||
|
||||
func main() {
|
||||
baseURL := flag.String("base-url", "", "public load balancer URL")
|
||||
authFile := flag.String("auth-file", "", "local JSON file with token and chat_id")
|
||||
rate := flag.Float64("rate", 0, "scheduled requests per second")
|
||||
duration := flag.Duration("duration", 20*time.Second, "scheduling window")
|
||||
maxInFlight := flag.Int("max-inflight", 256, "maximum concurrent requests")
|
||||
timeout := flag.Duration("timeout", 5*time.Second, "per-request timeout")
|
||||
flag.Parse()
|
||||
if *baseURL == "" || *authFile == "" || *rate <= 0 || *duration <= 0 || *maxInFlight <= 0 || *timeout <= 0 {
|
||||
fmt.Fprintln(os.Stderr, "base-url, auth-file, positive rate, duration, max-inflight and timeout are required")
|
||||
os.Exit(2)
|
||||
}
|
||||
content, err := os.ReadFile(*authFile)
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, "could not read auth file")
|
||||
os.Exit(2)
|
||||
}
|
||||
var auth credentials
|
||||
if err := json.Unmarshal(content, &auth); err != nil || auth.Token == "" || auth.ChatID == "" {
|
||||
fmt.Fprintln(os.Stderr, "invalid auth file")
|
||||
os.Exit(2)
|
||||
}
|
||||
nonce := make([]byte, 8)
|
||||
if _, err := rand.Read(nonce); err != nil {
|
||||
fmt.Fprintln(os.Stderr, "could not create workload identifier")
|
||||
os.Exit(2)
|
||||
}
|
||||
runID := hex.EncodeToString(nonce)
|
||||
payload, _ := json.Marshal(map[string]string{"text": "grade5-" + runID})
|
||||
transport := &http.Transport{
|
||||
MaxIdleConns: *maxInFlight,
|
||||
MaxIdleConnsPerHost: *maxInFlight,
|
||||
IdleConnTimeout: 90 * time.Second,
|
||||
}
|
||||
client := &http.Client{Transport: transport}
|
||||
defer transport.CloseIdleConnections()
|
||||
url := strings.TrimRight(*baseURL, "/") + "/api/v1/chats/" + auth.ChatID + "/messages"
|
||||
count := int(math.Round(*rate * duration.Seconds()))
|
||||
if count <= 0 || count > 2_000_000 {
|
||||
fmt.Fprintln(os.Stderr, "request count is outside 1..2000000")
|
||||
os.Exit(2)
|
||||
}
|
||||
results := make(chan result, count)
|
||||
semaphore := make(chan struct{}, *maxInFlight)
|
||||
var workers sync.WaitGroup
|
||||
started := time.Now()
|
||||
for i := 0; i < count; i++ {
|
||||
planned := started.Add(time.Duration(float64(i) / *rate * float64(time.Second)))
|
||||
if delay := time.Until(planned); delay > 0 {
|
||||
time.Sleep(delay)
|
||||
}
|
||||
lag := time.Since(planned)
|
||||
if lag > 250*time.Millisecond {
|
||||
results <- result{kind: "dropped_scheduler", lag: lag}
|
||||
continue
|
||||
}
|
||||
select {
|
||||
case semaphore <- struct{}{}:
|
||||
default:
|
||||
results <- result{kind: "dropped_inflight", lag: lag}
|
||||
continue
|
||||
}
|
||||
workers.Add(1)
|
||||
go func(sequence int, planned time.Time) {
|
||||
defer workers.Done()
|
||||
defer func() { <-semaphore }()
|
||||
scheduleLag := time.Since(planned)
|
||||
ctx, cancel := context.WithTimeout(context.Background(), *timeout)
|
||||
defer cancel()
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(payload))
|
||||
if err != nil {
|
||||
results <- result{kind: "client_request", lag: scheduleLag}
|
||||
return
|
||||
}
|
||||
req.Header.Set("Accept", "application/json")
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("Authorization", "Bearer "+auth.Token)
|
||||
req.Header.Set("Idempotency-Key", "g5-"+runID+"-"+strconv.Itoa(sequence))
|
||||
requestStarted := time.Now()
|
||||
response, err := client.Do(req)
|
||||
if err != nil {
|
||||
kind := "connection"
|
||||
var networkError net.Error
|
||||
if errors.Is(err, context.DeadlineExceeded) || errors.As(err, &networkError) && networkError.Timeout() {
|
||||
kind = "timeout"
|
||||
}
|
||||
results <- result{kind: kind, latency: time.Since(requestStarted), lag: scheduleLag, full: time.Since(planned)}
|
||||
return
|
||||
}
|
||||
_, readErr := io.Copy(io.Discard, io.LimitReader(response.Body, 1<<20))
|
||||
response.Body.Close()
|
||||
if readErr != nil {
|
||||
results <- result{kind: "response_read", status: response.StatusCode, latency: time.Since(requestStarted), lag: scheduleLag, full: time.Since(planned)}
|
||||
return
|
||||
}
|
||||
results <- result{kind: "response", status: response.StatusCode, latency: time.Since(requestStarted), lag: scheduleLag, full: time.Since(planned), instanceID: response.Header.Get("X-Instance-Id")}
|
||||
}(i, planned)
|
||||
}
|
||||
workers.Wait()
|
||||
close(results)
|
||||
wall := time.Since(started)
|
||||
counts := map[string]int{}
|
||||
instances := map[string]int{}
|
||||
latencies := make([]float64, 0, count)
|
||||
lags := make([]float64, 0, count)
|
||||
fullLatencies := make([]float64, 0, count)
|
||||
success := 0
|
||||
for item := range results {
|
||||
if item.full > 0 {
|
||||
fullLatencies = append(fullLatencies, float64(item.full)/float64(time.Millisecond))
|
||||
}
|
||||
if item.kind == "response" && item.status == http.StatusCreated {
|
||||
success++
|
||||
latencies = append(latencies, float64(item.latency)/float64(time.Millisecond))
|
||||
if item.instanceID != "" {
|
||||
instances[item.instanceID]++
|
||||
}
|
||||
} else if item.kind == "response" {
|
||||
counts["http_"+strconv.Itoa(item.status)]++
|
||||
} else {
|
||||
counts[item.kind]++
|
||||
}
|
||||
lags = append(lags, float64(item.lag)/float64(time.Millisecond))
|
||||
}
|
||||
report := map[string]any{
|
||||
"workload": "fixed-rate POST messages, unique Idempotency-Key, no retries",
|
||||
"started_at_utc": started.UTC().Format(time.RFC3339Nano),
|
||||
"run_id": runID,
|
||||
"scheduled_rps": *rate,
|
||||
"scheduled_duration_s": duration.Seconds(),
|
||||
"wall_duration_s": math.Round(wall.Seconds()*1000) / 1000,
|
||||
"scheduled_requests": count,
|
||||
"successful_requests": success,
|
||||
"failure_counts": counts,
|
||||
"success_ratio": math.Round(float64(success)/float64(count)*1_000_000) / 1_000_000,
|
||||
"successful_rps_window": math.Round(float64(success)/duration.Seconds()*1000) / 1000,
|
||||
"successful_rps_wall": math.Round(float64(success)/wall.Seconds()*1000) / 1000,
|
||||
"success_latency_ms": quantiles(latencies),
|
||||
"schedule_lag_ms": quantiles(lags),
|
||||
"completed_full_latency_ms": quantiles(fullLatencies),
|
||||
"instance_responses": instances,
|
||||
"max_inflight": *maxInFlight,
|
||||
"request_timeout_s": timeout.Seconds(),
|
||||
}
|
||||
output, _ := json.MarshalIndent(report, "", " ")
|
||||
fmt.Println(string(output))
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
{
|
||||
"seed_messages": 100000,
|
||||
"warmup_seconds": 10,
|
||||
"warmup_rate": "target",
|
||||
"settle_seconds": 3,
|
||||
"max_inflight": 1024,
|
||||
"runs": [
|
||||
{
|
||||
"name": "commit-0-repeat1",
|
||||
"phase": "wal_group_commit",
|
||||
"replicas": 2,
|
||||
"api_total_cpus": 4,
|
||||
"api_total_memory_mib": 1024,
|
||||
"pool_max_conns": 8,
|
||||
"commit_delay_us": 0,
|
||||
"rate": 3000,
|
||||
"duration_seconds": 30
|
||||
},
|
||||
{
|
||||
"name": "commit-1000-repeat2",
|
||||
"phase": "wal_group_commit",
|
||||
"replicas": 2,
|
||||
"api_total_cpus": 4,
|
||||
"api_total_memory_mib": 1024,
|
||||
"pool_max_conns": 8,
|
||||
"commit_delay_us": 1000,
|
||||
"rate": 3000,
|
||||
"duration_seconds": 30
|
||||
},
|
||||
{
|
||||
"name": "commit-1000-repeat3",
|
||||
"phase": "wal_group_commit",
|
||||
"replicas": 2,
|
||||
"api_total_cpus": 4,
|
||||
"api_total_memory_mib": 1024,
|
||||
"pool_max_conns": 8,
|
||||
"commit_delay_us": 1000,
|
||||
"rate": 3000,
|
||||
"duration_seconds": 30
|
||||
},
|
||||
{
|
||||
"name": "commit-0-repeat4",
|
||||
"phase": "wal_group_commit",
|
||||
"replicas": 2,
|
||||
"api_total_cpus": 4,
|
||||
"api_total_memory_mib": 1024,
|
||||
"pool_max_conns": 8,
|
||||
"commit_delay_us": 0,
|
||||
"rate": 3000,
|
||||
"duration_seconds": 30
|
||||
},
|
||||
{
|
||||
"name": "commit-0-repeat5",
|
||||
"phase": "wal_group_commit",
|
||||
"replicas": 2,
|
||||
"api_total_cpus": 4,
|
||||
"api_total_memory_mib": 1024,
|
||||
"pool_max_conns": 8,
|
||||
"commit_delay_us": 0,
|
||||
"rate": 3000,
|
||||
"duration_seconds": 30
|
||||
},
|
||||
{
|
||||
"name": "commit-1000-repeat6",
|
||||
"phase": "wal_group_commit",
|
||||
"replicas": 2,
|
||||
"api_total_cpus": 4,
|
||||
"api_total_memory_mib": 1024,
|
||||
"pool_max_conns": 8,
|
||||
"commit_delay_us": 1000,
|
||||
"rate": 3000,
|
||||
"duration_seconds": 30
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
{
|
||||
"seed_messages": 100000,
|
||||
"warmup_seconds": 3,
|
||||
"max_inflight": 1024,
|
||||
"runs": [
|
||||
{"name":"pool32-fixed-r1000-n1", "phase":"fixed_pool32", "replicas":1, "api_total_cpus":4, "api_total_memory_mib":1024, "pool_max_conns":32, "rate":1000, "duration_seconds":20},
|
||||
{"name":"pool32-fixed-r1000-n2", "phase":"fixed_pool32", "replicas":2, "api_total_cpus":4, "api_total_memory_mib":1024, "pool_max_conns":16, "rate":1000, "duration_seconds":20},
|
||||
{"name":"pool32-fixed-r1000-n4", "phase":"fixed_pool32", "replicas":4, "api_total_cpus":4, "api_total_memory_mib":1024, "pool_max_conns":8, "rate":1000, "duration_seconds":20},
|
||||
{"name":"pool32-fixed-r2000-n4", "phase":"fixed_pool32", "replicas":4, "api_total_cpus":4, "api_total_memory_mib":1024, "pool_max_conns":8, "rate":2000, "duration_seconds":20},
|
||||
{"name":"pool32-fixed-r2000-n2", "phase":"fixed_pool32", "replicas":2, "api_total_cpus":4, "api_total_memory_mib":1024, "pool_max_conns":16, "rate":2000, "duration_seconds":20},
|
||||
{"name":"pool32-fixed-r2000-n1", "phase":"fixed_pool32", "replicas":1, "api_total_cpus":4, "api_total_memory_mib":1024, "pool_max_conns":32, "rate":2000, "duration_seconds":20},
|
||||
{"name":"pool32-fixed-r3000-n1", "phase":"fixed_pool32", "replicas":1, "api_total_cpus":4, "api_total_memory_mib":1024, "pool_max_conns":32, "rate":3000, "duration_seconds":20},
|
||||
{"name":"pool32-fixed-r3000-n2", "phase":"fixed_pool32", "replicas":2, "api_total_cpus":4, "api_total_memory_mib":1024, "pool_max_conns":16, "rate":3000, "duration_seconds":20},
|
||||
{"name":"pool32-fixed-r3000-n4", "phase":"fixed_pool32", "replicas":4, "api_total_cpus":4, "api_total_memory_mib":1024, "pool_max_conns":8, "rate":3000, "duration_seconds":20},
|
||||
{"name":"grow-r1000-c2", "phase":"resource_growth", "replicas":2, "api_total_cpus":2, "api_total_memory_mib":512, "pool_max_conns":16, "rate":1000, "duration_seconds":20},
|
||||
{"name":"grow-r1000-c3", "phase":"resource_growth", "replicas":2, "api_total_cpus":3, "api_total_memory_mib":768, "pool_max_conns":16, "rate":1000, "duration_seconds":20},
|
||||
{"name":"grow-r1000-c4", "phase":"resource_growth", "replicas":2, "api_total_cpus":4, "api_total_memory_mib":1024, "pool_max_conns":16, "rate":1000, "duration_seconds":20},
|
||||
{"name":"grow-r2000-c4", "phase":"resource_growth", "replicas":2, "api_total_cpus":4, "api_total_memory_mib":1024, "pool_max_conns":16, "rate":2000, "duration_seconds":20},
|
||||
{"name":"grow-r2000-c3", "phase":"resource_growth", "replicas":2, "api_total_cpus":3, "api_total_memory_mib":768, "pool_max_conns":16, "rate":2000, "duration_seconds":20},
|
||||
{"name":"grow-r2000-c2", "phase":"resource_growth", "replicas":2, "api_total_cpus":2, "api_total_memory_mib":512, "pool_max_conns":16, "rate":2000, "duration_seconds":20},
|
||||
{"name":"grow-r3000-c2", "phase":"resource_growth", "replicas":2, "api_total_cpus":2, "api_total_memory_mib":512, "pool_max_conns":16, "rate":3000, "duration_seconds":20},
|
||||
{"name":"grow-r3000-c3", "phase":"resource_growth", "replicas":2, "api_total_cpus":3, "api_total_memory_mib":768, "pool_max_conns":16, "rate":3000, "duration_seconds":20},
|
||||
{"name":"grow-r3000-c4", "phase":"resource_growth", "replicas":2, "api_total_cpus":4, "api_total_memory_mib":1024, "pool_max_conns":16, "rate":3000, "duration_seconds":20}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
{
|
||||
"seed_messages": 100000,
|
||||
"warmup_seconds": 10,
|
||||
"warmup_rate": "target",
|
||||
"settle_seconds": 3,
|
||||
"max_inflight": 1024,
|
||||
"public_smoke_after": true,
|
||||
"runs": [
|
||||
{
|
||||
"name": "db05-n1",
|
||||
"phase": "db_cpu_causal",
|
||||
"replicas": 1,
|
||||
"api_total_cpus": 4,
|
||||
"api_total_memory_mib": 1024,
|
||||
"pool_max_conns": 16,
|
||||
"postgres_cpus": 0.5,
|
||||
"rate": 2000,
|
||||
"duration_seconds": 30
|
||||
},
|
||||
{
|
||||
"name": "db05-n2",
|
||||
"phase": "db_cpu_causal",
|
||||
"replicas": 2,
|
||||
"api_total_cpus": 4,
|
||||
"api_total_memory_mib": 1024,
|
||||
"pool_max_conns": 8,
|
||||
"postgres_cpus": 0.5,
|
||||
"rate": 2000,
|
||||
"duration_seconds": 30
|
||||
},
|
||||
{
|
||||
"name": "db05-n4",
|
||||
"phase": "db_cpu_causal",
|
||||
"replicas": 4,
|
||||
"api_total_cpus": 4,
|
||||
"api_total_memory_mib": 1024,
|
||||
"pool_max_conns": 4,
|
||||
"postgres_cpus": 0.5,
|
||||
"rate": 2000,
|
||||
"duration_seconds": 30
|
||||
},
|
||||
{
|
||||
"name": "db2-n2-first",
|
||||
"phase": "db_cpu_causal",
|
||||
"replicas": 2,
|
||||
"api_total_cpus": 4,
|
||||
"api_total_memory_mib": 1024,
|
||||
"pool_max_conns": 8,
|
||||
"postgres_cpus": 2,
|
||||
"rate": 2000,
|
||||
"duration_seconds": 30
|
||||
},
|
||||
{
|
||||
"name": "db05-n2-repeat",
|
||||
"phase": "db_cpu_causal",
|
||||
"replicas": 2,
|
||||
"api_total_cpus": 4,
|
||||
"api_total_memory_mib": 1024,
|
||||
"pool_max_conns": 8,
|
||||
"postgres_cpus": 0.5,
|
||||
"rate": 2000,
|
||||
"duration_seconds": 30
|
||||
},
|
||||
{
|
||||
"name": "db2-n2-repeat",
|
||||
"phase": "db_cpu_causal",
|
||||
"replicas": 2,
|
||||
"api_total_cpus": 4,
|
||||
"api_total_memory_mib": 1024,
|
||||
"pool_max_conns": 8,
|
||||
"postgres_cpus": 2,
|
||||
"rate": 2000,
|
||||
"duration_seconds": 30
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
{
|
||||
"seed_messages": 100000,
|
||||
"warmup_seconds": 3,
|
||||
"max_inflight": 256,
|
||||
"runs": [
|
||||
{"name":"fixed-r500-n1", "phase":"fixed", "replicas":1, "api_total_cpus":4, "api_total_memory_mib":1024, "postgres_cpus":2, "rate":500, "duration_seconds":20},
|
||||
{"name":"fixed-r500-n2", "phase":"fixed", "replicas":2, "api_total_cpus":4, "api_total_memory_mib":1024, "postgres_cpus":2, "rate":500, "duration_seconds":20},
|
||||
{"name":"fixed-r500-n4", "phase":"fixed", "replicas":4, "api_total_cpus":4, "api_total_memory_mib":1024, "postgres_cpus":2, "rate":500, "duration_seconds":20},
|
||||
{"name":"fixed-r1000-n4", "phase":"fixed", "replicas":4, "api_total_cpus":4, "api_total_memory_mib":1024, "postgres_cpus":2, "rate":1000, "duration_seconds":20},
|
||||
{"name":"fixed-r1000-n2", "phase":"fixed", "replicas":2, "api_total_cpus":4, "api_total_memory_mib":1024, "postgres_cpus":2, "rate":1000, "duration_seconds":20},
|
||||
{"name":"fixed-r1000-n1", "phase":"fixed", "replicas":1, "api_total_cpus":4, "api_total_memory_mib":1024, "postgres_cpus":2, "rate":1000, "duration_seconds":20},
|
||||
{"name":"fixed-r1500-n1", "phase":"fixed", "replicas":1, "api_total_cpus":4, "api_total_memory_mib":1024, "postgres_cpus":2, "rate":1500, "duration_seconds":20},
|
||||
{"name":"fixed-r1500-n2", "phase":"fixed", "replicas":2, "api_total_cpus":4, "api_total_memory_mib":1024, "postgres_cpus":2, "rate":1500, "duration_seconds":20},
|
||||
{"name":"fixed-r1500-n4", "phase":"fixed", "replicas":4, "api_total_cpus":4, "api_total_memory_mib":1024, "postgres_cpus":2, "rate":1500, "duration_seconds":20},
|
||||
{"name":"fixed-r2000-n4", "phase":"fixed", "replicas":4, "api_total_cpus":4, "api_total_memory_mib":1024, "postgres_cpus":2, "rate":2000, "duration_seconds":20},
|
||||
{"name":"fixed-r2000-n2", "phase":"fixed", "replicas":2, "api_total_cpus":4, "api_total_memory_mib":1024, "postgres_cpus":2, "rate":2000, "duration_seconds":20},
|
||||
{"name":"fixed-r2000-n1", "phase":"fixed", "replicas":1, "api_total_cpus":4, "api_total_memory_mib":1024, "postgres_cpus":2, "rate":2000, "duration_seconds":20},
|
||||
{"name":"fixed-r2500-n1", "phase":"fixed", "replicas":1, "api_total_cpus":4, "api_total_memory_mib":1024, "postgres_cpus":2, "rate":2500, "duration_seconds":20},
|
||||
{"name":"fixed-r2500-n2", "phase":"fixed", "replicas":2, "api_total_cpus":4, "api_total_memory_mib":1024, "postgres_cpus":2, "rate":2500, "duration_seconds":20},
|
||||
{"name":"fixed-r2500-n4", "phase":"fixed", "replicas":4, "api_total_cpus":4, "api_total_memory_mib":1024, "postgres_cpus":2, "rate":2500, "duration_seconds":20}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
{
|
||||
"seed_messages": 100000,
|
||||
"warmup_seconds": 10,
|
||||
"warmup_rate": "target",
|
||||
"settle_seconds": 3,
|
||||
"max_inflight": 1024,
|
||||
"runs": [
|
||||
{
|
||||
"name": "pool-1-repeat1",
|
||||
"phase": "pool_causal",
|
||||
"replicas": 2,
|
||||
"api_total_cpus": 4,
|
||||
"api_total_memory_mib": 1024,
|
||||
"pool_max_conns": 1,
|
||||
"rate": 3000,
|
||||
"duration_seconds": 30
|
||||
},
|
||||
{
|
||||
"name": "pool-8-repeat2",
|
||||
"phase": "pool_causal",
|
||||
"replicas": 2,
|
||||
"api_total_cpus": 4,
|
||||
"api_total_memory_mib": 1024,
|
||||
"pool_max_conns": 8,
|
||||
"rate": 3000,
|
||||
"duration_seconds": 30
|
||||
},
|
||||
{
|
||||
"name": "pool-16-repeat3",
|
||||
"phase": "pool_causal",
|
||||
"replicas": 2,
|
||||
"api_total_cpus": 4,
|
||||
"api_total_memory_mib": 1024,
|
||||
"pool_max_conns": 16,
|
||||
"rate": 3000,
|
||||
"duration_seconds": 30
|
||||
},
|
||||
{
|
||||
"name": "pool-16-repeat4",
|
||||
"phase": "pool_causal",
|
||||
"replicas": 2,
|
||||
"api_total_cpus": 4,
|
||||
"api_total_memory_mib": 1024,
|
||||
"pool_max_conns": 16,
|
||||
"rate": 3000,
|
||||
"duration_seconds": 30
|
||||
},
|
||||
{
|
||||
"name": "pool-8-repeat5",
|
||||
"phase": "pool_causal",
|
||||
"replicas": 2,
|
||||
"api_total_cpus": 4,
|
||||
"api_total_memory_mib": 1024,
|
||||
"pool_max_conns": 8,
|
||||
"rate": 3000,
|
||||
"duration_seconds": 30
|
||||
},
|
||||
{
|
||||
"name": "pool-8-repeat6",
|
||||
"phase": "pool_causal",
|
||||
"replicas": 2,
|
||||
"api_total_cpus": 4,
|
||||
"api_total_memory_mib": 1024,
|
||||
"pool_max_conns": 8,
|
||||
"rate": 3000,
|
||||
"duration_seconds": 30
|
||||
},
|
||||
{
|
||||
"name": "pool-16-repeat7",
|
||||
"phase": "pool_causal",
|
||||
"replicas": 2,
|
||||
"api_total_cpus": 4,
|
||||
"api_total_memory_mib": 1024,
|
||||
"pool_max_conns": 16,
|
||||
"rate": 3000,
|
||||
"duration_seconds": 30
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"seed_messages": 100000,
|
||||
"warmup_seconds": 10,
|
||||
"warmup_rate": "target",
|
||||
"settle_seconds": 3,
|
||||
"max_inflight": 1024,
|
||||
"runs": [
|
||||
{"name":"pool8-r3000", "phase":"pool_screen", "replicas":2, "api_total_cpus":4, "api_total_memory_mib":1024, "pool_max_conns":8, "rate":3000, "duration_seconds":30},
|
||||
{"name":"pool4-r3000", "phase":"pool_screen", "replicas":2, "api_total_cpus":4, "api_total_memory_mib":1024, "pool_max_conns":4, "rate":3000, "duration_seconds":30},
|
||||
{"name":"pool16-r3000", "phase":"pool_screen", "replicas":2, "api_total_cpus":4, "api_total_memory_mib":1024, "pool_max_conns":16, "rate":3000, "duration_seconds":30}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
{
|
||||
"seed_messages": 100000,
|
||||
"warmup_seconds": 10,
|
||||
"warmup_rate": "target",
|
||||
"settle_seconds": 3,
|
||||
"max_inflight": 1024,
|
||||
"runs": [
|
||||
{
|
||||
"name": "wal-sync-True-1",
|
||||
"phase": "wal_ablation",
|
||||
"replicas": 2,
|
||||
"api_total_cpus": 4,
|
||||
"api_total_memory_mib": 1024,
|
||||
"pool_max_conns": 8,
|
||||
"diagnostic_async_commit": false,
|
||||
"rate": 3000,
|
||||
"duration_seconds": 30
|
||||
},
|
||||
{
|
||||
"name": "wal-sync-False-2",
|
||||
"phase": "wal_ablation",
|
||||
"replicas": 2,
|
||||
"api_total_cpus": 4,
|
||||
"api_total_memory_mib": 1024,
|
||||
"pool_max_conns": 8,
|
||||
"diagnostic_async_commit": true,
|
||||
"rate": 3000,
|
||||
"duration_seconds": 30
|
||||
},
|
||||
{
|
||||
"name": "wal-sync-True-3",
|
||||
"phase": "wal_ablation",
|
||||
"replicas": 2,
|
||||
"api_total_cpus": 4,
|
||||
"api_total_memory_mib": 1024,
|
||||
"pool_max_conns": 8,
|
||||
"diagnostic_async_commit": false,
|
||||
"rate": 3000,
|
||||
"duration_seconds": 30
|
||||
}
|
||||
],
|
||||
"public_smoke_after": true
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
matplotlib==3.11.2
|
||||
@@ -0,0 +1,396 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Repeatable, disposable Compose experiment for lab 3 scaling research."""
|
||||
|
||||
import argparse
|
||||
import csv
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import platform
|
||||
import re
|
||||
import socket
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import threading
|
||||
import time
|
||||
from datetime import datetime, timezone
|
||||
from urllib.parse import parse_qsl, urlencode, urlsplit, urlunsplit
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[3]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
from client import Client # noqa: E402
|
||||
|
||||
|
||||
def utc_now():
|
||||
return datetime.now(timezone.utc).isoformat(timespec="milliseconds")
|
||||
|
||||
|
||||
def command(argv, *, timeout=180, allow_failure=False, log=None):
|
||||
result = subprocess.run(argv, cwd=ROOT, capture_output=True, text=True, timeout=timeout)
|
||||
if log is not None:
|
||||
log.write_text(result.stdout + result.stderr)
|
||||
if result.returncode and not allow_failure:
|
||||
detail = (result.stderr or result.stdout)[-1200:]
|
||||
raise RuntimeError("command failed (%s): %s" % (result.returncode, detail))
|
||||
return result.stdout
|
||||
|
||||
|
||||
def free_port():
|
||||
with socket.socket() as listener:
|
||||
listener.bind(("127.0.0.1", 0))
|
||||
return listener.getsockname()[1]
|
||||
|
||||
|
||||
def write_override(path, *, lb_port, replicas, total_cpus, total_memory_mib, postgres_cpus,
|
||||
database_url_file=None):
|
||||
if replicas not in (1, 2, 4) or total_cpus <= 0 or total_memory_mib < 256:
|
||||
raise ValueError("invalid replica count or API budget")
|
||||
if total_memory_mib % replicas:
|
||||
raise ValueError("API memory budget must divide evenly between replicas")
|
||||
per_cpu = total_cpus / replicas
|
||||
per_memory = total_memory_mib // replicas
|
||||
source = (
|
||||
"services:\n"
|
||||
" api:\n"
|
||||
" scale: %d\n"
|
||||
" cpus: \"%.3f\"\n"
|
||||
" mem_limit: %dm\n"
|
||||
" environment:\n"
|
||||
" PG_POOL_DIAGNOSTICS: \"1\"\n"
|
||||
" secrets: !override\n"
|
||||
" - source: database_url_api\n"
|
||||
" target: database_url\n"
|
||||
" lb:\n"
|
||||
" ports: !override\n"
|
||||
" - \"127.0.0.1:%d:8080\"\n"
|
||||
" postgres:\n"
|
||||
" cpus: \"%.3f\"\n"
|
||||
" ports: !reset []\n"
|
||||
" command: [\"postgres\", \"-c\", \"shared_preload_libraries=pg_stat_statements\", \"-c\", \"track_io_timing=on\", \"-c\", \"track_wal_io_timing=on\"]\n"
|
||||
% (replicas, per_cpu, per_memory, lb_port, postgres_cpus)
|
||||
)
|
||||
if database_url_file:
|
||||
source += "secrets:\n database_url_api:\n file: %s\n" % json.dumps(str(database_url_file))
|
||||
path.write_text(source)
|
||||
|
||||
|
||||
def write_database_url(path, pool_max_conns):
|
||||
original = (ROOT / "secrets" / "database_url").read_text().strip()
|
||||
if pool_max_conns is None:
|
||||
path.write_text(original + "\n")
|
||||
else:
|
||||
if not isinstance(pool_max_conns, int) or pool_max_conns <= 0:
|
||||
raise ValueError("pool_max_conns must be positive")
|
||||
parsed = urlsplit(original)
|
||||
query = dict(parse_qsl(parsed.query, keep_blank_values=True))
|
||||
query["pool_max_conns"] = str(pool_max_conns)
|
||||
path.write_text(urlunsplit(parsed._replace(query=urlencode(query))) + "\n")
|
||||
os.chmod(path, 0o600)
|
||||
|
||||
|
||||
def psql(compose, sql, *, timeout=60):
|
||||
output = command(compose + ["exec", "-T", "postgres", "psql", "-U", "messenger", "-d", "messenger", "-v", "ON_ERROR_STOP=1", "-Atc", sql], timeout=timeout)
|
||||
return output.strip()
|
||||
|
||||
|
||||
def message_count(compose):
|
||||
return int(psql(compose, "SELECT count(*) FROM messages"))
|
||||
|
||||
|
||||
def reset_dataset(compose, chat_id, user_id, seed_count):
|
||||
chat_id, user_id = str(UUID(chat_id)), str(UUID(user_id))
|
||||
psql(compose, "TRUNCATE message_idempotency, messages")
|
||||
if seed_count:
|
||||
sql = ("INSERT INTO messages (chat_id, sender_id, text, created_at) "
|
||||
"SELECT '%s'::uuid, '%s'::uuid, 'seed-' || g, now() - interval '1 day' "
|
||||
"FROM generate_series(1, %d) AS g" % (chat_id, user_id, seed_count))
|
||||
psql(compose, sql, timeout=180)
|
||||
psql(compose, "ANALYZE messages; ANALYZE message_idempotency")
|
||||
actual = message_count(compose)
|
||||
if actual != seed_count:
|
||||
raise RuntimeError("dataset reset produced %d messages, expected %d" % (actual, seed_count))
|
||||
|
||||
|
||||
def api_ids(compose):
|
||||
return command(compose + ["ps", "-q", "api"]).splitlines()
|
||||
|
||||
|
||||
def api_limits(compose):
|
||||
identifiers = api_ids(compose)
|
||||
output = command(["docker", "inspect", "--format",
|
||||
"{{.Id}} {{.HostConfig.NanoCpus}} {{.HostConfig.Memory}}"] + identifiers,
|
||||
timeout=15)
|
||||
return [dict(zip(("container_id", "nano_cpus", "memory_bytes"), line.split()))
|
||||
for line in output.splitlines()]
|
||||
|
||||
|
||||
def wait_instances(base_url, expected, seconds=60):
|
||||
client = Client(base_url, timeout=3)
|
||||
found = set()
|
||||
deadline = time.monotonic() + seconds
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
response = client.call("GET", "/health/ready", schema="Health")
|
||||
found.add(response["headers"].get("X-Instance-Id"))
|
||||
if len(found) == expected:
|
||||
return sorted(found)
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(.15)
|
||||
raise RuntimeError("LB observed %d of %d API instances" % (len(found), expected))
|
||||
|
||||
|
||||
def sample_loop(stop, compose, path):
|
||||
ids = []
|
||||
for service in ("api", "lb", "postgres", "redis"):
|
||||
ids += command(compose + ["ps", "-q", service], timeout=10).splitlines()
|
||||
lb = command(compose + ["ps", "-q", "lb"], timeout=10).strip()
|
||||
with path.open("w") as output:
|
||||
while not stop.is_set():
|
||||
sample = {"at_utc": utc_now()}
|
||||
try:
|
||||
raw = command(["docker", "stats", "--no-stream", "--format", "{{json .}}"] + ids, timeout=15)
|
||||
sample["docker_stats"] = [json.loads(line) for line in raw.splitlines() if line.strip()]
|
||||
sample["docker_at_utc"] = utc_now()
|
||||
except Exception as exc:
|
||||
sample["docker_error"] = type(exc).__name__
|
||||
try:
|
||||
raw = psql(compose, "SELECT json_build_object('connections', count(*), 'active', count(*) FILTER (WHERE state='active'), 'lock_wait', count(*) FILTER (WHERE wait_event_type='Lock'), 'io_wait', count(*) FILTER (WHERE wait_event_type='IO')) FROM pg_stat_activity WHERE datname=current_database()", timeout=10)
|
||||
sample["postgres_activity"] = json.loads(raw)
|
||||
sample["postgres_at_utc"] = utc_now()
|
||||
except Exception as exc:
|
||||
sample["postgres_error"] = type(exc).__name__
|
||||
try:
|
||||
raw = command(["docker", "exec", lb, "sh", "-c", "printf 'show stat\\n' | socat - TCP4:127.0.0.1:9999"], timeout=10)
|
||||
rows = list(csv.DictReader(io.StringIO(raw.lstrip("# "))))
|
||||
sample["haproxy"] = [
|
||||
{key: row.get(key) for key in ("pxname", "svname", "status", "scur", "qcur", "stot", "ereq", "econ", "eresp", "wretr")}
|
||||
for row in rows if row.get("pxname") == "api_replicas"
|
||||
]
|
||||
sample["haproxy_at_utc"] = utc_now()
|
||||
except Exception as exc:
|
||||
sample["haproxy_error"] = type(exc).__name__
|
||||
output.write(json.dumps(sample, ensure_ascii=False) + "\n")
|
||||
output.flush()
|
||||
stop.wait(.5)
|
||||
|
||||
|
||||
def diagnostic_snapshot(compose):
|
||||
snapshot = {"at_utc": utc_now(), "cgroups": {}}
|
||||
snapshot["durability"] = json.loads(psql(compose, "SELECT json_build_object('fsync',current_setting('fsync'),'synchronous_commit',current_setting('synchronous_commit'),'commit_delay',current_setting('commit_delay'),'commit_siblings',current_setting('commit_siblings'))"))
|
||||
for service in ("api", "postgres", "lb", "redis"):
|
||||
for identifier in command(compose + ["ps", "-q", service]).splitlines():
|
||||
raw = command(["docker", "exec", identifier, "cat", "/sys/fs/cgroup/cpu.stat"], timeout=10)
|
||||
snapshot["cgroups"][identifier] = {"service": service,
|
||||
**{line.split()[0]: int(line.split()[1]) for line in raw.splitlines()}}
|
||||
snapshot["wal_io"] = json.loads(psql(compose, "SELECT coalesce(json_agg(row_to_json(i)), '[]'::json) FROM pg_stat_io i WHERE object='wal'"))
|
||||
snapshot["wal"] = json.loads(psql(compose, "SELECT row_to_json(w) FROM pg_stat_wal w"))
|
||||
return snapshot
|
||||
|
||||
|
||||
def collect_pool_stats(compose, since):
|
||||
snapshots = {}
|
||||
for identifier in api_ids(compose):
|
||||
result = subprocess.run(["docker", "logs", "--since", since, identifier],
|
||||
cwd=ROOT, capture_output=True, text=True, timeout=30)
|
||||
snapshots[identifier] = [
|
||||
{"line": line, "counters": {key: int(value) for key, value in
|
||||
re.findall(r'(max_conns|acquired|idle|acquire_count|empty_count|empty_wait_ns|canceled_count)=(\d+)', line)}}
|
||||
for line in (result.stdout + result.stderr).splitlines() if 'pg_pool_stats' in line
|
||||
]
|
||||
return snapshots
|
||||
|
||||
|
||||
def pg_stat_statements(compose):
|
||||
sql = ("SELECT coalesce(json_agg(row_to_json(q)), '[]'::json) FROM "
|
||||
"(SELECT queryid, calls, round(total_exec_time::numeric,3) AS total_exec_ms, "
|
||||
"round(mean_exec_time::numeric,3) AS mean_exec_ms, rows, shared_blks_hit, "
|
||||
"shared_blks_read, temp_blks_written, left(query,160) AS query "
|
||||
"FROM pg_stat_statements WHERE dbid=(SELECT oid FROM pg_database WHERE datname=current_database()) "
|
||||
"ORDER BY total_exec_time DESC LIMIT 15) AS q")
|
||||
return json.loads(psql(compose, sql))
|
||||
|
||||
|
||||
def run_load(binary, base_url, auth_file, rate, duration, max_inflight, output_path):
|
||||
raw = command([str(binary), "-base-url", base_url, "-auth-file", str(auth_file),
|
||||
"-rate", str(rate), "-duration", str(duration) + "s",
|
||||
"-max-inflight", str(max_inflight), "-timeout", "5s"], timeout=duration + 40)
|
||||
result = json.loads(raw)
|
||||
output_path.write_text(json.dumps(result, indent=2, ensure_ascii=False) + "\n")
|
||||
return result
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--plan", type=Path, required=True)
|
||||
parser.add_argument("--output", type=Path, required=True)
|
||||
args = parser.parse_args()
|
||||
plan = json.loads(args.plan.read_text())
|
||||
runs = plan["runs"]
|
||||
if not runs or not all(run["replicas"] in (1, 2, 4) for run in runs):
|
||||
raise ValueError("plan must have runs with 1, 2, or 4 replicas")
|
||||
output_dir = args.output.resolve()
|
||||
if output_dir.exists() and any(output_dir.iterdir()):
|
||||
raise FileExistsError("output directory must be empty")
|
||||
output_dir.mkdir(parents=True, exist_ok=True)
|
||||
(output_dir / "plan.json").write_text(json.dumps(plan, indent=2, ensure_ascii=False) + "\n")
|
||||
project = "lab3-grade5-" + uuid4().hex[:10]
|
||||
lb_port = free_port()
|
||||
base_url = "http://127.0.0.1:%d" % lb_port
|
||||
summary = {"project": project, "base_url": base_url, "started_at_utc": utc_now(),
|
||||
"host": {"platform": platform.platform(), "machine": platform.machine()},
|
||||
"runs": [], "cleanup": "not_started"}
|
||||
(output_dir / "summary.json").write_text(json.dumps(summary, indent=2, ensure_ascii=False) + "\n")
|
||||
with tempfile.TemporaryDirectory(prefix="lab3-grade5-") as temporary:
|
||||
temporary = Path(temporary)
|
||||
override = temporary / "override.yaml"
|
||||
auth_file = temporary / "auth.json"
|
||||
database_url_file = temporary / "database_url"
|
||||
binary = temporary / "grade5-load"
|
||||
first = runs[0]
|
||||
write_database_url(database_url_file, first.get("pool_max_conns"))
|
||||
write_override(override, lb_port=lb_port, replicas=first["replicas"],
|
||||
total_cpus=first["api_total_cpus"], total_memory_mib=first["api_total_memory_mib"],
|
||||
postgres_cpus=first.get("postgres_cpus", 2), database_url_file=database_url_file)
|
||||
compose = ["docker", "compose", "-p", project, "--env-file", ".env",
|
||||
"-f", "compose.yaml", "-f", str(override)]
|
||||
try:
|
||||
command(["go", "build", "-o", str(binary), "student-tests/lab3/grade5/load.go"], timeout=180,
|
||||
log=output_dir / "go-build.log")
|
||||
command(compose + ["config", "--quiet"], timeout=30)
|
||||
print("Building and starting disposable project", project, flush=True)
|
||||
command(compose + ["up", "-d", "--build"], timeout=900, log=output_dir / "compose-up.log")
|
||||
wait_instances(base_url, first["replicas"])
|
||||
psql(compose, "CREATE EXTENSION IF NOT EXISTS pg_stat_statements")
|
||||
client = Client(base_url)
|
||||
alice, _, _, chat = client.bootstrap()
|
||||
auth_file.write_text(json.dumps({"token": alice["token"], "chat_id": chat["id"]}))
|
||||
os.chmod(auth_file, 0o600)
|
||||
summary["chat_id"] = chat["id"]
|
||||
summary["seed_messages"] = plan["seed_messages"]
|
||||
summary["docker_server"] = command(["docker", "version", "--format", "{{.Server.Version}}"], timeout=15).strip()
|
||||
summary["compose_version"] = command(["docker", "compose", "version", "--short"], timeout=15).strip()
|
||||
summary["docker_resources"] = command(["docker", "info", "--format", "{{.NCPU}} CPUs, {{.MemTotal}} bytes RAM"], timeout=15).strip()
|
||||
previous_postgres_cpus = first.get("postgres_cpus", 2)
|
||||
for index, run in enumerate(runs, 1):
|
||||
name = run["name"]
|
||||
if not name.replace("-", "").replace("_", "").isalnum():
|
||||
raise ValueError("unsafe run name")
|
||||
run_dir = output_dir / ("%02d-%s" % (index, name))
|
||||
run_dir.mkdir()
|
||||
write_database_url(database_url_file, run.get("pool_max_conns"))
|
||||
write_override(override, lb_port=lb_port, replicas=run["replicas"],
|
||||
total_cpus=run["api_total_cpus"], total_memory_mib=run["api_total_memory_mib"],
|
||||
postgres_cpus=run.get("postgres_cpus", 2), database_url_file=database_url_file)
|
||||
command(compose + ["config", "--quiet"], timeout=30)
|
||||
print("Run %d/%d: %s" % (index, len(runs), name), flush=True)
|
||||
delay = run.get("commit_delay_us", 0)
|
||||
if not isinstance(delay, int) or not 0 <= delay <= 100000:
|
||||
raise ValueError("invalid commit_delay_us")
|
||||
psql(compose, "ALTER SYSTEM SET commit_delay='%d'" % delay)
|
||||
async_diagnostic = run.get("diagnostic_async_commit", False)
|
||||
if async_diagnostic and run.get("phase") != "wal_ablation":
|
||||
raise ValueError("asynchronous commit is allowed only in the disposable WAL diagnostic")
|
||||
psql(compose, "ALTER SYSTEM SET synchronous_commit='%s'" % ("off" if async_diagnostic else "on"))
|
||||
psql(compose, "SELECT pg_reload_conf()")
|
||||
if run.get("postgres_cpus", 2) != previous_postgres_cpus:
|
||||
command(compose + ["up", "-d", "--no-deps", "--no-build", "--force-recreate", "postgres"],
|
||||
timeout=120, log=run_dir / "compose-postgres.log")
|
||||
deadline = time.monotonic() + 60
|
||||
while True:
|
||||
try:
|
||||
if psql(compose, "SELECT 1", timeout=5) == "1":
|
||||
break
|
||||
except Exception:
|
||||
pass
|
||||
if time.monotonic() > deadline:
|
||||
raise RuntimeError("PostgreSQL did not become ready after budget change")
|
||||
time.sleep(1)
|
||||
previous_postgres_cpus = run.get("postgres_cpus", 2)
|
||||
command(compose + ["up", "-d", "--no-deps", "--no-build", "--force-recreate", "--scale", "api=%d" % run["replicas"], "api"],
|
||||
timeout=180, log=run_dir / "compose-scale.log")
|
||||
instances = wait_instances(base_url, run["replicas"])
|
||||
pg_id = command(compose + ["ps", "-q", "postgres"]).strip()
|
||||
pg_limit = json.loads(command(["docker", "inspect", "--format",
|
||||
'{"id":"{{.Id}}","service":"postgres","nano_cpus":{{.HostConfig.NanoCpus}},"memory":{{.HostConfig.Memory}}}', pg_id]))
|
||||
pg_cpu = run.get("postgres_cpus", 2)
|
||||
pg_filename = "limits-pg05.json" if pg_cpu == .5 else "limits-pg2.json" if pg_cpu == 2 else "limits-pg-%s.json" % pg_cpu
|
||||
(output_dir / pg_filename).write_text(json.dumps([pg_limit], indent=2) + "\n")
|
||||
warmup = plan.get("warmup_seconds", 3)
|
||||
reset_dataset(compose, chat["id"], alice["id"], plan["seed_messages"])
|
||||
if warmup:
|
||||
warmup_rate = plan.get("warmup_rate", min(200, run["rate"]))
|
||||
if warmup_rate == "target":
|
||||
warmup_rate = run["rate"]
|
||||
run_load(binary, base_url, auth_file, warmup_rate, warmup,
|
||||
plan.get("max_inflight", 1024),
|
||||
run_dir / "warmup.json")
|
||||
reset_dataset(compose, chat["id"], alice["id"], plan["seed_messages"])
|
||||
if plan.get("settle_seconds", 0):
|
||||
psql(compose, "CHECKPOINT")
|
||||
time.sleep(plan["settle_seconds"])
|
||||
psql(compose, "SELECT pg_stat_statements_reset()")
|
||||
before = message_count(compose)
|
||||
(run_dir / "diagnostics-before.json").write_text(json.dumps(diagnostic_snapshot(compose), indent=2) + "\n")
|
||||
stop = threading.Event()
|
||||
sampler = threading.Thread(target=sample_loop, args=(stop, compose, run_dir / "samples.jsonl"))
|
||||
sampler.start()
|
||||
try:
|
||||
load = run_load(binary, base_url, auth_file, run["rate"], run["duration_seconds"],
|
||||
run.get("max_inflight", plan.get("max_inflight", 1024)),
|
||||
run_dir / "load.json")
|
||||
finally:
|
||||
stop.set()
|
||||
sampler.join(timeout=30)
|
||||
after = message_count(compose)
|
||||
(run_dir / "pool-stats.json").write_text(json.dumps(collect_pool_stats(compose, load["started_at_utc"]), indent=2) + "\n")
|
||||
(run_dir / "diagnostics-after.json").write_text(json.dumps(diagnostic_snapshot(compose), indent=2) + "\n")
|
||||
sql_stats = pg_stat_statements(compose)
|
||||
(run_dir / "postgres-statements.json").write_text(json.dumps(sql_stats, indent=2, ensure_ascii=False) + "\n")
|
||||
item = {"name": name, "phase": run.get("phase", "unspecified"),
|
||||
"replicas": run["replicas"], "api_total_cpus": run["api_total_cpus"],
|
||||
"api_total_memory_mib": run["api_total_memory_mib"],
|
||||
"postgres_cpus": run.get("postgres_cpus", 2), "rate": run["rate"],
|
||||
"pool_max_conns_per_replica": run.get("pool_max_conns", "pgx_default"),
|
||||
"commit_delay_us": delay,
|
||||
"diagnostic_async_commit": async_diagnostic,
|
||||
"duration_seconds": run["duration_seconds"], "instances": instances,
|
||||
"api_limits": api_limits(compose),
|
||||
"messages_before": before, "messages_after": after,
|
||||
"messages_added": after-before, "load": load}
|
||||
summary["runs"].append(item)
|
||||
(output_dir / "summary.json").write_text(json.dumps(summary, indent=2, ensure_ascii=False) + "\n")
|
||||
print(" success=%d/%d, rps=%.1f, p99=%.1f ms" %
|
||||
(load["successful_requests"], load["scheduled_requests"],
|
||||
load["successful_rps_window"], load["success_latency_ms"]["p99"]), flush=True)
|
||||
if plan.get("public_smoke_after"):
|
||||
command(["make", "test", "BASE_URL=" + base_url], timeout=90,
|
||||
log=output_dir / "public-smoke.log")
|
||||
summary["public_smoke"] = "PASS"
|
||||
except Exception as exc:
|
||||
summary["error"] = str(exc)
|
||||
raise
|
||||
finally:
|
||||
print("Cleaning disposable project", project, flush=True)
|
||||
try:
|
||||
command(compose + ["down", "-v", "--remove-orphans"], timeout=180,
|
||||
log=output_dir / "cleanup.log")
|
||||
remaining_containers = command(["docker", "ps", "-aq", "--filter",
|
||||
"label=com.docker.compose.project=" + project], timeout=15).splitlines()
|
||||
remaining_volumes = command(["docker", "volume", "ls", "-q", "--filter",
|
||||
"label=com.docker.compose.project=" + project], timeout=15).splitlines()
|
||||
after = {"project": project, "containers": remaining_containers,
|
||||
"volumes": remaining_volumes, "at_utc": utc_now()}
|
||||
(output_dir / "environment-after.json").write_text(json.dumps(after, indent=2) + "\n")
|
||||
summary["cleanup"] = "PASS" if not remaining_containers and not remaining_volumes else "FAIL: resources remain"
|
||||
except Exception as exc:
|
||||
summary["cleanup"] = "FAIL: " + str(exc)
|
||||
summary["finished_at_utc"] = utc_now()
|
||||
(output_dir / "summary.json").write_text(json.dumps(summary, indent=2, ensure_ascii=False) + "\n")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,56 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Check accounting and effective settings in completed research artifacts."""
|
||||
import argparse
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def verify(directory):
|
||||
summary = json.loads((directory/'summary.json').read_text())
|
||||
assert summary['cleanup'] == 'PASS', 'cleanup did not pass'
|
||||
environment = json.loads((directory/'environment-after.json').read_text())
|
||||
assert not environment['containers'] and not environment['volumes'], 'test resources remain'
|
||||
if any(run.get('phase')=='db_cpu_causal' for run in summary['runs']):
|
||||
for filename, expected_cpu in (('limits-pg05.json',500000000),('limits-pg2.json',2000000000)):
|
||||
limits=json.loads((directory/filename).read_text())
|
||||
postgres=[item for item in limits if item['service']=='postgres']
|
||||
assert len(postgres)==1, 'PostgreSQL limit evidence missing'
|
||||
assert postgres[0]['nano_cpus']==expected_cpu and postgres[0]['memory']==512*1048576, 'PostgreSQL quota mismatch'
|
||||
checked = []
|
||||
for index, run in enumerate(summary['runs'],1):
|
||||
folder = directory/('%02d-%s' % (index,run['name']))
|
||||
load = run['load']
|
||||
assert load['successful_requests'] + sum(load['failure_counts'].values()) == load['scheduled_requests'], 'request accounting mismatch'
|
||||
assert run['messages_added'] >= load['successful_requests'], 'acknowledged data missing'
|
||||
assert run['messages_before'] == summary['seed_messages'], 'dataset differs'
|
||||
assert len(run.get('api_limits',[]))==run['replicas'], 'API limit evidence missing'
|
||||
for limits in run['api_limits']:
|
||||
assert int(limits['memory_bytes']) == run['api_total_memory_mib']*1048576/run['replicas'], 'API memory mismatch'
|
||||
assert int(limits['nano_cpus']) == run['api_total_cpus']*1e9/run['replicas'], 'API CPU mismatch'
|
||||
for boundary in ('before','after'):
|
||||
snapshot=json.loads((folder/('diagnostics-'+boundary+'.json')).read_text())
|
||||
settings=snapshot['durability']
|
||||
assert settings['fsync']=='on', 'fsync was disabled'
|
||||
expected='off' if run.get('diagnostic_async_commit') else 'on'
|
||||
assert settings['synchronous_commit']==expected, 'unexpected synchronous_commit'
|
||||
assert int(settings['commit_delay'])==run.get('commit_delay_us',0), 'commit_delay mismatch'
|
||||
if run.get('phase')=='db_cpu_causal':
|
||||
pools=json.loads((folder/'pool-stats.json').read_text())
|
||||
assert len(pools)==run['replicas'] and all(len(points)>1 for points in pools.values()), 'pool telemetry missing'
|
||||
assert all(point['counters']['max_conns']==run['pool_max_conns_per_replica']
|
||||
for points in pools.values() for point in points), 'effective pool limit mismatch'
|
||||
checked.append(dict(name=run['name'],requests=load['scheduled_requests'],
|
||||
unconfirmed_rows=run['messages_added']-load['successful_requests']))
|
||||
return dict(directory=str(directory),status='PASS',runs=checked)
|
||||
|
||||
|
||||
if __name__=='__main__':
|
||||
parser=argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('directories',nargs='+',type=Path)
|
||||
parser.add_argument('--output',type=Path)
|
||||
args=parser.parse_args()
|
||||
result=[verify(path) for path in args.directories]
|
||||
text=json.dumps(result,indent=2)+'\n'
|
||||
if args.output:
|
||||
args.output.write_text(text)
|
||||
print(text)
|
||||
Reference in New Issue
Block a user