diff --git a/.github/scripts/oswal-s3-bench-run.sh b/.github/scripts/oswal-s3-bench-run.sh index a9835c1e5f1..356a702a65c 100644 --- a/.github/scripts/oswal-s3-bench-run.sh +++ b/.github/scripts/oswal-s3-bench-run.sh @@ -22,12 +22,12 @@ check_runtime() { } pull_images() { - : "${RESULTS:?}" "${RUNTIME_IMAGE:?}" "${GREPTIMEDB_TAG:?}" + : "${RESULTS:?}" "${RUNTIME_IMAGE:?}" "${GREPTIMEDB_REF:?}" mkdir -p "$RESULTS/images" bash "$here/pull-benchmark-image.sh" "$RUNTIME_IMAGE" - bash "$here/pull-benchmark-image.sh" "greptime/greptimedb:$GREPTIMEDB_TAG" + bash "$here/pull-benchmark-image.sh" "$GREPTIMEDB_REF" docker image inspect "$RUNTIME_IMAGE" > "$RESULTS/images/runtime.json" - docker image inspect "greptime/greptimedb:$GREPTIMEDB_TAG" > "$RESULTS/images/greptimedb.json" + docker image inspect "$GREPTIMEDB_REF" > "$RESULTS/images/greptimedb.json" } wal_disk() { @@ -59,12 +59,60 @@ generate() { jq -e --argjson rows "$(jq .rows "$PLAN")" '.line_count == $rows' "$CORPUS_DIR/summary.json" >/dev/null } -# Scrape once, after the load succeeded or failed, while the server still runs. +# 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.prom" || true + grep -E '^(# (HELP|TYPE) )?greptime_logstore_object_store_wal_' "$dir/metrics.all" > "$dir/metrics$phase.prom" || true rm -f "$dir/metrics.all" - metrics_scraped=true + if [[ -z "$phase" ]]; then metrics_scraped=true; else restart_scraped=true; fi +} + +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. +server_cpu() { docker exec "$cid" cat /sys/fs/cgroup/cpu.stat 2>/dev/null | awk '/^usage_usec / {printf "%.3f", $2 / 1e6}' || true; } +host_cpu() { awk '/^cpu / {print $2 + $3 + $4 + $7 + $8 + $9, $2 + $3 + $4 + $5 + $6 + $7 + $8 + $9}' /proc/stat 2>/dev/null || true; } + +start_server() { + cid=$(docker run -d --init --name "$name$phase" --label "o11ybench.owner=$OWNER" \ + --add-host host.docker.internal:host-gateway \ + -p 127.0.0.1:4000:4000 -p 127.0.0.1:4001:4001 "${docker_env[@]}" ${mounts[@]+"${mounts[@]}"} \ + "$GREPTIMEDB_IMAGE" standalone start --http-addr=0.0.0.0:4000 --grpc-bind-addr=0.0.0.0:4001) + local deadline=$((SECONDS + 300)) + until curl --noproxy '*' -fsS --max-time 5 http://127.0.0.1:4000/health >/dev/null 2>&1; do + [[ $(docker inspect --format '{{.State.Running}}' "$cid") == true ]] || { echo "$id: server$phase exited" >&2; exit 1; } + ((SECONDS < deadline)) || { echo "$id: server$phase not healthy in 300s" >&2; exit 1; } + sleep 0.2 + done +} + +stop_server() { + if [[ "${1:-}" == kill ]]; then docker kill --signal KILL "$cid" >/dev/null; else docker stop -t 120 "$cid" >/dev/null; fi + docker logs "$cid" > "$dir/server$phase.log" 2>&1 + docker rm -fv "$cid" >/dev/null + cid= +} + +# Kill the loaded server, start the same configuration on the same prefix and +# data home, and time it until /health and until the loaded table answers. +restart() { + local table count started deadline + table=$(jq -er .table "$dir/greptimedb-1/load-result.json") + scrape_metrics || { echo "$id: metrics scrape failed" >&2; exit 4; } + stop_server kill + phase=-restart started=$(now) + start_server + restart_seconds=$(elapsed "$started") + deadline=$((SECONDS + 300)) + # Regions may still be opening after /health. + until count=$(curl --noproxy '*' -fsS --max-time 30 --data-urlencode "sql=SELECT count(*) FROM $table" \ + 'http://127.0.0.1:4000/v1/sql?db=public' | jq -er '.output[0].records.rows[0][0]'); do + ((SECONDS < deadline)) || { echo "$id: $table not readable in 300s after restart" >&2; exit 5; } + 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; } } finish() { @@ -74,15 +122,22 @@ finish() { if [[ -n "$cid" ]]; then # A load that succeeded without its metrics is not a measurement. scrape_metrics || { echo "$id: metrics scrape failed" >&2; [[ $rc != 0 ]] || rc=4; } - docker stop -t 120 "$cid" >/dev/null - docker logs "$cid" > "$dir/server.log" 2>&1 - docker rm -fv "$cid" >/dev/null + stop_server fi [[ -z "$wal_dir" ]] || sudo -n rm -rf "$wal_dir" + [[ -z "$home_dir" ]] || sudo -n rm -rf "$home_dir" jq -n --argjson spec "$spec" --arg device "$wal_device" --arg version "$version" \ --arg load_seconds "$load_seconds" --argjson exit_code "$rc" --argjson scraped "$metrics_scraped" \ + --argjson restart_scraped "$restart_scraped" --arg restart_seconds "$restart_seconds" \ + --arg restart_query_seconds "$restart_query_seconds" --arg restart_count "$restart_count" \ + --arg server_cpu_seconds "$server_cpu_seconds" --arg host_cpu_busy "$host_cpu_busy" --arg host_cpus "$(nproc 2>/dev/null)" \ '$spec + {wal_device: $device, version: $version, exit_code: $exit_code, metrics_scraped: $scraped, - load_wall_seconds: ($load_seconds | tonumber? // null)}' > "$dir/cell.json" + load_wall_seconds: ($load_seconds | tonumber? // null), + server_cpu_seconds: ($server_cpu_seconds | tonumber? // null), + host_cpu_busy: ($host_cpu_busy | tonumber? // null), host_cpus: ($host_cpus | tonumber? // null), + restart_scraped: $restart_scraped, restart_seconds: ($restart_seconds | tonumber? // null), + restart_query_seconds: ($restart_query_seconds | tonumber? // null), + restart_count: ($restart_count | tonumber? // null)}' > "$dir/cell.json" exit "$rc" } @@ -91,22 +146,29 @@ finish() { cell() { : "${PLAN:?}" "${RESULTS:?}" "${CORPUS_DIR:?}" "${OWNER:?}" "${RUNTIME_IMAGE:?}" "${GREPTIMEDB_IMAGE:?}" : "${RUN_PREFIX:?}" "${WAL_ROOT:?}" "${S3_BUCKET:?}" "${S3_REGION:?}" "${AWS_ACCESS_KEY_ID:?}" "${AWS_SECRET_ACCESS_KEY:?}" - spec=$1 cid= wal_dir= version= load_seconds= metrics_scraped=false id= - local concurrency name setting started ended + spec=$1 cid= wal_dir= home_dir= version= load_seconds= metrics_scraped=false id= phase= + restart_scraped=false restart_seconds= restart_query_seconds= restart_count= server_cpu_seconds= host_cpu_busy= + local concurrency setting started cpu_before host_before host_after id=$(jq -r .id <<< "$spec"); concurrency=$(jq -r .concurrency <<< "$spec") - dir="$RESULTS/cells/$id"; name="$OWNER-$id" + dir="$RESULTS/cells/$id" name="$OWNER-$id" mkdir -p "$dir" # The root holds data/ and the WAL's default prefix wal/ side by side. local settings=(STORAGE__TYPE=S3 "STORAGE__BUCKET=$S3_BUCKET" "STORAGE__REGION=$S3_REGION" "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) while IFS= read -r setting; do settings+=("$setting"); done \ < <(jq -r '.wal | to_entries[] | "WAL__\(.key)=\(.value)"' <<< "$spec") - local docker_env=() mounts=() + docker_env=() mounts=() for setting in "${settings[@]}"; do docker_env+=(-e "GREPTIMEDB_STANDALONE__$setting") printf 'GREPTIMEDB_STANDALONE__%s\n' "$setting" >> "$dir/config.env" done + while IFS= read -r setting; do + docker_env+=(-e "$setting") + printf '%s\n' "$setting" >> "$dir/config.env" + done < <(jq -r '.env // {} | to_entries[] | "\(.key)=\(.value)"' <<< "$spec") # Pass the two keys by name: their values never reach argv, a file or the artifact. export GREPTIMEDB_STANDALONE__STORAGE__ACCESS_KEY_ID=$AWS_ACCESS_KEY_ID export GREPTIMEDB_STANDALONE__STORAGE__SECRET_ACCESS_KEY=$AWS_SECRET_ACCESS_KEY @@ -119,20 +181,16 @@ cell() { else wal_device="s3://$S3_BUCKET/$RUN_PREFIX/$id/wal" fi + if jq -e '.restart' <<< "$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 trap finish EXIT - cid=$(docker run -d --init --name "$name" --label "o11ybench.owner=$OWNER" \ - --add-host host.docker.internal:host-gateway \ - -p 127.0.0.1:4000:4000 -p 127.0.0.1:4001:4001 "${docker_env[@]}" ${mounts[@]+"${mounts[@]}"} \ - "$GREPTIMEDB_IMAGE" standalone start --http-addr=0.0.0.0:4000 --grpc-bind-addr=0.0.0.0:4001) - local deadline=$((SECONDS + 300)) - until curl --noproxy '*' -fsS --max-time 5 http://127.0.0.1:4000/health >/dev/null 2>&1; do - [[ $(docker inspect --format '{{.State.Running}}' "$cid") == true ]] || { echo "$id: server exited" >&2; exit 1; } - ((SECONDS < deadline)) || { echo "$id: server not healthy in 300s" >&2; exit 1; } - sleep 2 - done + start_server version=$(docker exec "$cid" greptime --version | sed -n 's/^version: //p') [[ -n "$version" ]] - started=$(date +%s.%N) + 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" \ @@ -142,10 +200,15 @@ cell() { -e "TARGET_ID=$name" -e TARGET_HOST=127.0.0.1 -e PREPARE_WORKERS= -e "MAX_IN_FLIGHT=$concurrency" \ -e "GREPTIMEDB_BATCH_SIZE=$(jq -r .batch_rows "$PLAN")" --entrypoint /bin/bash \ "$RUNTIME_IMAGE" scripts/agent-observability/greptimedb.sh load > "$dir/load.log" 2>&1 - ended=$(date +%s.%N) - load_seconds=$(awk -v a="$started" -v b="$ended" 'BEGIN {printf "%.3f", b - a}') + load_seconds=$(elapsed "$started") + host_after=$(host_cpu) + server_cpu_seconds=$(awk -v a="$cpu_before" -v b="$(server_cpu)" 'BEGIN {if (a != "" && b != "") printf "%.3f", b - a}') + # 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' \ "$dir/greptimedb-1/load-result.json" >/dev/null + if jq -e '.restart' <<< "$spec" >/dev/null; then restart; fi } scrub() { diff --git a/.github/scripts/oswal-s3-bench-summary.py b/.github/scripts/oswal-s3-bench-summary.py index 67186d422da..7241425543c 100644 --- a/.github/scripts/oswal-s3-bench-summary.py +++ b/.github/scripts/oswal-s3-bench-summary.py @@ -26,6 +26,8 @@ from pathlib import Path PREFIX = "greptime_logstore_object_store_wal_" COUNTERS = ("created_objects_total", "stalled_appends_total", "poisoned_total", "create_failures_total", "create_conflicts_total") +# The Raft Engine controls every object store WAL cell is compared with: fsync per write and the default. +BASELINES = ("R", "R0") SAMPLE = re.compile(r'([a-zA-Z_:][a-zA-Z0-9_:]*)(?:\{([^}]*)\})?\s+(\S+)') @@ -64,25 +66,43 @@ def geomean(values: list) -> float | None: return math.exp(sum(map(math.log, values)) / len(values)) if values and all(v > 0 for v in values) else None +def read_metrics(path: Path) -> dict: + return parse_metrics(path.read_text() if path.exists() else "") + + 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" cell = json.loads(recorded.read_text()) if recorded.exists() else spec | {"exit_code": None, "missing": True} result_path = path / "greptimedb-1" / "load-result.json" result = json.loads(result_path.read_text()) if result_path.exists() else {} - metrics_path = path / "metrics.prom" - metrics = parse_metrics(metrics_path.read_text() if metrics_path.exists() else "") - ack = metrics["buckets"].get("append_ack_seconds", []) + metrics, restarted = read_metrics(path / "metrics.prom"), read_metrics(path / "metrics-restart.prom") 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"], "config": cell["config"], "exit_code": cell["exit_code"], "wal_device": cell.get("wal_device"), - "missing": cell.get("missing", False), - "version": cell.get("version"), "load_wall_seconds": cell.get("load_wall_seconds"), + "missing": cell.get("missing", False), "env": cell.get("env", {}), "sweep_value": cell.get("sweep_value"), + "version": cell.get("version"), "load_wall_seconds": wall, "rows": result.get("count_after"), "load_seconds": load_seconds, "rows_per_second": result.get("rows_per_second") if cell["exit_code"] == 0 else None, - "append_ack_p50_seconds": quantile(0.5, ack), "append_ack_p99_seconds": quantile(0.99, ack), + "server_cpu_cores": cpu / wall if cpu is not None and wall else None, + "host_cpu_busy": cell.get("host_cpu_busy"), "host_cpus": cell.get("host_cpus"), } + for name, key in (("append_ack_seconds", "append_ack"), ("seal_to_durable_seconds", "seal_to_durable"), + ("object_bytes", "object_bytes")): + buckets = metrics["buckets"].get(name, []) + row[f"{key}_p50"], row[f"{key}_p99"] = quantile(0.5, buckets), quantile(0.99, buckets) + if cell.get("restart"): + # A restarted process observed exactly one recovery, so the sum is its duration. + count = restarted["samples"].get("recovery_seconds_count") + row["restart"] = { + "wall_seconds": cell.get("restart_seconds"), "query_seconds": cell.get("restart_query_seconds"), + "rows": cell.get("restart_count"), + "recovery_seconds": restarted["samples"].get("recovery_seconds_sum") if count == 1 else None, + "recovered_objects": restarted["samples"].get("recovered_objects_total") + if cell.get("restart_scraped") else None, + } # The counters register on their first event, so a scrape of an object store WAL # that created objects omits the ones that never moved: those are zero, not unknown. active = (cell.get("metrics_scraped") and cell.get("wal", {}).get("PROVIDER") == "experimental_object_store" @@ -95,22 +115,35 @@ def load_cell(path: Path, spec: dict | None = None) -> dict: def ratios(rows: list) -> list: - """D/R and E/R per round and their geometric mean over the rounds, per concurrency.""" - speed = {(r["round"], r["concurrency"], r["config"]): r["rows_per_second"] for r in rows} + """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)] 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 in ("D", "E"): + for (config, value), baseline in ((s, b) for s in series for b in baselines): per_round = [] for round_number in rounds: - base, value = speed.get((round_number, concurrency, "R")), speed.get((round_number, concurrency, config)) - per_round.append(value / base if base and value else None) - complete = [value for value in per_round if value is not None] - result.append({"concurrency": concurrency, "ratio": f"{config}/R", "per_round": per_round, + 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}) return result +def overrides(env: dict) -> str: + return " ".join(f"{k.removeprefix('GREPTIMEDB_OSWAL_')}={v}" for k, v in sorted(env.items())) or "—" + + +def pair(a, b, digits=0, scale=1.0) -> str: + return f"{fmt(a, digits, scale)} / {fmt(b, digits, scale)}" + + def fmt(value, digits=0, scale=1.0) -> str: return "—" if value is None else f"{value * scale:,.{digits}f}" @@ -119,21 +152,38 @@ def render(run: dict, rows: list, pairs: list) -> str: lines = [f"## Object store WAL against S3 ({'smoke, MinIO' if run.get('smoke') else run.get('instance_type')})", ""] lines += [f"GreptimeDB `{run.get('greptimedb_image')}` ({next((r['version'] for r in rows if r['version']), '—')}); " f"{fmt(run.get('rows'))} rows in {run.get('batch_rows')}-row batches; bucket region {run.get('region')}.", ""] - lines += ["| Cell | Rows/s | Load s | Wall s | Rows | Ack p50 ms | Ack p99 ms | Creates | Creates/min " - "| Stalled | Poisoned | Create failures | Conflicts | WAL on |", - "| --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | --- |"] + lines += ["| Cell | Overrides | Rows/s | Load s | Wall s | Ack p50 / p99 ms | Seal to durable p50 / p99 ms " + "| Object p50 / p99 MiB | Creates | Creates/min | Stalled | Poisoned | Create failures | Conflicts " + "| 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 \ else f"{r['id']} (failed, exit {r['exit_code']})" lines.append(" | ".join([ - f"| {cell}", fmt(r["rows_per_second"]), fmt(r["load_seconds"], 1), fmt(r["load_wall_seconds"], 1), - fmt(r["rows"]), fmt(r["append_ack_p50_seconds"], 1, 1000), fmt(r["append_ack_p99_seconds"], 1, 1000), + 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), + pair(r["seal_to_durable_p50"], r["seal_to_durable_p99"], 1, 1000), + pair(r["object_bytes_p50"], r["object_bytes_p99"], 1, 1 / 2**20), *(fmt(r[c]) for c in COUNTERS[:1]), fmt(r["creates_per_minute"], 1), - *(fmt(r[c]) for c in COUNTERS[1:]), f"`{r['wal_device'] or '—'}` |"])) - lines += ["", "| Concurrency | Ratio | Per round | Geometric mean |", "| ---: | --- | --- | ---: |"] + *(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 '—'}` |"])) + 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 " + "| Recovery s | Recovered objects | Rows after restart |", + "| --- | --- | ---: | ---: | ---: | ---: | ---: | ---: |"] + for r in restarts: + x = r["restart"] + lines.append(" | ".join([ + 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 |", "| ---: | --- | ---: | --- | ---: |"] for p in pairs: - lines.append(f"| {p['concurrency']} | {p['ratio']} | {', '.join(fmt(v, 3) for v in p['per_round'])} " - f"| {fmt(p['geomean'], 3)} |") + lines.append(f"| {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 faad8ace674..25e49c87baf 100644 --- a/.github/scripts/oswal-s3-bench.py +++ b/.github/scripts/oswal-s3-bench.py @@ -34,13 +34,22 @@ from pathlib import Path SMOKE_ROWS = 50_000 # The o11ybench data profiles; a matching row count generates the canonical dataset. DATA_PROFILES = {5_000: "S", 2_000_000: "D", 10_000_000: "P", 100_000_000: "M"} -# Identical [storage] for every configuration; only [wal] differs. +# Identical [storage] for every configuration; only [wal] differs. R0 is the standalone default. WAL_CONFIGS = { "R": {"PROVIDER": "raft_engine", "SYNC_WRITE": "true", "DIR": "/wal"}, + "R0": {"PROVIDER": "raft_engine", "SYNC_WRITE": "false", "DIR": "/wal"}, "D": {"PROVIDER": "experimental_object_store", "ACK_MODE": "durable"}, "E": {"PROVIDER": "experimental_object_store", "ACK_MODE": "enqueued"}, } -ORDERS = (("R", "D", "E"), ("E", "D", "R")) +BASELINES = ("R", "R0") +# The pipeline depths an image built with the overrides reads; their defaults on main. +DEPTHS = {"GREPTIMEDB_OSWAL_MAX_IN_FLIGHT_CREATES": 4, "GREPTIMEDB_OSWAL_MAX_SEALED_BATCHES": None, + "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" +ENV_NAME = re.compile(r"[A-Za-z_][A-Za-z0-9_]*") +IMAGE = re.compile(r"[a-z0-9]+(?:[._-][a-z0-9]+)*(?::[0-9]+)?(?:/[a-z0-9]+(?:[._-][a-z0-9]+)*)+" + r"(?::[A-Za-z0-9_][A-Za-z0-9_.-]{0,127})?(?:@sha256:[0-9a-f]{64})?") NIGHTLY = re.compile(r"v\d+\.\d+\.\d+(?:-[0-9A-Za-z.]+)?-nightly-(\d{8})") TAG = re.compile(r"[A-Za-z0-9_][A-Za-z0-9_.-]{0,127}") DIGEST = re.compile(r".+@sha256:[0-9a-f]{64}") @@ -78,30 +87,92 @@ def build_manifest(plan: dict, greptimedb_inspect: list, runtime_image: str, raise ValueError("the GreptimeDB image has no sha256 repository digest") 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"], "greptimedb_image": image, "runtime_image": runtime_image, "instance_type": instance_type, "region": region, "prefix": prefix} -def build_plan(concurrency: str, rows: str, batch_rows: str, rounds: str, smoke: bool) -> dict: +def parse_extra_env(text: str) -> dict: + """A JSON object or K=V lines; the storage settings stay the benchmark's own.""" + if text.strip().startswith("{"): + parsed = json.loads(text) + if not all(isinstance(v, (str, int)) and not isinstance(v, bool) for v in parsed.values()): + raise ValueError("extra_env values must be strings or integers") + env = {k: str(v) for k, v in parsed.items()} + else: + env = {} + for line in filter(None, (line.strip() for line in text.splitlines())): + name, sep, value = line.partition("=") + if not sep or name.strip() in env: + raise ValueError(f"extra_env line is not a new K=V: {line!r}") + env[name.strip()] = value.strip() + for name, value in env.items(): + if not ENV_NAME.fullmatch(name) or name.startswith("GREPTIMEDB_STANDALONE__STORAGE__") or "\n" in value: + raise ValueError(f"extra_env may not set {name!r}") + if name in DEPTHS: + positive(name, value, 4096) + return env + + +def parse_sweep(text: str) -> tuple: + """NAME=v1,v2,... over one depth; the GREPTIMEDB_OSWAL_ prefix may be left out.""" + if not text.strip(): + return None, [None] + name, _, values = text.partition("=") + name = name.strip() if name.strip().startswith("GREPTIMEDB_OSWAL_") else f"GREPTIMEDB_OSWAL_{name.strip()}" + if name not in DEPTHS: + raise ValueError(f"sweep must name one of {', '.join(DEPTHS)}, got {text!r}") + points = [positive(name, value.strip(), 4096) for value in values.split(",")] + if len(set(points)) != len(points): + raise ValueError(f"sweep repeats a value: {text!r}") + return name, points + + +def check_depths(env: dict) -> None: + """Fail before provisioning on the sealed batch limit the store would reject.""" + creates = int(env.get("GREPTIMEDB_OSWAL_MAX_IN_FLIGHT_CREATES", DEPTHS["GREPTIMEDB_OSWAL_MAX_IN_FLIGHT_CREATES"])) + sealed = env.get("GREPTIMEDB_OSWAL_MAX_SEALED_BATCHES") + if sealed is not None and int(sealed) < creates + 2: + 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: 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) + 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) + # 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): - # Alternate the order between rounds so no configuration always runs first. + # Reverse the order every other round so no configuration or value always runs first. for level in levels: - for config in ORDERS[(round_number - 1) % 2]: + for config, point in series if round_number % 2 else reversed(series): + cell_env = env | ({swept: str(point)} if point is not None else {}) + 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}", "round": round_number, - "concurrency": level, "config": config, "wal": WAL_CONFIGS[config], + "id": 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, }) return { "smoke": smoke, "rows": row_count, "rounds": round_count, "batch_rows": positive("batch_rows", batch_rows, 100_000), "concurrency": levels, - "data_profile": profile or "custom", + "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, } @@ -114,6 +185,15 @@ def newest_nightly(tags: list[str]) -> str: return max(dated)[1] +def resolve_image(image: str, tag: str) -> str: + """The full image reference when given, else greptime/greptimedb at the resolved tag.""" + if image: + if not IMAGE.fullmatch(image) or not re.search(r"(:[^/]+|@sha256:[0-9a-f]{64})$", image): + raise ValueError(f"greptimedb_image must be a full reference with a tag or digest: {image!r}") + return image + return f"greptime/greptimedb:{resolve_tag(tag)}" + + def resolve_tag(requested: str) -> str: if requested != "nightly": if not TAG.fullmatch(requested): @@ -169,9 +249,15 @@ def main() -> int: for name in ("concurrency", "rows", "batch-rows", "rounds"): plan.add_argument(f"--{name}", required=True) 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"): + plan.add_argument(f"--{name}", default="") for name in ("timeout-minutes", "ttl-hours", "output"): plan.add_argument(f"--{name}") - commands.add_parser("tag").add_argument("requested") + image = commands.add_parser("image") + image.add_argument("--tag", required=True) + image.add_argument("--image", default="") regions = commands.add_parser("regions") for name in ("bucket", "runner"): regions.add_argument(f"--{name}", required=True) @@ -187,15 +273,16 @@ def main() -> int: if args.command == "plan": 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") + 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") 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']}") - elif args.command == "tag": - tag = resolve_tag(args.requested) - append_github("GITHUB_OUTPUT", "greptimedb_tag", tag) - print(f"GreptimeDB image tag: {tag}") + elif args.command == "image": + reference = resolve_image(args.image, args.tag) + append_github("GITHUB_OUTPUT", "greptimedb_ref", reference) + print(f"GreptimeDB image: {reference}") elif args.command == "regions": check_regions(args.bucket, args.runner) print(f"bucket and runner both in {args.runner}") diff --git a/.github/workflows/oswal-s3-bench.yml b/.github/workflows/oswal-s3-bench.yml index c31dfe8f1c3..e2dc61f15bf 100644 --- a/.github/workflows/oswal-s3-bench.yml +++ b/.github/workflows/oswal-s3-bench.yml @@ -10,6 +10,26 @@ on: description: 'Docker Hub greptime/greptimedb tag; nightly = the newest v*-nightly-* tag (latest is a release without the object store WAL)' type: string default: nightly + greptimedb_image: + description: 'Full image reference with a tag or digest; used instead of greptimedb_tag when set' + type: string + default: '' + configs: + description: 'WAL configurations: R (Raft Engine, sync_write), R0 (Raft Engine, standalone default), D (durable), E (enqueued)' + type: string + default: R,D,E + extra_env: + description: 'Environment for every GreptimeDB container: a JSON object or K=V lines' + type: string + default: '' + sweep: + description: 'One depth and its values, e.g. MAX_IN_FLIGHT_CREATES=1,2,4: one D and E cell per value (needs an image with the overrides)' + type: string + default: '' + restart: + 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 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 @@ -47,6 +67,11 @@ permissions: env: SMOKE: ${{ inputs.smoke }} GREPTIMEDB_TAG: ${{ inputs.greptimedb_tag }} + GREPTIMEDB_IMAGE_INPUT: ${{ inputs.greptimedb_image }} + CONFIGS: ${{ inputs.configs }} + EXTRA_ENV: ${{ inputs.extra_env }} + SWEEP: ${{ inputs.sweep }} + RESTART: ${{ inputs.restart }} REQUESTED_INSTANCE_TYPE: ${{ inputs.instance_type }} CONCURRENCY: ${{ inputs.concurrency }} ROWS: ${{ inputs.rows }} @@ -61,7 +86,7 @@ jobs: timeout-minutes: 15 outputs: instance_type: ${{ steps.runner.outputs.instance_type }} - greptimedb_tag: ${{ steps.plan.outputs.greptimedb_tag }} + greptimedb_ref: ${{ steps.plan.outputs.greptimedb_ref }} runtime_image: ${{ steps.runtime.outputs.runtime_image }} steps: - uses: actions/checkout@v4 @@ -77,8 +102,9 @@ 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" \ --timeout-minutes "$BENCHMARK_TIMEOUT_MINUTES" --ttl-hours "$JANITOR_TTL_HOURS" - python3 greptimedb/.github/scripts/oswal-s3-bench.py tag "$GREPTIMEDB_TAG" + python3 greptimedb/.github/scripts/oswal-s3-bench.py image --tag "$GREPTIMEDB_TAG" --image "$GREPTIMEDB_IMAGE_INPUT" - name: Resolve CI runner id: runner run: python3 greptimedb/.github/scripts/ci-runner-config.py --provider AWS --instance-type "$REQUESTED_INSTANCE_TYPE" @@ -132,7 +158,7 @@ jobs: timeout-minutes: ${{ fromJSON(format('{0}', inputs.benchmark_timeout_minutes)) }} env: INSTANCE_TYPE: ${{ inputs.smoke && 'ubuntu-latest' || needs.validate.outputs.instance_type }} - GREPTIMEDB_TAG: ${{ needs.validate.outputs.greptimedb_tag }} + GREPTIMEDB_REF: ${{ needs.validate.outputs.greptimedb_ref }} RUNTIME_IMAGE: ${{ needs.validate.outputs.runtime_image }} RUN_PREFIX: oswal-bench/${{ github.run_id }}-${{ github.run_attempt }} OWNER: o11ybench-oswal-${{ github.run_id }}-${{ github.run_attempt }} @@ -161,7 +187,8 @@ jobs: run: | 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" + --concurrency "$CONCURRENCY" --rows "$ROWS" --batch-rows "$BATCH_ROWS" --rounds "$ROUNDS" \ + --configs "$CONFIGS" --extra-env "$EXTRA_ENV" --sweep "$SWEEP" --restart "$RESTART" 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 dc81240f1ae..b617874db3c 100644 --- a/tests/perf/test_oswal_s3_bench_scripts.py +++ b/tests/perf/test_oswal_s3_bench_scripts.py @@ -76,6 +76,52 @@ class PlanTest(unittest.TestCase): with self.subTest(args=args), self.assertRaises(ValueError): bench.build_plan(*args, smoke=False) + def test_a_sweep_multiplies_the_object_store_cells_and_reverses_every_other_round(self): + plan = bench.build_plan("8", "2000000", "1000", "2", smoke=False, configs="R,R0,D,E", + sweep="MAX_IN_FLIGHT_CREATES=1,4") + self.assertEqual([c["id"] for c in plan["cells"]], [ + "1-8-R", "1-8-R0", "1-8-D-1", "1-8-D-4", "1-8-E-1", "1-8-E-4", + "2-8-E-4", "2-8-E-1", "2-8-D-4", "2-8-D-1", "2-8-R0", "2-8-R"]) + cells = {c["id"]: c for c in plan["cells"]} + self.assertEqual(cells["1-8-D-1"]["env"], {"GREPTIMEDB_OSWAL_MAX_IN_FLIGHT_CREATES": "1"}) + self.assertEqual((cells["1-8-R0"]["env"], cells["1-8-R0"]["sweep_value"]), ({}, None)) + self.assertEqual(cells["1-8-R0"]["wal"], {"PROVIDER": "raft_engine", "SYNC_WRITE": "false", "DIR": "/wal"}) + self.assertEqual(plan["sweep"], {"name": "GREPTIMEDB_OSWAL_MAX_IN_FLIGHT_CREATES", "values": [1, 4]}) + + def test_extra_env_and_restart_reach_every_cell(self): + for extra in ('{"GREPTIMEDB_OSWAL_MAX_IN_FLIGHT_CREATES": 4, "RUST_LOG": "info"}', + "GREPTIMEDB_OSWAL_MAX_IN_FLIGHT_CREATES=4\n\nRUST_LOG = info\n"): + plan = bench.build_plan("8", "2000000", "1000", "1", smoke=False, configs="R,D", extra_env=extra, + sweep="GREPTIMEDB_OSWAL_MAX_SEALED_BATCHES=6,32", restart=True) + with self.subTest(extra=extra): + self.assertEqual([c["id"] for c in plan["cells"]], ["1-8-R", "1-8-D-6", "1-8-D-32"]) + cells = {c["id"]: c for c in plan["cells"]} + self.assertEqual(cells["1-8-D-6"]["env"], {"GREPTIMEDB_OSWAL_MAX_IN_FLIGHT_CREATES": "4", + "RUST_LOG": "info", "GREPTIMEDB_OSWAL_MAX_SEALED_BATCHES": "6"}) + self.assertEqual(cells["1-8-D-6"]["wal"]["FLUSH_INTERVAL"], "10ms") + self.assertNotIn("FLUSH_INTERVAL", cells["1-8-R"]["wal"]) + self.assertTrue(all(c["restart"] for c in plan["cells"])) + + def test_invalid_sweeps_and_extra_env_are_rejected(self): + for kwargs in ({"sweep": "MAX_DELETES=1,2"}, {"sweep": "RECOVERY_CONCURRENCY=0,2"}, + {"sweep": "RECOVERY_CONCURRENCY=2,2"}, {"sweep": "MAX_SEALED_BATCHES=5,8"}, + {"extra_env": "GREPTIMEDB_OSWAL_MAX_IN_FLIGHT_CREATES=8", "sweep": "MAX_SEALED_BATCHES=8"}, + {"extra_env": "GREPTIMEDB_OSWAL_RECOVERY_CONCURRENCY=8", "sweep": "RECOVERY_CONCURRENCY=2"}, + {"extra_env": "GREPTIMEDB_STANDALONE__STORAGE__BUCKET=other"}, {"extra_env": "NO_VALUE"}, + {"extra_env": "A=1\nA=2"}, {"extra_env": '{"A": true}'}, {"extra_env": "1A=x"}, + {"extra_env": "GREPTIMEDB_OSWAL_MAX_IN_FLIGHT_CREATES=many"}, {"configs": "R,X"}, + {"configs": "D,D"}): + with self.subTest(kwargs=kwargs), self.assertRaises(ValueError): + bench.build_plan("8", "6000", "1000", "1", smoke=False, **kwargs) + + def test_the_image_is_the_full_reference_or_a_greptimedb_tag(self): + image = "docker.io/greptime/greptimedb-dev:dev-20261013-1791848986-a5a1a9f4" + self.assertEqual(bench.resolve_image(image, "nightly"), image) + self.assertEqual(bench.resolve_image("", "v1.4.0-nightly-20261012"), "greptime/greptimedb:v1.4.0-nightly-20261012") + for bad in ("greptimedb", "docker.io/greptime/greptimedb", "Docker.io/x/y:1", "x/y:bad tag"): + with self.subTest(bad=bad), self.assertRaises(ValueError): + bench.resolve_image(bad, "nightly") + 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"] @@ -117,14 +163,15 @@ class SummaryTest(unittest.TestCase): self.assertEqual(summary.quantile(0.99, [(0.1, 1.0), (float("inf"), 4.0)]), 0.1) self.assertNotIn("kafka_client_produce_elapsed_count", summary.parse_metrics(ACK_BUCKETS)["samples"]) - def write_cell(self, root, cell_id, rows_per_second, exit_code=0, metrics=""): - round_number, concurrency, config = cell_id.split("-") + def write_cell(self, root, cell_id, rows_per_second, exit_code=0, metrics="", **extra): + round_number, concurrency, config, *value = cell_id.split("-") path = root / "cells" / cell_id (path / "greptimedb-1").mkdir(parents=True) (path / "cell.json").write_text(json.dumps({ "id": cell_id, "round": int(round_number), "concurrency": int(concurrency), "config": config, - "wal": bench.WAL_CONFIGS[config], "metrics_scraped": True, - "exit_code": exit_code, "wal_device": "/dev/nvme1n1", "version": "1.4.0", "load_wall_seconds": 61.0})) + "wal": bench.WAL_CONFIGS[config], "metrics_scraped": True, "sweep_value": int(value[0]) if value else None, + "env": {"GREPTIMEDB_OSWAL_MAX_IN_FLIGHT_CREATES": value[0]} if value else {}, + "exit_code": exit_code, "wal_device": "/dev/nvme1n1", "version": "1.4.0", "load_wall_seconds": 61.0} | extra)) if exit_code == 0: (path / "greptimedb-1" / "load-result.json").write_text(json.dumps({ "count_after": 6000, "load_seconds": 60.0, "rows_per_second": rows_per_second})) @@ -149,10 +196,36 @@ class SummaryTest(unittest.TestCase): d_cell = next(c for c in result["cells"] if c["id"] == "1-8-D") self.assertEqual(d_cell["creates_per_minute"], 120.0) self.assertEqual(d_cell["stalled_appends_total"], 3) - self.assertIn("| 1-8-D | 80 | 60.0 | 61.0 | 6,000 | 128.0 | 253.4 | 120 | 120.0 | 3 | 0 | 0 | 0 |", output) + self.assertIn("| 1-8-D | — | 80 | 60.0 | 61.0 | 128.0 / 253.4 | — / — | — / — | 120 | 120.0 | 3 | 0 | 0 | 0 | — | — |", output) r_cell = next(c for c in result["cells"] if c["id"] == "1-8-R") self.assertIsNone(r_cell["stalled_appends_total"]) + def test_sweep_ratios_cover_both_controls_and_restart_cells_report_recovery(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + restart = {"restart": True, "restart_scraped": True, "restart_seconds": 3.5, + "restart_query_seconds": 4.25, "restart_count": 6000, + "server_cpu_seconds": 122.0, "host_cpu_busy": 0.5, "host_cpus": 8} + self.write_cell(root, "1-8-R", 100.0) + self.write_cell(root, "1-8-R0", 125.0) + self.write_cell(root, "1-8-D-2", 50.0, metrics=ACK_BUCKETS, **restart) + self.write_cell(root, "1-8-D-16", 75.0) + (root / "cells" / "1-8-D-2" / "metrics-restart.prom").write_text( + "greptime_logstore_object_store_wal_recovery_seconds_sum 1.5\n" + "greptime_logstore_object_store_wal_recovery_seconds_count 1\n" + "greptime_logstore_object_store_wal_recovered_objects_total 118\n") + rows = [summary.load_cell(path) for path in sorted((root / "cells").iterdir())] + pairs = {(p["ratio"], p["sweep_value"]): p["geomean"] for p in summary.ratios(rows)} + self.assertEqual(pairs, {("D/R", 2): 0.5, ("D/R0", 2): 0.4, ("D/R", 16): 0.75, ("D/R0", 16): 0.6}) + cell = next(r for r in rows if r["id"] == "1-8-D-2") + self.assertEqual(cell["restart"], {"wall_seconds": 3.5, "query_seconds": 4.25, "rows": 6000, + "recovery_seconds": 1.5, "recovered_objects": 118}) + self.assertEqual(cell["server_cpu_cores"], 2.0) + output = summary.render({}, rows, summary.ratios(rows)) + self.assertIn("| 1-8-D-2 | MAX_IN_FLIGHT_CREATES=2 | 120 | 3.50 | 4.25 | 1.500 | 118 | 6,000 |", output) + self.assertIn("| 2.00 | 50% of 8 |", output) + self.assertIn("| 8 | D/R0 | 16 | 0.600 | 0.600 |", output) + def test_untouched_counters_are_zero_only_for_an_active_object_store_wal(self): with tempfile.TemporaryDirectory() as directory: root = Path(directory) @@ -205,16 +278,17 @@ case "$1" in done [[ "$FAKE_LOAD_RC" == 0 ]] || exit "$FAKE_LOAD_RC" mkdir -p "$results/greptimedb-1" - echo "{\"count_before\": 0, \"count_after\": $FAKE_ROWS, \"load_seconds\": 2, \"rows_per_second\": 3000}" \ + echo "{\"count_before\": 0, \"count_after\": $FAKE_ROWS, \"load_seconds\": 2, \"rows_per_second\": 3000, \"table\": \"agent_observations\"}" \ > "$results/greptimedb-1/load-result.json" ;; inspect) echo true ;; - exec) echo 'version: 1.4.0-test' ;; + exec) [[ "$*" == *cpu.stat* ]] && echo 'usage_usec 5000000' || echo 'version: 1.4.0-test' ;; logs) echo 'server log' ;; esac """ FAKE_CURL = r"""#!/usr/bin/env bash printf '%s\n' "curl $*" >> "$FAKE_LOG" for arg in "$@"; do + [[ "$arg" != */v1/sql* ]] || { echo "{\"output\": [{\"records\": {\"rows\": [[${FAKE_COUNT:-6000}]]}}]}"; exit 0; } [[ "$arg" != */metrics ]] || { [[ "$FAKE_METRICS_RC" == 0 ]] || exit "$FAKE_METRICS_RC" printf '%s\n' 'greptime_logstore_object_store_wal_poisoned_total 1' 'other_total 2'; exit 0; @@ -225,19 +299,20 @@ done class CellLifecycleTest(unittest.TestCase): # the run script against fake docker and curl - def run_cells(self, root, load_rc, metrics_rc=0): + def run_cells(self, root, load_rc, metrics_rc=0, restart=False, count=6000): bin_dir = root / "bin" bin_dir.mkdir() for name, body in (("docker", FAKE_DOCKER), ("curl", FAKE_CURL)): (bin_dir / name).write_text(body) (bin_dir / name).chmod(0o755) - plan = bench.build_plan("8", "6000", "1000", "1", smoke=False) - plan["cells"] = [cell for cell in plan["cells"] if cell["config"] != "R"] + plan = bench.build_plan("8", "6000", "1000", "1", smoke=False, configs="D,E", restart=restart, + extra_env="GREPTIMEDB_OSWAL_RECOVERY_CONCURRENCY=2") (root / "results").mkdir() (root / "results" / "plan.json").write_text(json.dumps(plan)) env = os.environ | { "PATH": f"{bin_dir}:{os.environ['PATH']}", "FAKE_LOG": str(root / "fake.log"), - "FAKE_LOAD_RC": str(load_rc), "FAKE_METRICS_RC": str(metrics_rc), "FAKE_ROWS": "6000", "PLAN": str(root / "results" / "plan.json"), + "FAKE_LOAD_RC": str(load_rc), "FAKE_METRICS_RC": str(metrics_rc), "FAKE_ROWS": "6000", "FAKE_COUNT": str(count), + "PLAN": str(root / "results" / "plan.json"), "RESULTS": str(root / "results"), "CORPUS_DIR": str(root / "corpus"), "OWNER": "o11ybench-oswal-1-1", "RUNTIME_IMAGE": "runtime@sha256:" + "b" * 64, "GREPTIMEDB_IMAGE": "greptimedb@sha256:" + "a" * 64, "RUN_PREFIX": "oswal-bench/1-1", "WAL_ROOT": str(root / "wal"), "S3_BUCKET": "bucket", @@ -302,6 +377,9 @@ class CellLifecycleTest(unittest.TestCase): # the run script against fake docke self.assertIn("GREPTIMEDB_STANDALONE__STORAGE__ROOT=oswal-bench/1-1/1-8-D", config) self.assertIn("GREPTIMEDB_STANDALONE__WAL__ACK_MODE=durable", config) self.assertIn("GREPTIMEDB_STANDALONE__STORAGE__SECRET_ACCESS_KEY=", config) + self.assertIn("GREPTIMEDB_OSWAL_RECOVERY_CONCURRENCY=2", config) + self.assertIn("-e GREPTIMEDB_OSWAL_RECOVERY_CONCURRENCY=2 ", log) + self.assertNotIn("docker kill", log) recorded = json.loads((cell / "cell.json").read_text()) self.assertEqual((recorded["exit_code"], recorded["version"], recorded["metrics_scraped"]), (0, "1.4.0-test", True)) @@ -313,6 +391,34 @@ class CellLifecycleTest(unittest.TestCase): # the run script against fake docke self.assertNotEqual(leaked.returncode, 0) self.assertFalse((root / "results").exists()) + def test_a_restart_cell_kills_restarts_and_counts_the_rows(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + cells, _, log, _ = self.run_cells(root, load_rc=0, restart=True) + self.assertEqual(cells.returncode, 0, cells.stdout + cells.stderr) + self.assertEqual(log.count("docker kill --signal KILL fakecid"), 2) + self.assertEqual(log.count("docker stop -t 120 fakecid"), 2) + self.assertIn("--name o11ybench-oswal-1-1-1-8-D-restart", log) + self.assertIn("sql=SELECT count(*) FROM agent_observations", log) + cell = root / "results" / "cells" / "1-8-D" + recorded = json.loads((cell / "cell.json").read_text()) + self.assertEqual((recorded["exit_code"], recorded["restart_count"], recorded["restart_scraped"]), (0, 6000, True)) + self.assertIsInstance(recorded["restart_seconds"], float) + config = (cell / "config.env").read_text().splitlines() + self.assertIn("GREPTIMEDB_STANDALONE__STORAGE__DATA_HOME=/oswal_home", config) + self.assertIn("GREPTIMEDB_STANDALONE__WAL__FLUSH_INTERVAL=10ms", config) + self.assertIn(f"type=bind,src={root}/wal/1-8-D-home,dst=/oswal_home", log) + for name in ("metrics.prom", "metrics-restart.prom", "server.log", "server-restart.log"): + self.assertTrue((cell / name).exists(), name) + + def test_a_restart_that_loses_rows_fails_the_cell(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + cells, _, _, _ = self.run_cells(root, load_rc=0, restart=True, count=5999) + self.assertNotEqual(cells.returncode, 0) + recorded = json.loads((root / "results" / "cells" / "1-8-D" / "cell.json").read_text()) + self.assertEqual((recorded["exit_code"], recorded["restart_count"]), (5, 5999)) + if __name__ == "__main__": unittest.main()