diff --git a/.github/scripts/oswal-s3-bench-crash.py b/.github/scripts/oswal-s3-bench-crash.py index f3db26444b9..96d27bccfbc 100644 --- a/.github/scripts/oswal-s3-bench-crash.py +++ b/.github/scripts/oswal-s3-bench-crash.py @@ -20,6 +20,7 @@ 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. """ from __future__ import annotations @@ -50,12 +51,12 @@ def insert(url: str, table: str, seq: int, rows: int) -> str: return "000" -def writer(args, index: int) -> None: +def writer(args, index: int, deadline: float) -> None: directory, seq = Path(args.dir), args.first_seq + index with open(directory / f"attempted-{index}.log", "a") as attempted, \ open(directory / f"requests-{index}.log", "a") as requests, \ open(directory / f"acked-{index}.log", "a") as acked: - while True: + while time.monotonic() < deadline: attempted.write(f"{seq}\n") attempted.flush() code = insert(args.url, args.table, seq, args.rows) @@ -71,7 +72,8 @@ def writer(args, index: int) -> None: def write(args) -> int: os.makedirs(args.dir, exist_ok=True) - threads = [threading.Thread(target=writer, args=(args, i)) for i in range(args.writers)] + 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)] for thread in threads: thread.start() for thread in threads: @@ -170,6 +172,7 @@ def main() -> int: w.add_argument("--table", default="crash") for name in ("writers", "first-seq", "rows"): w.add_argument(f"--{name}", type=int, required=True) + w.add_argument("--seconds", type=float, default=0, help="stop after this long; 0 writes until a failure") c = commands.add_parser("check") c.add_argument("--run-dir", type=Path, required=True) c.add_argument("--cycle", type=int, required=True) diff --git a/.github/scripts/oswal-s3-bench-load.sh b/.github/scripts/oswal-s3-bench-load.sh new file mode 100644 index 00000000000..1748fb40d66 --- /dev/null +++ b/.github/scripts/oswal-s3-bench-load.sh @@ -0,0 +1,27 @@ +#!/usr/bin/env bash +# Runs inside the o11ybench runtime image: the load of scripts/agent-observability/greptimedb.sh +# with the same arguments plus the loader's --skip-create-table, for a table the cell created. +set -euo pipefail + +mkdir "/results/$RESULT_NAME" +mkdir -p /results/corpus +cp /work/corpus/summary.json /work/corpus/evidence.json /results/corpus/ +w="$PWD/workloads/logbench-agent-observability" +r="/results/$RESULT_NAME" +prepare_workers=${PREPARE_WORKERS:-$(python3 -c 'import sys; sys.path.insert(0, "scripts"); from benchmark_workers import effective_cpus; print(effective_cpus())')} +o11ybench-greptimedb-loader --workload logbench-agent-observability --prepare-workers "$prepare_workers" \ + --skip-create-table \ + --grpc-endpoint "$GRPC_ENDPOINT" --sql-endpoint "$ENDPOINT" \ + --database public --table agent_observations --batch-size "${GREPTIMEDB_BATCH_SIZE:-10000}" --write-mode stream --max-in-flight "${MAX_IN_FLIGHT:-1}" \ + --flush-table --request-timeout-seconds 900 \ + --schema "$w/schema.json" --physical-index-profiles "$w/physical-index-profiles.json" \ + --data /work/corpus/agent_observations.jsonl \ + --profile-summary /work/corpus/summary.json --evidence /work/corpus/evidence.json \ + --transcript-output "$r/load-transcript.jsonl" \ + --target-metadata-output "$r/target-metadata.json" \ + --greptimedb-image "$TARGET_IMAGE" --greptimedb-version "$TARGET_VERSION" \ + --greptimedb-digest "$TARGET_DIGEST" \ + --startup-input=standalone --startup-input=start \ + --startup-input=--http-addr=0.0.0.0:4000 \ + --startup-input=--grpc-bind-addr=0.0.0.0:4001 \ + > "$r/load-result.json" diff --git a/.github/scripts/oswal-s3-bench-run.sh b/.github/scripts/oswal-s3-bench-run.sh index 6fa329bf294..fcebe9d6610 100644 --- a/.github/scripts/oswal-s3-bench-run.sh +++ b/.github/scripts/oswal-s3-bench-run.sh @@ -224,6 +224,45 @@ crash_cycles() { done } +# Writes the table `dropped` for write_seconds, drops it and kills the server right +# away, while most of its objects are still indexed; restarts on the same prefix and +# data home, then writes and flushes the table `kept` and samples the indexed objects +# until the dropped table's objects are collected. +drop_restart() { + local writers rows seconds started deadline indexed recovered 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") seconds=$(jq -r .write_seconds <<< "$spec") + 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" + phase=-written; scrape_retry indexed_objects || { echo "$id: metrics scrape failed" >&2; exit 4; } + sql "DROP TABLE dropped" >/dev/null + stop_server kill + phase=-restart started=$(now) + start_server + restart_seconds=$(elapsed "$started") + 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 + 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. + phase=-collected + scrape_retry indexed_objects || { phase=-restart; echo "$id: metrics scrape failed" >&2; exit 4; } + phase=-restart + indexed=$(awk '/^greptime_logstore_object_store_wal_indexed_objects / {print $2}' "$dir/metrics-collected.prom") + printf '%s %s\n' "$(date +%s)" "$indexed" >> "$dir/collected.tsv" + # A start object, the newest object and kept's own may stay; the dropped table's go. + awk -v i="$indexed" -v r="${recovered:-0}" 'BEGIN {exit !(i <= 3 || 2 * i < r)}' && break + ((SECONDS < deadline)) || { echo "$id: $indexed of ${recovered:-?} recovered objects still indexed" >&2; exit 9; } + sleep 1 + done +} + finish() { local rc=$? trap - EXIT @@ -260,7 +299,7 @@ cell() { 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= indexed_before_kill= - local concurrency setting started cpu_before host_before host_after + local concurrency setting started cpu_before host_before host_after corpus partitions load script id=$(jq -r .id <<< "$spec"); concurrency=$(jq -r .concurrency <<< "$spec") dir="$RESULTS/cells/$id" name="$OWNER-$id" mkdir -p "$dir" @@ -269,7 +308,7 @@ cell() { "STORAGE__ROOT=$RUN_PREFIX/$id") [[ -z "${S3_CONTAINER_ENDPOINT:-}" ]] || settings+=("STORAGE__ENDPOINT=$S3_CONTAINER_ENDPOINT") # A restarted server needs the metadata the loaded one kept in its data home. - jq -e '.restart or .mode == "crash"' <<< "$spec" >/dev/null && settings+=(STORAGE__DATA_HOME=/oswal_home) + jq -e '.restart or .mode != "load"' <<< "$spec" >/dev/null && settings+=(STORAGE__DATA_HOME=/oswal_home) while IFS= read -r setting; do settings+=("$setting"); done \ < <(jq -r '.wal | to_entries[] | "WAL__\(.key)=\(.value)"' <<< "$spec") docker_env=() mounts=() @@ -293,7 +332,7 @@ cell() { else wal_device="s3://$S3_BUCKET/$RUN_PREFIX/$id/wal" fi - if jq -e '.restart or .mode == "crash"' <<< "$spec" >/dev/null; then + if jq -e '.restart or .mode != "load"' <<< "$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 @@ -302,18 +341,27 @@ cell() { version=$(docker exec "$cid" greptime --version | sed -n 's/^version: //p') [[ -n "$version" ]] if jq -e '.mode == "crash"' <<< "$spec" >/dev/null; then crash_cycles; return; fi + if jq -e '.mode == "drop"' <<< "$spec" >/dev/null; then drop_restart; return; fi + corpus="$CORPUS_DIR/corpus-$(jq -r .rows <<< "$spec")" partitions=$(jq -r '.partitions // 1' <<< "$spec") + # Only the load phase, run exactly as run-agent-observability.sh runs it, or with the + # loader writing into a table split into regions that the cell created first. + load=(scripts/agent-observability/greptimedb.sh load) script=() + if ((partitions > 1)); then + sql "$(python3 "$here/oswal-s3-bench.py" table --summary "$corpus/summary.json" --partitions "$partitions")" >/dev/null + load=(/work/oswal-s3-bench-load.sh) + script=(--mount "type=bind,src=$here/oswal-s3-bench-load.sh,dst=/work/oswal-s3-bench-load.sh,readonly") + fi cpu_before=$(server_cpu) host_before=$(host_cpu) started=$(now) - # Only the load phase, run exactly as run-agent-observability.sh runs it. runtime --name "$name-load" --network host \ - --mount "type=bind,src=$CORPUS_DIR/corpus-$(jq -r .rows <<< "$spec"),dst=/work/corpus,readonly" \ + --mount "type=bind,src=$corpus,dst=/work/corpus,readonly" ${script[@]+"${script[@]}"} \ --mount "type=bind,src=$dir,dst=/results" \ -e GRPC_ENDPOINT=127.0.0.1:4001 -e "DATA_PROFILE=$(jq -r .data_profile <<< "$spec")" -e RESULT_NAME=greptimedb-1 \ -e "ENDPOINT=http://127.0.0.1:4000/v1/sql?db=public&format=greptimedb_v1" \ -e "TARGET_IMAGE=$GREPTIMEDB_IMAGE" -e "TARGET_VERSION=$version" -e "TARGET_DIGEST=${GREPTIMEDB_IMAGE##*@}" \ -e "TARGET_ID=$name" -e TARGET_HOST=127.0.0.1 -e PREPARE_WORKERS= -e "MAX_IN_FLIGHT=$concurrency" \ -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 + "$RUNTIME_IMAGE" "${load[@]}" > "$dir/load.log" 2>&1 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}') @@ -322,6 +370,16 @@ cell() { '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 <<< "$spec")" '.count_before == 0 and .count_after == $rows' \ "$dir/greptimedb-1/load-result.json" >/dev/null + if ((partitions > 1)); then + # The server's own account of the rows each region took. + sql "SELECT p.partition_name, s.region_id, s.region_rows, s.written_bytes_since_open + FROM information_schema.partitions p JOIN information_schema.region_statistics s + ON p.greptime_partition_id = s.region_id + WHERE p.table_schema = 'public' AND p.table_name = 'agent_observations' + ORDER BY s.region_id" > "$dir/regions.json" + jq -e --argjson n "$partitions" '[.output[0].records.rows[] | select(.[2] > 0)] | length == $n' \ + "$dir/regions.json" >/dev/null || { echo "$id: fewer than $partitions regions took rows" >&2; exit 8; } + fi # An idle window: what the server sends with no writes, between two scrapes. if jq -e '.idle_seconds > 0' <<< "$spec" >/dev/null; then phase=-idle; scrape_metrics || { echo "$id: metrics scrape failed" >&2; exit 4; }; phase= diff --git a/.github/scripts/oswal-s3-bench-summary.py b/.github/scripts/oswal-s3-bench-summary.py index b64c6a16d1b..3e4ee78d3ed 100644 --- a/.github/scripts/oswal-s3-bench-summary.py +++ b/.github/scripts/oswal-s3-bench-summary.py @@ -29,6 +29,12 @@ COUNTERS = ("created_objects_total", "stalled_appends_total", "poisoned_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+)') +# Mito's line for every region it opened, with the WAL range it replayed. +REPLAY = re.compile(r"Replay WAL for region: (\d+)\(.*?provider: (\w+).*?rows recovered: (\d+), " + r"replay from entry id: (\d+), last entry id: (\d+),.*?elapsed: ([0-9.]+)(ns|µs|us|ms|s)\b") +UNITS = {"ns": 1e-9, "µs": 1e-6, "us": 1e-6, "ms": 1e-3, "s": 1.0} +# An object store WAL entry id is the object sequence above a 20-bit position. +POSITION_BITS = 20 def parse_metrics(text: str) -> dict: @@ -78,6 +84,49 @@ def read_metrics(path: Path) -> dict: return parse_metrics(path.read_text() if path.exists() else "") +def ratio(a, b): + return a / b if a is not None and b else None + + +def replay(log: Path, metrics: dict) -> dict | None: + """What a restarted server replayed: every region that had rows to replay, the objects of + its WAL range, and the log store's time serving region reads (`read_seconds`).""" + if not log.exists(): + return 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}) + 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, + "read_seconds": samples.get("read_seconds_sum"), "reads": samples.get("read_seconds_count")} + + +def client_latency(path: Path) -> tuple: + """The 50th and 99th percentile of the loader's own time per write request.""" + durations = [] + if path.exists(): + for line in path.read_text().splitlines(): + record = json.loads(line) if line.strip() else {} + if record.get("step") == "grpc_write_batch" and record.get("status") == "success": + durations.append(record["duration_seconds"]) + durations.sort() + return tuple(durations[max(0, math.ceil(q * len(durations)) - 1)] if durations else None for q in (0.5, 0.99)) + + +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"]] + + def interval_seconds(wal: dict) -> float: value = wal.get("FLUSH_INTERVAL", "100ms") return float(value[:-2]) / 1000 if value.endswith("ms") else float(value.rstrip("s")) @@ -115,7 +164,8 @@ def crash_cycles(path: Path, wal: dict) -> list: "indexed_before_kill": before.get("indexed_objects"), "recovery_seconds": after["samples"].get("recovery_seconds_sum") if once else None, "recovered_objects": after["samples"].get("recovered_objects_total", 0 if once else None), - "restart_requests": after["requests"]} + "restart_requests": after["requests"], + "replay": replay(path / f"server-restart-{cycle['cycle']}.log", after)} return cycles @@ -145,6 +195,13 @@ def load_cell(path: Path, spec: dict | None = None) -> dict: ("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) + row["client_p50"], row["client_p99"] = client_latency(path / "greptimedb-1" / "load-transcript.jsonl") + # An entry is one region's write; an append, counted only in the durable mode, carries one or more. + samples = metrics["samples"] + row["entries_per_object"] = ratio(samples.get("object_entries_sum"), samples.get("object_entries_count")) + row["appends_per_object"] = ratio(samples.get("append_ack_seconds_count"), samples.get("object_bytes_count")) + row["partitions"] = cell.get("partitions", 1) + row["region_rows"] = region_rows(path / "regions.json") if cell.get("restart"): # A restarted process observed exactly one recovery, so the sum is its duration. count = restarted["samples"].get("recovery_seconds_count") @@ -155,6 +212,7 @@ def load_cell(path: Path, spec: dict | None = None) -> dict: "recovered_objects": restarted["samples"].get("recovered_objects_total") if cell.get("restart_scraped") else None, "indexed_before_kill": cell.get("indexed_before_kill"), "min_objects": cell.get("min_objects", 0), + "replay": replay(path / "server-restart.log", restarted), } # 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. @@ -171,6 +229,21 @@ def load_cell(path: Path, spec: dict | None = None) -> dict: 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"] == "drop": + written = read_metrics(path / "metrics-written.prom")["samples"] + restarted_samples = restarted["samples"] + samples = [line.split() for line in (path / "collected.tsv").read_text().splitlines() + if line.strip()] if (path / "collected.tsv").exists() else [] + row["drop"] = { + "acked_batches": sum(len((p.read_text()).split()) for p in sorted((path / "dropped").glob("acked-*.log"))), + "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, + } if row["mode"] == "crash": row["cycles"] = crash_cycles(path, cell.get("wal", {})) if (path / "objects.tsv").exists(): @@ -296,6 +369,45 @@ def render(run: dict, rows: list, pairs: list) -> str: last = next((s for s in reversed(samples) if s[1] is not None), [None] * 4) lines.append(f"| {r['id']} | {', '.join('missing' if s[1] is None else str(s[1]) for s in samples)} " f"| {sum(s[1] is None for s in samples)} | {fmt(last[2])} | {fmt(last[3])} |") + details = [r for r in loads if any(r[k] is not None for k in ("client_p50", "entries_per_object", "region_rows"))] + if details: + lines += ["", "| Cell | Client p50 / p99 ms | Entries per object | Appends per object | Regions " + "| Rows per region min / max |", "| --- | ---: | ---: | ---: | ---: | ---: |"] + for r in details: + spread = r["region_rows"] or [] + lines.append(" | ".join([ + f"| {label(r)}", pair(r["client_p50"], r["client_p99"], 1, 1000), fmt(r["entries_per_object"], 1), + fmt(r["appends_per_object"], 2), fmt(len(spread) if spread else r["partitions"]), + pair(min(spread), max(spread)) if spread else "—"]) + " |") + replays = [(r["id"], "—", r["restart"]) for r in loads if r.get("restart", {}).get("replay")] + 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) |", + "| --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | --- |"] + 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'])})"]) + " |") + 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 |", + "| --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | --- |"] + for r in drops: + x = r["drop"] + # Objects the release already collected before the kill leave nothing to show. + verdict = "—" if x["indexed_at_end"] is None else \ + "nothing left at the kill" if (x["recovered_objects"] or 0) <= 3 else \ + "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["deleted_after_restart"]), fmt(x["seconds_to_collect"]), verdict]) + " |") restarts = [r for r in rows if "restart" in r] if restarts: lines += ["", "| Cell | Overrides | Objects created | Indexed at kill | Restart to /health s | Restart to count s " diff --git a/.github/scripts/oswal-s3-bench.py b/.github/scripts/oswal-s3-bench.py index 59a4d8cd83f..14980a9654d 100644 --- a/.github/scripts/oswal-s3-bench.py +++ b/.github/scripts/oswal-s3-bench.py @@ -29,6 +29,7 @@ import re import sys import time import urllib.request +from datetime import datetime from pathlib import Path SMOKE_ROWS = 50_000 @@ -44,9 +45,43 @@ WAL_CONFIGS = { 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} + "GREPTIMEDB_OSWAL_RECOVERY_CONCURRENCY": 64} # Restart cells seal ten times as often as the default so recovery has thousands of objects. RESTART_FLUSH_INTERVAL = "10ms" +# The loader's CREATE TABLE for the agent observability workload at the pinned runtime image. +AGENT_TABLE = """CREATE TABLE `agent_observations` ( + `event_time` TIMESTAMP(3) NOT NULL, + `biz_date` DATE NOT NULL, + `trace_id` STRING NOT NULL SKIPPING INDEX, + `session_id` STRING NOT NULL, + `observation_id` STRING NOT NULL SKIPPING INDEX, + `parent_observation_id` STRING NULL SKIPPING INDEX, + `seq_no` BIGINT NOT NULL, + `type` STRING NOT NULL INVERTED INDEX, + `status` STRING NOT NULL INVERTED INDEX, + `tenant` STRING NOT NULL, + `app` STRING NOT NULL, + `environment` STRING NOT NULL, + `task_category` STRING NULL, + `trace_archetype` STRING NULL, + `model` STRING NULL, + `tool_name` STRING NULL, + `input` STRING NULL FULLTEXT INDEX WITH(analyzer = 'English', backend = 'bloom', case_sensitive = 'false', granularity = '10240', false_positive_rate = '0.01'), + `output` STRING NULL FULLTEXT INDEX WITH(analyzer = 'English', backend = 'bloom', case_sensitive = 'false', granularity = '10240', false_positive_rate = '0.01'), + `input_tokens` BIGINT NULL, + `output_tokens` BIGINT NULL, + `total_cost` DOUBLE NULL, + `latency_ms` BIGINT NULL, + `payload` JSON2 NOT NULL, + TIME INDEX (`event_time`), + PRIMARY KEY (`tenant`, `app`, `environment`) +) +{partitions}ENGINE=mito +WITH( + append_mode = 'true', + 'compaction.type' = 'twcs', + 'compaction.twcs.time_window' = '2h' +)""" GROUP_NAME = re.compile(r"[a-z][a-z0-9]{0,11}") RESERVED_ENV = ("GREPTIMEDB_STANDALONE__STORAGE__", "GREPTIMEDB_STANDALONE__WAL__") ENV_NAME = re.compile(r"[A-Za-z_][A-Za-z0-9_]*") @@ -141,17 +176,34 @@ def check_depths(env: dict) -> None: raise ValueError(f"MAX_SEALED_BATCHES {sealed} is below MAX_IN_FLIGHT_CREATES {creates} plus 2") +def partitioned_table(summary: dict, partitions: int) -> str: + """The loader's table split into equal event_time ranges over the corpus window. The + generator draws event times uniformly from that window, so every range gets an equal + share of the rows and every batch writes to every region.""" + def millis(text): + return int(datetime.fromisoformat(text.replace("Z", "+00:00")).timestamp() * 1000) + start, end = millis(summary["start"]), millis(summary["end"]) + bounds = [start + (end - start) * i // partitions for i in range(1, partitions)] + if len(set(bounds)) != len(bounds) or not start < bounds[0]: + raise ValueError(f"the corpus window {summary['start']}..{summary['end']} is too short for {partitions} ranges") + ranges = [f"`event_time` < {bounds[0]}"] + ranges += [f"`event_time` >= {low} AND `event_time` < {high}" for low, high in zip(bounds, bounds[1:])] + ranges.append(f"`event_time` >= {bounds[-1]}") + clause = "PARTITION ON COLUMNS (`event_time`) (\n " + ",\n ".join(ranges) + "\n)\n" + return AGENT_TABLE.format(partitions=clause) + + def group_cells(group: dict, smoke: bool) -> list: """The cells of one group, in run order; a group without a name is the top-level inputs.""" name, mode = group.get("name", ""), group.get("mode", "load") - if mode not in ("load", "crash"): - raise ValueError(f"group {name!r}: mode must be load or crash, got {mode!r}") + if mode not in ("load", "crash", "drop"): + raise ValueError(f"group {name!r}: mode must be load, crash or drop, got {mode!r}") concurrency = str(group["concurrency"]) levels = [positive("concurrency", level.strip(), 256) for level in concurrency.split(",")] if len(set(levels)) != len(levels): raise ValueError(f"concurrency repeats a level: {concurrency!r}") chosen = [config.strip() for config in str(group["configs"]).split(",")] - allowed = set(WAL_CONFIGS) - (set(BASELINES) if mode == "crash" else set()) + allowed = set(WAL_CONFIGS) - (set(BASELINES) if mode != "load" else set()) if not chosen or len(set(chosen)) != len(chosen) or not set(chosen) <= allowed: raise ValueError(f"group {name!r}: configs must be distinct names among {', '.join(sorted(allowed))}, " f"got {group['configs']!r}") @@ -165,6 +217,9 @@ def group_cells(group: dict, smoke: bool) -> list: rounds = 1 if smoke else positive("rounds", str(group["rounds"]), 10) idle = int(group.get("idle_seconds", 0)) common = {"group": name, "mode": mode, "restart": restart, "idle_seconds": idle} + partitions = int(group.get("partitions", 1)) + if partitions != 1 and (mode != "load" or not 2 <= partitions <= 64): + raise ValueError(f"group {name!r}: partitions must be in 2..64 and needs mode load") if mode == "load": if not 0 <= idle <= 600: raise ValueError(f"group {name!r}: idle_seconds must be in 0..600") @@ -173,7 +228,14 @@ def group_cells(group: dict, smoke: bool) -> list: if min_objects < 0 or (min_objects and not restart): raise ValueError(f"group {name!r}: min_objects needs restart and must not be negative") common |= {"rows": rows, "data_profile": DATA_PROFILES.get(rows, "custom"), - "min_objects": 0 if smoke else min_objects} + "min_objects": 0 if smoke else min_objects, "partitions": partitions} + elif mode == "drop": + # Writes one table for write_seconds, drops it, kills and restarts the server, then + # writes and flushes another table and watches the dropped table's objects go. + write_seconds = int(group.get("write_seconds", 30)) + if not 1 <= write_seconds <= 600 or restart or idle: + raise ValueError(f"group {name!r}: write_seconds must be in 1..600, without restart or idle") + common |= {"write_seconds": min(write_seconds, 10) if smoke else write_seconds} else: cycles = int(group.get("cycles", 5)) kill_after = [int(v) for v in group.get("kill_after", [3, 10])] @@ -212,7 +274,8 @@ def parse_groups(text: str, defaults: dict) -> list: groups = json.loads(text) if not isinstance(groups, list) or not groups or not all(isinstance(g, dict) for g in groups): raise ValueError("groups must be a non-empty JSON list of objects") - known = set(defaults) | {"name", "mode", "idle_seconds", "cycles", "kill_after", "pin", "min_objects"} + known = set(defaults) | {"name", "mode", "idle_seconds", "cycles", "kill_after", "pin", "min_objects", + "partitions", "write_seconds"} names = [g.get("name") for g in groups] for group, name in zip(groups, names): if not isinstance(name, str) or not GROUP_NAME.fullmatch(name): @@ -334,6 +397,9 @@ def main() -> int: regions = commands.add_parser("regions") for name in ("bucket", "runner"): regions.add_argument(f"--{name}", required=True) + table = commands.add_parser("table") + table.add_argument("--summary", type=Path, required=True) + table.add_argument("--partitions", type=int, required=True) manifest = commands.add_parser("manifest") for name in ("results", "runtime-image", "instance-type", "region", "prefix"): manifest.add_argument(f"--{name}", required=True) @@ -359,6 +425,8 @@ def main() -> int: elif args.command == "regions": check_regions(args.bucket, args.runner) print(f"bucket and runner both in {args.runner}") + elif args.command == "table": + print(partitioned_table(json.loads(args.summary.read_text()), args.partitions)) elif args.command == "manifest": results = Path(args.results) manifest = build_manifest(json.loads((results / "plan.json").read_text()), diff --git a/.github/workflows/oswal-s3-bench.yml b/.github/workflows/oswal-s3-bench.yml index c9407f57af3..f8255fe347d 100644 --- a/.github/workflows/oswal-s3-bench.yml +++ b/.github/workflows/oswal-s3-bench.yml @@ -31,7 +31,7 @@ on: type: boolean default: false groups: - description: 'JSON list of cell groups, each overriding configs, sweep, extra_env, concurrency, rounds, rows, restart, plus idle_seconds, or mode crash with cycles, kill_after [min, max] and pin; empty = one group from the inputs above' + description: 'JSON list of cell groups, each overriding configs, sweep, extra_env, concurrency, rounds, rows, restart, plus idle_seconds and partitions (regions of the loaded table), or mode crash with cycles, kill_after [min, max] and pin, or mode drop with write_seconds; empty = one group from the inputs above' type: string default: '' instance_type: diff --git a/tests/perf/test_oswal_s3_bench_scripts.py b/tests/perf/test_oswal_s3_bench_scripts.py index 3af71531caa..7bc64e0343a 100644 --- a/tests/perf/test_oswal_s3_bench_scripts.py +++ b/tests/perf/test_oswal_s3_bench_scripts.py @@ -178,6 +178,33 @@ class PlanTest(unittest.TestCase): self.assertEqual(done.returncode, 0, done.stderr) self.assertTrue(done.stdout.startswith(expected), done.stdout) + def test_a_partitioned_group_and_a_drop_group(self): + groups = [{"name": "multi", "configs": "R,D", "concurrency": "8,32", "partitions": 8}, + {"name": "drop", "mode": "drop", "configs": "D", "rounds": 1, "write_seconds": 45}] + plan = bench.build_plan("8", "2000000", "1000", "1", smoke=False, groups=json.dumps(groups)) + cells = {c["id"]: c for c in plan["cells"]} + self.assertEqual(list(cells), ["multi-1-8-R", "multi-1-8-D", "multi-1-32-R", "multi-1-32-D", "drop-1-8-D"]) + self.assertEqual({c["partitions"] for c in plan["cells"] if c["mode"] == "load"}, {8}) + self.assertEqual((cells["drop-1-8-D"]["write_seconds"], cells["drop-1-8-D"]["mode"]), (45, "drop")) + self.assertNotIn("rows", cells["drop-1-8-D"]) + self.assertEqual([c["rows"] for c in plan["corpora"]], [2_000_000]) + smoke = bench.build_plan("8", "2000000", "1000", "1", smoke=True, groups=json.dumps(groups)) + self.assertEqual(next(c for c in smoke["cells"] if c["mode"] == "drop")["write_seconds"], 10) + self.assertEqual(bench.build_plan("8", "6000", "1000", "1", smoke=False)["cells"][0]["partitions"], 1) + + def test_the_partitioned_table_splits_the_corpus_window_into_equal_ranges(self): + ddl = bench.partitioned_table({"start": "2026-07-10T00:00:00Z", "end": "2026-07-10T01:00:00Z"}, 8) + start = 1783641600000 + bounds = [int(b) for b in re.findall(r"`event_time` < (\d+)", ddl)] + self.assertEqual(bounds, [start + 450_000 * i for i in range(1, 8)]) + self.assertIn(f"`event_time` >= {start + 450_000 * 7}\n)\nENGINE=mito", ddl) + self.assertEqual(ddl.count("`event_time` >="), 7) + self.assertTrue(ddl.startswith("CREATE TABLE `agent_observations` (")) + self.assertIn("PRIMARY KEY (`tenant`, `app`, `environment`)\n)\nPARTITION ON COLUMNS (`event_time`) (", ddl) + self.assertNotIn("{partitions}", ddl) + with self.assertRaises(ValueError): + bench.partitioned_table({"start": "2026-07-10T00:00:00Z", "end": "2026-07-10T00:00:00.004Z"}, 8) + 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"}], @@ -185,7 +212,12 @@ class PlanTest(unittest.TestCase): [{"name": "a", "mode": "crash", "configs": "D", "kill_after": [9, 5]}], [{"name": "a", "mode": "soak"}], [{"name": "a", "idle_seconds": 601}], [{"name": "a", "configs": "D", "min_objects": 6000}], - [{"name": "a", "configs": "D", "restart": True, "min_objects": -1}]): + [{"name": "a", "configs": "D", "restart": True, "min_objects": -1}], + [{"name": "a", "configs": "D", "partitions": 65}], [{"name": "a", "configs": "D", "partitions": 0}], + [{"name": "a", "mode": "crash", "configs": "D", "partitions": 8}], + [{"name": "a", "mode": "drop", "configs": "R"}], + [{"name": "a", "mode": "drop", "configs": "D", "write_seconds": 0}], + [{"name": "a", "mode": "drop", "configs": "D", "restart": True}]): with self.subTest(groups=groups), self.assertRaises(ValueError): bench.build_plan("8", "6000", "1000", "1", smoke=False, groups=json.dumps(groups)) @@ -312,7 +344,7 @@ class CrashOracleTest(unittest.TestCase): with tempfile.TemporaryDirectory() as directory: run = Path(directory) args = SimpleNamespace(dir=str(run / "cycle-1"), url=f"http://127.0.0.1:{server.server_port}/v1/sql", - table="crash", writers=2, first_seq=0, rows=3) + table="crash", writers=2, first_seq=0, rows=3, seconds=0) crash.write(args) found = {} for body in inserted: @@ -328,6 +360,37 @@ class CrashOracleTest(unittest.TestCase): server.server_close() +class WriterDeadlineTest(unittest.TestCase): + def test_writers_stop_at_the_deadline_with_every_batch_acknowledged(self): + import http.server + import threading + + class Handler(http.server.BaseHTTPRequestHandler): + def do_POST(self): + self.rfile.read(int(self.headers["Content-Length"])) + self.send_response(200) + self.end_headers() + + def log_message(self, *args): + pass + + server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler) + threading.Thread(target=server.serve_forever, daemon=True).start() + try: + with tempfile.TemporaryDirectory() as directory: + run = Path(directory) + 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)) + 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()) + finally: + server.shutdown() + server.server_close() + + class SummaryTest(unittest.TestCase): def test_quantile_interpolates_like_prometheus(self): buckets = summary.parse_metrics(ACK_BUCKETS)["buckets"]["append_ack_seconds"] @@ -396,7 +459,7 @@ class SummaryTest(unittest.TestCase): 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, - "indexed_before_kill": 117, "min_objects": 6000}) + "indexed_before_kill": 117, "min_objects": 6000, "replay": None}) 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 | 117 (under 6,000) | 3.50 | 4.25 | 1.500 | 118 " @@ -454,6 +517,78 @@ class SummaryTest(unittest.TestCase): 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, missing | 1 | 0 | 601 |", output) + def test_partitioned_load_cells_report_client_latency_entries_and_regions(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + metrics = (ACK_BUCKETS + "greptime_logstore_object_store_wal_object_entries_sum 4000\n" + "greptime_logstore_object_store_wal_object_entries_count 500\n" + "greptime_logstore_object_store_wal_object_bytes_count 500\n") + self.write_cell(root, "1-8-D", 80.0, metrics=metrics, partitions=8) + path = root / "cells" / "1-8-D" + transcript = [{"step": "create_table", "duration_seconds": 9.0}] + transcript += [{"step": "grpc_write_batch", "status": "success", "duration_seconds": d / 1000} + for d in range(1, 101)] + (path / "greptimedb-1" / "load-transcript.jsonl").write_text( + "".join(json.dumps(r) + "\n" for r in transcript)) + (path / "regions.json").write_text(json.dumps({"output": [{"records": {"rows": [ + [f"p{i}", 4398046511104 + i, 750 + i, 1000] for i in range(8)]}}]})) + cell = summary.load_cell(path) + self.assertEqual((cell["client_p50"], cell["client_p99"]), (0.05, 0.099)) + self.assertEqual((cell["entries_per_object"], cell["appends_per_object"]), (8.0, 0.2)) + self.assertEqual(cell["region_rows"], [750 + i for i in range(8)]) + output = summary.render({}, [cell], []) + self.assertIn("| 1-8-D | 50.0 / 99.0 | 8.0 | 0.20 | 8 | 750 / 757 |", output) + + def test_restarts_report_what_each_region_replayed(self): + log = ("INFO mito2::region::opener: Replay WAL for region: 4398046511104(1024, 0), provider: ObjectStore(" + 'ObjectStoreProvider { region_id: 4398046511104(1024, 0), prefix: "wal" }), rows recovered: 0, ' + "replay from entry id: 1048578, last entry id: 1048577, total timeseries replayed: 0, elapsed: 60.581µs\n" + "INFO mito2::region::opener: Replay WAL for region: 4402341478400(1025, 0), provider: ObjectStore(" + 'ObjectStoreProvider { region_id: 4402341478400(1025, 0), prefix: "wal" }), rows recovered: 12625000, ' + "replay from entry id: 4853858306, last entry id: 8164212737, total timeseries replayed: 82, " + "elapsed: 95.150155247s\n" + "INFO mito2::region::opener: Replay WAL for region: 4402341478401(1025, 1), provider: ObjectStore(" + 'ObjectStoreProvider { region_id: 4402341478401(1025, 1), prefix: "wal" }), rows recovered: 5, ' + "replay from entry id: 8164212736, last entry id: 8164212737, total timeseries replayed: 1, " + "elapsed: 12.5ms\n") + with tempfile.TemporaryDirectory() as directory: + path = Path(directory) + (path / "server-restart.log").write_text(log) + metrics = summary.parse_metrics("greptime_logstore_object_store_wal_read_seconds_sum 95.15\n" + "greptime_logstore_object_store_wal_read_seconds_count 3\n") + result = summary.replay(path / "server-restart.log", metrics) + 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.assertIsNone(summary.replay(path / "absent.log", metrics)) + raft = log.replace("ObjectStore(", "RaftEngine(") + (path / "server-restart.log").write_text(raft) + self.assertIsNone(summary.replay(path / "server-restart.log", metrics)["objects"]) + + def test_a_drop_cell_reports_the_objects_collected_after_its_restart(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + path = root / "cells" / "drop-1-8-D" + (path / "dropped").mkdir(parents=True) + (path / "cell.json").write_text(json.dumps({ + "id": "drop-1-8-D", "group": "drop", "mode": "drop", "round": 1, "concurrency": 8, "config": "D", + "wal": bench.WAL_CONFIGS["D"], "exit_code": 0, "restart_seconds": 2.5, "restart_scraped": True})) + write_lines(path / "dropped" / "acked-0.log", [0, 8, 16]) + write_lines(path / "dropped" / "acked-1.log", [1, 9]) + (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, + "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) + def test_untouched_counters_are_zero_only_for_an_active_object_store_wal(self): with tempfile.TemporaryDirectory() as directory: root = Path(directory) @@ -523,6 +658,11 @@ 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" != *region_statistics* ]] || { python3 -c 'import json, sys +print(json.dumps({"output": [{"records": {"rows": [[f"p{i}", i, int(n), 1] for i, n in enumerate(sys.argv[1].split(","))]}}]}))' \ + "$FAKE_REGION_ROWS"; exit 0; } +done for arg in "$@"; do [[ "$arg" != */v1/sql* ]] || { echo "{\"output\": [{\"records\": {\"rows\": [[${FAKE_COUNT:-6000}]]}}]}"; exit 0; } [[ "$arg" != */metrics ]] || { @@ -530,7 +670,8 @@ for arg in "$@"; do printf '%s\n' 'greptime_logstore_object_store_wal_poisoned_total 1' 'other_total 2' [[ -z "${FAKE_FULL_METRICS:-}" ]] || printf '%s\n' \ "greptime_logstore_object_store_wal_indexed_objects $FAKE_FULL_METRICS" \ - 'greptime_logstore_object_store_wal_recovery_seconds_count 1' + 'greptime_logstore_object_store_wal_recovery_seconds_count 1' \ + "greptime_logstore_object_store_wal_recovered_objects_total ${FAKE_RECOVERED:-0}" exit 0; } done @@ -663,8 +804,9 @@ 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"): - """A crash cell against fake docker and a stub SQL endpoint that the fake kill takes down.""" + def run_crash(self, root, metrics_rc=0, pin=False, sample_rc=0, full_metrics="5", groups=None, env=None): + """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 import threading flag, found = root / "killed", root / "found.log" @@ -692,13 +834,13 @@ class CellLifecycleTest(unittest.TestCase): # the run script against fake docke 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], - "pin": pin}]) + groups = groups or json.dumps([{"name": "crash", "configs": "D", "mode": "crash", "cycles": 2, + "kill_after": [1, 1], "pin": pin}]) 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", "OSWAL_SAMPLE_SECONDS": "0.2", "FAKE_SAMPLE_RC": str(sample_rc), - "FAKE_FULL_METRICS": full_metrics}) + "FAKE_FULL_METRICS": full_metrics} | (env or {})) try: return self.run_cells(root, load_rc=0, metrics_rc=metrics_rc, groups=groups) finally: @@ -762,6 +904,54 @@ class CellLifecycleTest(unittest.TestCase): # the run script against fake docke self.assertEqual((recorded["exit_code"], recorded["indexed_before_kill"], recorded["restart_count"]), (exit_code, 5, 6000)) + def test_a_partitioned_cell_creates_its_table_and_checks_every_region_took_rows(self): + for region_rows, exit_code in (("750,750,750,750,750,750,750,750", 0), ("1000,1000,1000,0,1000,1000,1000,0", 8)): + with self.subTest(region_rows=region_rows), tempfile.TemporaryDirectory() as directory: + root = Path(directory) + (root / "corpus" / "corpus-6000").mkdir(parents=True) + (root / "corpus" / "corpus-6000" / "summary.json").write_text(json.dumps( + {"start": "2026-07-10T00:00:00Z", "end": "2026-07-10T01:00:00Z"})) + groups = json.dumps([{"name": "multi", "configs": "D", "partitions": 8}]) + old = os.environ.copy() + os.environ["FAKE_REGION_ROWS"] = region_rows + try: + cells, _, log, _ = self.run_cells(root, load_rc=0, groups=groups) + finally: + os.environ.clear() + os.environ.update(old) + cell = root / "results" / "cells" / "multi-1-8-D" + self.assertEqual(json.loads((cell / "cell.json").read_text())["exit_code"], exit_code, + cells.stdout + cells.stderr) + self.assertIn("PARTITION ON COLUMNS (`event_time`)", urllib.parse.unquote_plus(log)) + self.assertIn(f"type=bind,src={SCRIPTS}/oswal-s3-bench-load.sh,dst=/work/oswal-s3-bench-load.sh,readonly", + log) + self.assertIn(" /work/oswal-s3-bench-load.sh", log) + self.assertNotIn("greptimedb.sh load", log) + self.assertEqual(len(json.loads((cell / "regions.json").read_text())["output"][0]["records"]["rows"]), 8) + + def test_a_drop_cell_restarts_and_waits_for_the_dropped_objects_to_go(self): + for indexed, recovered, exit_code in (("2", "0", 0), ("50", "200", 0), ("50", "60", 9)): + with self.subTest(indexed=indexed, recovered=recovered), 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=indexed, groups=groups, + env={"FAKE_RECOVERED": recovered, "OSWAL_COLLECT_SECONDS": "1"}) + cell = root / "results" / "cells" / "drop-1-8-D" + recorded = json.loads((cell / "cell.json").read_text()) + self.assertEqual(recorded["exit_code"], exit_code, cells.stdout + cells.stderr) + self.assertIsInstance(recorded["restart_seconds"], float) + sql = urllib.parse.unquote_plus(log) + for statement in ("CREATE TABLE dropped", "CREATE TABLE kept", "DROP TABLE dropped", + "ADMIN FLUSH_TABLE('kept')", "INSERT INTO kept VALUES (-1, "): + self.assertIn(statement, sql) + self.assertLess(sql.index("DROP TABLE dropped"), log.index("docker kill --signal KILL fakecid")) + 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", + "server-restart.log", "collected.tsv"): + 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)