From 33bdc70063756811992bc60ccd5cf42b9fc17fea Mon Sep 17 00:00:00 2001 From: jeremyhi Date: Tue, 13 Oct 2026 08:25:41 +0800 Subject: [PATCH] ci: add crash, pinned-prefix and idle cells to the S3 benchmark A groups input holds several cell groups in one dispatch, each with its own configurations, sweep, concurrency, rounds, rows, restart and environment, so experiments that need different settings share one runner. Each row count a load group uses gets its own corpus. - mode crash runs striped writers of acknowledged 1000-row batches, kills the server with SIGKILL at a random point in kill_after, restarts it on the same prefix and data home and checks every cycle: in the durable mode every acknowledged batch is present exactly once and every extra batch was in flight at the kill; in the enqueued mode no batch is present twice or in part and none was never attempted, and the acknowledged batches lost are counted. pin first writes one row into a second table and samples the indexed, deleted and created object counts every 30 s. - idle_seconds keeps a loaded server up without writes between two scrapes. - The summary adds WAL MB/s, objects/s, mean object size and whether batches sealed on size, object store requests per operation for the load, the restart and the idle window, and tables for crash cycles and pinned prefixes. Signed-off-by: jeremyhi --- .github/scripts/oswal-s3-bench-crash.py | 187 ++++++++++++++++++++++ .github/scripts/oswal-s3-bench-run.sh | 111 +++++++++++-- .github/scripts/oswal-s3-bench-summary.py | 147 ++++++++++++++--- .github/scripts/oswal-s3-bench.py | 112 ++++++++++--- .github/workflows/oswal-s3-bench.yml | 9 +- tests/perf/test_oswal_s3_bench_scripts.py | 179 ++++++++++++++++++++- 6 files changed, 674 insertions(+), 71 deletions(-) create mode 100644 .github/scripts/oswal-s3-bench-crash.py diff --git a/.github/scripts/oswal-s3-bench-crash.py b/.github/scripts/oswal-s3-bench-crash.py new file mode 100644 index 00000000000..b1d564a7d47 --- /dev/null +++ b/.github/scripts/oswal-s3-bench-crash.py @@ -0,0 +1,187 @@ +#!/usr/bin/env python3 +# Copyright 2023 Greptime Team +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Writer and oracle of the benchmark's crash cells. + +Every writer owns the stripe `first + index, first + index + writers, ...` of +batch sequence numbers, inserts `rows` rows per batch and stops at the first +statement that is not acknowledged, so a stripe has at most one attempted but +unacknowledged batch: the one in flight at the kill. Every request is logged +with its status and the time it ended, on the same clock as the kill stamps. +""" + +from __future__ import annotations + +import argparse +import collections +import json +import os +import sys +import threading +import time +import urllib.error +import urllib.parse +import urllib.request +from pathlib import Path + + +def insert(url: str, table: str, seq: int, rows: int) -> str: + values = ", ".join(f"({seq}, {seq * rows + i})" for i in range(rows)) + body = urllib.parse.urlencode({"sql": f"INSERT INTO {table} (seq, ts) VALUES {values}"}).encode() + try: + with urllib.request.urlopen(urllib.request.Request(url, data=body), timeout=60) as response: + return str(response.status) + except urllib.error.HTTPError as error: + return str(error.code) + except (OSError, urllib.error.URLError): + # The connection dropped: the request may or may not have been applied. + return "000" + + +def writer(args, index: int) -> None: + directory, seq = Path(args.dir), args.first_seq + index + with open(directory / f"attempted-{index}.log", "a") as attempted, \ + open(directory / f"requests-{index}.log", "a") as requests, \ + open(directory / f"acked-{index}.log", "a") as acked: + while True: + attempted.write(f"{seq}\n") + attempted.flush() + code = insert(args.url, args.table, seq, args.rows) + requests.write(f"{seq} {code} {time.time_ns()}\n") + requests.flush() + if code != "200": + break + acked.write(f"{seq}\n") + acked.flush() + seq += args.writers + (directory / f"exit-{index}.log").write_text(f"{time.time_ns()}\n") + + +def write(args) -> int: + os.makedirs(args.dir, exist_ok=True) + threads = [threading.Thread(target=writer, args=(args, i)) for i in range(args.writers)] + for thread in threads: + thread.start() + for thread in threads: + thread.join() + return 0 + + +def lines(path: Path) -> list: + return [line.split() for line in path.read_text().splitlines() if line.strip()] if path.exists() else [] + + +def check_kill(directory: Path, writers: int, before_ns: int, after_ns: int, window_max_ms: int) -> dict: + """A dropped connection is in flight when it ended at or after the stamp taken before the kill.""" + errors, in_flight, running = [], 0, 0 + if after_ns - before_ns > window_max_ms * 1_000_000: + errors.append(f"kill window {after_ns - before_ns}ns exceeds {window_max_ms}ms") + for index in range(writers): + exit_path = directory / f"exit-{index}.log" + if not exit_path.exists(): + errors.append(f"writer {index} left no exit time") + continue + running += int(exit_path.read_text()) >= before_ns + for seq, code, end_ns in lines(directory / f"requests-{index}.log"): + if code == "200": + continue + if code != "000": + errors.append(f"writer {index}: batch {seq} rejected with HTTP {code}") + elif int(end_ns) < before_ns: + errors.append(f"writer {index}: batch {seq} lost its connection before the kill") + else: + in_flight += 1 + if running == 0: + errors.append("no writer was running at the kill") + return {"kill_window_ns": after_ns - before_ns, "in_flight": in_flight, "writers_at_kill": running, + "kill_errors": errors} + + +def verify(run_dir: Path, found: dict, rows: int, enqueued: bool) -> dict: + """Checks the table, read as batch -> row count, against every cycle's writers so far.""" + acked, stripes = [], collections.OrderedDict() + for cycle_dir in sorted(run_dir.glob("cycle-*"), key=lambda p: int(p.name.split("-")[1])): + for path in sorted(cycle_dir.glob("attempted-*.log")): + stripes[(cycle_dir.name, path.name)] = [int(seq) for (seq,) in lines(path)] + for path in sorted(cycle_dir.glob("acked-*.log")): + acked += [int(seq) for (seq,) in lines(path)] + acked_set = set(acked) + attempted = {seq for stripe in stripes.values() for seq in stripe} + errors = [] + duplicated = sorted(seq for seq, count in found.items() if count > rows) + partial = sorted(seq for seq, count in found.items() if count < rows) + if duplicated: + errors.append(f"batches present more than once: {duplicated[:20]}") + if partial: + errors.append(f"batches present in part: {partial[:20]}") + missing = sorted(acked_set - set(found)) + if missing and not enqueued: + errors.append(f"acknowledged but absent: {missing[:20]}") + unattempted = sorted(set(found) - attempted) + if unattempted: + errors.append(f"present but never attempted: {unattempted[:20]}") + # The unacknowledged tail of each stripe was in flight at a kill. + in_flight = set() + for key, stripe in stripes.items(): + prefix = 0 + while prefix < len(stripe) and stripe[prefix] in acked_set: + prefix += 1 + if any(seq in acked_set for seq in stripe[prefix:]): + errors.append(f"{key}: acknowledged after a failure") + in_flight.update(stripe[prefix:]) + extra = sorted(set(found) - acked_set) + stray = [seq for seq in extra if seq not in in_flight] + if stray and not enqueued: + errors.append(f"present, unacknowledged and not in flight at a kill: {stray[:20]}") + if len(acked) != len(acked_set): + errors.append("a batch was acknowledged twice") + return {"found_batches": len(found), "acked_batches": len(acked_set), "lost_batches": len(missing), + "lost_rows": len(missing) * rows, "extra_batches": len(extra), "verify_errors": errors} + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + commands = parser.add_subparsers(dest="command", required=True) + w = commands.add_parser("write") + w.add_argument("--dir", required=True) + w.add_argument("--url", required=True) + w.add_argument("--table", default="crash") + for name in ("writers", "first-seq", "rows"): + w.add_argument(f"--{name}", type=int, required=True) + c = commands.add_parser("check") + c.add_argument("--run-dir", type=Path, required=True) + c.add_argument("--cycle", type=int, required=True) + c.add_argument("--found", type=Path, required=True, help="GreptimeDB JSON output of SELECT seq, count(*)") + c.add_argument("--mode", choices=("durable", "enqueued"), required=True) + for name in ("writers", "rows", "before-ns", "after-ns", "window-max-ms"): + c.add_argument(f"--{name}", type=int, required=True) + args = parser.parse_args() + if args.command == "write": + return write(args) + rows = json.loads(args.found.read_text())["output"][0]["records"]["rows"] + result = {"cycle": args.cycle} + result |= check_kill(args.run_dir / f"cycle-{args.cycle}", args.writers, args.before_ns, args.after_ns, + args.window_max_ms) + result |= verify(args.run_dir, {int(seq): int(count) for seq, count in rows}, args.rows, + args.mode == "enqueued") + result["cycle_acked_batches"] = sum( + len(lines(p)) for p in (args.run_dir / f"cycle-{args.cycle}").glob("acked-*.log")) + result["passed"] = not result["kill_errors"] and not result["verify_errors"] + print(json.dumps(result)) + return 0 if result["passed"] else 1 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/.github/scripts/oswal-s3-bench-run.sh b/.github/scripts/oswal-s3-bench-run.sh index 356a702a65c..3de0170f7cc 100644 --- a/.github/scripts/oswal-s3-bench-run.sh +++ b/.github/scripts/oswal-s3-bench-run.sh @@ -46,28 +46,36 @@ wal_disk() { findmnt -no SOURCE,FSTYPE -T "$root" | tee "$RESULTS/wal-disk.txt" } +# One corpus per row count the load cells use; crash cells write their own rows. generate() { : "${PLAN:?}" "${RESULTS:?}" "${CORPUS_DIR:?}" "${OWNER:?}" "${RUNTIME_IMAGE:?}" - local args=() arg - while IFS= read -r arg; do args+=("$arg"); done < <(jq -r '.generator_args[]' "$PLAN") - mkdir -p "$CORPUS_DIR" - runtime --name "$OWNER-generator" --mount "type=bind,src=$CORPUS_DIR,dst=/work/corpus" \ - "$RUNTIME_IMAGE" scripts/generate_agent_observations.py "${args[@]}" \ - --output /work/corpus/agent_observations.jsonl \ - --summary-output /work/corpus/summary.json --evidence-output /work/corpus/evidence.json \ - > "$RESULTS/generator.log" 2>&1 - jq -e --argjson rows "$(jq .rows "$PLAN")" '.line_count == $rows' "$CORPUS_DIR/summary.json" >/dev/null + local corpus args arg dir rows + while IFS= read -r corpus; do + args=() dir="$CORPUS_DIR/$(jq -r .dir <<< "$corpus")" rows=$(jq .rows <<< "$corpus") + while IFS= read -r arg; do args+=("$arg"); done < <(jq -r '.generator_args[]' <<< "$corpus") + mkdir -p "$dir" + runtime --name "$OWNER-generator-$rows" --mount "type=bind,src=$dir,dst=/work/corpus" \ + "$RUNTIME_IMAGE" scripts/generate_agent_observations.py "${args[@]}" \ + --output /work/corpus/agent_observations.jsonl \ + --summary-output /work/corpus/summary.json --evidence-output /work/corpus/evidence.json \ + >> "$RESULTS/generator.log" 2>&1 + jq -e --argjson rows "$rows" '.line_count == $rows' "$dir/summary.json" >/dev/null + done < <(jq -c '.corpora[]' "$PLAN") } # Scrape once per server, after the load succeeded or failed, while it still runs: # the loaded server into metrics.prom, a restarted one into metrics-restart.prom. scrape_metrics() { curl --noproxy '*' -fsS --max-time 30 http://127.0.0.1:4000/metrics > "$dir/metrics.all" || { rm -f "$dir/metrics.all"; return 1; } - grep -E '^(# (HELP|TYPE) )?greptime_logstore_object_store_wal_' "$dir/metrics.all" > "$dir/metrics$phase.prom" || true + grep -E '^(# (HELP|TYPE) )?(greptime_logstore_object_store_wal_|opendal_operation_(duration_seconds_count|errors_total))' \ + "$dir/metrics.all" > "$dir/metrics$phase.prom" || true rm -f "$dir/metrics.all" - if [[ -z "$phase" ]]; then metrics_scraped=true; else restart_scraped=true; fi + case "$phase" in "") metrics_scraped=true ;; -restart) restart_scraped=true ;; esac } +sql() { curl --noproxy '*' -fsS --max-time 30 --data-urlencode "sql=$1" 'http://127.0.0.1:4000/v1/sql?db=public'; } +now_ns() { python3 -c 'import time; print(time.time_ns())'; } + now() { date +%s.%N; } elapsed() { awk -v a="$1" -v b="$(now)" 'BEGIN {printf "%.3f", b - a}'; } # CPU seconds the server's cgroup used, and busy and total jiffies of the host. @@ -112,7 +120,69 @@ restart() { sleep 0.2 done restart_query_seconds=$(elapsed "$started") restart_count=$count - [[ "$count" == "$(jq .rows "$PLAN")" ]] || { echo "$id: $count rows after restart" >&2; exit 5; } + [[ "$count" == "$(jq .rows <<< "$spec")" ]] || { echo "$id: $count rows after restart" >&2; exit 5; } +} + +# Pins the WAL with one row in a second table before the writers start, if asked, +# and samples the object counts every 30 s while they run. +sample_objects() { + while sleep 30; do + curl --noproxy '*' -fsS --max-time 10 http://127.0.0.1:4000/metrics 2>/dev/null | awk -v t="$(date +%s)" ' + /^greptime_logstore_object_store_wal_indexed_objects / {i = $2} + /^greptime_logstore_object_store_wal_deleted_objects_total / {d = $2} + /^greptime_logstore_object_store_wal_created_objects_total / {c = $2} + END {print t, i + 0, d + 0, c + 0}' >> "$dir/objects.tsv" + done +} + +# Writers insert striped batches until a SIGKILL at a random point stops the +# server; it restarts on the same prefix and data home and the table is checked +# against what was acknowledged. Nothing is cleaned between cycles. +crash_cycles() { + local writers rows cycles kill_min kill_max cycle cdir wpid spid= delay before after started restart_s query_s next=0 pin_count + writers=$(jq -r .concurrency <<< "$spec") rows=$(jq -r .batch_rows "$PLAN") cycles=$(jq -r .cycles <<< "$spec") + kill_min=$(jq -r '.kill_after[0]' <<< "$spec") kill_max=$(jq -r '.kill_after[1]' <<< "$spec") + if jq -e .pin <<< "$spec" >/dev/null; then + sql "CREATE TABLE pin (v BIGINT, ts TIMESTAMP TIME INDEX)" >/dev/null + sql "INSERT INTO pin VALUES (1, 0)" >/dev/null + fi + sql "CREATE TABLE crash (seq BIGINT, ts TIMESTAMP TIME INDEX) WITH (append_mode = 'true')" >/dev/null + for ((cycle = 1; cycle <= cycles; cycle++)); do + cdir="$dir/cycle-$cycle"; mkdir -p "$cdir" + python3 "$here/oswal-s3-bench-crash.py" write --dir "$cdir" --url 'http://127.0.0.1:4000/v1/sql?db=public' \ + --writers "$writers" --first-seq "$next" --rows "$rows" & + wpid=$! + if jq -e .pin <<< "$spec" >/dev/null; then sample_objects & spid=$!; fi + delay=$(awk -v a="$kill_min" -v b="$kill_max" 'BEGIN {srand(); printf "%.3f", a + rand() * (b - a)}') + sleep "$delay" + phase=-cycle-$cycle; scrape_metrics || true + before=$(now_ns); docker kill --signal KILL "$cid" >/dev/null; after=$(now_ns) + wait "$wpid" + [[ -z "$spid" ]] || { kill "$spid" 2>/dev/null; wait "$spid" 2>/dev/null || true; spid=; } + stop_server kill + phase=-restart-$cycle started=$(now) + start_server + restart_s=$(elapsed "$started") + until sql "SELECT seq, count(*) FROM crash GROUP BY seq" > "$cdir/found.json" 2>/dev/null; do + (($(elapsed "$started" | cut -d. -f1) < 300)) || { echo "$id: crash not readable after restart $cycle" >&2; exit 5; } + sleep 0.2 + done + query_s=$(elapsed "$started") + scrape_metrics || true + pin_count=null + if jq -e .pin <<< "$spec" >/dev/null; then + pin_count=$(sql "SELECT count(*) FROM pin" | jq -er '.output[0].records.rows[0][0]') + fi + local verdict=0 + python3 "$here/oswal-s3-bench-crash.py" check --run-dir "$dir" --cycle "$cycle" --found "$cdir/found.json" \ + --mode "$(jq -r .wal.ACK_MODE <<< "$spec")" --writers "$writers" --rows "$rows" \ + --before-ns "$before" --after-ns "$after" --window-max-ms 2000 > "$cdir/check.json" || verdict=$? + jq -c --arg delay "$delay" --arg restart "$restart_s" --arg query "$query_s" --argjson pin "$pin_count" \ + '. + {kill_after_seconds: ($delay | tonumber), restart_seconds: ($restart | tonumber), + restart_query_seconds: ($query | tonumber), pin_rows: $pin}' "$cdir/check.json" >> "$dir/cycles.jsonl" + ((verdict == 0)) || { echo "$id: cycle $cycle failed its check" >&2; exit 6; } + next=$(cat "$cdir"/attempted-*.log | sort -n | tail -1); next=$((next + 1)) + done } finish() { @@ -157,7 +227,7 @@ cell() { "STORAGE__ROOT=$RUN_PREFIX/$id") [[ -z "${S3_CONTAINER_ENDPOINT:-}" ]] || settings+=("STORAGE__ENDPOINT=$S3_CONTAINER_ENDPOINT") # A restarted server needs the metadata the loaded one kept in its data home. - jq -e '.restart' <<< "$spec" >/dev/null && settings+=(STORAGE__DATA_HOME=/oswal_home) + jq -e '.restart or .mode == "crash"' <<< "$spec" >/dev/null && settings+=(STORAGE__DATA_HOME=/oswal_home) while IFS= read -r setting; do settings+=("$setting"); done \ < <(jq -r '.wal | to_entries[] | "WAL__\(.key)=\(.value)"' <<< "$spec") docker_env=() mounts=() @@ -181,7 +251,7 @@ cell() { else wal_device="s3://$S3_BUCKET/$RUN_PREFIX/$id/wal" fi - if jq -e '.restart' <<< "$spec" >/dev/null; then + if jq -e '.restart or .mode == "crash"' <<< "$spec" >/dev/null; then home_dir="$WAL_ROOT/$id-home"; mkdir -p "$home_dir" mounts+=(--mount "type=bind,src=$home_dir,dst=/oswal_home") fi @@ -189,12 +259,14 @@ cell() { start_server version=$(docker exec "$cid" greptime --version | sed -n 's/^version: //p') [[ -n "$version" ]] + if jq -e '.mode == "crash"' <<< "$spec" >/dev/null; then crash_cycles; return; fi cpu_before=$(server_cpu) host_before=$(host_cpu) started=$(now) # Only the load phase, run exactly as run-agent-observability.sh runs it. runtime --name "$name-load" --network host \ - --mount "type=bind,src=$CORPUS_DIR,dst=/work/corpus,readonly" --mount "type=bind,src=$dir,dst=/results" \ - -e GRPC_ENDPOINT=127.0.0.1:4001 -e "DATA_PROFILE=$(jq -r .data_profile "$PLAN")" -e RESULT_NAME=greptimedb-1 \ + --mount "type=bind,src=$CORPUS_DIR/corpus-$(jq -r .rows <<< "$spec"),dst=/work/corpus,readonly" \ + --mount "type=bind,src=$dir,dst=/results" \ + -e GRPC_ENDPOINT=127.0.0.1:4001 -e "DATA_PROFILE=$(jq -r .data_profile <<< "$spec")" -e RESULT_NAME=greptimedb-1 \ -e "ENDPOINT=http://127.0.0.1:4000/v1/sql?db=public&format=greptimedb_v1" \ -e "TARGET_IMAGE=$GREPTIMEDB_IMAGE" -e "TARGET_VERSION=$version" -e "TARGET_DIGEST=${GREPTIMEDB_IMAGE##*@}" \ -e "TARGET_ID=$name" -e TARGET_HOST=127.0.0.1 -e PREPARE_WORKERS= -e "MAX_IN_FLIGHT=$concurrency" \ @@ -206,8 +278,13 @@ cell() { # Busy share of all host CPUs during the load, the loader included. host_cpu_busy=$(awk -v a="$host_before" -v b="$host_after" \ 'BEGIN {split(a, x, " "); split(b, y, " "); if (y[2] > x[2]) printf "%.4f", (y[1] - x[1]) / (y[2] - x[2])}') - jq -e --argjson rows "$(jq .rows "$PLAN")" '.count_before == 0 and .count_after == $rows' \ + jq -e --argjson rows "$(jq .rows <<< "$spec")" '.count_before == 0 and .count_after == $rows' \ "$dir/greptimedb-1/load-result.json" >/dev/null + # An idle window: what the server sends with no writes, between two scrapes. + if jq -e '.idle_seconds > 0' <<< "$spec" >/dev/null; then + phase=-idle; scrape_metrics || { echo "$id: metrics scrape failed" >&2; exit 4; }; phase= + sleep "$(jq -r .idle_seconds <<< "$spec")" + fi if jq -e '.restart' <<< "$spec" >/dev/null; then restart; fi } diff --git a/.github/scripts/oswal-s3-bench-summary.py b/.github/scripts/oswal-s3-bench-summary.py index 7241425543c..c11b6c86192 100644 --- a/.github/scripts/oswal-s3-bench-summary.py +++ b/.github/scripts/oswal-s3-bench-summary.py @@ -32,10 +32,16 @@ SAMPLE = re.compile(r'([a-zA-Z_:][a-zA-Z0-9_:]*)(?:\{([^}]*)\})?\s+(\S+)') def parse_metrics(text: str) -> dict: - """Map each unlabeled sample to its value and each histogram to its buckets.""" - samples, buckets = {}, {} + """Map each unlabeled sample to its value, each histogram to its buckets, and the + object store requests (data files and WAL together) to their count per operation.""" + samples, buckets, requests = {}, {}, {} for line in text.splitlines(): match = SAMPLE.fullmatch(line.strip()) + if match and match.group(1) == "opendal_operation_duration_seconds_count": + operation = re.search(r'operation="([^"]+)"', match.group(2) or "") + if operation: + requests[operation.group(1)] = requests.get(operation.group(1), 0) + float(match.group(3)) + continue if not match or not match.group(1).startswith(PREFIX): continue name, labels, value = match.group(1)[len(PREFIX):], match.group(2) or "", float(match.group(3)) @@ -44,7 +50,8 @@ def parse_metrics(text: str) -> dict: buckets.setdefault(name[:-len("_bucket")], []).append((float(le.group(1)), value)) else: samples[name] = value - return {"samples": samples, "buckets": {name: sorted(items) for name, items in buckets.items()}} + return {"samples": samples, "buckets": {name: sorted(items) for name, items in buckets.items()}, + "requests": requests} def quantile(q: float, buckets: list) -> float | None: @@ -70,6 +77,27 @@ def read_metrics(path: Path) -> dict: return parse_metrics(path.read_text() if path.exists() else "") +def interval_seconds(wal: dict) -> float: + value = wal.get("FLUSH_INTERVAL", "100ms") + return float(value[:-2]) / 1000 if value.endswith("ms") else float(value.rstrip("s")) + + +def crash_cycles(path: Path) -> list: + """Each cycle's check plus the loaded server's metrics before the kill and the restarted one's after.""" + cycles = [json.loads(line) for line in (path / "cycles.jsonl").read_text().splitlines() + if line.strip()] if (path / "cycles.jsonl").exists() else [] + for cycle in cycles: + before = read_metrics(path / f"metrics-cycle-{cycle['cycle']}.prom")["samples"] + after = read_metrics(path / f"metrics-restart-{cycle['cycle']}.prom") + once = after["samples"].get("recovery_seconds_count") == 1 + cycle |= {"created_before_kill": before.get("created_objects_total"), + "indexed_before_kill": before.get("indexed_objects"), + "recovery_seconds": after["samples"].get("recovery_seconds_sum") if once else None, + "recovered_objects": after["samples"].get("recovered_objects_total", 0 if once else None), + "restart_requests": after["requests"]} + return cycles + + def load_cell(path: Path, spec: dict | None = None) -> dict: """One cell's row; a planned cell that never recorded a result has no values, so no ratio uses its round.""" recorded = path / "cell.json" @@ -80,7 +108,8 @@ def load_cell(path: Path, spec: dict | None = None) -> dict: load_seconds = result.get("load_seconds") wall, cpu = cell.get("load_wall_seconds"), cell.get("server_cpu_seconds") row = { - "id": cell["id"], "round": cell["round"], "concurrency": cell["concurrency"], + "id": cell["id"], "group": cell.get("group", ""), "mode": cell.get("mode", "load"), + "round": cell["round"], "concurrency": cell["concurrency"], "config": cell["config"], "exit_code": cell["exit_code"], "wal_device": cell.get("wal_device"), "missing": cell.get("missing", False), "env": cell.get("env", {}), "sweep_value": cell.get("sweep_value"), "version": cell.get("version"), "load_wall_seconds": wall, @@ -111,31 +140,61 @@ def load_cell(path: Path, spec: dict | None = None) -> dict: row[counter] = metrics["samples"].get(counter, 0 if active else None) created = row["created_objects_total"] row["creates_per_minute"] = created * 60 / load_seconds if created is not None and load_seconds else None + # WAL traffic of the load; more objects than seal ticks, or objects near the + # 8 MiB threshold, mean batches sealed on size rather than on the timer. + written, objects = metrics["samples"].get("object_bytes_sum"), metrics["samples"].get("object_bytes_count") + per_second = created / load_seconds if created and load_seconds else None + mean = written / objects if written and objects else None + row |= {"wal_mb_per_second": written / load_seconds / 1e6 if written and load_seconds else None, + "objects_per_second": per_second, "mean_object_bytes": mean, + "sealed_on_size": None if per_second is None else + per_second > 1.05 / interval_seconds(cell.get("wal", {})) or (mean or 0) >= 0.9 * 8 * 2**20, + "requests": metrics["requests"], "restart_requests": restarted["requests"]} + if cell.get("idle_seconds"): + idle = read_metrics(path / "metrics-idle.prom") + start = idle["samples"].get("created_objects_total", 0) + row["idle"] = {"seconds": cell["idle_seconds"], + "creates": None if created is None else created - start, + "requests": {op: n - idle["requests"].get(op, 0) for op, n in metrics["requests"].items() + if n != idle["requests"].get(op, 0)}} + if row["mode"] == "crash": + row["cycles"] = crash_cycles(path) + if (path / "objects.tsv").exists(): + row["objects_samples"] = [[int(float(v)) for v in line.split()] + for line in (path / "objects.tsv").read_text().splitlines() if line.strip()] return row def ratios(rows: list) -> list: """Each object store WAL cell over each Raft Engine control per swept value and round, and their geometric mean over the rounds, per concurrency.""" - speed = {(r["round"], r["concurrency"], r["config"], r["sweep_value"]): r["rows_per_second"] for r in rows} - series = sorted({(r["config"], r["sweep_value"]) for r in rows if r["config"] not in BASELINES}, - key=lambda s: (s[0], s[1] or 0)) - baselines = [b for b in BASELINES if any(r["config"] == b for r in rows)] + rows = [r for r in rows if r["mode"] == "load"] + speed = {(r["group"], r["round"], r["concurrency"], r["config"], r["sweep_value"]): r["rows_per_second"] + for r in rows} result = [] - for concurrency in sorted({r["concurrency"] for r in rows}): - rounds = sorted({r["round"] for r in rows if r["concurrency"] == concurrency}) - for (config, value), baseline in ((s, b) for s in series for b in baselines): - per_round = [] - for round_number in rounds: - base = speed.get((round_number, concurrency, baseline, None)) - measured = speed.get((round_number, concurrency, config, value)) - per_round.append(measured / base if base and measured else None) - complete = [ratio for ratio in per_round if ratio is not None] - result.append({"concurrency": concurrency, "ratio": f"{config}/{baseline}", "sweep_value": value, - "per_round": per_round, - "geomean": geomean(complete) if len(complete) == len(per_round) else None}) + for group in dict.fromkeys(r["group"] for r in rows): + members = [r for r in rows if r["group"] == group] + series = sorted({(r["config"], r["sweep_value"]) for r in members if r["config"] not in BASELINES}, + key=lambda s: (s[0], s[1] or 0)) + baselines = [b for b in BASELINES if any(r["config"] == b for r in members)] + for concurrency in sorted({r["concurrency"] for r in members}): + rounds = sorted({r["round"] for r in members if r["concurrency"] == concurrency}) + for (config, value), baseline in ((s, b) for s in series for b in baselines): + per_round = [] + for round_number in rounds: + base = speed.get((group, round_number, concurrency, baseline, None)) + measured = speed.get((group, round_number, concurrency, config, value)) + per_round.append(measured / base if base and measured else None) + complete = [ratio for ratio in per_round if ratio is not None] + result.append({"group": group, "concurrency": concurrency, "ratio": f"{config}/{baseline}", + "sweep_value": value, "per_round": per_round, + "geomean": geomean(complete) if len(complete) == len(per_round) else None}) return result +def operations(requests: dict) -> str: + return ", ".join(f"{op} {n:,.0f}" for op, n in sorted(requests.items())) or "—" + + def overrides(env: dict) -> str: return " ".join(f"{k.removeprefix('GREPTIMEDB_OSWAL_')}={v}" for k, v in sorted(env.items())) or "—" @@ -157,9 +216,12 @@ def render(run: dict, rows: list, pairs: list) -> str: "| Server CPUs | Host busy | WAL on |", "| --- | --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: " "| ---: | ---: | --- |"] - for r in rows: - cell = f"{r['id']} (not run)" if r["missing"] else r["id"] if r["exit_code"] == 0 \ + def label(r): + return f"{r['id']} (not run)" if r["missing"] else r["id"] if r["exit_code"] == 0 \ else f"{r['id']} (failed, exit {r['exit_code']})" + loads = [r for r in rows if r["mode"] == "load"] + for r in loads: + cell = label(r) lines.append(" | ".join([ f"| {cell}", overrides(r["env"]), fmt(r["rows_per_second"]), fmt(r["load_seconds"], 1), fmt(r["load_wall_seconds"], 1), pair(r["append_ack_p50"], r["append_ack_p99"], 1, 1000), @@ -169,6 +231,42 @@ def render(run: dict, rows: list, pairs: list) -> str: *(fmt(r[c]) for c in COUNTERS[1:]), fmt(r["server_cpu_cores"], 2), "—" if r["host_cpu_busy"] is None else f"{r['host_cpu_busy']:.0%} of {r['host_cpus'] or '?'}", f"`{r['wal_device'] or '—'}` |"])) + lines += ["", "| Cell | WAL MB/s | Objects/s | Mean object MiB | Sealed on size | Requests during the load " + "| Requests of the restart | Idle s | Idle creates | Idle requests |", + "| --- | ---: | ---: | ---: | --- | --- | --- | ---: | ---: | --- |"] + for r in loads: + idle = r.get("idle") or {} + lines.append(" | ".join([ + f"| {label(r)}", fmt(r["wal_mb_per_second"], 1), fmt(r["objects_per_second"], 1), + fmt(r["mean_object_bytes"], 2, 1 / 2**20), + "—" if r["sealed_on_size"] is None else ("yes" if r["sealed_on_size"] else "no"), + operations(r["requests"]), operations(r["restart_requests"]) if "restart" in r else "—", + fmt(idle.get("seconds")), fmt(idle.get("creates")), operations(idle["requests"]) if idle else "—"]) + " |") + crashes = [r for r in rows if r["mode"] == "crash"] + if crashes: + lines += ["", "| Cell | Cycle | Kill after s | Acked batches | In flight | Found | Acked so far | Lost batches " + "| Lost rows | Extra | Indexed at kill | Restart to /health s | Recovery s | Recovered objects " + "| Pin rows | Verdict |", + "| --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: " + "| ---: | --- |"] + for r in crashes: + for c in r["cycles"] or [{}]: + lines.append(" | ".join([ + f"| {label(r)}", fmt(c.get("cycle")), fmt(c.get("kill_after_seconds"), 1), + fmt(c.get("cycle_acked_batches")), fmt(c.get("in_flight")), fmt(c.get("found_batches")), + fmt(c.get("acked_batches")), fmt(c.get("lost_batches")), fmt(c.get("lost_rows")), + fmt(c.get("extra_batches")), fmt(c.get("indexed_before_kill")), fmt(c.get("restart_seconds"), 2), + fmt(c.get("recovery_seconds"), 3), fmt(c.get("recovered_objects")), fmt(c.get("pin_rows")), + "—" if not c else "pass" if c.get("passed") else "FAIL: " + "; ".join( + c.get("kill_errors", []) + c.get("verify_errors", []))]) + " |") + pinned = [r for r in crashes if r.get("objects_samples")] + if pinned: + lines += ["", "| Cell | Indexed objects every 30 s | Deleted objects at the end | Created objects at the end |", + "| --- | --- | ---: | ---: |"] + for r in pinned: + samples = r["objects_samples"] + lines.append(f"| {r['id']} | {', '.join(str(s[1]) for s in samples)} | {samples[-1][2]:,} " + f"| {samples[-1][3]:,} |") restarts = [r for r in rows if "restart" in r] if restarts: lines += ["", "| Cell | Overrides | Objects created | Restart to /health s | Restart to count s " @@ -180,9 +278,10 @@ def render(run: dict, rows: list, pairs: list) -> str: f"| {r['id']}", overrides(r["env"]), fmt(r["created_objects_total"]), fmt(x["wall_seconds"], 2), fmt(x["query_seconds"], 2), fmt(x["recovery_seconds"], 3), fmt(x["recovered_objects"]), f"{fmt(x['rows'])} |"])) - lines += ["", "| Concurrency | Ratio | Swept value | Per round | Geometric mean |", "| ---: | --- | ---: | --- | ---: |"] + lines += ["", "| Group | Concurrency | Ratio | Swept value | Per round | Geometric mean |", + "| --- | ---: | --- | ---: | --- | ---: |"] for p in pairs: - lines.append(f"| {p['concurrency']} | {p['ratio']} | {fmt(p['sweep_value'])} " + lines.append(f"| {p['group'] or '—'} | {p['concurrency']} | {p['ratio']} | {fmt(p['sweep_value'])} " f"| {', '.join(fmt(v, 3) for v in p['per_round'])} | {fmt(p['geomean'], 3)} |") return "\n".join(lines) + "\n" diff --git a/.github/scripts/oswal-s3-bench.py b/.github/scripts/oswal-s3-bench.py index 0ddf42f4225..d9c2da38065 100644 --- a/.github/scripts/oswal-s3-bench.py +++ b/.github/scripts/oswal-s3-bench.py @@ -47,6 +47,7 @@ DEPTHS = {"GREPTIMEDB_OSWAL_MAX_IN_FLIGHT_CREATES": 4, "GREPTIMEDB_OSWAL_MAX_SEA "GREPTIMEDB_OSWAL_RECOVERY_CONCURRENCY": 8} # Restart cells seal ten times as often as the default so recovery has thousands of objects. RESTART_FLUSH_INTERVAL = "10ms" +GROUP_NAME = re.compile(r"[a-z][a-z0-9]{0,11}") RESERVED_ENV = ("GREPTIMEDB_STANDALONE__STORAGE__", "GREPTIMEDB_STANDALONE__WAL__") ENV_NAME = re.compile(r"[A-Za-z_][A-Za-z0-9_]*") # Docker's reference grammar: path components separated by ".", "_", "__" or runs of "-". @@ -90,7 +91,7 @@ def build_manifest(plan: dict, greptimedb_inspect: list, runtime_image: str, return {"smoke": plan["smoke"], "rows": plan["rows"], "rounds": plan["rounds"], "concurrency": plan["concurrency"], "batch_rows": plan["batch_rows"], "configs": plan["configs"], "extra_env": plan["extra_env"], "sweep": plan["sweep"], - "restart": plan["restart"], + "restart": plan["restart"], "groups": plan["groups"], "greptimedb_image": image, "runtime_image": runtime_image, "instance_type": instance_type, "region": region, "prefix": prefix} @@ -140,26 +141,49 @@ def check_depths(env: dict) -> None: raise ValueError(f"MAX_SEALED_BATCHES {sealed} is below MAX_IN_FLIGHT_CREATES {creates} plus 2") -def build_plan(concurrency: str, rows: str, batch_rows: str, rounds: str, smoke: bool, - configs: str = "R,D,E", extra_env: str = "", sweep: str = "", restart: bool = False) -> dict: +def group_cells(group: dict, smoke: bool) -> list: + """The cells of one group, in run order; a group without a name is the top-level inputs.""" + name, mode = group.get("name", ""), group.get("mode", "load") + if mode not in ("load", "crash"): + raise ValueError(f"group {name!r}: mode must be load or crash, got {mode!r}") + concurrency = str(group["concurrency"]) levels = [positive("concurrency", level.strip(), 256) for level in concurrency.split(",")] if len(set(levels)) != len(levels): raise ValueError(f"concurrency repeats a level: {concurrency!r}") - chosen = [config.strip() for config in configs.split(",")] - if not chosen or len(set(chosen)) != len(chosen) or not set(chosen) <= set(WAL_CONFIGS): - raise ValueError(f"configs must be distinct names among {', '.join(WAL_CONFIGS)}, got {configs!r}") - env = parse_extra_env(extra_env) - swept, points = parse_sweep(sweep) + chosen = [config.strip() for config in str(group["configs"]).split(",")] + allowed = set(WAL_CONFIGS) - (set(BASELINES) if mode == "crash" else set()) + if not chosen or len(set(chosen)) != len(chosen) or not set(chosen) <= allowed: + raise ValueError(f"group {name!r}: configs must be distinct names among {', '.join(sorted(allowed))}, " + f"got {group['configs']!r}") + extra = group.get("extra_env", "") + env = parse_extra_env(json.dumps(extra) if isinstance(extra, dict) else str(extra)) + swept, points = parse_sweep(str(group.get("sweep", ""))) if swept in env: raise ValueError(f"{swept} is both swept and set in extra_env") - row_count = SMOKE_ROWS if smoke else positive("rows", rows, 100_000_000) - round_count = 1 if smoke else positive("rounds", rounds, 10) - profile = DATA_PROFILES.get(row_count) + restart = group.get("restart", False) is True + rows = SMOKE_ROWS if smoke else positive("rows", str(group["rows"]), 100_000_000) + rounds = 1 if smoke else positive("rounds", str(group["rounds"]), 10) + idle = int(group.get("idle_seconds", 0)) + common = {"group": name, "mode": mode, "restart": restart, "idle_seconds": idle} + if mode == "load": + if not 0 <= idle <= 600: + raise ValueError(f"group {name!r}: idle_seconds must be in 0..600") + common |= {"rows": rows, "data_profile": DATA_PROFILES.get(rows, "custom")} + else: + cycles = int(group.get("cycles", 5)) + kill_after = [int(v) for v in group.get("kill_after", [3, 10])] + if not 1 <= cycles <= 20 or len(kill_after) != 2 or not 1 <= kill_after[0] <= kill_after[1] <= 3600: + raise ValueError(f"group {name!r}: cycles must be in 1..20 and kill_after a [min, max] in 1..3600") + if restart or idle: + raise ValueError(f"group {name!r}: a crash group restarts after every kill and has no idle window") + if smoke: + cycles, kill_after = min(cycles, 2), [min(v, 60) for v in kill_after] + common |= {"cycles": cycles, "kill_after": kill_after, "pin": group.get("pin", False) is True} # Raft Engine ignores the depths, so each baseline runs once per round and level. series = [(config, point) for config in WAL_CONFIGS if config in chosen for point in (points if config not in BASELINES else [None])] cells = [] - for round_number in range(1, round_count + 1): + for round_number in range(1, rounds + 1): # Reverse the order every other round so no configuration or value always runs first. for level in levels: for config, point in series if round_number % 2 else reversed(series): @@ -167,18 +191,58 @@ def build_plan(concurrency: str, rows: str, batch_rows: str, rounds: str, smoke: if config not in BASELINES: check_depths(cell_env) wal = WAL_CONFIGS[config] | ({"FLUSH_INTERVAL": RESTART_FLUSH_INTERVAL} if restart and config not in BASELINES else {}) - cells.append({ - "id": f"{round_number}-{level}-{config}" + (f"-{point}" if point is not None else ""), + cells.append(common | { + "id": (f"{name}-" if name else "") + f"{round_number}-{level}-{config}" + + (f"-{point}" if point is not None else ""), "round": round_number, "concurrency": level, "config": config, "wal": wal, - "env": cell_env, "sweep_value": point, "restart": restart, + "env": cell_env, "sweep_value": point, }) + return cells + + +def parse_groups(text: str, defaults: dict) -> list: + """A JSON list of groups; every key a group leaves out takes the top-level input's value.""" + if not text.strip(): + return [defaults] + groups = json.loads(text) + if not isinstance(groups, list) or not groups or not all(isinstance(g, dict) for g in groups): + raise ValueError("groups must be a non-empty JSON list of objects") + known = set(defaults) | {"name", "mode", "idle_seconds", "cycles", "kill_after", "pin"} + names = [g.get("name") for g in groups] + for group, name in zip(groups, names): + if not isinstance(name, str) or not GROUP_NAME.fullmatch(name): + raise ValueError(f"every group needs a name of up to 12 lowercase letters and digits, got {name!r}") + if set(group) - known: + raise ValueError(f"group {name!r} has unknown keys {sorted(set(group) - known)}") + if len(set(names)) != len(names): + raise ValueError(f"group names repeat: {names}") + return [defaults | group for group in groups] + + +def build_plan(concurrency: str, rows: str, batch_rows: str, rounds: str, smoke: bool, + configs: str = "R,D,E", extra_env: str = "", sweep: str = "", restart: bool = False, + groups: str = "") -> dict: + defaults = {"concurrency": concurrency, "rows": rows, "rounds": rounds, "configs": configs, + "extra_env": extra_env, "sweep": sweep, "restart": restart} + resolved = parse_groups(groups, defaults) + swept, points = parse_sweep(sweep) + cells = [cell for group in resolved for cell in group_cells(group, smoke)] + if len({cell["id"] for cell in cells}) != len(cells): + raise ValueError("two cells share an id") + corpora = [] + for count in dict.fromkeys(cell["rows"] for cell in cells if cell["mode"] == "load"): + profile = DATA_PROFILES.get(count) + corpora.append({"rows": count, "dir": f"corpus-{count}", "data_profile": profile or "custom", + "generator_args": ["--data-profile", profile] if profile else ["--line-count", str(count)]}) + first = cells[0] return { - "smoke": smoke, "rows": row_count, "rounds": round_count, - "batch_rows": positive("batch_rows", batch_rows, 100_000), "concurrency": levels, - "configs": chosen, "extra_env": env, "sweep": {"name": swept, "values": points} if swept else None, - "restart": restart, "data_profile": profile or "custom", - "generator_args": ["--data-profile", profile] if profile else ["--line-count", str(row_count)], - "cells": cells, + "smoke": smoke, "rows": first.get("rows"), "rounds": max(cell["round"] for cell in cells), + "batch_rows": positive("batch_rows", batch_rows, 100_000), + "concurrency": sorted({cell["concurrency"] for cell in cells}), + "configs": list(dict.fromkeys(cell["config"] for cell in cells)), + "extra_env": parse_extra_env(extra_env), "groups": [g.get("name", "") for g in resolved], + "sweep": {"name": swept, "values": points} if swept else None, + "restart": restart, "corpora": corpora, "cells": cells, } @@ -255,7 +319,7 @@ def main() -> int: plan.add_argument("--smoke", choices=("true", "false"), required=True) plan.add_argument("--restart", choices=("true", "false"), default="false") plan.add_argument("--configs", default="R,D,E") - for name in ("extra-env", "sweep"): + for name in ("extra-env", "sweep", "groups"): plan.add_argument(f"--{name}", default="") for name in ("timeout-minutes", "ttl-hours", "output"): plan.add_argument(f"--{name}") @@ -278,11 +342,11 @@ def main() -> int: if args.timeout_minutes or args.ttl_hours: validate_budgets(args.timeout_minutes or "", args.ttl_hours or "") result = build_plan(args.concurrency, args.rows, args.batch_rows, args.rounds, args.smoke == "true", - args.configs, args.extra_env, args.sweep, args.restart == "true") + args.configs, args.extra_env, args.sweep, args.restart == "true", args.groups) if args.output: with open(args.output, "w") as output: json.dump(result, output, indent=2) - print(f"{len(result['cells'])} cells, {result['rows']} rows, profile {result['data_profile']}") + print(f"{len(result['cells'])} cells; corpora {[c['rows'] for c in result['corpora']]}") elif args.command == "image": reference = resolve_image(args.image, args.tag) append_github("GITHUB_OUTPUT", "greptimedb_ref", reference) diff --git a/.github/workflows/oswal-s3-bench.yml b/.github/workflows/oswal-s3-bench.yml index e2dc61f15bf..6c7d37b4b3d 100644 --- a/.github/workflows/oswal-s3-bench.yml +++ b/.github/workflows/oswal-s3-bench.yml @@ -30,6 +30,10 @@ on: description: 'After each load, SIGKILL the server, restart it on the same prefix and data home, and time recovery; object store cells flush every 10ms' type: boolean default: false + groups: + description: 'JSON list of cell groups, each overriding configs, sweep, extra_env, concurrency, rounds, rows, restart, plus idle_seconds, or mode crash with cycles, kill_after [min, max] and pin; empty = one group from the inputs above' + type: string + default: '' instance_type: description: EC2 instance type in the bucket region; the d of c6id gives a local NVMe instance store for the Raft Engine WAL type: string @@ -72,6 +76,7 @@ env: EXTRA_ENV: ${{ inputs.extra_env }} SWEEP: ${{ inputs.sweep }} RESTART: ${{ inputs.restart }} + GROUPS: ${{ inputs.groups }} REQUESTED_INSTANCE_TYPE: ${{ inputs.instance_type }} CONCURRENCY: ${{ inputs.concurrency }} ROWS: ${{ inputs.rows }} @@ -102,7 +107,7 @@ jobs: run: | python3 greptimedb/.github/scripts/oswal-s3-bench.py plan --smoke "$SMOKE" \ --concurrency "$CONCURRENCY" --rows "$ROWS" --batch-rows "$BATCH_ROWS" --rounds "$ROUNDS" \ - --configs "$CONFIGS" --extra-env "$EXTRA_ENV" --sweep "$SWEEP" --restart "$RESTART" \ + --configs "$CONFIGS" --extra-env "$EXTRA_ENV" --sweep "$SWEEP" --restart "$RESTART" --groups "$GROUPS" \ --timeout-minutes "$BENCHMARK_TIMEOUT_MINUTES" --ttl-hours "$JANITOR_TTL_HOURS" python3 greptimedb/.github/scripts/oswal-s3-bench.py image --tag "$GREPTIMEDB_TAG" --image "$GREPTIMEDB_IMAGE_INPUT" - name: Resolve CI runner @@ -188,7 +193,7 @@ jobs: bash greptimedb/.github/scripts/oswal-s3-bench-run.sh pull python3 greptimedb/.github/scripts/oswal-s3-bench.py plan --smoke "$SMOKE" --output "$PLAN" \ --concurrency "$CONCURRENCY" --rows "$ROWS" --batch-rows "$BATCH_ROWS" --rounds "$ROUNDS" \ - --configs "$CONFIGS" --extra-env "$EXTRA_ENV" --sweep "$SWEEP" --restart "$RESTART" + --configs "$CONFIGS" --extra-env "$EXTRA_ENV" --sweep "$SWEEP" --restart "$RESTART" --groups "$GROUPS" python3 greptimedb/.github/scripts/oswal-s3-bench.py manifest --results "$RESULTS" \ --runtime-image "$RUNTIME_IMAGE" --instance-type "$INSTANCE_TYPE" --region "$S3_REGION" --prefix "$RUN_PREFIX" - name: Probe the bucket diff --git a/tests/perf/test_oswal_s3_bench_scripts.py b/tests/perf/test_oswal_s3_bench_scripts.py index affc01d4cd1..698d26ea4cc 100644 --- a/tests/perf/test_oswal_s3_bench_scripts.py +++ b/tests/perf/test_oswal_s3_bench_scripts.py @@ -20,9 +20,11 @@ import json import os import subprocess import sys +import re import tempfile import unittest from pathlib import Path +from types import SimpleNamespace SCRIPTS = Path(__file__).parents[2] / ".github/scripts" @@ -35,6 +37,7 @@ def load(name, filename): bench = load("oswal_s3_bench", "oswal-s3-bench.py") +crash = load("oswal_s3_bench_crash", "oswal-s3-bench-crash.py") summary = load("oswal_s3_bench_summary", "oswal-s3-bench-summary.py") ACK_BUCKETS = """# TYPE greptime_logstore_object_store_wal_append_ack_seconds histogram @@ -57,8 +60,9 @@ class PlanTest(unittest.TestCase): self.assertEqual([c["id"] for c in plan["cells"]], [ "1-1-R", "1-1-D", "1-1-E", "1-8-R", "1-8-D", "1-8-E", "2-1-E", "2-1-D", "2-1-R", "2-8-E", "2-8-D", "2-8-R"]) - self.assertEqual(plan["generator_args"], ["--data-profile", "D"]) - self.assertEqual((plan["rows"], plan["batch_rows"], plan["data_profile"]), (2_000_000, 1000, "D")) + self.assertEqual(plan["corpora"], [{"rows": 2_000_000, "dir": "corpus-2000000", "data_profile": "D", + "generator_args": ["--data-profile", "D"]}]) + self.assertEqual((plan["rows"], plan["batch_rows"]), (2_000_000, 1000)) self.assertEqual({c["config"]: c["wal"] for c in plan["cells"]}, { "R": {"PROVIDER": "raft_engine", "SYNC_WRITE": "true", "DIR": "/wal"}, "D": {"PROVIDER": "experimental_object_store", "ACK_MODE": "durable"}, @@ -66,8 +70,8 @@ class PlanTest(unittest.TestCase): def test_smoke_overrides_rows_and_rounds(self): plan = bench.build_plan("8", "2000000", "1000", "2", smoke=True) - self.assertEqual((plan["rows"], plan["rounds"], plan["data_profile"]), (50_000, 1, "custom")) - self.assertEqual(plan["generator_args"], ["--line-count", "50000"]) + self.assertEqual((plan["rows"], plan["rounds"], plan["corpora"][0]["data_profile"]), (50_000, 1, "custom")) + self.assertEqual(plan["corpora"][0]["generator_args"], ["--line-count", "50000"]) self.assertEqual([c["id"] for c in plan["cells"]], ["1-8-R", "1-8-D", "1-8-E"]) def test_invalid_inputs_are_rejected(self): @@ -134,6 +138,37 @@ class PlanTest(unittest.TestCase): with self.subTest(bad=bad), self.assertRaises(ValueError): bench.resolve_image(bad, "nightly") + def test_groups_inherit_the_inputs_and_keep_their_own_settings(self): + groups = [{"name": "recovery", "configs": "D", "rows": 4000000, "rounds": 1, "restart": True, + "sweep": "RECOVERY_CONCURRENCY=2,32"}, + {"name": "crashe", "mode": "crash", "configs": "E", "rounds": 1, "cycles": 3, "kill_after": [5, 9]}, + {"name": "pin", "mode": "crash", "configs": "D", "rounds": 1, "cycles": 1, + "kill_after": [540, 540], "pin": True}, + {"name": "idle", "configs": "D", "rounds": 1, "idle_seconds": 180}] + plan = bench.build_plan("8", "2000000", "1000", "2", smoke=False, groups=json.dumps(groups)) + self.assertEqual([c["id"] for c in plan["cells"]], [ + "recovery-1-8-D-2", "recovery-1-8-D-32", "crashe-1-8-E", "pin-1-8-D", "idle-1-8-D"]) + self.assertEqual([c["rows"] for c in plan["corpora"]], [4_000_000, 2_000_000]) + cells = {c["id"]: c for c in plan["cells"]} + self.assertEqual(cells["recovery-1-8-D-2"]["wal"]["FLUSH_INTERVAL"], "10ms") + self.assertEqual((cells["crashe-1-8-E"]["cycles"], cells["crashe-1-8-E"]["kill_after"]), (3, [5, 9])) + self.assertTrue(cells["pin-1-8-D"]["pin"]) + self.assertNotIn("FLUSH_INTERVAL", cells["pin-1-8-D"]["wal"]) + self.assertEqual(cells["idle-1-8-D"]["idle_seconds"], 180) + smoke = bench.build_plan("8", "2000000", "1000", "2", smoke=True, groups=json.dumps(groups)) + pin = next(c for c in smoke["cells"] if c["group"] == "pin") + self.assertEqual((pin["cycles"], pin["kill_after"]), (1, [60, 60])) + self.assertEqual([c["rows"] for c in smoke["corpora"]], [50_000]) + + def test_invalid_groups_are_rejected(self): + for groups in ([], [{"configs": "D"}], [{"name": "Bad"}], [{"name": "a"}, {"name": "a"}], + [{"name": "a", "colour": "red"}], [{"name": "a", "mode": "crash", "configs": "R"}], + [{"name": "a", "mode": "crash", "configs": "D", "restart": True}], + [{"name": "a", "mode": "crash", "configs": "D", "kill_after": [9, 5]}], + [{"name": "a", "mode": "soak"}], [{"name": "a", "idle_seconds": 601}]): + with self.subTest(groups=groups), self.assertRaises(ValueError): + bench.build_plan("8", "6000", "1000", "1", smoke=False, groups=json.dumps(groups)) + def test_nightly_tag_is_the_newest_by_date(self): tags = ["latest", "v1.3.0-alpha.1-nightly-20260907", "v1.4.0-nightly-20261012", "v1.4.0-nightly-20261005", "nightly-arm64"] @@ -165,6 +200,102 @@ class PlanTest(unittest.TestCase): bench.build_manifest(plan, [{"RepoDigests": []}], "", "", "", "") +def write_lines(path, lines): + path.write_text("".join(f"{line}\n" for line in lines)) + + +def crash_cycle(root, cycle, stripes, acked, requests, exits): + """One cycle of two writers: attempted stripes, acked batches, requests and exit times per writer.""" + directory = root / f"cycle-{cycle}" + directory.mkdir(parents=True) + for index in range(2): + write_lines(directory / f"attempted-{index}.log", stripes[index]) + write_lines(directory / f"acked-{index}.log", acked[index]) + write_lines(directory / f"requests-{index}.log", requests[index]) + (directory / f"exit-{index}.log").write_text(f"{exits[index]}\n") + return directory + + +class CrashOracleTest(unittest.TestCase): + # Writer 0 got batches 0 and 2 acknowledged and lost 4 in flight; writer 1 got 1 and lost 3. + STRIPES = ([0, 2, 4], [1, 3]) + ACKED = ([0, 2], [1]) + REQUESTS = (["0 200 10", "2 200 20", "4 000 105"], ["1 200 15", "3 000 101"]) + + def check(self, root, found, mode="durable", requests=REQUESTS, exits=(106, 102)): + crash_cycle(root, 1, self.STRIPES, self.ACKED, requests, exits) + result = crash.check_kill(root / "cycle-1", 2, 100, 104, 2000) + return result | crash.verify(root, found, 10, mode == "enqueued") + + def test_acked_batches_present_once_and_an_in_flight_extra_pass(self): + with tempfile.TemporaryDirectory() as directory: + result = self.check(Path(directory), {0: 10, 1: 10, 2: 10, 4: 10}) + self.assertEqual((result["kill_errors"], result["verify_errors"]), ([], [])) + self.assertEqual((result["in_flight"], result["writers_at_kill"], result["extra_batches"], + result["lost_batches"]), (2, 2, 1, 0)) + + def test_durable_violations_are_reported(self): + cases = {"acknowledged but absent": {0: 10, 1: 10}, "present more than once": {0: 20, 1: 10, 2: 10}, + "present in part": {0: 10, 1: 10, 2: 7}, "never attempted": {0: 10, 1: 10, 2: 10, 9: 10}} + for error, found in cases.items(): + with self.subTest(error=error), tempfile.TemporaryDirectory() as directory: + result = self.check(Path(directory), found) + self.assertTrue(any(error in e for e in result["verify_errors"]), result["verify_errors"]) + + def test_enqueued_loses_acked_batches_without_failing(self): + with tempfile.TemporaryDirectory() as directory: + result = self.check(Path(directory), {0: 10}, mode="enqueued") + self.assertEqual(result["verify_errors"], []) + self.assertEqual((result["lost_batches"], result["lost_rows"]), (2, 20)) + + def test_a_connection_lost_before_the_kill_fails(self): + with tempfile.TemporaryDirectory() as directory: + requests = (["0 200 10", "2 200 20", "4 000 50"], ["1 200 15", "3 500 101"]) + result = self.check(Path(directory), {0: 10, 1: 10, 2: 10}, requests=requests, exits=(51, 99)) + self.assertEqual(len(result["kill_errors"]), 3, result["kill_errors"]) + + def test_the_writer_stops_each_stripe_at_its_first_unacknowledged_batch(self): + import http.server + import threading + inserted, lock = [], threading.Lock() + + class Handler(http.server.BaseHTTPRequestHandler): + def do_POST(self): + body = self.rfile.read(int(self.headers["Content-Length"])).decode() + with lock: + if len(inserted) >= 6: + self.close_connection = True + self.connection.close() + return + inserted.append(body) + self.send_response(200) + self.end_headers() + + def log_message(self, *args): + pass + + server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler) + threading.Thread(target=server.serve_forever, daemon=True).start() + try: + with tempfile.TemporaryDirectory() as directory: + run = Path(directory) + args = SimpleNamespace(dir=str(run / "cycle-1"), url=f"http://127.0.0.1:{server.server_port}/v1/sql", + table="crash", writers=2, first_seq=0, rows=3) + crash.write(args) + found = {} + for body in inserted: + for seq in set(re.findall(r"%28(\d+)%2C", body)): + found[int(seq)] = 3 + result = crash.verify(run, found, 3, False) + self.assertEqual((result["verify_errors"], result["acked_batches"]), ([], 6)) + for index in range(2): + attempted = (run / "cycle-1" / f"attempted-{index}.log").read_text().split() + self.assertEqual([int(seq) % 2 for seq in attempted], [index] * len(attempted)) + finally: + server.shutdown() + server.server_close() + + class SummaryTest(unittest.TestCase): def test_quantile_interpolates_like_prometheus(self): buckets = summary.parse_metrics(ACK_BUCKETS)["buckets"]["append_ack_seconds"] @@ -238,6 +369,46 @@ class SummaryTest(unittest.TestCase): self.assertIn("| 2.00 | 50% of 8 |", output) self.assertIn("| 8 | D/R0 | 16 | 0.600 | 0.600 |", output) + def test_traffic_idle_crash_and_pinned_cells_are_summarized(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + traffic = ("greptime_logstore_object_store_wal_created_objects_total 600\n" + "greptime_logstore_object_store_wal_object_bytes_sum 3000000000\n" + "greptime_logstore_object_store_wal_object_bytes_count 600\n" + 'opendal_operation_duration_seconds_count{scheme="s3",operation="write"} 650\n' + 'opendal_operation_duration_seconds_count{scheme="s3",operation="read"} 40\n') + self.write_cell(root, "1-32-E", 90.0, metrics=traffic, idle_seconds=180, group="") + (root / "cells" / "1-32-E" / "metrics-idle.prom").write_text( + traffic.replace(" 600\n", " 598\n", 1).replace("} 650", "} 648")) + cell = summary.load_cell(root / "cells" / "1-32-E") + self.assertEqual((cell["objects_per_second"], cell["mean_object_bytes"], cell["sealed_on_size"]), + (10.0, 5e6, False)) + self.assertAlmostEqual(cell["wal_mb_per_second"], 50.0) + self.assertEqual(cell["idle"], {"seconds": 180, "creates": 2, "requests": {"write": 2}}) + path = root / "cells" / "pin-1-8-D" + path.mkdir(parents=True) + (path / "cell.json").write_text(json.dumps({ + "id": "pin-1-8-D", "group": "pin", "mode": "crash", "round": 1, "concurrency": 8, "config": "D", + "wal": bench.WAL_CONFIGS["D"], "exit_code": 0, "metrics_scraped": True})) + (path / "cycles.jsonl").write_text(json.dumps({ + "cycle": 1, "kill_after_seconds": 540.0, "cycle_acked_batches": 4000, "in_flight": 8, + "found_batches": 4003, "acked_batches": 4000, "lost_batches": 0, "lost_rows": 0, "extra_batches": 3, + "restart_seconds": 4.5, "pin_rows": 1, "passed": True, "kill_errors": [], "verify_errors": []}) + "\n") + (path / "metrics-cycle-1.prom").write_text( + "greptime_logstore_object_store_wal_indexed_objects 5400\n" + "greptime_logstore_object_store_wal_created_objects_total 5401\n") + (path / "metrics-restart-1.prom").write_text( + "greptime_logstore_object_store_wal_recovery_seconds_sum 2.5\n" + "greptime_logstore_object_store_wal_recovery_seconds_count 1\n" + "greptime_logstore_object_store_wal_recovered_objects_total 5399\n") + (path / "objects.tsv").write_text("100 300 0 301\n130 600 0 601\n") + rows = [summary.load_cell(p) for p in sorted((root / "cells").iterdir())] + output = summary.render({}, rows, summary.ratios(rows)) + self.assertIn("| 1-32-E | 50.0 | 10.0 | 4.77 | no | read 40, write 650 | — | 180 | 2 | write 2 |", output) + self.assertIn("| pin-1-8-D | 1 | 540.0 | 4,000 | 8 | 4,003 | 4,000 | 0 | 0 | 3 | 5,400 | 4.50 | 2.500 " + "| 5,399 | 1 | pass |", output) + self.assertIn("| pin-1-8-D | 300, 600 | 0 | 601 |", output) + def test_untouched_counters_are_zero_only_for_an_active_object_store_wal(self): with tempfile.TemporaryDirectory() as directory: root = Path(directory)