Skeleton contracts / contracts (pull_request) Canceled after 0s
Сообщения должны переживать рестарт, а доступ идти через Bearer, а не X-User-Id. Трек 2 сравнивает план keyset-запроса и сверяет pg_restore.
510 lines
15 KiB
Go
510 lines
15 KiB
Go
// Команда эксперимента трека 2: план запроса и восстановление.
|
|
//
|
|
// Режимы:
|
|
//
|
|
// prepare — 100 000 сообщений в чатах неравного размера, база должна называться track2;
|
|
// explain — слабый индекс (только chat_id) против рабочего (chat_id, created_at, id),
|
|
// плюс стоимость вставки;
|
|
// verify — сверка track2 и базы, восстановленной из pg_dump.
|
|
//
|
|
// В продовой схеме остаётся только составной индекс. Слабый создаётся на время замера и удаляется.
|
|
package main
|
|
|
|
import (
|
|
"context"
|
|
"crypto/sha256"
|
|
"encoding/hex"
|
|
"encoding/json"
|
|
"flag"
|
|
"fmt"
|
|
"os"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/google/uuid"
|
|
"github.com/jackc/pgx/v5"
|
|
"github.com/jackc/pgx/v5/pgxpool"
|
|
)
|
|
|
|
func main() {
|
|
mode := flag.String("mode", "", "prepare|explain|verify")
|
|
dsn := flag.String("database-url", "", "postgres URL базы track2")
|
|
restore := flag.String("restore-url", "", "postgres URL восстановленной базы")
|
|
outDir := flag.String("out", "evidence/track2", "каталог JSON")
|
|
flag.Parse()
|
|
if *mode == "" || *dsn == "" {
|
|
fmt.Fprintln(os.Stderr, "нужны -mode и -database-url")
|
|
os.Exit(2)
|
|
}
|
|
if !strings.Contains(*dsn, "track2") {
|
|
fmt.Fprintln(os.Stderr, "отказ: database-url должен указывать на базу track2, чтобы не затереть стенд smoke")
|
|
os.Exit(2)
|
|
}
|
|
ctx := context.Background()
|
|
switch *mode {
|
|
case "prepare":
|
|
if err := prepare(ctx, *dsn); err != nil {
|
|
fail(err)
|
|
}
|
|
case "explain":
|
|
if err := explain(ctx, *dsn, *outDir); err != nil {
|
|
fail(err)
|
|
}
|
|
case "verify":
|
|
if *restore == "" || !strings.Contains(*restore, "track2_restore") {
|
|
fmt.Fprintln(os.Stderr, "нужен -restore-url на базу track2_restore")
|
|
os.Exit(2)
|
|
}
|
|
if err := verify(ctx, *dsn, *restore, *outDir); err != nil {
|
|
fail(err)
|
|
}
|
|
default:
|
|
fmt.Fprintln(os.Stderr, "неизвестный mode")
|
|
os.Exit(2)
|
|
}
|
|
}
|
|
|
|
func prepare(ctx context.Context, dsn string) error {
|
|
pool, err := open(ctx, dsn)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer pool.Close()
|
|
// Та же схема, что у API, но без statement_timeout: загрузка 100k не должна обрываться.
|
|
if err := applySchema(ctx, pool); err != nil {
|
|
return err
|
|
}
|
|
if _, err := pool.Exec(ctx, `TRUNCATE messages, chat_members, chats, users`); err != nil {
|
|
return err
|
|
}
|
|
userID := uuid.New()
|
|
now := time.Now().UTC().Truncate(time.Millisecond)
|
|
if _, err := pool.Exec(ctx, `
|
|
INSERT INTO users (id, username, display_name, password_hash, created_at)
|
|
VALUES ($1, 'track2_user', 'Трек 2', 'not-a-login-hash', $2)`, userID, now); err != nil {
|
|
return err
|
|
}
|
|
// Сумма размеров = 100 000. Один чат сильно больше остальных — так план на «горячей» истории
|
|
// не маскируется равномерным распределением.
|
|
sizes := []int{1, 50, 500, 5000, 20000, 74449}
|
|
sum := 0
|
|
for _, n := range sizes {
|
|
sum += n
|
|
}
|
|
if sum != 100000 {
|
|
return fmt.Errorf("sizes sum %d", sum)
|
|
}
|
|
type chat struct {
|
|
id uuid.UUID
|
|
size int
|
|
}
|
|
chats := make([]chat, len(sizes))
|
|
for i, n := range sizes {
|
|
chats[i] = chat{id: uuid.New(), size: n}
|
|
if _, err := pool.Exec(ctx, `INSERT INTO chats (id, title, created_at) VALUES ($1, $2, $3)`,
|
|
chats[i].id, fmt.Sprintf("chat-%d", n), now.Add(time.Duration(i)*time.Millisecond)); err != nil {
|
|
return err
|
|
}
|
|
if _, err := pool.Exec(ctx, `INSERT INTO chat_members (chat_id, user_id) VALUES ($1, $2)`, chats[i].id, userID); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
rows := make([][]any, 0, 1000)
|
|
flush := func() error {
|
|
if len(rows) == 0 {
|
|
return nil
|
|
}
|
|
_, err := pool.CopyFrom(ctx, pgx.Identifier{"messages"},
|
|
[]string{"id", "chat_id", "sender_id", "text", "created_at"}, pgx.CopyFromRows(rows))
|
|
rows = rows[:0]
|
|
return err
|
|
}
|
|
for _, c := range chats {
|
|
for i := 0; i < c.size; i++ {
|
|
rows = append(rows, []any{
|
|
uuid.New(),
|
|
c.id,
|
|
userID,
|
|
fmt.Sprintf("m-%d", i),
|
|
now.Add(time.Duration(i) * time.Millisecond),
|
|
})
|
|
if len(rows) == 1000 {
|
|
if err := flush(); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
}
|
|
}
|
|
if err := flush(); err != nil {
|
|
return err
|
|
}
|
|
var n int
|
|
if err := pool.QueryRow(ctx, `SELECT count(*) FROM messages`).Scan(&n); err != nil {
|
|
return err
|
|
}
|
|
fmt.Printf("prepared messages=%d chats=%d\n", n, len(chats))
|
|
if n != 100000 {
|
|
return fmt.Errorf("expected 100000 messages, got %d", n)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func explain(ctx context.Context, dsn, outDir string) error {
|
|
if err := os.MkdirAll(outDir, 0o755); err != nil {
|
|
return err
|
|
}
|
|
pool, err := open(ctx, dsn)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer pool.Close()
|
|
var chatID uuid.UUID
|
|
var size int
|
|
if err := pool.QueryRow(ctx, `
|
|
SELECT chat_id, count(*) FROM messages GROUP BY chat_id ORDER BY count(*) DESC LIMIT 1`,
|
|
).Scan(&chatID, &size); err != nil {
|
|
return err
|
|
}
|
|
var curAt time.Time
|
|
var curID uuid.UUID
|
|
// Середина большой истории: keyset не должен для каждой страницы читать все предыдущие строки.
|
|
if err := pool.QueryRow(ctx, `
|
|
SELECT created_at, id FROM messages
|
|
WHERE chat_id = $1
|
|
ORDER BY created_at, id
|
|
OFFSET 30000 LIMIT 1`, chatID).Scan(&curAt, &curID); err != nil {
|
|
return err
|
|
}
|
|
|
|
weak, err := withIndex(ctx, pool, false, func() (map[string]any, error) {
|
|
return explainQuery(ctx, pool, chatID, curAt, curID)
|
|
})
|
|
if err != nil {
|
|
return fmt.Errorf("weak plan: %w", err)
|
|
}
|
|
strong, err := withIndex(ctx, pool, true, func() (map[string]any, error) {
|
|
return explainQuery(ctx, pool, chatID, curAt, curID)
|
|
})
|
|
if err != nil {
|
|
return fmt.Errorf("strong plan: %w", err)
|
|
}
|
|
writeCost, err := measureInsert(ctx, pool, chatID)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
summary := map[string]any{
|
|
"largest_chat_messages": size,
|
|
"cursor_offset": 30000,
|
|
"weak_index": "messages_chat_only_idx (chat_id)",
|
|
"strong_index": "messages_history_idx (chat_id, created_at, id)",
|
|
"weak_plan": summarizePlan(weak),
|
|
"strong_plan": summarizePlan(strong),
|
|
"write_cost": writeCost,
|
|
}
|
|
if err := writeJSON(outDir+"/explain-weak.json", weak); err != nil {
|
|
return err
|
|
}
|
|
if err := writeJSON(outDir+"/explain-strong.json", strong); err != nil {
|
|
return err
|
|
}
|
|
if err := writeJSON(outDir+"/summary.json", summary); err != nil {
|
|
return err
|
|
}
|
|
fmt.Printf("weak: %s\nstrong: %s\nwrite: %+v\n", summarizePlan(weak), summarizePlan(strong), writeCost)
|
|
return nil
|
|
}
|
|
|
|
func verify(ctx context.Context, srcDSN, dstDSN, outDir string) error {
|
|
src, err := open(ctx, srcDSN)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer src.Close()
|
|
dst, err := open(ctx, dstDSN)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer dst.Close()
|
|
srcCount, srcSum, err := fingerprint(ctx, src)
|
|
if err != nil {
|
|
return fmt.Errorf("source: %w", err)
|
|
}
|
|
dstCount, dstSum, err := fingerprint(ctx, dst)
|
|
if err != nil {
|
|
return fmt.Errorf("restore: %w", err)
|
|
}
|
|
var srcSample, dstSample string
|
|
q := `
|
|
SELECT id::text FROM messages m
|
|
JOIN (SELECT chat_id FROM messages GROUP BY chat_id ORDER BY count(*) DESC LIMIT 1) big
|
|
ON big.chat_id = m.chat_id
|
|
ORDER BY m.created_at, m.id
|
|
LIMIT 1`
|
|
if err := src.QueryRow(ctx, q).Scan(&srcSample); err != nil {
|
|
return err
|
|
}
|
|
if err := dst.QueryRow(ctx, q).Scan(&dstSample); err != nil {
|
|
return err
|
|
}
|
|
report := map[string]any{
|
|
"source_messages": srcCount.messages,
|
|
"restore_messages": dstCount.messages,
|
|
"source_chats": srcCount.chats,
|
|
"restore_chats": dstCount.chats,
|
|
"source_sha256": srcSum,
|
|
"restore_sha256": dstSum,
|
|
"source_first_id": srcSample,
|
|
"restore_first_id": dstSample,
|
|
"counts_match": srcCount == dstCount,
|
|
"checksum_match": srcSum == dstSum,
|
|
"first_id_match": srcSample == dstSample,
|
|
}
|
|
if err := os.MkdirAll(outDir, 0o755); err != nil {
|
|
return err
|
|
}
|
|
if err := writeJSON(outDir+"/restore.json", report); err != nil {
|
|
return err
|
|
}
|
|
fmt.Printf("restore match counts=%v checksum=%v first=%v messages=%d\n",
|
|
srcCount == dstCount, srcSum == dstSum, srcSample == dstSample, srcCount.messages)
|
|
if srcCount != dstCount || srcSum != dstSum || srcSample != dstSample {
|
|
return fmt.Errorf("restore mismatch")
|
|
}
|
|
return nil
|
|
}
|
|
|
|
type counts struct {
|
|
messages int
|
|
chats int
|
|
}
|
|
|
|
func fingerprint(ctx context.Context, pool *pgxpool.Pool) (counts, string, error) {
|
|
var c counts
|
|
if err := pool.QueryRow(ctx, `SELECT count(*) FROM messages`).Scan(&c.messages); err != nil {
|
|
return c, "", err
|
|
}
|
|
if err := pool.QueryRow(ctx, `SELECT count(*) FROM chats`).Scan(&c.chats); err != nil {
|
|
return c, "", err
|
|
}
|
|
rows, err := pool.Query(ctx, `SELECT id::text, created_at::text, text FROM messages ORDER BY created_at, id`)
|
|
if err != nil {
|
|
return c, "", err
|
|
}
|
|
defer rows.Close()
|
|
h := sha256.New()
|
|
for rows.Next() {
|
|
var id, ts, text string
|
|
if err := rows.Scan(&id, &ts, &text); err != nil {
|
|
return c, "", err
|
|
}
|
|
_, _ = fmt.Fprintf(h, "%s|%s|%s\n", id, ts, text)
|
|
}
|
|
if err := rows.Err(); err != nil {
|
|
return c, "", err
|
|
}
|
|
return c, hex.EncodeToString(h.Sum(nil)), nil
|
|
}
|
|
|
|
func withIndex(ctx context.Context, pool *pgxpool.Pool, strong bool, fn func() (map[string]any, error)) (map[string]any, error) {
|
|
if _, err := pool.Exec(ctx, `DROP INDEX IF EXISTS messages_history_idx`); err != nil {
|
|
return nil, err
|
|
}
|
|
if _, err := pool.Exec(ctx, `DROP INDEX IF EXISTS messages_chat_only_idx`); err != nil {
|
|
return nil, err
|
|
}
|
|
var create string
|
|
if strong {
|
|
create = `CREATE INDEX messages_history_idx ON messages (chat_id, created_at, id)`
|
|
} else {
|
|
create = `CREATE INDEX messages_chat_only_idx ON messages (chat_id)`
|
|
}
|
|
if _, err := pool.Exec(ctx, create); err != nil {
|
|
return nil, err
|
|
}
|
|
plan, err := fn()
|
|
// Продовый индекс возвращаем даже если замер упал.
|
|
_, _ = pool.Exec(ctx, `DROP INDEX IF EXISTS messages_chat_only_idx`)
|
|
_, recErr := pool.Exec(ctx, `CREATE INDEX IF NOT EXISTS messages_history_idx ON messages (chat_id, created_at, id)`)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if recErr != nil {
|
|
return nil, recErr
|
|
}
|
|
return plan, nil
|
|
}
|
|
|
|
func explainQuery(ctx context.Context, pool *pgxpool.Pool, chatID uuid.UUID, curAt time.Time, curID uuid.UUID) (map[string]any, error) {
|
|
var raw []byte
|
|
err := pool.QueryRow(ctx, `
|
|
EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON)
|
|
SELECT id, created_at FROM messages
|
|
WHERE chat_id = $1 AND (created_at, id) > ($2, $3)
|
|
ORDER BY created_at, id
|
|
LIMIT 50`, chatID, curAt, curID).Scan(&raw)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
var parsed any
|
|
if err := json.Unmarshal(raw, &parsed); err != nil {
|
|
return nil, err
|
|
}
|
|
return map[string]any{"explain": parsed}, nil
|
|
}
|
|
|
|
func measureInsert(ctx context.Context, pool *pgxpool.Pool, chatID uuid.UUID) (map[string]any, error) {
|
|
var userID uuid.UUID
|
|
if err := pool.QueryRow(ctx, `SELECT user_id FROM chat_members WHERE chat_id = $1`, chatID).Scan(&userID); err != nil {
|
|
return nil, err
|
|
}
|
|
if _, err := pool.Exec(ctx, `DROP TABLE IF EXISTS messages_write_probe`); err != nil {
|
|
return nil, err
|
|
}
|
|
if _, err := pool.Exec(ctx, `
|
|
CREATE TABLE messages_write_probe (
|
|
id uuid PRIMARY KEY,
|
|
chat_id uuid NOT NULL,
|
|
sender_id uuid NOT NULL,
|
|
text text NOT NULL,
|
|
created_at timestamptz NOT NULL
|
|
)`); err != nil {
|
|
return nil, err
|
|
}
|
|
defer pool.Exec(ctx, `DROP TABLE IF EXISTS messages_write_probe`)
|
|
one, err := timedInsert(ctx, pool, chatID, userID, `CREATE INDEX probe_chat ON messages_write_probe (chat_id)`)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if _, err := pool.Exec(ctx, `TRUNCATE messages_write_probe`); err != nil {
|
|
return nil, err
|
|
}
|
|
if _, err := pool.Exec(ctx, `DROP INDEX IF EXISTS probe_chat`); err != nil {
|
|
return nil, err
|
|
}
|
|
both, err := timedInsert(ctx, pool, chatID, userID, `
|
|
CREATE INDEX probe_chat ON messages_write_probe (chat_id);
|
|
CREATE INDEX probe_hist ON messages_write_probe (chat_id, created_at, id)`)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return map[string]any{
|
|
"rows": 5000,
|
|
"only_chat_id_index_ms": one,
|
|
"chat_id_plus_history_ms": both,
|
|
}, nil
|
|
}
|
|
|
|
func timedInsert(ctx context.Context, pool *pgxpool.Pool, chatID, userID uuid.UUID, indexSQL string) (int64, error) {
|
|
for _, stmt := range strings.Split(indexSQL, ";") {
|
|
stmt = strings.TrimSpace(stmt)
|
|
if stmt == "" {
|
|
continue
|
|
}
|
|
if _, err := pool.Exec(ctx, stmt); err != nil {
|
|
return 0, err
|
|
}
|
|
}
|
|
rows := make([][]any, 5000)
|
|
base := time.Now().UTC()
|
|
for i := range rows {
|
|
rows[i] = []any{uuid.New(), chatID, userID, "w", base.Add(time.Duration(i) * time.Millisecond)}
|
|
}
|
|
start := time.Now()
|
|
_, err := pool.CopyFrom(ctx, pgx.Identifier{"messages_write_probe"},
|
|
[]string{"id", "chat_id", "sender_id", "text", "created_at"}, pgx.CopyFromRows(rows))
|
|
return time.Since(start).Milliseconds(), err
|
|
}
|
|
|
|
func summarizePlan(plan map[string]any) string {
|
|
list, _ := plan["explain"].([]any)
|
|
if len(list) == 0 {
|
|
return "empty"
|
|
}
|
|
root, _ := list[0].(map[string]any)
|
|
p, _ := root["Plan"].(map[string]any)
|
|
node, _ := p["Node Type"].(string)
|
|
return fmt.Sprintf("node=%s execution_ms=%v shared_hit_blocks=%v sort=%v",
|
|
node, root["Execution Time"], p["Shared Hit Blocks"], hasNode(p, "Sort"))
|
|
}
|
|
|
|
func hasNode(plan map[string]any, name string) bool {
|
|
if plan == nil {
|
|
return false
|
|
}
|
|
if plan["Node Type"] == name {
|
|
return true
|
|
}
|
|
children, _ := plan["Plans"].([]any)
|
|
for _, child := range children {
|
|
m, _ := child.(map[string]any)
|
|
if hasNode(m, name) {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
func applySchema(ctx context.Context, pool *pgxpool.Pool) error {
|
|
stmts := []string{
|
|
`CREATE TABLE IF NOT EXISTS users (
|
|
id uuid PRIMARY KEY,
|
|
username text NOT NULL UNIQUE,
|
|
display_name text NOT NULL,
|
|
password_hash text NOT NULL,
|
|
created_at timestamptz NOT NULL)`,
|
|
`CREATE TABLE IF NOT EXISTS chats (
|
|
id uuid PRIMARY KEY,
|
|
title text NOT NULL,
|
|
created_at timestamptz NOT NULL)`,
|
|
`CREATE TABLE IF NOT EXISTS chat_members (
|
|
chat_id uuid NOT NULL REFERENCES chats (id),
|
|
user_id uuid NOT NULL REFERENCES users (id),
|
|
PRIMARY KEY (chat_id, user_id))`,
|
|
`CREATE TABLE IF NOT EXISTS messages (
|
|
id uuid PRIMARY KEY,
|
|
chat_id uuid NOT NULL REFERENCES chats (id),
|
|
sender_id uuid NOT NULL REFERENCES users (id),
|
|
text text NOT NULL,
|
|
created_at timestamptz NOT NULL)`,
|
|
`CREATE INDEX IF NOT EXISTS messages_history_idx ON messages (chat_id, created_at, id)`,
|
|
}
|
|
for _, stmt := range stmts {
|
|
if _, err := pool.Exec(ctx, stmt); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func open(ctx context.Context, dsn string) (*pgxpool.Pool, error) {
|
|
cfg, err := pgxpool.ParseConfig(dsn)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
cfg.MaxConns = 4
|
|
cfg.ConnConfig.ConnectTimeout = 5 * time.Second
|
|
pool, err := pgxpool.NewWithConfig(ctx, cfg)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if err := pool.Ping(ctx); err != nil {
|
|
pool.Close()
|
|
return nil, err
|
|
}
|
|
_, _ = pool.Exec(ctx, `SET statement_timeout = 0`)
|
|
return pool, nil
|
|
}
|
|
|
|
func writeJSON(path string, v any) error {
|
|
b, err := json.MarshalIndent(v, "", " ")
|
|
if err != nil {
|
|
return err
|
|
}
|
|
return os.WriteFile(path, append(b, '\n'), 0o644)
|
|
}
|
|
|
|
func fail(err error) {
|
|
fmt.Fprintln(os.Stderr, err)
|
|
os.Exit(1)
|
|
}
|