From 0b0eab9a9206e24bbd2d78f11feefcaaefd10d09 Mon Sep 17 00:00:00 2001 From: WenyXu Date: Tue, 20 Oct 2026 13:43:52 +0000 Subject: [PATCH] ci: control cache capacity for sharing benchmarks Signed-off-by: WenyXu --- .github/benchmark-patches/agent.patch | 205 ++++++++++++++++ .github/benchmark-patches/traces.patch | 223 ++++++++++++++++++ .github/benchmark-patches/vmbench.patch | 210 +++++++++++++++++ .github/scripts/apply-cache-capacity-patch.py | 103 ++++++++ .github/workflows/agent-observability.yml | 20 ++ .github/workflows/tracesbench.yml | 20 ++ .github/workflows/vmbench-long-range.yml | 20 ++ 7 files changed, 801 insertions(+) create mode 100644 .github/benchmark-patches/agent.patch create mode 100644 .github/benchmark-patches/traces.patch create mode 100644 .github/benchmark-patches/vmbench.patch create mode 100644 .github/scripts/apply-cache-capacity-patch.py diff --git a/.github/benchmark-patches/agent.patch b/.github/benchmark-patches/agent.patch new file mode 100644 index 00000000000..ca84ca91ce1 --- /dev/null +++ b/.github/benchmark-patches/agent.patch @@ -0,0 +1,205 @@ +--- a/scripts/run-agent-observability.sh ++++ b/scripts/run-agent-observability.sh +@@ -145,6 +145,7 @@ + greptimedb) + port=$greptimedb_http_port; publish=(-p "127.0.0.1:$port:4000" -p "127.0.0.1:$greptimedb_grpc_port:4001") + args=(standalone start --http-addr=0.0.0.0:4000 --grpc-bind-addr=0.0.0.0:4001) ++ envs=(--entrypoint /greptime/bin/greptime -e 'GREPTIMEDB_STANDALONE__REGION_ENGINE[0]__MITO__PAGE_CACHE_SIZE=512MiB') + version_command=(greptime --version) + endpoint="http://127.0.0.1:$port/v1/sql?db=public&format=greptimedb_v1"; health="http://127.0.0.1:$port/health" ;; + clickhouse) +@@ -219,6 +220,9 @@ + sleep 2 + done + timing_end 0 ++if [[ "$target" == greptimedb ]]; then ++ python3 "$ROOT/scripts/cache_capacity_evidence.py" "$cid" "http://127.0.0.1:$greptimedb_http_port" "$dir" ++fi + docker exec "$cid" "${version_command[@]}" > "$dir/version.txt" + case "$target" in + greptimedb) version=$(sed -n 's/^version: //p' "$dir/version.txt") ;; +--- /dev/null ++++ b/scripts/cache_capacity_evidence.py +@@ -0,0 +1,182 @@ ++#!/usr/bin/env python3 ++# Copyright 2023 Greptime Team ++# Licensed under the Apache License, Version 2.0. ++"""Benchmark-only gate for equal Parquet capacity, before load/query work.""" ++import decimal ++import hashlib ++import json ++from pathlib import Path ++import re ++import subprocess ++import sys ++import tomllib ++import urllib.request ++ ++KEY = 'GREPTIMEDB_STANDALONE__REGION_ENGINE[0]__MITO__PAGE_CACHE_SIZE' ++VALUE = '512MiB' ++EXPECTED = 512 * 1024**2 ++# Audited source: Serialize omits content_cache_size iff its value is 512 MiB. ++# Unknown revisions must provide an explicit value; schema shape alone is not proof. ++OMISSION_RULES = { ++ 'c7d970da0bb0aa2420cefef5c2cd72d6e6bb6972': { ++ 'config_git_blob': '94428174f16c79cc0dcf41715501d707272a1dc8', ++ 'path': 'src/mito2/src/config.rs', ++ 'rule': 'ParquetPageConfig::is_default_content_cache_size == ReadableSize::mb(512)', ++ }, ++} ++ ++ ++def size(value): ++ if not isinstance(value, str): ++ raise ValueError('Cache capacity must be an explicit byte string') ++ match = re.fullmatch(r'([0-9]+(?:\.[0-9]+)?)\s*(B|KiB|MiB|GiB)', value) ++ if not match: ++ raise ValueError('Unsupported cache byte format') ++ return int(decimal.Decimal(match[1]) * {'B': 1, 'KiB': 1024, 'MiB': 1024**2, 'GiB': 1024**3}[match[2]]) ++ ++ ++def resolve_capacity(mito, revision): ++ page = mito.get('parquet_page', {}) ++ if not isinstance(page, dict): ++ raise ValueError('Invalid Parquet page configuration') ++ declared = [size(value) for value in ++ (mito.get('page_cache_size'), page.get('content_cache_size')) if value is not None] ++ if len(set(declared)) > 1: ++ raise ValueError('Conflicting cache capacity aliases') ++ proof = None ++ if declared: ++ capacity, method = declared[0], 'explicit_serialized_config' ++ elif revision in OMISSION_RULES and 'content_cache_page_size' in page: ++ capacity, method = EXPECTED, 'audited_serialization_omission_rule' ++ proof = OMISSION_RULES[revision] ++ else: ++ raise ValueError('Missing capacity without an audited serialization rule') ++ if capacity != EXPECTED: ++ raise ValueError('Effective Parquet cache capacity is not 512MiB') ++ return capacity, method, proof ++ ++ ++def other_cache_settings(mito): ++ memory_fields = ('sst_meta_cache_size', 'vector_cache_size', 'selector_result_cache_size', ++ 'range_result_cache_size', 'prefilter_result_cache_size', 'manifest_cache_size') ++ index = mito['index'] ++ index_fields = ('metadata_cache_size', 'content_cache_size', 'content_cache_page_size', ++ 'result_cache_size', 'staging_size', 'write_buffer_size') ++ boolean_fields = ('enable_write_cache', 'preload_index_cache', 'enable_refill_cache_on_read') ++ if any(type(mito[field]) is not bool for field in boolean_fields): ++ raise ValueError('Invalid cache policy boolean') ++ if type(mito['index_cache_percent']) is not int or not 0 <= mito['index_cache_percent'] <= 100: ++ raise ValueError('Invalid index file-cache share') ++ return { ++ 'memory_cache_bytes': {field: size(mito[field]) for field in memory_fields}, ++ 'write_cache': { ++ **{field: mito[field] for field in boolean_fields}, ++ 'capacity_bytes': size(mito['write_cache_size']), ++ 'index_cache_percent': mito['index_cache_percent'], ++ # Option::None has no TOML value; absence is retained as null. ++ 'ttl': mito.get('write_cache_ttl'), ++ }, ++ 'index': { ++ **{field + '_bytes': size(index[field]) for field in index_fields}, ++ 'staging_ttl': index.get('staging_ttl'), ++ 'build_mode': index['build_mode'], ++ }, ++ } ++ ++ ++def observed_cache_settings(mito): ++ """Retain only cache settings, before parsing or validating their values.""" ++ fields = ('page_cache_size', 'sst_meta_cache_size', 'vector_cache_size', ++ 'selector_result_cache_size', 'range_result_cache_size', ++ 'prefilter_result_cache_size', 'manifest_cache_size', ++ 'enable_write_cache', 'write_cache_size', 'write_cache_ttl', ++ 'preload_index_cache', 'enable_refill_cache_on_read', 'index_cache_percent') ++ nested = { ++ 'parquet_page': ('content_cache_size', 'content_cache_page_size'), ++ 'index': ('metadata_cache_size', 'content_cache_size', 'content_cache_page_size', ++ 'result_cache_size', 'staging_size', 'write_buffer_size', ++ 'staging_ttl', 'build_mode'), ++ } ++ # Never copy arbitrary nested objects, even if a malformed cache field contains one. ++ def scalar(value): ++ return value if value is None or type(value) in (str, int, float, bool) else '' ++ values = {key: scalar(mito[key]) for key in fields if key in mito} ++ missing = [key for key in fields if key not in mito] ++ for section, names in nested.items(): ++ table = mito.get(section) ++ if isinstance(table, dict): ++ values[section] = {key: scalar(table[key]) for key in names if key in table} ++ missing.extend(section + '.' + key for key in names if key not in table) ++ elif section in mito: ++ values[section] = '' ++ else: ++ missing.append(section) ++ return {'values': values, 'missing_fields': missing} ++ ++ ++def attest(container, endpoint, output): ++ output = Path(output) ++ output.mkdir(parents=True, exist_ok=True) ++ evidence = {'status': 'started', 'environment_key': KEY, 'requested_bytes': EXPECTED, ++ 'helper_sha256': hashlib.sha256(Path(__file__).read_bytes()).hexdigest(), ++ 'observation': {}} ++ def save(): ++ temporary = output / 'cache-capacity.json.tmp' ++ temporary.write_text(json.dumps(evidence, indent=2) + '\n') ++ temporary.replace(output / 'cache-capacity.json') ++ save() ++ observations = evidence['observation'] ++ failures = [] ++ # Attempt independent observations even if the environment or one endpoint is wrong. ++ for stage in ('container', 'status', 'config'): ++ try: ++ if stage == 'container': ++ info = json.loads(subprocess.check_output(['docker', 'inspect', container]))[0] ++ env = [value for value in info['Config']['Env'] if value.startswith(KEY + '=')] ++ observations['environment_values'] = env ++ observations['running'] = info['State']['Running'] ++ evidence.update(image=info['Config']['Image'], container_id=info['Id']) ++ elif stage == 'status': ++ with urllib.request.urlopen(endpoint.rstrip('/') + '/status', timeout=15) as response: ++ evidence['source_revision'] = json.load(response)['commit'] ++ else: ++ with urllib.request.urlopen(endpoint.rstrip('/') + '/config', timeout=15) as response: ++ raw = response.read() ++ evidence['config_sha256'] = hashlib.sha256(raw).hexdigest() ++ config = tomllib.loads(raw.decode()) ++ engines = [engine['mito'] for engine in config['region_engine'] if 'mito' in engine] ++ observations['mito_engine_count'] = len(engines) ++ observations['mito_cache_settings'] = [observed_cache_settings(engine) for engine in engines] ++ except Exception as error: ++ # Exception messages can embed response bodies or arbitrary configuration values. ++ failures.append({'stage': stage, 'error_type': type(error).__name__}) ++ save() ++ stage = 'observations' ++ try: ++ if failures: ++ observations['errors'] = failures ++ raise ValueError('Incomplete capacity observations') ++ stage = 'environment' ++ if env != [KEY + '=' + VALUE] or not info['State']['Running']: ++ raise ValueError('Missing explicit Parquet capacity or stopped database') ++ stage = 'mito_engine_count' ++ if len(engines) != 1: ++ raise ValueError('Expected one Mito engine') ++ mito = engines[0] ++ stage = 'parquet_capacity' ++ capacity, method, proof = resolve_capacity(mito, evidence['source_revision']) ++ evidence.update(effective_parquet_cache_bytes=capacity, capacity_evidence=method, ++ serialization_rule_evidence=proof) ++ stage = 'other_cache_settings' ++ evidence['other_cache_settings'] = other_cache_settings(mito) ++ evidence['status'] = 'passed' ++ save() ++ return evidence ++ except Exception as error: ++ evidence.update(status='failed', failed_stage=stage, error_type=type(error).__name__) ++ save() ++ raise ++ ++ ++if __name__ == '__main__': ++ attest(*sys.argv[1:]) diff --git a/.github/benchmark-patches/traces.patch b/.github/benchmark-patches/traces.patch new file mode 100644 index 00000000000..4b6fa16d2b4 --- /dev/null +++ b/.github/benchmark-patches/traces.patch @@ -0,0 +1,223 @@ +--- a/scripts/run_tracesbench_docker.py ++++ b/scripts/run_tracesbench_docker.py +@@ -30,6 +30,8 @@ + limits += ['--cpus', args.runtime_cpus] + if args.runtime_memory != '0': + limits += ['--memory', args.runtime_memory, '--memory-swap', args.runtime_memory] ++ for source in ('run_tracesbench_docker.py', 'cache_capacity_evidence.py'): ++ limits += ['--mount', f'type=bind,src={ROOT / "scripts" / source},dst=/opt/o11ybench/scripts/{source},readonly'] + command[2:2] = [*limits, '--env', f'SQLITE_TMPDIR={args.root}/scratch'] + return command + +@@ -111,6 +113,8 @@ + + def limited_docker(args, command, **kwargs): + if command[:2] == ['docker', 'create']: ++ if args.target == 'greptimedb': ++ command = command[:2] + ['--entrypoint', '/greptime/bin/greptime', '--env', 'GREPTIMEDB_STANDALONE__REGION_ENGINE[0]__MITO__PAGE_CACHE_SIZE=512MiB'] + command[2:] + command = command[:2] + ['--cpus', args.db_cpus, '--memory', args.db_memory, '--memory-swap', args.db_memory] + command[2:] + return subprocess.run(command, **kwargs) + +@@ -195,6 +199,7 @@ + success=False, correctness=[], samples=[], output=str(output), command=sys.argv, + execution={'runtime_image': args.runtime_image, 'db_cpus': args.db_cpus, 'db_memory': args.db_memory, + 'sources': bench.runtime.source_revisions(['scripts/run_tracesbench_docker.py', ++ 'scripts/cache_capacity_evidence.py', + 'scripts/tracesbench_runtime_task.py', + 'scripts/tracesbench_query_plans.py', + 'scripts/tracesbench_physical_probe.py', +@@ -272,6 +277,9 @@ + for source, dest in copies: + owned.copy_in(source, dest) + owned.start(ready) ++ if args.target == 'greptimedb': ++ from cache_capacity_evidence import attest ++ record['execution']['cache_capacity'] = attest(owned.id, endpoint, output) + if args.target == 'tempo' and args.dataset == 'main': + _, effective = runner.loader.read_effective_config(endpoint) + (output / 'tempo-effective.yaml').write_text(effective) +--- /dev/null ++++ b/scripts/cache_capacity_evidence.py +@@ -0,0 +1,182 @@ ++#!/usr/bin/env python3 ++# Copyright 2023 Greptime Team ++# Licensed under the Apache License, Version 2.0. ++"""Benchmark-only gate for equal Parquet capacity, before load/query work.""" ++import decimal ++import hashlib ++import json ++from pathlib import Path ++import re ++import subprocess ++import sys ++import tomllib ++import urllib.request ++ ++KEY = 'GREPTIMEDB_STANDALONE__REGION_ENGINE[0]__MITO__PAGE_CACHE_SIZE' ++VALUE = '512MiB' ++EXPECTED = 512 * 1024**2 ++# Audited source: Serialize omits content_cache_size iff its value is 512 MiB. ++# Unknown revisions must provide an explicit value; schema shape alone is not proof. ++OMISSION_RULES = { ++ 'c7d970da0bb0aa2420cefef5c2cd72d6e6bb6972': { ++ 'config_git_blob': '94428174f16c79cc0dcf41715501d707272a1dc8', ++ 'path': 'src/mito2/src/config.rs', ++ 'rule': 'ParquetPageConfig::is_default_content_cache_size == ReadableSize::mb(512)', ++ }, ++} ++ ++ ++def size(value): ++ if not isinstance(value, str): ++ raise ValueError('Cache capacity must be an explicit byte string') ++ match = re.fullmatch(r'([0-9]+(?:\.[0-9]+)?)\s*(B|KiB|MiB|GiB)', value) ++ if not match: ++ raise ValueError('Unsupported cache byte format') ++ return int(decimal.Decimal(match[1]) * {'B': 1, 'KiB': 1024, 'MiB': 1024**2, 'GiB': 1024**3}[match[2]]) ++ ++ ++def resolve_capacity(mito, revision): ++ page = mito.get('parquet_page', {}) ++ if not isinstance(page, dict): ++ raise ValueError('Invalid Parquet page configuration') ++ declared = [size(value) for value in ++ (mito.get('page_cache_size'), page.get('content_cache_size')) if value is not None] ++ if len(set(declared)) > 1: ++ raise ValueError('Conflicting cache capacity aliases') ++ proof = None ++ if declared: ++ capacity, method = declared[0], 'explicit_serialized_config' ++ elif revision in OMISSION_RULES and 'content_cache_page_size' in page: ++ capacity, method = EXPECTED, 'audited_serialization_omission_rule' ++ proof = OMISSION_RULES[revision] ++ else: ++ raise ValueError('Missing capacity without an audited serialization rule') ++ if capacity != EXPECTED: ++ raise ValueError('Effective Parquet cache capacity is not 512MiB') ++ return capacity, method, proof ++ ++ ++def other_cache_settings(mito): ++ memory_fields = ('sst_meta_cache_size', 'vector_cache_size', 'selector_result_cache_size', ++ 'range_result_cache_size', 'prefilter_result_cache_size', 'manifest_cache_size') ++ index = mito['index'] ++ index_fields = ('metadata_cache_size', 'content_cache_size', 'content_cache_page_size', ++ 'result_cache_size', 'staging_size', 'write_buffer_size') ++ boolean_fields = ('enable_write_cache', 'preload_index_cache', 'enable_refill_cache_on_read') ++ if any(type(mito[field]) is not bool for field in boolean_fields): ++ raise ValueError('Invalid cache policy boolean') ++ if type(mito['index_cache_percent']) is not int or not 0 <= mito['index_cache_percent'] <= 100: ++ raise ValueError('Invalid index file-cache share') ++ return { ++ 'memory_cache_bytes': {field: size(mito[field]) for field in memory_fields}, ++ 'write_cache': { ++ **{field: mito[field] for field in boolean_fields}, ++ 'capacity_bytes': size(mito['write_cache_size']), ++ 'index_cache_percent': mito['index_cache_percent'], ++ # Option::None has no TOML value; absence is retained as null. ++ 'ttl': mito.get('write_cache_ttl'), ++ }, ++ 'index': { ++ **{field + '_bytes': size(index[field]) for field in index_fields}, ++ 'staging_ttl': index.get('staging_ttl'), ++ 'build_mode': index['build_mode'], ++ }, ++ } ++ ++ ++def observed_cache_settings(mito): ++ """Retain only cache settings, before parsing or validating their values.""" ++ fields = ('page_cache_size', 'sst_meta_cache_size', 'vector_cache_size', ++ 'selector_result_cache_size', 'range_result_cache_size', ++ 'prefilter_result_cache_size', 'manifest_cache_size', ++ 'enable_write_cache', 'write_cache_size', 'write_cache_ttl', ++ 'preload_index_cache', 'enable_refill_cache_on_read', 'index_cache_percent') ++ nested = { ++ 'parquet_page': ('content_cache_size', 'content_cache_page_size'), ++ 'index': ('metadata_cache_size', 'content_cache_size', 'content_cache_page_size', ++ 'result_cache_size', 'staging_size', 'write_buffer_size', ++ 'staging_ttl', 'build_mode'), ++ } ++ # Never copy arbitrary nested objects, even if a malformed cache field contains one. ++ def scalar(value): ++ return value if value is None or type(value) in (str, int, float, bool) else '' ++ values = {key: scalar(mito[key]) for key in fields if key in mito} ++ missing = [key for key in fields if key not in mito] ++ for section, names in nested.items(): ++ table = mito.get(section) ++ if isinstance(table, dict): ++ values[section] = {key: scalar(table[key]) for key in names if key in table} ++ missing.extend(section + '.' + key for key in names if key not in table) ++ elif section in mito: ++ values[section] = '' ++ else: ++ missing.append(section) ++ return {'values': values, 'missing_fields': missing} ++ ++ ++def attest(container, endpoint, output): ++ output = Path(output) ++ output.mkdir(parents=True, exist_ok=True) ++ evidence = {'status': 'started', 'environment_key': KEY, 'requested_bytes': EXPECTED, ++ 'helper_sha256': hashlib.sha256(Path(__file__).read_bytes()).hexdigest(), ++ 'observation': {}} ++ def save(): ++ temporary = output / 'cache-capacity.json.tmp' ++ temporary.write_text(json.dumps(evidence, indent=2) + '\n') ++ temporary.replace(output / 'cache-capacity.json') ++ save() ++ observations = evidence['observation'] ++ failures = [] ++ # Attempt independent observations even if the environment or one endpoint is wrong. ++ for stage in ('container', 'status', 'config'): ++ try: ++ if stage == 'container': ++ info = json.loads(subprocess.check_output(['docker', 'inspect', container]))[0] ++ env = [value for value in info['Config']['Env'] if value.startswith(KEY + '=')] ++ observations['environment_values'] = env ++ observations['running'] = info['State']['Running'] ++ evidence.update(image=info['Config']['Image'], container_id=info['Id']) ++ elif stage == 'status': ++ with urllib.request.urlopen(endpoint.rstrip('/') + '/status', timeout=15) as response: ++ evidence['source_revision'] = json.load(response)['commit'] ++ else: ++ with urllib.request.urlopen(endpoint.rstrip('/') + '/config', timeout=15) as response: ++ raw = response.read() ++ evidence['config_sha256'] = hashlib.sha256(raw).hexdigest() ++ config = tomllib.loads(raw.decode()) ++ engines = [engine['mito'] for engine in config['region_engine'] if 'mito' in engine] ++ observations['mito_engine_count'] = len(engines) ++ observations['mito_cache_settings'] = [observed_cache_settings(engine) for engine in engines] ++ except Exception as error: ++ # Exception messages can embed response bodies or arbitrary configuration values. ++ failures.append({'stage': stage, 'error_type': type(error).__name__}) ++ save() ++ stage = 'observations' ++ try: ++ if failures: ++ observations['errors'] = failures ++ raise ValueError('Incomplete capacity observations') ++ stage = 'environment' ++ if env != [KEY + '=' + VALUE] or not info['State']['Running']: ++ raise ValueError('Missing explicit Parquet capacity or stopped database') ++ stage = 'mito_engine_count' ++ if len(engines) != 1: ++ raise ValueError('Expected one Mito engine') ++ mito = engines[0] ++ stage = 'parquet_capacity' ++ capacity, method, proof = resolve_capacity(mito, evidence['source_revision']) ++ evidence.update(effective_parquet_cache_bytes=capacity, capacity_evidence=method, ++ serialization_rule_evidence=proof) ++ stage = 'other_cache_settings' ++ evidence['other_cache_settings'] = other_cache_settings(mito) ++ evidence['status'] = 'passed' ++ save() ++ return evidence ++ except Exception as error: ++ evidence.update(status='failed', failed_stage=stage, error_type=type(error).__name__) ++ save() ++ raise ++ ++ ++if __name__ == '__main__': ++ attest(*sys.argv[1:]) diff --git a/.github/benchmark-patches/vmbench.patch b/.github/benchmark-patches/vmbench.patch new file mode 100644 index 00000000000..e4ae4ffbe7b --- /dev/null +++ b/.github/benchmark-patches/vmbench.patch @@ -0,0 +1,210 @@ +--- a/scripts/run_benchmark_plan.py ++++ b/scripts/run_benchmark_plan.py +@@ -474,9 +474,10 @@ + if target.get("docker", {}).get(key) is not None: + limits.extend([f"--{key}", str(target["docker"][key])]) + if kind == "greptimedb": +- env = target.get("docker", {}).get("env", {}) ++ env = target.get("docker", {}).get("env", {}).copy() ++ env["GREPTIMEDB_STANDALONE__REGION_ENGINE[0]__MITO__PAGE_CACHE_SIZE"] = "512MiB" + args = [ +- "docker", "run", "-d", ++ "docker", "run", "-d", "--entrypoint", "/greptime/bin/greptime", + "--name", name, + "--label", f"o11ybench.run-id={plan['run_id']}", + *limits, +@@ -1582,6 +1583,9 @@ + run_checked(cmd, manifest) + started_container = name + wait_for_health(target_urls(target)["health"]) ++ if target.get("kind") == "greptimedb": ++ from cache_capacity_evidence import attest ++ attest(name, target_urls(target)["health"].removesuffix("/health"), target_root) + manifest.setdefault("load_results", {})[target["name"]] = load_remote_write(plan, target, target_root) + manifest.setdefault("post_load_results", {})[target["name"]] = run_post_load_gates( + plan, target, target_root, name +--- /dev/null ++++ b/scripts/cache_capacity_evidence.py +@@ -0,0 +1,182 @@ ++#!/usr/bin/env python3 ++# Copyright 2023 Greptime Team ++# Licensed under the Apache License, Version 2.0. ++"""Benchmark-only gate for equal Parquet capacity, before load/query work.""" ++import decimal ++import hashlib ++import json ++from pathlib import Path ++import re ++import subprocess ++import sys ++import tomllib ++import urllib.request ++ ++KEY = 'GREPTIMEDB_STANDALONE__REGION_ENGINE[0]__MITO__PAGE_CACHE_SIZE' ++VALUE = '512MiB' ++EXPECTED = 512 * 1024**2 ++# Audited source: Serialize omits content_cache_size iff its value is 512 MiB. ++# Unknown revisions must provide an explicit value; schema shape alone is not proof. ++OMISSION_RULES = { ++ 'c7d970da0bb0aa2420cefef5c2cd72d6e6bb6972': { ++ 'config_git_blob': '94428174f16c79cc0dcf41715501d707272a1dc8', ++ 'path': 'src/mito2/src/config.rs', ++ 'rule': 'ParquetPageConfig::is_default_content_cache_size == ReadableSize::mb(512)', ++ }, ++} ++ ++ ++def size(value): ++ if not isinstance(value, str): ++ raise ValueError('Cache capacity must be an explicit byte string') ++ match = re.fullmatch(r'([0-9]+(?:\.[0-9]+)?)\s*(B|KiB|MiB|GiB)', value) ++ if not match: ++ raise ValueError('Unsupported cache byte format') ++ return int(decimal.Decimal(match[1]) * {'B': 1, 'KiB': 1024, 'MiB': 1024**2, 'GiB': 1024**3}[match[2]]) ++ ++ ++def resolve_capacity(mito, revision): ++ page = mito.get('parquet_page', {}) ++ if not isinstance(page, dict): ++ raise ValueError('Invalid Parquet page configuration') ++ declared = [size(value) for value in ++ (mito.get('page_cache_size'), page.get('content_cache_size')) if value is not None] ++ if len(set(declared)) > 1: ++ raise ValueError('Conflicting cache capacity aliases') ++ proof = None ++ if declared: ++ capacity, method = declared[0], 'explicit_serialized_config' ++ elif revision in OMISSION_RULES and 'content_cache_page_size' in page: ++ capacity, method = EXPECTED, 'audited_serialization_omission_rule' ++ proof = OMISSION_RULES[revision] ++ else: ++ raise ValueError('Missing capacity without an audited serialization rule') ++ if capacity != EXPECTED: ++ raise ValueError('Effective Parquet cache capacity is not 512MiB') ++ return capacity, method, proof ++ ++ ++def other_cache_settings(mito): ++ memory_fields = ('sst_meta_cache_size', 'vector_cache_size', 'selector_result_cache_size', ++ 'range_result_cache_size', 'prefilter_result_cache_size', 'manifest_cache_size') ++ index = mito['index'] ++ index_fields = ('metadata_cache_size', 'content_cache_size', 'content_cache_page_size', ++ 'result_cache_size', 'staging_size', 'write_buffer_size') ++ boolean_fields = ('enable_write_cache', 'preload_index_cache', 'enable_refill_cache_on_read') ++ if any(type(mito[field]) is not bool for field in boolean_fields): ++ raise ValueError('Invalid cache policy boolean') ++ if type(mito['index_cache_percent']) is not int or not 0 <= mito['index_cache_percent'] <= 100: ++ raise ValueError('Invalid index file-cache share') ++ return { ++ 'memory_cache_bytes': {field: size(mito[field]) for field in memory_fields}, ++ 'write_cache': { ++ **{field: mito[field] for field in boolean_fields}, ++ 'capacity_bytes': size(mito['write_cache_size']), ++ 'index_cache_percent': mito['index_cache_percent'], ++ # Option::None has no TOML value; absence is retained as null. ++ 'ttl': mito.get('write_cache_ttl'), ++ }, ++ 'index': { ++ **{field + '_bytes': size(index[field]) for field in index_fields}, ++ 'staging_ttl': index.get('staging_ttl'), ++ 'build_mode': index['build_mode'], ++ }, ++ } ++ ++ ++def observed_cache_settings(mito): ++ """Retain only cache settings, before parsing or validating their values.""" ++ fields = ('page_cache_size', 'sst_meta_cache_size', 'vector_cache_size', ++ 'selector_result_cache_size', 'range_result_cache_size', ++ 'prefilter_result_cache_size', 'manifest_cache_size', ++ 'enable_write_cache', 'write_cache_size', 'write_cache_ttl', ++ 'preload_index_cache', 'enable_refill_cache_on_read', 'index_cache_percent') ++ nested = { ++ 'parquet_page': ('content_cache_size', 'content_cache_page_size'), ++ 'index': ('metadata_cache_size', 'content_cache_size', 'content_cache_page_size', ++ 'result_cache_size', 'staging_size', 'write_buffer_size', ++ 'staging_ttl', 'build_mode'), ++ } ++ # Never copy arbitrary nested objects, even if a malformed cache field contains one. ++ def scalar(value): ++ return value if value is None or type(value) in (str, int, float, bool) else '' ++ values = {key: scalar(mito[key]) for key in fields if key in mito} ++ missing = [key for key in fields if key not in mito] ++ for section, names in nested.items(): ++ table = mito.get(section) ++ if isinstance(table, dict): ++ values[section] = {key: scalar(table[key]) for key in names if key in table} ++ missing.extend(section + '.' + key for key in names if key not in table) ++ elif section in mito: ++ values[section] = '' ++ else: ++ missing.append(section) ++ return {'values': values, 'missing_fields': missing} ++ ++ ++def attest(container, endpoint, output): ++ output = Path(output) ++ output.mkdir(parents=True, exist_ok=True) ++ evidence = {'status': 'started', 'environment_key': KEY, 'requested_bytes': EXPECTED, ++ 'helper_sha256': hashlib.sha256(Path(__file__).read_bytes()).hexdigest(), ++ 'observation': {}} ++ def save(): ++ temporary = output / 'cache-capacity.json.tmp' ++ temporary.write_text(json.dumps(evidence, indent=2) + '\n') ++ temporary.replace(output / 'cache-capacity.json') ++ save() ++ observations = evidence['observation'] ++ failures = [] ++ # Attempt independent observations even if the environment or one endpoint is wrong. ++ for stage in ('container', 'status', 'config'): ++ try: ++ if stage == 'container': ++ info = json.loads(subprocess.check_output(['docker', 'inspect', container]))[0] ++ env = [value for value in info['Config']['Env'] if value.startswith(KEY + '=')] ++ observations['environment_values'] = env ++ observations['running'] = info['State']['Running'] ++ evidence.update(image=info['Config']['Image'], container_id=info['Id']) ++ elif stage == 'status': ++ with urllib.request.urlopen(endpoint.rstrip('/') + '/status', timeout=15) as response: ++ evidence['source_revision'] = json.load(response)['commit'] ++ else: ++ with urllib.request.urlopen(endpoint.rstrip('/') + '/config', timeout=15) as response: ++ raw = response.read() ++ evidence['config_sha256'] = hashlib.sha256(raw).hexdigest() ++ config = tomllib.loads(raw.decode()) ++ engines = [engine['mito'] for engine in config['region_engine'] if 'mito' in engine] ++ observations['mito_engine_count'] = len(engines) ++ observations['mito_cache_settings'] = [observed_cache_settings(engine) for engine in engines] ++ except Exception as error: ++ # Exception messages can embed response bodies or arbitrary configuration values. ++ failures.append({'stage': stage, 'error_type': type(error).__name__}) ++ save() ++ stage = 'observations' ++ try: ++ if failures: ++ observations['errors'] = failures ++ raise ValueError('Incomplete capacity observations') ++ stage = 'environment' ++ if env != [KEY + '=' + VALUE] or not info['State']['Running']: ++ raise ValueError('Missing explicit Parquet capacity or stopped database') ++ stage = 'mito_engine_count' ++ if len(engines) != 1: ++ raise ValueError('Expected one Mito engine') ++ mito = engines[0] ++ stage = 'parquet_capacity' ++ capacity, method, proof = resolve_capacity(mito, evidence['source_revision']) ++ evidence.update(effective_parquet_cache_bytes=capacity, capacity_evidence=method, ++ serialization_rule_evidence=proof) ++ stage = 'other_cache_settings' ++ evidence['other_cache_settings'] = other_cache_settings(mito) ++ evidence['status'] = 'passed' ++ save() ++ return evidence ++ except Exception as error: ++ evidence.update(status='failed', failed_stage=stage, error_type=type(error).__name__) ++ save() ++ raise ++ ++ ++if __name__ == '__main__': ++ attest(*sys.argv[1:]) diff --git a/.github/scripts/apply-cache-capacity-patch.py b/.github/scripts/apply-cache-capacity-patch.py new file mode 100644 index 00000000000..953b5e1ddf9 --- /dev/null +++ b/.github/scripts/apply-cache-capacity-patch.py @@ -0,0 +1,103 @@ +# 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. + +"""Apply one reviewed, pinned benchmark-only cache-capacity patch before data work.""" +import argparse +import hashlib +import json +from pathlib import Path +import re +import shutil +import subprocess + +LANES = { + "agent": ("2f40fb3fdbdc", "scripts/run-agent-observability.sh"), + "vmbench": ("b43785b56f42", "scripts/run_benchmark_plan.py"), + "traces": ("77a84e1c8136", "scripts/run_tracesbench_docker.py"), +} + + +def sha(path): + return hashlib.sha256(path.read_bytes()).hexdigest() + + +def run(command, log): + result = subprocess.run(command, text=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) + log.write_text(result.stdout) + result.check_returncode() + return result.stdout + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--lane", choices=LANES, required=True) + parser.add_argument("--checkout", type=Path, required=True) + parser.add_argument("--expected-revision", required=True) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + output = args.output.resolve() + # A second invocation must not replace evidence from the first attempt. + output.mkdir(parents=True, exist_ok=False) + state = {"status": "started", "lane": args.lane, + "expected_revision": args.expected_revision, "apply_script_sha256": sha(Path(__file__))} + def save(): + temporary = output / "status.json.tmp" + temporary.write_text(json.dumps(state, indent=2) + "\n") + temporary.replace(output / "status.json") + save() + try: + # Probe before modifying the checkout or beginning data generation. + import tomllib # noqa: F401 + if shutil.which("patch") is None: + raise RuntimeError("patch executable is required") + checkout = args.checkout.resolve(strict=True) + prefix, launcher = LANES[args.lane] + if not re.fullmatch(r"[0-9a-f]{40}", args.expected_revision) or not args.expected_revision.startswith(prefix): + raise ValueError("Runtime revision is not the reviewed lane pin") + revision = run(["git", "-C", str(checkout), "rev-parse", "HEAD"], output / "revision.txt").strip() + state["original_revision"] = revision + if revision != args.expected_revision: + raise ValueError("Checkout and resolved runtime revision differ") + dirty = run(["git", "-C", str(checkout), "status", "--porcelain", "--untracked-files=all"], output / "status-before.txt") + if dirty: + raise ValueError("Benchmark checkout must be clean, including untracked files") + patch = Path(__file__).resolve().parents[1] / "benchmark-patches" / (args.lane + ".patch") + state["patch_sha256"] = sha(patch) + shutil.copyfile(patch, output / patch.name) + expected = {launcher, "scripts/cache_capacity_evidence.py"} + targets = [line[6:] for line in patch.read_text().splitlines() if line.startswith("+++ b/")] + if set(targets) != expected or len(targets) != len(expected): + raise ValueError("Patch changes files outside the reviewed lane") + state["modified_files"] = {name: {"before_sha256": sha(checkout / name) if (checkout / name).exists() else None} for name in sorted(expected)} + save() + command = ["patch", "--batch", "--forward", "--fuzz=0", "-p1", "-d", str(checkout), "-i", str(patch)] + run(command + ["--dry-run"], output / "patch-dry-run.log") + run(command, output / "patch-apply.log") + status = run(["git", "-C", str(checkout), "status", "--porcelain", "--untracked-files=all"], output / "status-after.txt") + actual = {line[3:] for line in status.splitlines()} + if actual != expected: + raise ValueError("Unexpected modified files after patch application") + for name in expected: + state["modified_files"][name]["after_sha256"] = sha(checkout / name) + run(["git", "-C", str(checkout), "diff", "--check"], output / "diff-check.txt") + state["status"] = "passed" + save() + except Exception as error: + state.update(status="failed", error=str(error)) + save() + raise + + +if __name__ == "__main__": + main() diff --git a/.github/workflows/agent-observability.yml b/.github/workflows/agent-observability.yml index d265801d4a0..2cd34873682 100644 --- a/.github/workflows/agent-observability.yml +++ b/.github/workflows/agent-observability.yml @@ -333,6 +333,18 @@ jobs: ref: ${{ env.RESOLVED_O11YBENCH_REF }} path: o11ybench persist-credentials: false + - name: Set up Python for cache capacity control + uses: actions/setup-python@v5 + with: + python-version: '3.11' + update-environment: true + - name: Apply reviewed cache capacity control + shell: bash + run: | + set -euo pipefail + python3 greptimedb/.github/scripts/apply-cache-capacity-patch.py --lane agent \ + --checkout "$GITHUB_WORKSPACE/o11ybench" --expected-revision "$RESOLVED_O11YBENCH_REF" \ + --output "$GITHUB_WORKSPACE/cache-capacity-patch" - name: Verify benchmark checkout revision shell: bash run: test "$(git -C "$O11YBENCH_DIR" rev-parse HEAD)" = "$RESOLVED_O11YBENCH_REF" @@ -424,6 +436,14 @@ jobs: if: always() && inputs.compare_greptimedb run: | python3 greptimedb/.github/scripts/benchmark-version-comparison.py report --kind agent --root "$ARTIFACT_ROOT" >> "$GITHUB_STEP_SUMMARY" + - name: Upload cache capacity patch evidence + if: always() + uses: actions/upload-artifact@v4 + with: + name: cache-capacity-patch + path: ${{ github.workspace }}/cache-capacity-patch + if-no-files-found: warn + retention-days: 14 - name: Upload results (no dataset) if: always() uses: actions/upload-artifact@v4 diff --git a/.github/workflows/tracesbench.yml b/.github/workflows/tracesbench.yml index 049faaef1a7..103fcd3e8bc 100644 --- a/.github/workflows/tracesbench.yml +++ b/.github/workflows/tracesbench.yml @@ -314,6 +314,18 @@ jobs: ref: ${{ env.RESOLVED_O11YBENCH_REF }} path: o11ybench persist-credentials: false + - name: Set up Python for cache capacity control + uses: actions/setup-python@v5 + with: + python-version: '3.11' + update-environment: true + - name: Apply reviewed cache capacity control + shell: bash + run: | + set -euo pipefail + python3 greptimedb/.github/scripts/apply-cache-capacity-patch.py --lane traces \ + --checkout "$GITHUB_WORKSPACE/o11ybench" --expected-revision "$RESOLVED_O11YBENCH_REF" \ + --output "$GITHUB_WORKSPACE/cache-capacity-patch" - name: Check runner and runtime identity id: runtime run: | @@ -446,6 +458,14 @@ jobs: mkdir -p "$RUNNER_TEMP/tracesbench-artifacts/baseline" rsync -a --no-owner --no-group "$RUN_ROOT/baseline/runs" "$RUNNER_TEMP/tracesbench-artifacts/baseline/" fi + - name: Upload cache capacity patch evidence + if: always() + uses: actions/upload-artifact@v4 + with: + name: cache-capacity-patch + path: ${{ github.workspace }}/cache-capacity-patch + if-no-files-found: warn + retention-days: 14 - name: Upload HTML and results (no corpus) if: always() uses: actions/upload-artifact@v4 diff --git a/.github/workflows/vmbench-long-range.yml b/.github/workflows/vmbench-long-range.yml index aaf2dd7f437..df8e138bc78 100644 --- a/.github/workflows/vmbench-long-range.yml +++ b/.github/workflows/vmbench-long-range.yml @@ -275,6 +275,18 @@ jobs: ref: ${{ env.RESOLVED_O11YBENCH_REF }} path: o11ybench persist-credentials: false + - name: Set up Python for cache capacity control + uses: actions/setup-python@v5 + with: + python-version: '3.11' + update-environment: true + - name: Apply reviewed cache capacity control + shell: bash + run: | + set -euo pipefail + python3 greptimedb/.github/scripts/apply-cache-capacity-patch.py --lane vmbench \ + --checkout "$GITHUB_WORKSPACE/o11ybench" --expected-revision "$RESOLVED_O11YBENCH_REF" \ + --output "$GITHUB_WORKSPACE/cache-capacity-patch" - uses: actions/download-artifact@v4 with: name: ${{ needs.validate.outputs.plan_artifact }} @@ -340,6 +352,14 @@ jobs: rsync -a --no-owner --no-group --exclude='db-data/' --exclude='/data/*.bin' \ "$ARTIFACT_ROOT-warm/" "$RUNNER_TEMP/vmbench-artifacts/$(basename "$ARTIFACT_ROOT-warm")/" fi + - name: Upload cache capacity patch evidence + if: always() + uses: actions/upload-artifact@v4 + with: + name: cache-capacity-patch + path: ${{ github.workspace }}/cache-capacity-patch + if-no-files-found: warn + retention-days: 14 - name: Upload HTML and results (no dataset or DB files) if: always() uses: actions/upload-artifact@v4