test: add manual S3 metric snapshot benchmark (#9573)

* test: add repeatable metric snapshot S3 benchmark

Signed-off-by: jeremyhi <fengjiachun@gmail.com>

* test: use only existing CI S3 permissions in the metric snapshot benchmark

The CI S3 user is not allowed GetBucketLocation or ListBucketMultipartUploads,
so the bucket probe and the prefix cleanup failed with AccessDenied. Use only
list, put, get and delete under the run prefix, as the object store WAL
benchmark does, and probe S3 before allocating the EC2 runner.

Signed-off-by: jeremyhi <fengjiachun@gmail.com>

* test: scope metric snapshot inventory to the current round

The full round's S3 inventory listed the whole run prefix, so it also counted
the smoke snapshot. List only the round's snapshot prefix while cleanup still
covers the run, and assert that the teardown's S3 cleanup step runs always()
with the validated run prefix.

Signed-off-by: jeremyhi <fengjiachun@gmail.com>

* docs: record the AWS validation run of the metric snapshot benchmark

Signed-off-by: jeremyhi <fengjiachun@gmail.com>

---------

Signed-off-by: jeremyhi <fengjiachun@gmail.com>
(cherry picked from commit 7df99f946e)
This commit is contained in:
jeremyhi
2026-10-23 14:43:10 +08:00
committed by discord9
parent 069b942518
commit 97e3bfd547
9 changed files with 1592 additions and 0 deletions
@@ -0,0 +1,101 @@
# Copyright 2023 Greptime Team
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import copy
import importlib.util
from pathlib import Path
import unittest
spec = importlib.util.spec_from_file_location(
"fixture", Path(__file__).resolve().parents[1] / "metric-snapshot-fixture.py"
)
fixture = importlib.util.module_from_spec(spec)
spec.loader.exec_module(fixture)
class ValidatorTests(unittest.TestCase):
def records(self):
return {
"schema": {"column_schemas": [
{"name": "ts", "data_type": "TimestampMillisecond"},
*[{"name": f"tag_{i:03d}", "data_type": "String"} for i in range(10)],
{"name": "val", "data_type": "Float64"},
]},
"rows": [fixture.row(0, j, 50) for j in range(32)],
}
def test_full_tag_coverage_and_heterogeneous_schemas(self):
for per_group in (50, 10000):
variants = {tuple(fixture.tags(i, per_group)) for i in range(per_group)}
self.assertEqual(set().union(*map(set, variants)), set(range(298)))
self.assertGreater(len(variants), 1)
self.assertTrue(all(len(tags) == 10 for tags in variants))
def test_accepts_engine_column_order_with_matching_values(self):
records = self.records()
order = [*range(1, 11), 0, 11] # The engine returns tags, timestamp, value.
records["schema"]["column_schemas"] = [
records["schema"]["column_schemas"][index] for index in order
]
records["rows"] = [[values[index] for index in order] for values in records["rows"]]
fixture.check_records(0, 50, records)
records["rows"][1][10] = 2
with self.assertRaisesRegex(RuntimeError, "typed values"):
fixture.check_records(0, 50, records)
def test_rejects_column_type_and_membership_changes(self):
fixture.check_records(0, 50, self.records())
for mutation in ("type", "extra", "missing"):
records = self.records()
columns = records["schema"]["column_schemas"]
if mutation == "type":
columns[0]["data_type"] = "TimestampMicrosecond"
elif mutation == "extra":
columns.append({"name": "unexpected", "data_type": "String"})
else:
del columns[1]
with self.subTest(mutation=mutation), self.assertRaisesRegex(RuntimeError, "schema"):
fixture.check_records(0, 50, records)
def test_rejects_null_and_numeric_type_changes(self):
for value in ("", 0, False):
records = self.records()
records["rows"][0][-1] = value # Expected SQL NULL.
with self.subTest(value=value), self.assertRaisesRegex(RuntimeError, "typed values"):
fixture.check_records(0, 50, records)
records = self.records()
records["rows"][4][-1] = 1 # Numeric equality to 1.0 must not hide a type change.
with self.assertRaisesRegex(RuntimeError, "typed values"):
fixture.check_records(0, 50, records)
def test_source_comparison_requires_same_ddl_and_remapped_ids(self):
source = {"fixture": {"tables_per_group": 50}, "schema_sha256": "schema",
"data_sha256": "data", "ddl_sha256": "ddl",
"table_ids": {"m000000": 1024, "phy_00": 1025}}
target = copy.deepcopy(source)
target["table_ids"] = {"m000000": 1041, "phy_00": 1042}
fixture.compare_source(target, source)
self.assertEqual(target["remapped_table_ids"], 2)
for field in ("schema_sha256", "data_sha256", "ddl_sha256"):
changed = copy.deepcopy(target)
changed[field] = "changed"
with self.subTest(field=field), self.assertRaisesRegex(RuntimeError, field):
fixture.compare_source(changed, source)
target["table_ids"]["phy_00"] = 1025
with self.assertRaisesRegex(RuntimeError, "not all remapped"):
fixture.compare_source(target, source)
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,74 @@
#!/usr/bin/env python3
# Copyright 2023 Greptime Team
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Failure accounting for the metric snapshot runner."""
import importlib.util
import json
from pathlib import Path
import tempfile
import unittest
from unittest.mock import patch
SPEC = importlib.util.spec_from_file_location(
"metric_snapshot_bench", Path(__file__).resolve().parents[1] / "metric-snapshot-s3-bench.py")
bench = importlib.util.module_from_spec(SPEC)
SPEC.loader.exec_module(bench)
class PhaseTests(unittest.TestCase):
def test_docker_nanosecond_timestamps(self):
start = bench.docker_timestamp("2026-10-14T06:06:44.72000818Z")
end = bench.docker_timestamp("2026-10-14T06:06:46.123456789Z")
self.assertAlmostEqual((end - start).total_seconds(), 1.403448)
def test_resource_interference_invalidates_success_and_preserves_fixture(self):
with tempfile.TemporaryDirectory() as directory:
runner = bench.Benchmark.__new__(bench.Benchmark)
runner.round_dir = Path(directory)
runner.server_pid = 0
runner.phases = []
runner.metrics = lambda: ""
runner.summary = lambda: None
fixture = runner.round_dir / "source-validation.json"
fixture.write_text('{"data_sha256":"fixture"}')
before = {"available": True, "pswpout_pages": 0, "oom_kill": 0}
after = {"available": True, "pswpout_pages": 1, "oom_kill": 0}
with patch.object(bench, "host_memory", side_effect=[before, after]):
with self.assertRaisesRegex(RuntimeError, "Resource interference"):
runner.phase("source-validation", lambda: None)
self.assertEqual(json.loads(fixture.read_text()), {"data_sha256": "fixture"})
evidence = json.loads((runner.round_dir / "source-validation-resources.json").read_text())
self.assertEqual(evidence["outcome"], "resource-invalid")
self.assertEqual(evidence["new_swapout_pages"], 1)
def test_action_failure_keeps_failed_resource_evidence(self):
with tempfile.TemporaryDirectory() as directory:
runner = bench.Benchmark.__new__(bench.Benchmark)
runner.round_dir = Path(directory)
runner.server_pid = 0
runner.phases = []
runner.metrics = lambda: ""
runner.summary = lambda: None
def fail():
raise RuntimeError("export failed")
with patch.object(bench, "host_memory", return_value={"available": False}):
with self.assertRaisesRegex(RuntimeError, "export failed"):
runner.phase("export", fail)
evidence = json.loads((runner.round_dir / "export-resources.json").read_text())
self.assertEqual(evidence["outcome"], "failed")
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,203 @@
#!/usr/bin/env python3
# Copyright 2023 Greptime Team
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Offline safety checks for the metric snapshot workflow's budget and cleanup."""
import importlib.util
import io
import json
from pathlib import Path
import tempfile
import unittest
from unittest import mock
SPEC = importlib.util.spec_from_file_location("snapshot_ops", Path(__file__).parents[1] / "metric-snapshot-s3-ops.py")
ops = importlib.util.module_from_spec(SPEC)
SPEC.loader.exec_module(ops)
PREFIX = "metric-snapshot-bench/123-1/"
class FakeS3:
def __init__(self):
self.objects = [{"Key": PREFIX + "current", "Size": 11}, {"Key": PREFIX + "data", "Size": 7}]
self.deleted = []
def get_paginator(self, operation):
assert operation == "list_objects_v2"
parent = self
class Paginator:
def paginate(self, **kwargs):
assert kwargs["Bucket"] == "bucket" and kwargs["Prefix"].startswith(PREFIX)
# Keys outside the run prefix model a misbehaving listing and are always returned.
return iter([{"Contents": [item for item in parent.objects if not item["Key"].startswith(PREFIX)
or item["Key"].startswith(kwargs["Prefix"])]}])
return Paginator()
def put_object(self, **kwargs):
self.objects.append({"Key": kwargs["Key"], "Size": len(kwargs["Body"])})
return {}
def get_object(self, **kwargs):
return {"Body": io.BytesIO(b"metric snapshot benchmark")}
def delete_object(self, **kwargs):
self.deleted.append(kwargs)
self.objects = [item for item in self.objects if item["Key"] != kwargs["Key"]]
class OperationsTest(unittest.TestCase):
def env(self, **changes):
return dict(GREPTIMEDB_IMAGE="greptime/greptimedb-nightly@sha256:" + "a" * 64,
EXPECTED_COMMIT="b" * 40, LOGICAL_TABLES_PER_GROUP="10000",
BENCHMARK_TIMEOUT_MINUTES="240", PRIOR_SPEND_USD="0",
S3_REGION="ap-southeast-1", RUNNER_REGION="ap-southeast-1", S3_BUCKET="bucket",
RUN_PREFIX=PREFIX) | changes
def test_budget_includes_provision_cleanup_and_other_cost_reserve(self):
plan = ops.plan(self.env())
self.assertEqual(plan["attempt_reserve_usd"], "6.4392")
ops.plan(self.env(PRIOR_SPEND_USD="13.5608"))
for changes in ({"PRIOR_SPEND_USD": "13.5609"}, {"PRIOR_SPEND_USD": "15"},
{"PRIOR_SPEND_USD": "NaN"}, {"PRIOR_SPEND_USD": "-1"},
{"BENCHMARK_TIMEOUT_MINUTES": "241"}, {"LOGICAL_TABLES_PER_GROUP": "49"},
{"LOGICAL_TABLES_PER_GROUP": "10001"}, {"S3_REGION": "us-east-1"},
{"GREPTIMEDB_IMAGE": "greptime/greptimedb:latest"},
{"GREPTIMEDB_IMAGE": "docker.io/greptime/greptimedb@sha256:" + "a" * 64},
{"GREPTIMEDB_IMAGE": "greptime/greptimedb:nightly@sha256:" + "a" * 64},
{"EXPECTED_COMMIT": "abcdef"}):
with self.subTest(changes=changes), self.assertRaises(ValueError):
ops.plan(self.env(**changes))
def watcher_env(self):
return self.env(GITHUB_REPOSITORY="GreptimeTeam/greptimedb", GITHUB_RUN_ID="123",
GITHUB_RUN_ATTEMPT="2", GH_TOKEN="test-token", BENCHMARK_TIMEOUT_MINUTES="30")
def test_watcher_completed_job_uses_original_attempt_and_does_not_wait(self):
for conclusion in ("success", "failure", "cancelled"):
response = io.BytesIO(json.dumps({"jobs": [{"name": "benchmark", "status": "completed",
"conclusion": conclusion}]}).encode())
with self.subTest(conclusion=conclusion), \
mock.patch.object(ops.urllib.request, "urlopen", return_value=response) as fetch, \
mock.patch.object(ops.time, "time", return_value=1005), \
mock.patch.object(ops.time, "sleep") as sleep:
self.assertEqual(ops.wait_for_benchmark(self.watcher_env(), 1000),
{"benchmark_conclusion": conclusion, "owned_attempt": "1"})
self.assertIn("/runs/123/attempts/1/jobs?", fetch.call_args.args[0].full_url)
sleep.assert_not_called()
def test_watcher_queue_reaches_durable_deadline(self):
deadline = 1000 + (45 + 30 + 10) * 60
clock = [deadline - 31]
def advance(seconds):
self.assertLessEqual(seconds, 30)
clock[0] += seconds
def queued(*args, **kwargs):
return io.BytesIO(b'{"jobs": [{"name": "benchmark", "status": "queued"}]}')
with mock.patch.object(ops.urllib.request, "urlopen", side_effect=queued) as fetch, \
mock.patch.object(ops.time, "time", side_effect=lambda: clock[0]), \
mock.patch.object(ops.time, "sleep", side_effect=advance), \
self.assertRaisesRegex(TimeoutError, "proceeding to resource cleanup"):
ops.wait_for_benchmark(self.watcher_env(), 1000)
self.assertEqual(clock[0], deadline)
self.assertEqual(fetch.call_count, 2)
def test_watcher_api_error_fails_immediately_for_cleanup(self):
with mock.patch.object(ops.urllib.request, "urlopen", side_effect=OSError("API unavailable")), \
mock.patch.object(ops.time, "time", return_value=1005), \
mock.patch.object(ops.time, "sleep") as sleep, \
self.assertRaises(OSError):
ops.wait_for_benchmark(self.watcher_env(), 1000)
sleep.assert_not_called()
def test_cleanup_deletes_every_listed_object(self):
s3 = FakeS3()
result = ops.cleanup(s3, "bucket", PREFIX)
self.assertEqual(result["objects"], 0)
self.assertEqual(s3.deleted, [{"Bucket": "bucket", "Key": PREFIX + "current"},
{"Bucket": "bucket", "Key": PREFIX + "data"}])
def test_probe_refuses_occupied_prefix_and_removes_its_object(self):
with self.assertRaisesRegex(ValueError, "already occupied"):
ops.probe(FakeS3(), "bucket", PREFIX)
s3 = FakeS3()
s3.objects = []
self.assertEqual(ops.probe(s3, "bucket", PREFIX)["objects"], 0)
self.assertEqual(s3.deleted, [{"Bucket": "bucket", "Key": PREFIX + "_probe"}])
def test_failed_probe_delete_still_has_hosted_cleanup_path(self):
s3 = FakeS3()
s3.objects = []
with mock.patch.object(s3, "delete_object", side_effect=OSError("temporary delete failure")), \
self.assertRaises(OSError):
ops.probe(s3, "bucket", PREFIX)
self.assertEqual([item["Key"] for item in s3.objects], [PREFIX + "_probe"])
workflow = (Path(__file__).parents[2] / "workflows/metric-snapshot-s3-bench.yml").read_text()
teardown = workflow.split(" teardown:\n", 1)[1]
job_if = next(line.strip() for line in teardown.splitlines() if line.startswith(" if:"))
self.assertEqual(job_if, "if: ${{ always() && needs.validate.outputs.run_id != '' }}")
ec2 = teardown.split(" - name: Delete EC2, its temporary disks and runner registration\n", 1)[1]
self.assertEqual(ec2.splitlines()[0].strip(), "if: ${{ always() && needs.provision.result != 'skipped' }}")
self.assertIn(" RUN_PREFIX: ${{ needs.validate.outputs.run_prefix }}\n", teardown.split(" steps:", 1)[0])
s3_cleanup = teardown.split(" - name: Remove and verify only this run's S3 prefix\n", 1)[1].split(" - ", 1)[0]
self.assertEqual(s3_cleanup.splitlines()[0].strip(), "if: always()")
self.assertIn("run: uv run greptimedb/.github/scripts/metric-snapshot-s3-ops.py cleanup\n", s3_cleanup)
self.assertEqual(ops.cleanup(s3, "bucket", PREFIX)["objects"], 0)
def test_round_inventory_excludes_other_rounds_while_cleanup_covers_the_run(self):
s3 = FakeS3()
s3.objects = [{"Key": PREFIX + "smoke/pack-000000.bin", "Size": 3},
{"Key": PREFIX + "full/pack-000000.bin", "Size": 5},
{"Key": PREFIX + "full/index.json", "Size": 2}]
full = ops.inventory(s3, "bucket", PREFIX, "full")
self.assertEqual((full["prefix"], full["objects"], full["bytes"]), (PREFIX + "full/", 2, 7))
self.assertEqual(ops.inventory(s3, "bucket", PREFIX, "smoke")["bytes"], 3)
self.assertEqual(ops.inventory(s3, "bucket", PREFIX)["objects"], 3)
for round in ("", "../full", "full/"):
with self.subTest(round=round), self.assertRaises(ValueError):
ops.inventory(s3, "bucket", PREFIX, round)
self.assertEqual(ops.cleanup(s3, "bucket", PREFIX)["objects"], 0)
self.assertEqual(len(s3.deleted), 3)
def test_bad_prefix_and_out_of_scope_response_cannot_delete(self):
for prefix in ("", "metric-snapshot-bench/", "metric-snapshot-bench/123-1", PREFIX + "../", "oswal-bench/123-1/"):
s3 = FakeS3()
with self.subTest(prefix=prefix), self.assertRaises(ValueError):
ops.cleanup(s3, "bucket", prefix)
self.assertEqual(s3.deleted, [])
s3 = FakeS3()
s3.objects[0]["Key"] = "other-run/current"
with self.assertRaises(ValueError):
ops.inventory(s3, "bucket", PREFIX, "full")
with self.assertRaises(ValueError):
ops.cleanup(s3, "bucket", PREFIX)
self.assertEqual(s3.deleted, [])
def test_credential_crossing_read_boundary_blocks_artifact_upload(self):
with tempfile.TemporaryDirectory() as directory:
logfile = Path(directory) / "server.log"
logfile.write_bytes(b"a" * (1024 * 1024 - 4) + b"private-key" + b"tail")
with self.assertRaisesRegex(ValueError, "upload is blocked"):
ops.scrub(directory, {"AWS_SECRET_ACCESS_KEY": "private-key"})
logfile.write_text("safe log\n")
ops.scrub(directory, {"AWS_SECRET_ACCESS_KEY": "private-key"})
if __name__ == "__main__":
unittest.main()