From 8b05b26ca4bd233b9f1f2e0048c0b10a8cb606a6 Mon Sep 17 00:00:00 2001 From: jeremyhi Date: Thu, 15 Oct 2026 22:15:42 +0800 Subject: [PATCH] ci: keep each restart's replay and fail drop cells whose writers stop early A server's log is named after the phase it started in, so every crash cycle's restarted server keeps its own log and replay lines. Timed writers fail unless every writer ran to its deadline, and a drop cell stops before its drop when they do. Replay results keep every region with its WAL range, and the drop summary no longer reads a release counter from the restarted process. Signed-off-by: jeremyhi --- .github/scripts/oswal-s3-bench-crash.py | 21 +++++++-- .github/scripts/oswal-s3-bench-run.sh | 14 ++++-- .github/scripts/oswal-s3-bench-summary.py | 39 +++++++++------- tests/perf/test_oswal_s3_bench_scripts.py | 57 +++++++++++++++++------ 4 files changed, 93 insertions(+), 38 deletions(-) diff --git a/.github/scripts/oswal-s3-bench-crash.py b/.github/scripts/oswal-s3-bench-crash.py index 96d27bccfbc..92e7c5c3923 100644 --- a/.github/scripts/oswal-s3-bench-crash.py +++ b/.github/scripts/oswal-s3-bench-crash.py @@ -20,7 +20,8 @@ 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. -With `--seconds` the writers also stop once that long has passed. +With `--seconds` the writers also stop once that long has passed, and the +command fails unless every writer wrote until then without a failure. """ from __future__ import annotations @@ -51,7 +52,7 @@ def insert(url: str, table: str, seq: int, rows: int) -> str: return "000" -def writer(args, index: int, deadline: float) -> None: +def writer(args, index: int, deadline: float, failures: list) -> 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, \ @@ -63,6 +64,7 @@ def writer(args, index: int, deadline: float) -> None: requests.write(f"{seq} {code} {time.time_ns()}\n") requests.flush() if code != "200": + failures.append(f"writer {index}: batch {seq} ended with {code}") break acked.write(f"{seq}\n") acked.flush() @@ -73,11 +75,24 @@ def writer(args, index: int, deadline: float) -> None: def write(args) -> int: os.makedirs(args.dir, exist_ok=True) deadline = time.monotonic() + args.seconds if args.seconds else float("inf") - threads = [threading.Thread(target=writer, args=(args, i, deadline)) for i in range(args.writers)] + failures = [] + + def run(index): + try: + writer(args, index, deadline, failures) + except Exception as error: + failures.append(f"writer {index}: {error!r}") + raise + + threads = [threading.Thread(target=run, args=(i,)) for i in range(args.writers)] for thread in threads: thread.start() for thread in threads: thread.join() + # Crash cells end their writers with a kill; timed writers must have run to the deadline. + if args.seconds and (failures or not any(lines(Path(args.dir) / f"acked-{i}.log") for i in range(args.writers))): + print("; ".join(failures) or "no batch was acknowledged", file=sys.stderr) + return 1 return 0 diff --git a/.github/scripts/oswal-s3-bench-run.sh b/.github/scripts/oswal-s3-bench-run.sh index fcebe9d6610..2ae4f8f9162 100644 --- a/.github/scripts/oswal-s3-bench-run.sh +++ b/.github/scripts/oswal-s3-bench-run.sh @@ -93,7 +93,9 @@ elapsed() { awk -v a="$1" -v b="$(now)" 'BEGIN {printf "%.3f", b - a}'; } 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; } +# A server's log is named after the phase it started in, whatever phase stops it. start_server() { + server_phase=$phase 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[@]}"} \ @@ -114,7 +116,7 @@ stop_server() { killed) docker wait "$cid" >/dev/null ;; *) docker stop -t 120 "$cid" >/dev/null ;; esac - docker logs "$cid" > "$dir/server$phase.log" 2>&1 + docker logs "$cid" > "$dir/server$server_phase.log" 2>&1 docker rm -fv "$cid" >/dev/null cid= } @@ -234,7 +236,8 @@ drop_restart() { sql "CREATE TABLE dropped (seq BIGINT, ts TIMESTAMP TIME INDEX) WITH (append_mode = 'true')" >/dev/null sql "CREATE TABLE kept (seq BIGINT, ts TIMESTAMP TIME INDEX) WITH (append_mode = 'true')" >/dev/null python3 "$here/oswal-s3-bench-crash.py" write --dir "$dir/dropped" --url "$sql_url" --table dropped \ - --writers "$writers" --first-seq 0 --rows "$rows" --seconds "$seconds" + --writers "$writers" --first-seq 0 --rows "$rows" --seconds "$seconds" \ + || { echo "$id: the writers of dropped stopped before $seconds s" >&2; exit 10; } phase=-written; scrape_retry indexed_objects || { echo "$id: metrics scrape failed" >&2; exit 4; } sql "DROP TABLE dropped" >/dev/null stop_server kill @@ -244,13 +247,14 @@ drop_restart() { scrape_retry recovery_seconds_count || { echo "$id: metrics scrape failed" >&2; exit 4; } recovered=$(awk '/^greptime_logstore_object_store_wal_recovered_objects_total / {print $2}' "$dir/metrics-restart.prom") python3 "$here/oswal-s3-bench-crash.py" write --dir "$dir/kept" --url "$sql_url" --table kept \ - --writers 1 --first-seq 0 --rows "$rows" --seconds 2 + --writers 1 --first-seq 0 --rows "$rows" --seconds 2 \ + || { echo "$id: the writer of kept stopped before 2 s" >&2; exit 10; } sql "ADMIN FLUSH_TABLE('kept')" >/dev/null # The flushed watermark becomes durable with the next object, so every sample writes one row. deadline=$((SECONDS + ${OSWAL_COLLECT_SECONDS:-120})) while :; do sql "INSERT INTO kept VALUES (-1, $SECONDS)" >/dev/null - # The samples have their own file; the final scrape and the log keep the restart's name. + # The samples have their own file; the final scrape keeps the restart's name. phase=-collected scrape_retry indexed_objects || { phase=-restart; echo "$id: metrics scrape failed" >&2; exit 4; } phase=-restart @@ -296,7 +300,7 @@ 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= home_dir= version= load_seconds= metrics_scraped=false id= phase= + spec=$1 cid= wal_dir= home_dir= version= load_seconds= metrics_scraped=false id= phase= server_phase= restart_scraped=false restart_seconds= restart_query_seconds= restart_count= server_cpu_seconds= host_cpu_busy= indexed_before_kill= local concurrency setting started cpu_before host_before host_after corpus partitions load script diff --git a/.github/scripts/oswal-s3-bench-summary.py b/.github/scripts/oswal-s3-bench-summary.py index 3e4ee78d3ed..c0d4fc19f40 100644 --- a/.github/scripts/oswal-s3-bench-summary.py +++ b/.github/scripts/oswal-s3-bench-summary.py @@ -96,18 +96,25 @@ def replay(log: Path, metrics: dict) -> dict | None: regions = [] for match in REPLAY.finditer(log.read_text(errors="replace")): region, provider, rows, first, last, elapsed, unit = match.groups() - if int(rows): - objects = (int(last) >> POSITION_BITS) - (int(first) >> POSITION_BITS) + 1 \ - if provider == "ObjectStore" else None - regions.append({"region": int(region), "rows": int(rows), "seconds": float(elapsed) * UNITS[unit], - "objects": objects}) + # The range runs from the first entry to replay to the last one; it is empty when first > last. + objects = None if provider != "ObjectStore" else 0 if int(first) > int(last) else \ + (int(last) >> POSITION_BITS) - (int(first) >> POSITION_BITS) + 1 + regions.append({"region": int(region), "rows": int(rows), "first_entry_id": int(first), + "last_entry_id": int(last), "seconds": float(elapsed) * UNITS[unit], "objects": objects}) samples = metrics["samples"] return {"regions": regions, "rows": sum(r["rows"] for r in regions), "seconds": max((r["seconds"] for r in regions), default=None), - "objects": sum(r["objects"] or 0 for r in regions) if regions and regions[0]["objects"] else None, + "objects": sum(r["objects"] for r in regions) if regions and regions[0]["objects"] is not None else None, "read_seconds": samples.get("read_seconds_sum"), "reads": samples.get("read_seconds_count")} +def replayed(regions: list) -> str: + """Each region that replayed rows: its rows, the objects of its range and its time.""" + return "; ".join(f"{r['region']}: {r['rows']:,} rows" + ( + f", objects {r['first_entry_id'] >> POSITION_BITS:,}–{r['last_entry_id'] >> POSITION_BITS:,}" + if r["objects"] else "") + f", {r['seconds']:.2f} s" for r in regions if r["rows"]) or "—" + + def client_latency(path: Path) -> tuple: """The 50th and 99th percentile of the loader's own time per write request.""" durations = [] @@ -124,7 +131,7 @@ def region_rows(path: Path) -> list | None: """Rows per region of a partitioned load cell, as the server reported them after the load.""" if not path.exists(): return None - return [int(row[2]) for row in json.loads(path.read_text())["output"][0]["records"]["rows"]] + return [int(row[2] or 0) for row in json.loads(path.read_text())["output"][0]["records"]["rows"]] def interval_seconds(wal: dict) -> float: @@ -239,7 +246,6 @@ def load_cell(path: Path, spec: dict | None = None) -> dict: "indexed_before_drop": written.get("indexed_objects"), "restart_seconds": cell.get("restart_seconds"), "recovered_objects": restarted_samples.get("recovered_objects_total"), - "release_records": restarted_samples.get("release_records_total"), "indexed_at_end": int(float(samples[-1][1])) if samples else None, "deleted_after_restart": restarted_samples.get("deleted_objects_total"), "seconds_to_collect": int(samples[-1][0]) - int(samples[0][0]) if samples else None, @@ -383,21 +389,22 @@ def render(run: dict, rows: list, pairs: list) -> str: replays += [(r["id"], fmt(c["cycle"]), c | {"wall_seconds": c.get("restart_seconds")}) for r in crashes for c in r["cycles"] if c.get("replay")] if replays: - lines += ["", "| Cell | Cycle | Restart to /health s | Recovery s | Recovered objects | Regions replayed " - "| Rows replayed | Objects replayed | Slowest region replay s | Read seconds (reads) |", - "| --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | --- |"] + lines += ["", "| Cell | Cycle | Restart to /health s | Recovery s | Recovered objects | Regions opened " + "| Rows replayed | Objects replayed | Slowest region replay s | Read seconds (reads) " + "| Regions with rows |", + "| --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | --- | --- |"] for cell, cycle, x in replays: y = x["replay"] lines.append(" | ".join([ f"| {cell}", cycle, fmt(x.get("wall_seconds"), 2), fmt(x.get("recovery_seconds"), 3), fmt(x.get("recovered_objects")), fmt(len(y["regions"])), fmt(y["rows"]), fmt(y["objects"]), - fmt(y["seconds"], 2), f"{fmt(y['read_seconds'], 2)} ({fmt(y['reads'])})"]) + " |") + fmt(y["seconds"], 2), f"{fmt(y['read_seconds'], 2)} ({fmt(y['reads'])})", + replayed(y["regions"])]) + " |") drops = [r for r in rows if r.get("drop")] if drops: lines += ["", "| Cell | Acked batches before the drop | Indexed before the drop | Restart to /health s " - "| Recovered objects | Release records | Indexed at the end | Deleted after the restart " - "| Seconds to collect | Verdict |", - "| --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | --- |"] + "| Recovered objects | Indexed at the end | Deleted after the restart | Seconds to collect | Verdict |", + "| --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | --- |"] for r in drops: x = r["drop"] # Objects the release already collected before the kill leave nothing to show. @@ -406,7 +413,7 @@ def render(run: dict, rows: list, pairs: list) -> str: "collected" if r["exit_code"] == 0 else "still indexed" lines.append(" | ".join([ f"| {label(r)}", fmt(x["acked_batches"]), fmt(x["indexed_before_drop"]), fmt(x["restart_seconds"], 2), - fmt(x["recovered_objects"]), fmt(x["release_records"]), fmt(x["indexed_at_end"]), + fmt(x["recovered_objects"]), fmt(x["indexed_at_end"]), fmt(x["deleted_after_restart"]), fmt(x["seconds_to_collect"]), verdict]) + " |") restarts = [r for r in rows if "restart" in r] if restarts: diff --git a/tests/perf/test_oswal_s3_bench_scripts.py b/tests/perf/test_oswal_s3_bench_scripts.py index 7bc64e0343a..f7f0243357e 100644 --- a/tests/perf/test_oswal_s3_bench_scripts.py +++ b/tests/perf/test_oswal_s3_bench_scripts.py @@ -364,11 +364,12 @@ class WriterDeadlineTest(unittest.TestCase): def test_writers_stop_at_the_deadline_with_every_batch_acknowledged(self): import http.server import threading + status = [200] class Handler(http.server.BaseHTTPRequestHandler): def do_POST(self): self.rfile.read(int(self.headers["Content-Length"])) - self.send_response(200) + self.send_response(status[0]) self.end_headers() def log_message(self, *args): @@ -379,13 +380,18 @@ class WriterDeadlineTest(unittest.TestCase): try: with tempfile.TemporaryDirectory() as directory: run = Path(directory) - crash.write(SimpleNamespace(dir=str(run / "cycle-1"), url=f"http://127.0.0.1:{server.server_port}/", - table="dropped", writers=2, first_seq=0, rows=2, seconds=0.3)) + args = SimpleNamespace(dir=str(run / "cycle-1"), url=f"http://127.0.0.1:{server.server_port}/", + table="dropped", writers=2, first_seq=0, rows=2, seconds=0.3) + self.assertEqual(crash.write(args), 0) result = crash.verify(run, {}, 2, True, 1) self.assertGreater(result["cycle_acked_batches"], 0) self.assertEqual(result["verify_errors"], []) for index in range(2): self.assertTrue((run / "cycle-1" / f"exit-{index}.log").exists()) + # A rejected batch ends a timed writer early, which fails the command. + status[0] = 503 + args.dir, args.seconds = str(run / "cycle-2"), 30 + self.assertEqual(crash.write(args), 1) finally: server.shutdown() server.server_close() @@ -560,7 +566,14 @@ class SummaryTest(unittest.TestCase): self.assertEqual((result["rows"], result["objects"], result["read_seconds"], result["reads"]), (12_625_005, 3158 + 1, 95.15, 3)) self.assertAlmostEqual(result["seconds"], 95.150155247) - self.assertEqual([r["region"] for r in result["regions"]], [4402341478400, 4402341478401]) + self.assertEqual([(r["region"], r["rows"], r["objects"]) for r in result["regions"]], + [(4398046511104, 0, 0), (4402341478400, 12_625_000, 3158), (4402341478401, 5, 1)]) + self.assertEqual((result["regions"][1]["first_entry_id"], result["regions"][1]["last_entry_id"]), + (4853858306, 8164212737)) + self.assertAlmostEqual(result["regions"][0]["seconds"], 60.581e-6) + self.assertEqual(summary.replayed(result["regions"]), + "4402341478400: 12,625,000 rows, objects 4,629–7,786, 95.15 s; " + "4402341478401: 5 rows, objects 7,786–7,786, 0.01 s") self.assertIsNone(summary.replay(path / "absent.log", metrics)) raft = log.replace("ObjectStore(", "RaftEngine(") (path / "server-restart.log").write_text(raft) @@ -579,15 +592,14 @@ class SummaryTest(unittest.TestCase): (path / "metrics-written.prom").write_text("greptime_logstore_object_store_wal_indexed_objects 300\n") (path / "metrics-restart.prom").write_text( "greptime_logstore_object_store_wal_recovered_objects_total 280\n" - "greptime_logstore_object_store_wal_release_records_total 1\n" "greptime_logstore_object_store_wal_deleted_objects_total 279\n") (path / "collected.tsv").write_text("100 281\n101 120\n104 2\n") cell = summary.load_cell(path) self.assertEqual(cell["drop"], {"acked_batches": 5, "indexed_before_drop": 300, "restart_seconds": 2.5, - "recovered_objects": 280, "release_records": 1, "indexed_at_end": 2, + "recovered_objects": 280, "indexed_at_end": 2, "deleted_after_restart": 279, "seconds_to_collect": 4}) output = summary.render({}, [cell], []) - self.assertIn("| drop-1-8-D | 5 | 300 | 2.50 | 280 | 1 | 2 | 279 | 4 | collected |", output) + self.assertIn("| drop-1-8-D | 5 | 300 | 2.50 | 280 | 2 | 279 | 4 | collected |", output) def test_untouched_counters_are_zero_only_for_an_active_object_store_wal(self): with tempfile.TemporaryDirectory() as directory: @@ -635,7 +647,7 @@ FAKE_DOCKER = r"""#!/usr/bin/env bash printf '%s\n' "docker $*" >> "$FAKE_LOG" case "$1" in run) - for arg in "$@"; do [[ "$arg" != -d ]] || { rm -f "${FAKE_KILL_FLAG:-/nonexistent}"; echo "keys=${GREPTIMEDB_STANDALONE__STORAGE__ACCESS_KEY_ID:+set}${GREPTIMEDB_STANDALONE__STORAGE__SECRET_ACCESS_KEY:+set}" >> "$FAKE_LOG"; echo fakecid; exit 0; }; done + for arg in "$@"; do [[ "$arg" != -d ]] || { echo $(($(cat "$FAKE_LOG.runs" 2>/dev/null || echo 0) + 1)) > "$FAKE_LOG.runs"; rm -f "${FAKE_KILL_FLAG:-/nonexistent}"; echo "keys=${GREPTIMEDB_STANDALONE__STORAGE__ACCESS_KEY_ID:+set}${GREPTIMEDB_STANDALONE__STORAGE__SECRET_ACCESS_KEY:+set}" >> "$FAKE_LOG"; echo fakecid; exit 0; }; done for arg in "$@"; do case "$arg" in type=bind,src=*,dst=/results) results=${arg#type=bind,src=}; results=${results%,dst=/results} ;; esac done @@ -646,7 +658,9 @@ case "$1" in kill) touch "${FAKE_KILL_FLAG:-/dev/null}" ;; inspect) echo true ;; exec) [[ "$*" == *cpu.stat* ]] && echo 'usage_usec 5000000' || echo 'version: 1.4.0-test' ;; - logs) echo 'server log' ;; + logs) echo 'server log' + # The rows a server replayed are its start number, so each log can be told apart. + [[ -z "${FAKE_REPLAY:-}" ]] || echo "INFO Replay WAL for region: 4398046511104(1024, 0), provider: ObjectStore(x), rows recovered: $(cat "$FAKE_LOG.runs"), replay from entry id: 1048577, last entry id: 2097153, total timeseries replayed: 1, elapsed: 1.5s" ;; esac """ FAKE_CURL = r"""#!/usr/bin/env bash @@ -804,7 +818,8 @@ class CellLifecycleTest(unittest.TestCase): # the run script against fake docke self.assertEqual(log.count("/metrics"), 2) self.assertIn(f"type=bind,src={root}/corpus/corpus-6000,dst=/work/corpus,readonly", log) - def run_crash(self, root, metrics_rc=0, pin=False, sample_rc=0, full_metrics="5", groups=None, env=None): + def run_crash(self, root, metrics_rc=0, pin=False, sample_rc=0, full_metrics="5", groups=None, env=None, + status=200): """A crash cell, or another group that writes through the crash writer, against fake docker and a stub SQL endpoint that the fake kill takes down.""" import http.server @@ -823,7 +838,7 @@ class CellLifecycleTest(unittest.TestCase): # the run script against fake docke seq = re.search(r"VALUES [(](\d+),", body).group(1) with lock, open(found, "a") as out: out.write(seq + "\n") - self.send_response(200) + self.send_response(status) self.end_headers() def log_message(self, *args): @@ -852,9 +867,12 @@ class CellLifecycleTest(unittest.TestCase): # the run script against fake docke def test_a_crash_cell_kills_restarts_and_checks_every_cycle(self): with tempfile.TemporaryDirectory() as directory: root = Path(directory) - cells, _, log, _ = self.run_crash(root) + cells, _, log, _ = self.run_crash(root, env={"FAKE_REPLAY": "1"}) self.assertEqual(cells.returncode, 0, cells.stdout + cells.stderr) cell = root / "results" / "cells" / "crash-1-8-D" + # Server 1 is loaded and killed; servers 2 and 3 are the restarts of cycles 1 and 2. + replays = [c["replay"]["rows"] for c in summary.load_cell(cell)["cycles"]] + self.assertEqual(replays, [2, 3]) cycles = [json.loads(line) for line in (cell / "cycles.jsonl").read_text().splitlines()] self.assertEqual([c["cycle"] for c in cycles], [1, 2]) for c in cycles: @@ -864,7 +882,8 @@ class CellLifecycleTest(unittest.TestCase): # the run script against fake docke self.assertEqual(log.count("docker kill --signal KILL fakecid"), 2) self.assertEqual(log.count("docker wait fakecid"), 2) self.assertIn("GREPTIMEDB_STANDALONE__STORAGE__DATA_HOME=/oswal_home", (cell / "config.env").read_text()) - for name in ("metrics-start-1.prom", "metrics-cycle-2.prom", "metrics-restart-2.prom", "server-cycle-1.log"): + for name in ("metrics-start-1.prom", "metrics-cycle-2.prom", "metrics-restart-2.prom", "server.log", + "server-restart-1.log", "server-restart-2.log"): self.assertTrue((cell / name).exists(), name) def test_failed_pinned_samples_are_missing_not_zero(self): @@ -948,10 +967,20 @@ class CellLifecycleTest(unittest.TestCase): # the run script against fake docke self.assertEqual(log.count("docker kill --signal KILL fakecid"), 1) self.assertTrue(list((cell / "dropped").glob("acked-*.log"))) self.assertTrue(list((cell / "kept").glob("acked-*.log"))) - for name in ("metrics-written.prom", "metrics-restart.prom", "server-written.log", + for name in ("metrics-written.prom", "metrics-restart.prom", "server.log", "server-restart.log", "collected.tsv"): self.assertTrue((cell / name).exists(), name) + def test_a_drop_cell_whose_writers_fail_stops_before_the_drop(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + groups = json.dumps([{"name": "drop", "mode": "drop", "configs": "D", "write_seconds": 1}]) + cells, _, log, _ = self.run_crash(root, full_metrics="2", groups=groups, status=503) + recorded = json.loads((root / "results" / "cells" / "drop-1-8-D" / "cell.json").read_text()) + self.assertEqual(recorded["exit_code"], 10, cells.stdout + cells.stderr) + self.assertNotIn("DROP TABLE", urllib.parse.unquote_plus(log)) + self.assertNotIn("docker kill", log) + def test_a_crash_cycle_without_its_scrapes_fails_the_cell(self): with tempfile.TemporaryDirectory() as directory: root = Path(directory)