From 55eac3a4a156961241047b7e90e0809b8795828f Mon Sep 17 00:00:00 2001 From: jeremyhi Date: Tue, 13 Oct 2026 08:50:38 +0800 Subject: [PATCH] ci: fix the groups variable and report crash traffic per cycle GROUPS is a Bash array of the user's group ids, so the workflow passes the input as OSWAL_GROUPS. An idle window no longer counts toward the load's traffic, crash cycles report their own WAL traffic from a baseline scrape when their writers start, losses are reported per cycle beside the cumulative check, and a crash cycle that loses a metrics scrape after three attempts fails its cell. Signed-off-by: jeremyhi --- .github/scripts/oswal-s3-bench-crash.py | 24 ++-- .github/scripts/oswal-s3-bench-run.sh | 28 ++++- .github/scripts/oswal-s3-bench-summary.py | 84 ++++++++----- .github/workflows/oswal-s3-bench.yml | 6 +- tests/perf/test_oswal_s3_bench_scripts.py | 146 +++++++++++++++++++--- 5 files changed, 223 insertions(+), 65 deletions(-) diff --git a/.github/scripts/oswal-s3-bench-crash.py b/.github/scripts/oswal-s3-bench-crash.py index b1d564a7d47..f3db26444b9 100644 --- a/.github/scripts/oswal-s3-bench-crash.py +++ b/.github/scripts/oswal-s3-bench-crash.py @@ -109,14 +109,20 @@ def check_kill(directory: Path, writers: int, before_ns: int, after_ns: int, win "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() +def verify(run_dir: Path, found: dict, rows: int, enqueued: bool, cycle: int) -> dict: + """Checks the table, read as batch -> row count, against every cycle's writers so far, and + counts what the given cycle's writers acknowledged, left and lost on their own.""" + acked, stripes, cycle_attempted, cycle_acked = [], collections.OrderedDict(), set(), set() for cycle_dir in sorted(run_dir.glob("cycle-*"), key=lambda p: int(p.name.split("-")[1])): + current = cycle_dir.name == f"cycle-{cycle}" for path in sorted(cycle_dir.glob("attempted-*.log")): stripes[(cycle_dir.name, path.name)] = [int(seq) for (seq,) in lines(path)] + if current: + cycle_attempted.update(stripes[(cycle_dir.name, path.name)]) for path in sorted(cycle_dir.glob("acked-*.log")): acked += [int(seq) for (seq,) in lines(path)] + if current: + cycle_acked.update(int(seq) for (seq,) in lines(path)) acked_set = set(acked) attempted = {seq for stripe in stripes.values() for seq in stripe} errors = [] @@ -147,8 +153,12 @@ def verify(run_dir: Path, found: dict, rows: int, enqueued: bool) -> dict: 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} + present = set(found) & cycle_attempted + return {"cycle_acked_batches": len(cycle_acked), "cycle_present_batches": len(present), + "cycle_lost_batches": len(cycle_acked - present), "cycle_lost_rows": len(cycle_acked - present) * rows, + "cycle_extra_batches": len(present - cycle_acked), + "total_found_batches": len(found), "total_acked_batches": len(acked_set), + "total_lost_batches": len(missing), "total_extra_batches": len(extra), "verify_errors": errors} def main() -> int: @@ -175,9 +185,7 @@ def main() -> int: 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")) + args.mode == "enqueued", args.cycle) result["passed"] = not result["kill_errors"] and not result["verify_errors"] print(json.dumps(result)) return 0 if result["passed"] else 1 diff --git a/.github/scripts/oswal-s3-bench-run.sh b/.github/scripts/oswal-s3-bench-run.sh index 4696c8e3d8e..5c12c2be27e 100644 --- a/.github/scripts/oswal-s3-bench-run.sh +++ b/.github/scripts/oswal-s3-bench-run.sh @@ -73,6 +73,13 @@ scrape_metrics() { case "$phase" in "") metrics_scraped=true ;; -restart) restart_scraped=true ;; esac } +# A crash cycle cannot repeat a scrape once its server is killed, so it retries. +scrape_retry() { + local attempt + for attempt in 1 2 3; do scrape_metrics && return 0; sleep 1; done + return 1 +} + 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())'; } @@ -146,6 +153,7 @@ sample_objects() { # 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 + local load_start complete sql_url=${OSWAL_SQL_URL:-http://127.0.0.1:4000/v1/sql?db=public} 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 @@ -154,14 +162,17 @@ crash_cycles() { 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' \ + cdir="$dir/cycle-$cycle" complete=true; mkdir -p "$cdir" + # The counters of this server process before its writers start are the cycle's baseline. + phase=-start-$cycle; scrape_retry || complete=false + load_start=$(now_ns) + python3 "$here/oswal-s3-bench-crash.py" write --dir "$cdir" --url "$sql_url" \ --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 + phase=-cycle-$cycle; scrape_retry || complete=false 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=; } @@ -174,7 +185,7 @@ crash_cycles() { sleep 0.2 done query_s=$(elapsed "$started") - scrape_metrics || true + scrape_retry || complete=false 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]') @@ -184,9 +195,14 @@ crash_cycles() { --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" + --argjson load "$(awk -v a="$load_start" -v b="$before" 'BEGIN {printf "%.3f", (b - a) / 1e9}')" \ + --argjson complete "$complete" \ + '. + {kill_after_seconds: ($delay | tonumber), load_seconds: $load, restart_seconds: ($restart | tonumber), + restart_query_seconds: ($query | tonumber), pin_rows: $pin, metrics_complete: $complete}' \ + "$cdir/check.json" >> "$dir/cycles.jsonl" ((verdict == 0)) || { echo "$id: cycle $cycle failed its check" >&2; exit 6; } + # A cycle without its scrapes is not a measurement, whatever the table held. + [[ "$complete" == true ]] || { echo "$id: cycle $cycle lost a metrics scrape" >&2; exit 4; } next=$(cat "$cdir"/attempted-*.log | sort -n | tail -1); next=$((next + 1)) done } diff --git a/.github/scripts/oswal-s3-bench-summary.py b/.github/scripts/oswal-s3-bench-summary.py index c11b6c86192..66114f868f8 100644 --- a/.github/scripts/oswal-s3-bench-summary.py +++ b/.github/scripts/oswal-s3-bench-summary.py @@ -82,14 +82,34 @@ def interval_seconds(wal: dict) -> float: return float(value[:-2]) / 1000 if value.endswith("ms") else float(value.rstrip("s")) -def crash_cycles(path: Path) -> list: +def traffic(end: dict, start: dict, seconds, wal: dict) -> dict: + """WAL traffic between two scrapes of one process over `seconds`; more objects than seal + ticks, or objects near the 8 MiB threshold, mean batches sealed on size rather than on the timer.""" + def delta(name): + value = end["samples"].get(name) + return None if value is None else value - start["samples"].get(name, 0) + created, written, objects = delta("created_objects_total"), delta("object_bytes_sum"), delta("object_bytes_count") + per_second = created / seconds if created and seconds else None + mean = written / objects if written and objects else None + return {"wal_mb_per_second": written / seconds / 1e6 if written and 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(wal) or (mean or 0) >= 0.9 * 8 * 2**20, + "requests": {op: n - start["requests"].get(op, 0) for op, n in end["requests"].items() + if n != start["requests"].get(op, 0)}} + + +def crash_cycles(path: Path, wal: dict) -> 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"] + start = read_metrics(path / f"metrics-start-{cycle['cycle']}.prom") + killed = read_metrics(path / f"metrics-cycle-{cycle['cycle']}.prom") + before = killed["samples"] after = read_metrics(path / f"metrics-restart-{cycle['cycle']}.prom") once = after["samples"].get("recovery_seconds_count") == 1 + cycle |= traffic(killed, start, cycle.get("load_seconds"), wal) 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, @@ -104,7 +124,9 @@ def load_cell(path: Path, spec: dict | None = None) -> dict: 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, restarted = read_metrics(path / "metrics.prom"), read_metrics(path / "metrics-restart.prom") + final, restarted = read_metrics(path / "metrics.prom"), read_metrics(path / "metrics-restart.prom") + # With an idle window the scrape taken when the load ended describes the load. + metrics = read_metrics(path / "metrics-idle.prom") if cell.get("idle_seconds") else final load_seconds = result.get("load_seconds") wall, cpu = cell.get("load_wall_seconds"), cell.get("server_cpu_seconds") row = { @@ -140,25 +162,15 @@ 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"]} + row |= traffic(metrics, {"samples": {}, "requests": {}}, load_seconds, cell.get("wal", {})) + row["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)}} + idle = traffic(final, metrics, cell["idle_seconds"], cell.get("wal", {})) + end = final["samples"].get("created_objects_total") + row["idle"] = {"seconds": cell["idle_seconds"], "requests": idle["requests"], + "creates": None if end is None else end - metrics["samples"].get("created_objects_total", 0)} if row["mode"] == "crash": - row["cycles"] = crash_cycles(path) + row["cycles"] = crash_cycles(path, cell.get("wal", {})) 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()] @@ -244,21 +256,33 @@ def render(run: dict, rows: list, pairs: list) -> str: 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 |", + lines += ["", "| Cell | Cycle | Kill after s | Acked | Present | Lost | Lost rows | Extra | In flight " + "| All found | All acked | All lost | Indexed at kill | Restart to /health s | Recovery s " + "| Recovered objects | Pin rows | Verdict |", "| --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: " - "| ---: | --- |"] + "| ---: | ---: | ---: | --- |"] for r in crashes: for c in r["cycles"] or [{}]: + verdict = "—" if not c else "FAIL: " + "; ".join(c.get("kill_errors", []) + c.get("verify_errors", [])) \ + if not c.get("passed") else "pass" if c.get("metrics_complete", True) else "pass, scrape missing" 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", []))]) + " |") + fmt(c.get("cycle_acked_batches")), fmt(c.get("cycle_present_batches")), + fmt(c.get("cycle_lost_batches")), fmt(c.get("cycle_lost_rows")), fmt(c.get("cycle_extra_batches")), + fmt(c.get("in_flight")), fmt(c.get("total_found_batches")), fmt(c.get("total_acked_batches")), + fmt(c.get("total_lost_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")), verdict]) + " |") + lines += ["", "| Cell | Cycle | Load s | WAL MB/s | Objects/s | Mean object MiB | Sealed on size " + "| Requests until the kill | Requests of the restart |", + "| --- | ---: | ---: | ---: | ---: | ---: | --- | --- | --- |"] + for r in crashes: + for c in r["cycles"]: + lines.append(" | ".join([ + f"| {r['id']}", fmt(c["cycle"]), fmt(c.get("load_seconds"), 1), fmt(c["wal_mb_per_second"], 1), + fmt(c["objects_per_second"], 1), fmt(c["mean_object_bytes"], 2, 1 / 2**20), + "—" if c["sealed_on_size"] is None else ("yes" if c["sealed_on_size"] else "no"), + operations(c["requests"]), operations(c["restart_requests"])]) + " |") 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 |", diff --git a/.github/workflows/oswal-s3-bench.yml b/.github/workflows/oswal-s3-bench.yml index 6c7d37b4b3d..c9407f57af3 100644 --- a/.github/workflows/oswal-s3-bench.yml +++ b/.github/workflows/oswal-s3-bench.yml @@ -76,7 +76,7 @@ env: EXTRA_ENV: ${{ inputs.extra_env }} SWEEP: ${{ inputs.sweep }} RESTART: ${{ inputs.restart }} - GROUPS: ${{ inputs.groups }} + OSWAL_GROUPS: ${{ inputs.groups }} REQUESTED_INSTANCE_TYPE: ${{ inputs.instance_type }} CONCURRENCY: ${{ inputs.concurrency }} ROWS: ${{ inputs.rows }} @@ -107,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" --groups "$GROUPS" \ + --configs "$CONFIGS" --extra-env "$EXTRA_ENV" --sweep "$SWEEP" --restart "$RESTART" --groups "$OSWAL_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 @@ -193,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" --groups "$GROUPS" + --configs "$CONFIGS" --extra-env "$EXTRA_ENV" --sweep "$SWEEP" --restart "$RESTART" --groups "$OSWAL_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 35f5f874b4d..ad3d2796732 100644 --- a/tests/perf/test_oswal_s3_bench_scripts.py +++ b/tests/perf/test_oswal_s3_bench_scripts.py @@ -23,6 +23,7 @@ import sys import re import tempfile import unittest +import urllib.parse from pathlib import Path from types import SimpleNamespace @@ -160,6 +161,18 @@ class PlanTest(unittest.TestCase): self.assertEqual((pin["cycles"], pin["kill_after"]), (1, [60, 60])) self.assertEqual([c["rows"] for c in smoke["corpora"]], [50_000]) + def test_the_workflow_passes_groups_through_bash_unchanged(self): + workflow = (SCRIPTS.parent / "workflows" / "oswal-s3-bench.yml").read_text() + self.assertIn("OSWAL_GROUPS: ${{ inputs.groups }}", workflow) + self.assertEqual(workflow.count('--groups "$OSWAL_GROUPS"'), 2) + command = (f'python3 "{SCRIPTS}/oswal-s3-bench.py" plan --smoke false --concurrency 8 --rows 6000 ' + '--batch-rows 1000 --rounds 1 --groups "$OSWAL_GROUPS"') + for groups, expected in (("", "3 cells"), ('[{"name": "a", "configs": "D,E"}]', "2 cells")): + done = subprocess.run(["bash", "-c", command], env=os.environ | {"OSWAL_GROUPS": groups}, + capture_output=True, text=True, timeout=60) + self.assertEqual(done.returncode, 0, done.stderr) + self.assertTrue(done.stdout.startswith(expected), done.stdout) + 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"}], @@ -225,14 +238,14 @@ class CrashOracleTest(unittest.TestCase): 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") + return result | crash.verify(root, found, 10, mode == "enqueued", 1) 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)) + self.assertEqual((result["in_flight"], result["writers_at_kill"], result["cycle_extra_batches"], + result["cycle_lost_batches"], result["cycle_present_batches"]), (2, 2, 1, 0, 4)) 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}, @@ -246,7 +259,19 @@ class CrashOracleTest(unittest.TestCase): 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)) + self.assertEqual((result["cycle_lost_batches"], result["cycle_lost_rows"], result["total_lost_batches"]), + (2, 20, 2)) + + def test_a_later_cycle_reports_only_its_own_losses(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + crash_cycle(root, 1, self.STRIPES, self.ACKED, self.REQUESTS, (106, 102)) + crash_cycle(root, 2, ([10, 12], [11]), ([10], [11]), (["10 200 210", "12 000 305"], ["11 200 215"]), + (306, 302)) + # Cycle 1 lost batches 1 and 2; cycle 2 lost nothing. + result = crash.verify(root, {0: 10, 10: 10, 11: 10}, 10, True, 2) + self.assertEqual((result["cycle_acked_batches"], result["cycle_lost_batches"], + result["total_lost_batches"], result["total_acked_batches"]), (2, 0, 2, 5)) def test_a_connection_lost_before_the_kill_fails(self): with tempfile.TemporaryDirectory() as directory: @@ -286,8 +311,8 @@ class CrashOracleTest(unittest.TestCase): 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)) + result = crash.verify(run, found, 3, False, 1) + self.assertEqual((result["verify_errors"], result["total_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)) @@ -377,26 +402,34 @@ class SummaryTest(unittest.TestCase): "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")) + # The final scrape follows a 180 s idle window that created 2 objects of 1 MB. + self.write_cell(root, "1-32-E", 90.0, idle_seconds=180, group="", metrics=traffic.replace( + " 600\n", " 602\n", 1).replace("3000000000", "3002000000").replace("count 600", "count 602") + .replace("} 650", "} 652")) + (root / "cells" / "1-32-E" / "metrics-idle.prom").write_text(traffic.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}}) + self.assertEqual(cell["idle"], {"seconds": 180, "creates": 2, "requests": {"write": 4}}) 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") + "cycle": 1, "kill_after_seconds": 540.0, "load_seconds": 540.0, "cycle_acked_batches": 4000, + "cycle_present_batches": 4003, "cycle_lost_batches": 0, "cycle_lost_rows": 0, "cycle_extra_batches": 3, + "in_flight": 8, "total_found_batches": 4003, "total_acked_batches": 4000, "total_lost_batches": 0, + "restart_seconds": 4.5, "pin_rows": 1, "passed": True, "metrics_complete": True, + "kill_errors": [], "verify_errors": []}) + "\n") + (path / "metrics-start-1.prom").write_text("greptime_logstore_object_store_wal_created_objects_total 1\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") + "greptime_logstore_object_store_wal_created_objects_total 5401\n" + "greptime_logstore_object_store_wal_object_bytes_sum 10800000000\n" + "greptime_logstore_object_store_wal_object_bytes_count 5400\n" + 'opendal_operation_duration_seconds_count{operation="write"} 9000\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" @@ -404,9 +437,10 @@ class SummaryTest(unittest.TestCase): (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("| 1-32-E | 50.0 | 10.0 | 4.77 | no | read 40, write 648 | — | 180 | 2 | write 4 |", output) + self.assertIn("| pin-1-8-D | 1 | 540.0 | 4,000 | 4,003 | 0 | 0 | 3 | 8 | 4,003 | 4,000 | 0 | 5,400 " + "| 4.50 | 2.500 | 5,399 | 1 | pass |", output) + self.assertIn("| pin-1-8-D | 1 | 540.0 | 20.0 | 10.0 | 1.91 | no | write 9,000 | — |", 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): @@ -455,7 +489,7 @@ FAKE_DOCKER = r"""#!/usr/bin/env bash printf '%s\n' "docker $*" >> "$FAKE_LOG" case "$1" in run) - for arg in "$@"; do [[ "$arg" != -d ]] || { 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 ]] || { 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 @@ -463,6 +497,7 @@ case "$1" in mkdir -p "$results/greptimedb-1" echo "{\"count_before\": 0, \"count_after\": $FAKE_ROWS, \"load_seconds\": 2, \"rows_per_second\": 3000, \"table\": \"agent_observations\"}" \ > "$results/greptimedb-1/load-result.json" ;; + 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' ;; @@ -470,6 +505,12 @@ esac """ FAKE_CURL = r"""#!/usr/bin/env bash printf '%s\n' "curl $*" >> "$FAKE_LOG" +for arg in "$@"; do + [[ "$arg" != *"GROUP BY seq"* ]] || { python3 -c 'import collections, json, sys +counts = collections.Counter(int(l) for l in open(sys.argv[1]) if l.strip()) +print(json.dumps({"output": [{"records": {"rows": [[k, v * int(sys.argv[2])] for k, v in counts.items()]}}]}))' \ + "$FAKE_FOUND" "$FAKE_BATCH_ROWS"; exit 0; } +done for arg in "$@"; do [[ "$arg" != */v1/sql* ]] || { echo "{\"output\": [{\"records\": {\"rows\": [[${FAKE_COUNT:-6000}]]}}]}"; exit 0; } [[ "$arg" != */metrics ]] || { @@ -606,6 +647,75 @@ 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): + """A crash cell against fake docker and a stub SQL endpoint that the fake kill takes down.""" + import http.server + import threading + flag, found = root / "killed", root / "found.log" + found.write_text("") + lock = threading.Lock() + + class Handler(http.server.BaseHTTPRequestHandler): + def do_POST(self): + body = urllib.parse.unquote_plus(self.rfile.read(int(self.headers["Content-Length"])).decode()) + if flag.exists(): + self.close_connection = True + self.connection.close() + return + 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.end_headers() + + def log_message(self, *args): + pass + + class Server(http.server.ThreadingHTTPServer): + request_queue_size = 64 # all eight writers connect at once + + server = Server(("127.0.0.1", 0), Handler) + threading.Thread(target=server.serve_forever, daemon=True).start() + groups = json.dumps([{"name": "crash", "configs": "D", "mode": "crash", "cycles": 2, "kill_after": [1, 1]}]) + old = os.environ.copy() + os.environ.update({"OSWAL_SQL_URL": f"http://127.0.0.1:{server.server_port}/v1/sql", + "FAKE_KILL_FLAG": str(flag), "FAKE_FOUND": str(found), "FAKE_BATCH_ROWS": "1000"}) + try: + return self.run_cells(root, load_rc=0, metrics_rc=metrics_rc, groups=groups) + finally: + os.environ.clear() + os.environ.update(old) + server.shutdown() + server.server_close() + + 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) + self.assertEqual(cells.returncode, 0, cells.stdout + cells.stderr) + cell = root / "results" / "cells" / "crash-1-8-D" + 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: + self.assertTrue(c["passed"] and c["metrics_complete"], c) + self.assertEqual((c["cycle_lost_batches"], c["writers_at_kill"]), (0, 8)) + self.assertGreater(c["cycle_acked_batches"], 0) + 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"): + self.assertTrue((cell / name).exists(), name) + + def test_a_crash_cycle_without_its_scrapes_fails_the_cell(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + cells, _, _, _ = self.run_crash(root, metrics_rc=22) + self.assertNotEqual(cells.returncode, 0) + cell = root / "results" / "cells" / "crash-1-8-D" + cycle = json.loads((cell / "cycles.jsonl").read_text().splitlines()[0]) + self.assertEqual((cycle["passed"], cycle["metrics_complete"]), (True, False)) + self.assertEqual(json.loads((cell / "cell.json").read_text())["exit_code"], 4) + def test_a_restart_that_loses_rows_fails_the_cell(self): with tempfile.TemporaryDirectory() as directory: root = Path(directory)