Merge upstream/main into feat/flow-memory-scope

Conflict: FrontendClient::sql gained a timezone parameter upstream while
this branch added the flow extensions parameter. Both are kept: the
signature takes extensions and timezone; the distributed path applies the
timezone override and then forwards the flow extensions, the standalone
path sets both on the QueryContext builder.

Signed-off-by: discord9 <discord9@163.com>
This commit is contained in:
discord9
2026-11-10 20:32:29 +08:00
354 changed files with 37301 additions and 4824 deletions
@@ -50,6 +50,11 @@ inputs:
runs:
using: composite
steps:
- name: Set up Linux runner
uses: ./.github/actions/setup-linux-runner
with:
tools: make shasum
- name: Run integration test
if: ${{ inputs.disable-run-tests == 'false' }}
shell: bash
@@ -1,19 +1,41 @@
name: Set up benchmark dependencies
name: Set up Linux runner dependencies
description: Reuse installed tools and install missing dependencies on an Ubuntu self-hosted runner
inputs:
tools:
description: Space-separated commands to install if missing (Ubuntu package names, except shasum)
required: false
default: curl
expected-architecture:
description: Optional uname architecture required by the workload
required: false
default: ''
runs:
using: composite
steps:
- name: Check host and install missing tools
shell: bash
env:
REQUIRED_TOOLS: ${{ inputs.tools }}
EXPECTED_ARCH: ${{ inputs.expected-architecture }}
run: |
set -euo pipefail
[[ "$(uname -m)" == x86_64 ]]
if [[ -n "$EXPECTED_ARCH" ]]; then
[[ "$(uname -m)" == "$EXPECTED_ARCH" ]]
fi
command -v git
missing=()
for tool in curl jq python3 rsync; do
command -v "$tool" >/dev/null || missing+=("$tool")
read -r -a tools <<< "$REQUIRED_TOOLS"
for tool in "${tools[@]}"; do
if ! command -v "$tool" >/dev/null; then
case "$tool" in
shasum) missing+=(libdigest-sha-perl) ;;
*) missing+=("$tool") ;;
esac
fi
done
if ((${#missing[@]})); then
. /etc/os-release
[[ "$ID" == ubuntu ]]
sudo -n apt-get update
sudo -n env DEBIAN_FRONTEND=noninteractive NEEDRESTART_MODE=l apt-get install -y --no-install-recommends "${missing[@]}"
fi
@@ -24,6 +46,8 @@ runs:
if ! command -v docker >/dev/null; then
. /etc/os-release
[[ "$ID" == ubuntu ]]
sudo -n apt-get update
sudo -n env DEBIAN_FRONTEND=noninteractive NEEDRESTART_MODE=l apt-get install -y --no-install-recommends curl ca-certificates
sudo -n install -m 0755 -d /etc/apt/keyrings
curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo -n tee /etc/apt/keyrings/docker.asc >/dev/null
sudo -n chmod a+r /etc/apt/keyrings/docker.asc
@@ -133,9 +133,10 @@ def benchmark(root, targets):
return '\n'.join(lines)
def lifecycle(root, targets):
manifest = read(root / 'run-manifest.json')
corpus = read(root / 'corpus' / 'summary.json')
def lifecycle(root, targets, data_root=None):
data_root = data_root or root
manifest = read(data_root / 'run-manifest.json')
corpus = read(data_root / 'corpus' / 'summary.json')
lines = ['# Load / lifecycle summary', '',
f'Dataset: **{cell(manifest.get("profile", corpus.get("data_profile", {}).get("id")))}**; rows: **{cell(corpus.get("line_count"))}**; '
f'seed: `{cell(corpus.get("seed"))}`.',
@@ -161,12 +162,13 @@ def lifecycle(root, targets):
physical_rows = []
load_rows = []
details = ['<details>', '<summary>DDL, index configuration and image provenance</summary>', '']
raw_bytes = read(root / 'corpus' / 'size.json').get('raw_jsonl_bytes')
raw_bytes = read(data_root / 'corpus' / 'size.json').get('raw_jsonl_bytes')
for t in targets:
directory = result_dir(root, t)
physical = read(directory / 'physical-evidence.json')
storage = physical.get('storage', {})
total = storage.get('engine_total_bytes')
s3 = read(root / f'{t}-1' / 'storage.json').get('type') == 's3'
total = None if s3 else storage.get('engine_total_bytes')
stats = read(root / f'{t}-1' / 'post-load-docker-stats.json')
ratio = f'{raw_bytes / total:.2f}×' if (physical.get('passed') is True and
isinstance(raw_bytes, (int, float)) and raw_bytes > 0 and
@@ -186,6 +188,7 @@ def lifecycle(root, targets):
lines += ['## Load and physical evidence', '', table(['DB', 'Write transport', 'Batches', 'Load smoke rows'], load_rows), '',
f'Raw JSONL size: **{size(raw_bytes)}**. Ratio = raw JSONL / engine bytes at collection time; '
'not a settled-storage guarantee. CPU/memory are post-load snapshots, not peaks. '
'S3 total/compression is omitted: local files exclude remote objects. '
'Missing artifacts remain blank; pre-cleanup stats are not substituted.', '',
table(['DB', 'Engine size', 'Size ratio', 'Materialization', 'SSTs / active parts',
'Post-load CPU', 'Post-load memory / limit'], physical_rows), '', *details, '</details>', '']
+25 -13
View File
@@ -62,11 +62,12 @@ def row(query, metric, old, new, compatible, reason):
improvement_percent=delta, status='comparable' if delta is not None else reason)
def agent(root):
def agent(root, storage="file"):
candidate, baseline = (root, root / "baseline") if storage == "file" else (root / "s3", root / "baseline/s3")
def load(r):
return read(r / 'greptimedb-1/greptimedb-1/measured-summary.json')
a, b = load(root / 'baseline'), load(root)
finished = [r / 'greptimedb-1/exit-code.txt' for r in (root / 'baseline', root)]
a, b = load(baseline), load(candidate)
finished = [r / 'greptimedb-1/exit-code.txt' for r in (baseline, candidate)]
compatible = (all(p.is_file() and p.read_text().strip() == '0' for p in finished)
and a.get('passed') is True and b.get('passed') is True
and same(a, b, ('contract_sha256', 'data_profile', 'query_window', 'warmup_runs', 'measured_runs')))
@@ -81,8 +82,9 @@ def agent(root):
return rows
def traces(root):
a, b = (read(r / 'runs/greptimedb/run.json') for r in (root / 'baseline', root))
def traces(root, storage="file"):
candidate, baseline = (root, root / "baseline") if storage == "file" else (root / "s3", root / "baseline/s3")
a, b = (read(r / 'runs/greptimedb/run.json') for r in (baseline, candidate))
compatible = (a.get('success') is True and b.get('success') is True
and same(a, b, ('expected', 'protocol', 'audit_expected', 'corpus'))
and same(a.get('execution', {}), b.get('execution', {}),
@@ -110,18 +112,22 @@ def traces(root):
return rows
def long_range(root):
def long_range(root, storage="file"):
names = ("greptimedb-baseline", "greptimedb") if storage == "file" else ("greptimedb-s3-baseline", "greptimedb-s3")
def target_root(name):
nested = root / "o11ybench" / ("o11ybench-" + name)
return nested if nested.exists() else root
rows = []
manifest = read(root / 'run-manifest.json')
manifests = {name: read(target_root(name) / 'run-manifest.json') for name in names}
healthy = all(
all(field in (manifest.get(phase, {}).get(target, {}).get('docker', {}) if phase == 'post_load_results'
else manifest.get(phase, {}).get(target, {})).get('state', '').split()
all(field in (manifests[target].get(phase, {}).get(target, {}).get('docker', {}) if phase == 'post_load_results'
else manifests[target].get(phase, {}).get(target, {})).get('state', '').split()
for field in ('Running=true', 'ExitCode=0', 'OOMKilled=false'))
for phase in ('post_load_results', 'post_query_results')
for target in ('greptimedb-baseline', 'greptimedb'))
for target in names)
for mode in ('serial', 'concurrent-duration-c1', 'concurrent-duration-c4'):
a, b = (read(root / name / 'results-vmbench-long-range' / (mode + '-summary.json'))
for name in ('greptimedb-baseline', 'greptimedb'))
a, b = (read(target_root(name) / name / 'results-vmbench-long-range' / (mode + '-summary.json'))
for name in names)
fields = ('workload', 'query_file_sha256', 'start', 'end', 'step', 'profile', 'data_duration',
'scrape_interval', 'cache_policy_effective', 'mode', 'connection_mode', 'request_timeout_seconds')
fields += ('tries', 'warmup_runs') if mode == 'serial' else ('concurrency', 'duration_seconds', 'warmup_seconds')
@@ -178,7 +184,13 @@ def main():
parser.error('report requires --root and --kind')
document = {'kind': args.kind, 'baseline_tag': os.environ.get('BASELINE_GREPTIMEDB_TAG', ''),
'candidate_tag': os.environ.get('GREPTIMEDB_TAG', ''),
'rows': {'agent': agent, 'traces': traces, 'long-range': long_range}[args.kind](args.root)}
'rows': []}
mode = os.environ.get('GREPTIMEDB_STORAGE', 'file')
for storage in (['file', 's3'] if mode == 'both' else [mode]):
rows = {'agent': agent, 'traces': traces, 'long-range': long_range}[args.kind](args.root, storage)
for item in rows:
item['query'] = storage.upper() + '/' + item['query']
document['rows'].extend(rows)
text = render(document)
# Preserve partial comparisons even if a target failed before creating output.
args.root.mkdir(parents=True, exist_ok=True)
+12 -5
View File
@@ -13,8 +13,12 @@ AWS uses `aws-ec2-runner-provision.py` and `aws-ec2-runner-teardown.py` directly
Repository variables supply `EC2_RUNNER_REGION`, `EC2_RUNNER_SUBNET_ID`, and
`EC2_RUNNER_SECURITY_GROUP_ID`; credentials use `AWS_ACCESS_KEY_ID`,
`AWS_SECRET_ACCESS_KEY`, and `GH_PERSONAL_ACCESS_TOKEN` secrets.
The current region is Singapore (`ap-southeast-1`). By default the script selects
the newest available Canonical Ubuntu 24.04 amd64 server AMI in that region
The runner region comes from `EC2_RUNNER_REGION` (currently `us-east-1`).
The subnet and security group must belong to the selected AWS account and region.
For benchmarks using real S3, `AWS_CI_TEST_BUCKET_REGION` must match the runner
region; `AWS_CI_TEST_BUCKET` must be accessible with the configured credentials.
By default the script selects the newest available Canonical Ubuntu 24.04 amd64
server AMI in that region
(owner `099720109477`) and logs its ID. Set `BENCHMARK_EC2_IMAGE_ID` to pin a
prepared Ubuntu AMI. Existing build CI's `EC2_RUNNER_LINUX_AMD64_IMAGE_ID` is
unaffected. Both workflows default `system_disk_gib` to `auto` (also accepting
@@ -31,9 +35,12 @@ swappiness 10, disables systemd-oomd and background automatic updates, and sets
`OOMPolicy=continue` on the runner service. Explicit setup package installation
remains enabled.
Both benchmark jobs call `.github/actions/setup-benchmark` after checkout. It
reuses existing tools, installs missing curl/jq/python3/rsync, installs Docker CE
if absent, and checks Docker access. Missing packages require passwordless sudo;
Benchmark jobs call `.github/actions/setup-linux-runner` after checkout with
`tools: curl jq python3 rsync` and require x86_64. Linux artifact builds reuse
the same action with `tools: make shasum` on either amd64 or arm64; the RISC-V
cross-build calls it on amd64 too. The action reuses installed commands, maps
`shasum` to Ubuntu package `libdigest-sha-perl`, installs Docker CE if absent,
and checks Docker access. Missing packages require passwordless sudo;
Aliyun's prepared image normally provides the tools and Docker already. Existing
Docker installations are preserved, so exact versions need not match between
providers. Provisioning must establish Docker permissions before starting the
+4 -3
View File
@@ -105,8 +105,9 @@ class Benchmark:
self.endpoint = os.environ.get("S3_ENDPOINT", "")
if self.endpoint and not local_smoke:
raise ValueError("Custom S3 endpoints are restricted to local smoke")
if not local_smoke and os.environ["S3_REGION"] != "ap-southeast-1":
raise ValueError("Cloud benchmark requires ap-southeast-1")
if not local_smoke and (not os.environ["S3_REGION"].strip()
or os.environ["S3_REGION"] != os.environ["RUNNER_REGION"]):
raise ValueError("Cloud benchmark requires the same nonempty bucket and runner region")
self.containers = set()
self.network_created = False
self.phases = []
@@ -324,7 +325,7 @@ level = "info"
lines = ["# Metric packed snapshot benchmark", "", f"Image: `{self.image}`",
f"Source commit: `{self.commit}`", "",
"Local smoke only; timings are not AWS results." if self.local_smoke else
"AWS S3 in ap-southeast-1; source and target use local File storage.", "",
f"S3 in {os.environ['S3_REGION']}; source and target use local File storage.", "",
"| Round | Phase | Seconds | Result |", "| --- | --- | ---: | --- |"]
for phase in self.phases:
lines.append(f"| {phase['round']} | {phase['phase']} | {phase['wall_seconds']:.3f} | {phase['outcome']} |")
+25 -12
View File
@@ -21,7 +21,7 @@
"""Budget preflight and strictly scoped S3 operations for the metric snapshot benchmark."""
import argparse
from decimal import Decimal
from decimal import Decimal, InvalidOperation
import json
import os
from pathlib import Path
@@ -29,8 +29,8 @@ import re
import time
import urllib.request
REGION = "ap-southeast-1"
HOURLY_USD = Decimal("0.9408")
# Historical budget estimate; dispatch can supply a rate for the configured region.
DEFAULT_HOURLY_USD = "0.9408"
OTHER_RESERVE_USD = Decimal("1.50")
@@ -40,6 +40,16 @@ def owned_prefix(prefix):
return prefix
def hourly_estimate(env):
try:
estimate = Decimal(env.get("EC2_HOURLY_USD", DEFAULT_HOURLY_USD))
except InvalidOperation as error:
raise ValueError("EC2_HOURLY_USD must be a positive finite estimate") from error
if not estimate.is_finite() or estimate <= 0:
raise ValueError("EC2_HOURLY_USD must be a positive finite estimate")
return estimate
def plan(env):
image = env["GREPTIMEDB_IMAGE"]
if not re.fullmatch(r"greptime/greptimedb(?:-nightly)?@sha256:[0-9a-f]{64}", image):
@@ -49,21 +59,22 @@ def plan(env):
tables, minutes = int(env["LOGICAL_TABLES_PER_GROUP"]), int(env["BENCHMARK_TIMEOUT_MINUTES"])
if not 50 <= tables <= 10_000 or not 30 <= minutes <= 240:
raise ValueError("logical tables per group must be 50..10000; timeout must be 30..240 minutes")
if env["S3_REGION"] != REGION or env["RUNNER_REGION"] != REGION:
raise ValueError("bucket and runner must both use ap-southeast-1")
if not env["S3_REGION"].strip() or env["S3_REGION"] != env["RUNNER_REGION"]:
raise ValueError("bucket and runner must use the same nonempty region")
if not env["S3_BUCKET"]:
raise ValueError("S3 bucket is required")
prior = Decimal(env["PRIOR_SPEND_USD"])
# Reserve 45m provision, 10m queue allowance and 20m cleanup beyond the job timeout.
reservation = HOURLY_USD * Decimal(minutes + 75) / 60 + OTHER_RESERVE_USD
hourly = hourly_estimate(env)
reservation = hourly * Decimal(minutes + 75) / 60 + OTHER_RESERVE_USD
if not prior.is_finite() or prior < 0 or prior >= 15 or prior + reservation > 20:
raise ValueError("campaign budget exhausted: prior spend must be below $15 and leave the full attempt reserve within $20")
return {"image": image, "expected_commit": env["EXPECTED_COMMIT"],
"logical_tables_per_group": tables, "smoke_logical_tables": 500,
"timeout_minutes": minutes, "prefix": owned_prefix(env["RUN_PREFIX"]),
"instance_type": "c6id.4xlarge", "region": REGION,
"instance_type": "c6id.4xlarge", "region": env["S3_REGION"],
"prior_estimated_usd": str(prior), "attempt_reserve_usd": str(reservation),
"ec2_hourly_usd": str(HOURLY_USD), "other_reserve_usd": str(OTHER_RESERVE_USD),
"ec2_hourly_usd": str(hourly), "other_reserve_usd": str(OTHER_RESERVE_USD),
"cost_note": "Estimate, not an AWS billing total or a hard spending cap."}
@@ -71,8 +82,8 @@ def client(region):
import boto3
from botocore.config import Config
if region != REGION:
raise ValueError("S3 region must be ap-southeast-1")
if not region.strip():
raise ValueError("S3 region is required")
return boto3.client("s3", region_name=region, config=Config(
connect_timeout=10, read_timeout=30, retries={"mode": "standard", "max_attempts": 3}))
@@ -193,8 +204,10 @@ def main():
if args.started_at is None:
parser.error("cost requires --started-at")
seconds = max(0, int(time.time()) - args.started_at)
estimate = HOURLY_USD * Decimal(seconds) / 3600
result = {"allocation_window_seconds": seconds, "ec2_estimate_usd": str(round(estimate, 4)),
hourly = hourly_estimate(os.environ)
estimate = hourly * Decimal(seconds) / 3600
result = {"allocation_window_seconds": seconds, "ec2_hourly_usd": str(hourly),
"ec2_estimate_usd": str(round(estimate, 4)),
"campaign_estimate_with_other_reserve_usd": str(round(
Decimal(os.environ["PRIOR_SPEND_USD"]) + estimate + OTHER_RESERVE_USD, 4)),
"note": "Allocation wall-time estimate plus $1.50 reserve for S3, disk and IPv4; not an AWS bill."}
+316
View File
@@ -0,0 +1,316 @@
# 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.
"""Select File/S3 benchmark arms without changing workload adapters."""
import argparse
import copy
import importlib.util
import json
from pathlib import Path
import sys
import os
import subprocess
def validate(env):
mode = env.get('GREPTIMEDB_STORAGE', 'file')
if mode not in ('file', 's3', 'both'):
raise ValueError('GREPTIMEDB_STORAGE must be file, s3 or both')
if mode != 'file':
if env.get('RUN_GREPTIMEDB') != 'true':
raise ValueError('S3 requires Run GreptimeDB')
if env.get('PROVIDER') != 'AWS':
raise ValueError('S3 comparisons require an AWS runner')
if not env.get('S3_BUCKET') or not env.get('S3_REGION'):
raise ValueError('AWS_CI_TEST_BUCKET and AWS_CI_TEST_BUCKET_REGION must be configured')
if env['S3_REGION'] != env.get('RUNNER_REGION'):
raise ValueError('S3 bucket and EC2 runner regions must match')
return mode
def replace(command, key, value):
result = list(command)
if key in result:
result[result.index(key) + 1] = value
else:
result += [key, value]
return result
def commands(command, mode):
"""Recovery visits each owned root; execution uses explicit workflow steps."""
stage = command[command.index('--stage') + 1]
if stage != 'cleanup':
raise ValueError('only cleanup may expand multiple arms')
result = [list(command)]
if mode != 'file':
root = command[command.index('--root') + 1]
owner = command[command.index('--owner') + 1]
secondary = replace(command, '--root', root + '/s3')
result.append(replace(secondary, '--owner', owner + '-s3'))
return result
def module(path):
sys.path.insert(0, str(path.parent))
spec = importlib.util.spec_from_file_location(path.stem.replace('-', '_'), path)
result = importlib.util.module_from_spec(spec)
spec.loader.exec_module(result)
return result
def summary(kind, root, targets, section, mode):
filename = 'agent-observability-summary.py' if kind == 'agent' else 'tracesbench-summary.py'
renderer = module(Path(__file__).with_name(filename))
primary = [t for t in targets if t != 'greptimedb' or mode != 's3']
arms = [(root, primary, 'File')]
if mode != 'file' and 'greptimedb' in targets:
arms.append((root / 's3', ['greptimedb'], 'S3'))
output = []
for arm, selected, label in arms:
if not selected:
continue
output.append('## ' + ('GreptimeDB S3' if label == 'S3' else 'Primary targets (GreptimeDB File)'))
if kind == 'agent':
body = (renderer.benchmark(arm, selected) if section == 'benchmark'
else renderer.lifecycle(arm, selected, data_root=root.parent if root.name == 'baseline' else root))
else:
report, runs = renderer.load(arm)
body = (renderer.benchmark(report, runs, selected) if section == 'benchmark'
else renderer.lifecycle(report, runs, arm, selected))
body = body.replace('| greptimedb |', '| GreptimeDB ' + label + ' |')
body = body.replace('**greptimedb**', '**GreptimeDB ' + label + '**')
output.append(body)
if label == 'S3':
directories = [arm / 'greptimedb-1'] if kind == 'agent' else [arm / 'runs/greptimedb']
for directory in directories:
for action in ('probe', 'inventory', 'cleanup'):
path = directory / ('s3-' + action + '.json')
data = json.loads(path.read_text()) if path.exists() else {}
status = 'passed' if data.get('passed') is True else 'failed / unavailable'
count = data.get('object_count', data.get('deleted_objects', '—'))
output.append(f'- S3 {action}: **{status}**; objects: {count}.')
return '\n\n'.join(output)
def split_metrics(plan):
"""One executor root per target, with the immutable dataset shared by all."""
result = {}
for target in plan['targets']:
child = copy.deepcopy(plan)
name = target['name']
dest = str(Path(plan['output_root']) / 'o11ybench' / ('o11ybench-' + name))
child['output_root'] = dest
child['run_id'] = plan['run_id'] + '-' + name
child['targets'] = [copy.deepcopy(target)]
child['data']['generate'] = False
child['report'].update(root=dest + '/report', index_html=dest + '/report/index.html')
child['artifacts'] = {k: dest + '/' + Path(v).name for k, v in plan['artifacts'].items()}
result[name] = child
return result
def metrics(action, args):
parser = argparse.ArgumentParser()
parser.add_argument('--plan', type=Path, required=True)
parser.add_argument('--tools', type=Path, required=True)
parser.add_argument('--runtime-image', required=True)
parser.add_argument('--target')
a = parser.parse_args(args)
plan = json.loads(a.plan.read_text())
plan['runtime_image'] = a.runtime_image
executor = module(a.tools / 'scripts/run_benchmark_plan.py')
root = Path(plan['output_root'])
if action == 'metrics-prepare':
executor.require_safe_execute_root(root)
root.mkdir(parents=True, exist_ok=False)
manifest = executor.build_manifest(plan)
executor.run_checked([str(executor.DOWNLOAD_DATA)], manifest,
env=executor.generation_environment(plan))
(root / 'generation.json').write_text(json.dumps(manifest, indent=2) + '\n')
for name, child in split_metrics(plan).items():
(a.plan.parent / (name + '.json')).write_text(json.dumps(child, indent=2) + '\n')
elif action == 'metrics-run':
path = a.plan.parent / (a.target + '.json')
child = json.loads(path.read_text())
executor.execute_plan(child, executor.build_manifest(child), replace=False)
subprocess.run([sys.executable, str(a.tools / 'scripts/check_run_benchmark_plan.py'),
'--artifacts', child['output_root']], check=True)
else:
# Validate every selected target together, retaining cross-target gates.
manifests = [executor.build_manifest(child) for child in split_metrics(plan).values()]
combined = executor.build_manifest(plan)
combined['targets'] = [target for m in manifests for target in m['targets']]
for command in executor.validation_commands(combined):
subprocess.run(command, check=True)
def overview(path):
"""Render the same validated report data into the GitHub job summary."""
data = json.loads(path.read_text())
renderer = module(Path(__file__).with_name('agent-observability-summary.py'))
lines = ['# Storage comparison', '', 'Smoke results are diagnostic; see classification per arm. '
'No cold-object-store performance claim. Missing results are not passes.', '']
for workload in data['workloads']:
labels = {p['id']: p['label'] for p in workload['participants']}
for scenario in workload['scenarios']:
lines += ['## ' + workload['title'] + ' / ' + scenario['label'], '']
rows = []
for result in scenario['results']:
lines += [labels[result['participant']] + ': ' + str(result.get('classification')), '']
for query_id, query in result['queries'].items():
m = query['metrics']
rows.append([query_id, labels[result['participant']], query['status'],
renderer.duration(m.get('p50_ms', m.get('median_ms'))),
renderer.duration(m.get('p95_ms')), renderer.duration(m.get('p99_ms'))])
lines.append(renderer.table(['Query', 'DB / storage', 'Status', 'P50 / median', 'P95', 'P99'], rows))
return '\n'.join(lines)
def audit(root, report, targets, mode, baseline=False, allow_trace_query_failures=False):
data = json.loads(report.read_text())
actual = {(p['target'], p.get('storage', {}).get('type'), p['role'])
for w in data['workloads'] for p in w['participants']}
expected = {(t, None, 'comparison') for t in targets if t != 'greptimedb'}
modes = ['file', 's3'] if mode == 'both' else [mode]
if 'greptimedb' in targets:
expected |= {('greptimedb', m, role) for m in modes
for role in (['candidate', 'baseline'] if baseline else ['candidate'])}
if actual != expected:
raise ValueError(f'participant mismatch: expected {sorted(map(str, expected))}, got {sorted(map(str, actual))}')
query_failures = []
for w in data['workloads']:
partial = allow_trace_query_failures and w.get('id') == 'traces'
if partial and not w['scenarios']:
raise ValueError('missing trace scenarios')
for scenario in w['scenarios']:
if partial and {r['participant'] for r in scenario['results']} != {p['id'] for p in w['participants']}:
raise ValueError('missing trace participant results')
for result in scenario['results']:
if partial and result.get('health') != 'recorded healthy snapshots':
raise ValueError('missing or unhealthy trace evidence: ' + result['participant'])
queries = result['queries']
if not any(q['status'] == 'passed' for q in queries.values()):
raise ValueError('no successful measured queries: ' + result['participant'])
if any(q['status'] == 'unavailable' or (q['status'] == 'failed' and not partial)
for q in queries.values()):
raise ValueError('failed or unavailable queries: ' + result['participant'])
for query_id, query in queries.items():
if query['status'] == 'failed':
query_failures.append(dict(workload=w['id'], scenario=scenario['id'],
participant=result['participant'], query=query_id,
reason=query.get('reason', '')))
for manifest_path in root.glob('o11ybench/*/run-manifest.json'):
manifest = json.loads(manifest_path.read_text())
if manifest.get('status') != 'passed':
raise ValueError('incomplete target manifest: ' + str(manifest_path))
probes = list(root.rglob('s3-probe.json'))
expected_s3 = sum(m == 's3' for _, m, _ in expected)
if len(probes) != expected_s3:
raise ValueError('missing or duplicate S3 evidence')
for probe in probes:
for action in ('probe', 'inventory', 'cleanup'):
payload = json.loads(probe.with_name('s3-' + action + '.json').read_text())
if payload.get('passed') is not True or (action == 'inventory' and payload.get('object_count', 0) <= 0):
raise ValueError('failed S3 ' + action)
text = (root / 'ci-summary.md').read_text()
for m in modes if 'greptimedb' in targets else []:
if m.upper() not in text:
raise ValueError('storage mode missing from saved summary: ' + m)
result = dict(passed=True, participants=[dict(target=t, storage=m, role=role)
for t, m, role in sorted(expected, key=str)], s3_arms=len(probes), query_failures=query_failures)
(root / 'artifact-audit.json').write_text(json.dumps(result, indent=2) + '\n')
lines = ['## Artifact validation', '', '- Selected participants: ' + str(len(expected)) + '; all present.',
'- Query result coverage and S3 probe/inventory/cleanup: passed.', '']
if query_failures:
lines += ['- Collection completed with query failures; this is not an all-pass query run.', '']
lines += [f"- {f['participant']} / {f['query']}: failed (excluded from comparison)."
for f in query_failures]
lines.append('')
renderer = module(Path(__file__).with_name('agent-observability-summary.py'))
rows = []
for probe in probes:
inv = json.loads(probe.with_name('s3-inventory.json').read_text())
cleanup = json.loads(probe.with_name('s3-cleanup.json').read_text())
rows.append([str(probe.parent.relative_to(root)), inv['object_count'], inv['object_bytes'],
cleanup.get('deleted_objects'), 'passed'])
if rows:
lines.append(renderer.table(['S3 arm', 'Objects', 'Remote bytes', 'Deleted current objects', 'Cleanup'], rows))
text = '\n'.join(lines) + '\n'
with (root / 'ci-summary.md').open('a') as output:
output.write(text)
if os.environ.get('GITHUB_STEP_SUMMARY'):
with Path(os.environ['GITHUB_STEP_SUMMARY']).open('a') as output:
output.write(text)
return result
def main():
if len(sys.argv) > 1 and sys.argv[1] == 'audit':
parser = argparse.ArgumentParser()
parser.add_argument('--root', type=Path, required=True)
parser.add_argument('--report', type=Path, required=True)
parser.add_argument('--targets', required=True)
parser.add_argument('--allow-trace-query-failures', action='store_true',
help='Retain failed Traces queries after native validation; missing results still fail')
args = parser.parse_args(sys.argv[2:])
print(json.dumps(audit(args.root, args.report, args.targets.split(','),
os.environ.get('GREPTIMEDB_STORAGE', 'file'),
os.environ.get('COMPARE_GREPTIMEDB') == 'true', args.allow_trace_query_failures)))
return
if len(sys.argv) > 1 and sys.argv[1] == 'normalize-metrics':
path = Path(sys.argv[2])
plan = json.loads(path.read_text())
for target in plan['targets']:
if target.get('storage', {}).get('type') == 's3' and '-s3' not in target['name']:
target['name'] = target['name'].replace('-baseline', '-s3-baseline') if target['name'].endswith('-baseline') else target['name'] + '-s3'
path.write_text(json.dumps(plan, indent=2) + '\n')
return
if len(sys.argv) > 1 and sys.argv[1].startswith('metrics-'):
metrics(sys.argv[1], sys.argv[2:])
return
if len(sys.argv) > 1 and sys.argv[1] == 'overview':
print(overview(Path(sys.argv[2])))
return
if len(sys.argv) > 1 and sys.argv[1] == 'summary':
parser = argparse.ArgumentParser()
parser.add_argument('--kind', choices=['agent', 'traces'], required=True)
parser.add_argument('--root', type=Path, required=True)
parser.add_argument('--targets', required=True)
parser.add_argument('--section', choices=['benchmark', 'lifecycle'], required=True)
args = parser.parse_args(sys.argv[2:])
print(summary(args.kind, args.root, args.targets.split(','), args.section,
os.environ.get('GREPTIMEDB_STORAGE', 'file')))
return
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('action', choices=['validate', 'run'])
parser.add_argument('command', nargs=argparse.REMAINDER)
args = parser.parse_args()
mode = validate(os.environ)
if args.action == 'validate':
print('GreptimeDB storage: ' + mode)
return
command = args.command[1:] if args.command[:1] == ['--'] else args.command
planned = commands(command, mode)
failed = 0
for cmd in planned:
result = subprocess.run(cmd)
failed = failed or result.returncode
# Cleanup must try both arms even if one failed. Target failures remain
# visible, while the other arm can still produce diagnostic evidence.
raise SystemExit(failed)
if __name__ == '__main__':
main()
@@ -28,6 +28,25 @@ SPEC.loader.exec_module(bench)
class PhaseTests(unittest.TestCase):
def test_cloud_region_configuration(self):
for bucket, runner, accepted in (("us-east-1", "us-east-1", True),
("ap-southeast-1", "ap-southeast-1", True),
("us-east-1", "ap-southeast-1", False),
("", "", False)):
with self.subTest(bucket=bucket, runner=runner), tempfile.TemporaryDirectory() as directory:
env = dict(GREPTIMEDB_IMAGE="greptime/greptimedb@sha256:" + "a" * 64,
EXPECTED_COMMIT="b" * 40, RUN_PREFIX="metric-snapshot-bench/123-1/",
RESULTS=str(Path(directory) / "results"), DATA_ROOT=str(Path(directory) / "data"),
S3_REGION=bucket, RUNNER_REGION=runner, S3_ENDPOINT="")
with patch.dict(bench.os.environ, env):
if accepted:
benchmark = bench.Benchmark(local_smoke=False)
benchmark.summary()
self.assertIn(f"S3 in {bucket};", (benchmark.results / "summary.md").read_text())
else:
with self.assertRaisesRegex(ValueError, "same nonempty"):
bench.Benchmark(local_smoke=False)
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")
@@ -20,6 +20,7 @@ import io
import json
from pathlib import Path
import tempfile
import types
import unittest
from unittest import mock
@@ -82,6 +83,45 @@ class OperationsTest(unittest.TestCase):
with self.subTest(changes=changes), self.assertRaises(ValueError):
ops.plan(self.env(**changes))
def test_regions_follow_configuration_and_reject_mismatch_or_empty(self):
for region in ("us-east-1", "ap-southeast-1"):
with self.subTest(region=region):
self.assertEqual(ops.plan(self.env(S3_REGION=region, RUNNER_REGION=region))["region"], region)
for bucket, runner in (("us-east-1", "ap-southeast-1"), ("", ""), (" ", " ")):
with self.subTest(bucket=bucket, runner=runner), self.assertRaises(ValueError):
ops.plan(self.env(S3_REGION=bucket, RUNNER_REGION=runner))
def test_client_uses_configured_region(self):
boto = types.ModuleType("boto3")
boto.client = mock.Mock()
config = types.ModuleType("botocore.config")
config.Config = mock.Mock()
with mock.patch.dict("sys.modules", {"boto3": boto, "botocore.config": config}):
for region in ("us-east-1", "ap-southeast-1"):
ops.client(region)
self.assertEqual(boto.client.call_args.kwargs["region_name"], region)
with self.assertRaises(ValueError):
ops.client("")
def test_hourly_estimate_controls_reservation_and_cost(self):
env = self.env(EC2_HOURLY_USD="2", BENCHMARK_TIMEOUT_MINUTES="30")
plan = ops.plan(env)
self.assertEqual(plan["ec2_hourly_usd"], "2")
self.assertEqual(plan["attempt_reserve_usd"], "5.00")
with mock.patch.dict(ops.os.environ, env), mock.patch.object(ops.time, "time", return_value=4600), \
mock.patch("sys.argv", ["ops", "cost", "--started-at", "1000"]), \
mock.patch("sys.stdout", new_callable=io.StringIO) as output:
ops.main()
cost = json.loads(output.getvalue())
self.assertEqual(cost["ec2_hourly_usd"], "2")
self.assertEqual(cost["ec2_estimate_usd"], "2.0000")
self.assertEqual(cost["campaign_estimate_with_other_reserve_usd"], "3.5000")
for rate in ("", "invalid", "0", "-1", "NaN", "Infinity", "-Infinity"):
with self.subTest(rate=rate), self.assertRaises(ValueError):
ops.plan(self.env(EC2_HOURLY_USD=rate))
with self.assertRaises(ValueError):
ops.plan(self.env(EC2_HOURLY_USD="4"))
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")
+79 -22
View File
@@ -2,6 +2,11 @@ name: Agent Observability Benchmark
on:
workflow_dispatch:
inputs:
greptimedb_storage:
description: 'GreptimeDB data storage (S3 requires AWS in the bucket region; WAL stays local)'
type: choice
options: [file, s3, both]
default: file
run_greptimedb:
description: Run GreptimeDB
type: boolean
@@ -56,7 +61,7 @@ on:
type: string
required: false
runtime_image:
description: 'Runtime image: auto = AWS ECR Public or Aliyun ACR by provider; explicit tag/digest overrides'
description: 'Runtime image: auto = pinned S3 test runtime on ACR; explicit tag/digest overrides'
type: string
default: auto
required: true
@@ -99,6 +104,11 @@ on:
permissions:
contents: read
env:
GREPTIMEDB_STORAGE: ${{ inputs.greptimedb_storage || 'file' }}
S3_BUCKET: ${{ vars.AWS_CI_TEST_BUCKET }}
S3_REGION: ${{ vars.AWS_CI_TEST_BUCKET_REGION }}
RUNNER_REGION: ${{ vars.EC2_RUNNER_REGION }}
RUN_GREPTIMEDB: ${{ inputs.run_greptimedb }}
COMPARE_GREPTIMEDB: ${{ inputs.compare_greptimedb }}
BASELINE_GREPTIMEDB_TAG: ${{ inputs.baseline_greptimedb_tag }}
PROFILE: ${{ inputs.dataset }}
@@ -106,7 +116,7 @@ env:
CLICKHOUSE_TAG: ${{ inputs.clickhouse_tag }}
VICTORIALOGS_TAG: ${{ inputs.victorialogs_tag }}
O11YBENCH_REF: ${{ inputs.o11ybench_ref }}
RUNTIME_IMAGE: ${{ inputs.runtime_image != 'auto' && inputs.runtime_image || inputs.provider == 'AWS' && 'public.ecr.aws/i8k6a5e1/greptime/o11ybenchruntime:2f40fb3fdbdc@sha256:8940782216bf5d066308fd71f6e346d950073c41cfb5756c5f3dc8aacf069cbc' || 'greptime-registry.cn-hangzhou.cr.aliyuncs.com/tools/o11ybench-runtime:2f40fb3fdbdc@sha256:8940782216bf5d066308fd71f6e346d950073c41cfb5756c5f3dc8aacf069cbc' }}
RUNTIME_IMAGE: ${{ inputs.runtime_image != 'auto' && inputs.runtime_image || 'greptime-registry.cn-hangzhou.cr.aliyuncs.com/tools/o11ybench-runtime:s3-test-b0cf5204d2fc@sha256:c2bf622db6056a2029842f4dc1cc1f37b82773bd45b134a0a83ffe2a8cd62214' }}
PROVIDER: ${{ inputs.provider }}
REQUESTED_INSTANCE_TYPE: ${{ inputs.instance_type }}
SYSTEM_DISK_GIB: ${{ inputs.system_disk_gib }}
@@ -130,6 +140,10 @@ jobs:
with:
path: greptimedb
persist-credentials: false
- name: Validate GreptimeDB storage
run: |
python3 greptimedb/tests/perf/test_o11ybench_storage.py
python3 greptimedb/.github/scripts/o11ybench-storage.py validate
- name: Validate version comparison
env:
RUN_GREPTIMEDB: ${{ inputs.run_greptimedb }}
@@ -287,7 +301,10 @@ jobs:
path: greptimedb
persist-credentials: false
- name: Set up benchmark dependencies
uses: ./greptimedb/.github/actions/setup-benchmark
uses: ./greptimedb/.github/actions/setup-linux-runner
with:
tools: curl jq python3 rsync
expected-architecture: x86_64
- name: Check Docker on ephemeral Linux host
shell: bash
run: |
@@ -367,24 +384,48 @@ jobs:
--owner "$OWNER" --runtime-image "$RESOLVED_RUNTIME_IMAGE" \
--root "$ARTIFACT_ROOT" --profile "$PROFILE" --db-cpus "$DB_CPUS" --db-memory "$DB_MEMORY"
cp "$MANIFEST_PATH" "$ARTIFACT_ROOT/run-manifest.json"
- name: Load and benchmark baseline GreptimeDB
id: baseline_greptimedb
if: ${{ !cancelled() && steps.generate.outcome == 'success' && needs.validate.outputs.greptimedb == 'true' && inputs.compare_greptimedb }}
- name: Load and benchmark baseline GreptimeDB (File)
id: baseline_greptimedb_file
if: ${{ !cancelled() && steps.generate.outcome == 'success' && needs.validate.outputs.greptimedb == 'true' && inputs.greptimedb_storage != 's3' && inputs.compare_greptimedb }}
run: |-
GITHUB_STEP_SUMMARY= bash o11ybench/scripts/run-agent-observability.sh --stage target --execute \
GITHUB_STEP_SUMMARY= bash o11ybench/scripts/run-agent-observability.sh --stage target --greptimedb-storage file --execute \
--owner "$OWNER-base" --runtime-image "$RESOLVED_RUNTIME_IMAGE" --root "$ARTIFACT_ROOT/baseline" --data-root "$ARTIFACT_ROOT" \
--profile "$PROFILE" --db-cpus "$DB_CPUS" --db-memory "$DB_MEMORY" \
--target greptimedb --image "$BASELINE_GREPTIMEDB_IMAGE" \
--greptimedb-http-port "$GREPTIMEDB_HTTP_PORT" --greptimedb-grpc-port "$GREPTIMEDB_GRPC_PORT"
- name: Load and benchmark greptimedb
id: greptimedb
if: ${{ !cancelled() && steps.generate.outcome == 'success' && needs.validate.outputs.greptimedb == 'true' }}
- name: Load and benchmark baseline GreptimeDB (S3)
env:
AWS_ACCESS_KEY_ID: ${{ inputs.greptimedb_storage != 'file' && secrets.AWS_ACCESS_KEY_ID || '' }}
AWS_SECRET_ACCESS_KEY: ${{ inputs.greptimedb_storage != 'file' && secrets.AWS_SECRET_ACCESS_KEY || '' }}
id: baseline_greptimedb_s3
if: ${{ !cancelled() && steps.generate.outcome == 'success' && needs.validate.outputs.greptimedb == 'true' && inputs.greptimedb_storage != 'file' && inputs.compare_greptimedb }}
run: |-
GITHUB_STEP_SUMMARY= bash o11ybench/scripts/run-agent-observability.sh --stage target --execute \
GITHUB_STEP_SUMMARY= bash o11ybench/scripts/run-agent-observability.sh --stage target --greptimedb-storage s3 --execute \
--owner "$OWNER-base-s3" --runtime-image "$RESOLVED_RUNTIME_IMAGE" --root "$ARTIFACT_ROOT/baseline/s3" --data-root "$ARTIFACT_ROOT" \
--profile "$PROFILE" --db-cpus "$DB_CPUS" --db-memory "$DB_MEMORY" \
--target greptimedb --image "$BASELINE_GREPTIMEDB_IMAGE" \
--greptimedb-http-port "$GREPTIMEDB_HTTP_PORT" --greptimedb-grpc-port "$GREPTIMEDB_GRPC_PORT"
- name: Load and benchmark greptimedb (File)
id: greptimedb_file
if: ${{ !cancelled() && steps.generate.outcome == 'success' && needs.validate.outputs.greptimedb == 'true' && inputs.greptimedb_storage != 's3' }}
run: |-
GITHUB_STEP_SUMMARY= bash o11ybench/scripts/run-agent-observability.sh --stage target --greptimedb-storage file --execute \
--owner "$OWNER" --runtime-image "$RESOLVED_RUNTIME_IMAGE" --root "$ARTIFACT_ROOT" \
--profile "$PROFILE" --db-cpus "$DB_CPUS" --db-memory "$DB_MEMORY" \
--target greptimedb --image "$GREPTIMEDB_IMAGE" \
--greptimedb-http-port "$GREPTIMEDB_HTTP_PORT" --greptimedb-grpc-port "$GREPTIMEDB_GRPC_PORT"
- name: Load and benchmark greptimedb (S3)
env:
AWS_ACCESS_KEY_ID: ${{ inputs.greptimedb_storage != 'file' && secrets.AWS_ACCESS_KEY_ID || '' }}
AWS_SECRET_ACCESS_KEY: ${{ inputs.greptimedb_storage != 'file' && secrets.AWS_SECRET_ACCESS_KEY || '' }}
id: greptimedb_s3
if: ${{ !cancelled() && steps.generate.outcome == 'success' && needs.validate.outputs.greptimedb == 'true' && inputs.greptimedb_storage != 'file' }}
run: |-
GITHUB_STEP_SUMMARY= bash o11ybench/scripts/run-agent-observability.sh --stage target --greptimedb-storage s3 --execute \
--owner "$OWNER-s3" --runtime-image "$RESOLVED_RUNTIME_IMAGE" --root "$ARTIFACT_ROOT/s3" --data-root "$ARTIFACT_ROOT" \
--profile "$PROFILE" --db-cpus "$DB_CPUS" --db-memory "$DB_MEMORY" \
--target greptimedb --image "$GREPTIMEDB_IMAGE" \
--greptimedb-http-port "$GREPTIMEDB_HTTP_PORT" --greptimedb-grpc-port "$GREPTIMEDB_GRPC_PORT"
- name: Load and benchmark clickhouse
id: clickhouse
if: ${{ !cancelled() && steps.generate.outcome == 'success' && needs.validate.outputs.clickhouse == 'true' }}
@@ -404,7 +445,7 @@ jobs:
--target victorialogs --image "$VICTORIALOGS_IMAGE" \
--victorialogs-http-port "$VICTORIALOGS_HTTP_PORT"
- name: Compare all three targets
if: ${{ !cancelled() && steps.greptimedb.outcome == 'success' && steps.clickhouse.outcome == 'success' && steps.victorialogs.outcome
if: ${{ !cancelled() && steps.greptimedb_file.outcome == 'success' && steps.clickhouse.outcome == 'success' && steps.victorialogs.outcome
== 'success' }}
run: |-
docker run --rm --user "$(id -u):$(id -g)" --label "o11ybench.owner=$OWNER" \
@@ -415,45 +456,61 @@ jobs:
--victorialogs-summary /results/victorialogs-1/victorialogs-1/measured-summary.json \
--output /results/comparison.json
- name: Clean up owned containers
env:
AWS_ACCESS_KEY_ID: ${{ inputs.greptimedb_storage != 'file' && secrets.AWS_ACCESS_KEY_ID || '' }}
AWS_SECRET_ACCESS_KEY: ${{ inputs.greptimedb_storage != 'file' && secrets.AWS_SECRET_ACCESS_KEY || '' }}
if: always()
run: |-
if [[ -f o11ybench/scripts/run-agent-observability.sh ]]; then
GITHUB_STEP_SUMMARY= bash o11ybench/scripts/run-agent-observability.sh --stage cleanup --execute \
GITHUB_STEP_SUMMARY= python3 greptimedb/.github/scripts/o11ybench-storage.py run -- bash o11ybench/scripts/run-agent-observability.sh --stage cleanup --execute --runtime-image "$RESOLVED_RUNTIME_IMAGE" \
--owner "$OWNER" --root "$ARTIFACT_ROOT"
fi
- name: Clean up baseline containers
env:
AWS_ACCESS_KEY_ID: ${{ inputs.greptimedb_storage != 'file' && secrets.AWS_ACCESS_KEY_ID || '' }}
AWS_SECRET_ACCESS_KEY: ${{ inputs.greptimedb_storage != 'file' && secrets.AWS_SECRET_ACCESS_KEY || '' }}
if: always() && inputs.compare_greptimedb
run: |-
if [[ -f o11ybench/scripts/run-agent-observability.sh ]]; then
GITHUB_STEP_SUMMARY= bash o11ybench/scripts/run-agent-observability.sh --stage cleanup --execute \
GITHUB_STEP_SUMMARY= python3 greptimedb/.github/scripts/o11ybench-storage.py run -- bash o11ybench/scripts/run-agent-observability.sh --stage cleanup --execute --runtime-image "$RESOLVED_RUNTIME_IMAGE" \
--owner "$OWNER-base" --root "$ARTIFACT_ROOT/baseline"
fi
- name: Benchmark summary
if: always()
run: |
python3 greptimedb/.github/scripts/agent-observability-summary.py \
--root "$ARTIFACT_ROOT" --targets "$TARGETS" --section benchmark >> "$GITHUB_STEP_SUMMARY"
python3 greptimedb/.github/scripts/o11ybench-storage.py summary --kind agent \
--root "$ARTIFACT_ROOT" --targets "$TARGETS" --section benchmark | tee -a "$ARTIFACT_ROOT/ci-summary.md" >> "$GITHUB_STEP_SUMMARY"
- name: Load / lifecycle summary
if: always()
run: |
python3 greptimedb/.github/scripts/agent-observability-summary.py \
--root "$ARTIFACT_ROOT" --targets "$TARGETS" --section lifecycle >> "$GITHUB_STEP_SUMMARY"
python3 greptimedb/.github/scripts/o11ybench-storage.py summary --kind agent \
--root "$ARTIFACT_ROOT" --targets "$TARGETS" --section lifecycle | tee -a "$ARTIFACT_ROOT/ci-summary.md" >> "$GITHUB_STEP_SUMMARY"
- name: Baseline load / lifecycle summary
if: always() && inputs.compare_greptimedb
run: |
echo '## Baseline GreptimeDB' >> "$GITHUB_STEP_SUMMARY"
python3 greptimedb/.github/scripts/agent-observability-summary.py \
--root "$ARTIFACT_ROOT/baseline" --targets greptimedb --section lifecycle >> "$GITHUB_STEP_SUMMARY"
echo '## Baseline GreptimeDB' | tee -a "$ARTIFACT_ROOT/ci-summary.md" >> "$GITHUB_STEP_SUMMARY"
python3 greptimedb/.github/scripts/o11ybench-storage.py summary --kind agent \
--root "$ARTIFACT_ROOT/baseline" --targets greptimedb --section lifecycle | tee -a "$ARTIFACT_ROOT/ci-summary.md" >> "$GITHUB_STEP_SUMMARY"
- name: GreptimeDB version comparison
if: always() && inputs.compare_greptimedb
run: |
python3 greptimedb/.github/scripts/benchmark-version-comparison.py report --kind agent --root "$ARTIFACT_ROOT" >> "$GITHUB_STEP_SUMMARY"
python3 greptimedb/.github/scripts/benchmark-version-comparison.py report --kind agent --root "$ARTIFACT_ROOT" | tee -a "$ARTIFACT_ROOT/ci-summary.md" >> "$GITHUB_STEP_SUMMARY"
- name: Render storage comparison overview
if: always() && steps.generate.outcome == 'success'
run: |
python3 o11ybench/scripts/build_query_performance_report.py --agent "$ARTIFACT_ROOT" \
--output "$ARTIFACT_ROOT-query-report.html" --json-output "$ARTIFACT_ROOT-query-report.json"
python3 greptimedb/.github/scripts/o11ybench-storage.py overview "$ARTIFACT_ROOT-query-report.json" \
| tee -a "$ARTIFACT_ROOT/ci-summary.md" >> "$GITHUB_STEP_SUMMARY"
python3 greptimedb/.github/scripts/o11ybench-storage.py audit --root "$ARTIFACT_ROOT" \
--report "$ARTIFACT_ROOT-query-report.json" --targets "$TARGETS"
- name: Upload results (no dataset)
if: always()
uses: actions/upload-artifact@v4
with:
name: agent-observability-${{ github.run_id }}-${{ github.run_attempt }}
path: |-
${{ env.ARTIFACT_ROOT }}-query-report.*
${{ env.MANIFEST_PATH }}
${{ env.ARTIFACT_ROOT }}
!${{ env.ARTIFACT_ROOT }}/corpus/agent_observations.jsonl
+7
View File
@@ -4,6 +4,11 @@ name: GreptimeDB Development Build
on:
workflow_dispatch: # Allows you to run this workflow manually.
inputs:
ec2_volume_size:
description: Root volume size in GiB for each EC2 build runner
type: number
required: false
default: 500
large-page-size:
description: Build GreptimeDB with large page size (65536).
type: boolean
@@ -133,6 +138,7 @@ jobs:
aws-region: ${{ vars.EC2_RUNNER_REGION }}
github-token: ${{ secrets.GH_PERSONAL_ACCESS_TOKEN }}
image-id: ${{ vars.EC2_RUNNER_LINUX_AMD64_IMAGE_ID }}
ec2-volume-size: ${{ inputs.ec2_volume_size || 500 }}
security-group-id: ${{ vars.EC2_RUNNER_SECURITY_GROUP_ID }}
subnet-id: ${{ vars.EC2_RUNNER_SUBNET_ID }}
@@ -147,6 +153,7 @@ jobs:
aws-region: ${{ vars.EC2_RUNNER_REGION }}
github-token: ${{ secrets.GH_PERSONAL_ACCESS_TOKEN }}
image-id: ${{ vars.EC2_RUNNER_LINUX_ARM64_IMAGE_ID }}
ec2-volume-size: ${{ inputs.ec2_volume_size || 500 }}
security-group-id: ${{ vars.EC2_RUNNER_SECURITY_GROUP_ID }}
subnet-id: ${{ vars.EC2_RUNNER_SUBNET_ID }}
+10 -1
View File
@@ -18,6 +18,11 @@ on:
description: 'Setup, 500-table smoke and full run timeout, 30..240 minutes'
type: number
default: 240
ec2_hourly_usd:
description: 'Positive EC2 hourly USD budget estimate; historical default, not live regional pricing'
required: true
type: string
default: '0.9408'
prior_spend_usd:
description: 'Cumulative estimated cloud spend for all earlier attempts in this $20 campaign'
required: true
@@ -34,6 +39,7 @@ env:
LOGICAL_TABLES_PER_GROUP: ${{ inputs.logical_tables_per_group }}
BENCHMARK_TIMEOUT_MINUTES: ${{ inputs.benchmark_timeout_minutes }}
PRIOR_SPEND_USD: ${{ inputs.prior_spend_usd }}
EC2_HOURLY_USD: ${{ inputs.ec2_hourly_usd }}
RUN_PREFIX: metric-snapshot-bench/${{ github.run_id }}-${{ github.run_attempt }}/
S3_BUCKET: ${{ vars.AWS_CI_TEST_BUCKET }}
S3_REGION: ${{ vars.AWS_CI_TEST_BUCKET_REGION }}
@@ -125,7 +131,10 @@ jobs:
path: greptimedb
persist-credentials: false
- name: Set up benchmark dependencies
uses: ./greptimedb/.github/actions/setup-benchmark
uses: ./greptimedb/.github/actions/setup-linux-runner
with:
tools: curl jq python3 rsync
expected-architecture: x86_64
- uses: astral-sh/setup-uv@v6
- name: Mount the temporary local File data disk
run: |
+7
View File
@@ -9,6 +9,11 @@ on:
- cron: '0 0 * * 1-5'
workflow_dispatch: # Allows you to run this workflow manually.
inputs:
ec2_volume_size:
description: Root volume size in GiB for each EC2 build runner
type: number
required: false
default: 500
linux_amd64_runner:
type: choice
description: The runner uses to build linux-amd64 artifacts
@@ -113,6 +118,7 @@ jobs:
aws-region: ${{ vars.EC2_RUNNER_REGION }}
github-token: ${{ secrets.GH_PERSONAL_ACCESS_TOKEN }}
image-id: ${{ vars.EC2_RUNNER_LINUX_AMD64_IMAGE_ID }}
ec2-volume-size: ${{ inputs.ec2_volume_size || 500 }}
security-group-id: ${{ vars.EC2_RUNNER_SECURITY_GROUP_ID }}
subnet-id: ${{ vars.EC2_RUNNER_SUBNET_ID }}
@@ -127,6 +133,7 @@ jobs:
aws-region: ${{ vars.EC2_RUNNER_REGION }}
github-token: ${{ secrets.GH_PERSONAL_ACCESS_TOKEN }}
image-id: ${{ vars.EC2_RUNNER_LINUX_ARM64_IMAGE_ID }}
ec2-volume-size: ${{ inputs.ec2_volume_size || 500 }}
security-group-id: ${{ vars.EC2_RUNNER_SECURITY_GROUP_ID }}
subnet-id: ${{ vars.EC2_RUNNER_SUBNET_ID }}
+4 -1
View File
@@ -205,7 +205,10 @@ jobs:
path: greptimedb
persist-credentials: false
- name: Set up benchmark dependencies
uses: ./greptimedb/.github/actions/setup-benchmark
uses: ./greptimedb/.github/actions/setup-linux-runner
with:
tools: curl jq python3 rsync
expected-architecture: x86_64
- uses: astral-sh/setup-uv@v6
- name: Start the MinIO fixture
if: inputs.smoke
+12
View File
@@ -20,6 +20,11 @@ on:
- cron: '0 0 * * 1-5'
workflow_dispatch: # Allows you to run this workflow manually.
inputs:
ec2_volume_size:
description: Root volume size in GiB for each EC2 build runner
type: number
required: false
default: 500
linux_amd64_runner:
type: choice
description: The runner uses to build linux-amd64 artifacts
@@ -215,6 +220,7 @@ jobs:
aws-region: ${{ vars.EC2_RUNNER_REGION }}
github-token: ${{ secrets.GH_PERSONAL_ACCESS_TOKEN }}
image-id: ${{ vars.EC2_RUNNER_LINUX_AMD64_IMAGE_ID }}
ec2-volume-size: ${{ inputs.ec2_volume_size || 500 }}
security-group-id: ${{ vars.EC2_RUNNER_SECURITY_GROUP_ID }}
subnet-id: ${{ vars.EC2_RUNNER_SUBNET_ID }}
@@ -229,6 +235,7 @@ jobs:
aws-region: ${{ vars.EC2_RUNNER_REGION }}
github-token: ${{ secrets.GH_PERSONAL_ACCESS_TOKEN }}
image-id: ${{ vars.EC2_RUNNER_LINUX_ARM64_IMAGE_ID }}
ec2-volume-size: ${{ inputs.ec2_volume_size || 500 }}
security-group-id: ${{ vars.EC2_RUNNER_SECURITY_GROUP_ID }}
subnet-id: ${{ vars.EC2_RUNNER_SUBNET_ID }}
@@ -298,6 +305,11 @@ jobs:
fetch-depth: 0
persist-credentials: false
- name: Set up Linux runner
uses: ./.github/actions/setup-linux-runner
with:
tools: make shasum
- name: Prepare riscv64 dev-builder image
shell: bash
env:
+97 -21
View File
@@ -2,6 +2,11 @@ name: Tracesbench
on:
workflow_dispatch:
inputs:
greptimedb_storage:
description: 'GreptimeDB data storage (S3 requires AWS in the bucket region; WAL stays local)'
type: choice
options: [file, s3, both]
default: file
run_greptimedb:
description: Run GreptimeDB
type: boolean
@@ -39,7 +44,7 @@ on:
default: sanity
required: true
runtime_image:
description: 'Runtime image: auto = AWS ECR Public or Aliyun ACR by provider; explicit tag/digest overrides'
description: 'Runtime image: auto = pinned S3 test runtime on ACR; explicit tag/digest overrides'
type: string
default: auto
required: true
@@ -107,6 +112,11 @@ on:
permissions:
contents: read
env:
GREPTIMEDB_STORAGE: ${{ inputs.greptimedb_storage || 'file' }}
S3_BUCKET: ${{ vars.AWS_CI_TEST_BUCKET }}
S3_REGION: ${{ vars.AWS_CI_TEST_BUCKET_REGION }}
RUNNER_REGION: ${{ vars.EC2_RUNNER_REGION }}
RUN_GREPTIMEDB: ${{ inputs.run_greptimedb }}
COMPARE_GREPTIMEDB: ${{ inputs.compare_greptimedb }}
BASELINE_GREPTIMEDB_TAG: ${{ inputs.baseline_greptimedb_tag }}
DATASET: ${{ inputs.dataset }}
@@ -114,7 +124,7 @@ env:
RUNTIME_CPUS: ${{ inputs.runtime_cpus }}
RUNTIME_MEMORY: ${{ inputs.runtime_memory }}
BENCHMARK_ROOT: ${{ inputs.benchmark_root }}
RUNTIME_IMAGE: ${{ inputs.runtime_image != 'auto' && inputs.runtime_image || inputs.provider == 'AWS' && 'public.ecr.aws/i8k6a5e1/greptime/o11ybenchruntime:77a84e1c8136@sha256:c482993ec177b026235d6cd0c61d4fb6d6f1088bc78bdc0e5964a5398de6dba0' || 'greptime-registry.cn-hangzhou.cr.aliyuncs.com/tools/o11ybench-runtime:77a84e1c8136@sha256:c482993ec177b026235d6cd0c61d4fb6d6f1088bc78bdc0e5964a5398de6dba0' }}
RUNTIME_IMAGE: ${{ inputs.runtime_image != 'auto' && inputs.runtime_image || 'greptime-registry.cn-hangzhou.cr.aliyuncs.com/tools/o11ybench-runtime:s3-test-b0cf5204d2fc@sha256:c2bf622db6056a2029842f4dc1cc1f37b82773bd45b134a0a83ffe2a8cd62214' }}
PROVIDER: ${{ inputs.provider }}
REQUESTED_INSTANCE_TYPE: ${{ inputs.instance_type }}
SYSTEM_DISK_GIB: ${{ inputs.system_disk_gib }}
@@ -162,6 +172,10 @@ jobs:
[[ "$GREPTIMEDB_TAG" =~ ^[a-zA-Z0-9_][a-zA-Z0-9_.-]{0,127}$ ]] || { echo 'Invalid GreptimeDB image tag' >&2; exit 1; }
fi
printf 'targets=%s\n' "$selected" >> "$GITHUB_OUTPUT"
- name: Validate GreptimeDB storage
run: |
python3 greptimedb/tests/perf/test_o11ybench_storage.py
python3 greptimedb/.github/scripts/o11ybench-storage.py validate
- name: Validate version comparison
env:
RUN_GREPTIMEDB: ${{ inputs.run_greptimedb }}
@@ -317,7 +331,10 @@ jobs:
path: greptimedb
persist-credentials: false
- name: Set up benchmark dependencies
uses: ./greptimedb/.github/actions/setup-benchmark
uses: ./greptimedb/.github/actions/setup-linux-runner
with:
tools: curl jq python3 rsync
expected-architecture: x86_64
- name: Checkout matching benchmark tools
uses: actions/checkout@v4
with:
@@ -386,22 +403,44 @@ jobs:
python3 o11ybench/scripts/run_tracesbench_docker.py --stage generate \
--dataset "$DATASET" --runtime-cpus "$RUNTIME_CPUS" --runtime-memory "$RUNTIME_MEMORY" \
--root "$RUN_ROOT" --owner "$OWNER" --runtime-image "$RESOLVED_RUNTIME_IMAGE"
- name: Baseline GreptimeDB load, correctness and benchmark
if: ${{ !cancelled() && steps.generate.outcome == 'success' && needs.validate.outputs.greptimedb == 'true' && inputs.compare_greptimedb }}
- name: Baseline GreptimeDB load, correctness and benchmark (File)
if: ${{ !cancelled() && steps.generate.outcome == 'success' && needs.validate.outputs.greptimedb == 'true' && inputs.greptimedb_storage != 's3' && inputs.compare_greptimedb }}
run: |
python3 o11ybench/scripts/run_tracesbench_docker.py --stage target --target greptimedb --port 14000 --greptimedb-image "$BASELINE_GREPTIMEDB_IMAGE" \
python3 o11ybench/scripts/run_tracesbench_docker.py --stage target --greptimedb-storage file --target greptimedb --port 14000 --greptimedb-image "$BASELINE_GREPTIMEDB_IMAGE" \
--db-cpus "$DB_CPUS" --db-memory "$DB_MEMORY" --query-timeout-seconds "$QUERY_TIMEOUT_SECONDS" --load-workers "$LOAD_WORKERS" \
--dataset "$DATASET" --runtime-cpus "$RUNTIME_CPUS" --runtime-memory "$RUNTIME_MEMORY" \
--root "$RUN_ROOT/baseline" --data-root "$RUN_ROOT" --owner "$OWNER-base" --runtime-image "$RESOLVED_RUNTIME_IMAGE"
python3 o11ybench/scripts/check_tracesbench_query_plans.py "$RUN_ROOT/baseline/runs/greptimedb"
- name: GreptimeDB load, correctness and benchmark
if: ${{ !cancelled() && steps.generate.outcome == 'success' && needs.validate.outputs.greptimedb == 'true' }}
- name: Baseline GreptimeDB load, correctness and benchmark (S3)
env:
AWS_ACCESS_KEY_ID: ${{ inputs.greptimedb_storage != 'file' && secrets.AWS_ACCESS_KEY_ID || '' }}
AWS_SECRET_ACCESS_KEY: ${{ inputs.greptimedb_storage != 'file' && secrets.AWS_SECRET_ACCESS_KEY || '' }}
if: ${{ !cancelled() && steps.generate.outcome == 'success' && needs.validate.outputs.greptimedb == 'true' && inputs.greptimedb_storage != 'file' && inputs.compare_greptimedb }}
run: |
python3 o11ybench/scripts/run_tracesbench_docker.py --stage target --target greptimedb --port 14000 --greptimedb-image "$GREPTIMEDB_IMAGE" \
python3 o11ybench/scripts/run_tracesbench_docker.py --stage target --greptimedb-storage s3 --target greptimedb --port 14000 --greptimedb-image "$BASELINE_GREPTIMEDB_IMAGE" \
--db-cpus "$DB_CPUS" --db-memory "$DB_MEMORY" --query-timeout-seconds "$QUERY_TIMEOUT_SECONDS" --load-workers "$LOAD_WORKERS" \
--dataset "$DATASET" --runtime-cpus "$RUNTIME_CPUS" --runtime-memory "$RUNTIME_MEMORY" \
--root "$RUN_ROOT/baseline/s3" --data-root "$RUN_ROOT" --owner "$OWNER-base-s3" --runtime-image "$RESOLVED_RUNTIME_IMAGE"
python3 o11ybench/scripts/check_tracesbench_query_plans.py "$RUN_ROOT/baseline/s3/runs/greptimedb"
- name: GreptimeDB load, correctness and benchmark (File)
if: ${{ !cancelled() && steps.generate.outcome == 'success' && needs.validate.outputs.greptimedb == 'true' && inputs.greptimedb_storage != 's3' }}
run: |
python3 o11ybench/scripts/run_tracesbench_docker.py --stage target --greptimedb-storage file --target greptimedb --port 14000 --greptimedb-image "$GREPTIMEDB_IMAGE" \
--db-cpus "$DB_CPUS" --db-memory "$DB_MEMORY" --query-timeout-seconds "$QUERY_TIMEOUT_SECONDS" --load-workers "$LOAD_WORKERS" \
--dataset "$DATASET" --runtime-cpus "$RUNTIME_CPUS" --runtime-memory "$RUNTIME_MEMORY" \
--root "$RUN_ROOT" --owner "$OWNER" --runtime-image "$RESOLVED_RUNTIME_IMAGE"
python3 o11ybench/scripts/check_tracesbench_query_plans.py "$RUN_ROOT/runs/greptimedb"
- name: GreptimeDB load, correctness and benchmark (S3)
env:
AWS_ACCESS_KEY_ID: ${{ inputs.greptimedb_storage != 'file' && secrets.AWS_ACCESS_KEY_ID || '' }}
AWS_SECRET_ACCESS_KEY: ${{ inputs.greptimedb_storage != 'file' && secrets.AWS_SECRET_ACCESS_KEY || '' }}
if: ${{ !cancelled() && steps.generate.outcome == 'success' && needs.validate.outputs.greptimedb == 'true' && inputs.greptimedb_storage != 'file' }}
run: |
python3 o11ybench/scripts/run_tracesbench_docker.py --stage target --greptimedb-storage s3 --target greptimedb --port 14000 --greptimedb-image "$GREPTIMEDB_IMAGE" \
--db-cpus "$DB_CPUS" --db-memory "$DB_MEMORY" --query-timeout-seconds "$QUERY_TIMEOUT_SECONDS" --load-workers "$LOAD_WORKERS" \
--dataset "$DATASET" --runtime-cpus "$RUNTIME_CPUS" --runtime-memory "$RUNTIME_MEMORY" \
--root "$RUN_ROOT/s3" --data-root "$RUN_ROOT" --owner "$OWNER-s3" --runtime-image "$RESOLVED_RUNTIME_IMAGE"
python3 o11ybench/scripts/check_tracesbench_query_plans.py "$RUN_ROOT/s3/runs/greptimedb"
- name: VictoriaTraces load, correctness and benchmark
if: ${{ !cancelled() && steps.generate.outcome == 'success' && needs.validate.outputs.victoriatraces == 'true' }}
run: |
@@ -419,49 +458,80 @@ jobs:
- name: GreptimeDB version comparison
if: always() && inputs.compare_greptimedb
run: |
python3 greptimedb/.github/scripts/benchmark-version-comparison.py report --kind traces --root "$RUN_ROOT" >> "$GITHUB_STEP_SUMMARY"
- name: Validate and render report
python3 greptimedb/.github/scripts/benchmark-version-comparison.py report --kind traces --root "$RUN_ROOT" | tee -a "$RUN_ROOT/ci-summary.md" >> "$GITHUB_STEP_SUMMARY"
- name: Validate and render primary report
if: always() && steps.generate.outcome == 'success'
env:
AWS_ACCESS_KEY_ID: ${{ inputs.greptimedb_storage != 'file' && secrets.AWS_ACCESS_KEY_ID || '' }}
AWS_SECRET_ACCESS_KEY: ${{ inputs.greptimedb_storage != 'file' && secrets.AWS_SECRET_ACCESS_KEY || '' }}
COMPARE_GREPTIMEDB: ${{ inputs.compare_greptimedb }}
run: |
if [[ "$GREPTIMEDB_STORAGE" == s3 ]]; then
TARGETS=$(tr "," "\n" <<< "$TARGETS" | sed "/^greptimedb$/d" | paste -sd, -)
[[ -n "$TARGETS" ]] || exit 0
fi
comparison_args=()
if [[ "$COMPARE_GREPTIMEDB" == true ]]; then
if [[ "$COMPARE_GREPTIMEDB" == true && "$GREPTIMEDB_STORAGE" != s3 ]]; then
comparison_args+=(--baseline-run "$RUN_ROOT/baseline/runs/greptimedb/run.json")
fi
python3 o11ybench/scripts/run_tracesbench_docker.py --stage report --targets "$TARGETS" "${comparison_args[@]}" \
python3 o11ybench/scripts/run_tracesbench_docker.py --stage report --targets "${TARGETS}" "${comparison_args[@]}" \
--dataset "$DATASET" --runtime-cpus "$RUNTIME_CPUS" --runtime-memory "$RUNTIME_MEMORY" \
--root "$RUN_ROOT" --owner "$OWNER" --runtime-image "$RESOLVED_RUNTIME_IMAGE"
- name: Validate and render S3 report
if: always() && steps.generate.outcome == 'success' && inputs.greptimedb_storage != 'file'
run: |
python3 o11ybench/scripts/run_tracesbench_docker.py --stage report --targets greptimedb \
--dataset "$DATASET" --runtime-cpus "$RUNTIME_CPUS" --runtime-memory "$RUNTIME_MEMORY" \
--root "$RUN_ROOT/s3" --data-root "$RUN_ROOT" --owner "$OWNER-s3" --runtime-image "$RESOLVED_RUNTIME_IMAGE"
- name: Clean up owned containers
env:
AWS_ACCESS_KEY_ID: ${{ inputs.greptimedb_storage != 'file' && secrets.AWS_ACCESS_KEY_ID || '' }}
AWS_SECRET_ACCESS_KEY: ${{ inputs.greptimedb_storage != 'file' && secrets.AWS_SECRET_ACCESS_KEY || '' }}
if: always() && steps.runtime.outcome == 'success'
run: |
python3 o11ybench/scripts/run_tracesbench_docker.py --stage cleanup \
python3 greptimedb/.github/scripts/o11ybench-storage.py run -- python3 o11ybench/scripts/run_tracesbench_docker.py --stage cleanup \
--dataset "$DATASET" --runtime-cpus "$RUNTIME_CPUS" --runtime-memory "$RUNTIME_MEMORY" \
--root "$RUN_ROOT" --owner "$OWNER" --runtime-image "$RESOLVED_RUNTIME_IMAGE"
- name: Clean up baseline containers
env:
AWS_ACCESS_KEY_ID: ${{ inputs.greptimedb_storage != 'file' && secrets.AWS_ACCESS_KEY_ID || '' }}
AWS_SECRET_ACCESS_KEY: ${{ inputs.greptimedb_storage != 'file' && secrets.AWS_SECRET_ACCESS_KEY || '' }}
if: always() && steps.runtime.outcome == 'success' && inputs.compare_greptimedb
run: |
python3 o11ybench/scripts/run_tracesbench_docker.py --stage cleanup \
python3 greptimedb/.github/scripts/o11ybench-storage.py run -- python3 o11ybench/scripts/run_tracesbench_docker.py --stage cleanup \
--root "$RUN_ROOT/baseline" --owner "$OWNER-base" --runtime-image "$RESOLVED_RUNTIME_IMAGE"
- name: Benchmark summary
if: always()
run: python3 greptimedb/.github/scripts/tracesbench-summary.py --root "$RUN_ROOT" --targets "$TARGETS" --section benchmark >> "$GITHUB_STEP_SUMMARY"
run: python3 greptimedb/.github/scripts/o11ybench-storage.py summary --kind traces --root "$RUN_ROOT" --targets "$TARGETS" --section benchmark | tee -a "$RUN_ROOT/ci-summary.md" >> "$GITHUB_STEP_SUMMARY"
- name: Load / lifecycle summary
if: always()
run: python3 greptimedb/.github/scripts/tracesbench-summary.py --root "$RUN_ROOT" --targets "$TARGETS" --section lifecycle >> "$GITHUB_STEP_SUMMARY"
run: python3 greptimedb/.github/scripts/o11ybench-storage.py summary --kind traces --root "$RUN_ROOT" --targets "$TARGETS" --section lifecycle | tee -a "$RUN_ROOT/ci-summary.md" >> "$GITHUB_STEP_SUMMARY"
- name: Baseline load / lifecycle summary
if: always() && inputs.compare_greptimedb
run: |
echo '## Baseline GreptimeDB' >> "$GITHUB_STEP_SUMMARY"
python3 greptimedb/.github/scripts/tracesbench-summary.py \
--root "$RUN_ROOT/baseline" --targets greptimedb --section lifecycle >> "$GITHUB_STEP_SUMMARY"
echo '## Baseline GreptimeDB' | tee -a "$RUN_ROOT/ci-summary.md" >> "$GITHUB_STEP_SUMMARY"
python3 greptimedb/.github/scripts/o11ybench-storage.py summary --kind traces \
--root "$RUN_ROOT/baseline" --targets greptimedb --section lifecycle | tee -a "$RUN_ROOT/ci-summary.md" >> "$GITHUB_STEP_SUMMARY"
- name: Render storage comparison overview
if: always() && steps.generate.outcome == 'success'
run: |
mkdir -p "$RUN_ROOT/metadata"
cp "$METADATA_ROOT"/*-image.json "$RUN_ROOT/metadata/"
python3 o11ybench/scripts/build_query_performance_report.py --traces "$RUN_ROOT" \
--output "$RUN_ROOT-query-report.html" --json-output "$RUN_ROOT-query-report.json"
python3 greptimedb/.github/scripts/o11ybench-storage.py overview "$RUN_ROOT-query-report.json" \
| tee -a "$RUN_ROOT/ci-summary.md" >> "$GITHUB_STEP_SUMMARY"
python3 greptimedb/.github/scripts/o11ybench-storage.py audit --root "$RUN_ROOT" \
--report "$RUN_ROOT-query-report.json" --targets "$TARGETS" --allow-trace-query-failures
- name: Stage benchmark artifacts
if: always()
run: |
mkdir -p "$RUNNER_TEMP/tracesbench-artifacts"
cp "$RUN_ROOT"-query-report.* "$RUNNER_TEMP/tracesbench-artifacts/" 2>/dev/null || true
if [[ -d "$METADATA_ROOT" ]]; then
rsync -a --no-owner --no-group "$METADATA_ROOT" "$RUNNER_TEMP/tracesbench-artifacts/"
fi
for entry in runs report report.json report.md version-comparison.json version-comparison.md; do
for entry in artifact-audit.json metadata runs report report.json report.md ci-summary.md version-comparison.json version-comparison.md; do
if [[ -e "$RUN_ROOT/$entry" ]]; then
rsync -a --no-owner --no-group "$RUN_ROOT/$entry" "$RUNNER_TEMP/tracesbench-artifacts/"
fi
@@ -470,6 +540,12 @@ jobs:
mkdir -p "$RUNNER_TEMP/tracesbench-artifacts/baseline"
rsync -a --no-owner --no-group "$RUN_ROOT/baseline/runs" "$RUNNER_TEMP/tracesbench-artifacts/baseline/"
fi
for arm in s3 baseline/s3; do
if [[ -d "$RUN_ROOT/$arm" ]]; then
mkdir -p "$RUNNER_TEMP/tracesbench-artifacts/$arm"
rsync -a --no-owner --no-group --exclude scratch --exclude corpora "$RUN_ROOT/$arm/" "$RUNNER_TEMP/tracesbench-artifacts/$arm/"
fi
done
- name: Upload HTML and results (no corpus)
if: always()
uses: actions/upload-artifact@v4
+111 -13
View File
@@ -2,6 +2,11 @@ name: VMBench Long Range
on:
workflow_dispatch:
inputs:
greptimedb_storage:
description: 'GreptimeDB data storage (S3 requires AWS in the bucket region; WAL stays local)'
type: choice
options: [file, s3, both]
default: file
run_greptimedb:
description: Run GreptimeDB
type: boolean
@@ -12,6 +17,11 @@ on:
type: boolean
default: false
required: false
run_prometheus:
description: Run Prometheus (requires a runtime image with managed Prometheus support)
type: boolean
default: false
required: false
range_preset:
description: Long-range query window (fixed dataset per preset)
type: choice
@@ -40,8 +50,13 @@ on:
type: string
default: v1.114.0@sha256:227ad53fd57a4b4430624898a1be0cac39431e1235fa0dc92f567cce38969344
required: true
prometheus_tag:
description: Docker Hub prom/prometheus tag or tag@sha256 digest
type: string
default: v3.2.1@sha256:6927e0919a144aa7616fd0137d4816816d42f6b816de3af269ab065250859a62
required: true
runtime_image:
description: 'Runtime image: auto = AWS ECR Public or Aliyun ACR by provider; explicit tag/digest overrides'
description: 'Runtime image: auto = pinned Prometheus/File/S3 runtime on ACR; explicit tag/digest overrides'
type: string
default: auto
required: true
@@ -89,13 +104,19 @@ on:
permissions:
contents: read
env:
GREPTIMEDB_STORAGE: ${{ inputs.greptimedb_storage || 'file' }}
S3_BUCKET: ${{ vars.AWS_CI_TEST_BUCKET }}
S3_REGION: ${{ vars.AWS_CI_TEST_BUCKET_REGION }}
RUNNER_REGION: ${{ vars.EC2_RUNNER_REGION }}
RUN_GREPTIMEDB: ${{ inputs.run_greptimedb }}
COMPARE_GREPTIMEDB: ${{ inputs.compare_greptimedb }}
BASELINE_GREPTIMEDB_TAG: ${{ inputs.baseline_greptimedb_tag }}
BENCHMARK_ROOT: ${{ inputs.benchmark_root }}
RANGE_PRESET: ${{ inputs.range_preset }}
GREPTIMEDB_TAG: ${{ inputs.greptimedb_tag }}
VICTORIAMETRICS_TAG: ${{ inputs.victoriametrics_tag }}
RUNTIME_IMAGE: ${{ inputs.runtime_image != 'auto' && inputs.runtime_image || inputs.provider == 'AWS' && 'public.ecr.aws/i8k6a5e1/greptime/o11ybenchruntime:b43785b56f42@sha256:e38811eb68caf3682ba56f5591a3e8e27e78e7983a923abb29fa2d7cd8fdbd46' || 'greptime-registry.cn-hangzhou.cr.aliyuncs.com/tools/o11ybench-runtime:b43785b56f42@sha256:e38811eb68caf3682ba56f5591a3e8e27e78e7983a923abb29fa2d7cd8fdbd46' }}
PROMETHEUS_TAG: ${{ inputs.prometheus_tag }}
RUNTIME_IMAGE: ${{ inputs.runtime_image != 'auto' && inputs.runtime_image || 'greptime-registry.cn-hangzhou.cr.aliyuncs.com/tools/o11ybench-runtime:345b6f7c-prometheus-s3@sha256:39d207f4a9c479b8614b8283e2d049fc8f430fcbd2b3362ce3035cfbf294edf9' }}
PROVIDER: ${{ inputs.provider }}
REQUESTED_INSTANCE_TYPE: ${{ inputs.instance_type }}
SYSTEM_DISK_GIB: ${{ inputs.system_disk_gib }}
@@ -119,6 +140,10 @@ jobs:
with:
path: greptimedb
persist-credentials: false
- name: Validate GreptimeDB storage
run: |
python3 greptimedb/tests/perf/test_o11ybench_storage.py
python3 greptimedb/.github/scripts/o11ybench-storage.py validate
- name: Validate version comparison
env:
RUN_GREPTIMEDB: ${{ inputs.run_greptimedb }}
@@ -149,6 +174,7 @@ jobs:
env:
RUN_GREPTIMEDB: ${{ inputs.run_greptimedb }}
RUN_VICTORIAMETRICS: ${{ inputs.run_victoriametrics }}
RUN_PROMETHEUS: ${{ inputs.run_prometheus }}
run: |
set -euo pipefail
[[ "$BENCHMARK_ROOT" == /* && "$BENCHMARK_ROOT" != / && "$BENCHMARK_ROOT" != */ ]]
@@ -173,17 +199,18 @@ jobs:
[[ "$revision" =~ ^[0-9a-f]{40}$ ]]
printf 'runtime_image=%s\no11ybench_ref=%s\nsystem_disk_gib=%s\n' "$resolved" "$revision" "$SYSTEM_DISK_GIB" >> "$GITHUB_OUTPUT"
printf 'run_id=long-range-%s-%s\nplan_artifact=vmbench-plan-%s-%s\n' "$GITHUB_RUN_ID" "$GITHUB_RUN_ATTEMPT" "$GITHUB_RUN_ID" "$GITHUB_RUN_ATTEMPT" >> "$GITHUB_OUTPUT"
args=(--workload vmbench-long-range --range-preset "$RANGE_PRESET"
args=(--workload vmbench-long-range --range-preset "$RANGE_PRESET" --greptimedb-storage "$GREPTIMEDB_STORAGE"
--db-cpus "$DB_CPUS" --db-memory "$DB_MEMORY"
--run-classification controlled_server_benchmark --no-open-browser)
if [[ "$COMPARE_GREPTIMEDB" == true ]]; then
args+=(--target "greptimedb:name=greptimedb-baseline,image=greptime/greptimedb:$BASELINE_GREPTIMEDB_TAG,url=http://127.0.0.1:14000/v1/prometheus/api/v1/query_range")
fi
# Tags become target-spec fields; reject separators before passing them to the planner.
for target in greptimedb victoriametrics; do
for target in greptimedb victoriametrics prometheus; do
case "$target" in
greptimedb) enabled=$RUN_GREPTIMEDB; tag=$GREPTIMEDB_TAG; repo=greptime/greptimedb; url=http://127.0.0.1:14000/v1/prometheus/api/v1/query_range ;;
victoriametrics) enabled=$RUN_VICTORIAMETRICS; tag=$VICTORIAMETRICS_TAG; repo=victoriametrics/victoria-metrics; url=http://127.0.0.1:18428/api/v1/query_range ;;
prometheus) enabled=$RUN_PROMETHEUS; tag=$PROMETHEUS_TAG; repo=prom/prometheus; url=http://127.0.0.1:19090/api/v1/query_range ;;
esac
[[ "$enabled" == true ]] || continue
[[ "$tag" =~ ^[a-zA-Z0-9_][a-zA-Z0-9_.-]{0,127}(@sha256:[0-9a-f]{64})?$ ]]
@@ -192,10 +219,11 @@ jobs:
# The packaged planner owns profile, target and resource-limit validation.
mkdir -p "$RUNNER_TEMP/vmbench-plans"
# Keep the original warm defaults: serial 5/1 and c1/c4 30s/5s.
docker run --rm "$resolved" scripts/o11ybench_plan.py "${args[@]}" \
docker run --rm -e S3_BUCKET -e S3_REGION "$resolved" scripts/o11ybench_plan.py "${args[@]}" \
--run-id "long-range-$GITHUB_RUN_ID-$GITHUB_RUN_ATTEMPT-warm" \
--output-root "$BENCHMARK_ROOT/o11ybench/o11ybench-long-range-$GITHUB_RUN_ID-$GITHUB_RUN_ATTEMPT-warm" \
--cache-policy warm > "$RUNNER_TEMP/vmbench-plans/warm.json"
python3 greptimedb/.github/scripts/o11ybench-storage.py normalize-metrics "$RUNNER_TEMP/vmbench-plans/warm.json"
- uses: actions/upload-artifact@v4
with:
name: vmbench-plan-${{ github.run_id }}-${{ github.run_attempt }}
@@ -278,7 +306,10 @@ jobs:
path: greptimedb
persist-credentials: false
- name: Set up benchmark dependencies
uses: ./greptimedb/.github/actions/setup-benchmark
uses: ./greptimedb/.github/actions/setup-linux-runner
with:
tools: curl jq python3 rsync
expected-architecture: x86_64
- name: Checkout matching benchmark tools
uses: actions/checkout@v4
with:
@@ -337,25 +368,92 @@ jobs:
--plan "$METADATA_ROOT/warm.json" --runtime-image "$RESOLVED_RUNTIME_IMAGE" --dry-run \
> "$METADATA_ROOT/warm-execution-plan.json"
cat "$METADATA_ROOT/warm-execution-plan.json"
- name: Warm serial and concurrent benchmarks
- name: Generate shared dataset and split target plans
id: generate
run: |
set -euo pipefail
python3 -u o11ybench/scripts/run_benchmark_plan.py \
--plan "$METADATA_ROOT/warm.json" --runtime-image "$RESOLVED_RUNTIME_IMAGE" --execute \
2>&1 | tee "$METADATA_ROOT/warm-execution.log"
python3 o11ybench/scripts/check_run_benchmark_plan.py --artifacts "$ARTIFACT_ROOT-warm"
python3 greptimedb/.github/scripts/o11ybench-storage.py metrics-prepare \
--plan "$METADATA_ROOT/warm.json" --tools o11ybench --runtime-image "$RESOLVED_RUNTIME_IMAGE"
- name: Load and benchmark Baseline GreptimeDB File
if: ${{ !cancelled() && steps.generate.outcome == 'success' && inputs.compare_greptimedb && inputs.greptimedb_storage != 's3' }}
run: |
python3 greptimedb/.github/scripts/o11ybench-storage.py metrics-run --target greptimedb-baseline \
--plan "$METADATA_ROOT/warm.json" --tools o11ybench --runtime-image "$RESOLVED_RUNTIME_IMAGE"
- name: Load and benchmark Baseline GreptimeDB S3
if: ${{ !cancelled() && steps.generate.outcome == 'success' && inputs.compare_greptimedb && inputs.greptimedb_storage != 'file' }}
env:
AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }}
AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
run: |
python3 greptimedb/.github/scripts/o11ybench-storage.py metrics-run --target greptimedb-s3-baseline \
--plan "$METADATA_ROOT/warm.json" --tools o11ybench --runtime-image "$RESOLVED_RUNTIME_IMAGE"
- name: Load and benchmark GreptimeDB File
if: ${{ !cancelled() && steps.generate.outcome == 'success' && inputs.run_greptimedb && inputs.greptimedb_storage != 's3' }}
run: |
python3 greptimedb/.github/scripts/o11ybench-storage.py metrics-run --target greptimedb \
--plan "$METADATA_ROOT/warm.json" --tools o11ybench --runtime-image "$RESOLVED_RUNTIME_IMAGE"
- name: Load and benchmark GreptimeDB S3
if: ${{ !cancelled() && steps.generate.outcome == 'success' && inputs.run_greptimedb && inputs.greptimedb_storage != 'file' }}
env:
AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }}
AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
run: |
python3 greptimedb/.github/scripts/o11ybench-storage.py metrics-run --target greptimedb-s3 \
--plan "$METADATA_ROOT/warm.json" --tools o11ybench --runtime-image "$RESOLVED_RUNTIME_IMAGE"
- name: Load and benchmark VictoriaMetrics
if: ${{ !cancelled() && steps.generate.outcome == 'success' && inputs.run_victoriametrics }}
run: |
python3 greptimedb/.github/scripts/o11ybench-storage.py metrics-run --target victoriametrics \
--plan "$METADATA_ROOT/warm.json" --tools o11ybench --runtime-image "$RESOLVED_RUNTIME_IMAGE"
- name: Load and benchmark Prometheus
if: ${{ !cancelled() && steps.generate.outcome == 'success' && inputs.run_prometheus }}
run: |
python3 greptimedb/.github/scripts/o11ybench-storage.py metrics-run --target prometheus \
--plan "$METADATA_ROOT/warm.json" --tools o11ybench --runtime-image "$RESOLVED_RUNTIME_IMAGE"
- name: Validate all selected target results
if: always() && steps.generate.outcome == 'success'
run: |
python3 greptimedb/.github/scripts/o11ybench-storage.py metrics-validate \
--plan "$METADATA_ROOT/warm.json" --tools o11ybench --runtime-image "$RESOLVED_RUNTIME_IMAGE"
- name: Clean up owned containers
env:
AWS_ACCESS_KEY_ID: ${{ inputs.greptimedb_storage != 'file' && secrets.AWS_ACCESS_KEY_ID || '' }}
AWS_SECRET_ACCESS_KEY: ${{ inputs.greptimedb_storage != 'file' && secrets.AWS_SECRET_ACCESS_KEY || '' }}
if: always()
run: |
docker ps -aq --filter "label=o11ybench.run-id=$RUN_ID-warm" | xargs -r docker rm -fv
for name in greptimedb greptimedb-s3 greptimedb-baseline greptimedb-s3-baseline victoriametrics prometheus; do
plan="$METADATA_ROOT/$name.json"
[[ -f "$plan" ]] || continue
run_id=$(jq -r '.run_id // empty' "$plan")
[[ -n "$run_id" ]] || continue
docker ps -aq --filter "label=o11ybench.run-id=$run_id" | xargs -r docker rm -fv
done
if [[ -d "$ARTIFACT_ROOT-warm" ]]; then
for probe in "$ARTIFACT_ROOT-warm"/o11ybench/*/*/s3-probe.json; do
[[ -f "$probe" ]] || continue
python3 o11ybench/scripts/greptimedb_storage.py recover --runtime-image "$RESOLVED_RUNTIME_IMAGE" --output "${probe%/*}"
done
fi
- name: GreptimeDB version comparison
if: always() && inputs.compare_greptimedb
run: |
python3 greptimedb/.github/scripts/benchmark-version-comparison.py report --kind long-range --root "$ARTIFACT_ROOT-warm" >> "$GITHUB_STEP_SUMMARY"
python3 greptimedb/.github/scripts/benchmark-version-comparison.py report --kind long-range --root "$ARTIFACT_ROOT-warm" | tee -a "$ARTIFACT_ROOT-warm/ci-summary.md" >> "$GITHUB_STEP_SUMMARY"
- name: Render storage comparison overview
if: always() && steps.generate.outcome == 'success'
run: |
mkdir -p "$ARTIFACT_ROOT-warm/metadata"
cp "$METADATA_ROOT"/*-image.json "$ARTIFACT_ROOT-warm/metadata/"
python3 o11ybench/scripts/build_query_performance_report.py --metrics "$ARTIFACT_ROOT-warm" \
--output "$ARTIFACT_ROOT-warm-query-report.html" --json-output "$ARTIFACT_ROOT-warm-query-report.json"
python3 greptimedb/.github/scripts/o11ybench-storage.py overview "$ARTIFACT_ROOT-warm-query-report.json" \
| tee -a "$ARTIFACT_ROOT-warm/ci-summary.md" >> "$GITHUB_STEP_SUMMARY"
python3 greptimedb/.github/scripts/o11ybench-storage.py audit --root "$ARTIFACT_ROOT-warm" \
--report "$ARTIFACT_ROOT-warm-query-report.json" --targets "$(jq -r '[.targets[].kind] | unique | join(",")' "$METADATA_ROOT/warm.json")"
- name: Stage benchmark artifacts
if: always()
run: |
mkdir -p "$RUNNER_TEMP/vmbench-artifacts"
cp "$ARTIFACT_ROOT-warm"-query-report.* "$RUNNER_TEMP/vmbench-artifacts/" 2>/dev/null || true
if [[ -d "$METADATA_ROOT" ]]; then
rsync -a --no-owner --no-group "$METADATA_ROOT" "$RUNNER_TEMP/vmbench-artifacts/"
fi
Generated
+26 -25
View File
@@ -1657,7 +1657,7 @@ dependencies = [
"maybe-owned",
"rustix 1.0.7",
"rustix-linux-procfs",
"windows-sys 0.60.2",
"windows-sys 0.61.2",
"winx",
]
@@ -2285,7 +2285,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "117725a109d387c937a1533ce01b450cbde6b88abceea8473c4d7a85853cda3c"
dependencies = [
"lazy_static",
"windows-sys 0.48.0",
"windows-sys 0.59.0",
]
[[package]]
@@ -4518,6 +4518,7 @@ version = "1.4.0-alpha.0"
dependencies = [
"api",
"arrow-flight",
"async-stream",
"async-trait",
"bytes",
"cache",
@@ -4613,7 +4614,6 @@ dependencies = [
"parquet-variant-compute",
"parquet-variant-json",
"paste",
"regex",
"serde",
"serde_json",
"snafu 0.8.6",
@@ -6158,7 +6158,7 @@ dependencies = [
[[package]]
name = "greptime-proto"
version = "0.1.0"
source = "git+https://github.com/GreptimeTeam/greptime-proto.git?rev=9eb24ddd94ddb9295bff9e596834832a7d8ba008#9eb24ddd94ddb9295bff9e596834832a7d8ba008"
source = "git+https://github.com/GreptimeTeam/greptime-proto.git?rev=1a30dcbfc215923ed8de0e80d8d9dbe1fc7917b6#1a30dcbfc215923ed8de0e80d8d9dbe1fc7917b6"
dependencies = [
"prost 0.14.1",
"prost-types 0.14.1",
@@ -6251,11 +6251,11 @@ dependencies = [
[[package]]
name = "halfbrown"
version = "0.3.0"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "aa2c385c6df70fd180bbb673d93039dbd2cd34e41d782600bdf6e1ca7bce39aa"
checksum = "0c7ed2f2edad8a14c8186b847909a41fbb9c3eafa44f88bd891114ed5019da09"
dependencies = [
"hashbrown 0.15.4",
"hashbrown 0.16.1",
"serde",
]
@@ -6770,7 +6770,7 @@ dependencies = [
"libc",
"percent-encoding",
"pin-project-lite",
"socket2 0.5.10",
"socket2 0.6.4",
"tokio",
"tower-service",
"tracing",
@@ -8195,6 +8195,7 @@ dependencies = [
"bytes",
"chrono",
"common-base",
"common-cache",
"common-config",
"common-error",
"common-macro",
@@ -9333,7 +9334,7 @@ version = "0.50.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5"
dependencies = [
"windows-sys 0.60.2",
"windows-sys 0.61.2",
]
[[package]]
@@ -10816,9 +10817,9 @@ dependencies = [
[[package]]
name = "pgwire"
version = "0.42.1"
version = "0.42.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1452e6541bcc64e166ff9d350c25c09334c0c80e8f60fde5e36ff81768eeaa55"
checksum = "69354d96ef951739b5ccc75a99a8a1b09bc164afde265be9656ddab87395b481"
dependencies = [
"async-trait",
"aws-lc-rs",
@@ -11606,7 +11607,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ac6c3320f9abac597dcbc668774ef006702672474aad53c6d596b62e487b40b1"
dependencies = [
"heck 0.5.0",
"itertools 0.10.5",
"itertools 0.14.0",
"log",
"multimap",
"once_cell",
@@ -11654,7 +11655,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8a56d757972c98b346a9b766e3f02746cde6dd1cd1d1d563472929fdd74bec4d"
dependencies = [
"anyhow",
"itertools 0.10.5",
"itertools 0.14.0",
"proc-macro2",
"quote",
"syn 2.0.117",
@@ -11667,7 +11668,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9120690fafc389a67ba3803df527d0ec9cbbc9cc45e4cc20b332996dfb672425"
dependencies = [
"anyhow",
"itertools 0.10.5",
"itertools 0.14.0",
"proc-macro2",
"quote",
"syn 2.0.117",
@@ -11964,6 +11965,7 @@ dependencies = [
"async-stream",
"async-trait",
"bytes",
"cache",
"catalog",
"chrono",
"common-base",
@@ -11974,6 +11976,7 @@ dependencies = [
"common-macro",
"common-meta",
"common-plugins",
"common-procedure",
"common-query",
"common-recordbatch",
"common-runtime",
@@ -13221,7 +13224,7 @@ dependencies = [
"security-framework 3.7.0",
"security-framework-sys",
"webpki-root-certs",
"windows-sys 0.60.2",
"windows-sys 0.61.2",
]
[[package]]
@@ -13991,13 +13994,11 @@ checksum = "d66dc143e6b11c1eddc06d5c423cfc97062865baf299914ab64caa38182078fe"
[[package]]
name = "simd-json"
version = "0.15.1"
version = "0.19.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c962f626b54771990066e5435ec8331d1462576cd2d1e62f24076ae014f92112"
checksum = "e8f2e4d523646f7da6dde3983bd18ede0babc21c258ab708b3dd93ea0259719d"
dependencies = [
"getrandom 0.3.4",
"halfbrown",
"ref-cast",
"serde",
"serde_json",
"simdutf8",
@@ -14146,7 +14147,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "52d1cfed4120b4d927bf7c0f86d2087a4a7d6027c906d9f9d525a80573b9be51"
dependencies = [
"libc",
"windows-sys 0.60.2",
"windows-sys 0.61.2",
]
[[package]]
@@ -14717,7 +14718,7 @@ dependencies = [
"cfg-if",
"libc",
"psm",
"windows-sys 0.60.2",
"windows-sys 0.61.2",
]
[[package]]
@@ -15342,7 +15343,7 @@ dependencies = [
"getrandom 0.3.4",
"once_cell",
"rustix 1.0.7",
"windows-sys 0.60.2",
"windows-sys 0.61.2",
]
[[package]]
@@ -16595,9 +16596,9 @@ checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65"
[[package]]
name = "value-trait"
version = "0.11.0"
version = "0.12.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0508fce11ad19e0aab49ce20b6bec7f8f82902ded31df1c9fc61b90f0eb396b8"
checksum = "545a3d7089f11f1741d12963c057adf9443fc24325110a6a6daf582e825fd51b"
dependencies = [
"float-cmp",
"halfbrown",
@@ -17112,7 +17113,7 @@ version = "0.1.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf221c93e13a30d793f7645a0e7762c55d169dbb0a49671918a2319d289b10bb"
dependencies = [
"windows-sys 0.48.0",
"windows-sys 0.59.0",
]
[[package]]
+2 -2
View File
@@ -164,7 +164,7 @@ fs2 = "0.4"
fst = "0.4.7"
futures = "0.3"
futures-util = "0.3"
greptime-proto = { git = "https://github.com/GreptimeTeam/greptime-proto.git", rev = "9eb24ddd94ddb9295bff9e596834832a7d8ba008" }
greptime-proto = { git = "https://github.com/GreptimeTeam/greptime-proto.git", rev = "1a30dcbfc215923ed8de0e80d8d9dbe1fc7917b6" }
hdfs-native = "0.14.6"
hex = "0.4"
hostname = "0.4.0"
@@ -248,7 +248,7 @@ serde_json = { version = "1.0", features = ["float_roundtrip"] }
serde_with = "3"
serde_yaml_ng = "0.10"
sha2 = "0.10"
simd-json = "0.15"
simd-json = "0.19"
similar-asserts = "1.6.0"
smallvec = { version = "1", features = ["serde"] }
snafu = "0.8"
+82 -94
View File
@@ -9,13 +9,11 @@
<h2 align="center">Metrics, logs, and traces.<br/>
One engine, on your infrastructure.</h2>
> A columnar database for metrics, logs, and traces on object storage.
> Apache-2.0 licensed core.
<div align="center">
<a href="https://docs.greptime.com/user-guide/overview/">User Guide</a> &nbsp;·&nbsp;
<a href="https://greptimedb.rs/">API Docs</a> &nbsp;·&nbsp;
<a href="https://live.greptime.cloud/dashboard/?info=eyJ1c2VybmFtZSI6ImdyZXB0aW1lIiwicGFzc3dvcmQiOiJkZW1vc2Vzc2lvbiJ9&query_guide=1&utm_source=github&utm_medium=readme&utm_campaign=greptimedb#/dashboard/explore">Live Demo</a> &nbsp;·&nbsp;
<a href="https://github.com/GreptimeTeam/greptimedb/issues/7685">Roadmap 2026</a> &nbsp;·&nbsp;
<a href="https://greptime.com/slack">Slack</a>
@@ -61,76 +59,6 @@ LIMIT 20;
Metrics join the same way, on any tag the tables share, such as `service`,
`host`, or `pod`.
## Why You Might Use It
- You run Prometheus plus Loki or Elasticsearch and want one backend instead of three
- You have outgrown Prometheus on cardinality or retention and don't want the Thanos/Mimir operational surface
- You are hitting Loki's query performance limits as log volume grows
- You need long retention on object storage without a separate analytics stack
- You want to query telemetry with SQL, not only a domain query language
- You are storing GenAI or agent telemetry ([OTel GenAI conventions](https://opentelemetry.io/docs/specs/semconv/gen-ai/)) alongside infrastructure signals
Learn more in [Why GreptimeDB](https://docs.greptime.com/user-guide/concepts/why-greptimedb).
## What's Supported
| | |
|---|---|
| **Ingest** | [OpenTelemetry (OTLP)](https://docs.greptime.com/user-guide/ingest-data/for-observability/opentelemetry/), [Prometheus Remote Write](https://docs.greptime.com/user-guide/ingest-data/for-observability/prometheus/), [Loki Push](https://docs.greptime.com/user-guide/ingest-data/for-observability/loki), [Elasticsearch Bulk](https://docs.greptime.com/user-guide/ingest-data/for-observability/elasticsearch), [InfluxDB line protocol](https://docs.greptime.com/user-guide/protocols/influxdb-line-protocol), [gRPC](https://docs.greptime.com/user-guide/protocols/grpc/) |
| **Query** | [SQL](https://docs.greptime.com/user-guide/query-data/overview/), [PromQL](https://docs.greptime.com/user-guide/query-data/promql/), [Jaeger-compatible trace queries](https://docs.greptime.com/user-guide/query-data/jaeger/), MySQL and PostgreSQL wire protocols |
| **Storage** | S3, GCS, Azure Blob and S3-compatible endpoints as [primary storage](https://docs.greptime.com/user-guide/deployments-administration/configuration/#storage-options), with memory and local-disk caches |
| **Built in** | Retention policies, downsampling, [continuous aggregation](https://docs.greptime.com/user-guide/flow-computation/overview), explicit table partitioning, and [inverted / skipping / fulltext indexes](https://docs.greptime.com/user-guide/manage-data/data-index) |
Compute and storage are disaggregated: object storage holds the data, while memory and local-disk caches keep recent and frequently queried data close to compute.
<p align="center">
<a href="https://github.com/GreptimeTeam/greptimedb/raw/main/docs/overview.png" target="_blank" rel="noopener">
<img alt="GreptimeDB Overview" src="docs/overview.png" width="900px">
</a>
</p>
## Benchmarks
* [Agent RCA Bench](https://rca-bench.greptime.com/): LLM agents doing root cause analysis
over GreptimeDB versus Prometheus + Loki + Tempo. 40% fewer wrong diagnoses, 48% fewer
input tokens, 45% lower cost
([write-up](https://greptime.com/blogs/2026-09-08-agent-rca-bench-interface-semantic-layer))
* [GreptimeDB tops JSONBench's billion-record cold run test](https://greptime.com/blogs/2025-03-18-jsonbench-greptimedb-performance)
* [TSBS Benchmark](https://github.com/GreptimeTeam/greptimedb/tree/main/docs/benchmarks/tsbs)
* [More benchmark reports](https://docs.greptime.com/user-guide/concepts/features-that-you-concern#how-is-greptimedbs-performance-compared-to-other-solutions)
## Compatibility and Migration
Compatibility is per protocol, and query-side coverage is narrower than ingestion.
| | Compatible | Not compatible |
|---|---|---|
| **Prometheus** | Remote Write ingestion; PromQL queries | Gaps are listed in [PromQL compatibility](https://docs.greptime.com/user-guide/query-data/promql/) |
| **Loki** | Push ingestion; dual-write through Grafana Alloy makes the [cutover gradual](https://greptime.com/blogs/2026-07-23-from-loki-to-greptimedb-dual-write-migration) | LogQL and the rest of the Loki query API |
| **Elasticsearch** | `_bulk` ingestion in the open-source core; [QueryDSL](https://docs.greptime.com/enterprise/elasticsearch-compatible/query/) partially, in Enterprise | Most other Elasticsearch APIs |
## Limitations and Edition Boundary
Cluster deployment, object storage, the Flow engine, and every ingestion protocol listed above are in the Apache-2.0 build. Repartitioning, region migration, and index creation are manual operations there.
Read replicas, workload isolation, and automated repartitioning are **GreptimeDB Enterprise** features, along with enterprise security and governance. The [Enterprise overview](https://docs.greptime.com/enterprise/overview/) has the current list, and [pricing](https://www.greptime.com/pricing#differences) has the edition comparison.
## Architecture
GreptimeDB can run in two modes:
* **Standalone** — single binary for development and small deployments.
* **Distributed** — four components, each independently scalable:
- **Frontend** — protocol entry (OTel, Prometheus, MySQL/PostgreSQL, gRPC, ingestion APIs for Elasticsearch/InfluxDB/Loki) and the distributed query engine. Stateless, scales horizontally.
- **Datanode** — region engine with WAL, memtable, SST, cache, compaction, and indexes. Persists data to object storage. Elastic.
- **Metasrv** — metadata, routing, repartitioning, and security. Backed by a pluggable KV layer (etcd or RDS).
- **Flownode** (optional) — continuous flow computation (streaming and materialized views).
For deeper coverage, see the [architecture doc](https://docs.greptime.com/contributor-guide/overview/#architecture) or [DeepWiki](https://deepwiki.com/GreptimeTeam/greptimedb/1-overview).
<a href="https://github.com/GreptimeTeam/greptimedb/raw/main/docs/architecture.png" target="_blank" rel="noopener">
<img alt="GreptimeDB System Overview" src="https://cdn.jsdelivr.net/gh/GreptimeTeam/greptimedb@main/docs/architecture.png">
</a>
## Try GreptimeDB
**For AI agents** — paste this prompt into your agent:
@@ -150,20 +78,81 @@ docker run -p 127.0.0.1:4000-4003:4000-4003 \
--mysql-addr 0.0.0.0:4002 \
--postgres-addr 0.0.0.0:4003
```
Dashboard: [http://localhost:4000/dashboard](http://localhost:4000/dashboard)
Dashboard: [http://localhost:4000/dashboard](http://localhost:4000/dashboard)
Or skip the install and try the [Live Demo](https://live.greptime.cloud/dashboard/?info=eyJ1c2VybmFtZSI6ImdyZXB0aW1lIiwicGFzc3dvcmQiOiJkZW1vc2Vzc2lvbiJ9&query_guide=1&utm_source=github&utm_medium=readme&utm_campaign=greptimedb#/dashboard/explore).
Read more in the [full Install Guide](https://docs.greptime.com/getting-started/installation/overview).
Next: [Quickstart](https://docs.greptime.com/getting-started/quick-start), the [full Install Guide](https://docs.greptime.com/getting-started/installation/overview), [Demo Scenes](https://github.com/GreptimeTeam/demo-scene), and the [FAQ](https://docs.greptime.com/faq-and-others/faq).
**Troubleshooting:**
* Cannot connect to the database? Ensure that ports `4000`, `4001`, `4002`, and `4003` are not blocked by a firewall or used by other services.
* Failed to start? Check the container logs with `docker logs greptime` for further details.
## Why You Might Use It
## Getting Started
- You run Prometheus plus Loki or Elasticsearch and want one backend instead of three
- You have outgrown Prometheus on cardinality or retention and don't want the Thanos/Mimir operational surface
- You are hitting Loki's query performance limits as log volume grows
- You need long retention on object storage without a separate analytics stack
- You want to query telemetry with SQL, not only a domain query language
- You are storing GenAI or agent telemetry ([OTel GenAI conventions](https://opentelemetry.io/docs/specs/semconv/gen-ai/)) alongside infrastructure signals
- [Quickstart](https://docs.greptime.com/getting-started/quick-start)
- [User Guide](https://docs.greptime.com/user-guide/overview)
- [Demo Scenes](https://github.com/GreptimeTeam/demo-scene)
- [FAQ](https://docs.greptime.com/faq-and-others/faq)
Learn more in [Why GreptimeDB](https://docs.greptime.com/user-guide/concepts/why-greptimedb).
## What's Supported
| | |
|---|---|
| **Ingest** | [OpenTelemetry (OTLP)](https://docs.greptime.com/user-guide/ingest-data/for-observability/opentelemetry/), [Prometheus Remote Write](https://docs.greptime.com/user-guide/ingest-data/for-observability/prometheus/) (with [native histograms](https://docs.greptime.com/user-guide/ingest-data/for-observability/prometheus/#native-histograms) over Remote Write 2.0), [Loki Push](https://docs.greptime.com/user-guide/ingest-data/for-observability/loki), [Elasticsearch Bulk](https://docs.greptime.com/user-guide/ingest-data/for-observability/elasticsearch), [InfluxDB line protocol](https://docs.greptime.com/user-guide/protocols/influxdb-line-protocol), [gRPC](https://docs.greptime.com/user-guide/protocols/grpc/) |
| **Query** | [SQL](https://docs.greptime.com/user-guide/query-data/overview/), [PromQL](https://docs.greptime.com/user-guide/query-data/promql/), [Jaeger-compatible trace queries](https://docs.greptime.com/user-guide/query-data/jaeger/), MySQL and PostgreSQL wire protocols |
| **Storage** | S3, GCS, Azure Blob and S3-compatible endpoints as [primary storage](https://docs.greptime.com/user-guide/deployments-administration/configuration/#storage-options), with memory and local-disk caches |
| **Built in** | [Pipelines](https://docs.greptime.com/user-guide/logs/use-custom-pipelines) that parse and transform logs at ingestion, retention policies, downsampling, [continuous aggregation](https://docs.greptime.com/user-guide/flow-computation/overview), explicit table partitioning, and [inverted / skipping / fulltext indexes](https://docs.greptime.com/user-guide/manage-data/data-index) |
Compute and storage are disaggregated: object storage holds the data, while memory and local-disk caches keep recent and frequently queried data close to compute.
<p align="center">
<a href="https://github.com/GreptimeTeam/greptimedb/raw/main/docs/overview.png" target="_blank" rel="noopener">
<img alt="GreptimeDB Overview" src="docs/overview.png" width="900px">
</a>
</p>
## Benchmarks
* [Agent RCA Bench](https://rca-bench.greptime.com/): LLM agents doing root cause analysis
over GreptimeDB versus Prometheus + Loki + Tempo, 168 investigations per interface across
six models. 40% fewer wrong diagnoses, about 48% fewer input tokens, about 45% lower
estimated cost
([write-up](https://greptime.com/blogs/2026-09-08-agent-rca-bench-interface-semantic-layer))
* [JSONBench billion-record cold run: first place as of March 2025](https://greptime.com/blogs/2025-03-18-jsonbench-greptimedb-performance)
* [TSBS Benchmark](https://github.com/GreptimeTeam/greptimedb/tree/main/docs/benchmarks/tsbs)
* [More benchmark reports](https://docs.greptime.com/user-guide/concepts/features-that-you-concern#how-is-greptimedbs-performance-compared-to-other-solutions)
## Compatibility and Migration
Compatibility is per protocol, and query-side coverage is narrower than ingestion.
| | Compatible | Not compatible |
|---|---|---|
| **Prometheus** | Remote Write ingestion; PromQL queries | Gaps are listed in [PromQL compatibility](https://docs.greptime.com/user-guide/query-data/promql/) |
| **Loki** | Push ingestion; dual-write through Grafana Alloy makes the [cutover gradual](https://greptime.com/blogs/2026-07-23-from-loki-to-greptimedb-dual-write-migration) | LogQL and the rest of the Loki query API |
| **Elasticsearch** | `_bulk` ingestion in the open-source core; [QueryDSL](https://docs.greptime.com/enterprise/elasticsearch-compatible/query/) partially, in Enterprise | Most other Elasticsearch APIs |
## Limitations and Edition Boundary
Cluster deployment, object storage, the Flow engine, and every ingestion protocol listed above are in the Apache-2.0 build. Repartitioning and region migration are manual operations there.
Read replicas, workload isolation, and automated repartitioning are **GreptimeDB Enterprise** features, along with enterprise security and governance. The [Enterprise overview](https://docs.greptime.com/enterprise/overview/) has the current list, and [pricing](https://www.greptime.com/pricing#differences) has the edition comparison. For GreptimeDB Enterprise inquiries, [contact us](https://greptime.com/contactus).
## Architecture
GreptimeDB can run in two modes:
* **Standalone** — single binary for development and small deployments.
* **Distributed** — four components, each independently scalable:
- **Frontend** — protocol endpoints and the distributed query engine. Stateless, scales horizontally.
- **Datanode** — region engine with WAL, memtable, SST, cache, compaction, and indexes. Persists data to object storage.
- **Metasrv** — metadata, region routing, and cluster coordination (DDL procedures, failover, region migration, repartitioning). Backed by a pluggable KV layer (etcd or RDS).
- **Flownode** (optional) — continuous flow computation (streaming and materialized views).
For deeper coverage, see the [architecture doc](https://docs.greptime.com/contributor-guide/overview/#architecture) or [DeepWiki](https://deepwiki.com/GreptimeTeam/greptimedb/1-overview).
<a href="https://github.com/GreptimeTeam/greptimedb/raw/main/docs/architecture.png" target="_blank" rel="noopener">
<img alt="GreptimeDB System Overview" src="https://cdn.jsdelivr.net/gh/GreptimeTeam/greptimedb@main/docs/architecture.png">
</a>
## Build From Source
@@ -202,12 +191,10 @@ See the [Contribution Guidelines](CONTRIBUTING.md) for the full developer workfl
GreptimeDB is generally available, with stable APIs and regular releases. It runs in production at scale — [OceanBase Cloud](https://greptime.com/blogs/2025-07-22-user-case-obcloud-log-management-greptimedb) operates 80+ GreptimeDB clusters managing 300 TB of logs, cutting log storage cost by 60%+ after migrating from Grafana Loki. See more in [case studies](https://greptime.com/blogs/?category=Use%20Case).
Release lines and support windows are in the [version reference](https://docs.greptime.com/nightly/reference/about-greptimedb-version). For where the project is going, read the [v1.0 highlights](https://greptime.com/blogs/2025-11-05-greptimedb-v1-highlights), the [2026 roadmap](https://greptime.com/blogs/2026-02-11-greptimedb-roadmap-2026), and [what we mean by an observability database](https://greptime.com/blogs/2026-08-26-what-is-an-observability-database).
Releases follow [Semantic Versioning](https://docs.greptime.com/reference/about-greptimedb-version). For where the project is going, read the [v1.0 highlights](https://greptime.com/blogs/2025-11-05-greptimedb-v1-highlights), the [2026 roadmap](https://github.com/GreptimeTeam/greptimedb/issues/7685), and [what we mean by an observability database](https://greptime.com/blogs/2026-08-26-what-is-an-observability-database).
## Community
We invite you to engage and contribute!
- [Slack](https://greptime.com/slack)
- [Discussions](https://github.com/GreptimeTeam/greptimedb/discussions)
- [Official Website](https://greptime.com/)
@@ -218,6 +205,14 @@ We invite you to engage and contribute!
If GreptimeDB is useful to you, please star the repo.
<a href="https://www.star-history.com/?repos=GreptimeTeam%2FGreptimeDB&type=date&legend=top-left">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/chart?repos=GreptimeTeam/GreptimeDB&type=date&theme=dark&legend=top-left" />
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/chart?repos=GreptimeTeam/GreptimeDB&type=date&legend=top-left" />
<img alt="Star History Chart" src="https://api.star-history.com/chart?repos=GreptimeTeam/GreptimeDB&type=date&legend=top-left" />
</picture>
</a>
<img alt="Known Users" src="https://greptime.com/logo/img/users.png"/>
## License
@@ -230,17 +225,10 @@ A small set of peripheral, enterprise-only features are gated behind the
separate [GreptimeDB Enterprise License](LICENSE-ENTERPRISE). Source files under
that license carry an explicit Enterprise License header.
## Commercial Support
Scaling observability on your infrastructure?
[GreptimeDB Enterprise](https://docs.greptime.com/enterprise/overview/) adds the operational,
security, and support layer for production deployments.
[Contact us](https://greptime.com/contactus) for details.
## Contributing
- Read our [Contribution Guidelines](CONTRIBUTING.md).
- Explore [Internal Concepts](https://docs.greptime.com/contributor-guide/overview.html) and [DeepWiki](https://deepwiki.com/GreptimeTeam/greptimedb).
- Explore [Internal Concepts](https://docs.greptime.com/contributor-guide/overview/) and [DeepWiki](https://deepwiki.com/GreptimeTeam/greptimedb).
- Pick up a [good first issue](https://github.com/GreptimeTeam/greptimedb/issues?q=is%3Aissue+is%3Aopen+label%3A%22good+first+issue%22) and join the #contributors [Slack](https://greptime.com/slack) channel.
[![Integration CI](https://github.com/GreptimeTeam/greptimedb/actions/workflows/integration.yml/badge.svg)](https://github.com/GreptimeTeam/greptimedb/actions/workflows/integration.yml)
+4 -2
View File
@@ -190,7 +190,7 @@
| `region_engine.mito.experimental_series_index_maintenance_interval` | String | `5m` | Interval between series-index maintenance runs. Zero uses the default of 5 min. |
| `region_engine.mito.experimental_series_index_bucket_width` | String | `5days` | Requested minimum series-index bucket width (default: 5 days), rounded up to<br/>an exact multiple of each region's compaction time window. |
| `region_engine.mito.max_background_flushes` | Integer | Auto | Max number of running background flush jobs (default: 1/2 of cpu cores). |
| `region_engine.mito.max_background_compactions` | Integer | Auto | Max number of running background compaction jobs (default: 1/4 of cpu cores). |
| `region_engine.mito.max_background_compactions` | Integer | Auto | Max number of running background compaction jobs (default: 1/4 of cpu cores).<br/>The same limit bounds engine-wide admission of local compaction units and<br/>the merge-output budget of each automatic per-region pick. Outputs sharing<br/>inputs form one unit. Expired SSTs may add one expiration-only unit outside<br/>the merge-output budget; it still consumes a slot in the same admission limit.<br/>Manual compaction keeps using the request's parallelism. |
| `region_engine.mito.max_background_purges` | Integer | Auto | Max number of running background purge jobs (default: number of cpu cores). |
| `region_engine.mito.experimental_compaction_memory_limit` | String | 0 | Memory budget for compaction tasks.<br/>Supports absolute size (e.g., "2GiB", "512MB") or percentage of system memory (e.g., "50%").<br/>Setting it to 0 or "unlimited" disables the limit. |
| `region_engine.mito.experimental_compaction_on_exhausted` | String | wait | Behavior when compaction cannot acquire memory from the budget.<br/>Options: "wait" (default, 10s), "wait(<duration>)", "fail" |
@@ -276,6 +276,7 @@
| `pipeline` | -- | -- | The pipeline options. |
| `pipeline.cache_ttl` | String | `10s` | Time to live of the local pipeline cache. Default is `10s`. |
| `pipeline.allow_vrl_host_access` | Bool | `false` | Allow VRL to access the server environment, filesystem, hostname, local timezone,<br/>network, and logs. Default is false. Enable only for trusted pipeline authors.<br/>Applies to pipeline creation, execution, and dry-runs. Requires a restart. |
| `pipeline.ignore_errors` | Bool | `false` | Default for the HTTP log ingestion and pipeline dry-run `ignore_errors` parameter.<br/>Explicit request values override this setting. Malformed input may be discarded,<br/>and invalid custom timestamps in identity ingestion fall back to server time.<br/>Pipeline execution errors are controlled separately by `skip_error`.<br/>Default is false. Requires a restart. |
| `event_recorder` | -- | -- | Configuration options for the event recorder. |
| `event_recorder.ttl` | String | `90d` | TTL for the events table that will be used to store the events. Default is `90d`. |
| `event_recorder.event_types` | Array | All | Event types to record. Current available event types: `create_database`,<br/>`alter_database`, `drop_database`, `create_flow`, `drop_flow`,<br/>`create_table`, `create_logical_tables`, `alter_table`, `alter_logical_tables`,<br/>`drop_table`, `undrop_table`, `purge_dropped_table`, `truncate_table`,<br/>`create_view`, `drop_view`, `admin_function`, `reconcile_catalog`,<br/>`reconcile_database`, `reconcile_table`, `reconcile_logical_tables`.<br/>When omitted, all current and future event types are recorded.<br/>Set to an empty array to disable event recording. |
@@ -438,6 +439,7 @@
| `pipeline` | -- | -- | The pipeline options. |
| `pipeline.cache_ttl` | String | `10s` | Time to live of the frontend-local pipeline cache. A pipeline created or deleted on<br/>another frontend takes effect on this one after at most this duration. |
| `pipeline.allow_vrl_host_access` | Bool | `false` | Allow VRL to access the server environment, filesystem, hostname, local timezone,<br/>network, and logs. Default is false. Enable only for trusted pipeline authors.<br/>Applies to pipeline creation, execution, and dry-runs. Requires a restart. |
| `pipeline.ignore_errors` | Bool | `false` | Default for the HTTP log ingestion and pipeline dry-run `ignore_errors` parameter.<br/>Explicit request values override this setting. Malformed input may be discarded,<br/>and invalid custom timestamps in identity ingestion fall back to server time.<br/>Pipeline execution errors are controlled separately by `skip_error`.<br/>Default is false. Requires a restart. |
| `event_recorder` | -- | -- | Configuration options for the event recorder. |
| `event_recorder.ttl` | String | `90d` | TTL for the events table that will be used to store the events. Default is `90d`. |
| `event_recorder.event_types` | Array | All | Event types to record. Current available event type: `admin_function`.<br/>When omitted, all current and future event types are recorded.<br/>Set to an empty array to disable event recording. |
@@ -671,7 +673,7 @@
| `region_engine.mito.experimental_series_index_maintenance_interval` | String | `5m` | Interval between series-index maintenance runs. Zero uses the default of 5 min. |
| `region_engine.mito.experimental_series_index_bucket_width` | String | `5days` | Requested minimum series-index bucket width (default: 5 days), rounded up to<br/>an exact multiple of each region's compaction time window. |
| `region_engine.mito.max_background_flushes` | Integer | Auto | Max number of running background flush jobs (default: 1/2 of cpu cores). |
| `region_engine.mito.max_background_compactions` | Integer | Auto | Max number of running background compaction jobs (default: 1/4 of cpu cores). |
| `region_engine.mito.max_background_compactions` | Integer | Auto | Max number of running background compaction jobs (default: 1/4 of cpu cores).<br/>The same limit bounds engine-wide admission of local compaction units and<br/>the merge-output budget of each automatic per-region pick. Outputs sharing<br/>inputs form one unit. Expired SSTs may add one expiration-only unit outside<br/>the merge-output budget; it still consumes a slot in the same admission limit.<br/>Manual compaction keeps using the request's parallelism. |
| `region_engine.mito.max_background_purges` | Integer | Auto | Max number of running background purge jobs (default: number of cpu cores). |
| `region_engine.mito.experimental_compaction_memory_limit` | String | 0 | Memory budget for compaction tasks.<br/>Supports absolute size (e.g., "2GiB", "512MB") or percentage of system memory (e.g., "50%").<br/>Setting it to 0 or "unlimited" disables the limit. |
| `region_engine.mito.experimental_compaction_on_exhausted` | String | wait | Behavior when compaction cannot acquire memory from the budget.<br/>Options: "wait" (default, 10s), "wait(<duration>)", "fail" |
+5
View File
@@ -580,6 +580,11 @@ compress_manifest = false
#+ max_background_flushes = 4
## Max number of running background compaction jobs (default: 1/4 of cpu cores).
## The same limit bounds engine-wide admission of local compaction units and
## the merge-output budget of each automatic per-region pick. Outputs sharing
## inputs form one unit. Expired SSTs may add one expiration-only unit outside
## the merge-output budget; it still consumes a slot in the same admission limit.
## Manual compaction keeps using the request's parallelism.
## @toml2docs:none-default="Auto"
#+ max_background_compactions = 2
+6
View File
@@ -519,6 +519,12 @@ cache_ttl = "10s"
## network, and logs. Default is false. Enable only for trusted pipeline authors.
## Applies to pipeline creation, execution, and dry-runs. Requires a restart.
allow_vrl_host_access = false
## Default for the HTTP log ingestion and pipeline dry-run `ignore_errors` parameter.
## Explicit request values override this setting. Malformed input may be discarded,
## and invalid custom timestamps in identity ingestion fall back to server time.
## Pipeline execution errors are controlled separately by `skip_error`.
## Default is false. Requires a restart.
ignore_errors = false
## Configuration options for the event recorder.
[event_recorder]
+11
View File
@@ -795,6 +795,11 @@ compress_manifest = false
#+ max_background_flushes = 4
## Max number of running background compaction jobs (default: 1/4 of cpu cores).
## The same limit bounds engine-wide admission of local compaction units and
## the merge-output budget of each automatic per-region pick. Outputs sharing
## inputs form one unit. Expired SSTs may add one expiration-only unit outside
## the merge-output budget; it still consumes a slot in the same admission limit.
## Manual compaction keeps using the request's parallelism.
## @toml2docs:none-default="Auto"
#+ max_background_compactions = 2
@@ -1151,6 +1156,12 @@ cache_ttl = "10s"
## network, and logs. Default is false. Enable only for trusted pipeline authors.
## Applies to pipeline creation, execution, and dry-runs. Requires a restart.
allow_vrl_host_access = false
## Default for the HTTP log ingestion and pipeline dry-run `ignore_errors` parameter.
## Explicit request values override this setting. Malformed input may be discarded,
## and invalid custom timestamps in identity ingestion fall back to server time.
## Pipeline execution errors are controlled separately by `skip_error`.
## Default is false. Requires a restart.
ignore_errors = false
## Configuration options for the event recorder.
[event_recorder]
+12 -5
View File
@@ -1,14 +1,17 @@
# Metric snapshot benchmark on AWS S3
The manual `Metric Snapshot S3 Benchmark` workflow tests packed Metric export and
restore against real S3 in `ap-southeast-1`. It must first exist on the repository's
default branch for GitHub to register `workflow_dispatch`. It was validated on AWS
restore against real S3 in the configured CI bucket region. It must first exist on
the repository's default branch for GitHub to register `workflow_dispatch`. It was validated on AWS
by run [38544464731](https://github.com/GreptimeTeam/greptimedb/actions/runs/38544464731);
[#9573](https://github.com/GreptimeTeam/greptimedb/pull/9573) records its conditions and results.
## Run
Use the repository's existing EC2 runner configuration and CI S3 credentials.
`AWS_CI_TEST_BUCKET_REGION` and `EC2_RUNNER_REGION` must be nonempty and equal;
for example, both can be `us-east-1`. The configured subnet, security group and
AMI (if explicitly supplied) must also belong to the runner region.
The workflow passes credentials only through CI; no local AWS credentials are
needed. Source, target and CLI use the same immutable image. This image's source
SHA and required CLI capabilities have been checked:
@@ -20,6 +23,7 @@ gh workflow run metric-snapshot-s3-bench.yml \
-f expected_commit=f690bbb2040865c0d22b0b57d51612b60ae27cd0 \
-f logical_tables_per_group=10000 \
-f benchmark_timeout_minutes=240 \
-f ec2_hourly_usd=0.9408 \
-f prior_spend_usd=0
```
@@ -28,9 +32,12 @@ earlier cloud attempts in the campaign, including failed setup and cleanup.
Do not reset the estimate to zero when retrying. The workflow accepts 50–10,000
logical tables per group and a 30–240 minute benchmark job timeout.
The runner is fixed at `c6id.4xlarge` (16 vCPU, 32 GiB RAM). At the recorded
Singapore Linux on-demand estimate of $0.9408/hour, the default attempt reserves
$6.4392: four benchmark hours, 45 minutes of provisioning, 10 minutes for queueing,
The runner is fixed at `c6id.4xlarge` (16 vCPU, 32 GiB RAM). Set
`ec2_hourly_usd` to a positive, finite hourly budget estimate appropriate for the
selected region and instance. Its default $0.9408/hour preserves the historical
Singapore estimate; it is not a live regional price or a guaranteed upper bound.
The same estimate is used for preflight reservation and the final cost summary.
At that default rate, the default attempt reserves $6.4392: four benchmark hours, 45 minutes of provisioning, 10 minutes for queueing,
20 minutes of cleanup, and $1.50 for S3, disk and IPv4 costs. Preflight rejects prior spend at or above
$15, or an attempt whose reserve would exceed the cumulative $20 budget.
These estimates and checks are not an AWS hard spending cap or an AWS bill.
@@ -13962,7 +13962,7 @@
"uid": "${metrics}"
},
"editorMode": "code",
"expr": "sum by (result) (\n changes(greptime_region_balancer_actions_total[$__rate_interval])\n)",
"expr": "sum by (result) (\n increase(greptime_region_balancer_actions_total[$__rate_interval])\n)",
"hide": false,
"instant": false,
"legendFormat": "{{result}}",
@@ -14064,7 +14064,7 @@
"uid": "${metrics}"
},
"editorMode": "code",
"expr": "sum by (gate, reason) (changes(greptime_region_balancer_gate_stop_total[$__rate_interval]))",
"expr": "sum by (gate, reason) (increase(greptime_region_balancer_gate_stop_total[$__rate_interval]))",
"hide": false,
"instant": false,
"legendFormat": "{{gate}} / {{reason}}",
@@ -14399,7 +14399,7 @@
"uid": "${metrics}"
},
"editorMode": "code",
"expr": "sum by (result) (changes(greptime_auto_repartition_actions_total[$__rate_interval]))",
"expr": "sum by (result) (increase(greptime_auto_repartition_actions_total[$__rate_interval]))",
"hide": false,
"instant": false,
"legendFormat": "{{result}}",
@@ -14415,7 +14415,7 @@
"type": "prometheus",
"uid": "${metrics}"
},
"description": "Auto repartition gate stop count by gate and reason",
"description": "Repartition gate stop increments. Baseline failures show detailed reasons when available; otherwise the aggregate invalid_baseline series is retained. Fallback is matched per source before aggregation to avoid double counting across mixed versions.",
"fieldConfig": {
"defaults": {
"color": {
@@ -14501,12 +14501,25 @@
"uid": "${metrics}"
},
"editorMode": "code",
"expr": "sum by (gate, reason) (changes(greptime_auto_repartition_gate_stop_total[$__rate_interval]))",
"expr": "sum by (gate, reason) (\n increase(greptime_auto_repartition_gate_stop_total{reason!=\"invalid_baseline\"}[$__rate_interval])\n or\n (increase(greptime_auto_repartition_gate_stop_total{reason=\"invalid_baseline\"}[$__rate_interval])\n unless ignoring (gate, reason)\n increase(greptime_auto_repartition_invalid_baseline_total[$__rate_interval]))\n)",
"hide": false,
"instant": false,
"legendFormat": "{{gate}} / {{reason}}",
"range": true,
"refId": "A"
},
{
"datasource": {
"type": "prometheus",
"uid": "${metrics}"
},
"editorMode": "code",
"expr": "sum by (reason) (increase(greptime_auto_repartition_invalid_baseline_total[$__rate_interval]))",
"hide": false,
"instant": false,
"legendFormat": "baseline / {{reason}}",
"range": true,
"refId": "B"
}
],
"title": "Auto Repartition Gate Stops",
@@ -241,14 +241,20 @@ ORDER BY data_size DESC;` | `piechart` | Distribution of leader regions and data
| Title | Query | Type | Description | Datasource | Unit | Legend Format |
| --- | --- | --- | --- | --- | --- | --- |
| Region Balancer Actions | `sum by (result) (
changes(greptime_region_balancer_actions_total[$__rate_interval])
increase(greptime_region_balancer_actions_total[$__rate_interval])
)` | `timeseries` | Region balancer action count | `prometheus` | `short` | `{{result}}` |
| Region Balancer Gate Stops | `sum by (gate, reason) (changes(greptime_region_balancer_gate_stop_total[$__rate_interval]))` | `timeseries` | Region balancer gate stop count by gate and reason | `prometheus` | `short` | `{{gate}} / {{reason}}` |
| Region Balancer Gate Stops | `sum by (gate, reason) (increase(greptime_region_balancer_gate_stop_total[$__rate_interval]))` | `timeseries` | Region balancer gate stop count by gate and reason | `prometheus` | `short` | `{{gate}} / {{reason}}` |
| Region Balancer Datanodes | `sum by (state) (greptime_region_balancer_datanodes)` | `stat` | Region balancer datanode count by state | `prometheus` | `short` | `{{state}}` |
| Region Balancer Regions | `sum by (state) (greptime_region_balancer_regions)` | `stat` | Region balancer region count by state | `prometheus` | `short` | `{{state}}` |
| Region Balancer Datanode Stability | `sum by (state) (greptime_region_balancer_datanode_stability)` | `stat` | Region balancer datanode stability statistics by state | `prometheus` | `binBps` | `{{state}}` |
| Auto Repartition Actions | `sum by (result) (changes(greptime_auto_repartition_actions_total[$__rate_interval]))` | `timeseries` | Auto repartition action count by result | `prometheus` | `short` | `{{result}}` |
| Auto Repartition Gate Stops | `sum by (gate, reason) (changes(greptime_auto_repartition_gate_stop_total[$__rate_interval]))` | `timeseries` | Auto repartition gate stop count by gate and reason | `prometheus` | `short` | `{{gate}} / {{reason}}` |
| Auto Repartition Actions | `sum by (result) (increase(greptime_auto_repartition_actions_total[$__rate_interval]))` | `timeseries` | Auto repartition action count by result | `prometheus` | `short` | `{{result}}` |
| Auto Repartition Gate Stops | `sum by (gate, reason) (
increase(greptime_auto_repartition_gate_stop_total{reason!="invalid_baseline"}[$__rate_interval])
or
(increase(greptime_auto_repartition_gate_stop_total{reason="invalid_baseline"}[$__rate_interval])
unless ignoring (gate, reason)
increase(greptime_auto_repartition_invalid_baseline_total[$__rate_interval]))
)`<br/>`sum by (reason) (increase(greptime_auto_repartition_invalid_baseline_total[$__rate_interval]))` | `timeseries` | Repartition gate stop increments. Baseline failures show detailed reasons when available; otherwise the aggregate invalid_baseline series is retained. Fallback is matched per source before aggregation to avoid double counting across mixed versions. | `prometheus` | `short` | `{{gate}} / {{reason}}` |
| Auto Repartition Sampling P99 | `histogram_quantile(0.99, sum by (le, stage) (rate(greptime_auto_repartition_sampling_elapsed_bucket[$__rate_interval])))` | `timeseries` | Auto repartition sampling elapsed time by stage | `prometheus` | `s` | `{{stage}}` |
| Auto Repartition Executor P99 | `histogram_quantile(0.99, sum by (le, stage) (rate(greptime_auto_repartition_executor_elapsed_bucket[$__rate_interval])))` | `timeseries` | Auto repartition executor elapsed time by stage | `prometheus` | `s` | `{{stage}}` |
# Object Store
@@ -1904,7 +1904,7 @@ groups:
queries:
- expr: |-
sum by (result) (
changes(greptime_region_balancer_actions_total[$__rate_interval])
increase(greptime_region_balancer_actions_total[$__rate_interval])
)
datasource:
type: prometheus
@@ -1915,7 +1915,7 @@ groups:
description: Region balancer gate stop count by gate and reason
unit: short
queries:
- expr: sum by (gate, reason) (changes(greptime_region_balancer_gate_stop_total[$__rate_interval]))
- expr: sum by (gate, reason) (increase(greptime_region_balancer_gate_stop_total[$__rate_interval]))
datasource:
type: prometheus
uid: ${metrics}
@@ -1955,21 +1955,33 @@ groups:
description: Auto repartition action count by result
unit: short
queries:
- expr: sum by (result) (changes(greptime_auto_repartition_actions_total[$__rate_interval]))
- expr: sum by (result) (increase(greptime_auto_repartition_actions_total[$__rate_interval]))
datasource:
type: prometheus
uid: ${metrics}
legendFormat: '{{result}}'
- title: Auto Repartition Gate Stops
type: timeseries
description: Auto repartition gate stop count by gate and reason
description: Repartition gate stop increments. Baseline failures show detailed reasons when available; otherwise the aggregate invalid_baseline series is retained. Fallback is matched per source before aggregation to avoid double counting across mixed versions.
unit: short
queries:
- expr: sum by (gate, reason) (changes(greptime_auto_repartition_gate_stop_total[$__rate_interval]))
- expr: |-
sum by (gate, reason) (
increase(greptime_auto_repartition_gate_stop_total{reason!="invalid_baseline"}[$__rate_interval])
or
(increase(greptime_auto_repartition_gate_stop_total{reason="invalid_baseline"}[$__rate_interval])
unless ignoring (gate, reason)
increase(greptime_auto_repartition_invalid_baseline_total[$__rate_interval]))
)
datasource:
type: prometheus
uid: ${metrics}
legendFormat: '{{gate}} / {{reason}}'
- expr: sum by (reason) (increase(greptime_auto_repartition_invalid_baseline_total[$__rate_interval]))
datasource:
type: prometheus
uid: ${metrics}
legendFormat: baseline / {{reason}}
- title: Auto Repartition Sampling P99
type: timeseries
description: Auto repartition sampling elapsed time by stage
@@ -13962,7 +13962,7 @@
"uid": "${metrics}"
},
"editorMode": "code",
"expr": "sum by (result) (\n changes(greptime_region_balancer_actions_total[$__rate_interval])\n)",
"expr": "sum by (result) (\n increase(greptime_region_balancer_actions_total[$__rate_interval])\n)",
"hide": false,
"instant": false,
"legendFormat": "{{result}}",
@@ -14064,7 +14064,7 @@
"uid": "${metrics}"
},
"editorMode": "code",
"expr": "sum by (gate, reason) (changes(greptime_region_balancer_gate_stop_total[$__rate_interval]))",
"expr": "sum by (gate, reason) (increase(greptime_region_balancer_gate_stop_total[$__rate_interval]))",
"hide": false,
"instant": false,
"legendFormat": "{{gate}} / {{reason}}",
@@ -14399,7 +14399,7 @@
"uid": "${metrics}"
},
"editorMode": "code",
"expr": "sum by (result) (changes(greptime_auto_repartition_actions_total[$__rate_interval]))",
"expr": "sum by (result) (increase(greptime_auto_repartition_actions_total[$__rate_interval]))",
"hide": false,
"instant": false,
"legendFormat": "{{result}}",
@@ -14415,7 +14415,7 @@
"type": "prometheus",
"uid": "${metrics}"
},
"description": "Auto repartition gate stop count by gate and reason",
"description": "Repartition gate stop increments. Baseline failures show detailed reasons when available; otherwise the aggregate invalid_baseline series is retained. Fallback is matched per source before aggregation to avoid double counting across mixed versions.",
"fieldConfig": {
"defaults": {
"color": {
@@ -14501,12 +14501,25 @@
"uid": "${metrics}"
},
"editorMode": "code",
"expr": "sum by (gate, reason) (changes(greptime_auto_repartition_gate_stop_total[$__rate_interval]))",
"expr": "sum by (gate, reason) (\n increase(greptime_auto_repartition_gate_stop_total{reason!=\"invalid_baseline\"}[$__rate_interval])\n or\n (increase(greptime_auto_repartition_gate_stop_total{reason=\"invalid_baseline\"}[$__rate_interval])\n unless ignoring (gate, reason)\n increase(greptime_auto_repartition_invalid_baseline_total[$__rate_interval]))\n)",
"hide": false,
"instant": false,
"legendFormat": "{{gate}} / {{reason}}",
"range": true,
"refId": "A"
},
{
"datasource": {
"type": "prometheus",
"uid": "${metrics}"
},
"editorMode": "code",
"expr": "sum by (reason) (increase(greptime_auto_repartition_invalid_baseline_total[$__rate_interval]))",
"hide": false,
"instant": false,
"legendFormat": "baseline / {{reason}}",
"range": true,
"refId": "B"
}
],
"title": "Auto Repartition Gate Stops",
@@ -241,14 +241,20 @@ ORDER BY data_size DESC;` | `piechart` | Distribution of leader regions and data
| Title | Query | Type | Description | Datasource | Unit | Legend Format |
| --- | --- | --- | --- | --- | --- | --- |
| Region Balancer Actions | `sum by (result) (
changes(greptime_region_balancer_actions_total[$__rate_interval])
increase(greptime_region_balancer_actions_total[$__rate_interval])
)` | `timeseries` | Region balancer action count | `prometheus` | `short` | `{{result}}` |
| Region Balancer Gate Stops | `sum by (gate, reason) (changes(greptime_region_balancer_gate_stop_total[$__rate_interval]))` | `timeseries` | Region balancer gate stop count by gate and reason | `prometheus` | `short` | `{{gate}} / {{reason}}` |
| Region Balancer Gate Stops | `sum by (gate, reason) (increase(greptime_region_balancer_gate_stop_total[$__rate_interval]))` | `timeseries` | Region balancer gate stop count by gate and reason | `prometheus` | `short` | `{{gate}} / {{reason}}` |
| Region Balancer Datanodes | `sum by (state) (greptime_region_balancer_datanodes)` | `stat` | Region balancer datanode count by state | `prometheus` | `short` | `{{state}}` |
| Region Balancer Regions | `sum by (state) (greptime_region_balancer_regions)` | `stat` | Region balancer region count by state | `prometheus` | `short` | `{{state}}` |
| Region Balancer Datanode Stability | `sum by (state) (greptime_region_balancer_datanode_stability)` | `stat` | Region balancer datanode stability statistics by state | `prometheus` | `binBps` | `{{state}}` |
| Auto Repartition Actions | `sum by (result) (changes(greptime_auto_repartition_actions_total[$__rate_interval]))` | `timeseries` | Auto repartition action count by result | `prometheus` | `short` | `{{result}}` |
| Auto Repartition Gate Stops | `sum by (gate, reason) (changes(greptime_auto_repartition_gate_stop_total[$__rate_interval]))` | `timeseries` | Auto repartition gate stop count by gate and reason | `prometheus` | `short` | `{{gate}} / {{reason}}` |
| Auto Repartition Actions | `sum by (result) (increase(greptime_auto_repartition_actions_total[$__rate_interval]))` | `timeseries` | Auto repartition action count by result | `prometheus` | `short` | `{{result}}` |
| Auto Repartition Gate Stops | `sum by (gate, reason) (
increase(greptime_auto_repartition_gate_stop_total{reason!="invalid_baseline"}[$__rate_interval])
or
(increase(greptime_auto_repartition_gate_stop_total{reason="invalid_baseline"}[$__rate_interval])
unless ignoring (gate, reason)
increase(greptime_auto_repartition_invalid_baseline_total[$__rate_interval]))
)`<br/>`sum by (reason) (increase(greptime_auto_repartition_invalid_baseline_total[$__rate_interval]))` | `timeseries` | Repartition gate stop increments. Baseline failures show detailed reasons when available; otherwise the aggregate invalid_baseline series is retained. Fallback is matched per source before aggregation to avoid double counting across mixed versions. | `prometheus` | `short` | `{{gate}} / {{reason}}` |
| Auto Repartition Sampling P99 | `histogram_quantile(0.99, sum by (le, stage) (rate(greptime_auto_repartition_sampling_elapsed_bucket[$__rate_interval])))` | `timeseries` | Auto repartition sampling elapsed time by stage | `prometheus` | `s` | `{{stage}}` |
| Auto Repartition Executor P99 | `histogram_quantile(0.99, sum by (le, stage) (rate(greptime_auto_repartition_executor_elapsed_bucket[$__rate_interval])))` | `timeseries` | Auto repartition executor elapsed time by stage | `prometheus` | `s` | `{{stage}}` |
# Object Store
@@ -1904,7 +1904,7 @@ groups:
queries:
- expr: |-
sum by (result) (
changes(greptime_region_balancer_actions_total[$__rate_interval])
increase(greptime_region_balancer_actions_total[$__rate_interval])
)
datasource:
type: prometheus
@@ -1915,7 +1915,7 @@ groups:
description: Region balancer gate stop count by gate and reason
unit: short
queries:
- expr: sum by (gate, reason) (changes(greptime_region_balancer_gate_stop_total[$__rate_interval]))
- expr: sum by (gate, reason) (increase(greptime_region_balancer_gate_stop_total[$__rate_interval]))
datasource:
type: prometheus
uid: ${metrics}
@@ -1955,21 +1955,33 @@ groups:
description: Auto repartition action count by result
unit: short
queries:
- expr: sum by (result) (changes(greptime_auto_repartition_actions_total[$__rate_interval]))
- expr: sum by (result) (increase(greptime_auto_repartition_actions_total[$__rate_interval]))
datasource:
type: prometheus
uid: ${metrics}
legendFormat: '{{result}}'
- title: Auto Repartition Gate Stops
type: timeseries
description: Auto repartition gate stop count by gate and reason
description: Repartition gate stop increments. Baseline failures show detailed reasons when available; otherwise the aggregate invalid_baseline series is retained. Fallback is matched per source before aggregation to avoid double counting across mixed versions.
unit: short
queries:
- expr: sum by (gate, reason) (changes(greptime_auto_repartition_gate_stop_total[$__rate_interval]))
- expr: |-
sum by (gate, reason) (
increase(greptime_auto_repartition_gate_stop_total{reason!="invalid_baseline"}[$__rate_interval])
or
(increase(greptime_auto_repartition_gate_stop_total{reason="invalid_baseline"}[$__rate_interval])
unless ignoring (gate, reason)
increase(greptime_auto_repartition_invalid_baseline_total[$__rate_interval]))
)
datasource:
type: prometheus
uid: ${metrics}
legendFormat: '{{gate}} / {{reason}}'
- expr: sum by (reason) (increase(greptime_auto_repartition_invalid_baseline_total[$__rate_interval]))
datasource:
type: prometheus
uid: ${metrics}
legendFormat: baseline / {{reason}}
- title: Auto Repartition Sampling P99
type: timeseries
description: Auto repartition sampling elapsed time by stage
+7
View File
@@ -15,6 +15,7 @@ headerPath = "licenses/enterprise-header.txt"
# with the "# enterprise" block in `licenserc.toml`'s `excludes` — both are
# enforced by `make check-enterprise-license`.
includes = [
"src/datatypes/src/schema/sketch.rs",
"src/common/meta/src/rpc/ddl/trigger.rs",
"src/operator/src/expr_helper/trigger.rs",
"src/sql/src/statements/alter/trigger.rs",
@@ -25,6 +26,12 @@ includes = [
"src/sql/src/parsers/create_parser/trigger.rs",
"src/sql/src/parsers/show_parser/trigger.rs",
"src/mito2/src/extension.rs",
"src/mito2/src/compaction/multi_region.rs",
"src/mito2/src/compaction/multi_region/source.rs",
"src/mito2/src/compaction/multi_region/memory.rs",
"src/mito2/src/compaction/multi_region/worker.rs",
"src/mito2/src/compaction/multi_region/writer.rs",
"src/mito2/src/compaction/multi_region/tests.rs",
"src/common/function/src/admin/purge_table.rs",
"src/catalog/src/system_schema/information_schema/recycle_bin.rs",
"src/common/meta/src/ddl/purge_dropped_table.rs",
+7
View File
@@ -31,6 +31,7 @@ excludes = [
# Keep this list in sync with that file's `includes`; enforced by
# `make check-enterprise-license`.
# enterprise:start
"src/datatypes/src/schema/sketch.rs",
"src/common/meta/src/rpc/ddl/trigger.rs",
"src/operator/src/expr_helper/trigger.rs",
"src/sql/src/statements/alter/trigger.rs",
@@ -41,6 +42,12 @@ excludes = [
"src/sql/src/parsers/create_parser/trigger.rs",
"src/sql/src/parsers/show_parser/trigger.rs",
"src/mito2/src/extension.rs",
"src/mito2/src/compaction/multi_region.rs",
"src/mito2/src/compaction/multi_region/source.rs",
"src/mito2/src/compaction/multi_region/memory.rs",
"src/mito2/src/compaction/multi_region/worker.rs",
"src/mito2/src/compaction/multi_region/writer.rs",
"src/mito2/src/compaction/multi_region/tests.rs",
"src/common/function/src/admin/purge_table.rs",
"src/catalog/src/system_schema/information_schema/recycle_bin.rs",
"src/common/meta/src/ddl/purge_dropped_table.rs",
+66 -1
View File
@@ -280,6 +280,52 @@ pub fn as_skipping_index_type(skipping_index_type: PbSkippingIndexType) -> Skipp
}
}
/// Converts fulltext options for a JSON2 type hint to the wire representation.
pub fn json_fulltext_options_to_proto(
options: FulltextOptions,
) -> crate::v1::JsonFulltextIndexOptions {
crate::v1::JsonFulltextIndexOptions {
analyzer: match options.analyzer {
FulltextAnalyzer::English => Analyzer::English.into(),
FulltextAnalyzer::Chinese => Analyzer::Chinese.into(),
},
case_sensitive: options.case_sensitive,
backend: match options.backend {
FulltextBackend::Bloom => PbFulltextBackend::Bloom.into(),
FulltextBackend::Tantivy => PbFulltextBackend::Tantivy.into(),
},
granularity: options.granularity,
false_positive_rate: options.false_positive_rate(),
}
}
/// Validates fulltext options received for a JSON2 type hint.
/// The presence of these options enables the fulltext index.
pub fn json_fulltext_options_from_proto(
options: crate::v1::JsonFulltextIndexOptions,
) -> datatypes::error::Result<FulltextOptions> {
let analyzer = Analyzer::try_from(options.analyzer).map_err(|_| {
datatypes::error::InvalidFulltextOptionSnafu {
msg: format!("Unknown fulltext analyzer: {}", options.analyzer),
}
.build()
})?;
let backend = PbFulltextBackend::try_from(options.backend).map_err(|_| {
datatypes::error::InvalidFulltextOptionSnafu {
msg: format!("Unknown fulltext backend: {}", options.backend),
}
.build()
})?;
FulltextOptions::new(
true,
as_fulltext_option_analyzer(analyzer),
options.case_sensitive,
as_fulltext_option_backend(backend),
options.granularity,
options.false_positive_rate,
)
}
/// Validates skipping options received for a JSON2 type hint.
pub fn json_skipping_options_from_proto(
options: crate::v1::JsonSkippingIndexOptions,
@@ -299,7 +345,6 @@ pub fn json_skipping_options_from_proto(
#[cfg(test)]
mod tests {
use common_base::readable_size::ReadableSize;
use datatypes::data_type::ConcreteDataType;
use datatypes::schema::{CompressionOptions, FulltextAnalyzer, FulltextBackend};
@@ -307,6 +352,26 @@ mod tests {
use super::*;
use crate::v1::ColumnDataType;
#[test]
fn json_fulltext_options_roundtrip() {
for backend in [FulltextBackend::Bloom, FulltextBackend::Tantivy] {
let options =
FulltextOptions::new(true, FulltextAnalyzer::Chinese, true, backend, 8, 0.05)
.unwrap();
let wire = json_fulltext_options_to_proto(options.clone());
assert_eq!(options, json_fulltext_options_from_proto(wire).unwrap());
let mut invalid = wire;
invalid.backend = 99;
assert!(json_fulltext_options_from_proto(invalid).is_err());
let mut invalid = wire;
invalid.analyzer = 99;
assert!(json_fulltext_options_from_proto(invalid).is_err());
let mut invalid = wire;
invalid.granularity = 0;
assert!(json_fulltext_options_from_proto(invalid).is_err());
}
}
#[test]
fn test_try_as_column_schema() {
let column_def = ColumnDef {
+390 -33
View File
@@ -25,11 +25,15 @@ use common_meta::rpc::procedure;
use common_procedure::{ProcedureInfo, ProcedureState};
use common_query::request::QueryRequest;
use common_recordbatch::adapter::{AsyncRecordBatchStreamAdapter, DfRecordBatchStreamAdapter};
use common_recordbatch::filter::MetadataFilter;
use common_recordbatch::util::{ChainedRecordBatchStream, LimitedRecordBatchStream};
use common_recordbatch::{DfSendableRecordBatchStream, SendableRecordBatchStream};
use datafusion::common::Result;
use common_recordbatch::{
DfSendableRecordBatchStream, EmptyRecordBatchStream, SendableRecordBatchStream,
};
use datafusion::common::tree_node::TreeNodeRecursion;
use datafusion::common::{Result, ScalarValue};
use datafusion::execution::TaskContext;
use datafusion::logical_expr::LogicalPlan;
use datafusion::physical_expr::{EquivalenceProperties, Partitioning, PhysicalExpr};
use datafusion::physical_plan::execution_plan::{Boundedness, EmissionType};
use datafusion::physical_plan::{DisplayAs, DisplayFormatType, ExecutionPlan, PlanProperties};
@@ -38,10 +42,13 @@ use datatypes::schema::SchemaRef;
use futures_util::future::try_join_all;
use meta_client::MetaClientRef;
use snafu::ResultExt;
use store_api::compaction_task;
use store_api::storage::RegionId;
use crate::error;
use crate::information_schema::{DatanodeInspectRequest, InformationExtension};
use crate::information_schema::{
DatanodeInspectKind, DatanodeInspectRequest, InformationExtension,
};
pub struct DistributedInformationExtension {
meta_client: MetaClientRef,
@@ -60,18 +67,53 @@ impl DistributedInformationExtension {
meta_client: MetaClientRef,
datanode_manager: DatanodeManagerRef,
request: DatanodeInspectRequest,
) -> std::result::Result<SendableRecordBatchStream, crate::error::Error> {
) -> crate::error::Result<SendableRecordBatchStream> {
let nodes = meta_client
.list_nodes(Some(Role::Datanode))
.await
.map_err(BoxedError::new)
.context(crate::error::ListNodesSnafu)?;
Self::inspect_nodes(datanode_manager, request, nodes).await
}
/// Executes inspection against discovered nodes after applying safe node pruning.
async fn inspect_nodes(
datanode_manager: DatanodeManagerRef,
request: DatanodeInspectRequest,
nodes: Vec<NodeInfo>,
) -> crate::error::Result<SendableRecordBatchStream> {
let nodes = prune_compaction_nodes(&request, nodes);
let limit = request.scan.limit;
let plan = request
.build_plan()
.context(crate::error::DatafusionSnafu)?;
let stream = Self::inspect_query_nodes(datanode_manager, plan, nodes).await?;
match limit {
Some(limit) => Ok(Box::pin(LimitedRecordBatchStream::new(stream, limit))),
None => Ok(stream),
}
}
async fn inspect_query_stream(
meta_client: MetaClientRef,
datanode_manager: DatanodeManagerRef,
plan: LogicalPlan,
) -> crate::error::Result<SendableRecordBatchStream> {
let nodes = meta_client
.list_nodes(Some(Role::Datanode))
.await
.map_err(BoxedError::new)
.context(crate::error::ListNodesSnafu)?;
Self::inspect_query_nodes(datanode_manager, plan, nodes).await
}
/// Shares query dispatch and empty-stream schema handling for scans and query plans.
async fn inspect_query_nodes(
datanode_manager: DatanodeManagerRef,
plan: LogicalPlan,
nodes: Vec<NodeInfo>,
) -> crate::error::Result<SendableRecordBatchStream> {
let schema = inspection_query_schema(&plan)?;
let streams = try_join_all(nodes.into_iter().map(|node| {
let datanode_manager = datanode_manager.clone();
let plan = plan.clone();
@@ -91,20 +133,55 @@ impl DistributedInformationExtension {
}))
.await?;
let chained =
ChainedRecordBatchStream::new(streams).context(crate::error::CreateRecordBatchSnafu)?;
match limit {
Some(limit) => Ok(Box::pin(LimitedRecordBatchStream::new(
Box::pin(chained),
limit,
))),
None => Ok(Box::pin(chained)),
}
chain_inspection_streams(streams, schema)
}
}
fn inspection_query_schema(plan: &LogicalPlan) -> crate::error::Result<SchemaRef> {
datatypes::schema::Schema::try_from(plan.schema().clone())
.map(Arc::new)
.map_err(|error| datafusion::common::DataFusionError::External(Box::new(error)))
.context(crate::error::DatafusionSnafu)
}
fn chain_inspection_streams(
streams: Vec<SendableRecordBatchStream>,
schema: SchemaRef,
) -> crate::error::Result<SendableRecordBatchStream> {
if streams.is_empty() {
return Ok(Box::pin(EmptyRecordBatchStream::new(schema)));
}
Ok(Box::pin(
ChainedRecordBatchStream::new(streams).context(crate::error::CreateRecordBatchSnafu)?,
))
}
#[derive(Debug, Clone)]
enum InspectPlan {
Scan(DatanodeInspectRequest),
Query(LogicalPlan),
}
/// Prunes reporting nodes only for live compaction inspection. Region routes cannot
/// locate tasks left on a former owner, so only known node IDs can exclude nodes.
fn prune_compaction_nodes(request: &DatanodeInspectRequest, nodes: Vec<NodeInfo>) -> Vec<NodeInfo> {
if request.kind != DatanodeInspectKind::CompactionTasks {
return nodes;
}
let filter = MetadataFilter::new(&request.scan.filters);
nodes
.into_iter()
.filter(|node| {
filter.matches(|name| {
(name == compaction_task::NODE_ID)
.then_some(ScalarValue::UInt64(Some(node.peer.id)))
})
})
.collect()
}
struct DistributedInspectExec {
request: DatanodeInspectRequest,
plan: InspectPlan,
meta_client: MetaClientRef,
datanode_manager: DatanodeManagerRef,
schema: SchemaRef,
@@ -115,7 +192,7 @@ struct DistributedInspectExec {
impl std::fmt::Debug for DistributedInspectExec {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("DistributedInspectExec")
.field("request", &self.request)
.field("plan", &self.plan)
.field("schema", &self.schema)
.finish_non_exhaustive()
}
@@ -127,6 +204,20 @@ impl DistributedInspectExec {
schema: SchemaRef,
meta_client: MetaClientRef,
datanode_manager: DatanodeManagerRef,
) -> Self {
Self::with_plan(
InspectPlan::Scan(request),
schema,
meta_client,
datanode_manager,
)
}
fn with_plan(
plan: InspectPlan,
schema: SchemaRef,
meta_client: MetaClientRef,
datanode_manager: DatanodeManagerRef,
) -> Self {
let arrow_schema = schema.arrow_schema().clone();
let properties = Arc::new(PlanProperties::new(
@@ -136,7 +227,7 @@ impl DistributedInspectExec {
Boundedness::Bounded,
));
Self {
request,
plan,
meta_client,
datanode_manager,
schema,
@@ -148,11 +239,19 @@ impl DistributedInspectExec {
impl DisplayAs for DistributedInspectExec {
fn fmt_as(&self, _t: DisplayFormatType, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"DistributedInspectExec: kind={:?}, scan={}, schema={:?}",
self.request.kind, self.request.scan, self.arrow_schema
)
match &self.plan {
InspectPlan::Scan(request) => write!(
f,
"DistributedInspectExec: kind={:?}, scan={}, schema={:?}",
request.kind, request.scan, self.arrow_schema
),
InspectPlan::Query(plan) => write!(
f,
"DistributedInspectExec: query={}, schema={:?}",
plan.display_indent(),
self.arrow_schema
),
}
}
}
@@ -207,15 +306,27 @@ impl ExecutionPlan for DistributedInspectExec {
let meta_client = self.meta_client.clone();
let datanode_manager = self.datanode_manager.clone();
let request = self.request.clone();
let plan = self.plan.clone();
let schema = self.schema.clone();
let future = async move {
DistributedInformationExtension::inspect_datanode_stream(
meta_client,
datanode_manager,
request,
)
.await
match plan {
InspectPlan::Scan(request) => {
DistributedInformationExtension::inspect_datanode_stream(
meta_client,
datanode_manager,
request,
)
.await
}
InspectPlan::Query(plan) => {
DistributedInformationExtension::inspect_query_stream(
meta_client,
datanode_manager,
plan,
)
.await
}
}
.map_err(BoxedError::new)
.context(common_recordbatch::error::ExternalSnafu)
};
@@ -299,6 +410,23 @@ impl InformationExtension for DistributedInformationExtension {
.await
}
fn supports_inspect_query_plan(&self) -> bool {
true
}
fn inspect_datanode_query_plan(
&self,
plan: LogicalPlan,
) -> crate::error::Result<Option<Arc<dyn ExecutionPlan>>> {
let schema = inspection_query_schema(&plan)?;
Ok(Some(Arc::new(DistributedInspectExec::with_plan(
InspectPlan::Query(plan),
schema,
self.meta_client.clone(),
self.datanode_manager.clone(),
))))
}
fn inspect_datanode_plan(
&self,
request: DatanodeInspectRequest,
@@ -318,21 +446,198 @@ mod tests {
use common_meta::node_manager::{DatanodeManager, DatanodeRef};
use common_meta::peer::Peer;
use datafusion::common::tree_node::TreeNode;
use datafusion::logical_expr::LogicalPlan;
use datafusion::datasource::empty::EmptyTable;
use datafusion::logical_expr::{Expr, LogicalPlan};
use datafusion::physical_plan::sorts::sort::SortExec;
use datafusion::prelude::SessionContext;
use datatypes::arrow::datatypes::DataType;
use meta_client::client::MetaClientBuilder;
use store_api::sst_entry::ManifestSstEntry;
use store_api::storage::ScanRequest;
use store_api::compaction_task::CompactionTaskEntry;
use super::*;
use crate::information_schema::DatanodeInspectKind;
struct UnusedDatanodeManager;
#[async_trait::async_trait]
impl DatanodeManager for UnusedDatanodeManager {
async fn datanode(&self, _node: &Peer) -> DatanodeRef {
panic!("plan tests must not contact datanodes")
panic!("this test must not contact datanodes")
}
}
fn inspection_nodes() -> Vec<NodeInfo> {
[1, 2, 3]
.into_iter()
.map(|id| NodeInfo {
peer: Peer::new(id, format!("datanode-{id}:3001")),
last_activity_ts: 0,
status: common_meta::cluster::NodeStatus::Standalone,
version: String::new(),
git_commit: String::new(),
start_time_ms: 0,
total_cpu_millicores: 0,
total_memory_bytes: 0,
cpu_usage_millicores: 0,
memory_usage_bytes: 0,
hostname: String::new(),
env_vars: Default::default(),
schedulable: None,
})
.collect()
}
/// Uses the default optimizer to produce the predicates seen by inspection scans.
async fn compaction_sql_filters(predicate: Option<&str>) -> Vec<Expr> {
let ctx = SessionContext::new();
ctx.register_table(
"compaction_tasks",
Arc::new(EmptyTable::new(
CompactionTaskEntry::schema().arrow_schema().clone(),
)),
)
.unwrap();
let mut sql = "SELECT * FROM compaction_tasks".to_string();
if let Some(predicate) = predicate {
sql.push_str(" WHERE ");
sql.push_str(predicate);
}
let plan = ctx.sql(&sql).await.unwrap().into_optimized_plan().unwrap();
let mut filters = Vec::new();
plan.apply(|plan| {
match plan {
LogicalPlan::Filter(filter) => filters.push(filter.predicate.clone()),
LogicalPlan::TableScan(scan) => filters.extend(scan.filters.iter().cloned()),
_ => {}
}
Ok(TreeNodeRecursion::Continue)
})
.unwrap();
filters
}
#[tokio::test]
async fn test_compaction_node_pruning() {
for (predicate, expected, expect_cast) in [
(Some("node_id = 2"), vec![2], false),
(Some("node_id != 2"), vec![1, 3], false),
(Some("node_id > 2"), vec![3], false),
(Some("node_id >= 2"), vec![2, 3], false),
(Some("node_id < 2"), vec![1], false),
(Some("node_id <= 2"), vec![1, 2], false),
(Some("2 = node_id"), vec![2], false),
(Some("2 < node_id"), vec![3], false),
(None, vec![1, 2, 3], false),
(Some("state = 'running'"), vec![1, 2, 3], false),
(Some("node_id = 2 OR table_id = 42"), vec![1, 2, 3], false),
(Some("node_id = 2 AND state = 'running'"), vec![2], false),
] {
let filters = compaction_sql_filters(predicate).await;
let mut has_cast = false;
for filter in &filters {
filter
.apply(|expr| {
has_cast |= matches!(expr, Expr::Cast(cast) if cast.field.data_type() == &DataType::Decimal128(20, 0)
&& matches!(cast.expr.as_ref(), Expr::Column(_)));
Ok(TreeNodeRecursion::Continue)
})
.unwrap();
}
assert_eq!(has_cast, expect_cast, "optimized predicate: {predicate:?}");
let request = DatanodeInspectRequest {
kind: DatanodeInspectKind::CompactionTasks,
scan: ScanRequest {
filters,
..Default::default()
},
};
let actual: Vec<_> = prune_compaction_nodes(&request, inspection_nodes())
.into_iter()
.map(|node| node.peer.id)
.collect();
assert_eq!(
actual, expected,
"{predicate:?}: {:?}",
request.scan.filters
);
}
let filters = compaction_sql_filters(Some("node_id = 99")).await;
for kind in [
DatanodeInspectKind::SstManifest,
DatanodeInspectKind::SstStorage,
DatanodeInspectKind::SstIndexMeta,
DatanodeInspectKind::RegionInfo,
] {
let request = DatanodeInspectRequest {
kind,
scan: ScanRequest {
filters: filters.clone(),
..Default::default()
},
};
let actual: Vec<_> = prune_compaction_nodes(&request, inspection_nodes())
.into_iter()
.map(|node| node.peer.id)
.collect();
assert_eq!(actual, vec![1, 2, 3]);
}
}
#[tokio::test]
async fn test_compaction_empty_nodes_preserve_projected_schema() {
let filters = compaction_sql_filters(Some("node_id = 99")).await;
for nodes in [vec![], inspection_nodes()] {
for (projection, expected) in [
(
vec![3, 0, 2],
vec![
("node_id", DataType::UInt64, true),
("task_id", DataType::Utf8, false),
("table_id", DataType::UInt32, false),
],
),
(vec![], vec![]),
] {
let request = DatanodeInspectRequest {
kind: DatanodeInspectKind::CompactionTasks,
scan: ScanRequest {
projection: Some(projection),
filters: filters.clone(),
..Default::default()
},
};
// Panics if the production dispatch path contacts any excluded node.
let stream = DistributedInformationExtension::inspect_nodes(
Arc::new(UnusedDatanodeManager),
request,
nodes.clone(),
)
.await
.unwrap();
let batches = common_recordbatch::RecordBatches::try_collect(stream)
.await
.unwrap();
assert_eq!(
batches.iter().map(|batch| batch.num_rows()).sum::<usize>(),
0
);
let schema = batches.schema();
let actual: Vec<_> = schema
.arrow_schema()
.fields()
.iter()
.map(|field| {
(
field.name().as_str(),
field.data_type().clone(),
field.is_nullable(),
)
})
.collect();
assert_eq!(actual, expected);
}
}
}
@@ -385,6 +690,55 @@ mod tests {
}
}
#[tokio::test]
async fn test_inspection_query_plan_is_lazy_and_preserves_schema() {
let ctx = datafusion::prelude::SessionContext::new();
let remote = ctx
.sql("SELECT count(*), sum(value) FROM (VALUES (1), (2)) AS t(value)")
.await
.unwrap()
.into_unoptimized_plan();
let extension = DistributedInformationExtension::new(
Arc::new(MetaClientBuilder::new(0, api::v1::meta::Role::Frontend).build()),
Arc::new(UnusedDatanodeManager),
);
assert!(extension.supports_inspect_query_plan());
let exec = extension
.inspect_datanode_query_plan(remote.clone())
.unwrap()
.unwrap();
assert_eq!(exec.schema(), remote.schema().inner().clone());
let inspect = exec.downcast_ref::<DistributedInspectExec>().unwrap();
let InspectPlan::Query(plan) = &inspect.plan else {
panic!("expected inspection query")
};
assert_eq!(plan, &remote);
assert!(exec.children().is_empty());
// Creating or dropping an unpolled execution must not contact metadata or datanodes.
for _ in 0..2 {
let stream = exec.execute(0, ctx.task_ctx()).unwrap();
assert_eq!(stream.schema(), exec.schema());
drop(stream);
}
assert!(exec.execute(1, ctx.task_ctx()).is_err());
}
#[tokio::test]
async fn test_empty_inspection_query_stream_keeps_output_schema() {
use futures_util::StreamExt;
let ctx = datafusion::prelude::SessionContext::new();
let remote = ctx
.sql("SELECT count(*), sum(value) FROM (VALUES (1)) AS t(value)")
.await
.unwrap()
.into_unoptimized_plan();
let schema = inspection_query_schema(&remote).unwrap();
let mut stream = chain_inspection_streams(vec![], schema.clone()).unwrap();
assert_eq!(stream.schema(), schema);
assert!(stream.next().await.is_none());
}
#[tokio::test]
async fn test_sql_manifest_sort_stays_on_frontend() {
let ctx = datafusion::prelude::SessionContext::new();
@@ -410,8 +764,11 @@ mod tests {
if let Some(scan) = plan.downcast_ref::<DistributedInspectExec>() {
found_scan = true;
// All matching rows must reach the frontend global sort.
assert_eq!(scan.request.scan.limit, None);
let remote = scan.request.clone().build_plan().unwrap();
let InspectPlan::Scan(request) = &scan.plan else {
panic!("expected scan plan")
};
assert_eq!(request.scan.limit, None);
let remote = request.clone().build_plan().unwrap();
remote.apply(|node| {
assert!(!matches!(
node,
@@ -14,6 +14,7 @@
mod cluster_info;
pub mod columns;
mod compaction_tasks;
pub mod flow_statistics;
pub mod flows;
mod information_memory_table;
@@ -58,6 +59,7 @@ use lazy_static::lazy_static;
use paste::paste;
use process_list::InformationSchemaProcessList;
use region_info::InformationSchemaRegionInfo;
use store_api::compaction_task::CompactionTaskEntry;
use store_api::metric_engine_consts::{
MEMTABLE_PARTITION_TREE_PRIMARY_KEY_ENCODING, PRIMARY_KEY_ENCODING,
};
@@ -74,6 +76,7 @@ use crate::CatalogManager;
use crate::error::Error;
use crate::process_manager::ProcessManagerRef;
use crate::system_schema::information_schema::cluster_info::InformationSchemaClusterInfo;
use crate::system_schema::information_schema::compaction_tasks::InformationSchemaCompactionTasks;
use crate::system_schema::information_schema::flow_statistics::InformationSchemaFlowStatistics;
use crate::system_schema::information_schema::flows::InformationSchemaFlows;
use crate::system_schema::information_schema::information_memory_table::get_schema_columns;
@@ -312,6 +315,9 @@ impl InformationSchemaProvider {
self.catalog_manager.clone(),
),
) as _),
COMPACTION_TASKS => Some(Arc::new(InformationSchemaCompactionTasks::new(
self.catalog_manager.clone(),
)) as _),
REGION_INFO => Some(Arc::new(InformationSchemaRegionInfo::new(
self.catalog_manager.clone(),
)) as _),
@@ -382,6 +388,7 @@ impl InformationSchemaProvider {
CLUSTER_INFO,
PROCEDURE_INFO,
REGION_STATISTICS,
COMPACTION_TASKS,
REGION_INFO,
SSTS_MANIFEST,
SSTS_STORAGE,
@@ -466,6 +473,21 @@ pub trait InformationExtension {
request: DatanodeInspectRequest,
) -> std::result::Result<SendableRecordBatchStream, Self::Error>;
/// Whether this extension can execute an inspection query on every datanode.
fn supports_inspect_query_plan(&self) -> bool {
false
}
/// Builds a plan that executes an inspection query independently on each datanode.
/// The caller supplies a plan over reserved inspection tables and retains any
/// required global aggregation. The returned schema is the query output schema.
fn inspect_datanode_query_plan(
&self,
_plan: LogicalPlan,
) -> std::result::Result<Option<Arc<dyn ExecutionPlan>>, Self::Error> {
Ok(None)
}
/// Builds a physical plan for datanode inspect if the extension can expose
/// the distributed fan-in semantics to DataFusion.
fn inspect_datanode_plan(
@@ -491,6 +513,8 @@ pub struct DatanodeInspectRequest {
/// The kind of the datanode inspect request.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DatanodeInspectKind {
/// Live compaction cycles.
CompactionTasks,
/// List SST entries recorded in manifest
SstManifest,
/// List SST entries discovered in storage layer
@@ -505,6 +529,7 @@ impl DatanodeInspectRequest {
/// Builds a logical plan for the datanode inspect request.
pub fn build_plan(self) -> std::result::Result<LogicalPlan, DataFusionError> {
match self.kind {
DatanodeInspectKind::CompactionTasks => CompactionTaskEntry::build_plan(self.scan),
DatanodeInspectKind::SstManifest => ManifestSstEntry::build_plan(self.scan),
DatanodeInspectKind::SstStorage => StorageSstEntry::build_plan(self.scan),
DatanodeInspectKind::SstIndexMeta => PuffinIndexMetaEntry::build_plan(self.scan),
@@ -689,11 +714,11 @@ mod tests {
// An extension replacing a built-in supplies the replacement table's scope.
let provider = provider.with_extra_table_factories(factories.clone());
let expected_count =
44 + usize::from(with_process_manager) + usize::from(cfg!(feature = "enterprise"))
45 + usize::from(with_process_manager) + usize::from(cfg!(feature = "enterprise"))
- if catalog == DEFAULT_CATALOG_NAME {
0
} else {
8
9
};
assert_eq!(provider.tables().len(), expected_count);
for (name, table) in provider.tables() {
@@ -809,6 +834,29 @@ mod tests {
);
}
#[test]
fn test_compaction_tasks_build_plan() {
let request = DatanodeInspectRequest {
kind: DatanodeInspectKind::CompactionTasks,
scan: ScanRequest {
projection: Some(vec![0]),
filters: vec![
datafusion::logical_expr::col("state")
.eq(datafusion::logical_expr::lit("running")),
],
limit: Some(1),
..Default::default()
},
};
let plan = request.build_plan().unwrap();
assert_eq!(plan.schema().fields().len(), 1);
assert!(
plan.display_indent()
.to_string()
.contains("__compaction_tasks")
);
}
#[test]
fn test_datanode_inspect_region_info_build_plan() {
let plan = DatanodeInspectRequest {
@@ -0,0 +1,97 @@
// 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.
use std::sync::{Arc, Weak};
use common_catalog::consts::INFORMATION_SCHEMA_COMPACTION_TASKS_TABLE_ID;
use common_error::ext::BoxedError;
use common_recordbatch::SendableRecordBatchStream;
use common_recordbatch::adapter::AsyncRecordBatchStreamAdapter;
use datafusion::physical_plan::ExecutionPlan;
use datatypes::schema::SchemaRef;
use snafu::ResultExt;
use store_api::compaction_task::CompactionTaskEntry;
use store_api::storage::{ScanRequest, TableId};
use crate::CatalogManager;
use crate::error::Result;
use crate::information_schema::{
COMPACTION_TASKS, DatanodeInspectKind, InformationSchemaTableScope, InformationTable,
};
use crate::system_schema::SystemTable;
use crate::system_schema::utils;
/// Information schema table for live compaction tasks.
pub struct InformationSchemaCompactionTasks {
schema: SchemaRef,
catalog_manager: Weak<dyn CatalogManager>,
}
impl InformationSchemaCompactionTasks {
pub(crate) fn new(catalog_manager: Weak<dyn CatalogManager>) -> Self {
Self {
schema: CompactionTaskEntry::schema(),
catalog_manager,
}
}
}
impl InformationTable for InformationSchemaCompactionTasks {
fn scope(&self) -> InformationSchemaTableScope {
InformationSchemaTableScope::Global
}
}
impl SystemTable for InformationSchemaCompactionTasks {
fn table_id(&self) -> TableId {
INFORMATION_SCHEMA_COMPACTION_TASKS_TABLE_ID
}
fn table_name(&self) -> &'static str {
COMPACTION_TASKS
}
fn schema(&self) -> SchemaRef {
self.schema.clone()
}
fn to_stream(&self, request: ScanRequest) -> Result<SendableRecordBatchStream> {
let schema = utils::projected_schema(&self.schema, &request)?;
let info_ext = utils::information_extension(&self.catalog_manager)?;
let req =
utils::inspect_request(DatanodeInspectKind::CompactionTasks, &self.schema, request)?;
let future = async move {
info_ext
.inspect_datanode(req)
.await
.map_err(BoxedError::new)
.context(common_recordbatch::error::ExternalSnafu)
};
Ok(Box::pin(AsyncRecordBatchStreamAdapter::new(
schema,
Box::pin(future),
)))
}
fn scan_plan(&self, request: ScanRequest) -> Result<Option<Arc<dyn ExecutionPlan>>> {
utils::inspect_plan(
&self.catalog_manager,
DatanodeInspectKind::CompactionTasks,
&self.schema,
request,
)
}
}
@@ -75,7 +75,12 @@ const INIT_CAPACITY: usize = 42;
/// - `query_scanned_bytes`: The total bytes scanned by queries since region opened.
/// - `memtable_size`: The memtable size in bytes.
/// - `disk_size`: The approximate disk size in bytes.
/// - `manifest_size`: The manifest size in bytes.
/// - `manifest_size`: Stored bytes of the latest observed checkpoint and subsequent
/// deltas (compressed when enabled), excluding staging and `_last_checkpoint`.
/// Older files retained on disk, including failed deletions, are not counted.
/// Followers update this estimate on sync; metadata read failures can leave it stale.
/// Promotion does not refresh it, so an incomplete estimate can persist without
/// further syncs or checkpoints.
/// - `sst_size`: The sst data files size in bytes.
/// - `index_size`: The sst index files size in bytes.
/// - `engine`: The engine type.
@@ -28,38 +28,14 @@ use store_api::sst_entry::{ManifestSstEntry, PuffinIndexMetaEntry, StorageSstEnt
use store_api::storage::{ScanRequest, TableId};
use crate::CatalogManager;
use crate::error::{ProjectSchemaSnafu, Result};
use crate::error::Result;
use crate::information_schema::{
DatanodeInspectKind, DatanodeInspectRequest, InformationSchemaTableScope, InformationTable,
SSTS_INDEX_META, SSTS_MANIFEST, SSTS_STORAGE,
DatanodeInspectKind, InformationSchemaTableScope, InformationTable, SSTS_INDEX_META,
SSTS_MANIFEST, SSTS_STORAGE,
};
use crate::system_schema::SystemTable;
use crate::system_schema::utils;
fn projected_schema(schema: &SchemaRef, request: &ScanRequest) -> Result<SchemaRef> {
if let Some(p) = request.projection.as_deref() {
Ok(Arc::new(schema.try_project(p).context(ProjectSchemaSnafu)?))
} else {
Ok(schema.clone())
}
}
fn inspect_plan(
catalog_manager: &Weak<dyn CatalogManager>,
kind: DatanodeInspectKind,
schema: &SchemaRef,
request: ScanRequest,
) -> Result<Option<Arc<dyn ExecutionPlan>>> {
let projected_schema = projected_schema(schema, &request)?;
let info_ext = utils::information_extension(catalog_manager)?;
let req = DatanodeInspectRequest {
kind,
scan: request,
};
info_ext.inspect_datanode_plan(req, projected_schema)
}
/// Information schema table for sst manifest.
pub struct InformationSchemaSstsManifest {
schema: SchemaRef,
@@ -95,12 +71,9 @@ impl SystemTable for InformationSchemaSstsManifest {
}
fn to_stream(&self, request: ScanRequest) -> Result<SendableRecordBatchStream> {
let schema = projected_schema(&self.schema, &request)?;
let schema = utils::projected_schema(&self.schema, &request)?;
let info_ext = utils::information_extension(&self.catalog_manager)?;
let req = DatanodeInspectRequest {
kind: DatanodeInspectKind::SstManifest,
scan: request,
};
let req = utils::inspect_request(DatanodeInspectKind::SstManifest, &self.schema, request)?;
let future = async move {
info_ext
@@ -116,7 +89,7 @@ impl SystemTable for InformationSchemaSstsManifest {
}
fn scan_plan(&self, request: ScanRequest) -> Result<Option<Arc<dyn ExecutionPlan>>> {
inspect_plan(
utils::inspect_plan(
&self.catalog_manager,
DatanodeInspectKind::SstManifest,
&self.schema,
@@ -160,13 +133,10 @@ impl SystemTable for InformationSchemaSstsStorage {
}
fn to_stream(&self, request: ScanRequest) -> Result<SendableRecordBatchStream> {
let schema = projected_schema(&self.schema, &request)?;
let schema = utils::projected_schema(&self.schema, &request)?;
let info_ext = utils::information_extension(&self.catalog_manager)?;
let req = DatanodeInspectRequest {
kind: DatanodeInspectKind::SstStorage,
scan: request,
};
let req = utils::inspect_request(DatanodeInspectKind::SstStorage, &self.schema, request)?;
let future = async move {
info_ext
@@ -182,7 +152,7 @@ impl SystemTable for InformationSchemaSstsStorage {
}
fn scan_plan(&self, request: ScanRequest) -> Result<Option<Arc<dyn ExecutionPlan>>> {
inspect_plan(
utils::inspect_plan(
&self.catalog_manager,
DatanodeInspectKind::SstStorage,
&self.schema,
@@ -226,13 +196,10 @@ impl SystemTable for InformationSchemaSstsIndexMeta {
}
fn to_stream(&self, request: ScanRequest) -> Result<SendableRecordBatchStream> {
let schema = projected_schema(&self.schema, &request)?;
let schema = utils::projected_schema(&self.schema, &request)?;
let info_ext = utils::information_extension(&self.catalog_manager)?;
let req = DatanodeInspectRequest {
kind: DatanodeInspectKind::SstIndexMeta,
scan: request,
};
let req = utils::inspect_request(DatanodeInspectKind::SstIndexMeta, &self.schema, request)?;
let future = async move {
info_ext
@@ -248,7 +215,7 @@ impl SystemTable for InformationSchemaSstsIndexMeta {
}
fn scan_plan(&self, request: ScanRequest) -> Result<Option<Arc<dyn ExecutionPlan>>> {
inspect_plan(
utils::inspect_plan(
&self.catalog_manager,
DatanodeInspectKind::SstIndexMeta,
&self.schema,
@@ -259,6 +226,7 @@ impl SystemTable for InformationSchemaSstsIndexMeta {
#[cfg(test)]
mod tests {
use crate::information_schema::DatanodeInspectRequest;
use cache::{build_fundamental_cache_registry, with_default_composite_cache_registry};
use common_catalog::consts::{DEFAULT_CATALOG_NAME, INFORMATION_SCHEMA_NAME};
use common_meta::cache::{CacheRegistryBuilder, LayeredCacheRegistryBuilder};
@@ -317,6 +285,63 @@ mod tests {
}
}
#[test]
fn test_inspect_request_keeps_unsafe_filters_on_frontend() {
use datafusion::arrow::datatypes::{DataType, TimeUnit};
use datafusion::logical_expr::expr::Cast;
use datafusion::logical_expr::{Expr, col, lit};
for (kind, schema) in [
(
DatanodeInspectKind::CompactionTasks,
store_api::compaction_task::CompactionTaskEntry::schema(),
),
(DatanodeInspectKind::SstManifest, ManifestSstEntry::schema()),
(DatanodeInspectKind::SstStorage, StorageSstEntry::schema()),
(
DatanodeInspectKind::SstIndexMeta,
PuffinIndexMetaEntry::schema(),
),
] {
let safe = col(&schema.column_schemas()[0].name).is_not_null();
let scan = ScanRequest {
projection: Some(vec![0]),
filters: vec![safe.clone()],
limit: Some(1),
..Default::default()
};
assert_eq!(
utils::inspect_request(kind, &schema, scan.clone()).unwrap(),
DatanodeInspectRequest {
kind,
scan: scan.clone()
}
);
for unsafe_filter in [
Expr::Cast(Cast::new(
Box::new(lit(0_i64)),
DataType::Timestamp(TimeUnit::Nanosecond, Some("+08:00".into())),
))
.is_not_null(),
Expr::Cast(Cast::new(Box::new(lit(1_i64)), DataType::Decimal32(9, 0)))
.is_not_null(),
col("missing_column").is_null(),
] {
let mut input = scan.clone();
input.filters.push(unsafe_filter);
let mut expected = scan.clone();
expected.limit = None;
assert_eq!(
utils::inspect_request(kind, &schema, input).unwrap(),
DatanodeInspectRequest {
kind,
scan: expected
}
);
}
}
}
#[tokio::test]
async fn ssts_manifest_uses_information_extension_scan_plan() {
let backend = Arc::new(MemoryKvBackend::default());
@@ -60,3 +60,6 @@ pub const USER_PRIVILEGES: &str = "user_privileges";
/// MySQL's session list. GreptimeDB reports its own sessions through [`PROCESS_LIST`];
/// this table only exists so MySQL tooling finds the name and column shape it expects.
pub const PROCESSLIST: &str = "processlist";
/// Live compaction tasks.
pub const COMPACTION_TASKS: &str = "compaction_tasks";
+69 -5
View File
@@ -12,18 +12,82 @@
// See the License for the specific language governing permissions and
// limitations under the License.
use std::sync::Weak;
pub mod tables;
use std::sync::{Arc, Weak};
use common_meta::key::TableMetadataManagerRef;
use snafu::OptionExt;
use common_query::logical_plan::is_lossless_substrait_type;
use datafusion::common::DFSchema;
use datafusion::common::tree_node::{TreeNode, TreeNodeRecursion};
use datafusion::logical_expr::ExprSchemable;
use datafusion::physical_plan::ExecutionPlan;
use datatypes::schema::SchemaRef;
use snafu::{OptionExt, ResultExt};
use store_api::storage::ScanRequest;
use crate::CatalogManager;
use crate::error::{GetInformationExtensionSnafu, Result, UpgradeWeakCatalogManagerRefSnafu};
use crate::information_schema::InformationExtensionRef;
use crate::error::{
GetInformationExtensionSnafu, ProjectSchemaSnafu, Result, UpgradeWeakCatalogManagerRefSnafu,
};
use crate::information_schema::{
DatanodeInspectKind, DatanodeInspectRequest, InformationExtensionRef,
};
use crate::kvbackend::KvBackendCatalogManager;
use crate::system_schema::semantic_graph::EntityGraphProviderRef;
pub mod tables;
/// Projects an inspection table schema according to the scan request.
pub(crate) fn projected_schema(schema: &SchemaRef, request: &ScanRequest) -> Result<SchemaRef> {
if let Some(p) = request.projection.as_deref() {
Ok(Arc::new(schema.try_project(p).context(ProjectSchemaSnafu)?))
} else {
Ok(schema.clone())
}
}
/// Builds a datanode inspection plan with the requested output schema.
pub(crate) fn inspect_plan(
catalog_manager: &Weak<dyn CatalogManager>,
kind: DatanodeInspectKind,
schema: &SchemaRef,
request: ScanRequest,
) -> Result<Option<Arc<dyn ExecutionPlan>>> {
let projected_schema = projected_schema(schema, &request)?;
let info_ext = information_extension(catalog_manager)?;
let req = inspect_request(kind, schema, request)?;
info_ext.inspect_datanode_plan(req, projected_schema)
}
/// System table predicates are inexact: the frontend keeps a residual filter. Dropping
/// an unsafe remote filter preserves correctness only if no remote limit truncates it.
pub(crate) fn inspect_request(
kind: DatanodeInspectKind,
schema: &SchemaRef,
mut scan: ScanRequest,
) -> Result<DatanodeInspectRequest> {
let schema =
DFSchema::try_from(schema.arrow_schema().clone()).context(crate::error::DatafusionSnafu)?;
let filter_count = scan.filters.len();
scan.filters.retain(|filter| {
let mut supported = true;
let visited = filter.apply(|expr| {
if !expr
.get_type(&schema)
.is_ok_and(|data_type| is_lossless_substrait_type(&data_type))
{
supported = false;
return Ok(TreeNodeRecursion::Stop);
}
Ok(TreeNodeRecursion::Continue)
});
visited.is_ok() && supported
});
if scan.filters.len() != filter_count {
scan.limit = None;
}
Ok(DatanodeInspectRequest { kind, scan })
}
/// Try to get the entity-graph provider from a `[CatalogManager]` weak reference.
/// Returns `None` when the manager is not the kv-backed one or the provider has
+38
View File
@@ -626,6 +626,44 @@ mod tests {
}
}
#[tokio::test]
async fn test_cancel_compaction_through_handle() {
let server = RegionTestServer::start().await;
let requester = server.create_requester(ChannelConfig::default(), false, false);
let request = RegionRequest {
header: Some(RegionRequestHeader::default()),
body: Some(region_request::Body::CancelCompaction(
api::v1::region::CancelCompactionRequest {
region_id: 42,
task_id: "cycle-id".into(),
},
)),
};
for affected_rows in [0, 1] {
let mut response = build_response(StatusCode::Success);
response.affected_rows = affected_rows;
server
.service
.responses
.lock()
.unwrap()
.push_back(Ok(response));
assert_eq!(
requester
.handle(request.clone())
.await
.unwrap()
.affected_rows,
affected_rows as usize
);
}
let requests = server.service.requests.lock().unwrap();
assert_eq!(requests.len(), 2);
for (actual, _, _) in requests.iter() {
assert_eq!(actual.body, request.body);
}
}
fn build_insert_request() -> RegionRequest {
RegionRequest {
header: Some(RegionRequestHeader {
+2
View File
@@ -128,6 +128,8 @@ pub const INFORMATION_SCHEMA_PLUGINS_TABLE_ID: u32 = 47;
pub const INFORMATION_SCHEMA_USER_PRIVILEGES_TABLE_ID: u32 = 48;
/// id for information_schema.PROCESSLIST (for mysql)
pub const INFORMATION_SCHEMA_PROCESSLIST_TABLE_ID: u32 = 49;
/// Id for information_schema.compaction_tasks.
pub const INFORMATION_SCHEMA_COMPACTION_TASKS_TABLE_ID: u32 = 50;
// ----- End of information_schema tables -----
+10
View File
@@ -16,6 +16,7 @@ use std::fmt::Display;
use std::io;
use std::str::FromStr;
use async_compression::Level;
use async_compression::tokio::bufread::{BzDecoder, GzipDecoder, XzDecoder, ZstdDecoder};
use async_compression::tokio::write;
use bytes::Bytes;
@@ -88,6 +89,15 @@ impl CompressionType {
Self::Uncompressed => "",
}
}
/// Encodes `content` as a gzip stream at level 0, which stores it without compression.
pub async fn encode_gzip_stored(content: &[u8]) -> io::Result<Vec<u8>> {
let mut buffer = Vec::with_capacity(content.len());
let mut encoder = write::GzipEncoder::with_quality(&mut buffer, Level::Precise(0));
encoder.write_all(content).await?;
encoder.shutdown().await?;
Ok(buffer)
}
}
macro_rules! impl_compression_type {
+3
View File
@@ -13,6 +13,7 @@
// limitations under the License.
mod build_index_table;
mod cancel_region_compaction;
mod discard_unflushed_data;
mod flush_compact_region;
mod flush_compact_table;
@@ -35,6 +36,7 @@ use reconcile_database::ReconcileDatabaseFunction;
use reconcile_table::ReconcileTableFunction;
use crate::admin::build_index_table::{BuildIndexFunction, BuildSeriesIndexFunction};
use crate::admin::cancel_region_compaction::CancelRegionCompactionFunction;
use crate::admin::discard_unflushed_data::DiscardUnflushedDataFunction;
use crate::flush_flow::FlushFlowFunction;
use crate::function_registry::FunctionRegistry;
@@ -48,6 +50,7 @@ impl AdminFunction {
registry.register(MigrateRegionFunction::factory());
registry.register(FlushRegionFunction::factory());
registry.register(CompactRegionFunction::factory());
registry.register(CancelRegionCompactionFunction::factory());
registry.register(FlushTableFunction::factory());
registry.register(CompactTableFunction::factory());
registry.register(GcRegionsFunction::factory());
@@ -0,0 +1,210 @@
// 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.
use arrow::datatypes::DataType as ArrowDataType;
use common_macro::admin_fn;
use common_query::error::{
InvalidFuncArgsSnafu, MissingTableMutationHandlerSnafu, Result, UnsupportedInputDataTypeSnafu,
};
use datafusion_expr::Signature;
use datatypes::data_type::DataType;
use datatypes::prelude::{ConcreteDataType, Value, ValueRef};
use session::context::QueryContextRef;
use snafu::ensure;
use store_api::storage::RegionId;
use crate::handlers::TableMutationHandlerRef;
use crate::helper;
/// Cancels the region compaction identified by `(region_id, task_id)`.
/// Returns one when cancellation is issued or already pending, and zero when absent.
#[admin_fn(
name = CancelRegionCompactionFunction,
display_name = cancel_region_compaction,
sig_fn = signature,
ret = uint64
)]
pub(crate) async fn cancel_region_compaction(
table_mutation_handler: &TableMutationHandlerRef,
query_ctx: &QueryContextRef,
params: &[ValueRef<'_>],
) -> Result<Value> {
ensure!(
params.len() == 2,
InvalidFuncArgsSnafu {
err_msg: format!(
"cancel_region_compaction expects 2 arguments, received {}",
params.len()
),
}
);
let Some(region_id) = helper::cast_u64(&params[0])? else {
return UnsupportedInputDataTypeSnafu {
function: "cancel_region_compaction",
datatypes: params
.iter()
.map(|value| value.data_type())
.collect::<Vec<_>>(),
}
.fail();
};
let ValueRef::String(task_id) = params[1] else {
return InvalidFuncArgsSnafu {
err_msg: "task_id must be a non-empty string",
}
.fail();
};
ensure!(
!task_id.trim().is_empty(),
InvalidFuncArgsSnafu {
err_msg: "task_id must be a non-empty string"
}
);
let affected_rows = table_mutation_handler
.cancel_region_compaction(
RegionId::from_u64(region_id),
task_id.to_string(),
query_ctx.clone(),
)
.await?;
Ok(Value::from(affected_rows as u64))
}
fn signature() -> Signature {
// Matches COMPACT_REGION: primitive numerics without Decimal or Float16 overloads.
helper::one_of_sigs2(
ConcreteDataType::numerics()
.into_iter()
.map(|data_type| data_type.as_arrow_type())
.collect(),
vec![ArrowDataType::Utf8],
)
}
#[cfg(test)]
mod tests {
use std::sync::Arc;
use arrow::datatypes::Field;
use datafusion_common::ScalarValue;
use datafusion_expr::{ColumnarValue, ScalarFunctionArgs};
use super::*;
use crate::function::FunctionContext;
use crate::function_registry;
#[tokio::test]
async fn test_cancel_region_compaction_arguments() {
let ctx = FunctionContext::mock();
let handler = ctx.state.table_mutation_handler.as_ref().unwrap();
for params in [
vec![],
vec![ValueRef::UInt64(42)],
vec![
ValueRef::UInt64(42),
ValueRef::String("task"),
ValueRef::Null,
],
vec![ValueRef::Null, ValueRef::String("task")],
vec![ValueRef::UInt64(42), ValueRef::Null],
vec![ValueRef::UInt64(42), ValueRef::UInt64(1)],
vec![ValueRef::UInt64(42), ValueRef::String(" \t")],
] {
assert!(
cancel_region_compaction(handler, &ctx.query_ctx, &params)
.await
.is_err(),
"{params:?}"
);
}
let error = cancel_region_compaction(
handler,
&ctx.query_ctx,
&[ValueRef::Null, ValueRef::String("cycle-id")],
)
.await
.unwrap_err();
assert!(matches!(
error,
common_query::error::Error::UnsupportedInputDataType { .. }
));
assert_eq!(
cancel_region_compaction(
handler,
&ctx.query_ctx,
&[ValueRef::UInt64(u64::MAX), ValueRef::String("cycle-id")]
)
.await
.unwrap(),
Value::UInt64(42)
);
}
#[tokio::test]
async fn test_cancel_region_compaction_async_function() {
let factory = function_registry::FUNCTION_REGISTRY
.get_function("cancel_region_compaction")
.unwrap();
for (ctx, has_handler) in [
(FunctionContext::mock(), true),
(FunctionContext::default(), false),
] {
let function = factory.provide(ctx);
let result = function
.as_async()
.unwrap()
.invoke_async_with_args(ScalarFunctionArgs {
args: vec![
ColumnarValue::Scalar(ScalarValue::UInt64(Some(u64::MAX))),
ColumnarValue::Scalar(ScalarValue::Utf8(Some("cycle-id".into()))),
],
arg_fields: vec![
Arc::new(Field::new("region_id", ArrowDataType::UInt64, false)),
Arc::new(Field::new("task_id", ArrowDataType::Utf8, false)),
],
return_field: Arc::new(Field::new("result", ArrowDataType::UInt64, false)),
number_rows: 1,
config_options: Default::default(),
})
.await;
if has_handler {
let ColumnarValue::Array(array) = result.unwrap() else {
panic!("expected array output");
};
assert_eq!(
ScalarValue::try_from_array(&array, 0).unwrap(),
ScalarValue::UInt64(Some(42))
);
} else {
assert!(
result
.unwrap_err()
.to_string()
.contains("Missing TableMutationHandler")
);
}
}
}
#[test]
fn test_cancel_region_compaction_registration_and_signature() {
let factory = function_registry::FUNCTION_REGISTRY
.get_function("cancel_region_compaction")
.unwrap();
let function = factory.provide(FunctionContext::mock());
assert_eq!(function.name(), "cancel_region_compaction");
assert_eq!(function.return_type(&[]).unwrap(), ArrowDataType::UInt64);
assert_eq!(function.signature(), &signature());
}
}
+8
View File
@@ -70,6 +70,14 @@ pub trait TableMutationHandler: Send + Sync {
ctx: QueryContextRef,
) -> Result<AffectedRows>;
/// Cancels one identified compaction task on a table region.
async fn cancel_region_compaction(
&self,
region_id: RegionId,
task_id: String,
ctx: QueryContextRef,
) -> Result<AffectedRows>;
/// Discard all unflushed data from a table region.
async fn discard_unflushed_data(
&self,
+50 -17
View File
@@ -23,7 +23,7 @@ use datafusion::common::{DFSchema, Result as DfResult};
use datafusion::execution::SessionStateBuilder;
use datafusion::logical_expr::{self, ColumnarValue, Expr, Volatility};
use datafusion::physical_planner::{DefaultPhysicalPlanner, PhysicalPlanner};
use datafusion_common::DataFusionError;
use datafusion_common::{DataFusionError, ScalarValue};
use datafusion_expr::physical_planning_context::PhysicalPlanningContext;
use datafusion_expr::{ScalarFunctionArgs, Signature};
use datatypes::arrow::array::RecordBatch;
@@ -101,14 +101,19 @@ impl Function for MatchesFunction {
impl MatchesFunction {
fn eval(&self, data_array: ArrayRef, pattern: &str) -> DfResult<ColumnarValue> {
let data_type = data_array.data_type();
if !data_type.is_string() {
return Err(DataFusionError::Execution(format!(
"unsupported datatype {data_type}"
)));
}
let col_name = "data";
let parser_context = ParserContext::default();
let raw_ast = parser_context.parse_pattern(pattern)?;
let ast = raw_ast.transform_ast()?;
let like_expr = ast.into_like_expr(col_name);
let input_schema = Self::input_schema();
let like_expr = ast.into_like_expr(col_name, data_type);
let input_schema = Self::input_schema(data_type);
let session_state = SessionStateBuilder::new().with_default_features().build();
let planner = DefaultPhysicalPlanner::default();
let physical_expr = planner.create_physical_expr(
@@ -119,7 +124,7 @@ impl MatchesFunction {
)?;
let arrow_schema = Arc::new(input_schema.as_arrow().clone());
let input_record_batch = RecordBatch::try_new(arrow_schema, vec![data_array]).unwrap();
let input_record_batch = RecordBatch::try_new(arrow_schema, vec![data_array])?;
let num_rows = input_record_batch.num_rows();
let result = physical_expr.evaluate(&input_record_batch)?;
@@ -128,9 +133,9 @@ impl MatchesFunction {
Ok(ColumnarValue::Array(Arc::new(result_array)))
}
fn input_schema() -> DFSchema {
fn input_schema(data_type: &DataType) -> DFSchema {
DFSchema::from_unqualified_fields(
[Arc::new(Field::new("data", DataType::Utf8, true))].into(),
[Arc::new(Field::new("data", data_type.clone(), true))].into(),
HashMap::new(),
)
.unwrap()
@@ -165,10 +170,10 @@ enum BinaryOp {
}
impl PatternAst {
fn into_like_expr(self, column: &str) -> Expr {
fn into_like_expr(self, column: &str, data_type: &DataType) -> Expr {
match self {
PatternAst::Literal { op, pattern } => {
let expr = Self::convert_literal(column, &pattern);
let expr = Self::convert_literal(column, &pattern, data_type);
match op {
UnaryOp::Must => expr,
UnaryOp::Optional => expr,
@@ -181,7 +186,7 @@ impl PatternAst {
}
let exprs = children
.into_iter()
.map(|child| child.into_like_expr(column));
.map(|child| child.into_like_expr(column, data_type));
// safety: children is not empty
match op {
BinaryOp::And => exprs.reduce(Expr::and).unwrap(),
@@ -189,7 +194,7 @@ impl PatternAst {
}
}
PatternAst::Group { op, child } => {
let child = child.into_like_expr(column);
let child = child.into_like_expr(column, data_type);
match op {
UnaryOp::Must => child,
UnaryOp::Optional => child,
@@ -199,11 +204,14 @@ impl PatternAst {
}
}
fn convert_literal(column: &str, pattern: &str) -> Expr {
logical_expr::col(column).like(logical_expr::lit(format!(
"%{}%",
crate::utils::escape_like_pattern(pattern)
)))
fn convert_literal(column: &str, pattern: &str, data_type: &DataType) -> Expr {
let pattern = Some(format!("%{}%", crate::utils::escape_like_pattern(pattern)));
let pattern = match data_type {
DataType::Utf8View => ScalarValue::Utf8View(pattern),
DataType::LargeUtf8 => ScalarValue::LargeUtf8(pattern),
_ => ScalarValue::Utf8(pattern),
};
logical_expr::col(column).like(Expr::Literal(pattern, None))
}
/// Transform this AST with preset rules to make it correct.
@@ -836,7 +844,6 @@ impl Tokenizer {
#[cfg(test)]
mod test {
use datafusion::arrow::array::StringArray;
use datafusion_common::ScalarValue;
use datafusion_common::config::ConfigOptions;
use super::*;
@@ -1294,6 +1301,32 @@ mod test {
}
}
#[test]
fn evaluate_matches_string_layouts() {
let input: ArrayRef = Arc::new(StringArray::from(vec![
Some("error timeout"),
Some("healthy"),
None,
]));
let function = MatchesFunction::default();
for data_type in [DataType::Utf8, DataType::LargeUtf8, DataType::Utf8View] {
let input = datatypes::arrow::compute::cast(&input, &data_type).unwrap();
for (pattern, expected) in [
("error", vec![Some(true), Some(false), None]),
("error AND timeout", vec![Some(true), Some(false), None]),
("error OR healthy", vec![Some(true), Some(true), None]),
] {
let expected: ArrayRef = Arc::new(BooleanArray::from(expected));
let actual = function
.eval(input.clone(), pattern)
.unwrap()
.to_array(3)
.unwrap();
assert_eq!(expected.as_ref(), actual.as_ref(), "{data_type}, {pattern}");
}
}
}
#[test]
fn evaluate_matches() {
let input_data = vec![
+9
View File
@@ -199,6 +199,15 @@ impl FunctionState {
Ok(ROWS)
}
async fn cancel_region_compaction(
&self,
_region_id: RegionId,
_task_id: String,
_ctx: QueryContextRef,
) -> Result<AffectedRows> {
Ok(ROWS)
}
async fn discard_unflushed_data(
&self,
_region_id: RegionId,
+13
View File
@@ -17,6 +17,7 @@ use api::v1::add_column_location::LocationType;
use api::v1::alter_table_expr::Kind;
use api::v1::column_def::{
as_fulltext_option_analyzer, as_fulltext_option_backend, as_skipping_index_type,
json_fulltext_options_from_proto,
};
use api::v1::{
AddColumnLocation as Location, AlterTableExpr, Analyzer, CreateTableExpr, DropColumns,
@@ -75,6 +76,16 @@ fn json_settings_from_proto(settings: api::v1::JsonSettings) -> Result<JsonSetti
path: hint.path,
data_type,
inverted_index: hint.inverted_index,
fulltext_index: hint
.fulltext_index
.map(json_fulltext_options_from_proto)
.transpose()
.map_err(|err| {
InvalidJsonSettingsSnafu {
err: err.to_string(),
}
.build()
})?,
skipping_index: hint
.skipping_index
.map(api::v1::column_def::json_skipping_options_from_proto)
@@ -437,6 +448,7 @@ mod tests {
data_type: ColumnDataType::String as i32,
inverted_index: enabled,
skipping_index: None,
fulltext_index: None,
..Default::default()
}],
max_auto_expanded_paths: Some(0),
@@ -496,6 +508,7 @@ mod tests {
data_type: ColumnDataType::String as i32,
inverted_index,
skipping_index: None,
fulltext_index: None,
..Default::default()
}],
max_auto_expanded_paths: Some(0),
+37 -12
View File
@@ -102,11 +102,13 @@ pub struct RegionStat {
pub region_manifest: RegionManifestInfo,
/// The total bytes written of the region since region opened.
pub written_bytes: u64,
/// Total Parquet bytes committed by flushes since the region opened.
/// Total ingested Parquet bytes since the region opened.
/// Currently counts only committed flush output.
///
/// Excludes index files, compaction and imported SSTs. Resets on region reopen.
#[serde(default)]
pub flushed_parquet_bytes: u64,
/// Accepts the legacy `flushed_parquet_bytes` key; upgrade metasrv before datanodes.
#[serde(default, alias = "flushed_parquet_bytes")]
pub ingested_parquet_bytes: u64,
/// The total query CPU time of the region since region opened.
///
/// Unit: nanoseconds.
@@ -338,7 +340,7 @@ impl From<&api::v1::meta::RegionStat> for RegionStat {
index_size: region_stat.index_size,
region_manifest: region_stat.manifest.into(),
written_bytes: region_stat.written_bytes,
flushed_parquet_bytes: region_stat.flushed_parquet_bytes,
ingested_parquet_bytes: region_stat.ingested_parquet_bytes,
query_cpu_time: region_stat.query_cpu_time,
query_scanned_bytes: region_stat.query_scanned_bytes,
data_topic_latest_entry_id: region_stat.data_topic_latest_entry_id,
@@ -603,7 +605,7 @@ mod tests {
file_removed_cnt: 0,
},
written_bytes: 0,
flushed_parquet_bytes: 4096,
ingested_parquet_bytes: 4096,
query_cpu_time: 10,
query_scanned_bytes: 20,
data_topic_latest_entry_id: 0,
@@ -616,14 +618,14 @@ mod tests {
let stat_val = DatanodeStatValue { stats: vec![stat] };
let mut value = serde_json::to_value(stat_val).unwrap();
let region_stat = value[0]["region_stats"][0].as_object_mut().unwrap();
region_stat.remove("flushed_parquet_bytes");
region_stat.remove("ingested_parquet_bytes");
region_stat.remove("query_cpu_time");
region_stat.remove("query_scanned_bytes");
let stat_val: DatanodeStatValue = serde_json::from_value(value).unwrap();
let region_stat = &stat_val.stats[0].region_stats[0];
assert_eq!(region_stat.flushed_parquet_bytes, 0);
assert_eq!(region_stat.ingested_parquet_bytes, 0);
assert_eq!(region_stat.query_cpu_time, 0);
assert_eq!(region_stat.query_scanned_bytes, 0);
}
@@ -713,10 +715,10 @@ mod tests {
}
#[test]
fn test_flushed_parquet_bytes_from_heartbeat() {
fn test_ingested_parquet_bytes_from_heartbeat() {
for bytes in [0, 4096, u64::MAX] {
let statistic = RegionStatistic {
flushed_parquet_bytes: bytes,
ingested_parquet_bytes: bytes,
..Default::default()
};
let mut region = api::v1::meta::RegionStat::default();
@@ -735,12 +737,35 @@ mod tests {
};
let stat = Stat::try_from(&request).unwrap();
let stat = &stat.region_stats[0];
assert_eq!(stat.flushed_parquet_bytes, bytes);
assert_eq!(stat.ingested_parquet_bytes, bytes);
let encoded = serde_json::to_vec(stat).unwrap();
let wire: serde_json::Value = serde_json::from_slice(&encoded).unwrap();
assert_eq!(wire["ingested_parquet_bytes"], bytes);
assert!(wire.get("flushed_parquet_bytes").is_none());
let mut old_wire = wire.clone();
old_wire
.as_object_mut()
.unwrap()
.remove("ingested_parquet_bytes");
old_wire["flushed_parquet_bytes"] = bytes.into();
assert_eq!(
&serde_json::from_value::<RegionStat>(old_wire).unwrap(),
stat
);
let decoded: RegionStat = serde_json::from_slice(&encoded).unwrap();
assert_eq!(&decoded, stat);
let mut legacy = serde_json::to_value(&statistic).unwrap();
legacy
.as_object_mut()
.unwrap()
.remove("ingested_parquet_bytes");
legacy["flushed_parquet_bytes"] = bytes.into();
region.extensions.insert(
REGION_STATISTIC_KEY.to_string(),
serde_json::to_vec(&legacy).unwrap(),
);
assert_eq!(RegionStat::from(&region).ingested_parquet_bytes, bytes);
legacy
.as_object_mut()
.unwrap()
@@ -749,10 +774,10 @@ mod tests {
REGION_STATISTIC_KEY.to_string(),
serde_json::to_vec(&legacy).unwrap(),
);
assert_eq!(RegionStat::from(&region).flushed_parquet_bytes, 0);
assert_eq!(RegionStat::from(&region).ingested_parquet_bytes, 0);
}
assert_eq!(
RegionStat::from(&api::v1::meta::RegionStat::default()).flushed_parquet_bytes,
RegionStat::from(&api::v1::meta::RegionStat::default()).ingested_parquet_bytes,
0
);
}
+82 -3
View File
@@ -683,6 +683,7 @@ pub struct LocalManager {
config: ManagerConfig,
pause_aware: Option<PauseAwareRef>,
event_recorder: EventRecorderHandle,
recovery_complete: AtomicBool,
}
impl LocalManager {
@@ -705,6 +706,7 @@ impl LocalManager {
config,
pause_aware,
event_recorder: EventRecorderHandle::new(event_recorder),
recovery_complete: AtomicBool::new(false),
}
}
@@ -894,12 +896,29 @@ impl ProcedureManager for LocalManager {
*task = Some(task_inner);
self.recovery_complete.store(false, Ordering::Release);
self.manager_ctx.reset_runtime_state();
self.manager_ctx.start();
info!("LocalManager is start.");
if let Err(error) = self.recover().await {
// A failed recovery must leave start() retryable, not merely not ready.
self.manager_ctx.stop();
if let Some(task) = task.take()
&& let Err(e) = task.stop().await.context(StopRemoveOutdatedMetaTaskSnafu)
{
error!(e; "Failed to stop remove outdated meta task after recovery failure");
}
self.manager_ctx.abort_runner_tasks().await;
self.manager_ctx.reset_runtime_state();
return Err(error);
}
self.recovery_complete.store(true, Ordering::Release);
info!("LocalManager is started.");
Ok(())
}
self.recover().await
fn is_ready(&self) -> bool {
self.recovery_complete.load(Ordering::Acquire) && self.manager_ctx.running()
}
async fn stop(&self) -> Result<()> {
@@ -1024,7 +1043,7 @@ mod tests {
use super::*;
use crate::error::{self, Error};
use crate::store::state_store::{ObjectStateStore, StateStore};
use crate::store::state_store::{KeyValueStream, ObjectStateStore, StateStore};
use crate::test_util::InMemoryPoisonStore;
use crate::{
ChildSubmissionOutcome, Context, EventContext, EventTrigger, Procedure, ProcedureEvent,
@@ -1950,6 +1969,66 @@ mod tests {
assert!(matches!(err, Error::LoaderConflict { .. }), "{err}");
}
/// Injects a transient failure while listing stored procedures.
struct FailingRecoveryStore {
/// Stores procedures after the injected failure.
inner: ObjectStateStore,
/// Fails the next recovery scan when set.
fail: AtomicBool,
}
#[async_trait]
impl StateStore for FailingRecoveryStore {
async fn put(&self, key: &str, value: Vec<u8>) -> Result<()> {
self.inner.put(key, value).await
}
async fn walk_top_down(&self, path: &str) -> Result<KeyValueStream> {
if self.fail.swap(false, AtomicOrdering::Relaxed) {
return Err(Error::external(MockError::new(
StatusCode::StorageUnavailable,
)));
}
self.inner.walk_top_down(path).await
}
async fn batch_delete(&self, keys: &[String]) -> Result<()> {
self.inner.batch_delete(keys).await
}
async fn delete(&self, key: &str) -> Result<()> {
self.inner.delete(key).await
}
}
#[tokio::test]
async fn test_start_retries_failed_recovery() {
let dir = create_temp_dir("retry_failed_recovery");
let store = Arc::new(FailingRecoveryStore {
inner: ObjectStateStore::new(test_util::new_object_store(&dir)),
fail: AtomicBool::new(true),
});
let manager = LocalManager::new(
ManagerConfig::default(),
store,
Arc::new(InMemoryPoisonStore::new()),
None,
None,
);
assert!(manager.start().await.is_err());
assert!(!manager.is_ready());
assert!(!manager.manager_ctx.running());
assert!(manager.remove_outdated_meta_task.lock().await.is_none());
manager.start().await.unwrap();
assert!(manager.is_ready());
manager.start().await.unwrap();
assert!(manager.is_ready());
manager.stop().await.unwrap();
assert!(!manager.is_ready());
}
#[tokio::test]
async fn test_recover() {
let dir = create_temp_dir("recover");
+3
View File
@@ -713,6 +713,9 @@ pub trait ProcedureManager: Send + Sync + 'static {
/// Callers should ensure all loaders are registered.
async fn start(&self) -> Result<()>;
/// Returns whether startup recovery has completed and the manager is running.
fn is_ready(&self) -> bool;
/// Stops the background GC task.
async fn stop(&self) -> Result<()>;
+3 -1
View File
@@ -23,7 +23,9 @@ use datafusion::logical_expr::{LogicalPlan, LogicalPlanBuilder};
use datafusion_common::{Column, TableReference};
use datafusion_expr::dml::InsertOp;
use datafusion_expr::{DmlStatement, TableSource, WriteOp, col};
pub use expr::{build_filter_from_timestamp, build_same_type_ts_filter};
pub use expr::{
build_filter_from_timestamp, build_same_type_ts_filter, is_lossless_substrait_type,
};
use crate::error::Result;
+28
View File
@@ -15,6 +15,7 @@
use common_time::Timestamp;
use common_time::range::TimestampRange;
use common_time::timestamp::TimeUnit;
use datafusion::arrow::datatypes::DataType as ArrowDataType;
use datafusion_common::{Column, ScalarValue};
use datafusion_expr::expr::Expr;
use datafusion_expr::{Operator, and, binary_expr};
@@ -22,6 +23,33 @@ use datatypes::data_type::DataType;
use datatypes::schema::ColumnSchema;
use datatypes::value::Value;
/// Whether a scalar type is in the conservative lossless Substrait transport subset.
///
/// In particular, timestamp timezone identifiers are lost by Substrait even when
/// encoding succeeds. Additional Arrow types need transport coverage first.
pub fn is_lossless_substrait_type(data_type: &ArrowDataType) -> bool {
matches!(
data_type,
ArrowDataType::Null
| ArrowDataType::Boolean
| ArrowDataType::Int8
| ArrowDataType::Int16
| ArrowDataType::Int32
| ArrowDataType::Int64
| ArrowDataType::UInt8
| ArrowDataType::UInt16
| ArrowDataType::UInt32
| ArrowDataType::UInt64
| ArrowDataType::Float32
| ArrowDataType::Float64
| ArrowDataType::Utf8
| ArrowDataType::Binary
| ArrowDataType::Date32
| ArrowDataType::Timestamp(_, None)
| ArrowDataType::Decimal128(_, _)
)
}
/// Builds a filter for a timestamp column with the same type as the timestamp column.
/// Returns [None] if time range is [None] or full time range.
pub fn build_same_type_ts_filter(
+10 -2
View File
@@ -55,7 +55,7 @@ impl From<NaiveDate> for Date {
impl Display for Date {
/// [Date] is formatted according to ISO-8601 standard.
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
if let Some(abs_date) = NaiveDate::from_num_days_from_ce_opt(UNIX_EPOCH_FROM_CE + self.0) {
if let Some(abs_date) = self.to_chrono_date() {
write!(f, "{}", abs_date.format("%F"))
} else {
write!(f, "Date({})", self.0)
@@ -93,7 +93,9 @@ impl Date {
}
pub fn to_chrono_date(&self) -> Option<NaiveDate> {
NaiveDate::from_num_days_from_ce_opt(UNIX_EPOCH_FROM_CE + self.0)
UNIX_EPOCH_FROM_CE
.checked_add(self.0)
.and_then(NaiveDate::from_num_days_from_ce_opt)
}
/// Format Date for given format and timezone.
@@ -217,6 +219,12 @@ mod tests {
assert_eq!("1970-02-12", Date::new(42).to_string());
}
#[test]
fn test_to_chrono_date_out_of_range() {
assert_eq!(None, Date::new(i32::MAX).to_chrono_date());
assert_eq!("Date(2147483647)", Date::new(i32::MAX).to_string());
}
#[test]
pub fn test_date_parse() {
assert_eq!(
+1
View File
@@ -14,6 +14,7 @@ workspace = true
[dependencies]
api.workspace = true
arrow-flight.workspace = true
async-stream.workspace = true
async-trait.workspace = true
bytes.workspace = true
catalog.workspace = true
+1
View File
@@ -1931,6 +1931,7 @@ impl RegionServerInner {
RegionRequest::Alter(_)
| RegionRequest::Flush(_)
| RegionRequest::Compact(_)
| RegionRequest::CancelCompaction(_)
| RegionRequest::Truncate(_)
| RegionRequest::BuildIndex(_)
| RegionRequest::EnterStaging(_)
+24 -1
View File
@@ -29,19 +29,23 @@ use datafusion_expr::{LogicalPlan, TableSource};
use futures::TryStreamExt;
use session::context::QueryContextRef;
use snafu::{OptionExt, ResultExt};
use store_api::compaction_task::CompactionTaskEntry;
use store_api::region_info::RegionInfoEntry;
use store_api::sst_entry::{ManifestSstEntry, PuffinIndexMetaEntry, StorageSstEntry};
use store_api::storage::RegionId;
use crate::error::{DataFusionSnafu, ListStorageSstsSnafu, Result, UnexpectedSnafu};
use crate::region_server::RegionServer;
use crate::region_server::catalog::inspect::{InspectTable, ManifestSstSource};
use crate::region_server::catalog::inspect::{
CompactionTasksSource, InspectTable, ManifestSstSource,
};
/// Reserved internal table kinds used.
/// These are recognized by reserved table names and mapped to providers.
#[allow(clippy::enum_variant_names)]
#[derive(Clone, Debug, PartialEq, Eq, Hash, Copy)]
enum InternalTableKind {
InspectCompactionTasks,
InspectSstManifest,
InspectSstStorage,
InspectSstIndexMeta,
@@ -51,6 +55,9 @@ enum InternalTableKind {
impl InternalTableKind {
/// Determine if the name is a reserved internal table (case-insensitive).
pub fn from_table_name(name: &str) -> Option<Self> {
if name.eq_ignore_ascii_case(CompactionTaskEntry::reserved_table_name_for_inspection()) {
return Some(Self::InspectCompactionTasks);
}
if name.eq_ignore_ascii_case(ManifestSstEntry::reserved_table_name_for_inspection()) {
return Some(Self::InspectSstManifest);
}
@@ -69,6 +76,7 @@ impl InternalTableKind {
/// Return the `TableProvider` for the internal table.
pub async fn table_provider(&self, server: &RegionServer) -> Result<Arc<dyn TableProvider>> {
match self {
Self::InspectCompactionTasks => server.inspect_compaction_tasks_provider().await,
Self::InspectSstManifest => server.inspect_sst_manifest_provider().await,
Self::InspectSstStorage => server.inspect_sst_storage_provider().await,
Self::InspectSstIndexMeta => server.inspect_sst_index_meta_provider().await,
@@ -78,6 +86,20 @@ impl InternalTableKind {
}
impl RegionServer {
/// Exposes current scheduler state through the shared lazy inspection provider.
pub async fn inspect_compaction_tasks_provider(&self) -> Result<Arc<dyn TableProvider>> {
let mito = {
let guard = self.inner.mito_engine.read().unwrap();
guard.as_ref().cloned().context(UnexpectedSnafu {
violated: "mito engine not available",
})?
};
Ok(Arc::new(InspectTable::new(Arc::new(
CompactionTasksSource::new(mito),
))))
}
/// Exposes manifest SSTs through a lazy table with metadata predicate pruning.
pub async fn inspect_sst_manifest_provider(&self) -> Result<Arc<dyn TableProvider>> {
let mito = {
@@ -353,6 +375,7 @@ impl TreeNodeRewriter for NameAwareDataSourceInjector {
#[cfg(test)]
mod tests {
mod compaction;
mod manifest;
use std::sync::Arc;
@@ -27,6 +27,7 @@ use datafusion_common::DataFusionError;
use datafusion_expr::{Expr, TableProviderFilterPushDown, TableType};
use futures::StreamExt;
use mito2::engine::MitoEngine;
use store_api::compaction_task::{CompactionTaskBatchBuilder, CompactionTaskEntry};
use store_api::sst_entry::{ManifestSstBatchBuilder, ManifestSstEntry};
/// Supplies batches for an internal inspection table. Implementations may prune
@@ -156,6 +157,48 @@ impl InspectSource for ManifestSstSource {
}
}
/// Reads live compaction state only when a scan is executed.
pub(crate) struct CompactionTasksSource {
engine: MitoEngine,
}
impl CompactionTasksSource {
/// Creates a source backed by the engine's live compaction cycles.
pub(crate) fn new(engine: MitoEngine) -> Self {
Self { engine }
}
}
impl std::fmt::Debug for CompactionTasksSource {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("CompactionTasksSource")
.finish_non_exhaustive()
}
}
impl InspectSource for CompactionTasksSource {
fn schema(&self) -> SchemaRef {
CompactionTaskEntry::schema().arrow_schema().clone()
}
fn scan(&self, request: &InspectScan, _ctx: Arc<TaskContext>) -> SendableRecordBatchStream {
let engine = self.engine.clone();
let request = request.clone();
let schema = request.schema.clone();
let builder = CompactionTaskBatchBuilder::new(schema.clone());
let stream = async_stream::try_stream! {
let entries = engine
.inspect_compaction_tasks(&request.filters)
.await
.map_err(|error| DataFusionError::External(Box::new(error)))?;
for entries in entries.chunks(request.batch_size) {
yield builder.build(entries)?;
}
};
Box::pin(RecordBatchStreamAdapter::new(schema, stream))
}
}
#[derive(Debug)]
struct InspectPartition {
source: Arc<dyn InspectSource>,
@@ -308,4 +351,139 @@ mod tests {
assert_eq!(source.scans.load(Ordering::SeqCst), 1);
assert_eq!(source.drops.load(Ordering::SeqCst), 1);
}
#[tokio::test]
async fn test_manifest_optimized_sql_pruning() {
use std::sync::Mutex;
use datafusion_expr::{col, lit};
use mito2::config::MitoConfig;
use mito2::manifest::action::RegionEdit;
use mito2::sst::file::FileMeta;
use mito2::test_util::{CreateRequestBuilder, TestEnv};
use store_api::region_engine::RegionEngine;
use store_api::region_request::RegionRequest;
use store_api::storage::{FileId, RegionId};
#[derive(Debug)]
struct RecordingSource {
inner: ManifestSstSource,
filters: Mutex<Vec<Expr>>,
candidates: Arc<AtomicUsize>,
}
impl InspectSource for RecordingSource {
fn schema(&self) -> SchemaRef {
self.inner.schema()
}
fn scan(
&self,
request: &InspectScan,
ctx: Arc<TaskContext>,
) -> SendableRecordBatchStream {
*self.filters.lock().unwrap() = request.filters.clone();
let candidates = self.candidates.clone();
let stream = self.inner.scan(request, ctx).map(move |batch| {
if let Ok(batch) = &batch {
candidates.fetch_add(batch.num_rows(), Ordering::SeqCst);
}
batch
});
Box::pin(RecordBatchStreamAdapter::new(
request.schema.clone(),
stream,
))
}
}
let mut env = TestEnv::new().await.with_node_id(42);
let engine = env
.create_engine(MitoConfig {
schedule_compaction_after_edit: false,
..Default::default()
})
.await;
let region_id = RegionId::new(11, 1);
engine
.handle_request(
region_id,
RegionRequest::Create(CreateRequestBuilder::new().build()),
)
.await
.unwrap();
engine
.edit_region(
region_id,
RegionEdit {
files_to_add: vec![FileMeta {
region_id,
file_id: FileId::from_bytes(1u128.to_be_bytes()),
..Default::default()
}],
files_to_remove: vec![],
timestamp_ms: None,
compaction_time_window: None,
flushed_entry_id: None,
flushed_sequence: None,
committed_sequence: None,
},
)
.await
.unwrap();
let source = Arc::new(RecordingSource {
inner: ManifestSstSource::new(engine),
filters: Mutex::new(Vec::new()),
candidates: Arc::new(AtomicUsize::new(0)),
});
let ctx = SessionContext::new();
ctx.register_table("manifest", Arc::new(InspectTable::new(source.clone())))
.unwrap();
for (predicate, expected_filter, expected_count) in [
("node_id = 99".to_string(), col("node_id").eq(lit(99u64)), 0),
(
"node_id != 42".to_string(),
col("node_id").not_eq(lit(42u64)),
0,
),
("node_id = 42".to_string(), col("node_id").eq(lit(42u64)), 1),
(
"region_id = 0".to_string(),
col("region_id").eq(lit(0u64)),
0,
),
(
format!("region_id = {}", region_id.as_u64()),
col("region_id").eq(lit(region_id.as_u64())),
1,
),
] {
source.candidates.store(0, Ordering::SeqCst);
source.filters.lock().unwrap().clear();
// collect() runs the default optimizer and the actual inspection provider.
let batches = ctx
.sql(&format!("SELECT file_id FROM manifest WHERE {predicate}"))
.await
.unwrap()
.collect()
.await
.unwrap();
// The scanner receives a UInt64 comparison, with no Decimal cast.
assert_eq!(
*source.filters.lock().unwrap(),
vec![expected_filter],
"{predicate}"
);
// Count the manifest source's candidates before DataFusion's residual filter.
assert_eq!(
source.candidates.load(Ordering::SeqCst),
expected_count,
"{predicate}"
);
assert_eq!(
batches.iter().map(|batch| batch.num_rows()).sum::<usize>(),
expected_count,
"{predicate}"
);
}
}
}
@@ -0,0 +1,366 @@
// 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.
use std::sync::Arc;
use std::time::Duration;
use api::v1::Rows;
use api::v1::region::{CancelCompactionRequest, region_request};
use common_error::ext::ErrorExt;
use common_error::status_code::StatusCode;
use datafusion::arrow::compute::concat_batches;
use datafusion::arrow::record_batch::RecordBatch;
use datafusion::catalog::MemTable;
use datafusion::prelude::SessionContext;
use mito2::config::MitoConfig;
use mito2::engine::listener::EventListener;
use mito2::test_util::{
CreateRequestBuilder, TestEnv, build_rows_for_key, flush_region, put_rows, rows_schema,
};
use servers::grpc::region_server::RegionServerHandler;
use store_api::compaction_task::CompactionTaskEntry;
use store_api::region_engine::RegionEngine;
use store_api::region_request::{RegionCompactRequest, RegionRequest};
use store_api::storage::RegionId;
use tokio::sync::Semaphore;
use crate::region_server::catalog::inspect::{CompactionTasksSource, InspectTable};
use crate::tests::mock_region_server;
struct MergeGate {
entered: Semaphore,
resume: Semaphore,
}
#[async_trait::async_trait]
impl EventListener for MergeGate {
async fn on_compaction_unit_merge_begin(&self, _: RegionId, _: u64) {
self.entered.add_permits(1);
if let Ok(permit) = self.resume.acquire().await {
permit.forget();
}
}
}
struct ReleaseGate(Arc<MergeGate>);
impl Drop for ReleaseGate {
fn drop(&mut self) {
self.0.resume.close();
}
}
async fn query(context: &SessionContext, sql: &str) -> RecordBatch {
let frame = context.sql(sql).await.unwrap();
let schema = Arc::new(frame.schema().as_arrow().clone());
let batches = frame.collect().await.unwrap();
concat_batches(&schema, &batches).unwrap()
}
/// Ablates lazy inspection against eager snapshots under the same gated workload.
#[tokio::test]
async fn test_compaction_tasks_live_scan_and_pushdown() {
let gate = Arc::new(MergeGate {
entered: Semaphore::new(0),
resume: Semaphore::new(0),
});
let guard = ReleaseGate(gate.clone());
let mut env = TestEnv::new().await;
let engine = env
.create_engine_with(
MitoConfig {
max_background_compactions: 2,
min_compaction_interval: Duration::from_secs(3600),
..Default::default()
},
None,
Some(gate.clone()),
None,
)
.await;
let mut jobs = Vec::new();
for table_id in [11, 12] {
let region_id = RegionId::new(table_id, 1);
let create = CreateRequestBuilder::new()
.insert_option("compaction.type", "twcs")
.insert_option("compaction.twcs.trigger_file_num", "100")
.build();
let schema = rows_schema(&create);
engine
.handle_request(region_id, RegionRequest::Create(create))
.await
.unwrap();
for _ in 0..2 {
put_rows(
&engine,
region_id,
Rows {
schema: schema.clone(),
rows: build_rows_for_key("a", 0, 10, 0),
},
)
.await;
flush_region(&engine, region_id, None).await;
}
let engine = engine.clone();
jobs.push(tokio::spawn(async move {
engine
.handle_request(
region_id,
RegionRequest::Compact(RegionCompactRequest {
options: api::v1::region::compact_request::Options::StrictWindow(
api::v1::region::StrictWindow {
window_seconds: 3600,
},
),
..Default::default()
}),
)
.await
.unwrap();
}));
}
tokio::time::timeout(Duration::from_secs(20), gate.entered.acquire_many(2))
.await
.unwrap()
.unwrap()
.forget();
let entries = engine.inspect_compaction_tasks(&[]).await.unwrap();
assert_eq!(entries.len(), 2);
for entry in &entries {
assert_eq!(entry.state.as_ref(), "running");
assert_eq!(entry.trigger_type.as_ref(), "manual");
assert_eq!(entry.input_files, Some(2));
let options: serde_json::Value = serde_json::from_str(&entry.request_options).unwrap();
assert_eq!(options["window_seconds"], 3600);
assert!(entry.effective_options.is_some());
}
let lazy = SessionContext::new();
lazy.register_table(
"tasks",
Arc::new(InspectTable::new(Arc::new(CompactionTasksSource::new(
engine.clone(),
)))),
)
.unwrap();
let eager = SessionContext::new();
let batch = CompactionTaskEntry::to_record_batch(&entries).unwrap();
eager
.register_table(
"tasks",
Arc::new(MemTable::try_new(batch.schema(), vec![vec![batch]]).unwrap()),
)
.unwrap();
// Repeat with identical state and workload; only the scan implementation differs.
for _ in 0..3 {
for sql in [
"SELECT task_id, request_options, effective_options FROM tasks ORDER BY task_id",
"SELECT task_id, input_time_start, input_time_end, output_time_start, output_time_end FROM tasks ORDER BY task_id",
"SELECT task_id FROM tasks WHERE input_time_start <= CAST('1970-01-01T00:00:01Z' AS TIMESTAMP(9)) AND output_time_end > CAST('1970-01-01T00:00:01Z' AS TIMESTAMP(9)) ORDER BY task_id",
"SELECT task_id FROM tasks WHERE output_time_end IS NULL ORDER BY task_id",
"SELECT task_id FROM tasks WHERE table_id = 12 AND state = 'running' LIMIT 1",
"SELECT count(*) FROM tasks WHERE table_id = 12",
"SELECT task_id FROM tasks WHERE table_id = 99 LIMIT 1",
"SELECT task_id FROM tasks WHERE table_id = 99 OR trigger_type = 'manual' ORDER BY task_id",
"SELECT task_id FROM tasks WHERE length(request_options) > 2 ORDER BY task_id LIMIT 1",
"SELECT task_id FROM tasks WHERE table_id = 12 AND length(request_options) < 2 LIMIT 1",
"SELECT task_id FROM tasks WHERE table_id = 99 OR length(request_options) > 2 ORDER BY task_id LIMIT 1",
"SELECT table_id FROM tasks ORDER BY table_id DESC LIMIT 1",
"SELECT task_id FROM tasks WHERE node_id IS NULL ORDER BY task_id",
"SELECT task_id FROM tasks LIMIT 0",
] {
assert_eq!(query(&lazy, sql).await, query(&eager, sql).await, "{sql}");
}
}
drop(guard);
for job in jobs {
tokio::time::timeout(Duration::from_secs(20), job)
.await
.unwrap()
.unwrap();
}
tokio::time::timeout(Duration::from_secs(10), async {
loop {
if engine
.inspect_compaction_tasks(&[])
.await
.unwrap()
.is_empty()
{
break;
}
tokio::task::yield_now().await;
}
})
.await
.unwrap();
assert_eq!(
query(&lazy, "SELECT task_id FROM tasks").await.num_rows(),
0
);
}
/// Cancels the exact observed cycle through the datanode handler and engine routing.
#[tokio::test]
async fn test_cancel_compaction_live_task() {
tokio::time::timeout(Duration::from_secs(30), async {
let gate = Arc::new(MergeGate {
entered: Semaphore::new(0),
resume: Semaphore::new(0),
});
let release = ReleaseGate(gate.clone());
let mut env = TestEnv::new().await;
let engine = env
.create_engine_with(
MitoConfig {
min_compaction_interval: Duration::from_secs(3600),
..Default::default()
},
None,
Some(gate.clone()),
None,
)
.await;
let mut server = mock_region_server();
server.register_engine(Arc::new(engine.clone()));
let region_id = RegionId::new(13, 1);
let create = CreateRequestBuilder::new()
.insert_option("compaction.type", "twcs")
.insert_option("compaction.twcs.trigger_file_num", "100")
.build();
let schema = rows_schema(&create);
server
.handle_request(region_id, RegionRequest::Create(create))
.await
.unwrap();
for _ in 0..2 {
put_rows(
&engine,
region_id,
Rows {
schema: schema.clone(),
rows: build_rows_for_key("a", 0, 10, 0),
},
)
.await;
flush_region(&engine, region_id, None).await;
}
let compact = {
let engine = engine.clone();
tokio::spawn(async move {
engine
.handle_request(
region_id,
RegionRequest::Compact(RegionCompactRequest {
options: api::v1::region::compact_request::Options::StrictWindow(
api::v1::region::StrictWindow {
window_seconds: 3600,
},
),
..Default::default()
}),
)
.await
})
};
gate.entered.acquire().await.unwrap().forget();
let tasks = engine.inspect_compaction_tasks(&[]).await.unwrap();
assert_eq!(tasks.len(), 1);
let task_id = tasks[0].task_id.to_string();
for (id, expected) in [
("stale-task-id", 0),
(task_id.as_str(), 1),
(task_id.as_str(), 1),
] {
let response = RegionServerHandler::handle(
&server,
region_request::Body::CancelCompaction(CancelCompactionRequest {
region_id: region_id.as_u64(),
task_id: id.into(),
}),
)
.await
.unwrap();
assert_eq!(response.affected_rows, expected);
assert_eq!(
response.header.unwrap().status.unwrap().status_code,
StatusCode::Success as u32
);
let tasks = engine.inspect_compaction_tasks(&[]).await.unwrap();
assert_eq!(tasks.len(), 1);
assert_eq!(tasks[0].task_id.as_ref(), task_id);
assert_eq!(
tasks[0].state.as_ref(),
if id == "stale-task-id" {
"running"
} else {
"cancelling"
}
);
}
drop(release);
assert!(compact.await.unwrap().is_err());
while !engine
.inspect_compaction_tasks(&[])
.await
.unwrap()
.is_empty()
{
tokio::task::yield_now().await;
}
let response = RegionServerHandler::handle(
&server,
region_request::Body::CancelCompaction(CancelCompactionRequest {
region_id: region_id.as_u64(),
task_id,
}),
)
.await
.unwrap();
assert_eq!(response.affected_rows, 0);
engine.stop().await.unwrap();
})
.await
.expect("datanode cancellation lifecycle did not complete");
}
#[tokio::test]
async fn test_cancel_compaction_routing_errors() {
tokio::time::timeout(Duration::from_secs(10), async {
let server = mock_region_server();
let region_id = RegionId::new(14, 1);
let request = CancelCompactionRequest {
region_id: region_id.as_u64(),
task_id: "cycle-id".into(),
};
let error = RegionServerHandler::handle(
&server,
region_request::Body::CancelCompaction(request.clone()),
)
.await
.unwrap_err();
assert_eq!(error.status_code(), StatusCode::RegionNotFound);
let error = RegionServerHandler::handle(
&server,
region_request::Body::CancelCompaction(CancelCompactionRequest {
task_id: " \t".into(),
..request
}),
)
.await
.unwrap_err();
assert_eq!(error.status_code(), StatusCode::InvalidArguments);
})
.await
.expect("datanode cancellation routing did not complete");
}
+1 -1
View File
@@ -6,6 +6,7 @@ license.workspace = true
[features]
default = []
enterprise = []
test = []
[lints]
@@ -31,7 +32,6 @@ parquet-variant.workspace = true
parquet-variant-compute.workspace = true
parquet-variant-json.workspace = true
paste.workspace = true
regex.workspace = true
serde.workspace = true
serde_json.workspace = true
snafu.workspace = true
+11
View File
@@ -278,6 +278,14 @@ pub enum Error {
location: Location,
},
#[cfg(feature = "enterprise")]
#[snafu(display("Invalid sketch option: {}", msg))]
InvalidSketchOption {
msg: String,
#[snafu(implicit)]
location: Location,
},
#[snafu(display("Invalid skipping index option: {}", msg))]
InvalidSkippingIndexOption {
msg: String,
@@ -370,6 +378,9 @@ impl ErrorExt for Error {
| InvalidSkippingIndexOption { .. }
| InvalidCompressionOption { .. } => StatusCode::InvalidArguments,
#[cfg(feature = "enterprise")]
InvalidSketchOption { .. } => StatusCode::InvalidArguments,
ValueExceedsPrecision { .. }
| CastType { .. }
| CastTimeType { .. }
+63 -2
View File
@@ -33,6 +33,7 @@ use crate::data_type::ConcreteDataType;
use crate::error::{self, InvalidJson2SettingsSnafu, Result, UnsupportedJsonTypeSnafu};
use crate::json::value::{JsonValue, JsonVariant, encode_serde_json_as_jsonb};
use crate::prelude::DataType as _;
use crate::schema::{FulltextOptions, SkippingIndexOptions};
use crate::types::json_type::{JsonNativeType, JsonObjectType};
use crate::value::{ListValue, StructValue, Value};
@@ -95,7 +96,10 @@ pub struct JsonTypeHint {
pub inverted_index: bool,
/// Optional Bloom Filter configuration for this path.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub skipping_index: Option<crate::schema::SkippingIndexOptions>,
pub skipping_index: Option<SkippingIndexOptions>,
/// Optional fulltext configuration for a string path.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub fulltext_index: Option<FulltextOptions>,
}
/// Specifies how encoding handles a value that does not match its JSON2 type hint.
@@ -218,8 +222,24 @@ fn validate_type_hints(type_hints: &[JsonTypeHint]) -> Result<()> {
let mut object = JsonObjectType::new();
for hint in type_hints {
if let Some(options) = &hint.fulltext_index {
if !hint.data_type.is_string() {
return InvalidJson2SettingsSnafu {
reason: "JSON2 FULLTEXT index only supports string type hints",
}
.fail();
}
FulltextOptions::new(
options.enable,
options.analyzer.clone(),
options.case_sensitive,
options.backend.clone(),
options.granularity,
options.false_positive_rate(),
)?;
}
if let Some(options) = &hint.skipping_index {
crate::schema::SkippingIndexOptions::new(
SkippingIndexOptions::new(
options.granularity,
options.false_positive_rate(),
options.index_type.clone(),
@@ -748,6 +768,28 @@ mod tests {
&struct_value.items()[index]
}
#[test]
fn test_fulltext_settings_roundtrip() {
let old =
r#"{"type_hints":[{"path":["message"],"type":{"String":{}},"inverted_index":false}]}"#;
let legacy: JsonSettings = serde_json::from_str(old).unwrap();
assert!(legacy.type_hints()[0].fulltext_index.is_none());
let mut hints = legacy.type_hints().to_vec();
hints[0].fulltext_index = Some(crate::schema::FulltextOptions {
enable: true,
..Default::default()
});
let settings = JsonSettings::try_new(hints.clone(), Some(0)).unwrap();
assert_eq!(
settings,
serde_json::from_str::<JsonSettings>(&serde_json::to_string(&settings).unwrap())
.unwrap()
);
assert!(!settings.equivalent(&legacy));
hints[0].data_type = ConcreteDataType::int64_datatype();
assert!(JsonSettings::try_new(hints, Some(0)).is_err());
}
#[test]
fn test_skipping_index_settings_roundtrip() {
let old = r#"{"type_hints":[{"path":["service","name"],"type":{"String":{}},"inverted_index":true}]}"#;
@@ -774,12 +816,14 @@ mod tests {
data_type: ConcreteDataType::string_datatype(),
inverted_index: false,
skipping_index: None,
fulltext_index: None,
},
JsonTypeHint {
path: vec!["count".to_string()],
data_type: ConcreteDataType::int64_datatype(),
inverted_index: false,
skipping_index: None,
fulltext_index: None,
},
];
let settings = JsonSettings::try_new(hints.clone(), Some(10))?;
@@ -852,12 +896,14 @@ mod tests {
data_type: ConcreteDataType::int64_datatype(),
inverted_index: true,
skipping_index: None,
fulltext_index: None,
},
JsonTypeHint {
path: vec!["user".to_string(), "name".to_string()],
data_type: ConcreteDataType::string_datatype(),
inverted_index: false,
skipping_index: None,
fulltext_index: None,
},
],
None,
@@ -874,12 +920,14 @@ mod tests {
data_type: ConcreteDataType::int64_datatype(),
inverted_index: true,
skipping_index: None,
fulltext_index: None,
},
JsonTypeHint {
path: vec!["user".to_string(), "name".to_string()],
data_type: ConcreteDataType::string_datatype(),
inverted_index: false,
skipping_index: None,
fulltext_index: None,
},
];
@@ -920,6 +968,7 @@ mod tests {
data_type: ConcreteDataType::string_datatype(),
inverted_index,
skipping_index: None,
fulltext_index: None,
};
let serialized = json!({"type_hints": [hint.clone()]});
assert_eq!(
@@ -955,6 +1004,7 @@ mod tests {
data_type,
inverted_index: false,
skipping_index: None,
fulltext_index: None,
};
assert!(
JsonSettings::try_new(
@@ -1019,6 +1069,7 @@ mod tests {
data_type: ConcreteDataType::int64_datatype(),
inverted_index: false,
skipping_index: None,
fulltext_index: None,
}],
None,
)?;
@@ -1050,12 +1101,14 @@ mod tests {
data_type: ConcreteDataType::string_datatype(),
inverted_index: false,
skipping_index: None,
fulltext_index: None,
},
JsonTypeHint {
path: vec!["to_int".to_string()],
data_type: ConcreteDataType::int64_datatype(),
inverted_index: false,
skipping_index: None,
fulltext_index: None,
},
],
None,
@@ -1091,6 +1144,7 @@ mod tests {
data_type: ConcreteDataType::int64_datatype(),
inverted_index: false,
skipping_index: None,
fulltext_index: None,
}],
None,
)?;
@@ -1253,6 +1307,7 @@ mod tests {
data_type: ConcreteDataType::int64_datatype(),
inverted_index: false,
skipping_index: None,
fulltext_index: None,
}];
let settings = JsonSettings::try_new(type_hints, None)?;
@@ -1286,6 +1341,7 @@ mod tests {
data_type: ConcreteDataType::uint64_datatype(),
inverted_index: false,
skipping_index: None,
fulltext_index: None,
}];
let settings = JsonSettings::try_new(type_hints, None)?;
@@ -1321,6 +1377,7 @@ mod tests {
data_type: ConcreteDataType::int64_datatype(),
inverted_index: false,
skipping_index: None,
fulltext_index: None,
}];
let settings = JsonSettings::try_new(type_hints, None)?;
@@ -1347,6 +1404,7 @@ mod tests {
data_type: ConcreteDataType::string_datatype(),
inverted_index: false,
skipping_index: None,
fulltext_index: None,
}];
let settings = JsonSettings::try_new(type_hints, None)?;
@@ -1373,6 +1431,7 @@ mod tests {
data_type: ConcreteDataType::int64_datatype(),
inverted_index: false,
skipping_index: None,
fulltext_index: None,
}];
let settings = JsonSettings::try_new(type_hints, None)?;
@@ -1388,12 +1447,14 @@ mod tests {
data_type: ConcreteDataType::int64_datatype(),
inverted_index: false,
skipping_index: None,
fulltext_index: None,
},
JsonTypeHint {
path: vec!["user".to_string(), "name".to_string()],
data_type: ConcreteDataType::string_datatype(),
inverted_index: false,
skipping_index: None,
fulltext_index: None,
},
];
let settings = JsonSettings::try_new(type_hints, None)?;
+6 -2
View File
@@ -15,6 +15,8 @@
mod column_schema;
pub mod constraint;
pub mod ext;
#[cfg(feature = "enterprise")]
mod sketch;
use std::collections::HashMap;
use std::sync::Arc;
@@ -36,10 +38,12 @@ pub use crate::schema::column_schema::{
COLUMN_SKIPPING_INDEX_OPT_KEY_FALSE_POSITIVE_RATE, COLUMN_SKIPPING_INDEX_OPT_KEY_GRANULARITY,
COLUMN_SKIPPING_INDEX_OPT_KEY_TYPE, COMMENT_KEY, COMPRESSION_KEY, ColumnEncoding,
ColumnExtType, ColumnSchema, CompressionOptions, CompressionType, FULLTEXT_KEY,
FulltextAnalyzer, FulltextBackend, FulltextOptions, INVERTED_INDEX_KEY, Metadata,
SKIPPING_INDEX_KEY, SkippingIndexOptions, SkippingIndexType, TIME_INDEX_KEY,
FulltextAnalyzer, FulltextBackend, FulltextOptions, HLL_KEY, INVERTED_INDEX_KEY, KLL_KEY,
MG_KEY, Metadata, SKIPPING_INDEX_KEY, SkippingIndexOptions, SkippingIndexType, TIME_INDEX_KEY,
};
pub use crate::schema::constraint::ColumnDefaultConstraint;
#[cfg(feature = "enterprise")]
pub use crate::schema::sketch::{HllOptions, KllOptions, MgOptions};
/// Key used to store version number of the schema in metadata.
pub const VERSION_KEY: &str = "greptime:version";
+125
View File
@@ -32,6 +32,8 @@ use crate::error::{
use crate::extension::json::Json2ExtensionType;
use crate::schema::TYPE_KEY;
use crate::schema::constraint::ColumnDefaultConstraint;
#[cfg(feature = "enterprise")]
use crate::schema::sketch::{HllOptions, KllOptions, MgOptions};
use crate::value::Value;
use crate::vectors::json::builder::JsonVectorBuilder;
use crate::vectors::{MutableVector, VectorRef};
@@ -51,6 +53,12 @@ pub const INVERTED_INDEX_KEY: &str = "greptime:inverted_index";
pub const SKIPPING_INDEX_KEY: &str = "greptime:skipping_index";
/// Key used to store SST compression options in arrow field's metadata.
pub const COMPRESSION_KEY: &str = "greptime:compression";
/// Key used to store HLL options in arrow field's metadata.
pub const HLL_KEY: &str = "greptime:hll";
/// Key used to store KLL options in arrow field's metadata.
pub const KLL_KEY: &str = "greptime:kll";
/// Key used to store MG options in arrow field's metadata.
pub const MG_KEY: &str = "greptime:mg";
/// Keys used in fulltext options
pub const COLUMN_FULLTEXT_CHANGE_OPT_KEY_ENABLE: &str = "enable";
@@ -436,6 +444,99 @@ impl ColumnSchema {
Ok(())
}
/// Retrieves independently enabled HLL options, validating stored parameters.
#[cfg(feature = "enterprise")]
pub fn hll_options(&self) -> Result<Option<HllOptions>> {
self.metadata
.get(HLL_KEY)
.map(|json| serde_json::from_str(json).context(error::DeserializeSnafu { json }))
.transpose()
}
/// Enables HLL with validated options.
#[cfg(feature = "enterprise")]
pub fn with_hll_options(mut self, options: HllOptions) -> Result<Self> {
self.set_hll_options(&options)?;
Ok(self)
}
/// Sets HLL options without modifying other algorithm metadata.
#[cfg(feature = "enterprise")]
pub fn set_hll_options(&mut self, options: &HllOptions) -> Result<()> {
options.validate()?;
let json = serde_json::to_string(options).context(error::SerializeSnafu)?;
self.metadata.insert(HLL_KEY.to_string(), json);
Ok(())
}
/// Removes only HLL options.
#[cfg(feature = "enterprise")]
pub fn unset_hll_options(&mut self) {
self.metadata.remove(HLL_KEY);
}
/// Retrieves independently enabled KLL options, validating stored parameters.
#[cfg(feature = "enterprise")]
pub fn kll_options(&self) -> Result<Option<KllOptions>> {
self.metadata
.get(KLL_KEY)
.map(|json| serde_json::from_str(json).context(error::DeserializeSnafu { json }))
.transpose()
}
/// Enables KLL with validated options.
#[cfg(feature = "enterprise")]
pub fn with_kll_options(mut self, options: KllOptions) -> Result<Self> {
self.set_kll_options(&options)?;
Ok(self)
}
/// Sets KLL options without modifying other algorithm metadata.
#[cfg(feature = "enterprise")]
pub fn set_kll_options(&mut self, options: &KllOptions) -> Result<()> {
options.validate()?;
let json = serde_json::to_string(options).context(error::SerializeSnafu)?;
self.metadata.insert(KLL_KEY.to_string(), json);
Ok(())
}
/// Removes only KLL options.
#[cfg(feature = "enterprise")]
pub fn unset_kll_options(&mut self) {
self.metadata.remove(KLL_KEY);
}
/// Retrieves independently enabled MG options, validating stored parameters.
#[cfg(feature = "enterprise")]
pub fn mg_options(&self) -> Result<Option<MgOptions>> {
self.metadata
.get(MG_KEY)
.map(|json| serde_json::from_str(json).context(error::DeserializeSnafu { json }))
.transpose()
}
/// Enables MG with validated options.
#[cfg(feature = "enterprise")]
pub fn with_mg_options(mut self, options: MgOptions) -> Result<Self> {
self.set_mg_options(&options)?;
Ok(self)
}
/// Sets MG options without modifying other algorithm metadata.
#[cfg(feature = "enterprise")]
pub fn set_mg_options(&mut self, options: &MgOptions) -> Result<()> {
options.validate()?;
let json = serde_json::to_string(options).context(error::SerializeSnafu)?;
self.metadata.insert(MG_KEY.to_string(), json);
Ok(())
}
/// Removes only MG options.
#[cfg(feature = "enterprise")]
pub fn unset_mg_options(&mut self) {
self.metadata.remove(MG_KEY);
}
/// Retrieves the SST compression options for the column.
pub fn compression_options(&self) -> Result<Option<CompressionOptions>> {
match self.metadata.get(COMPRESSION_KEY) {
@@ -1350,6 +1451,30 @@ mod tests {
assert_eq!(column_schema, new_column_schema);
}
#[test]
fn test_column_schema_preserves_sketch_metadata() {
let metadata = Metadata::from([
(
"greptime:hll".to_string(),
r#"{"precision":10}"#.to_string(),
),
("greptime:kll".to_string(), r#"{"capacity":64}"#.to_string()),
(
"greptime:mg".to_string(),
r#"{"max-counters":64}"#.to_string(),
),
]);
let column = ColumnSchema::new("v", ConcreteDataType::int64_datatype(), true)
.with_metadata(metadata.clone());
let field = Field::try_from(&column).unwrap();
assert_eq!(&metadata, field.metadata());
assert_eq!(column, ColumnSchema::try_from(&field).unwrap());
assert_eq!(
column,
serde_json::from_str::<ColumnSchema>(&serde_json::to_string(&column).unwrap()).unwrap()
);
}
#[test]
fn test_column_schema_with_duplicate_metadata() {
let metadata = Metadata::from([(DEFAULT_CONSTRAINT_KEY.to_string(), "v1".to_string())]);
+316
View File
@@ -0,0 +1,316 @@
// Copyright 2023-2026 GrepTime Inc.
//
// This file is part of the GreptimeDB Enterprise Edition and is licensed under
// the GreptimeDB Enterprise License. You may not use this file except in
// compliance with that license. A copy of the license is available at the root
// of this repository in the file LICENSE-ENTERPRISE.
//
// Unless required by applicable law or agreed to in writing, this software is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
// either express or implied.
use serde::{Deserialize, Deserializer, Serialize};
use snafu::ensure;
use sqlparser_derive::{Visit, VisitMut};
use crate::error::{InvalidSketchOptionSnafu, Result};
/// HLL options for a column. Metadata presence enables the algorithm.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Visit, VisitMut)]
#[serde(default, rename_all = "kebab-case")]
pub struct HllOptions {
/// Base-two logarithm of the register count, in 4..=18; defaults to 10.
#[serde(deserialize_with = "deserialize_hll_precision")]
pub precision: u8,
}
impl HllOptions {
/// Validates the supported algorithm parameter range.
pub fn validate(&self) -> Result<()> {
ensure!(
(4..=18).contains(&self.precision),
InvalidSketchOptionSnafu {
msg: format!("HLL precision must be in 4..=18, got {}", self.precision)
}
);
Ok(())
}
}
impl Default for HllOptions {
fn default() -> Self {
Self { precision: 10 }
}
}
/// KLL options for a column. Metadata presence enables the algorithm.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Visit, VisitMut)]
#[serde(default, rename_all = "kebab-case")]
pub struct KllOptions {
/// Per-level capacity parameter, at least 8; defaults to 64.
#[serde(deserialize_with = "deserialize_kll_capacity")]
pub capacity: u16,
}
impl KllOptions {
/// Validates the supported algorithm parameter range.
pub fn validate(&self) -> Result<()> {
ensure!(
self.capacity >= 8,
InvalidSketchOptionSnafu {
msg: format!("KLL capacity must be at least 8, got {}", self.capacity)
}
);
Ok(())
}
}
impl Default for KllOptions {
fn default() -> Self {
Self { capacity: 64 }
}
}
/// MG options for a column. Metadata presence enables the algorithm.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Visit, VisitMut)]
#[serde(default, rename_all = "kebab-case")]
pub struct MgOptions {
/// Maximum number of counters, greater than zero; defaults to 64.
#[serde(deserialize_with = "deserialize_mg_max_counters")]
pub max_counters: u32,
}
impl MgOptions {
/// Validates the supported algorithm parameter range.
pub fn validate(&self) -> Result<()> {
ensure!(
self.max_counters > 0,
InvalidSketchOptionSnafu {
msg: format!(
"MG max_counters must be positive, got {}",
self.max_counters
)
}
);
Ok(())
}
}
impl Default for MgOptions {
fn default() -> Self {
Self { max_counters: 64 }
}
}
fn deserialize_hll_precision<'de, D: Deserializer<'de>>(
deserializer: D,
) -> std::result::Result<u8, D::Error> {
let precision = u8::deserialize(deserializer)?;
HllOptions { precision }
.validate()
.map_err(serde::de::Error::custom)?;
Ok(precision)
}
fn deserialize_kll_capacity<'de, D: Deserializer<'de>>(
deserializer: D,
) -> std::result::Result<u16, D::Error> {
let capacity = u16::deserialize(deserializer)?;
KllOptions { capacity }
.validate()
.map_err(serde::de::Error::custom)?;
Ok(capacity)
}
fn deserialize_mg_max_counters<'de, D: Deserializer<'de>>(
deserializer: D,
) -> std::result::Result<u32, D::Error> {
let max_counters = u32::deserialize(deserializer)?;
MgOptions { max_counters }
.validate()
.map_err(serde::de::Error::custom)?;
Ok(max_counters)
}
#[cfg(test)]
mod tests {
use arrow::datatypes::Field;
use super::*;
use crate::data_type::ConcreteDataType;
use crate::schema::{ColumnSchema, HLL_KEY, KLL_KEY, MG_KEY};
#[test]
fn test_defaults_and_parameter_validation() {
assert_eq!(
HllOptions::default(),
serde_json::from_str::<HllOptions>("{}").unwrap()
);
assert_eq!(
KllOptions::default(),
serde_json::from_str::<KllOptions>("{}").unwrap()
);
assert_eq!(
MgOptions::default(),
serde_json::from_str::<MgOptions>("{}").unwrap()
);
for precision in [4, 10, 18] {
let options = HllOptions { precision };
assert_eq!(
options,
serde_json::from_str::<HllOptions>(&serde_json::to_string(&options).unwrap())
.unwrap()
);
}
for precision in [0, 3, 19, 255] {
assert!(
serde_json::from_str::<HllOptions>(&format!(r#"{{"precision":{precision}}}"#))
.is_err()
);
}
for capacity in [0, 7] {
assert!(
serde_json::from_str::<KllOptions>(&format!(r#"{{"capacity":{capacity}}}"#))
.is_err()
);
}
assert!(serde_json::from_str::<MgOptions>(r#"{"max-counters":0}"#).is_err());
assert!(serde_json::from_str::<MgOptions>(r#"{"max-counters":4294967296}"#).is_err());
for capacity in [8, u16::MAX] {
let options = KllOptions { capacity };
assert_eq!(
options,
serde_json::from_str::<KllOptions>(&serde_json::to_string(&options).unwrap())
.unwrap()
);
}
for capacity in [1, u32::MAX] {
let options = MgOptions {
max_counters: capacity,
};
assert_eq!(
options,
serde_json::from_str::<MgOptions>(&serde_json::to_string(&options).unwrap())
.unwrap()
);
}
}
#[test]
fn test_independent_metadata_and_roundtrip() {
let mut column = ColumnSchema::new("v", ConcreteDataType::int64_datatype(), true);
assert_eq!(None, column.hll_options().unwrap());
assert_eq!(None, column.kll_options().unwrap());
assert_eq!(None, column.mg_options().unwrap());
column = column
.with_hll_options(HllOptions::default())
.unwrap()
.with_kll_options(KllOptions::default())
.unwrap()
.with_mg_options(MgOptions::default())
.unwrap();
let field = Field::try_from(&column).unwrap();
assert_eq!(field.metadata()[HLL_KEY], r#"{"precision":10}"#);
assert_eq!(field.metadata()[KLL_KEY], r#"{"capacity":64}"#);
assert_eq!(field.metadata()[MG_KEY], r#"{"max-counters":64}"#);
assert_eq!(column, ColumnSchema::try_from(&field).unwrap());
assert_eq!(
column,
serde_json::from_str::<ColumnSchema>(&serde_json::to_string(&column).unwrap()).unwrap()
);
let before = column.clone();
assert!(
column
.set_hll_options(&HllOptions { precision: 3 })
.is_err()
);
assert!(column.set_kll_options(&KllOptions { capacity: 7 }).is_err());
assert!(
column
.set_mg_options(&MgOptions { max_counters: 0 })
.is_err()
);
assert_eq!(before, column);
column
.set_hll_options(&HllOptions { precision: 12 })
.unwrap();
column
.set_kll_options(&KllOptions { capacity: 128 })
.unwrap();
column
.set_mg_options(&MgOptions { max_counters: 256 })
.unwrap();
assert_eq!(
Some(HllOptions { precision: 12 }),
column.hll_options().unwrap()
);
assert_eq!(
Some(KllOptions { capacity: 128 }),
column.kll_options().unwrap()
);
assert_eq!(
Some(MgOptions { max_counters: 256 }),
column.mg_options().unwrap()
);
column.unset_hll_options();
assert_eq!(None, column.hll_options().unwrap());
assert_eq!(
Some(KllOptions { capacity: 128 }),
column.kll_options().unwrap()
);
assert_eq!(
Some(MgOptions { max_counters: 256 }),
column.mg_options().unwrap()
);
column.unset_kll_options();
assert_eq!(None, column.kll_options().unwrap());
assert_eq!(
Some(MgOptions { max_counters: 256 }),
column.mg_options().unwrap()
);
column.unset_mg_options();
assert_eq!(None, column.mg_options().unwrap());
}
#[test]
fn test_invalid_persisted_options_are_rejected_by_getters() {
let column = ColumnSchema::new("v", ConcreteDataType::int64_datatype(), true);
let field = Field::try_from(&column).unwrap().with_metadata(
[
(HLL_KEY.to_string(), r#"{"precision":19}"#.to_string()),
(KLL_KEY.to_string(), r#"{"capacity":0}"#.to_string()),
(MG_KEY.to_string(), "malformed json".to_string()),
]
.into(),
);
let column = ColumnSchema::try_from(&field).unwrap();
assert!(column.hll_options().is_err());
assert!(column.kll_options().is_err());
assert!(column.mg_options().is_err());
}
#[test]
fn test_mg_max_counters_serialization() {
let expected = MgOptions { max_counters: 128 };
assert_eq!(
expected,
serde_json::from_str::<MgOptions>(r#"{"max-counters":128}"#).unwrap()
);
assert_eq!(
r#"{"max-counters":128}"#,
serde_json::to_string(&expected).unwrap()
);
assert!(serde_json::from_str::<MgOptions>(r#"{"max-counters":0}"#).is_err());
}
#[test]
fn test_validation_errors_include_values() {
for (error, value) in [
(HllOptions { precision: 19 }.validate().unwrap_err(), "19"),
(KllOptions { capacity: 7 }.validate().unwrap_err(), "7"),
(MgOptions { max_counters: 0 }.validate().unwrap_err(), "0"),
] {
assert!(error.to_string().contains(value), "{error}");
}
}
}
+116 -111
View File
@@ -14,12 +14,11 @@
use std::collections::BTreeMap;
use std::fmt::{Debug, Display, Formatter};
use std::sync::{Arc, LazyLock};
use std::sync::Arc;
use arrow::datatypes::DataType as ArrowDataType;
use arrow_schema::{Field, Fields};
use common_base::bytes::Bytes;
use regex::{Captures, Regex};
use serde::{Deserialize, Serialize};
use crate::Error;
@@ -389,16 +388,35 @@ impl Display for JsonType {
}
/// Converts a json type value to string
///
/// The binary jsonb is serialized directly with `serde_json`, so both object keys and
/// string values are escaped by `serde_json`. `RawJsonb::to_string()` is deliberately
/// avoided, since it falls back to the lossy raw bytes when serialization fails.
///
/// Some write paths (e.g. `COPY FROM` csv/json/parquet files, or a JSON parameter bound
/// as text through the MySQL protocol) currently store the JSON *text* as the column
/// bytes instead of binary jsonb, and such data may already be persisted. When the bytes
/// are not valid jsonb but are valid JSON text, they are re-encoded as jsonb and then
/// serialized the same way, so the output is still escaped by `serde_json`. Anything else
/// is reported as an error.
pub fn jsonb_to_string(val: &[u8]) -> Result<String> {
if val.is_empty() {
return Ok("".to_string());
}
match jsonb::from_slice(val) {
Ok(jsonb_value) => {
let serialized = jsonb_value.to_string();
fix_unicode_point(&serialized)
}
Err(e) => InvalidJsonbSnafu { error: e }.fail(),
match serde_json::to_string(&jsonb::RawJsonb::new(val)) {
Ok(s) => Ok(s),
Err(e) => match jsonb::parse_value_standard_mode(val) {
Ok(json) => serde_json::to_string(&jsonb::RawJsonb::new(&json.to_vec())).map_err(|e| {
InvalidJsonSnafu {
value: e.to_string(),
}
.build()
}),
Err(_) => InvalidJsonSnafu {
value: e.to_string(),
}
.fail(),
},
}
}
@@ -409,59 +427,6 @@ pub fn jsonb_to_serde_json(val: &[u8]) -> Result<serde_json::Value> {
.map_err(|error| InvalidJsonbSnafu { error }.build())
}
/// Normalizes a JSON string by converting Rust-style Unicode escape sequences to JSON-compatible format.
///
/// The input is scanned for Rust-style Unicode code
/// point escapes of the form `\\u{H...}` (a backslash, `u`, an opening brace,
/// followed by 1–6 hexadecimal digits, and a closing brace). Each such escape is
/// converted into JSON-compatible UTF‑16 escape sequences:
///
/// - For code points in the Basic Multilingual Plane (≤ `0xFFFF`), the escape is
/// converted to a single JSON `\\uXXXX` sequence with four uppercase hex digits.
/// - For code points above `0xFFFF` and less than Unicode max code point `0x10FFFF`,
/// the code point is encoded as a UTF‑16 surrogate pair and emitted as two consecutive
/// `\\uXXXX` sequences (as JSON format required).
///
/// After this normalization, the function returns the normalized string
fn fix_unicode_point(json: &str) -> Result<String> {
static UNICODE_CODE_POINT_PATTERN: LazyLock<Regex> = LazyLock::new(|| {
// Match literal "\u{...}" sequences, capturing 1–6 (code point range) hex digits
// inside braces.
Regex::new(r"\\u\{([0-9a-fA-F]{1,6})}").unwrap_or_else(|e| panic!("{}", e))
});
let v = UNICODE_CODE_POINT_PATTERN.replace_all(json, |caps: &Captures| {
// Extract the hex payload (without braces) and parse to a code point.
let hex = &caps[1];
let Ok(code) = u32::from_str_radix(hex, 16) else {
// On parse failure, leave the original escape sequence unchanged.
return caps[0].to_string();
};
if code <= 0xFFFF {
// Basic Multilingual Plane: JSON can represent this directly as \uXXXX.
format!("\\u{:04X}", code)
} else if code > 0x10FFFF {
// Beyond max Unicode code point
caps[0].to_string()
} else {
// Supplementary planes: JSON needs UTF-16 surrogate pairs.
// Convert the code point to a 20-bit value.
let code = code - 0x10000;
// High surrogate: top 10 bits, offset by 0xD800.
let high = 0xD800 + ((code >> 10) & 0x3FF);
// Low surrogate: bottom 10 bits, offset by 0xDC00.
let low = 0xDC00 + (code & 0x3FF);
// Emit two \uXXXX escapes in sequence.
format!("\\u{:04X}\\u{:04X}", high, low)
}
});
Ok(v.to_string())
}
/// Parses a string to a json type value
pub fn parse_string_to_jsonb(s: &str) -> Result<Vec<u8>> {
jsonb::parse_value_standard_mode(s.as_bytes())
@@ -488,60 +453,100 @@ mod tests {
Ok(())
}
use super::*;
#[test]
fn test_fix_unicode_point() -> Result<()> {
let valid_cases = vec![
(r#"{"data": "simple ascii"}"#, r#"{"data": "simple ascii"}"#),
(
r#"{"data":"Greek sigma: \u{03a3}"}"#,
r#"{"data":"Greek sigma: \u03A3"}"#,
),
(
r#"{"data":"Joker card: \u{1f0df}"}"#,
r#"{"data":"Joker card: \uD83C\uDCDF"}"#,
),
(
r#"{"data":"BMP boundary: \u{ffff}"}"#,
r#"{"data":"BMP boundary: \uFFFF"}"#,
),
(
r#"{"data":"Supplementary min: \u{10000}"}"#,
r#"{"data":"Supplementary min: \uD800\uDC00"}"#,
),
(
r#"{"data":"Supplementary max: \u{10ffff}"}"#,
r#"{"data":"Supplementary max: \uDBFF\uDFFF"}"#,
),
];
for (input, expect) in valid_cases {
let v = fix_unicode_point(input)?;
assert_eq!(v, expect);
}
let invalid_escape_cases = vec![
(
r#"{"data": "Invalid hex: \u{gggg}"}"#,
r#"{"data": "Invalid hex: \u{gggg}"}"#,
),
(
r#"{"data": "Empty braces: \u{}"}"#,
r#"{"data": "Empty braces: \u{}"}"#,
),
(
r#"{"data": "Out of range: \u{1100000}"}"#,
r#"{"data": "Out of range: \u{1100000}"}"#,
),
];
for (input, expect) in invalid_escape_cases {
let v = fix_unicode_point(input)?;
assert_eq!(v, expect);
}
fn test_jsonb_to_string_escapes_object_keys()
-> std::result::Result<(), Box<dyn std::error::Error>> {
let expected = serde_json::json!({
"": 1,
"a\"b": {"c\\d": ["x", {"e\nf\tg\u{1}": true}], "h": null},
"plain": "v\"q",
});
let input = expected.to_string();
let value = jsonb::parse_value(input.as_bytes()).map_err(|e| e.to_string())?;
let text = jsonb_to_string(&value.to_vec())?;
assert_eq!(serde_json::from_str::<serde_json::Value>(&text)?, expected);
assert!(text.contains(r#""a\"b":"#), "{text}");
Ok(())
}
#[test]
fn test_jsonb_to_string_preserves_literal_unicode_escape_key() {
let input = r#"{"\\u{1f600}":"value"}"#;
let bytes = parse_string_to_jsonb(input).unwrap();
let text = jsonb_to_string(&bytes).unwrap();
assert_eq!(
serde_json::from_str::<serde_json::Value>(&text).unwrap(),
serde_json::from_str::<serde_json::Value>(input).unwrap(),
);
// A BMP literal key round-trips unchanged as well.
let input = r#"{"\\u{41}":"value"}"#;
let bytes = parse_string_to_jsonb(input).unwrap();
let text = jsonb_to_string(&bytes).unwrap();
assert_eq!(text, input);
}
#[test]
fn test_jsonb_to_string_escapes_string_values() {
// Literal `\u{...}` text and a NUL in a value must still render as valid JSON
// that round-trips to the same value.
for input in [
r#"{"k":"\\u{1f600}"}"#,
r#"{"k":"\\u{41}"}"#,
r#"{"k":"a\u0000b"}"#,
r#"["\\u{1f600}","\u0000"]"#,
] {
let bytes = parse_string_to_jsonb(input).unwrap();
let text = jsonb_to_string(&bytes).unwrap();
assert_eq!(
serde_json::from_str::<serde_json::Value>(&text).unwrap(),
serde_json::from_str::<serde_json::Value>(input).unwrap(),
"{input} -> {text}"
);
}
// U+2028 is emitted as-is, which is still valid JSON.
let bytes = parse_string_to_jsonb("{\"k\":\"a\\u2028b\"}").unwrap();
assert_eq!(jsonb_to_string(&bytes).unwrap(), "{\"k\":\"a\u{2028}b\"}");
}
#[test]
fn test_jsonb_to_string_rejects_invalid_jsonb() {
assert!(jsonb_to_string(&[1, 2, 3, 4]).is_err());
assert_eq!(jsonb_to_string(&[]).unwrap(), "");
}
#[test]
fn test_jsonb_to_string_accepts_json_text_bytes() {
// Bytes written as JSON text rather than binary jsonb (e.g. by `COPY FROM`).
assert_eq!(
jsonb_to_string(br#"{"foo":"bar"}"#).unwrap(),
r#"{"foo":"bar"}"#
);
assert_eq!(
jsonb_to_string(br#"{"a":null, "foo":"bar"}"#).unwrap(),
r#"{"a":null,"foo":"bar"}"#
);
// Keys and values coming from text are still escaped by serde_json.
assert_eq!(
jsonb_to_string(br#"{"a\"b":"c\u0000d"}"#).unwrap(),
r#"{"a\"b":"c\u0000d"}"#
);
assert!(jsonb_to_string(b"{not json").is_err());
}
#[test]
fn test_jsonb_to_string_keeps_compact_format() -> Result<()> {
let value = jsonb::parse_value(br#"{"b": [1, 2.5, "x"], "a": {"c": false}}"#).unwrap();
assert_eq!(
jsonb_to_string(&value.to_vec())?,
r#"{"a":{"c":false},"b":[1,2.5,"x"]}"#
);
Ok(())
}
use super::*;
#[test]
fn test_json_type_include() {
fn test(this: &JsonNativeType, that: &JsonNativeType, expected: bool) {
+1
View File
@@ -644,6 +644,7 @@ mod test {
data_type: ConcreteDataType::string_datatype(),
inverted_index: false,
skipping_index: None,
fulltext_index: None,
}],
Some(0),
)?;
@@ -1062,18 +1062,21 @@ mod tests {
data_type: ConcreteDataType::string_datatype(),
inverted_index: false,
skipping_index: None,
fulltext_index: None,
},
JsonTypeHint {
path: vec!["commit".to_string(), "operation".to_string()],
data_type: ConcreteDataType::string_datatype(),
inverted_index: false,
skipping_index: None,
fulltext_index: None,
},
JsonTypeHint {
path: vec!["time_us".to_string()],
data_type: ConcreteDataType::int64_datatype(),
inverted_index: false,
skipping_index: None,
fulltext_index: None,
},
],
Some(0),
@@ -1170,6 +1173,7 @@ mod tests {
data_type: ConcreteDataType::string_datatype(),
inverted_index: false,
skipping_index: None,
fulltext_index: None,
}],
Some(2),
)?;
@@ -1336,6 +1340,7 @@ mod tests {
data_type: ConcreteDataType::string_datatype(),
inverted_index: false,
skipping_index: None,
fulltext_index: None,
}],
Some(8),
)?;
+107 -40
View File
@@ -26,6 +26,7 @@ use common_grpc::channel_manager::{ChannelConfig, ChannelManager, load_client_tl
use common_meta::peer::{Peer, PeerDiscovery};
use common_query::{Output, OutputData};
use common_telemetry::warn;
use common_time::Timezone;
use futures::stream::{FuturesUnordered, StreamExt};
use meta_client::client::MetaClient;
use query::datafusion::QUERY_PARALLELISM_HINT;
@@ -363,7 +364,10 @@ impl FrontendClient {
})
}
/// Execute a SQL statement on the frontend.
/// Executes SQL with optional Flow budget extensions and an optional
/// timezone override.
///
/// `timezone`, when set, overrides the session timezone for this statement.
///
/// `extensions` are forwarded to the executing frontend exactly like
/// `query_with_terminal_metrics` does: as query context extensions in
@@ -382,10 +386,14 @@ impl FrontendClient {
schema: &str,
sql: &str,
extensions: &[(&str, &str)],
timezone: Option<Timezone>,
) -> Result<Output, Error> {
match self {
FrontendClient::Distributed { .. } => {
let db = self.get_random_active_frontend(catalog, schema).await?;
let mut db = self.get_random_active_frontend(catalog, schema).await?;
if let Some(timezone) = timezone {
db.database.set_timezone(timezone.to_string());
}
db.database
.flight_request()
.with_flow_extensions(extensions)
@@ -397,46 +405,46 @@ impl FrontendClient {
FrontendClient::Standalone {
database_client, ..
} => {
let extensions = HashMap::from_iter(
extensions
.iter()
.map(|(key, value)| ((*key).to_string(), (*value).to_string())),
);
let ctx = QueryContextBuilder::default()
// Each request gets fresh query state, including read snapshots.
let mut ctx = QueryContextBuilder::default()
.current_catalog(catalog.to_string())
.current_schema(schema.to_string())
.extensions(extensions)
.build();
let ctx = Arc::new(ctx);
{
let database_client = {
database_client
.handler
.lock()
.map_err(|e| {
UnexpectedSnafu {
reason: format!("Failed to lock database client: {e}"),
}
.build()
})?
.as_ref()
.context(UnexpectedSnafu {
reason: "Standalone's frontend instance is not set",
})?
.upgrade()
.context(UnexpectedSnafu {
reason: "Failed to upgrade database client",
})?
};
let req = Request::Query(QueryRequest {
query: Some(Query::Sql(sql.to_string())),
});
database_client
.do_query(req, ctx)
.await
.map_err(BoxedError::new)
.context(ExternalSnafu)
.extensions(HashMap::from_iter(
extensions
.iter()
.map(|(key, value)| ((*key).to_string(), (*value).to_string())),
));
if let Some(timezone) = timezone {
ctx = ctx.timezone(timezone);
}
let ctx = Arc::new(ctx.build());
let database_client = {
database_client
.handler
.lock()
.map_err(|e| {
UnexpectedSnafu {
reason: format!("Failed to lock database client: {e}"),
}
.build()
})?
.as_ref()
.context(UnexpectedSnafu {
reason: "Standalone's frontend instance is not set",
})?
.upgrade()
.context(UnexpectedSnafu {
reason: "Failed to upgrade database client",
})?
};
let req = Request::Query(QueryRequest {
query: Some(Query::Sql(sql.to_string())),
});
database_client
.do_query(req, ctx)
.await
.map_err(BoxedError::new)
.context(ExternalSnafu)
}
}
}
@@ -1138,6 +1146,64 @@ mod tests {
(addr, server)
}
#[tokio::test]
async fn test_sql_timezone_and_fresh_context() {
struct ContextHandler {
expected_timezone: Timezone,
contexts: Mutex<Vec<QueryContextRef>>,
}
#[async_trait::async_trait]
impl GrpcQueryHandlerWithBoxedError for ContextHandler {
async fn do_query(
&self,
request: Request,
ctx: QueryContextRef,
) -> std::result::Result<Output, BoxedError> {
assert_eq!(ctx.current_catalog(), "test_catalog");
assert_eq!(ctx.current_schema(), "test_schema");
assert_eq!(ctx.timezone(), self.expected_timezone);
assert!(ctx.snapshots().is_empty());
ctx.set_snapshot(1, 42);
self.contexts.lock().unwrap().push(ctx);
assert!(matches!(request, Request::Query(QueryRequest {
query: Some(Query::Sql(sql)),
}) if sql == "SELECT to_unixtime('2026-01-01 00:00:00')"));
Ok(Output::new_with_affected_rows(0))
}
}
for timezone in [None, Some("UTC"), Some("+08:00")] {
let timezone = timezone.map(|tz| Timezone::from_tz_string(tz).unwrap());
let handler = Arc::new(ContextHandler {
expected_timezone: timezone
.clone()
.unwrap_or_else(|| QueryContextBuilder::default().build().timezone()),
contexts: Mutex::new(Vec::new()),
});
let grpc_handler: Arc<dyn GrpcQueryHandlerWithBoxedError> = handler.clone();
let client = FrontendClient::from_grpc_handler(
Arc::downgrade(&grpc_handler),
QueryOptions::default(),
);
for _ in 0..2 {
client
.sql(
"test_catalog",
"test_schema",
"SELECT to_unixtime('2026-01-01 00:00:00')",
&[],
timezone.clone(),
)
.await
.unwrap();
}
let contexts = handler.contexts.lock().unwrap();
assert_eq!(contexts.len(), 2);
assert!(!Arc::ptr_eq(&contexts[0], &contexts[1]));
}
}
#[tokio::test]
async fn wait_initialized() {
let (client, handler_mut) =
@@ -1229,6 +1295,7 @@ mod tests {
(query::options::FLOW_MAX_MEMORY_BYTES, "536870912"),
(query::options::FLOW_ID, "7"),
],
None,
)
.await
.unwrap();
@@ -1267,7 +1334,7 @@ mod tests {
FrontendClient::from_grpc_handler(Arc::downgrade(&handler), QueryOptions::default());
client
.sql("greptime", "public", "select 1", &[])
.sql("greptime", "public", "select 1", &[], None)
.await
.unwrap();
+4
View File
@@ -28,6 +28,7 @@ remote datanodes via `operator`/`client`.
| `instance/builder` | `src/frontend/src/instance/builder.rs` | `FrontendBuilder` assembles `Instance` from its dependencies |
| `instance/grpc` | `src/frontend/src/instance/grpc.rs` | `GrpcQueryHandler`: insert/delete/query/promql over gRPC |
| `instance/region_query` | `src/frontend/src/instance/region_query.rs` | Routes distributed region reads to datanodes |
| `instance/exemplar` | `src/frontend/src/instance/exemplar.rs` | Resolves and authorizes selector branches before bounded exemplar-table scans |
| `instance/*` | `src/frontend/src/instance/` | Per-protocol handlers (`influxdb.rs`, `promql.rs`, `otlp/`, `jaeger.rs`, `logs.rs`, `prom_store.rs`, ...) |
| `frontend` | `src/frontend/src/frontend.rs` | `Frontend` lifecycle wrapper (`FrontendOptions`, start/shutdown) |
| `server` | `src/frontend/src/server.rs` | `Services`: builds and wires the protocol servers |
@@ -42,6 +43,9 @@ including caches owned by pipeline and protocol handlers.
- **SQL query** (`instance.rs`): `do_query_inner` handles parsing, interceptors,
permission checks, timeout/cancellation, and delegates planning/execution to
`StatementExecutor`. Distributed scans enter through `region_query.rs`.
- **Exemplar query** (`instance/exemplar.rs`): authorize all selector branches
before calling `PromQueryInterceptor::pre_execute_exemplars` for each resolved
exemplar table, with that table's schema context, before scanning it.
- **Logical-table batch DDL** (`instance.rs`): dedicated SQL handler → bounded
parse/interception → all-member permissions → operator CREATE preparation →
one logical-table batch procedure. Keep pre-submission validation side-effect free.
+5 -2
View File
@@ -335,12 +335,15 @@ mod tests {
}
#[test]
fn test_pipeline_host_access_config() {
fn test_pipeline_config() {
let defaults: FrontendOptions = toml::from_str("").unwrap();
assert!(!defaults.pipeline.allow_vrl_host_access);
assert!(!defaults.pipeline.ignore_errors);
let options: FrontendOptions =
toml::from_str("[pipeline]\nallow_vrl_host_access = true").unwrap();
toml::from_str("[pipeline]\nallow_vrl_host_access = true\nignore_errors = true")
.unwrap();
assert!(options.pipeline.allow_vrl_host_access);
assert!(options.pipeline.ignore_errors);
let serialized = toml::to_string(&options).unwrap();
let restored: FrontendOptions = toml::from_str(&serialized).unwrap();
assert_eq!(options.pipeline, restored.pipeline);
+14
View File
@@ -16,6 +16,7 @@ pub mod builder;
mod copy_in;
mod dashboard;
mod entity_graph;
mod exemplar;
mod export_database;
mod grpc;
mod import_packed;
@@ -1129,6 +1130,11 @@ impl SqlQueryHandler for Instance {
stmt: Option<Statement>,
query_ctx: QueryContextRef,
) -> server_error::Result<Output> {
// Prepared statements reach here with a plan built before their current execution.
let plan = query::plan::refresh_partition_columns(plan, &self.catalog_manager, &query_ctx)
.await
.map_err(BoxedError::new)
.context(server_error::ExecutePlanSnafu)?;
self.do_exec_plan_inner(plan, stmt, query_ctx)
.await
.map_err(BoxedError::new)
@@ -1306,6 +1312,14 @@ impl Instance {
#[async_trait]
impl PrometheusHandler for Instance {
async fn query_exemplars(
&self,
query: servers::exemplar::query::Query,
ctx: QueryContextRef,
) -> server_error::Result<Vec<servers::exemplar::query::Series>> {
self.query_exemplars_inner(query, ctx).await
}
#[tracing::instrument(skip_all)]
async fn do_query(
&self,
+488
View File
@@ -0,0 +1,488 @@
// 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.
use std::collections::{BTreeMap, BTreeSet};
use std::sync::Arc;
use auth::{PermissionTableTarget, PermissionTableTargets};
use common_base::cancellation::CancellableFuture;
use common_catalog::consts::METRICS_EXEMPLARS_TABLE;
use common_error::ext::BoxedError;
use common_query::OutputData;
use common_query::prelude::{
EXEMPLAR_LABELS_COLUMN, EXEMPLAR_METRIC_COLUMN, greptime_timestamp, greptime_value,
};
use common_query::prometheus::format_prometheus_float;
use common_recordbatch::RecordBatch;
use common_time::{Timestamp, timestamp::TimeUnit};
use datafusion::common::{Column, ScalarValue};
use datafusion::execution::memory_pool::{MemoryConsumer, MemoryReservation};
use datafusion_expr::{BinaryExpr, Expr, Operator, lit};
use datatypes::arrow::datatypes::DataType;
use datatypes::data_type::ConcreteDataType;
use datatypes::value::Value;
use datatypes::vectors::json::array::JsonArray;
use datatypes::vectors::{Helper, VectorRef};
use futures::StreamExt;
use promql_parser::label::{METRIC_NAME, MatchOp, Matcher};
use servers::error::{self, Result};
use servers::exemplar::query::{Observation, Query, Selector, Series};
use servers::interceptor::{PromQueryInterceptor, PromQueryInterceptorRef};
use servers::prometheus_handler::PrometheusHandler;
use session::context::QueryContextRef;
use snafu::{OptionExt, ResultExt, ensure};
use store_api::metric_engine_consts::{
DATA_SCHEMA_TABLE_ID_COLUMN_NAME, DATA_SCHEMA_TSID_COLUMN_NAME,
};
use table::metadata::TableInfo;
use crate::instance::Instance;
type Labels = BTreeMap<String, String>;
// Retain NaN payloads and signed zero as distinct observations, using their stored bits.
type Observations = BTreeMap<Labels, BTreeMap<(i64, u64, Labels), Observation>>;
impl Instance {
pub(super) async fn query_exemplars_inner(
&self,
query: Query,
ctx: QueryContextRef,
) -> Result<Vec<Series>> {
self.check_prom_query_privilege(&ctx)?;
let interceptor = self.plugins.get::<PromQueryInterceptorRef<error::Error>>();
let mut groups = BTreeMap::<String, Vec<&Selector>>::new();
for selector in &query.selectors {
groups
.entry(selector.schema.clone())
.or_default()
.push(selector);
}
// Authorizes every branch before any exemplar scan, including absent destinations.
for (schema, selectors) in &groups {
let local = ctx.fork();
local.set_current_schema(schema);
let local = Arc::new(local);
let mut targets = vec![PermissionTableTarget::new(
ctx.current_catalog(),
schema,
METRICS_EXEMPLARS_TABLE,
)];
for selector in selectors {
let sources = selector
.matchers
.iter()
.filter(|matcher| {
matcher.name == METRIC_NAME
&& matches!(matcher.op, MatchOp::Equal)
&& !matcher.value.is_empty()
})
.map(|matcher| &matcher.value)
.collect::<BTreeSet<_>>();
if sources.is_empty() {
self.check_query_target_permission(PermissionTableTargets::Unresolved, &local)
.await?;
}
targets.extend(sources.into_iter().map(|source| {
PermissionTableTarget::new(ctx.current_catalog(), schema, source)
}));
}
self.check_query_target_permission(PermissionTableTargets::resolved(targets), &local)
.await?;
}
let ticket = self.process_manager.register_query(
ctx.current_catalog().to_string(),
groups.keys().cloned().collect(),
format!("query_exemplars({})", query.expression),
ctx.conn_info().to_string(),
Some(ctx.process_id()),
None,
);
let cancellation = ticket.cancellation_handle.clone();
let future = async {
let pool = self
.query_engine
.engine_state()
.session_state()
.runtime_env()
.memory_pool
.clone();
let mut reservation =
MemoryConsumer::new("Prometheus exemplar response").register(&pool);
let mut observations = Observations::new();
let mut skipped = 0;
for (schema, selectors) in groups {
let local = ctx.fork();
local.set_current_schema(&schema);
let local = Arc::new(local);
let Some(table) = self
.catalog_manager
.table(
ctx.current_catalog(),
&schema,
METRICS_EXEMPLARS_TABLE,
Some(&local),
)
.await
.map_err(BoxedError::new)
.context(error::ExecuteQuerySnafu)?
else {
continue;
};
let info = table.table_info();
operator::insert::validate_exemplar_table(&info)
.map_err(BoxedError::new)
.context(error::ExecuteQuerySnafu)?;
let filter = filter(&info, &selectors, query.bounds)?;
let frame = self
.query_engine
.read_table(table)
.map_err(BoxedError::new)
.context(error::ExecuteQuerySnafu)?;
let plan = frame
.filter(filter)
.context(error::DataFusionSnafu)?
.into_unoptimized_plan();
interceptor.pre_execute_exemplars(&query, info.table_ref(), local.clone())?;
let output = self
.statement_executor
.exec_plan(plan, local)
.await
.map_err(BoxedError::new)
.context(error::ExecuteQuerySnafu)?;
match output.data {
OutputData::Stream(mut stream) => {
while let Some(batch) = stream.next().await {
skipped += collect(
batch.context(error::CollectRecordbatchSnafu)?,
&info,
&mut observations,
&mut reservation,
)?;
tokio::task::yield_now().await;
}
}
OutputData::RecordBatches(batches) => {
for batch in batches.take() {
skipped += collect(batch, &info, &mut observations, &mut reservation)?;
tokio::task::yield_now().await;
}
}
_ => {
return error::UnexpectedResultSnafu {
reason: "exemplar scan did not return rows",
}
.fail();
}
}
}
if skipped > 0 {
let warning = format!("Skipped {skipped} malformed stored exemplars");
ctx.set_warning(match ctx.warning() {
Some(existing) => format!("{existing}; {warning}"),
None => warning,
});
}
Ok(observations
.into_iter()
.map(|(series_labels, observations)| Series {
series_labels,
exemplars: observations.into_values().collect(),
})
.collect())
};
let result = CancellableFuture::new(future, cancellation)
.await
.map_err(|_| error::CancelledSnafu.build())?;
drop(ticket);
result
}
}
fn column(name: &str) -> Expr {
Expr::Column(Column::from_name(name))
}
fn filter(info: &TableInfo, selectors: &[&Selector], bounds: (i64, i64)) -> Result<Expr> {
let schema = &info.meta.schema;
let tags = info
.meta
.primary_key_indices
.iter()
.map(|index| schema.column_schemas()[*index].name.as_str())
.filter(|name| {
![
DATA_SCHEMA_TABLE_ID_COLUMN_NAME,
DATA_SCHEMA_TSID_COLUMN_NAME,
]
.contains(name)
})
.collect::<BTreeSet<_>>();
let labels = selectors
.iter()
.map(|selector| {
selector
.matchers
.iter()
.map(|matcher| matcher_filter(matcher, &tags))
.fold(lit(true), Expr::and)
})
.fold(lit(false), Expr::or);
let unit = schema
.timestamp_column()
.and_then(|column| column.data_type.as_timestamp())
.map(|t| t.unit())
.context(error::UnexpectedResultSnafu {
reason: "exemplar time index is missing",
})?;
let start = Timestamp::new_nanosecond(bounds.0)
.convert_to_ceil(unit)
.context(error::InvalidQuerySnafu {
reason: "exemplar start exceeds timestamp range",
})?;
let end = Timestamp::new_nanosecond(bounds.1)
.convert_to(unit)
.context(error::InvalidQuerySnafu {
reason: "exemplar end exceeds timestamp range",
})?;
let literal = |timestamp: Timestamp| {
Expr::Literal(
match unit {
TimeUnit::Second => ScalarValue::TimestampSecond(Some(timestamp.value()), None),
TimeUnit::Millisecond => {
ScalarValue::TimestampMillisecond(Some(timestamp.value()), None)
}
TimeUnit::Microsecond => {
ScalarValue::TimestampMicrosecond(Some(timestamp.value()), None)
}
TimeUnit::Nanosecond => {
ScalarValue::TimestampNanosecond(Some(timestamp.value()), None)
}
},
None,
)
};
Ok(labels
.and(column(greptime_timestamp()).gt_eq(literal(start)))
.and(column(greptime_timestamp()).lt_eq(literal(end))))
}
fn matcher_filter(matcher: &Matcher, tags: &BTreeSet<&str>) -> Expr {
let name = if matcher.name == METRIC_NAME {
EXEMPLAR_METRIC_COLUMN
} else {
matcher.name.as_str()
};
// Storage fields and the physical metric column are not Prometheus series labels.
if (matcher.name == EXEMPLAR_METRIC_COLUMN || !tags.contains(name))
&& matcher.name != METRIC_NAME
{
return lit(matcher.is_match(""));
}
let col = column(name);
let condition = match &matcher.op {
MatchOp::Equal => col.clone().eq(lit(matcher.value.clone())),
MatchOp::NotEqual => col.clone().not_eq(lit(matcher.value.clone())),
MatchOp::Re(regex) | MatchOp::NotRe(regex) => Expr::BinaryExpr(BinaryExpr {
left: Box::new(col.clone()),
op: if matches!(matcher.op, MatchOp::Re(_)) {
Operator::RegexMatch
} else {
Operator::RegexNotMatch
},
right: Box::new(lit(regex.as_str().to_string())),
}),
};
if matcher.is_match("") {
col.is_null().or(condition)
} else {
condition
}
}
fn collect(
batch: RecordBatch,
info: &TableInfo,
observations: &mut Observations,
reservation: &mut MemoryReservation,
) -> Result<usize> {
let memory = batch.buffer_memory_size();
reservation
.try_grow(memory)
.context(error::DataFusionSnafu)?;
let schema = batch.df_record_batch().schema();
let index = |name: &str| schema.index_of(name).context(error::ArrowSnafu);
let metric = Helper::try_into_vector(batch.column(index(EXEMPLAR_METRIC_COLUMN)?))
.map_err(BoxedError::new)
.context(error::ExecuteQuerySnafu)?;
let time = Helper::try_into_vector(batch.column(index(greptime_timestamp())?))
.map_err(BoxedError::new)
.context(error::ExecuteQuerySnafu)?;
let value = Helper::try_into_vector(batch.column(index(greptime_value())?))
.map_err(BoxedError::new)
.context(error::ExecuteQuerySnafu)?;
let value_type = |vector: &VectorRef| {
let mut data_type = vector.data_type();
// Storage may dictionary-encode tags; Vector::get returns their decoded values.
while let ConcreteDataType::Dictionary(dictionary) = data_type {
data_type = dictionary.value_type().clone();
}
data_type
};
ensure!(
value_type(&metric).is_string()
&& value_type(&time).is_timestamp()
&& value_type(&value) == ConcreteDataType::float64_datatype(),
error::UnexpectedResultSnafu {
reason: "exemplar scan returned incompatible column types",
}
);
let label_index = index(EXEMPLAR_LABELS_COLUMN)?;
let labels = JsonArray::from(batch.column(label_index))
.project_to_v2(schema.field(label_index), &DataType::Binary)
.map_err(BoxedError::new)
.context(error::ExecuteQuerySnafu)?;
let mut tags = Vec::<(&str, VectorRef)>::new();
for tag in &info.meta.primary_key_indices {
let name = info.meta.schema.column_schemas()[*tag].name.as_str();
if ![
EXEMPLAR_METRIC_COLUMN,
DATA_SCHEMA_TABLE_ID_COLUMN_NAME,
DATA_SCHEMA_TSID_COLUMN_NAME,
]
.contains(&name)
{
let values = Helper::try_into_vector(batch.column(index(name)?))
.map_err(BoxedError::new)
.context(error::ExecuteQuerySnafu)?;
ensure!(
value_type(&values).is_string(),
error::UnexpectedResultSnafu {
reason: "exemplar scan returned a non-string tag",
}
);
tags.push((name, values));
}
}
let mut skipped = 0;
'rows: for row in 0..batch.num_rows() {
let Value::String(metric) = metric.get(row) else {
skipped += 1;
continue;
};
let Value::Timestamp(timestamp) = time.get(row) else {
skipped += 1;
continue;
};
let Some(timestamp) = timestamp.convert_to(TimeUnit::Nanosecond) else {
skipped += 1;
continue;
};
let timestamp = timestamp.value();
let Value::Float64(value) = value.get(row) else {
skipped += 1;
continue;
};
let mut series = BTreeMap::from([(METRIC_NAME.to_string(), metric.into_string())]);
for (name, values) in &tags {
if let Value::String(value) = values.get(row) {
series.insert((*name).to_string(), value.into_string());
}
}
let labels = JsonArray::from(&labels)
.try_get_value(row)
.map_err(BoxedError::new)
.context(error::ExecuteQuerySnafu)?;
let serde_json::Value::Object(labels) = labels else {
skipped += 1;
continue;
};
let mut string_labels = Labels::new();
for (name, value) in labels {
let serde_json::Value::String(value) = value else {
skipped += 1;
continue 'rows;
};
string_labels.insert(name, value);
}
let labels = string_labels;
let key = (timestamp, value.0.to_bits(), labels.clone());
if observations
.get(&series)
.is_some_and(|items| items.contains_key(&key))
{
continue;
}
let bytes = 256
+ series
.iter()
.chain(&labels)
.map(|(name, value)| name.len() + value.len() + 128)
.sum::<usize>()
* 2;
reservation
.try_grow(bytes)
.context(error::DataFusionSnafu)?;
observations.entry(series).or_default().insert(
key,
Observation {
labels,
value: format_prometheus_float(value.0),
timestamp: timestamp.div_euclid(1_000_000) as f64 / 1000.0,
},
);
}
reservation.shrink(memory);
Ok(skipped)
}
#[cfg(test)]
mod tests {
use datafusion::execution::memory_pool::{GreedyMemoryPool, MemoryPool};
use datatypes::prelude::ConcreteDataType;
use datatypes::schema::{ColumnSchema, Schema};
use datatypes::vectors::Float64Vector;
use table::metadata::{TableInfoBuilder, TableMeta};
use super::*;
#[test]
fn test_exemplar_scan_batch_respects_query_memory_budget() {
let schema = Arc::new(Schema::new(vec![ColumnSchema::new(
greptime_value(),
ConcreteDataType::float64_datatype(),
false,
)]));
let batch = RecordBatch::new(
schema,
vec![Arc::new(Float64Vector::from_vec(vec![1.0; 128])) as VectorRef],
)
.unwrap();
let info = TableInfoBuilder::new(METRICS_EXEMPLARS_TABLE, TableMeta::empty())
.build()
.unwrap();
let pool: Arc<dyn MemoryPool> = Arc::new(GreedyMemoryPool::new(1));
let mut reservation = MemoryConsumer::new("exemplar test").register(&pool);
let mut observations = Observations::new();
let error = collect(batch, &info, &mut observations, &mut reservation).unwrap_err();
assert!(matches!(
error,
error::Error::DataFusion {
error: datafusion::error::DataFusionError::ResourcesExhausted(_),
..
}
));
assert!(observations.is_empty());
assert_eq!(pool.reserved(), 0);
}
}
+5 -1
View File
@@ -23,7 +23,7 @@ use auth::{
use client::Output;
use common_error::ext::BoxedError;
use datatypes::timestamp::TimestampNanosecond;
use pipeline::{Pipeline, PipelineInfo, PipelineVersion};
use pipeline::{Pipeline, PipelineInfo, PipelineOptions, PipelineVersion};
use servers::error::{
AuthSnafu, Error as ServerError, ExecuteGrpcRequestSnafu, PipelineSnafu, Result as ServerResult,
};
@@ -146,6 +146,10 @@ impl PipelineHandler for Instance {
.await
}
fn pipeline_options(&self) -> &PipelineOptions {
self.pipeline_operator.options()
}
fn build_pipeline(&self, pipeline: &str) -> ServerResult<Pipeline> {
self.pipeline_operator
.build_pipeline(pipeline)
+11 -2
View File
@@ -53,8 +53,8 @@ use session::write_progress::WriteProgress;
use snafu::{IntoError, ResultExt};
use table::requests::{
OTLP_METRIC_COMPAT_KEY, OTLP_METRIC_COMPAT_PROM, SEMANTIC_PER_TABLE_INDEX_KEY,
SEMANTIC_SIGNAL_TYPE, SEMANTIC_SOURCE, SIGNAL_TYPE_LOG, SIGNAL_TYPE_METRIC,
SOURCE_OPENTELEMETRY,
SEMANTIC_PIPELINE, SEMANTIC_SIGNAL_TYPE, SEMANTIC_SOURCE, SIGNAL_TYPE_LOG, SIGNAL_TYPE_METRIC,
SOURCE_OPENTELEMETRY, TABLE_DATA_MODEL, TABLE_DATA_MODEL_LOG_V1,
};
pub(crate) use self::trace_ingest::TraceAuxCache;
@@ -460,6 +460,15 @@ impl OpenTelemetryProtocolHandler for Instance {
let mut c = (*ctx).clone();
c.set_extension(SEMANTIC_SIGNAL_TYPE, SIGNAL_TYPE_LOG);
c.set_extension(SEMANTIC_SOURCE, SOURCE_OPENTELEMETRY);
// Only applied when the table is auto-created. The v1 rows are built only
// when the table didn't exist at read time; pipeline-defined tables have no
// built-in schema.
if matches!(pipeline, PipelineWay::OtlpLogDirect(_)) {
c.set_extension(TABLE_DATA_MODEL, TABLE_DATA_MODEL_LOG_V1);
c.set_extension(SEMANTIC_PIPELINE, TABLE_DATA_MODEL_LOG_V1);
// TODO: declare the `service` entity on `service_name` once the cost of
// scanning log tables during entity-graph derivation is measured.
}
Arc::new(c)
};
+2 -1
View File
@@ -705,7 +705,8 @@ impl PromStoreProtocolHandler for Instance {
prom_store::validate_matchers(&query.matchers)?;
}
// TODO(dennis): use read_hints to speedup query if possible
// query_to_plan intersects valid time hints with each query's outer range.
// Other hints do not change raw samples or labels.
let results = self
.handle_remote_queries(ctx, &request.queries, &query_targets)
.await?;
+316 -33
View File
@@ -14,9 +14,12 @@
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use async_trait::async_trait;
use common_error::ext::BoxedError;
use common_telemetry::warn;
use puffin::puffin_manager::{PuffinWriter, PutOptions};
use snafu::{OptionExt, ResultExt};
use tantivy::indexer::NoMergePolicy;
@@ -37,6 +40,8 @@ pub const ROWID_FIELD_NAME: &str = "greptime_fulltext_rowid";
pub struct TantivyFulltextIndexCreator {
/// The tantivy index writer.
writer: Option<IndexWriter>,
/// Retained across awaits so abort can join a cancelled finish operation.
finishing: Option<common_runtime::JoinHandle<Result<()>>>,
/// The field for the text.
text_field: tantivy::schema::Field,
@@ -47,28 +52,98 @@ pub struct TantivyFulltextIndexCreator {
/// The current max row id.
max_rowid: u64,
/// The directory path in filesystem to store the index.
path: PathBuf,
/// Shared with blocking work so cancellation cannot unlink an active index.
directory: Arc<TempIndexDirectory>,
/// Pauses the real commit at its blocking boundary in lifecycle tests.
#[cfg(test)]
before_commit: Option<Arc<dyn Fn() + Send + Sync>>,
/// The configuration of the fulltext index.
config: Config,
}
/// Owns an empty temporary directory, never a pre-existing index.
struct TempIndexDirectory {
path: PathBuf,
removed: AtomicBool,
}
impl TempIndexDirectory {
fn create(path: PathBuf) -> Result<Arc<Self>> {
std::fs::create_dir_all(&path).context(IoSnafu)?;
if std::fs::read_dir(&path)
.context(IoSnafu)?
.next()
.transpose()
.context(IoSnafu)?
.is_some()
{
return Err(std::io::Error::new(
std::io::ErrorKind::AlreadyExists,
"Tantivy temporary directory must be empty",
))
.context(IoSnafu);
}
Ok(Arc::new(Self {
path,
removed: AtomicBool::new(false),
}))
}
}
impl Drop for TempIndexDirectory {
fn drop(&mut self) {
if self.removed.load(Ordering::Relaxed) {
return;
}
let path = self.path.clone();
common_runtime::spawn_blocking_global(move || {
if let Err(error) = std::fs::remove_dir_all(&path)
&& error.kind() != std::io::ErrorKind::NotFound
{
warn!(error; "Failed to remove temporary Tantivy directory: {}", path.display());
}
});
}
}
impl Drop for TantivyFulltextIndexCreator {
fn drop(&mut self) {
if let Some(writer) = self.writer.take() {
let directory = self.directory.clone();
// IndexWriter::drop joins its threads; neither that nor directory
// removal may block the async task cancelling this creator.
common_runtime::spawn_blocking_global(move || {
drop(writer);
drop(directory);
});
}
}
}
impl TantivyFulltextIndexCreator {
/// Creates a new `TantivyFulltextIndexCreator`.
///
/// The `path` is the directory path in filesystem to store the index.
/// `path` must be an empty temporary directory. It is removed after the
/// creator and any in-flight blocking work release it.
pub async fn new(path: impl AsRef<Path>, config: Config, memory_limit: usize) -> Result<Self> {
tokio::fs::create_dir_all(path.as_ref())
let path = path.as_ref().to_path_buf();
// Keep creation and its guard in the same task: dropping the awaiting
// future must not race mkdir against cleanup.
common_runtime::spawn_blocking_global(move || Self::create(path, config, memory_limit))
.await
.context(IoSnafu)?;
.context(JoinSnafu)?
}
fn create(path: PathBuf, config: Config, memory_limit: usize) -> Result<Self> {
let directory = TempIndexDirectory::create(path)?;
let mut schema_builder = Schema::builder();
let text_field = schema_builder.add_text_field(TEXT_FIELD_NAME, TEXT);
let rowid_field = schema_builder.add_u64_field(ROWID_FIELD_NAME, STORED);
let schema = schema_builder.build();
let mut index = Index::create_in_dir(&path, schema).context(TantivySnafu)?;
let mut index = Index::create_in_dir(&directory.path, schema).context(TantivySnafu)?;
index.settings_mut().docstore_compression = Compressor::Zstd(ZstdCompressor::default());
index.set_tokenizers(config.build_tantivy_tokenizer());
@@ -82,15 +157,43 @@ impl TantivyFulltextIndexCreator {
Ok(Self {
writer: Some(writer),
finishing: None,
text_field,
rowid_field,
max_rowid: 0,
path: path.as_ref().to_path_buf(),
directory,
#[cfg(test)]
before_commit: None,
config,
})
}
fn sanitize_memory_limit(memory_limit: usize) -> usize {
async fn finish_writer(&mut self) -> Result<()> {
if self.finishing.is_none() {
let writer = self.writer.take().context(FinishedSnafu)?;
let directory = self.directory.clone();
#[cfg(test)]
let before_commit = self.before_commit.clone();
self.finishing = Some(common_runtime::spawn_blocking_global(move || {
let _directory = directory;
// Declare the writer after the lease so error unwinding also
// drops/joins it before releasing the directory.
let mut writer = writer;
#[cfg(test)]
if let Some(before_commit) = before_commit {
before_commit();
}
writer.commit().context(TantivySnafu)?;
writer.wait_merging_threads().context(TantivySnafu)
}));
}
let completed = self.finishing.as_mut().context(FinishedSnafu)?.await;
self.finishing.take();
completed.context(JoinSnafu)?
}
/// Effective per-column allocation, also used by compaction admission.
pub fn sanitize_memory_limit(memory_limit: usize) -> usize {
// Port from tantivy::indexer::index_writer::{MEMORY_BUDGET_NUM_BYTES_MIN, MEMORY_BUDGET_NUM_BYTES_MAX}
const MARGIN_IN_BYTES: usize = 1_000_000;
const MEMORY_BUDGET_NUM_BYTES_MIN: usize = ((MARGIN_IN_BYTES as u32) * 15u32) as usize;
@@ -116,13 +219,7 @@ impl FulltextIndexCreator for TantivyFulltextIndexCreator {
blob_key: &str,
put_options: PutOptions,
) -> Result<u64> {
let mut writer = self.writer.take().context(FinishedSnafu)?;
common_runtime::spawn_blocking_global(move || {
writer.commit().context(TantivySnafu)?;
writer.wait_merging_threads().context(TantivySnafu)
})
.await
.context(JoinSnafu)??;
self.finish_writer().await?;
let property_key = KEY_FULLTEXT_CONFIG.to_string();
let property_value = serde_json::to_string(&self.config).context(SerializeToJsonSnafu)?;
@@ -130,7 +227,7 @@ impl FulltextIndexCreator for TantivyFulltextIndexCreator {
puffin_writer
.put_dir(
blob_key,
self.path.clone(),
self.directory.path.clone(),
put_options,
HashMap::from([(property_key, property_value)]),
)
@@ -140,15 +237,15 @@ impl FulltextIndexCreator for TantivyFulltextIndexCreator {
}
async fn abort(&mut self) -> Result<()> {
let mut writer = self.writer.take().context(FinishedSnafu)?;
common_runtime::spawn_blocking_global(move || {
writer.commit().context(TantivySnafu)?;
writer.wait_merging_threads().context(TantivySnafu)
})
.await
.context(JoinSnafu)??;
tokio::fs::remove_dir_all(&self.path).await.context(IoSnafu)
if self.writer.is_some() || self.finishing.is_some() {
self.finish_writer().await?;
}
match tokio::fs::remove_dir_all(&self.directory.path).await {
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
removed => removed.context(IoSnafu)?,
}
self.directory.removed.store(true, Ordering::Relaxed);
Ok(())
}
fn memory_usage(&self) -> usize {
@@ -171,7 +268,10 @@ mod tests {
use super::*;
use crate::fulltext_index::Analyzer;
struct MockPuffinWriter;
#[derive(Default)]
struct MockPuffinWriter {
blocked: Option<Arc<tokio::sync::Notify>>,
}
#[async_trait]
impl PuffinWriter for MockPuffinWriter {
@@ -191,10 +291,15 @@ mod tests {
async fn put_dir(
&mut self,
_key: &str,
_dir: PathBuf,
dir: PathBuf,
_options: PutOptions,
_properties: HashMap<String, String>,
) -> puffin::error::Result<u64> {
if let Some(blocked) = &self.blocked {
assert!(dir.join("meta.json").exists());
blocked.notify_one();
futures::future::pending::<()>().await;
}
Ok(0)
}
fn set_footer_lz4_compressed(&mut self, _lz4_compressed: bool) {
@@ -206,6 +311,178 @@ mod tests {
}
}
async fn assert_directory_removed(path: &Path) {
tokio::time::timeout(std::time::Duration::from_secs(10), async {
while tokio::fs::try_exists(path).await.unwrap() {
tokio::time::sleep(std::time::Duration::from_millis(10)).await;
}
})
.await
.expect("temporary Tantivy directory leaked");
}
#[tokio::test]
async fn test_creator_drop_cleans_temporary_files() {
for stage in ["active", "finished", "aborted"] {
let root = create_temp_dir("tantivy-drop-");
let path = root.path().join("index");
let mut creator = creator_with_text(&path).await;
assert!(path.join("meta.json").exists());
match stage {
"finished" => {
creator
.finish(
&mut MockPuffinWriter::default(),
"index",
PutOptions::default(),
)
.await
.unwrap();
}
"aborted" => {
creator.abort().await.unwrap();
}
_ => {}
}
drop(creator);
assert_directory_removed(&path).await;
assert!(root.path().exists());
}
}
#[tokio::test]
async fn test_abort_after_cancelled_finish_cleans_temporary_files() {
let root = create_temp_dir("tantivy-cancel-finish-");
let path = root.path().join("index");
let mut creator = creator_with_text(&path).await;
let blocked = Arc::new(tokio::sync::Notify::new());
let mut writer = MockPuffinWriter {
blocked: Some(blocked.clone()),
};
{
let finishing = creator.finish(&mut writer, "index", PutOptions::default());
tokio::pin!(finishing);
tokio::select! {
_ = blocked.notified() => {}
result = &mut finishing => panic!("finish did not reach the blocked upload: {result:?}"),
_ = tokio::time::sleep(std::time::Duration::from_secs(10)) => panic!("finish stalled"),
}
}
creator.abort().await.unwrap();
creator.abort().await.unwrap();
assert!(!path.exists());
}
async fn creator_with_text(path: &Path) -> TantivyFulltextIndexCreator {
let mut creator = TantivyFulltextIndexCreator::new(path, Config::default(), 1)
.await
.unwrap();
creator.push_text("indexed text").await.unwrap();
creator
}
/// Cancels the real `finish()` while its commit is blocked, leaving the
/// production retained handle and directory lease in flight.
async fn creator_with_blocked_commit(
path: &Path,
) -> (TantivyFulltextIndexCreator, std::sync::mpsc::Sender<()>) {
let mut creator = creator_with_text(path).await;
let started = Arc::new(tokio::sync::Notify::new());
let commit_started = started.clone();
let (release, released) = std::sync::mpsc::channel();
let released = Arc::new(std::sync::Mutex::new(released));
creator.before_commit = Some(Arc::new(move || {
commit_started.notify_one();
released.lock().unwrap().recv().unwrap();
}));
let mut writer = MockPuffinWriter::default();
{
let finishing = creator.finish(&mut writer, "index", PutOptions::default());
tokio::pin!(finishing);
tokio::select! {
_ = started.notified() => {}
result = &mut finishing => panic!("finish did not reach commit: {result:?}"),
_ = tokio::time::sleep(std::time::Duration::from_secs(10)) => panic!("commit stalled"),
}
}
assert!(creator.finishing.is_some());
(creator, release)
}
#[tokio::test]
async fn test_abort_joins_retained_finalization() {
let root = create_temp_dir("tantivy-retained-finalize-");
let path = root.path().join("index");
let (mut creator, release) = creator_with_blocked_commit(&path).await;
let aborting = tokio::spawn(async move {
creator.abort().await.unwrap();
creator
});
assert!(path.exists());
release.send(()).unwrap();
let mut creator = tokio::time::timeout(std::time::Duration::from_secs(10), aborting)
.await
.unwrap()
.unwrap();
assert!(creator.finishing.is_none());
assert!(!path.exists());
// Repeating abort must stay idempotent.
creator.abort().await.unwrap();
}
#[tokio::test]
async fn test_drop_with_retained_finalization_cleans_temporary_files() {
let root = create_temp_dir("tantivy-drop-retained-");
let path = root.path().join("index");
let (creator, release) = creator_with_blocked_commit(&path).await;
drop(creator);
assert!(path.exists());
release.send(()).unwrap();
assert_directory_removed(&path).await;
}
#[tokio::test]
async fn test_detached_initialization_cleans_its_result() {
let root = create_temp_dir("tantivy-detached-init-");
let path = root.path().join("index");
let creating_path = path.clone();
let (ready, initialized) = tokio::sync::oneshot::channel();
let (release, released) = std::sync::mpsc::channel();
// The real constructor runs on the blocking pool. Detaching its handle
// must clean even if cancellation happens before the result is delivered.
let creating = common_runtime::spawn_blocking_global(move || {
let creator =
TantivyFulltextIndexCreator::create(creating_path, Config::default(), 1).unwrap();
ready.send(()).unwrap();
released.recv().unwrap();
creator
});
tokio::time::timeout(std::time::Duration::from_secs(10), initialized)
.await
.unwrap()
.unwrap();
assert!(path.join("meta.json").exists());
drop(creating);
release.send(()).unwrap();
assert_directory_removed(&path).await;
}
#[tokio::test]
async fn test_initialization_preserves_nonempty_directory() {
let root = create_temp_dir("tantivy-existing-");
let sentinel = root.path().join("existing");
tokio::fs::write(&sentinel, "must survive").await.unwrap();
assert!(
TantivyFulltextIndexCreator::new(root.path(), Config::default(), 1)
.await
.is_err()
);
assert_eq!(
"must survive",
tokio::fs::read_to_string(&sentinel).await.unwrap()
);
}
#[tokio::test]
async fn test_creator_basic() {
let memory_limits = [1, 64_000_000, usize::MAX];
@@ -215,7 +492,7 @@ mod tests {
let texts = vec!["hello", "world", "hello, world", "foo!", "Bar"];
let config = Config::default();
build_index(&texts, temp_dir.path(), config, memory_limit).await;
let _creator = build_index(&texts, temp_dir.path(), config, memory_limit).await;
let cases = [
("hello", vec![0u32, 2]),
@@ -239,7 +516,7 @@ mod tests {
case_sensitive: true,
..Config::default()
};
build_index(&texts, temp_dir.path(), config, memory_limit).await;
let _creator = build_index(&texts, temp_dir.path(), config, memory_limit).await;
let cases = [
("hello", vec![0u32, 2]),
@@ -267,7 +544,7 @@ mod tests {
analyzer: Analyzer::Chinese,
..Config::default()
};
build_index(&texts, temp_dir.path(), config, memory_limit).await;
let _creator = build_index(&texts, temp_dir.path(), config, memory_limit).await;
let cases = [
("你好", vec![0u32, 2, 3]),
@@ -291,7 +568,7 @@ mod tests {
case_sensitive: true,
analyzer: Analyzer::Chinese,
};
build_index(&texts, temp_dir.path(), config, memory_limit).await;
let _creator = build_index(&texts, temp_dir.path(), config, memory_limit).await;
let cases = [
("你好", vec![0u32, 2, 3]),
@@ -307,7 +584,12 @@ mod tests {
}
}
async fn build_index(texts: &[&str], path: &Path, config: Config, memory_limit: usize) {
async fn build_index(
texts: &[&str],
path: &Path,
config: Config,
memory_limit: usize,
) -> TantivyFulltextIndexCreator {
let mut creator = TantivyFulltextIndexCreator::new(path, config, memory_limit)
.await
.unwrap();
@@ -315,9 +597,10 @@ mod tests {
creator.push_text(text).await.unwrap();
}
creator
.finish(&mut MockPuffinWriter, "", PutOptions::default())
.finish(&mut MockPuffinWriter::default(), "", PutOptions::default())
.await
.unwrap();
creator
}
async fn query_and_check(path: &Path, config: Config, cases: &[(&str, Vec<u32>)]) {
+1
View File
@@ -20,6 +20,7 @@ async-trait.workspace = true
bytes.workspace = true
chrono.workspace = true
common-base.workspace = true
common-cache.workspace = true
common-config.workspace = true
common-error.workspace = true
common-macro.workspace = true
+14
View File
@@ -445,6 +445,19 @@ pub enum Error {
location: Location,
},
#[snafu(display(
"Source WAL prefix {prefix} on {storage} does not hold the history of region {region_id}: {reason}. \
Check the source node prefix and whether its WAL objects were reclaimed or moved"
))]
MissingSourceWalHistory {
region_id: RegionId,
prefix: String,
storage: String,
reason: String,
#[snafu(implicit)]
location: Location,
},
#[snafu(display(
"Object store WAL gave up its start object {} after refusing a region without its history, and accepts nothing more until it opens again",
path
@@ -510,6 +523,7 @@ impl ErrorExt for Error {
| InvalidWalObjectStore { .. }
| MismatchedWalPrefix { .. }
| MissingWalHistory { .. }
| MissingSourceWalHistory { .. }
| MismatchedWalRegion { .. }
| IncompleteWalEntry { .. }
| InvalidWalEntryRange { .. } => StatusCode::InvalidArguments,
+14
View File
@@ -71,12 +71,26 @@
//! Entry ids are object-sequence-major, see [`entry_id`]: the high bits of an
//! id name the object that holds the entry, the low bits its position among
//! the entries of its region in that object.
//!
//! Remote recovery uses [`ObjectStoreWalReaders`] to share a read-only reader
//! per source prefix. Listing an upper bound reads no object indexes; preparing
//! a range refreshes the listing and reuses cached indexes. Known last-entry
//! bounds anchor their own chains, while listed bounds use the complete-chain
//! selection of startup recovery with an additional maximum-epoch check.
//! Neither path opens a writable store or modifies the source. The caller owns
//! the lifetime of pending recovery ranges and
//! publishes progress only after a successful read.
mod batch;
mod catalog;
mod format;
mod history;
mod index;
mod io;
mod prefetch;
mod reader;
mod store;
pub use batch::entry_id;
pub use reader::{NodeWalPrefix, ObjectStoreWalReader, ObjectStoreWalReaders, WalReadUpperBound};
pub use store::{ObjectStoreLogStore, WalHole};
@@ -0,0 +1,52 @@
// 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.
//! Validation of the history represented by a WAL catalog.
use store_api::logstore::EntryId;
use store_api::storage::RegionId;
use crate::object_store_wal::batch::sequence_floor;
use crate::object_store_wal::catalog::ObjectCatalog;
/// Returns why the observed prefix cannot contain history through `entry_id`.
/// Local histories started on this instance are handled by the caller.
pub(crate) fn missing_history(
catalog: &ObjectCatalog,
region_id: RegionId,
entry_id: EntryId,
found_empty: bool,
history_end: u64,
) -> Option<String> {
if catalog
.region_max_entry_id(region_id)
.is_some_and(|max_entry_id| max_entry_id >= entry_id)
{
return None;
}
if found_empty {
return Some("the prefix held no object when the prefix was listed".to_string());
}
let sequence_floor = sequence_floor(entry_id);
(sequence_floor > history_end).then(|| {
let held = match history_end {
0 => "no entry".to_string(),
history_end => format!("entries only in objects below {history_end}"),
};
format!(
"its watermark, entry {entry_id}, names object {}, but the prefix held {held} when the prefix was listed",
sequence_floor - 1
)
})
}
+301
View File
@@ -0,0 +1,301 @@
// 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.
//! Shared WAL object indexing and chain traversal.
use std::cmp::Reverse;
use std::collections::BTreeMap;
use std::ops::Range;
use bytes::Bytes;
use futures::{Stream, TryStreamExt};
use snafu::{IntoError, OptionExt, ensure};
use crate::error::{CorruptedWalObjectSnafu, Error, InvalidWalObjectSnafu, Result};
use crate::object_store_wal::format::{
FixedTrailer, FooterEntry, HEADER_LEN, Header, MIN_OBJECT_LEN, RELEASE_REGION_ID, TRAILER_LEN,
decode_footer, decode_header, decode_trailer, footer_range, verify_segment_ranges,
};
use crate::object_store_wal::io::{ListedObject, WalObjectRead};
/// Bytes recovery reads from the end of an object in one request. The window
/// holds the trailer and the footer of an object with up to 1364 regions of
/// 48 bytes each, so a second request for the footer is rare, and usually the
/// segment of release records, which is the last segment.
pub(crate) const RECOVERY_TAIL_WINDOW: usize = 64 * 1024;
/// Largest segment of release records that recovery keeps from the bytes it
/// read for a footer. It keeps them before it knows which objects are on the
/// chain, so the bound caps what objects off the chain hold until recovery
/// ends; a larger segment is read again if its object is on the chain. A
/// release seals its record at once, so a segment usually holds the records of
/// one or a few regions, 16 bytes each.
pub(crate) const MAX_KEPT_RELEASE_BYTES: u64 = 4 * 1024;
/// The objects recovery fetched, ordered by sequence, and the listed objects
/// that were gone when their header or footer was fetched, with the error the
/// fetch met. A collection of an earlier instance may complete after the
/// listing.
pub(crate) struct FetchedObjects {
pub(crate) objects: Vec<FetchedObject>,
pub(crate) vanished: Vec<(u64, Error)>,
}
/// An object as recovery fetched it: its key, header and footer, and its
/// segment of release records when the reads of the footer returned it.
pub(crate) struct FetchedObject {
pub(crate) object: ListedObject,
pub(crate) header: Header,
pub(crate) footer: Vec<FooterEntry>,
pub(crate) releases: Option<Bytes>,
}
/// Verified header and region index of an immutable object.
#[derive(Debug)]
pub(crate) struct FetchedFooter {
pub(crate) header: Header,
pub(crate) footer: Vec<FooterEntry>,
}
/// Returns, in sequence order, the objects on the chain that ends at the tip:
/// the complete object with the largest epoch, then the largest sequence.
///
/// An object is complete when every link on its chain holds, judged with the
/// reclaim boundary of that object: the chain starts at an object without a
/// predecessor or reaches a predecessor below the boundary, whether or not it
/// is present, and every other link names a present object that carries the
/// epoch the link records. The chain of the tip ends there, so objects below
/// its boundary are not replayed. Only one instance writes
/// under an epoch, so the epoch tells an object of the linking instance from
/// another object under the same sequence. A create that
/// was reported as failed may still leave its object, but every object
/// written after that failure links past it, and every instance writes under
/// an epoch above every object present when it opened, so neither such an
/// object nor a late object of an earlier instance ends the chosen chain.
pub(crate) fn select_chain(headers: &BTreeMap<u64, &Header>) -> Vec<u64> {
let mut candidates = headers.iter().collect::<Vec<_>>();
candidates.sort_unstable_by_key(|(object_seq, header)| Reverse((header.epoch, **object_seq)));
candidates
.into_iter()
.find_map(|(object_seq, _)| chain_ending_at(headers, *object_seq))
.unwrap_or_default()
}
/// Returns, in sequence order, the chain that ends at `tip` if `tip` is
/// complete, see [`select_chain`].
pub(crate) fn chain_ending_at(headers: &BTreeMap<u64, &Header>, tip: u64) -> Option<Vec<u64>> {
chain_from(headers, tip, headers.get(&tip)?.reclaim_boundary)
}
/// Walks predecessors down to the inclusive lower object boundary.
/// A missing object below the boundary does not belong to this read.
pub(crate) fn chain_from(
headers: &BTreeMap<u64, &Header>,
tip: u64,
boundary: u64,
) -> Option<Vec<u64>> {
let mut chain = vec![tip];
let mut header = *headers.get(&tip)?;
while let Some(link) = header.prev {
if link.object_seq >= header.object_seq {
return None;
}
if link.object_seq < boundary {
break;
}
header = headers
.get(&link.object_seq)
.filter(|prev| prev.epoch == link.epoch)?;
chain.push(link.object_seq);
}
chain.reverse();
Some(chain)
}
/// Fetches and verifies the headers and footers of `objects` as they are
/// listed, up to `concurrency` objects at a time, and returns them ordered by
/// object sequence whatever the order the fetches complete in. An object the
/// object store no longer has is returned as vanished; a failed listing or
/// any other failure abandons the remaining fetches.
pub(crate) async fn fetch_footers(
io: &dyn WalObjectRead,
objects: impl Stream<Item = Result<ListedObject>>,
concurrency: usize,
) -> Result<FetchedObjects> {
let outcomes = objects
.map_ok(|object| async move {
let object_seq = object.object_seq;
match fetch_footer_with_releases(io, object).await {
Ok(fetched) => Ok(Ok(fetched)),
Err(error) if is_not_found(&error) => Ok(Err((object_seq, error))),
Err(error) => Err(error),
}
})
.try_buffer_unordered(concurrency)
.try_collect::<Vec<_>>()
.await?;
let mut objects = Vec::with_capacity(outcomes.len());
let mut vanished = Vec::new();
for outcome in outcomes {
match outcome {
Ok(object) => objects.push(object),
Err(gone) => vanished.push(gone),
}
}
objects.sort_unstable_by_key(|fetched| fetched.object.object_seq);
Ok(FetchedObjects { objects, vanished })
}
pub(crate) fn is_not_found(error: &Error) -> bool {
matches!(error, Error::WalObjectStore { error, .. } if error.kind() == object_store::ErrorKind::NotFound)
}
/// Reads and verifies the header and footer without copying release records.
pub(crate) async fn fetch_footer(
io: &dyn WalObjectRead,
object: &ListedObject,
) -> Result<FetchedFooter> {
Ok(fetch_footer_window(io, object).await?.index)
}
/// The verified index and the download window, retained only during fetching.
struct FooterWindow {
index: FetchedFooter,
tail: Bytes,
tail_start: usize,
}
/// Retains a small release segment for startup recovery without another GET.
async fn fetch_footer_with_releases(
io: &dyn WalObjectRead,
object: ListedObject,
) -> Result<FetchedObject> {
let FooterWindow {
index,
tail,
tail_start,
} = fetch_footer_window(io, &object).await?;
// Copy only the release bytes so recovery does not retain the whole window.
let releases = index
.footer
.iter()
.find(|entry| entry.region_id == RELEASE_REGION_ID)
.filter(|entry| {
entry.segment_offset >= tail_start as u64 && entry.segment_len <= MAX_KEPT_RELEASE_BYTES
})
.map(|entry| {
let start = entry.segment_offset as usize - tail_start;
Bytes::copy_from_slice(&tail[start..start + entry.segment_len as usize])
});
Ok(FetchedObject {
object,
header: index.header,
footer: index.footer,
releases,
})
}
/// Verifies object sequence, header, trailer, footer checksum and segment ranges.
/// Small objects are read whole; large ones use concurrent header and tail reads,
/// followed by a separate footer read only when it begins before the tail window.
async fn fetch_footer_window(
io: &dyn WalObjectRead,
object: &ListedObject,
) -> Result<FooterWindow> {
let ListedObject {
object_seq, size, ..
} = *object;
let invalid = |source: Error| {
InvalidWalObjectSnafu {
path: object.path.clone(),
}
.into_error(source)
};
let object_len = usize::try_from(size)
.ok()
.filter(|len| *len >= MIN_OBJECT_LEN)
.with_context(|| CorruptedWalObjectSnafu {
reason: format!(
"truncated object, expected at least {MIN_OBJECT_LEN} bytes, actual {size}"
),
})
.map_err(invalid)?;
let window = object_len.min(RECOVERY_TAIL_WINDOW);
let tail_start = object_len - window;
let (head, tail) = if tail_start == 0 {
let bytes = io.get(object_seq).await?;
(bytes.clone(), bytes)
} else {
futures::try_join!(
io.get_range(object_seq, 0, HEADER_LEN as u64),
io.get_range(object_seq, tail_start as u64, window as u64)
)?
};
if head.len() < HEADER_LEN || tail.len() != window {
return Err(invalid(
CorruptedWalObjectSnafu {
reason: format!(
"object holds fewer bytes than the listed {size}, head {} bytes, tail {} bytes",
head.len(),
tail.len()
),
}
.build(),
));
}
let (header, trailer, footer_range) =
locate_footer(object_seq, object_len, &head, &tail).map_err(invalid)?;
let footer = if footer_range.start >= tail_start {
tail.slice(footer_range.start - tail_start..footer_range.end - tail_start)
} else {
io.get_range(
object_seq,
footer_range.start as u64,
footer_range.len() as u64,
)
.await?
};
let footer = decode_footer(&footer, trailer).map_err(invalid)?;
verify_segment_ranges(&footer, footer_range.start).map_err(invalid)?;
Ok(FooterWindow {
index: FetchedFooter { header, footer },
tail,
tail_start,
})
}
/// Verifies the header and trailer of the object `object_seq` of `object_len`
/// bytes from its first bytes `head` and its last bytes `tail`, and returns
/// the header and the trailer with the range the footer occupies in the object.
fn locate_footer(
object_seq: u64,
object_len: usize,
head: &[u8],
tail: &[u8],
) -> Result<(Header, FixedTrailer, Range<usize>)> {
let header = decode_header(head)?;
ensure!(
header.object_seq == object_seq,
CorruptedWalObjectSnafu {
reason: format!(
"header sequence {} does not match key sequence {object_seq}",
header.object_seq
),
}
);
let trailer = decode_trailer(&tail[tail.len() - TRAILER_LEN..])?;
let footer_range = footer_range(trailer, object_len)?;
Ok((header, trailer, footer_range))
}
+145 -11
View File
@@ -51,7 +51,7 @@ pub(crate) enum PutResult {
}
/// An object discovered by a LIST.
#[derive(Debug, Clone, PartialEq, Eq)]
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub(crate) struct ListedObject {
pub(crate) object_seq: u64,
pub(crate) path: String,
@@ -63,6 +63,7 @@ pub(crate) struct ListedObject {
#[derive(Clone)]
pub(crate) struct ObjectStoreIo {
store: ObjectStore,
prefix: String,
object_prefix: String,
/// Holds the keys of [`Self::probe_conditional_create`], outside
/// `object_prefix` so that no listing of the objects returns one.
@@ -74,20 +75,31 @@ impl ObjectStoreIo {
/// conditional creates, which is what keeps a retried write from
/// overwriting a durable object.
pub(crate) fn new(store: ObjectStore, prefix: impl AsRef<str>) -> Result<Self> {
let prefix = normalize_prefix(prefix.as_ref())?;
ensure!(
store.info().capability().write_with_if_not_exists,
InvalidWalObjectStoreSnafu {
reason: "object store does not support conditional create",
}
);
Self::new_readonly(store, prefix)
}
/// Binds a reader without requiring or probing write capabilities.
pub(crate) fn new_readonly(store: ObjectStore, prefix: impl AsRef<str>) -> Result<Self> {
let prefix = normalize_prefix(prefix.as_ref())?;
Ok(Self {
store,
object_prefix: format!("{prefix}/objects/"),
probe_prefix: format!("{prefix}/probes/"),
prefix,
})
}
/// The normalized source prefix, before the object-directory suffix.
pub(crate) fn prefix(&self) -> &str {
&self.prefix
}
/// Checks that the store refuses a conditional create of an object that
/// exists. The capability checked by [`Self::new`] is declared per
/// service, and a store behind the S3 service may accept the condition and
@@ -221,17 +233,24 @@ impl ObjectStoreIo {
/// Lists the objects under the prefix, ordered by object sequence. Keys
/// that do not follow the object layout are ignored.
pub(crate) async fn list(&self) -> Result<Vec<ListedObject>> {
let entries = self
.store
.list(&self.object_prefix)
.await
.with_context(|_| WalObjectStoreSnafu {
operation: "list",
path: self.object_prefix.clone(),
})?;
self.list_from(0).await
}
/// Lists from `object_seq`, including that object if it exists.
pub(crate) async fn list_from(&self, object_seq: u64) -> Result<Vec<ListedObject>> {
let mut listing = self.store.list_with(&self.object_prefix);
let start_after = object_seq.checked_sub(1).map(|seq| self.object_path(seq));
if let Some(path) = &start_after {
listing = listing.start_after(path);
}
let entries = listing.await.with_context(|_| WalObjectStoreSnafu {
operation: "list",
path: self.object_prefix.clone(),
})?;
let mut objects = entries
.iter()
.filter_map(|entry| self.listed_object(entry))
.filter(|object| object.object_seq >= object_seq)
.collect::<Vec<_>>();
objects.sort_unstable_by_key(|object| object.object_seq);
Ok(objects)
@@ -352,7 +371,7 @@ fn reports_existing_object(error: &object_store::Error) -> bool {
error.kind() == ErrorKind::ConditionNotMatch
}
fn normalize_prefix(prefix: &str) -> Result<String> {
pub(crate) fn normalize_prefix(prefix: &str) -> Result<String> {
let prefix = prefix.trim();
ensure!(
!prefix.is_empty() && !prefix.starts_with('/'),
@@ -372,6 +391,90 @@ fn normalize_prefix(prefix: &str) -> Result<String> {
Ok(prefix.to_string())
}
/// Read-only object access shared by readers and local recovery.
#[async_trait::async_trait]
pub(crate) trait WalObjectRead: Send + Sync {
async fn get(&self, object_seq: u64) -> Result<Bytes>;
async fn get_range(&self, object_seq: u64, offset: u64, len: u64) -> Result<Bytes>;
async fn list(&self) -> Result<Vec<ListedObject>>;
async fn list_from(&self, object_seq: u64) -> Result<Vec<ListedObject>> {
Ok(self
.list()
.await?
.into_iter()
.filter(|object| object.object_seq >= object_seq)
.collect())
}
fn object_path(&self, object_seq: u64) -> String;
/// The normalized node prefix shared with providers.
fn prefix(&self) -> &str;
/// Describes the object store the objects live in, for messages.
fn storage(&self) -> String;
}
/// Writable store access, including its startup listing pipeline.
#[async_trait::async_trait]
pub(crate) trait WalObjectIo: WalObjectRead {
async fn put_if_absent(&self, object_seq: u64, content: Bytes) -> Result<PutResult>;
async fn delete(&self, object_seq: u64) -> Result<()>;
/// See [`ObjectStoreIo::list_ahead`]; by default the objects
/// [`list`](WalObjectRead::list) returns.
fn list_ahead(&self) -> BoxStream<'_, Result<ListedObject>> {
Box::pin(try_stream! {
for object in self.list().await? { yield object; }
})
}
}
#[async_trait::async_trait]
impl WalObjectRead for ObjectStoreIo {
async fn get(&self, object_seq: u64) -> Result<Bytes> {
ObjectStoreIo::get(self, object_seq).await
}
async fn get_range(&self, object_seq: u64, offset: u64, len: u64) -> Result<Bytes> {
ObjectStoreIo::get_range(self, object_seq, offset, len).await
}
async fn list(&self) -> Result<Vec<ListedObject>> {
ObjectStoreIo::list(self).await
}
async fn list_from(&self, object_seq: u64) -> Result<Vec<ListedObject>> {
ObjectStoreIo::list_from(self, object_seq).await
}
fn object_path(&self, object_seq: u64) -> String {
ObjectStoreIo::object_path(self, object_seq)
}
fn storage(&self) -> String {
ObjectStoreIo::storage(self)
}
fn prefix(&self) -> &str {
ObjectStoreIo::prefix(self)
}
}
#[async_trait::async_trait]
impl WalObjectIo for ObjectStoreIo {
async fn put_if_absent(&self, object_seq: u64, content: Bytes) -> Result<PutResult> {
ObjectStoreIo::put_if_absent(self, object_seq, content).await
}
async fn delete(&self, object_seq: u64) -> Result<()> {
ObjectStoreIo::delete(self, object_seq).await
}
fn list_ahead(&self) -> BoxStream<'_, Result<ListedObject>> {
ObjectStoreIo::list_ahead(self)
}
}
#[cfg(test)]
mod tests {
use std::pin::pin;
@@ -392,6 +495,37 @@ mod tests {
ObjectStore::new(Memory::default()).unwrap()
}
#[tokio::test]
async fn test_list_from_passes_exclusive_predecessor_key() {
let seen = Arc::new(std::sync::Mutex::new(Vec::new()));
let layer = MockLayerBuilder::default()
.lister_factory(Arc::new({
let seen = seen.clone();
move |path, args, inner| {
seen.lock()
.unwrap()
.push((path.to_string(), args.start_after().map(str::to_string)));
inner
}
}))
.build()
.unwrap();
let io =
ObjectStoreIo::new_readonly(memory_store().layer(layer), "wal/datanodes/1/epochs/0")
.unwrap();
for seq in [5, 1, 0] {
io.list_from(seq).await.unwrap();
}
assert_eq!(
*seen.lock().unwrap(),
vec![
(io.object_prefix.clone(), Some(io.object_path(4))),
(io.object_prefix.clone(), Some(io.object_path(0))),
(io.object_prefix.clone(), None),
]
);
}
/// A reader whose every read fails with a temporary error.
struct FailingReader;
@@ -0,0 +1,134 @@
// 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.
//! Segment fetching shared by local reads and remote recovery.
use std::collections::VecDeque;
use std::sync::Arc;
use futures::stream::BoxStream;
use snafu::ResultExt;
use tokio::sync::{OwnedSemaphorePermit, Semaphore};
use tokio_util::task::AbortOnDropHandle;
use crate::error::{InvalidWalObjectSnafu, Result, WalSegmentFetchSnafu};
use crate::object_store_wal::format::{FooterEntry, Record, decode_segment};
use crate::object_store_wal::io::WalObjectRead;
/// Number of segments a read fetches ahead of the one whose entries it
/// yields. On S3 a replay that fetched each segment after the previous one
/// spent about 30 ms per object; with eight fetches in flight a segment
/// arrives about every 4 ms. The segments fetched ahead also take their bytes
/// from [`READ_PREFETCH_BYTES`].
pub(crate) const READ_PREFETCH_DEPTH: usize = 8;
/// Bytes of decoded segments that all reads of one store, or of one remote
/// source prefix, together fetch ahead. A segment counts as its length, which
/// bounds its payloads, plus a [`Record`]
/// per entry. A read always fetches the segment it yields next, as a read that
/// fetched one segment at a time did, and a later segment only while it fits
/// in what is left, so regions replayed in parallel hold one segment each, up
/// to about `max_batch_bytes` or more for one oversized append, plus at most
/// these bytes, however many regions open at once. While a fetch copies the
/// payloads out of the downloaded segment it briefly holds the segment's
/// length once more.
pub(crate) const READ_PREFETCH_BYTES: usize = 64 * 1024 * 1024;
/// Fetches and decodes the segment `entry` describes in the object
/// `object_seq`. A segment that does not decode is fetched once more, since
/// the download rather than the object may be damaged; when it still does not
/// decode the error is returned as [`crate::error::Error::InvalidWalObject`]. A failed fetch
/// is returned as is.
async fn fetch_segment(
io: &dyn WalObjectRead,
object_seq: u64,
entry: &FooterEntry,
) -> Result<Vec<Record>> {
let fetch = || io.get_range(object_seq, entry.segment_offset, entry.segment_len);
if let Ok(records) = decode_segment(&fetch().await?, entry) {
return Ok(records);
}
decode_segment(&fetch().await?, entry).with_context(|_| InvalidWalObjectSnafu {
path: io.object_path(object_seq),
})
}
/// Takes from `budget` the bytes the segment `entry` describes holds once
/// decoded, if they are free: its length plus a [`Record`] per entry.
fn try_reserve_prefetch_bytes(
budget: &Arc<Semaphore>,
entry: &FooterEntry,
) -> Option<OwnedSemaphorePermit> {
let records = u64::from(entry.entry_count) * std::mem::size_of::<Record>() as u64;
let bytes = u32::try_from(entry.segment_len.checked_add(records)?).ok()?;
budget.clone().try_acquire_many_owned(bytes).ok()
}
/// Runs [`fetch_segment`] on a task of its own, so the fetch proceeds while
/// the read is busy with earlier segments, and returns the outcome with
/// `permit`. The task holds the permit, so the reserved bytes are released
/// only with the buffers of the fetch. Dropping the returned future, as a
/// dropped read does, aborts the task; a task that panics fails the fetch with
/// [`crate::error::Error::WalSegmentFetch`].
fn spawn_fetch_segment(
io: Arc<dyn WalObjectRead>,
object_seq: u64,
entry: FooterEntry,
permit: Option<OwnedSemaphorePermit>,
) -> impl Future<Output = (Result<Vec<Record>>, Option<OwnedSemaphorePermit>)> + Send + 'static {
let task_io = io.clone();
let task = AbortOnDropHandle::new(common_runtime::spawn_global(async move {
let fetched = fetch_segment(task_io.as_ref(), object_seq, &entry).await;
(fetched, permit)
}));
async move {
match task.await {
Ok(fetched) => fetched,
Err(error) => (
Err(error).context(WalSegmentFetchSnafu {
path: io.object_path(object_seq),
}),
None,
),
}
}
}
/// Fetches segments in order, retaining prefetch permits until the consumer
/// advances. Errors are yielded for the caller to apply its own recovery policy.
pub(crate) fn segments(
io: Arc<dyn WalObjectRead>,
objects: Vec<(u64, FooterEntry)>,
budget: Arc<Semaphore>,
) -> BoxStream<'static, (u64, FooterEntry, Result<Vec<Record>>)> {
Box::pin(async_stream::stream! {
let mut objects = objects.into_iter().peekable();
let mut fetches = VecDeque::new();
loop {
while fetches.len() < READ_PREFETCH_DEPTH {
let Some((_, entry)) = objects.peek() else { break; };
let permit = if fetches.is_empty() { None } else {
match try_reserve_prefetch_bytes(&budget, entry) {
Some(permit) => Some(permit),
None => break,
}
};
let Some((seq, entry)) = objects.next() else { break; };
let fetch = spawn_fetch_segment(io.clone(), seq, entry.clone(), permit);
fetches.push_back((seq, entry, fetch));
}
let Some((seq, entry, fetch)) = fetches.pop_front() else { break; };
let (fetched, _permit) = fetch.await;
yield (seq, entry, fetched);
}
})
}
@@ -0,0 +1,441 @@
// 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.
//! Read-only access to another node's immutable WAL objects.
use std::collections::{BTreeMap, HashMap, HashSet};
use std::sync::{Arc, Mutex, PoisonError, Weak};
use async_stream::try_stream;
use common_cache::Cache;
use futures::{StreamExt, TryStreamExt};
use object_store::ObjectStore;
use snafu::{OptionExt, ResultExt, ensure};
use store_api::logstore::entry::{Entry, NaiveEntry};
use store_api::logstore::provider::Provider;
use store_api::logstore::{EntryId, SendableEntryStream};
use store_api::storage::RegionId;
use tokio::sync::Semaphore;
use crate::error::{
CorruptedWalObjectSnafu, Error, InvalidWalEntryRangeSnafu, InvalidWalObjectSnafu,
InvalidWalObjectStoreSnafu, MissingSourceWalHistorySnafu, ObjectStoreWalSnafu, Result,
};
use crate::object_store_wal::batch::{
OBJECT_SEQ_LIMIT, POSITION_BITS, POSITION_LIMIT, entry_id, sequence_floor,
};
use crate::object_store_wal::catalog::ObjectCatalog;
use crate::object_store_wal::format::{FooterEntry, Header};
use crate::object_store_wal::history;
use crate::object_store_wal::index;
use crate::object_store_wal::io::{self, ListedObject, ObjectStoreIo, WalObjectRead};
use crate::object_store_wal::prefetch;
/// Node-wide limit on concurrent remote object index reads. Startup recovery
/// keeps its existing, separate concurrency setting.
const FOOTER_CONCURRENCY: usize = 16;
/// Upper bound of a remote WAL recovery range. A reported final entry must be
/// present, whereas a LIST boundary need not contain entries of this region.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum WalReadUpperBound {
/// The durable last entry reported by the source on downgrade.
LastEntry(EntryId),
/// A conservative bound obtained by listing the source prefix.
Listed(EntryId),
}
impl WalReadUpperBound {
fn entry_id(self) -> EntryId {
match self {
Self::LastEntry(id) | Self::Listed(id) => id,
}
}
}
/// A normalized WAL node prefix: `<root>/datanodes/<node>/epochs/<generation>`.
/// Construct it from a persisted source prefix or
/// [`ObjectStoreWalConfig::node_prefix`](common_wal::config::object_store::ObjectStoreWalConfig::node_prefix).
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct NodeWalPrefix(String);
impl NodeWalPrefix {
/// Validates the node layout and removes a trailing slash.
pub fn try_new(prefix: &str) -> Result<Self> {
let prefix = io::normalize_prefix(prefix)?;
let mut parts = prefix.rsplitn(5, '/');
let generation = parts.next();
let epochs = parts.next();
let node = parts.next();
let datanodes = parts.next();
let root = parts.next();
let is_id = |part: Option<&str>| {
part.is_some_and(|part| {
(part == "0" || !part.starts_with('0'))
&& part.bytes().all(|byte| byte.is_ascii_digit())
&& part.parse::<u64>().is_ok()
})
};
ensure!(
is_id(generation)
&& epochs == Some("epochs")
&& is_id(node)
&& datanodes == Some("datanodes")
&& root.is_some(),
InvalidWalObjectStoreSnafu {
reason: format!("expected a WAL node prefix, got {prefix:?}"),
}
);
Ok(Self(prefix))
}
/// Returns the normalized prefix used in object keys and providers.
pub fn as_str(&self) -> &str {
&self.0
}
}
/// Readers shared by source prefix on one destination node and one WAL backend.
/// Keep this registry for the node's lifetime, and hold each returned reader
/// while any recovery range still references that source. Dropping the last
/// reader releases its cached indexes; no background task or writer is started.
pub struct ObjectStoreWalReaders {
store: ObjectStore,
readers: Mutex<HashMap<NodeWalPrefix, Weak<ObjectStoreWalReader>>>,
footer_budget: Arc<Semaphore>,
}
impl ObjectStoreWalReaders {
/// Creates an empty registry. Construction performs no storage requests.
pub fn new(store: ObjectStore) -> Self {
Self {
store,
readers: Mutex::new(HashMap::new()),
footer_budget: Arc::new(Semaphore::new(FOOTER_CONCURRENCY)),
}
}
/// Returns the shared reader for a full node prefix, without probing writes
/// or listing objects. Only read/list permissions are needed on the backend.
pub fn reader(&self, prefix: &NodeWalPrefix) -> Result<Arc<ObjectStoreWalReader>> {
let mut readers = self.readers.lock().unwrap_or_else(PoisonError::into_inner);
if let Some(reader) = readers.get(prefix).and_then(Weak::upgrade) {
return Ok(reader);
}
readers.retain(|_, reader| reader.strong_count() != 0);
let reader = Arc::new(ObjectStoreWalReader {
io: Arc::new(ObjectStoreIo::new_readonly(
self.store.clone(),
prefix.as_str(),
)?),
indexes: CachedObject::cache(),
footer_budget: self.footer_budget.clone(),
prefetch_budget: Arc::new(Semaphore::new(prefetch::READ_PREFETCH_BYTES)),
});
readers.insert(prefix.clone(), Arc::downgrade(&reader));
Ok(reader)
}
}
/// Reads remote WAL ranges without claiming an epoch or modifying the source.
/// The reader never honors missing-history or corrupted-segment skip options.
/// It does not own region roles, manifests, release positions or replay tasks.
pub struct ObjectStoreWalReader {
io: Arc<dyn WalObjectRead>,
/// Immutable indexes keyed by listed metadata, sharing loads within this prefix.
indexes: Cache<ListedObject, Arc<CachedObject>>,
/// Footer-load concurrency shared by all readers in the node's registry.
footer_budget: Arc<Semaphore>,
/// Prefetched bytes shared by reads of this source prefix only.
prefetch_budget: Arc<Semaphore>,
}
/// Cached metadata for an immutable WAL object, without recovery release records.
struct CachedObject {
object: ListedObject,
header: Header,
footer: Vec<FooterEntry>,
}
impl CachedObject {
/// Bounds retained index weight per source prefix. Eviction is asynchronous;
/// active reads can retain their own snapshots beyond this capacity.
fn cache() -> Cache<ListedObject, Arc<Self>> {
Cache::new(
"object_store_wal_indexes",
64 * 1024 * 1024,
|key: &ListedObject, value: &Arc<Self>| {
let bytes = std::mem::size_of::<ListedObject>()
+ key.path.capacity()
+ std::mem::size_of::<Self>()
+ value.object.path.capacity()
+ value.footer.capacity() * std::mem::size_of::<FooterEntry>();
u32::try_from(bytes).unwrap_or(u32::MAX)
},
|_, _, _| {},
)
}
}
impl ObjectStoreWalReader {
/// The normalized node prefix used by every entry's provider.
pub fn prefix(&self) -> &str {
self.io.prefix()
}
/// Lists keys only, returning a bound at or above every entry in the listed
/// objects. An empty prefix is an error, not an empty tail. No object index
/// or data is read on this readiness path. The bound covers the whole prefix;
/// `region_id` identifies the recovery request in missing-history errors.
pub async fn list_upper_bound(&self, region_id: RegionId) -> Result<EntryId> {
let objects = self.io.list().await?;
let seq = objects
.iter()
.map(|object| object.object_seq)
.max()
.with_context(|| MissingSourceWalHistorySnafu {
region_id,
prefix: self.prefix().to_string(),
storage: self.io.storage(),
reason: format!(
"empty WAL prefix {} while determining takeover bound",
self.prefix()
),
})?;
ensure!(
seq < OBJECT_SEQ_LIMIT,
CorruptedWalObjectSnafu {
reason: format!(
"listed key {} has sequence {seq} outside the entry-id range",
self.io.object_path(seq)
),
}
);
Ok(entry_id(seq, POSITION_LIMIT - 1))
}
/// Prepares a fresh view and streams only this region's `(after, upper]`.
/// Call after the recovery range has been registered in the manifest. Each
/// call (including a retry) starts a new LIST; cached indexes never replace
/// that LIST. Previously indexed, still-listed immutable objects are reused.
///
/// Errors can occur after entries have been yielded. The caller must finish
/// the stream successfully before publishing recovery progress. In the
/// `LastEntry` mode success also proves that the reported entry was read.
pub async fn read(
&self,
region_id: RegionId,
after: EntryId,
upper: WalReadUpperBound,
) -> Result<SendableEntryStream<'static, Entry, Error>> {
let upto = upper.entry_id();
ensure!(
after < upto,
InvalidWalEntryRangeSnafu {
region_id,
start_entry_id: after,
end_entry_id: upto,
}
);
let catalog = self.prepare(region_id, after, upper).await?;
let objects = catalog
.objects_for_entry_range(region_id, after + 1, upto)?
.into_iter()
.map(|(seq, entry)| (seq, entry.clone()))
.collect();
let mut segments =
prefetch::segments(self.io.clone(), objects, self.prefetch_budget.clone());
let provider = Provider::object_store_provider(region_id, self.prefix().to_string());
Ok(Box::pin(try_stream! {
let mut reached_upto = false;
while let Some((_, _, fetched)) = segments.next().await {
let entries = fetched?.into_iter()
.filter(|record| record.entry_id > after && record.entry_id <= upto)
.map(|record| {
reached_upto |= record.entry_id == upto;
Entry::Naive(NaiveEntry {
provider: provider.clone(), region_id,
entry_id: record.entry_id, data: record.payload.into(),
})
}).collect::<Vec<_>>();
if !entries.is_empty() { yield entries; }
}
if matches!(upper, WalReadUpperBound::LastEntry(_)) && !reached_upto {
Err(CorruptedWalObjectSnafu {
reason: format!("WAL recovery of region {region_id} did not reach reported entry {upto}"),
}.build())?;
}
}))
}
async fn prepare(
&self,
region_id: RegionId,
after: EntryId,
upper: WalReadUpperBound,
) -> Result<ObjectCatalog> {
let start = match upper {
WalReadUpperBound::LastEntry(_) => after >> POSITION_BITS,
WalReadUpperBound::Listed(_) => 0,
};
let listed = self.io.list_from(start).await?;
let present = listed.iter().cloned().collect::<HashSet<_>>();
// Each read owns its LIST snapshot. Drop cached indexes outside it,
// accepting a refetch for later reads with a lower watermark. In-flight
// loads may still insert old indexes; capacity also bounds retention.
let _ = self
.indexes
.invalidate_if(move |object, _| !present.contains(object));
ensure!(
!listed.is_empty(),
MissingSourceWalHistorySnafu {
region_id,
prefix: self.prefix().to_string(),
storage: self.io.storage(),
reason: format!("no WAL objects from sequence {start} in {}", self.prefix()),
}
);
if let WalReadUpperBound::Listed(upto) = upper {
ensure!(
listed
.iter()
.any(|object| object.object_seq >= upto >> POSITION_BITS),
CorruptedWalObjectSnafu {
reason: format!(
"WAL listing of {} does not reach recorded bound {upto}",
self.prefix()
),
}
);
}
let objects = futures::stream::iter(listed)
.map(|object| async move {
let seq = object.object_seq;
// Include listing metadata in the key so a load for a changed
// object cannot join an older in-flight load of the same sequence.
let cached = self
.indexes
.try_get_with(&object, async {
// Waiters share the loader without consuming footer permits.
let _permit = self.footer_budget.acquire().await.map_err(|_| {
CorruptedWalObjectSnafu {
reason: "remote WAL footer budget closed".to_string(),
}
.build()
})?;
let fetched = index::fetch_footer(self.io.as_ref(), &object).await?;
Ok::<_, Error>(Arc::new(CachedObject {
object: object.clone(),
header: fetched.header,
footer: fetched.footer,
}))
})
.await
.context(ObjectStoreWalSnafu)?;
Ok::<_, Error>((seq, cached))
})
.buffer_unordered(FOOTER_CONCURRENCY)
.try_collect::<BTreeMap<_, _>>()
.await?;
let headers = objects
.iter()
.map(|(seq, object)| (*seq, &object.header))
.collect::<BTreeMap<_, _>>();
let chain = match upper {
WalReadUpperBound::LastEntry(last) => {
// A later writer may already have reclaimed the oldest part.
// The reported L itself must still exist and be replayed.
let boundary = headers
.values()
.map(|header| header.reclaim_boundary)
.max()
.unwrap_or(0)
.max(start);
index::chain_from(&headers, last >> POSITION_BITS, boundary).with_context(|| {
CorruptedWalObjectSnafu {
reason: format!(
"missing WAL chain ending at reported entry {last} in {}",
self.prefix()
),
}
})?
}
WalReadUpperBound::Listed(_) => {
let chain = index::select_chain(&headers);
let tip = chain.last().with_context(|| CorruptedWalObjectSnafu {
reason: format!("no complete WAL chain in {}", self.prefix()),
})?;
let max_epoch = headers
.values()
.map(|header| header.epoch)
.max()
.unwrap_or(0);
ensure!(
headers[tip].epoch == max_epoch,
CorruptedWalObjectSnafu {
reason: format!(
"WAL chain in {} would fall back from epoch {max_epoch} to {}",
self.prefix(),
headers[tip].epoch
),
}
);
chain
}
};
let mut catalog = ObjectCatalog::default();
let mut history_end = 0;
for seq in chain {
let object = &objects[&seq];
history_end = history_end.max(
object
.footer
.iter()
.map(|entry| sequence_floor(entry.max_entry_id))
.max()
.unwrap_or(0),
);
// Keep only this region in the per-read catalog. All regions share
// the source's cached footers, rather than copying the entire node
// index into every concurrent region recovery.
let footer = object
.footer
.iter()
.filter(|entry| entry.region_id == region_id)
.cloned()
.collect();
catalog
.insert_object(seq, footer)
.with_context(|_| InvalidWalObjectSnafu {
path: object.object.path.clone(),
})?;
}
if matches!(upper, WalReadUpperBound::Listed(_))
&& let Some(reason) =
history::missing_history(&catalog, region_id, after, false, history_end)
{
return MissingSourceWalHistorySnafu {
region_id,
prefix: self.prefix().to_string(),
storage: self.io.storage(),
reason,
}
.fail();
}
Ok(catalog)
}
}
#[cfg(test)]
mod tests;
@@ -0,0 +1,878 @@
// 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.
use std::sync::atomic::{AtomicUsize, Ordering};
use std::time::Duration;
use bytes::Bytes;
use common_error::ext::ErrorExt;
use common_error::status_code::StatusCode;
use common_wal::config::object_store::ObjectStoreWalConfig;
use object_store::services::Memory;
use store_api::logstore::LogStore;
use super::*;
use crate::object_store_wal::ObjectStoreLogStore;
use crate::object_store_wal::format::{ChainLink, Header, Record, encode_object};
use crate::object_store_wal::io::ListedObject;
const PREFIX: &str = "wal/datanodes/1/epochs/0";
fn region() -> RegionId {
RegionId::new(1, 1)
}
fn record(seq: u64, position: u64) -> Record {
Record {
region_id: region(),
entry_id: entry_id(seq, position),
payload: Bytes::from(format!("{seq}/{position}")),
}
}
async fn put(
io: &ObjectStoreIo,
seq: u64,
epoch: u64,
prev: Option<(u64, u64)>,
boundary: u64,
records: &[Record],
) {
let object = encode_object(
Header {
object_seq: seq,
epoch,
prev: prev.map(|(object_seq, epoch)| ChainLink { object_seq, epoch }),
reclaim_boundary: boundary,
},
records,
)
.unwrap();
io.put_if_absent(seq, object.bytes).await.unwrap();
}
/// Implements only read capabilities. Reads can be parked to measure concurrent
/// index loads and cancellation deterministically.
struct ObservedIo {
io: ObjectStoreIo,
gets: Mutex<BTreeMap<u64, usize>>,
lists: Mutex<Vec<u64>>,
gate: Option<Arc<Semaphore>>,
active: AtomicUsize,
peak: AtomicUsize,
}
struct ActiveRead<'a>(&'a AtomicUsize);
impl Drop for ActiveRead<'_> {
fn drop(&mut self) {
self.0.fetch_sub(1, Ordering::SeqCst);
}
}
impl ObservedIo {
async fn begin_read(&self, seq: u64) -> ActiveRead<'_> {
*self.gets.lock().unwrap().entry(seq).or_default() += 1;
let active = self.active.fetch_add(1, Ordering::SeqCst) + 1;
self.peak.fetch_max(active, Ordering::SeqCst);
let guard = ActiveRead(&self.active);
if let Some(gate) = &self.gate {
gate.acquire().await.unwrap().forget();
}
guard
}
}
#[async_trait::async_trait]
impl WalObjectRead for ObservedIo {
async fn get(&self, seq: u64) -> Result<Bytes> {
let _guard = self.begin_read(seq).await;
self.io.get(seq).await
}
async fn get_range(&self, seq: u64, offset: u64, len: u64) -> Result<Bytes> {
let _guard = self.begin_read(seq).await;
self.io.get_range(seq, offset, len).await
}
async fn list(&self) -> Result<Vec<ListedObject>> {
self.lists.lock().unwrap().push(0);
self.io.list().await
}
async fn list_from(&self, seq: u64) -> Result<Vec<ListedObject>> {
self.lists.lock().unwrap().push(seq);
self.io.list_from(seq).await
}
fn object_path(&self, seq: u64) -> String {
self.io.object_path(seq)
}
fn storage(&self) -> String {
self.io.storage()
}
fn prefix(&self) -> &str {
self.io.prefix()
}
}
fn observed(io: ObjectStoreIo, gate: Option<Arc<Semaphore>>) -> Arc<ObservedIo> {
Arc::new(ObservedIo {
io,
gets: Mutex::new(BTreeMap::new()),
lists: Mutex::new(Vec::new()),
gate,
active: AtomicUsize::new(0),
peak: AtomicUsize::new(0),
})
}
fn reader(io: Arc<dyn WalObjectRead>, budget: Arc<Semaphore>) -> Arc<ObjectStoreWalReader> {
Arc::new(ObjectStoreWalReader {
io,
indexes: CachedObject::cache(),
footer_budget: budget,
prefetch_budget: Arc::new(Semaphore::new(prefetch::READ_PREFETCH_BYTES)),
})
}
fn fixture() -> (
ObjectStore,
ObjectStoreIo,
Arc<ObservedIo>,
Arc<ObjectStoreWalReader>,
) {
let store = ObjectStore::new(Memory::default()).unwrap();
let io = ObjectStoreIo::new(store.clone(), PREFIX).unwrap();
let observed = observed(io.clone(), None);
let reader = reader(
observed.clone(),
Arc::new(Semaphore::new(FOOTER_CONCURRENCY)),
);
(store, io, observed, reader)
}
async fn collect(
reader: &ObjectStoreWalReader,
after: u64,
upper: WalReadUpperBound,
) -> Result<Vec<Entry>> {
Ok(reader
.read(region(), after, upper)
.await?
.try_collect::<Vec<_>>()
.await?
.into_iter()
.flatten()
.collect())
}
fn expected(records: &[Record]) -> Vec<Entry> {
records
.iter()
.map(|record| {
Entry::Naive(NaiveEntry {
provider: Provider::object_store_provider(region(), PREFIX.to_string()),
region_id: region(),
entry_id: record.entry_id,
data: record.payload.to_vec(),
})
})
.collect()
}
#[tokio::test]
async fn test_reader_reads_existing_store_without_modifying_it() {
let store = ObjectStore::new(Memory::default()).unwrap();
let writer =
ObjectStoreLogStore::try_new(store.clone(), &ObjectStoreWalConfig::default(), 1, 0)
.await
.unwrap();
let provider = Provider::object_store_provider(region(), PREFIX.to_string());
let entry = writer
.entry(b"durable".to_vec(), 0, region(), &provider)
.unwrap();
writer.append_batch(vec![entry]).await.unwrap();
let last = writer.latest_entry_id(&provider).unwrap();
let io = ObjectStoreIo::new(store.clone(), PREFIX).unwrap();
let before = io.list().await.unwrap();
let registry = ObjectStoreWalReaders::new(store);
let reader = registry
.reader(&NodeWalPrefix::try_new(PREFIX).unwrap())
.unwrap();
assert!(Arc::ptr_eq(
&reader,
&registry
.reader(&NodeWalPrefix::try_new(&format!("{PREFIX}/")).unwrap())
.unwrap()
));
for upper in [
WalReadUpperBound::LastEntry(last),
WalReadUpperBound::Listed(reader.list_upper_bound(region()).await.unwrap()),
] {
assert_eq!(
collect(&reader, 0, upper).await.unwrap(),
vec![Entry::Naive(NaiveEntry {
provider: provider.clone(),
region_id: region(),
entry_id: last,
data: b"durable".to_vec(),
})]
);
}
assert_eq!(before, io.list().await.unwrap());
writer.stop().await.unwrap();
}
#[tokio::test]
async fn test_bounds_region_filtering_and_list_only_readiness() {
let (_, io, observed, reader) = fixture();
put(&io, 0, 1, None, 0, &[]).await;
let wanted = vec![record(1, 1), record(1, 2), record(1, 3)];
let mut mixed = wanted.clone();
mixed.push(Record {
region_id: RegionId::new(1, 2),
entry_id: entry_id(1, 1),
payload: Bytes::from_static(b"other"),
});
put(&io, 1, 1, Some((0, 1)), 0, &mixed).await;
let bound = reader.list_upper_bound(region()).await.unwrap();
assert_eq!(bound, entry_id(1, POSITION_LIMIT - 1));
assert!(observed.gets.lock().unwrap().is_empty());
for upper in [
WalReadUpperBound::LastEntry(entry_id(1, 2)),
WalReadUpperBound::Listed(entry_id(1, 2)),
] {
assert_eq!(
collect(&reader, entry_id(1, 1), upper).await.unwrap(),
expected(&wanted[1..2])
);
}
assert!(
reader
.read(region(), bound, WalReadUpperBound::Listed(bound))
.await
.is_err()
);
assert!(
reader
.read(region(), u64::MAX, WalReadUpperBound::Listed(bound))
.await
.is_err()
);
}
#[tokio::test]
async fn test_last_entry_anchors_its_chain_and_skips_history_before_after() {
let (_, io, observed, reader) = fixture();
// The predecessor of object 5 is below after's sequence; it may be absent.
put(&io, 5, 1, Some((2, 1)), 0, &[record(5, 1)]).await;
put(&io, 7, 1, Some((5, 1)), 0, &[record(7, 1)]).await;
// A newer, unrelated chain must not select away the known L.
put(&io, 8, 9, None, 0, &[record(8, 1)]).await;
assert_eq!(
collect(
&reader,
entry_id(4, 1),
WalReadUpperBound::LastEntry(entry_id(7, 1))
)
.await
.unwrap(),
expected(&[record(5, 1), record(7, 1)])
);
assert_eq!(*observed.lists.lock().unwrap(), vec![4]);
}
#[tokio::test]
async fn test_last_entry_requires_actual_entry_and_complete_chain() {
for missing in [0, 1, 2] {
let (_, io, _, reader) = fixture();
put(&io, 0, 1, None, 0, &[]).await;
if missing != 1 {
put(&io, 1, 1, Some((0, 1)), 0, &[record(1, 1)]).await;
}
if missing != 2 {
put(&io, 2, 1, Some((1, 1)), 0, &[record(2, 1)]).await;
}
let last = entry_id(2, if missing == 0 { 2 } else { 1 });
assert!(
collect(&reader, 0, WalReadUpperBound::LastEntry(last))
.await
.is_err()
);
}
}
#[tokio::test]
async fn test_last_entry_includes_after_object_and_checks_link_epoch() {
let (_, io, _, reader) = fixture();
put(&io, 3, 1, Some((1, 1)), 0, &[record(3, 1), record(3, 2)]).await;
assert_eq!(
collect(
&reader,
entry_id(3, 1),
WalReadUpperBound::LastEntry(entry_id(3, 2))
)
.await
.unwrap(),
expected(&[record(3, 2)])
);
put(&io, 4, 1, Some((3, 2)), 0, &[record(4, 1)]).await;
assert!(
collect(
&reader,
entry_id(3, 1),
WalReadUpperBound::LastEntry(entry_id(4, 1))
)
.await
.is_err()
);
}
#[tokio::test]
async fn test_listed_range_rejects_fallback_even_for_other_regions() {
let (_, io, _, reader) = fixture();
put(&io, 0, 1, None, 0, &[]).await;
put(&io, 1, 1, Some((0, 1)), 0, &[record(1, 1)]).await;
// The newer epoch has no entry of the requested region and its predecessor
// is missing. Filtering by region before comparing epochs would hide it.
put(&io, 5, 4, Some((3, 4)), 0, &[]).await;
let error = collect(
&reader,
0,
WalReadUpperBound::Listed(entry_id(5, POSITION_LIMIT - 1)),
)
.await
.unwrap_err();
assert!(error.to_string().contains("fall back"), "{error}");
// Known-L recovery does not require choosing the newest chain.
assert_eq!(
collect(&reader, 0, WalReadUpperBound::LastEntry(entry_id(1, 1)))
.await
.unwrap(),
expected(&[record(1, 1)])
);
}
#[tokio::test]
async fn test_empty_and_missing_history_fail_but_empty_region_tail_is_valid() {
let (_, io, _, reader) = fixture();
assert!(reader.list_upper_bound(region()).await.is_err());
assert!(
collect(&reader, 0, WalReadUpperBound::Listed(entry_id(1, 1)))
.await
.is_err()
);
put(&io, 0, 1, None, 0, &[]).await;
put(&io, 1, 1, Some((0, 1)), 0, &[record(1, 1)]).await;
assert!(
collect(
&reader,
entry_id(4, 1),
WalReadUpperBound::Listed(entry_id(5, 1))
)
.await
.is_err()
);
// No entry above after, and the LIST bound need not itself be an entry.
assert!(
collect(
&reader,
entry_id(1, 1),
WalReadUpperBound::Listed(entry_id(1, POSITION_LIMIT - 1))
)
.await
.unwrap()
.is_empty()
);
}
#[tokio::test]
async fn test_refresh_discovers_new_objects_and_reuses_only_present_indexes() {
let (_, io, observed, reader) = fixture();
put(&io, 0, 1, None, 0, &[]).await;
put(&io, 1, 1, Some((0, 1)), 0, &[record(1, 1)]).await;
let upper = WalReadUpperBound::Listed(reader.list_upper_bound(region()).await.unwrap());
assert_eq!(
collect(&reader, 0, upper).await.unwrap(),
expected(&[record(1, 1)])
);
let first = observed.gets.lock().unwrap().clone();
put(&io, 2, 1, Some((1, 1)), 0, &[record(2, 1)]).await;
assert_eq!(
collect(
&reader,
entry_id(1, 1),
WalReadUpperBound::Listed(entry_id(2, 1))
)
.await
.unwrap(),
expected(&[record(2, 1)])
);
// Neither the old index nor its data was fetched again.
assert_eq!(observed.gets.lock().unwrap()[&0], first[&0]);
assert_eq!(observed.gets.lock().unwrap()[&1], first[&1]);
assert_eq!(*observed.lists.lock().unwrap(), vec![0, 0, 0]);
io.delete(1).await.unwrap();
assert!(
collect(&reader, 0, WalReadUpperBound::LastEntry(entry_id(2, 1)))
.await
.is_err()
);
}
#[tokio::test]
async fn test_missing_and_corrupt_data_fail_after_prepare() {
for corrupt in [false, true] {
let (store, io, _, reader) = fixture();
put(&io, 0, 1, None, 0, &[]).await;
put(&io, 1, 1, Some((0, 1)), 0, &[record(1, 1)]).await;
let stream = reader
.read(region(), 0, WalReadUpperBound::LastEntry(entry_id(1, 1)))
.await
.unwrap();
if corrupt {
let mut bytes = io.get(1).await.unwrap().to_vec();
bytes[crate::object_store_wal::format::HEADER_LEN + 12] ^= 1;
store.write(&io.object_path(1), bytes).await.unwrap();
} else {
io.delete(1).await.unwrap();
}
assert!(stream.try_collect::<Vec<_>>().await.is_err());
}
}
#[tokio::test]
async fn test_reclaim_boundary_allows_missing_old_history() {
let (_, io, _, reader) = fixture();
put(&io, 5, 1, Some((2, 1)), 5, &[record(5, 1)]).await;
for upper in [
WalReadUpperBound::LastEntry(entry_id(5, 1)),
WalReadUpperBound::Listed(entry_id(5, 1)),
] {
assert_eq!(
collect(&reader, 0, upper).await.unwrap(),
expected(&[record(5, 1)])
);
}
}
#[tokio::test]
async fn test_footer_limit_is_shared_and_cancelled_refresh_releases_permits() {
let (_, io, _, _) = fixture();
for seq in 0..40 {
put(
&io,
seq,
1,
seq.checked_sub(1).map(|seq| (seq, 1)),
0,
&[record(seq, 1)],
)
.await;
}
let gate = Arc::new(Semaphore::new(0));
let observed = observed(io, Some(gate.clone()));
let budget = Arc::new(Semaphore::new(FOOTER_CONCURRENCY));
let first = reader(observed.clone(), budget.clone());
let second = reader(observed.clone(), budget.clone());
let task = tokio::spawn(async move {
first
.prepare(region(), 0, WalReadUpperBound::Listed(entry_id(39, 1)))
.await
});
tokio::time::timeout(Duration::from_secs(10), async {
while observed.active.load(Ordering::SeqCst) != FOOTER_CONCURRENCY {
tokio::task::yield_now().await;
}
})
.await
.unwrap();
assert_eq!(budget.available_permits(), 0);
task.abort();
assert!(task.await.unwrap_err().is_cancelled());
assert_eq!(budget.available_permits(), FOOTER_CONCURRENCY);
assert_eq!(observed.active.load(Ordering::SeqCst), 0);
let third = reader(observed.clone(), budget);
gate.add_permits(100);
let (a, b) = tokio::join!(
second.prepare(region(), 0, WalReadUpperBound::Listed(entry_id(39, 1))),
third.prepare(region(), 0, WalReadUpperBound::Listed(entry_id(39, 1))),
);
a.unwrap();
b.unwrap();
assert!(observed.peak.load(Ordering::SeqCst) <= FOOTER_CONCURRENCY);
}
fn assert_missing_history(error: Error, storage: &str) {
assert_eq!(error.status_code(), StatusCode::InvalidArguments);
assert!(!error.to_string().contains("accept_missing_history"));
assert!(error.to_string().contains("Check the source node prefix"));
match error {
Error::MissingSourceWalHistory {
region_id,
prefix,
storage: actual,
reason,
..
} => {
assert_eq!(region_id, region());
assert_eq!(prefix, PREFIX);
assert_eq!(actual, storage);
assert!(!reason.is_empty());
}
error => panic!("expected missing history, got {error}"),
}
}
#[tokio::test]
async fn test_missing_history_error_context() {
let (_, io, _, reader) = fixture();
assert_missing_history(
reader.list_upper_bound(region()).await.unwrap_err(),
&io.storage(),
);
for upper in [
WalReadUpperBound::Listed(entry_id(1, 1)),
WalReadUpperBound::LastEntry(entry_id(1, 1)),
] {
assert_missing_history(collect(&reader, 0, upper).await.unwrap_err(), &io.storage());
}
// The listing reaches the bound, but the surviving chain has no history
// covering the region's watermark.
put(&io, 5, 1, None, 5, &[]).await;
assert_missing_history(
collect(
&reader,
entry_id(4, 1),
WalReadUpperBound::Listed(entry_id(5, 1)),
)
.await
.unwrap_err(),
&io.storage(),
);
}
#[tokio::test]
async fn test_list_upper_bound_checks_object_sequence_limit() {
for seq in [
OBJECT_SEQ_LIMIT - 1,
OBJECT_SEQ_LIMIT,
10_000_000_000_000_000_000,
] {
let (store, io, observed, reader) = fixture();
// Only the key is needed for readiness; no header or footer is read.
store
.write(&io.object_path(seq), Bytes::new())
.await
.unwrap();
let bound = reader.list_upper_bound(region()).await;
if seq < OBJECT_SEQ_LIMIT {
assert_eq!(bound.unwrap(), u64::MAX);
} else {
assert!(
matches!(bound.unwrap_err(), Error::CorruptedWalObject { reason, .. } if reason.contains(&io.object_path(seq)) && reason.contains("outside the entry-id range"))
);
}
assert!(observed.gets.lock().unwrap().is_empty());
}
}
#[tokio::test]
async fn test_same_reader_prepares_regions_concurrently() {
let (_, io, _, _) = fixture();
put(&io, 1, 1, None, 0, &[record(1, 1)]).await;
let gate = Arc::new(Semaphore::new(0));
let observed = observed(io, Some(gate.clone()));
let budget = Arc::new(Semaphore::new(FOOTER_CONCURRENCY));
let reader = reader(observed.clone(), budget.clone());
let upper = WalReadUpperBound::Listed(entry_id(1, 1));
let first = tokio::spawn({
let reader = reader.clone();
async move { reader.prepare(region(), 0, upper).await }
});
tokio::time::timeout(Duration::from_secs(10), async {
while observed.active.load(Ordering::SeqCst) != 1 {
tokio::task::yield_now().await;
}
})
.await
.unwrap();
// Poll the second preparation into its pending load while the first GET is
// parked. Its LIST must finish independently, but its footer load is shared.
let second = reader.prepare(RegionId::new(1, 2), 0, upper);
tokio::pin!(second);
assert!(futures::poll!(&mut second).is_pending());
assert_eq!(*observed.lists.lock().unwrap(), vec![0, 0]);
assert_eq!(observed.active.load(Ordering::SeqCst), 1);
assert_eq!(budget.available_permits(), FOOTER_CONCURRENCY - 1);
gate.add_permits(1);
assert_eq!(
first.await.unwrap().unwrap().region_max_entry_id(region()),
Some(entry_id(1, 1))
);
assert_eq!(
tokio::time::timeout(Duration::from_secs(10), second)
.await
.unwrap()
.unwrap()
.region_max_entry_id(RegionId::new(1, 2)),
None
);
assert_eq!(*observed.gets.lock().unwrap(), BTreeMap::from([(1, 1)]));
assert_eq!(budget.available_permits(), FOOTER_CONCURRENCY);
}
#[tokio::test]
async fn test_last_entry_evicts_indexes_as_watermark_advances() {
let (_, io, _, reader) = fixture();
for seq in 1..=6 {
put(
&io,
seq,
1,
(seq > 1).then_some((seq - 1, 1)),
0,
&[record(seq, 1), record(seq, 2)],
)
.await;
}
let upper = WalReadUpperBound::LastEntry(entry_id(6, 2));
reader.prepare(region(), 0, upper).await.unwrap();
let listed = io.list().await.unwrap();
for start in 2..=6 {
let old = Arc::downgrade(
&reader
.indexes
.get(&listed[(start - 2) as usize])
.await
.unwrap(),
);
io.delete(start - 1).await.unwrap();
reader
.prepare(region(), entry_id(start, 1), upper)
.await
.unwrap();
assert_eq!(
cached_sequences(&reader, &listed).await,
(start..=6).collect::<Vec<_>>()
);
wait_for_index_release(&reader, &old).await;
}
let last = Arc::downgrade(&reader.indexes.get(&listed[5]).await.unwrap());
io.delete(6).await.unwrap();
assert!(matches!(
reader.prepare(region(), entry_id(6, 1), upper).await,
Err(Error::MissingSourceWalHistory { .. })
));
assert!(reader.indexes.get(&listed[5]).await.is_none());
wait_for_index_release(&reader, &last).await;
assert_eq!(reader.indexes.entry_count(), 0);
}
#[tokio::test]
async fn test_last_entry_refetches_evicted_indexes_for_lower_watermark() {
let (_, io, observed, reader) = fixture();
put(&io, 1, 1, None, 0, &[record(1, 1)]).await;
put(&io, 2, 1, Some((1, 1)), 0, &[record(2, 1), record(2, 2)]).await;
let upper = WalReadUpperBound::LastEntry(entry_id(2, 2));
reader.prepare(region(), 0, upper).await.unwrap();
reader
.prepare(region(), entry_id(2, 1), upper)
.await
.unwrap();
let listed = io.list().await.unwrap();
reader.indexes.run_pending_tasks().await;
assert_eq!(cached_sequences(&reader, &listed).await, vec![2]);
let before = observed.gets.lock().unwrap().clone();
let catalog = reader.prepare(region(), 0, upper).await.unwrap();
assert_eq!(catalog.region_max_entry_id(region()), Some(entry_id(2, 2)));
let after = observed.gets.lock().unwrap().clone();
assert_eq!(after[&1], before[&1] + 1);
assert_eq!(after[&2], before[&2]);
assert_eq!(cached_sequences(&reader, &listed).await, vec![1, 2]);
}
#[test]
fn test_node_prefix_validates_layout_and_exposes_provider_identity() {
let registry = ObjectStoreWalReaders::new(ObjectStore::new(Memory::default()).unwrap());
assert!(NodeWalPrefix::try_new("wal/datanodes/0/epochs/0").is_ok());
for root in ["wal", "archive/team/wal"] {
let config = ObjectStoreWalConfig {
prefix: root.to_string(),
..Default::default()
};
let expected = config.node_prefix(12, 34);
let prefix = NodeWalPrefix::try_new(&expected).unwrap();
let trailing = NodeWalPrefix::try_new(&format!("{expected}/")).unwrap();
assert_eq!(prefix, trailing);
assert_eq!(prefix.as_str(), expected);
let first = registry.reader(&prefix).unwrap();
assert_eq!(first.prefix(), expected);
assert!(Arc::ptr_eq(&first, &registry.reader(&trailing).unwrap()));
}
for invalid in [
"",
"wal",
"wal/datanodes/1",
"wal/datanodes/1/epochs/2/objects",
"datanodes/1/epochs/2",
"/wal/datanodes/1/epochs/2",
"wal//datanodes/1/epochs/2",
"wal/../datanodes/1/epochs/2",
"wal/datanodes/a/epochs/2",
"wal/datanodes/1/epochs/a",
"wal/datanodes/+1/epochs/2",
"wal/datanodes/01/epochs/2",
"wal/datanodes/0/epochs/02",
"wal/datanodes/00/epochs/0",
"wal/datanodes/1/epochs/18446744073709551616",
] {
assert!(
matches!(
NodeWalPrefix::try_new(invalid),
Err(Error::InvalidWalObjectStore { .. })
),
"{invalid}"
);
}
}
/// Invalidation hides an index immediately, but physical release may require
/// multiple cache maintenance passes. Wait for release rather than a pass count.
async fn wait_for_index_release(reader: &ObjectStoreWalReader, index: &Weak<CachedObject>) {
tokio::time::timeout(Duration::from_secs(10), async {
while index.upgrade().is_some() {
reader.indexes.run_pending_tasks().await;
tokio::task::yield_now().await;
}
})
.await
.expect("obsolete index remains allocated after cache maintenance");
}
async fn cached_sequences(reader: &ObjectStoreWalReader, listed: &[ListedObject]) -> Vec<u64> {
let mut sequences = Vec::new();
for object in listed {
if reader.indexes.get(object).await.is_some() {
sequences.push(object.object_seq);
}
}
sequences
}
#[tokio::test]
async fn test_selected_chain_excludes_orphan_inside_read_range() {
let (_, io, _, reader) = fixture();
put(&io, 0, 1, None, 0, &[]).await;
put(&io, 1, 1, Some((0, 1)), 0, &[record(1, 1)]).await;
// Object 2 is an orphan from an unsuccessful write; object 3 links past it.
put(&io, 2, 1, Some((1, 1)), 0, &[record(2, 1)]).await;
put(&io, 3, 1, Some((1, 1)), 0, &[record(3, 1)]).await;
for upper in [
WalReadUpperBound::LastEntry(entry_id(3, 1)),
WalReadUpperBound::Listed(entry_id(3, POSITION_LIMIT - 1)),
] {
assert_eq!(
collect(&reader, 0, upper).await.unwrap(),
expected(&[record(1, 1), record(3, 1)])
);
}
}
#[tokio::test]
async fn test_listing_must_reach_recorded_bound_even_with_valid_watermark() {
let (_, io, _, reader) = fixture();
put(&io, 0, 1, None, 0, &[]).await;
put(&io, 1, 1, Some((0, 1)), 0, &[record(1, 1)]).await;
let error = collect(
&reader,
entry_id(1, 1),
WalReadUpperBound::Listed(entry_id(2, POSITION_LIMIT - 1)),
)
.await
.unwrap_err();
assert!(
matches!(error, Error::CorruptedWalObject { reason, .. } if reason.contains("does not reach recorded bound"))
);
}
#[tokio::test]
async fn test_last_entry_uses_reclaim_boundary_from_later_object() {
let (_, io, _, reader) = fixture();
// L retains its original boundary, but a later object records reclamation
// of its predecessor. Known-L recovery must honor that newer boundary.
put(&io, 5, 1, Some((2, 1)), 0, &[record(5, 1)]).await;
put(&io, 6, 1, Some((5, 1)), 5, &[record(6, 1)]).await;
assert_eq!(
collect(&reader, 0, WalReadUpperBound::LastEntry(entry_id(5, 1)))
.await
.unwrap(),
expected(&[record(5, 1)])
);
}
#[tokio::test]
async fn test_listed_history_end_includes_other_regions() {
let (_, io, _, reader) = fixture();
let other = |seq| Record {
region_id: RegionId::new(1, 2),
..record(seq, 1)
};
put(&io, 0, 1, None, 0, &[]).await;
put(&io, 1, 1, Some((0, 1)), 0, &[record(1, 1), other(1)]).await;
put(&io, 2, 1, Some((1, 1)), 0, &[other(2)]).await;
assert!(
collect(
&reader,
entry_id(2, 1),
WalReadUpperBound::Listed(entry_id(2, POSITION_LIMIT - 1))
)
.await
.unwrap()
.is_empty()
);
}
#[tokio::test]
async fn test_changed_listing_metadata_refetches_index() {
let (store, io, observed, reader) = fixture();
put(&io, 1, 1, None, 0, &[record(1, 1)]).await;
reader
.prepare(region(), 0, WalReadUpperBound::LastEntry(entry_id(1, 1)))
.await
.unwrap();
let before = observed.gets.lock().unwrap()[&1];
let replacement = encode_object(
Header {
object_seq: 1,
epoch: 1,
prev: None,
reclaim_boundary: 0,
},
&[record(1, 1), record(1, 2)],
)
.unwrap();
store
.write(&io.object_path(1), replacement.bytes)
.await
.unwrap();
let catalog = reader
.prepare(region(), 0, WalReadUpperBound::LastEntry(entry_id(1, 2)))
.await
.unwrap();
assert_eq!(catalog.region_max_entry_id(region()), Some(entry_id(1, 2)));
assert_eq!(observed.gets.lock().unwrap()[&1], before + 1);
}
+166 -530
View File
@@ -14,9 +14,9 @@
//! Object store WAL construction, recovery, writes and region reads.
use std::cmp::Reverse;
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet, VecDeque};
use std::fmt;
#[cfg(any(test, feature = "testing"))]
use std::ops::Range;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex, PoisonError, RwLock};
@@ -27,17 +27,16 @@ use bytes::Bytes;
use common_telemetry::{debug, error, info, warn};
use common_wal::config::object_store::{AckMode, CorruptedSegmentAction, ObjectStoreWalConfig};
use futures::future::{BoxFuture, OptionFuture};
use futures::stream::{BoxStream, FuturesUnordered};
use futures::{Stream, StreamExt, TryStreamExt};
use futures::stream::FuturesUnordered;
use futures::{StreamExt, TryStreamExt};
use object_store::{ErrorKind, ObjectStore};
use snafu::{IntoError, OptionExt, ResultExt, ensure};
use store_api::logstore::entry::{Entry, NaiveEntry};
use store_api::logstore::provider::{ObjectStoreProvider, Provider};
use store_api::logstore::{AppendBatchResponse, EntryId, LogStore, SendableEntryStream};
use store_api::storage::RegionId;
use tokio::sync::{OwnedSemaphorePermit, Semaphore, mpsc, oneshot, watch};
use tokio::sync::{Semaphore, mpsc, oneshot, watch};
use tokio::time::MissedTickBehavior;
use tokio_util::task::AbortOnDropHandle;
use crate::error::{
CorruptedWalObjectSnafu, Error, IncompleteWalEntrySnafu, InvalidProviderSnafu,
@@ -45,7 +44,7 @@ use crate::error::{
MismatchedWalRegionSnafu, MissingWalHistorySnafu, ObjectStoreWalFailingSnafu,
ObjectStoreWalSnafu, ObjectStoreWalStoppedSnafu, Result, StaleWalObjectSnafu,
UnconfirmedWalEpochStartSnafu, WalObjectSequenceExhaustedSnafu,
WalObjectSequenceUnsettledSnafu, WalSegmentFetchSnafu, WalStartWithdrawnSnafu,
WalObjectSequenceUnsettledSnafu, WalStartWithdrawnSnafu,
};
use crate::metrics::{
METRIC_OBJECT_STORE_WAL_APPEND_ACK_SECONDS, METRIC_OBJECT_STORE_WAL_CREATE_CONFLICTS_TOTAL,
@@ -64,12 +63,13 @@ use crate::metrics::{
use crate::object_store_wal::batch::{OBJECT_SEQ_LIMIT, OpenBatch, entry_id, sequence_floor};
use crate::object_store_wal::catalog::ObjectCatalog;
use crate::object_store_wal::format::{
ChainLink, EncodedObject, FixedTrailer, FooterEntry, HEADER_LEN, Header, MIN_OBJECT_LEN,
RELEASE_REGION_ID, Record, Release, TRAILER_LEN, decode_footer, decode_header, decode_releases,
decode_segment, decode_trailer, encode_object, encode_releases, footer_range, object_len,
verify_segment_ranges,
ChainLink, EncodedObject, FooterEntry, HEADER_LEN, Header, RELEASE_REGION_ID, Record, Release,
decode_header, decode_releases, decode_segment, encode_object, encode_releases, object_len,
};
use crate::object_store_wal::io::{ListedObject, ObjectStoreIo, PutResult};
use crate::object_store_wal::index::{FetchedObject, FetchedObjects, fetch_footers, select_chain};
use crate::object_store_wal::io::{ObjectStoreIo, PutResult, WalObjectIo};
use crate::object_store_wal::prefetch::READ_PREFETCH_BYTES;
use crate::object_store_wal::{history, prefetch};
const COMMAND_BUFFER: usize = 1024;
/// Appends queued for the actor; a caller beyond them waits to send.
@@ -103,36 +103,8 @@ const MAX_SEALED_BATCHES: usize = 2 * MAX_IN_FLIGHT_CREATES;
/// 10,000 objects recover in about 10 s instead of about 100 s at 8, while the
/// reads use about a third of S3's request rate per prefix, leaving room for
/// the data file reads of start-up. Each lane holds one
/// [`RECOVERY_TAIL_WINDOW`], 4 MiB in all.
/// [`crate::object_store_wal::index::RECOVERY_TAIL_WINDOW`], 4 MiB in all.
const RECOVERY_CONCURRENCY: usize = 64;
/// Number of segments a read fetches ahead of the one whose entries it
/// yields. On S3 a replay that fetched each segment after the previous one
/// spent about 30 ms per object; with eight fetches in flight a segment
/// arrives about every 4 ms. The segments fetched ahead also take their bytes
/// from [`READ_PREFETCH_BYTES`].
const READ_PREFETCH_DEPTH: usize = 8;
/// Bytes of decoded segments that all reads of a store together fetch ahead; a
/// segment counts as its length, which bounds its payloads, plus a [`Record`]
/// per entry. A read always fetches the segment it yields next, as a read that
/// fetched one segment at a time did, and a later segment only while it fits
/// in what is left, so regions replayed in parallel hold one segment each, up
/// to about `max_batch_bytes` or more for one oversized append, plus at most
/// these bytes, however many regions open at once. While a fetch copies the
/// payloads out of the downloaded segment it briefly holds the segment's
/// length once more.
const READ_PREFETCH_BYTES: usize = 64 * 1024 * 1024;
/// Bytes recovery reads from the end of an object in one request. The window
/// holds the trailer and the footer of an object with up to 1364 regions of
/// 48 bytes each, so a second request for the footer is rare, and usually the
/// segment of release records, which is the last segment.
const RECOVERY_TAIL_WINDOW: usize = 64 * 1024;
/// Largest segment of release records that recovery keeps from the bytes it
/// read for a footer. It keeps them before it knows which objects are on the
/// chain, so the bound caps what objects off the chain hold until recovery
/// ends; a larger segment is read again if its object is on the chain. A
/// release seals its record at once, so a segment usually holds the records of
/// one or a few regions, 16 bytes each.
const MAX_KEPT_RELEASE_BYTES: u64 = 4 * 1024;
/// A log store over the immutable WAL objects under one prefix.
///
@@ -649,29 +621,13 @@ impl ObjectStoreLogStore {
{
return None;
}
if self
.catalog
.read()
.unwrap_or_else(PoisonError::into_inner)
.region_max_entry_id(region_id)
.is_some_and(|max_entry_id| max_entry_id >= entry_id)
{
return None;
}
if self.found_empty {
return Some("the prefix held no object when the WAL opened".to_string());
}
let sequence_floor = sequence_floor(entry_id);
(sequence_floor > self.history_end).then(|| {
let held = match self.history_end {
0 => "no entry".to_string(),
history_end => format!("entries only in objects below {history_end}"),
};
format!(
"its watermark, entry {entry_id}, names object {}, but the prefix held {held} when the WAL opened",
sequence_floor - 1
)
})
history::missing_history(
&self.catalog.read().unwrap_or_else(PoisonError::into_inner),
region_id,
entry_id,
self.found_empty,
self.history_end,
)
}
/// Deletes the start object of a store that found its prefix empty and
@@ -956,7 +912,7 @@ impl LogStore for ObjectStoreLogStore {
/// An object collected after the read listed it is skipped. Otherwise a
/// segment that does not decode fails the read or is skipped and recorded
/// as a hole, as `on_corrupted_segment` says; a failed fetch always fails
/// the read. Up to [`READ_PREFETCH_DEPTH`] segments are fetched ahead
/// the read. Up to [`prefetch::READ_PREFETCH_DEPTH`] segments are fetched ahead
/// while [`READ_PREFETCH_BYTES`] allows, and each outcome is handled in
/// sequence order.
async fn read(
@@ -999,35 +955,8 @@ impl LogStore for ObjectStoreLogStore {
let prefetch_budget = self.read_prefetch_budget.clone();
Ok(Box::pin(try_stream! {
let started_at = Instant::now();
let mut objects = objects.into_iter().peekable();
let mut fetches = VecDeque::new();
loop {
// The next segment is always fetched, a later one only with
// its bytes reserved from the budget.
while fetches.len() < READ_PREFETCH_DEPTH {
let Some((_, entry)) = objects.peek() else {
break;
};
let permit = if fetches.is_empty() {
None
} else {
match try_reserve_prefetch_bytes(&prefetch_budget, entry) {
Some(permit) => Some(permit),
None => break,
}
};
let Some((object_seq, footer_entry)) = objects.next() else {
break;
};
let fetch =
spawn_fetch_segment(io.clone(), object_seq, footer_entry.clone(), permit);
fetches.push_back((object_seq, footer_entry, fetch));
}
let Some((object_seq, footer_entry, fetch)) = fetches.pop_front() else {
break;
};
// The permit is held until the entries of the segment are yielded.
let (fetched, _permit) = fetch.await;
let mut segments = prefetch::segments(io.clone(), objects, prefetch_budget);
while let Some((object_seq, footer_entry, fetched)) = segments.next().await {
let records = match fetched {
Ok(records) => records,
Err(error) if is_collected(&catalog, &deleting, object_seq).await => {
@@ -2895,66 +2824,6 @@ async fn is_collected(
.contains_object(object_seq)
}
/// Fetches and decodes the segment `entry` describes in the object
/// `object_seq`. A segment that does not decode is fetched once more, since
/// the download rather than the object may be damaged; when it still does not
/// decode the error is returned as [`Error::InvalidWalObject`]. A failed fetch
/// is returned as is.
async fn fetch_segment(
io: &dyn WalObjectIo,
object_seq: u64,
entry: &FooterEntry,
) -> Result<Vec<Record>> {
let fetch = || io.get_range(object_seq, entry.segment_offset, entry.segment_len);
if let Ok(records) = decode_segment(&fetch().await?, entry) {
return Ok(records);
}
decode_segment(&fetch().await?, entry).with_context(|_| InvalidWalObjectSnafu {
path: io.object_path(object_seq),
})
}
/// Takes from `budget` the bytes the segment `entry` describes holds once
/// decoded, if they are free: its length plus a [`Record`] per entry.
fn try_reserve_prefetch_bytes(
budget: &Arc<Semaphore>,
entry: &FooterEntry,
) -> Option<OwnedSemaphorePermit> {
let records = u64::from(entry.entry_count) * std::mem::size_of::<Record>() as u64;
let bytes = u32::try_from(entry.segment_len.checked_add(records)?).ok()?;
budget.clone().try_acquire_many_owned(bytes).ok()
}
/// Runs [`fetch_segment`] on a task of its own, so the fetch proceeds while
/// the read is busy with earlier segments, and returns the outcome with
/// `permit`. The task holds the permit, so the reserved bytes are released
/// only with the buffers of the fetch. Dropping the returned future, as a
/// dropped read does, aborts the task; a task that panics fails the fetch with
/// [`Error::WalSegmentFetch`].
fn spawn_fetch_segment(
io: Arc<dyn WalObjectIo>,
object_seq: u64,
entry: FooterEntry,
permit: Option<OwnedSemaphorePermit>,
) -> impl Future<Output = (Result<Vec<Record>>, Option<OwnedSemaphorePermit>)> + Send + 'static {
let task_io = io.clone();
let task = AbortOnDropHandle::new(common_runtime::spawn_global(async move {
let fetched = fetch_segment(task_io.as_ref(), object_seq, &entry).await;
(fetched, permit)
}));
async move {
match task.await {
Ok(fetched) => fetched,
Err(error) => (
Err(error).context(WalSegmentFetchSnafu {
path: io.object_path(object_seq),
}),
None,
),
}
}
}
/// Records the segment `entry` describes in the object `object_seq` as a hole
/// of its region, once per object, counts the skip and warns about it. An
/// object collected meanwhile is skipped without a hole: the catalog is held
@@ -3049,24 +2918,6 @@ struct Recovered {
recovered_objects: u64,
}
/// The objects recovery fetched, ordered by sequence, and the listed objects
/// that were gone when their header or footer was fetched, with the error the
/// fetch met. A collection of an earlier instance may complete after the
/// listing.
struct FetchedObjects {
objects: Vec<FetchedObject>,
vanished: Vec<(u64, Error)>,
}
/// An object as recovery fetched it: its key, header and footer, and its
/// segment of release records when the reads of the footer returned it.
struct FetchedObject {
object: ListedObject,
header: Header,
footer: Vec<FooterEntry>,
releases: Option<Bytes>,
}
/// Rebuilds the catalog from object headers and footers,
/// so recovery costs a few small reads per object however large the objects
/// are. Segments are not read, except those of release records, see
@@ -3237,52 +3088,6 @@ fn finish_recovery(fetched: FetchedObjects) -> Result<Recovered> {
})
}
/// Returns, in sequence order, the objects on the chain that ends at the tip:
/// the complete object with the largest epoch, then the largest sequence.
///
/// An object is complete when every link on its chain holds, judged with the
/// reclaim boundary of that object: the chain starts at an object without a
/// predecessor or reaches a predecessor below the boundary, whether or not it
/// is present, and every other link names a present object that carries the
/// epoch the link records. The chain of the tip ends there, so objects below
/// its boundary are not replayed. Only one instance writes
/// under an epoch, so the epoch tells an object of the linking instance from
/// another object under the same sequence. A create that
/// was reported as failed may still leave its object, but every object
/// written after that failure links past it, and every instance writes under
/// an epoch above every object present when it opened, so neither such an
/// object nor a late object of an earlier instance ends the chosen chain.
fn select_chain(headers: &BTreeMap<u64, &Header>) -> Vec<u64> {
let mut candidates = headers.iter().collect::<Vec<_>>();
candidates.sort_unstable_by_key(|(object_seq, header)| Reverse((header.epoch, **object_seq)));
candidates
.into_iter()
.find_map(|(object_seq, _)| chain_ending_at(headers, *object_seq))
.unwrap_or_default()
}
/// Returns, in sequence order, the chain that ends at `tip` if `tip` is
/// complete, see [`select_chain`].
fn chain_ending_at(headers: &BTreeMap<u64, &Header>, tip: u64) -> Option<Vec<u64>> {
let reclaim_boundary = headers[&tip].reclaim_boundary;
let mut chain = vec![tip];
let mut header = headers[&tip];
while let Some(link) = header.prev {
if link.object_seq >= header.object_seq {
return None;
}
if link.object_seq < reclaim_boundary {
break;
}
header = headers
.get(&link.object_seq)
.filter(|prev| prev.epoch == link.epoch)?;
chain.push(link.object_seq);
}
chain.reverse();
Some(chain)
}
/// Writes the empty object that starts the epoch of this instance at
/// `object_seq`, linked to the recovered `tip` and carrying the recovered
/// `reclaim_boundary`, and returns it as the tip later objects extend,
@@ -3375,157 +3180,6 @@ async fn stale_conflict(
.fail()
}
/// Fetches and verifies the headers and footers of `objects` as they are
/// listed, up to `concurrency` objects at a time, and returns them ordered by
/// object sequence whatever the order the fetches complete in. An object the
/// object store no longer has is returned as vanished; a failed listing or
/// any other failure abandons the remaining fetches.
async fn fetch_footers(
io: &dyn WalObjectIo,
objects: impl Stream<Item = Result<ListedObject>>,
concurrency: usize,
) -> Result<FetchedObjects> {
let outcomes = objects
.map_ok(|object| async move {
match fetch_footer(io, &object).await {
Ok((header, footer, releases)) => Ok(Ok(FetchedObject {
object,
header,
footer,
releases,
})),
Err(error) if is_not_found(&error) => Ok(Err((object.object_seq, error))),
Err(error) => Err(error),
}
})
.try_buffer_unordered(concurrency)
.try_collect::<Vec<_>>()
.await?;
let mut objects = Vec::with_capacity(outcomes.len());
let mut vanished = Vec::new();
for outcome in outcomes {
match outcome {
Ok(object) => objects.push(object),
Err(gone) => vanished.push(gone),
}
}
objects.sort_unstable_by_key(|fetched| fetched.object.object_seq);
Ok(FetchedObjects { objects, vanished })
}
fn is_not_found(error: &Error) -> bool {
matches!(error, Error::WalObjectStore { error, .. } if error.kind() == object_store::ErrorKind::NotFound)
}
/// Reads the header, trailer and footer of `object` and verifies them: the
/// header must carry the sequence of the key, the trailer must be well formed,
/// the footer must match the checksum the trailer holds and its segments must
/// tile the object body. Also returns a copy of the segment of release records
/// when the bytes read hold it and it is at most [`MAX_KEPT_RELEASE_BYTES`],
/// which is not decoded here.
///
/// A short object is read whole. Otherwise the header and a window at the end
/// of the object are read concurrently, and the footer is read separately only
/// when it starts before the window.
async fn fetch_footer(
io: &dyn WalObjectIo,
object: &ListedObject,
) -> Result<(Header, Vec<FooterEntry>, Option<Bytes>)> {
let ListedObject {
object_seq, size, ..
} = *object;
let invalid = |source: Error| {
InvalidWalObjectSnafu {
path: object.path.clone(),
}
.into_error(source)
};
let object_len = usize::try_from(size)
.ok()
.filter(|len| *len >= MIN_OBJECT_LEN)
.with_context(|| CorruptedWalObjectSnafu {
reason: format!(
"truncated object, expected at least {MIN_OBJECT_LEN} bytes, actual {size}"
),
})
.map_err(invalid)?;
let window = object_len.min(RECOVERY_TAIL_WINDOW);
let tail_start = object_len - window;
let (head, tail) = if tail_start == 0 {
let bytes = io.get(object_seq).await?;
(bytes.clone(), bytes)
} else {
futures::try_join!(
io.get_range(object_seq, 0, HEADER_LEN as u64),
io.get_range(object_seq, tail_start as u64, window as u64)
)?
};
if head.len() < HEADER_LEN || tail.len() != window {
return Err(invalid(
CorruptedWalObjectSnafu {
reason: format!(
"object holds fewer bytes than the listed {size}, head {} bytes, tail {} bytes",
head.len(),
tail.len()
),
}
.build(),
));
}
let (header, trailer, footer_range) =
locate_footer(object_seq, object_len, &head, &tail).map_err(invalid)?;
let footer = if footer_range.start >= tail_start {
tail.slice(footer_range.start - tail_start..footer_range.end - tail_start)
} else {
io.get_range(
object_seq,
footer_range.start as u64,
footer_range.len() as u64,
)
.await?
};
let footer = decode_footer(&footer, trailer).map_err(invalid)?;
verify_segment_ranges(&footer, footer_range.start).map_err(invalid)?;
// A copy, so the window is not kept until the releases are decoded.
let releases = footer
.iter()
.find(|entry| entry.region_id == RELEASE_REGION_ID)
.filter(|entry| {
entry.segment_offset >= tail_start as u64 && entry.segment_len <= MAX_KEPT_RELEASE_BYTES
})
.map(|entry| {
let start = entry.segment_offset as usize - tail_start;
Bytes::copy_from_slice(&tail[start..start + entry.segment_len as usize])
});
Ok((header, footer, releases))
}
/// Verifies the header and trailer of the object `object_seq` of `object_len`
/// bytes from its first bytes `head` and its last bytes `tail`, and returns
/// the header and the trailer with the range the footer occupies in the object.
fn locate_footer(
object_seq: u64,
object_len: usize,
head: &[u8],
tail: &[u8],
) -> Result<(Header, FixedTrailer, Range<usize>)> {
let header = decode_header(head)?;
ensure!(
header.object_seq == object_seq,
CorruptedWalObjectSnafu {
reason: format!(
"header sequence {} does not match key sequence {object_seq}",
header.object_seq
),
}
);
let trailer = decode_trailer(&tail[tail.len() - TRAILER_LEN..])?;
let footer_range = footer_range(trailer, object_len)?;
Ok((header, trailer, footer_range))
}
fn durable_entry_ids(catalog: &ObjectCatalog) -> HashMap<RegionId, EntryId> {
let mut entry_ids = HashMap::new();
for (_, footer) in catalog.objects_in_order() {
@@ -3539,70 +3193,6 @@ fn durable_entry_ids(catalog: &ObjectCatalog) -> HashMap<RegionId, EntryId> {
entry_ids
}
/// Object access of the store, so tests can inject failures.
#[async_trait::async_trait]
pub(crate) trait WalObjectIo: Send + Sync {
async fn put_if_absent(&self, object_seq: u64, content: Bytes) -> Result<PutResult>;
async fn get(&self, object_seq: u64) -> Result<Bytes>;
async fn get_range(&self, object_seq: u64, offset: u64, len: u64) -> Result<Bytes>;
async fn delete(&self, object_seq: u64) -> Result<()>;
async fn list(&self) -> Result<Vec<ListedObject>>;
/// See [`ObjectStoreIo::list_ahead`]; by default the objects
/// [`list`](Self::list) returns.
fn list_ahead(&self) -> BoxStream<'_, Result<ListedObject>> {
Box::pin(try_stream! {
for object in self.list().await? {
yield object;
}
})
}
fn object_path(&self, object_seq: u64) -> String;
/// Describes the object store the objects live in, for messages.
fn storage(&self) -> String;
}
#[async_trait::async_trait]
impl WalObjectIo for ObjectStoreIo {
async fn put_if_absent(&self, object_seq: u64, content: Bytes) -> Result<PutResult> {
ObjectStoreIo::put_if_absent(self, object_seq, content).await
}
async fn get(&self, object_seq: u64) -> Result<Bytes> {
ObjectStoreIo::get(self, object_seq).await
}
async fn get_range(&self, object_seq: u64, offset: u64, len: u64) -> Result<Bytes> {
ObjectStoreIo::get_range(self, object_seq, offset, len).await
}
async fn delete(&self, object_seq: u64) -> Result<()> {
ObjectStoreIo::delete(self, object_seq).await
}
async fn list(&self) -> Result<Vec<ListedObject>> {
ObjectStoreIo::list(self).await
}
fn list_ahead(&self) -> BoxStream<'_, Result<ListedObject>> {
ObjectStoreIo::list_ahead(self)
}
fn object_path(&self, object_seq: u64) -> String {
ObjectStoreIo::object_path(self, object_seq)
}
fn storage(&self) -> String {
ObjectStoreIo::storage(self)
}
}
#[cfg(test)]
mod tests {
use std::sync::atomic::AtomicUsize;
@@ -3610,7 +3200,8 @@ mod tests {
use common_base::readable_size::ReadableSize;
use common_error::ext::{ErrorExt, RetryHint};
use common_error::status_code::StatusCode;
use futures::FutureExt;
use futures::stream::BoxStream;
use futures::{FutureExt, Stream};
use object_store::layers::mock::{self, MockLayerBuilder, oio};
use object_store::services::Memory;
use object_store::util::with_retry_layers;
@@ -3620,7 +3211,15 @@ mod tests {
use super::*;
use crate::error::{WalObjectConflictSnafu, WalObjectStoreSnafu};
use crate::object_store_wal::batch::{POSITION_LIMIT, entry_id};
use crate::object_store_wal::format::{FOOTER_ENTRY_LEN, decode_object};
use crate::object_store_wal::format::{
FOOTER_ENTRY_LEN, FixedTrailer, MIN_OBJECT_LEN, TRAILER_LEN, decode_footer, decode_object,
decode_trailer, footer_range,
};
use crate::object_store_wal::index::{
MAX_KEPT_RELEASE_BYTES, RECOVERY_TAIL_WINDOW, fetch_footer, is_not_found,
};
use crate::object_store_wal::io::{ListedObject, WalObjectRead};
use crate::object_store_wal::prefetch::READ_PREFETCH_DEPTH;
const PREFIX: &str = "wal/datanodes/1/epochs/2";
const WAIT: Duration = Duration::from_secs(30);
@@ -4725,7 +4324,7 @@ mod tests {
// A memory store names itself by its address as its bucket.
"storage provider \"wal-store\" (memory, bucket ",
"root \"/\")",
"the prefix held no object when the WAL opened",
"the prefix held no object when the prefix was listed",
"copy every object under the prefix",
"`[wal].accept_missing_history = true`",
] {
@@ -4962,7 +4561,7 @@ mod tests {
for entry_id in [id(3, 1), id(9, 1)] {
let message = missing_history(&store, region_id, entry_id).await.unwrap();
let reason = format!(
"its watermark, entry {entry_id}, names object {}, but the prefix held entries only in objects below 3 when the WAL opened",
"its watermark, entry {entry_id}, names object {}, but the prefix held entries only in objects below 3 when the prefix was listed",
entry_id >> 20
);
assert!(message.contains(&reason), "{message}");
@@ -4995,7 +4594,9 @@ mod tests {
assert_eq!(None, missing_history(&store, region(1), 0).await);
let message = missing_history(&store, region(1), id(0, 1)).await.unwrap();
assert!(
message.contains("names object 0, but the prefix held no entry when the WAL opened"),
message.contains(
"names object 0, but the prefix held no entry when the prefix was listed"
),
"{message}"
);
store.stop().await.unwrap();
@@ -9913,6 +9514,33 @@ mod tests {
lose_next: AtomicBool,
}
#[async_trait::async_trait]
impl WalObjectRead for LostResponseIo {
async fn get(&self, object_seq: u64) -> Result<Bytes> {
self.inner.get(object_seq).await
}
async fn get_range(&self, object_seq: u64, offset: u64, len: u64) -> Result<Bytes> {
self.inner.get_range(object_seq, offset, len).await
}
async fn list(&self) -> Result<Vec<ListedObject>> {
self.inner.list().await
}
fn object_path(&self, object_seq: u64) -> String {
self.inner.object_path(object_seq)
}
fn storage(&self) -> String {
self.inner.storage()
}
fn prefix(&self) -> &str {
self.inner.prefix()
}
}
#[async_trait::async_trait]
impl WalObjectIo for LostResponseIo {
async fn put_if_absent(&self, object_seq: u64, content: Bytes) -> Result<PutResult> {
@@ -9930,6 +9558,20 @@ mod tests {
})
}
async fn delete(&self, object_seq: u64) -> Result<()> {
self.inner.delete(object_seq).await
}
}
/// Object access whose first create lets another object land at a given
/// sequence first, as a create issued before recovery would.
struct RacingIo {
inner: ObjectStoreIo,
late: Mutex<Option<(u64, Bytes)>>,
}
#[async_trait::async_trait]
impl WalObjectRead for RacingIo {
async fn get(&self, object_seq: u64) -> Result<Bytes> {
self.inner.get(object_seq).await
}
@@ -9938,10 +9580,6 @@ mod tests {
self.inner.get_range(object_seq, offset, len).await
}
async fn delete(&self, object_seq: u64) -> Result<()> {
self.inner.delete(object_seq).await
}
async fn list(&self) -> Result<Vec<ListedObject>> {
self.inner.list().await
}
@@ -9953,13 +9591,10 @@ mod tests {
fn storage(&self) -> String {
self.inner.storage()
}
}
/// Object access whose first create lets another object land at a given
/// sequence first, as a create issued before recovery would.
struct RacingIo {
inner: ObjectStoreIo,
late: Mutex<Option<(u64, Bytes)>>,
fn prefix(&self) -> &str {
self.inner.prefix()
}
}
#[async_trait::async_trait]
@@ -9972,29 +9607,9 @@ mod tests {
self.inner.put_if_absent(object_seq, content).await
}
async fn get(&self, object_seq: u64) -> Result<Bytes> {
self.inner.get(object_seq).await
}
async fn get_range(&self, object_seq: u64, offset: u64, len: u64) -> Result<Bytes> {
self.inner.get_range(object_seq, offset, len).await
}
async fn delete(&self, object_seq: u64) -> Result<()> {
self.inner.delete(object_seq).await
}
async fn list(&self) -> Result<Vec<ListedObject>> {
self.inner.list().await
}
fn object_path(&self, object_seq: u64) -> String {
self.inner.object_path(object_seq)
}
fn storage(&self) -> String {
self.inner.storage()
}
}
/// Object access whose whole-object reads, or conditional creates, and
@@ -10072,6 +9687,39 @@ mod tests {
}
}
#[async_trait::async_trait]
impl WalObjectRead for ParkedIo {
async fn get(&self, object_seq: u64) -> Result<Bytes> {
if !self.park_creates && !self.park(object_seq).await {
return injected_failure("read", self.object_path(object_seq));
}
self.inner.get(object_seq).await
}
async fn get_range(&self, object_seq: u64, offset: u64, len: u64) -> Result<Bytes> {
if self.range_reads_parked.load(Ordering::SeqCst) && !self.park(object_seq).await {
return injected_failure("read", self.object_path(object_seq));
}
self.inner.get_range(object_seq, offset, len).await
}
async fn list(&self) -> Result<Vec<ListedObject>> {
self.inner.list().await
}
fn object_path(&self, object_seq: u64) -> String {
self.inner.object_path(object_seq)
}
fn storage(&self) -> String {
self.inner.storage()
}
fn prefix(&self) -> &str {
self.inner.prefix()
}
}
#[async_trait::async_trait]
impl WalObjectIo for ParkedIo {
async fn put_if_absent(&self, object_seq: u64, content: Bytes) -> Result<PutResult> {
@@ -10095,38 +9743,12 @@ mod tests {
self.inner.put_if_absent(object_seq, content).await
}
async fn get(&self, object_seq: u64) -> Result<Bytes> {
if !self.park_creates && !self.park(object_seq).await {
return injected_failure("read", self.object_path(object_seq));
}
self.inner.get(object_seq).await
}
async fn get_range(&self, object_seq: u64, offset: u64, len: u64) -> Result<Bytes> {
if self.range_reads_parked.load(Ordering::SeqCst) && !self.park(object_seq).await {
return injected_failure("read", self.object_path(object_seq));
}
self.inner.get_range(object_seq, offset, len).await
}
async fn delete(&self, object_seq: u64) -> Result<()> {
if self.deletes_parked.load(Ordering::SeqCst) && !self.park(object_seq).await {
return injected_failure("delete", self.object_path(object_seq));
}
self.inner.delete(object_seq).await
}
async fn list(&self) -> Result<Vec<ListedObject>> {
self.inner.list().await
}
fn object_path(&self, object_seq: u64) -> String {
self.inner.object_path(object_seq)
}
fn storage(&self) -> String {
self.inner.storage()
}
}
type RangeReads = Arc<Mutex<Vec<(u64, u64, u64)>>>;
@@ -10197,26 +9819,7 @@ mod tests {
}
#[async_trait::async_trait]
impl WalObjectIo for RecordingIo {
async fn put_if_absent(&self, object_seq: u64, content: Bytes) -> Result<PutResult> {
if let Some(error) = self.fail_next_put.lock().unwrap().take() {
return Err(error).context(WalObjectStoreSnafu {
operation: "write",
path: self.object_path(object_seq),
});
}
if self.duplicate_next_put.swap(false, Ordering::Relaxed) {
self.inner
.put_if_absent(object_seq, content.clone())
.await?;
}
let result = self.inner.put_if_absent(object_seq, content).await?;
if self.fail_after_next_put.swap(false, Ordering::Relaxed) {
return injected_failure("write", self.object_path(object_seq));
}
Ok(result)
}
impl WalObjectRead for RecordingIo {
async fn get(&self, object_seq: u64) -> Result<Bytes> {
self.inner.get(object_seq).await
}
@@ -10260,10 +9863,6 @@ mod tests {
Ok(bytes)
}
async fn delete(&self, object_seq: u64) -> Result<()> {
self.inner.delete(object_seq).await
}
async fn list(&self) -> Result<Vec<ListedObject>> {
if self.fail_next_list.swap(false, Ordering::Relaxed) {
return injected_failure("list", PREFIX.to_string());
@@ -10278,6 +9877,36 @@ mod tests {
fn storage(&self) -> String {
self.inner.storage()
}
fn prefix(&self) -> &str {
self.inner.prefix()
}
}
#[async_trait::async_trait]
impl WalObjectIo for RecordingIo {
async fn put_if_absent(&self, object_seq: u64, content: Bytes) -> Result<PutResult> {
if let Some(error) = self.fail_next_put.lock().unwrap().take() {
return Err(error).context(WalObjectStoreSnafu {
operation: "write",
path: self.object_path(object_seq),
});
}
if self.duplicate_next_put.swap(false, Ordering::Relaxed) {
self.inner
.put_if_absent(object_seq, content.clone())
.await?;
}
let result = self.inner.put_if_absent(object_seq, content).await?;
if self.fail_after_next_put.swap(false, Ordering::Relaxed) {
return injected_failure("write", self.object_path(object_seq));
}
Ok(result)
}
async fn delete(&self, object_seq: u64) -> Result<()> {
self.inner.delete(object_seq).await
}
}
/// Measurements of costs that grow with the catalog or the prefix,
@@ -10440,11 +10069,7 @@ mod tests {
}
#[async_trait::async_trait]
impl WalObjectIo for CountingIo {
async fn put_if_absent(&self, object_seq: u64, content: Bytes) -> Result<PutResult> {
self.inner.put_if_absent(object_seq, content).await
}
impl WalObjectRead for CountingIo {
async fn get(&self, object_seq: u64) -> Result<Bytes> {
self.gets.fetch_add(1, Ordering::Relaxed);
self.inner.get(object_seq).await
@@ -10455,18 +10080,10 @@ mod tests {
self.inner.get_range(object_seq, offset, len).await
}
async fn delete(&self, object_seq: u64) -> Result<()> {
self.inner.delete(object_seq).await
}
async fn list(&self) -> Result<Vec<ListedObject>> {
self.inner.list().await
}
fn list_ahead(&self) -> BoxStream<'_, Result<ListedObject>> {
self.inner.list_ahead()
}
fn object_path(&self, object_seq: u64) -> String {
self.inner.object_path(object_seq)
}
@@ -10474,6 +10091,25 @@ mod tests {
fn storage(&self) -> String {
self.inner.storage()
}
fn prefix(&self) -> &str {
self.inner.prefix()
}
}
#[async_trait::async_trait]
impl WalObjectIo for CountingIo {
async fn put_if_absent(&self, object_seq: u64, content: Bytes) -> Result<PutResult> {
self.inner.put_if_absent(object_seq, content).await
}
async fn delete(&self, object_seq: u64) -> Result<()> {
self.inner.delete(object_seq).await
}
fn list_ahead(&self) -> BoxStream<'_, Result<ListedObject>> {
self.inner.list_ahead()
}
}
/// The object store a measurement of recovery runs on: a fresh root
+4
View File
@@ -57,6 +57,10 @@ abstraction, election, key encoding, and the DDL manager live in `common-meta`;
`common-meta`'s `DdlManager`, executed via `common-procedure`.
- **Region migration**: `procedure/region_migration/manager.rs` plus per-step
files; triggered by failover or an explicit command.
- **HTTP drain administration**: `service/admin/datanode.rs` checks the same leader
predicate as gRPC procedure submission. Drain submissions and restoring scheduling
wait for procedure recovery and share admission control in `procedure/drain_datanode/manager.rs`; retain both
the recovered-procedure and concurrent-submission tests when changing this boundary.
- **Leader election**: via `common-meta`'s election; transitions in `state.rs`.
## Public surface
+1 -1
View File
@@ -1237,6 +1237,7 @@ impl ErrorExt for Error {
| Error::PusherNotFound { .. } => StatusCode::Unexpected,
Error::MailboxTimeout { .. } | Error::ExceededDeadline { .. } => StatusCode::Cancelled,
Error::PruneTaskAlreadyRunning { .. }
| Error::DrainDatanodeRunning { .. }
| Error::RetryLater { .. }
| Error::MailboxChannelClosed { .. }
| Error::IsNotLeader { .. } => StatusCode::IllegalState,
@@ -1286,7 +1287,6 @@ impl ErrorExt for Error {
| Error::MigrationAbort { .. }
| Error::MigrationRunning { .. }
| Error::RegionMigrated { .. }
| Error::DrainDatanodeRunning { .. }
| Error::DrainDatanodeAbort { .. }
| Error::DrainDatanodeRescanExceeded { .. } => StatusCode::Unexpected,
Error::TableNotFound { .. } => StatusCode::TableNotFound,
+1 -1
View File
@@ -495,7 +495,7 @@ fn dropped_region_stat(region_id: RegionId) -> RegionStat {
file_removed_cnt: 0,
},
written_bytes: 0,
flushed_parquet_bytes: 0,
ingested_parquet_bytes: 0,
query_cpu_time: 0,
query_scanned_bytes: 0,
data_topic_latest_entry_id: 0,
+1 -1
View File
@@ -453,7 +453,7 @@ fn mock_region_stat(
min_timestamp: None,
max_timestamp: None,
written_bytes: 0,
flushed_parquet_bytes: 0,
ingested_parquet_bytes: 0,
query_cpu_time: 0,
query_scanned_bytes: 0,
}
@@ -91,7 +91,7 @@ mod tests {
min_timestamp: None,
max_timestamp: None,
written_bytes: 0,
flushed_parquet_bytes: 0,
ingested_parquet_bytes: 0,
query_cpu_time: 0,
query_scanned_bytes: 0,
}
+1 -1
View File
@@ -100,7 +100,7 @@ mod tests {
data_topic_latest_entry_id: 0,
metadata_topic_latest_entry_id: 0,
written_bytes: 0,
flushed_parquet_bytes: 0,
ingested_parquet_bytes: 0,
query_cpu_time: 0,
query_scanned_bytes: 0,
min_timestamp: None,
@@ -298,7 +298,7 @@ mod tests {
file_removed_cnt: 0,
},
written_bytes,
flushed_parquet_bytes: 0,
ingested_parquet_bytes: 0,
query_cpu_time: 0,
query_scanned_bytes: 0,
data_topic_latest_entry_id: 200,
@@ -180,7 +180,7 @@ mod test {
data_topic_latest_entry_id: 0,
metadata_topic_latest_entry_id: 0,
written_bytes: 0,
flushed_parquet_bytes: 0,
ingested_parquet_bytes: 0,
query_cpu_time: 0,
query_scanned_bytes: 0,
min_timestamp: None,
+5
View File
@@ -861,6 +861,11 @@ impl Metasrv {
&self.kv_backend
}
/// Returns the shared KV backend that caches metadata while the leader cache is enabled.
pub fn leader_cached_kv_backend(&self) -> &Arc<LeaderCachedKvBackend> {
&self.leader_cached_kv_backend
}
/// Returns the undecorated peer client.
///
/// Its `active_datanodes` does not know about node scheduling states. Use
@@ -21,9 +21,11 @@ use common_meta::key::TableMetadataManagerRef;
use common_procedure::{ProcedureContext, ProcedureId, ProcedureManagerRef, ProcedureWithId};
use common_telemetry::info;
use common_time::util::current_time_millis;
use snafu::ResultExt;
use snafu::{OptionExt, ResultExt, ensure};
use tokio::sync::Mutex;
use crate::error::{self, Result};
use crate::key::NodeSchedulingRole;
use crate::metasrv::SelectorContext;
use crate::node_scheduling::NodeSchedulingManagerRef;
use crate::procedure::drain_datanode::{
@@ -36,14 +38,20 @@ pub type DrainDatanodeManagerRef = Arc<DrainDatanodeManager>;
/// Tracks the running drains, indexed by the drained datanode.
///
/// Mirrors `RegionMigrationProcedureTracker`: a drain of a datanode that is already being
/// drained is rejected at submission instead of waiting for the procedure lock.
/// Reserves each datanode for one drain and rejects concurrent submissions.
#[derive(Default, Clone)]
pub struct DrainDatanodeProcedureTracker {
running_procedures: Arc<RwLock<HashMap<DatanodeId, DrainDatanodeProcedureTask>>>,
}
impl DrainDatanodeProcedureTracker {
fn contains(&self, node_id: DatanodeId) -> bool {
self.running_procedures
.read()
.unwrap()
.contains_key(&node_id)
}
/// Returns the guard of a drain of `task.node_id`, or `None` if that datanode is already
/// being drained.
pub(crate) fn insert_running_procedure(
@@ -81,9 +89,7 @@ impl Drop for DrainDatanodeProcedureGuard {
/// Manages the [`DrainDatanodeProcedure`]s.
///
/// It registers the procedure loader and submits drain tasks. Procedures of the same
/// datanode are serialized by the procedure lock declared in
/// [`DrainDatanodeProcedure::lock_key`].
/// Registers the procedure loader and serializes submissions with restoring scheduling.
pub struct DrainDatanodeManager {
procedure_manager: ProcedureManagerRef,
table_metadata_manager: TableMetadataManagerRef,
@@ -92,6 +98,8 @@ pub struct DrainDatanodeManager {
selector_ctx: SelectorContext,
tracker: DrainDatanodeProcedureTracker,
/// Serializes submissions with restoring scheduling, including their KV operations.
admission: Mutex<()>,
}
impl DrainDatanodeManager {
@@ -111,15 +119,10 @@ impl DrainDatanodeManager {
selector_ctx,
tracker: DrainDatanodeProcedureTracker::default(),
admission: Mutex::new(()),
}
}
/// Returns the tracker of the running drains.
#[cfg(test)]
pub(crate) fn tracker(&self) -> DrainDatanodeProcedureTracker {
self.tracker.clone()
}
/// Returns the context of a drain run.
fn context(&self, persistent_ctx: PersistentContext) -> DrainDatanodeContext {
DrainDatanodeContext::new(
@@ -131,12 +134,13 @@ impl DrainDatanodeManager {
)
}
/// Submits a [`DrainDatanodeProcedure`] and returns its id.
/// Submits a drain, rejecting the task if the datanode is already being drained.
pub async fn submit_procedure(
&self,
procedure_context: ProcedureContext,
task: DrainDatanodeProcedureTask,
) -> Result<ProcedureId> {
let _admission = self.admission.lock().await;
if task.target_node_id == Some(task.node_id) {
return error::InvalidArgumentsSnafu {
err_msg: "the target datanode must differ from the drained datanode",
@@ -157,6 +161,15 @@ impl DrainDatanodeManager {
.fail();
}
// The budget starts at submission and must fit the persisted absolute deadline.
let deadline_ms = i64::try_from(timeout.as_millis())
.ok()
.and_then(|timeout_ms| current_time_millis().checked_add(timeout_ms))
.context(error::InvalidArgumentsSnafu {
err_msg: "the timeout exceeds the supported deadline range",
})?;
self.ensure_ready()?;
let Some(guard) = self.tracker.insert_running_procedure(&task) else {
return error::DrainDatanodeRunningSnafu {
node_id: task.node_id,
@@ -171,7 +184,7 @@ impl DrainDatanodeManager {
strategy: task.strategy,
// The budget starts when the task is submitted, so neither a slow start nor a
// restart extends it.
deadline_ms: current_time_millis() + timeout.as_millis() as i64,
deadline_ms,
};
let procedure = DrainDatanodeProcedure::new(self.context(persistent_ctx), vec![guard]);
let procedure_with_id =
@@ -189,6 +202,30 @@ impl DrainDatanodeManager {
Ok(procedure_id)
}
/// Restores scheduling only when no drain owns the node.
pub async fn mark_schedulable(&self, node_id: DatanodeId) -> Result<()> {
let _admission = self.admission.lock().await;
self.ensure_ready()?;
ensure!(
!self.tracker.contains(node_id),
error::DrainDatanodeRunningSnafu { node_id }
);
self.node_scheduling_manager
.mark_schedulable(NodeSchedulingRole::Datanode, node_id)
.await?;
Ok(())
}
fn ensure_ready(&self) -> Result<()> {
ensure!(
self.procedure_manager.is_ready(),
error::RetryLaterSnafu {
reason: "procedure manager has not completed recovery",
}
);
Ok(())
}
/// Registers the loader of [`DrainDatanodeProcedure`].
pub(crate) fn try_start(&self) -> Result<()> {
let table_metadata_manager = self.table_metadata_manager.clone();
@@ -225,18 +262,411 @@ impl DrainDatanodeManager {
#[cfg(test)]
mod tests {
use std::sync::Arc;
use std::time::Duration;
use common_procedure::Procedure;
use common_error::ext::ErrorExt;
use common_error::status_code::StatusCode;
use common_procedure::store::state_store::StateStore;
use common_procedure::{Procedure, ProcedureId, ProcedureManagerRef, Status};
use tokio::sync::Notify;
use crate::error;
use crate::procedure::drain_datanode::manager::DrainDatanodeProcedureTracker;
use crate::key::NodeSchedulingRole;
use crate::procedure::drain_datanode::manager::{
DrainDatanodeManager, DrainDatanodeProcedureTracker,
};
use crate::procedure::drain_datanode::test_util::{TestEnv, new_persistent_context};
use crate::procedure::drain_datanode::{
DEFAULT_PARALLELISM, DrainDatanodeProcedure, DrainDatanodeProcedureTask,
DrainDatanodeStrategy,
};
struct HoldDrainLock {
entered: Arc<Notify>,
release: Arc<Notify>,
}
#[async_trait::async_trait]
impl Procedure for HoldDrainLock {
fn type_name(&self) -> &str {
"test-hold-drain-lock"
}
async fn execute(
&mut self,
_: &common_procedure::Context,
) -> common_procedure::Result<Status> {
self.entered.notify_one();
self.release.notified().await;
Ok(Status::done())
}
fn dump(&self) -> common_procedure::Result<String> {
Ok(String::new())
}
fn lock_key(&self) -> common_procedure::LockKey {
common_procedure::LockKey::single_exclusive("__drain_datanode/1")
}
}
fn task() -> DrainDatanodeProcedureTask {
DrainDatanodeProcedureTask {
node_id: 1,
target_node_id: Some(2),
parallelism: DEFAULT_PARALLELISM,
strategy: DrainDatanodeStrategy::FailFast,
timeout: None,
}
}
async fn hold_drain_lock(procedure_manager: &ProcedureManagerRef) -> Arc<Notify> {
let entered = Arc::new(Notify::new());
let release = Arc::new(Notify::new());
procedure_manager
.submit(common_procedure::ProcedureWithId::with_random_id(Box::new(
HoldDrainLock {
entered: entered.clone(),
release: release.clone(),
},
)))
.await
.unwrap();
tokio::time::timeout(Duration::from_secs(5), entered.notified())
.await
.unwrap();
release
}
#[tokio::test]
async fn test_submit_drain_rejects_concurrent_tasks_and_scheduling() {
let env = TestEnv::new().await;
env.procedure_manager().start().await.unwrap();
let release = hold_drain_lock(env.procedure_manager()).await;
let manager = env.drain_manager();
let (first, second) = tokio::join!(
manager.submit_procedure(Default::default(), task()),
manager.submit_procedure(Default::default(), task()),
);
assert!(matches!(
(first, second),
(Ok(_), Err(error::Error::DrainDatanodeRunning { .. }))
| (Err(error::Error::DrainDatanodeRunning { .. }), Ok(_))
));
assert_eq!(
2,
env.procedure_manager()
.list_procedures()
.await
.unwrap()
.len()
);
let mut conflicting = task();
conflicting.target_node_id = Some(3);
for err in [
manager
.submit_procedure(Default::default(), conflicting)
.await
.unwrap_err(),
manager.mark_schedulable(1).await.unwrap_err(),
] {
assert!(matches!(&err, error::Error::DrainDatanodeRunning { .. }));
assert_eq!(StatusCode::IllegalState, err.status_code());
}
release.notify_one();
tokio::time::timeout(Duration::from_secs(5), async {
loop {
if !manager
.tracker
.running_procedures
.read()
.unwrap()
.contains_key(&1)
{
break;
}
tokio::task::yield_now().await;
}
})
.await
.unwrap();
manager.mark_schedulable(1).await.unwrap();
manager.mark_schedulable(1).await.unwrap();
env.procedure_manager().stop().await.unwrap();
}
struct RecoveryGate {
store: common_meta::state_store::KvStateStore,
entered: tokio::sync::Notify,
release: tokio::sync::Notify,
}
#[async_trait::async_trait]
impl common_procedure::store::state_store::StateStore for RecoveryGate {
async fn put(&self, key: &str, value: Vec<u8>) -> common_procedure::Result<()> {
self.store.put(key, value).await
}
async fn walk_top_down(
&self,
path: &str,
) -> common_procedure::Result<common_procedure::store::state_store::KeyValueStream>
{
if path == "procedure/" {
self.entered.notify_one();
self.release.notified().await;
}
self.store.walk_top_down(path).await
}
async fn batch_delete(&self, keys: &[String]) -> common_procedure::Result<()> {
self.store.batch_delete(keys).await
}
async fn delete(&self, key: &str) -> common_procedure::Result<()> {
self.store.delete(key).await
}
}
#[tokio::test]
async fn test_drain_admission_waits_for_recovery_and_rejects_running_task() {
use crate::procedure::region_migration::test_util::TestingEnv;
use common_procedure::local::{LocalManager, ManagerConfig};
use common_procedure::store::ProcedureMessage;
use common_procedure::test_util::InMemoryPoisonStore;
let env = TestEnv::new().await;
let mut original = DrainDatanodeProcedure::new(
env.context(new_persistent_context(
Some(2),
DrainDatanodeStrategy::FailFast,
)),
vec![],
);
assert!(
original
.execute(&TestingEnv::procedure_context())
.await
.unwrap()
.need_persist()
);
let id = ProcedureId::random();
let message = ProcedureMessage {
type_name: DrainDatanodeProcedure::TYPE_NAME.to_string(),
data: original.dump().unwrap(),
parent_id: None,
subprocedure_recovery: Default::default(),
step: 0,
error: None,
context: Default::default(),
};
drop(original);
let store = Arc::new(RecoveryGate {
store: common_meta::state_store::KvStateStore::new(env.env.kv_backend()),
entered: tokio::sync::Notify::new(),
release: tokio::sync::Notify::new(),
});
store
.put(
&format!("procedure/{id}/0000000000.step"),
serde_json::to_vec(&message).unwrap(),
)
.await
.unwrap();
let procedure_manager: ProcedureManagerRef = Arc::new(LocalManager::new(
ManagerConfig::default(),
store.clone(),
Arc::new(InMemoryPoisonStore::default()),
None,
None,
));
let manager = DrainDatanodeManager::new(
procedure_manager.clone(),
env.table_metadata_manager.clone(),
env.node_scheduling_manager.clone(),
env.region_migration_manager.clone(),
env.selector_ctx.clone(),
);
manager.try_start().unwrap();
let start = tokio::spawn({
let procedure_manager = procedure_manager.clone();
async move { procedure_manager.start().await }
});
tokio::time::timeout(Duration::from_secs(5), store.entered.notified())
.await
.unwrap();
assert!(!procedure_manager.is_ready());
assert!(matches!(
manager.submit_procedure(Default::default(), task()).await,
Err(error::Error::RetryLater { .. })
));
assert!(matches!(
manager.mark_schedulable(1).await,
Err(error::Error::RetryLater { .. })
));
assert!(
!env.node_scheduling_manager
.is_schedulable(NodeSchedulingRole::Datanode, 1)
.await
.unwrap()
);
// Hold execution while the real loader restores the checkpoint and tracker.
let release = hold_drain_lock(&procedure_manager).await;
store.release.notify_one();
tokio::time::timeout(Duration::from_secs(5), start)
.await
.unwrap()
.unwrap()
.unwrap();
assert!(procedure_manager.is_ready());
for _ in 0..2 {
assert!(matches!(
manager.submit_procedure(Default::default(), task()).await,
Err(error::Error::DrainDatanodeRunning { .. })
));
}
let mut conflicting = task();
conflicting.target_node_id = Some(3);
for err in [
manager
.submit_procedure(Default::default(), conflicting)
.await
.unwrap_err(),
manager.mark_schedulable(1).await.unwrap_err(),
] {
assert!(matches!(&err, error::Error::DrainDatanodeRunning { .. }));
assert_eq!(StatusCode::IllegalState, err.status_code());
}
release.notify_one();
tokio::time::timeout(Duration::from_secs(5), async {
while manager.tracker.contains(1) {
tokio::task::yield_now().await;
}
})
.await
.unwrap();
assert!(
procedure_manager
.procedure_state(id)
.await
.unwrap()
.unwrap()
.is_done()
);
let second = manager
.submit_procedure(Default::default(), task())
.await
.unwrap();
assert_ne!(id, second);
tokio::time::timeout(Duration::from_secs(5), async {
while manager.tracker.contains(1) {
tokio::task::yield_now().await;
}
})
.await
.unwrap();
assert!(
procedure_manager
.procedure_state(second)
.await
.unwrap()
.unwrap()
.is_done()
);
manager.mark_schedulable(1).await.unwrap();
procedure_manager.stop().await.unwrap();
assert!(!procedure_manager.is_ready());
assert!(matches!(
manager.mark_schedulable(1).await,
Err(error::Error::RetryLater { .. })
));
}
#[tokio::test]
async fn test_failed_drain_can_be_submitted_again() {
use crate::key::NodeSchedulingRole;
use crate::procedure::drain_datanode::test_util::leader_region;
let env = TestEnv::new().await;
env.create_table(vec![leader_region(
store_api::storage::RegionId::new(1024, 1),
1,
)])
.await;
env.node_scheduling_manager
.mark_unschedulable(NodeSchedulingRole::Datanode, 2)
.await
.unwrap();
env.procedure_manager().start().await.unwrap();
let manager = env.drain_manager();
let first = manager
.submit_procedure(Default::default(), task())
.await
.unwrap();
tokio::time::timeout(Duration::from_secs(5), async {
loop {
if env
.procedure_manager()
.procedure_state(first)
.await
.unwrap()
.unwrap()
.is_failed()
&& !manager
.tracker
.running_procedures
.read()
.unwrap()
.contains_key(&1)
{
break;
}
tokio::task::yield_now().await;
}
})
.await
.unwrap();
let second = manager
.submit_procedure(Default::default(), task())
.await
.unwrap();
assert_ne!(first, second);
env.procedure_manager().stop().await.unwrap();
}
#[tokio::test]
async fn test_failed_submission_releases_drain_admission() {
use common_procedure::local::{LocalManager, ManagerConfig};
use common_procedure::test_util::InMemoryPoisonStore;
let env = TestEnv::new().await;
let procedure_manager: ProcedureManagerRef = Arc::new(LocalManager::new(
ManagerConfig {
max_running_procedures: 0,
..Default::default()
},
Arc::new(common_meta::state_store::KvStateStore::new(
env.env.kv_backend(),
)),
Arc::new(InMemoryPoisonStore::default()),
None,
None,
));
procedure_manager.start().await.unwrap();
let manager = DrainDatanodeManager::new(
procedure_manager.clone(),
env.table_metadata_manager.clone(),
env.node_scheduling_manager.clone(),
env.region_migration_manager.clone(),
env.selector_ctx.clone(),
);
assert!(matches!(
manager.submit_procedure(Default::default(), task()).await,
Err(error::Error::SubmitProcedure { .. })
));
assert!(!manager.tracker.contains(1));
manager.mark_schedulable(1).await.unwrap();
procedure_manager.stop().await.unwrap();
}
#[tokio::test]
async fn test_submit_procedure_rejects_invalid_task() {
let env = TestEnv::new().await;
@@ -276,49 +706,42 @@ mod tests {
assert!(matches!(error, error::Error::InvalidArguments { .. }));
}
// The timeout must be greater than zero.
let error = manager
.submit_procedure(
common_procedure::ProcedureContext::default(),
DrainDatanodeProcedureTask {
node_id: 1,
target_node_id: Some(2),
parallelism: DEFAULT_PARALLELISM,
strategy: DrainDatanodeStrategy::FailFast,
timeout: Some(Duration::ZERO),
},
)
.await
.unwrap_err();
assert!(matches!(error, error::Error::InvalidArguments { .. }));
// Reject zero, millisecond conversion overflow, and absolute deadline overflow.
for timeout in [
Duration::ZERO,
Duration::from_millis(i64::MAX as u64 + 1),
Duration::from_millis(i64::MAX as u64),
] {
let error = manager
.submit_procedure(
common_procedure::ProcedureContext::default(),
DrainDatanodeProcedureTask {
timeout: Some(timeout),
..task()
},
)
.await
.unwrap_err();
assert!(matches!(error, error::Error::InvalidArguments { .. }));
assert!(!manager.tracker.contains(1));
}
assert!(
env.procedure_manager()
.list_procedures()
.await
.unwrap()
.is_empty()
);
assert!(
env.node_scheduling_manager
.is_schedulable(NodeSchedulingRole::Datanode, 1)
.await
.unwrap()
);
}
#[tokio::test]
async fn test_submit_procedure_rejects_a_running_drain() {
let env = TestEnv::new().await;
let manager = env.drain_manager();
let task = DrainDatanodeProcedureTask {
node_id: 1,
target_node_id: Some(2),
parallelism: DEFAULT_PARALLELISM,
strategy: DrainDatanodeStrategy::FailFast,
timeout: None,
};
// A drain of datanode 1 is running, for example one recovered after a restart.
let _guard = manager.tracker().insert_running_procedure(&task).unwrap();
let error = manager
.submit_procedure(common_procedure::ProcedureContext::default(), task)
.await
.unwrap_err();
assert!(matches!(error, error::Error::DrainDatanodeRunning { .. }));
assert!(!error.is_retryable());
}
#[tokio::test]
async fn test_drain_datanode_takes_the_place_back_on_reload() {
async fn test_drain_recovery_reserves_node_until_drop() {
let env = TestEnv::new().await;
let context = env.context(new_persistent_context(
Some(2),
@@ -328,7 +751,7 @@ mod tests {
let json = procedure.dump().unwrap();
let tracker = DrainDatanodeProcedureTracker::default();
// Reloading takes the place back, so a second drain of the datanode is rejected.
// Loading reserves the datanode before any runner starts.
let reloaded = DrainDatanodeProcedure::from_json(&json, &tracker, |persistent_ctx| {
env.context(persistent_ctx)
})
@@ -340,6 +763,7 @@ mod tests {
strategy: DrainDatanodeStrategy::FailFast,
timeout: None,
};
assert!(tracker.contains(task.node_id));
assert!(tracker.insert_running_procedure(&task).is_none());
// Dropping the reloaded procedure releases the place.

Some files were not shown because too many files have changed in this diff Show More