diff --git a/.github/actions/build-linux-artifacts/action.yml b/.github/actions/build-linux-artifacts/action.yml index 26028485061..a16c1a72405 100644 --- a/.github/actions/build-linux-artifacts/action.yml +++ b/.github/actions/build-linux-artifacts/action.yml @@ -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 diff --git a/.github/actions/setup-benchmark/action.yml b/.github/actions/setup-linux-runner/action.yml similarity index 60% rename from .github/actions/setup-benchmark/action.yml rename to .github/actions/setup-linux-runner/action.yml index a446a78a2c3..95de8e465c5 100644 --- a/.github/actions/setup-benchmark/action.yml +++ b/.github/actions/setup-linux-runner/action.yml @@ -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 diff --git a/.github/scripts/agent-observability-summary.py b/.github/scripts/agent-observability-summary.py index 33ba3ad7e6e..29e3e995536 100644 --- a/.github/scripts/agent-observability-summary.py +++ b/.github/scripts/agent-observability-summary.py @@ -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 = ['
', 'DDL, index configuration and image provenance', ''] - 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, '
', ''] diff --git a/.github/scripts/benchmark-version-comparison.py b/.github/scripts/benchmark-version-comparison.py index 1aa744df9ad..527797a2cb5 100644 --- a/.github/scripts/benchmark-version-comparison.py +++ b/.github/scripts/benchmark-version-comparison.py @@ -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) diff --git a/.github/scripts/ci-runners.md b/.github/scripts/ci-runners.md index 6e4b2b3a4f7..f21bdbdb0af 100644 --- a/.github/scripts/ci-runners.md +++ b/.github/scripts/ci-runners.md @@ -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 diff --git a/.github/scripts/metric-snapshot-s3-bench.py b/.github/scripts/metric-snapshot-s3-bench.py index 7bb01a410b1..6542a18ba04 100644 --- a/.github/scripts/metric-snapshot-s3-bench.py +++ b/.github/scripts/metric-snapshot-s3-bench.py @@ -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']} |") diff --git a/.github/scripts/metric-snapshot-s3-ops.py b/.github/scripts/metric-snapshot-s3-ops.py index f1e34defb89..f639ec90979 100644 --- a/.github/scripts/metric-snapshot-s3-ops.py +++ b/.github/scripts/metric-snapshot-s3-ops.py @@ -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."} diff --git a/.github/scripts/o11ybench-storage.py b/.github/scripts/o11ybench-storage.py new file mode 100644 index 00000000000..e050e933d95 --- /dev/null +++ b/.github/scripts/o11ybench-storage.py @@ -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() diff --git a/.github/scripts/tests/test_metric_snapshot_s3_bench.py b/.github/scripts/tests/test_metric_snapshot_s3_bench.py index c662ecbff76..092771e1154 100644 --- a/.github/scripts/tests/test_metric_snapshot_s3_bench.py +++ b/.github/scripts/tests/test_metric_snapshot_s3_bench.py @@ -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") diff --git a/.github/scripts/tests/test_metric_snapshot_s3_ops.py b/.github/scripts/tests/test_metric_snapshot_s3_ops.py index d22c09044b2..5c1a265af0f 100644 --- a/.github/scripts/tests/test_metric_snapshot_s3_ops.py +++ b/.github/scripts/tests/test_metric_snapshot_s3_ops.py @@ -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") diff --git a/.github/workflows/agent-observability.yml b/.github/workflows/agent-observability.yml index 90840536594..055af1d0f26 100644 --- a/.github/workflows/agent-observability.yml +++ b/.github/workflows/agent-observability.yml @@ -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 diff --git a/.github/workflows/dev-build.yml b/.github/workflows/dev-build.yml index da514f27def..0295c5d2779 100644 --- a/.github/workflows/dev-build.yml +++ b/.github/workflows/dev-build.yml @@ -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 }} diff --git a/.github/workflows/metric-snapshot-s3-bench.yml b/.github/workflows/metric-snapshot-s3-bench.yml index 724108e4065..8b961b1d4fa 100644 --- a/.github/workflows/metric-snapshot-s3-bench.yml +++ b/.github/workflows/metric-snapshot-s3-bench.yml @@ -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: | diff --git a/.github/workflows/nightly-build.yml b/.github/workflows/nightly-build.yml index 7b173c9a2be..81627e9fa4c 100644 --- a/.github/workflows/nightly-build.yml +++ b/.github/workflows/nightly-build.yml @@ -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 }} diff --git a/.github/workflows/oswal-s3-bench.yml b/.github/workflows/oswal-s3-bench.yml index 81fdc4eefb1..655582ff634 100644 --- a/.github/workflows/oswal-s3-bench.yml +++ b/.github/workflows/oswal-s3-bench.yml @@ -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 diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index d3c71199bc2..c4489f9aabd 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -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: diff --git a/.github/workflows/tracesbench.yml b/.github/workflows/tracesbench.yml index fd64ebfcf37..73fe62001df 100644 --- a/.github/workflows/tracesbench.yml +++ b/.github/workflows/tracesbench.yml @@ -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 diff --git a/.github/workflows/vmbench-long-range.yml b/.github/workflows/vmbench-long-range.yml index d4e3ad124c1..625156b6652 100644 --- a/.github/workflows/vmbench-long-range.yml +++ b/.github/workflows/vmbench-long-range.yml @@ -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 diff --git a/Cargo.lock b/Cargo.lock index e20142503f2..373ce2873e9 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -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]] diff --git a/Cargo.toml b/Cargo.toml index a6f77b1e9de..48e39ada226 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -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" diff --git a/README.md b/README.md index 5204dab9513..7c9bdc01b96 100644 --- a/README.md +++ b/README.md @@ -9,13 +9,11 @@

Metrics, logs, and traces.
One engine, on your infrastructure.

-> A columnar database for metrics, logs, and traces on object storage. -> Apache-2.0 licensed core. -
User Guide  ·  API Docs  ·  +Live Demo  ·  Roadmap 2026  ·  Slack @@ -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. - -

- - GreptimeDB Overview - -

- -## 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). - - - GreptimeDB System Overview - - ## 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. + +

+ + GreptimeDB Overview + +

+ +## 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). + + + GreptimeDB System Overview + ## 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. + + + + + Star History Chart + + + Known Users ## 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) diff --git a/config/config.md b/config/config.md index cd2b518f12c..9bbed619ab3 100644 --- a/config/config.md +++ b/config/config.md @@ -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
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).
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. | | `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.
Supports absolute size (e.g., "2GiB", "512MB") or percentage of system memory (e.g., "50%").
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.
Options: "wait" (default, 10s), "wait()", "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,
network, and logs. Default is false. Enable only for trusted pipeline authors.
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.
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. | | `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`,
`alter_database`, `drop_database`, `create_flow`, `drop_flow`,
`create_table`, `create_logical_tables`, `alter_table`, `alter_logical_tables`,
`drop_table`, `undrop_table`, `purge_dropped_table`, `truncate_table`,
`create_view`, `drop_view`, `admin_function`, `reconcile_catalog`,
`reconcile_database`, `reconcile_table`, `reconcile_logical_tables`.
When omitted, all current and future event types are recorded.
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
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,
network, and logs. Default is false. Enable only for trusted pipeline authors.
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.
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. | | `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`.
When omitted, all current and future event types are recorded.
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
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).
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. | | `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.
Supports absolute size (e.g., "2GiB", "512MB") or percentage of system memory (e.g., "50%").
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.
Options: "wait" (default, 10s), "wait()", "fail" | diff --git a/config/datanode.example.toml b/config/datanode.example.toml index a7e9417717f..45f1d93d39a 100644 --- a/config/datanode.example.toml +++ b/config/datanode.example.toml @@ -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 diff --git a/config/frontend.example.toml b/config/frontend.example.toml index c959dc10926..f0c1402327f 100644 --- a/config/frontend.example.toml +++ b/config/frontend.example.toml @@ -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] diff --git a/config/standalone.example.toml b/config/standalone.example.toml index 0fa5907f95b..7682e537861 100644 --- a/config/standalone.example.toml +++ b/config/standalone.example.toml @@ -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] diff --git a/docs/how-to/metric-snapshot-s3-bench.md b/docs/how-to/metric-snapshot-s3-bench.md index 86468bf3ffd..7bd5fb2efed 100644 --- a/docs/how-to/metric-snapshot-s3-bench.md +++ b/docs/how-to/metric-snapshot-s3-bench.md @@ -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. diff --git a/grafana/dashboards/metrics/cluster/dashboard.json b/grafana/dashboards/metrics/cluster/dashboard.json index fd1d0257594..51e3de64414 100644 --- a/grafana/dashboards/metrics/cluster/dashboard.json +++ b/grafana/dashboards/metrics/cluster/dashboard.json @@ -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", diff --git a/grafana/dashboards/metrics/cluster/dashboard.md b/grafana/dashboards/metrics/cluster/dashboard.md index 1c167af5152..a200b4c8338 100644 --- a/grafana/dashboards/metrics/cluster/dashboard.md +++ b/grafana/dashboards/metrics/cluster/dashboard.md @@ -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])) +)`
`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 diff --git a/grafana/dashboards/metrics/cluster/dashboard.yaml b/grafana/dashboards/metrics/cluster/dashboard.yaml index 01fdb7bbc31..0c950ab1b8c 100644 --- a/grafana/dashboards/metrics/cluster/dashboard.yaml +++ b/grafana/dashboards/metrics/cluster/dashboard.yaml @@ -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 diff --git a/grafana/dashboards/metrics/standalone/dashboard.json b/grafana/dashboards/metrics/standalone/dashboard.json index d980fb500d6..fd5adec8c83 100644 --- a/grafana/dashboards/metrics/standalone/dashboard.json +++ b/grafana/dashboards/metrics/standalone/dashboard.json @@ -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", diff --git a/grafana/dashboards/metrics/standalone/dashboard.md b/grafana/dashboards/metrics/standalone/dashboard.md index 7ed99d2ab2c..6dd5fd114fe 100644 --- a/grafana/dashboards/metrics/standalone/dashboard.md +++ b/grafana/dashboards/metrics/standalone/dashboard.md @@ -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])) +)`
`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 diff --git a/grafana/dashboards/metrics/standalone/dashboard.yaml b/grafana/dashboards/metrics/standalone/dashboard.yaml index 7f70dba0364..308320ab568 100644 --- a/grafana/dashboards/metrics/standalone/dashboard.yaml +++ b/grafana/dashboards/metrics/standalone/dashboard.yaml @@ -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 diff --git a/licenserc-enterprise.toml b/licenserc-enterprise.toml index d11d344b64d..939346f5cba 100644 --- a/licenserc-enterprise.toml +++ b/licenserc-enterprise.toml @@ -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", diff --git a/licenserc.toml b/licenserc.toml index 42e6464017c..e601ca6f7c1 100644 --- a/licenserc.toml +++ b/licenserc.toml @@ -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", diff --git a/src/api/src/v1/column_def.rs b/src/api/src/v1/column_def.rs index b1d2f0841d5..a7fd7fe4ad4 100644 --- a/src/api/src/v1/column_def.rs +++ b/src/api/src/v1/column_def.rs @@ -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 { + 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 { diff --git a/src/catalog/src/information_extension.rs b/src/catalog/src/information_extension.rs index 0c572eac562..259e98e70e7 100644 --- a/src/catalog/src/information_extension.rs +++ b/src/catalog/src/information_extension.rs @@ -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 { + ) -> crate::error::Result { 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, + ) -> crate::error::Result { + 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 { + 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, + ) -> crate::error::Result { + 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 { + 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, + schema: SchemaRef, +) -> crate::error::Result { + 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) -> Vec { + 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>> { + 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 { + [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 { + 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::(), + 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::().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::() { 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, diff --git a/src/catalog/src/system_schema/information_schema.rs b/src/catalog/src/system_schema/information_schema.rs index 1f65652289d..2a82e2ed911 100644 --- a/src/catalog/src/system_schema/information_schema.rs +++ b/src/catalog/src/system_schema/information_schema.rs @@ -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; + /// 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>, 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 { 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 { diff --git a/src/catalog/src/system_schema/information_schema/compaction_tasks.rs b/src/catalog/src/system_schema/information_schema/compaction_tasks.rs new file mode 100644 index 00000000000..53957fa4625 --- /dev/null +++ b/src/catalog/src/system_schema/information_schema/compaction_tasks.rs @@ -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, +} + +impl InformationSchemaCompactionTasks { + pub(crate) fn new(catalog_manager: Weak) -> 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 { + 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>> { + utils::inspect_plan( + &self.catalog_manager, + DatanodeInspectKind::CompactionTasks, + &self.schema, + request, + ) + } +} diff --git a/src/catalog/src/system_schema/information_schema/region_statistics.rs b/src/catalog/src/system_schema/information_schema/region_statistics.rs index 8a7c19adc00..ab2a30580b0 100644 --- a/src/catalog/src/system_schema/information_schema/region_statistics.rs +++ b/src/catalog/src/system_schema/information_schema/region_statistics.rs @@ -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. diff --git a/src/catalog/src/system_schema/information_schema/ssts.rs b/src/catalog/src/system_schema/information_schema/ssts.rs index ace6a87bce5..eb2bc5efd3f 100644 --- a/src/catalog/src/system_schema/information_schema/ssts.rs +++ b/src/catalog/src/system_schema/information_schema/ssts.rs @@ -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 { - 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, - kind: DatanodeInspectKind, - schema: &SchemaRef, - request: ScanRequest, -) -> Result>> { - 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 { - 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>> { - 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 { - 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>> { - 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 { - 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>> { - 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()); diff --git a/src/catalog/src/system_schema/information_schema/table_names.rs b/src/catalog/src/system_schema/information_schema/table_names.rs index 3e9b2e2d6de..7ae58ead59c 100644 --- a/src/catalog/src/system_schema/information_schema/table_names.rs +++ b/src/catalog/src/system_schema/information_schema/table_names.rs @@ -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"; diff --git a/src/catalog/src/system_schema/utils.rs b/src/catalog/src/system_schema/utils.rs index b989bf91228..03752796664 100644 --- a/src/catalog/src/system_schema/utils.rs +++ b/src/catalog/src/system_schema/utils.rs @@ -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 { + 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, + kind: DatanodeInspectKind, + schema: &SchemaRef, + request: ScanRequest, +) -> Result>> { + 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 { + 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 diff --git a/src/client/src/region.rs b/src/client/src/region.rs index 2e517eb30d0..a70f5b5c766 100644 --- a/src/client/src/region.rs +++ b/src/client/src/region.rs @@ -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 { diff --git a/src/common/catalog/src/consts.rs b/src/common/catalog/src/consts.rs index cf2b9363ea8..30e523533a0 100644 --- a/src/common/catalog/src/consts.rs +++ b/src/common/catalog/src/consts.rs @@ -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 ----- diff --git a/src/common/datasource/src/compression.rs b/src/common/datasource/src/compression.rs index b7eb2d8b644..2e72decdd26 100644 --- a/src/common/datasource/src/compression.rs +++ b/src/common/datasource/src/compression.rs @@ -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> { + 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 { diff --git a/src/common/function/src/admin.rs b/src/common/function/src/admin.rs index 79182dd74e9..733abf17502 100644 --- a/src/common/function/src/admin.rs +++ b/src/common/function/src/admin.rs @@ -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()); diff --git a/src/common/function/src/admin/cancel_region_compaction.rs b/src/common/function/src/admin/cancel_region_compaction.rs new file mode 100644 index 00000000000..54c0eb09ff7 --- /dev/null +++ b/src/common/function/src/admin/cancel_region_compaction.rs @@ -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 { + ensure!( + params.len() == 2, + InvalidFuncArgsSnafu { + err_msg: format!( + "cancel_region_compaction expects 2 arguments, received {}", + params.len() + ), + } + ); + let Some(region_id) = helper::cast_u64(¶ms[0])? else { + return UnsupportedInputDataTypeSnafu { + function: "cancel_region_compaction", + datatypes: params + .iter() + .map(|value| value.data_type()) + .collect::>(), + } + .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, ¶ms) + .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()); + } +} diff --git a/src/common/function/src/handlers.rs b/src/common/function/src/handlers.rs index 9dafd853a84..0c2491fce06 100644 --- a/src/common/function/src/handlers.rs +++ b/src/common/function/src/handlers.rs @@ -70,6 +70,14 @@ pub trait TableMutationHandler: Send + Sync { ctx: QueryContextRef, ) -> Result; + /// Cancels one identified compaction task on a table region. + async fn cancel_region_compaction( + &self, + region_id: RegionId, + task_id: String, + ctx: QueryContextRef, + ) -> Result; + /// Discard all unflushed data from a table region. async fn discard_unflushed_data( &self, diff --git a/src/common/function/src/scalars/matches.rs b/src/common/function/src/scalars/matches.rs index 109ad1daeb2..67abe944da2 100644 --- a/src/common/function/src/scalars/matches.rs +++ b/src/common/function/src/scalars/matches.rs @@ -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 { + 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![ diff --git a/src/common/function/src/state.rs b/src/common/function/src/state.rs index d7e4f5e85b5..c07d91b7fae 100644 --- a/src/common/function/src/state.rs +++ b/src/common/function/src/state.rs @@ -199,6 +199,15 @@ impl FunctionState { Ok(ROWS) } + async fn cancel_region_compaction( + &self, + _region_id: RegionId, + _task_id: String, + _ctx: QueryContextRef, + ) -> Result { + Ok(ROWS) + } + async fn discard_unflushed_data( &self, _region_id: RegionId, diff --git a/src/common/grpc-expr/src/alter.rs b/src/common/grpc-expr/src/alter.rs index dda1d84015a..f92e1456c2a 100644 --- a/src/common/grpc-expr/src/alter.rs +++ b/src/common/grpc-expr/src/alter.rs @@ -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 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::(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(®ion).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(®ion).flushed_parquet_bytes, 0); + assert_eq!(RegionStat::from(®ion).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 ); } diff --git a/src/common/procedure/src/local.rs b/src/common/procedure/src/local.rs index 8801028b198..980c7379b1c 100644 --- a/src/common/procedure/src/local.rs +++ b/src/common/procedure/src/local.rs @@ -683,6 +683,7 @@ pub struct LocalManager { config: ManagerConfig, pause_aware: Option, 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) -> Result<()> { + self.inner.put(key, value).await + } + + async fn walk_top_down(&self, path: &str) -> Result { + 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"); diff --git a/src/common/procedure/src/procedure.rs b/src/common/procedure/src/procedure.rs index b43f275b8a2..84f8fb9f4e9 100644 --- a/src/common/procedure/src/procedure.rs +++ b/src/common/procedure/src/procedure.rs @@ -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<()>; diff --git a/src/common/query/src/logical_plan.rs b/src/common/query/src/logical_plan.rs index 41a46d04622..b9a2fa2faeb 100644 --- a/src/common/query/src/logical_plan.rs +++ b/src/common/query/src/logical_plan.rs @@ -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; diff --git a/src/common/query/src/logical_plan/expr.rs b/src/common/query/src/logical_plan/expr.rs index 309115b05f1..c8686307e3e 100644 --- a/src/common/query/src/logical_plan/expr.rs +++ b/src/common/query/src/logical_plan/expr.rs @@ -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( diff --git a/src/common/time/src/date.rs b/src/common/time/src/date.rs index 38667abbcac..f474c372d19 100644 --- a/src/common/time/src/date.rs +++ b/src/common/time/src/date.rs @@ -55,7 +55,7 @@ impl From 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::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!( diff --git a/src/datanode/Cargo.toml b/src/datanode/Cargo.toml index 93bb6e89ed8..5bae783df1e 100644 --- a/src/datanode/Cargo.toml +++ b/src/datanode/Cargo.toml @@ -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 diff --git a/src/datanode/src/region_server.rs b/src/datanode/src/region_server.rs index 9c60972fbc3..07068f5a4d3 100644 --- a/src/datanode/src/region_server.rs +++ b/src/datanode/src/region_server.rs @@ -1931,6 +1931,7 @@ impl RegionServerInner { RegionRequest::Alter(_) | RegionRequest::Flush(_) | RegionRequest::Compact(_) + | RegionRequest::CancelCompaction(_) | RegionRequest::Truncate(_) | RegionRequest::BuildIndex(_) | RegionRequest::EnterStaging(_) diff --git a/src/datanode/src/region_server/catalog.rs b/src/datanode/src/region_server/catalog.rs index 789aa514785..9b26c35a660 100644 --- a/src/datanode/src/region_server/catalog.rs +++ b/src/datanode/src/region_server/catalog.rs @@ -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 { + 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> { 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> { + 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> { let mito = { @@ -353,6 +375,7 @@ impl TreeNodeRewriter for NameAwareDataSourceInjector { #[cfg(test)] mod tests { + mod compaction; mod manifest; use std::sync::Arc; diff --git a/src/datanode/src/region_server/catalog/inspect.rs b/src/datanode/src/region_server/catalog/inspect.rs index 307c8b42883..da3ebdb130b 100644 --- a/src/datanode/src/region_server/catalog/inspect.rs +++ b/src/datanode/src/region_server/catalog/inspect.rs @@ -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) -> 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, @@ -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>, + candidates: Arc, + } + + impl InspectSource for RecordingSource { + fn schema(&self) -> SchemaRef { + self.inner.schema() + } + + fn scan( + &self, + request: &InspectScan, + ctx: Arc, + ) -> 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::(), + expected_count, + "{predicate}" + ); + } + } } diff --git a/src/datanode/src/region_server/catalog/tests/compaction.rs b/src/datanode/src/region_server/catalog/tests/compaction.rs new file mode 100644 index 00000000000..aaa3a747f34 --- /dev/null +++ b/src/datanode/src/region_server/catalog/tests/compaction.rs @@ -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); +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"); +} diff --git a/src/datatypes/Cargo.toml b/src/datatypes/Cargo.toml index d1dd70acef1..d684415400b 100644 --- a/src/datatypes/Cargo.toml +++ b/src/datatypes/Cargo.toml @@ -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 diff --git a/src/datatypes/src/error.rs b/src/datatypes/src/error.rs index 745268f6e35..b41e199e3a0 100644 --- a/src/datatypes/src/error.rs +++ b/src/datatypes/src/error.rs @@ -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 { .. } diff --git a/src/datatypes/src/json.rs b/src/datatypes/src/json.rs index 2c86170fbce..1be06770e63 100644 --- a/src/datatypes/src/json.rs +++ b/src/datatypes/src/json.rs @@ -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, + pub skipping_index: Option, + /// Optional fulltext configuration for a string path. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub fulltext_index: Option, } /// 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::(&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)?; diff --git a/src/datatypes/src/schema.rs b/src/datatypes/src/schema.rs index 4652b0104d1..cae7b9aa2bc 100644 --- a/src/datatypes/src/schema.rs +++ b/src/datatypes/src/schema.rs @@ -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"; diff --git a/src/datatypes/src/schema/column_schema.rs b/src/datatypes/src/schema/column_schema.rs index 9dac9258116..d43f95b4c44 100644 --- a/src/datatypes/src/schema/column_schema.rs +++ b/src/datatypes/src/schema/column_schema.rs @@ -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> { + 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.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> { + 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.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> { + 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.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> { 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::(&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())]); diff --git a/src/datatypes/src/schema/sketch.rs b/src/datatypes/src/schema/sketch.rs new file mode 100644 index 00000000000..7017ad8b920 --- /dev/null +++ b/src/datatypes/src/schema/sketch.rs @@ -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 { + 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 { + 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 { + 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::("{}").unwrap() + ); + assert_eq!( + KllOptions::default(), + serde_json::from_str::("{}").unwrap() + ); + assert_eq!( + MgOptions::default(), + serde_json::from_str::("{}").unwrap() + ); + for precision in [4, 10, 18] { + let options = HllOptions { precision }; + assert_eq!( + options, + serde_json::from_str::(&serde_json::to_string(&options).unwrap()) + .unwrap() + ); + } + for precision in [0, 3, 19, 255] { + assert!( + serde_json::from_str::(&format!(r#"{{"precision":{precision}}}"#)) + .is_err() + ); + } + for capacity in [0, 7] { + assert!( + serde_json::from_str::(&format!(r#"{{"capacity":{capacity}}}"#)) + .is_err() + ); + } + assert!(serde_json::from_str::(r#"{"max-counters":0}"#).is_err()); + assert!(serde_json::from_str::(r#"{"max-counters":4294967296}"#).is_err()); + for capacity in [8, u16::MAX] { + let options = KllOptions { capacity }; + assert_eq!( + options, + serde_json::from_str::(&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::(&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::(&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::(r#"{"max-counters":128}"#).unwrap() + ); + assert_eq!( + r#"{"max-counters":128}"#, + serde_json::to_string(&expected).unwrap() + ); + assert!(serde_json::from_str::(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}"); + } + } +} diff --git a/src/datatypes/src/types/json_type.rs b/src/datatypes/src/types/json_type.rs index 3e629c2bfd1..dea46d07e06 100644 --- a/src/datatypes/src/types/json_type.rs +++ b/src/datatypes/src/types/json_type.rs @@ -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 { 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 { .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 { - static UNICODE_CODE_POINT_PATTERN: LazyLock = 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> { 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> { + 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::(&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::(&text).unwrap(), + serde_json::from_str::(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::(&text).unwrap(), + serde_json::from_str::(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) { diff --git a/src/datatypes/src/vectors/json/array.rs b/src/datatypes/src/vectors/json/array.rs index 48644ad5c58..6da59df5fde 100644 --- a/src/datatypes/src/vectors/json/array.rs +++ b/src/datatypes/src/vectors/json/array.rs @@ -644,6 +644,7 @@ mod test { data_type: ConcreteDataType::string_datatype(), inverted_index: false, skipping_index: None, + fulltext_index: None, }], Some(0), )?; diff --git a/src/datatypes/src/vectors/json/builder.rs b/src/datatypes/src/vectors/json/builder.rs index 515bd8ec3e5..cf6ce129c3d 100644 --- a/src/datatypes/src/vectors/json/builder.rs +++ b/src/datatypes/src/vectors/json/builder.rs @@ -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), )?; diff --git a/src/flow/src/batching_mode/frontend_client.rs b/src/flow/src/batching_mode/frontend_client.rs index 85e07f7c1f7..a4a84aa8d4c 100644 --- a/src/flow/src/batching_mode/frontend_client.rs +++ b/src/flow/src/batching_mode/frontend_client.rs @@ -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, ) -> Result { 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>, + } + + #[async_trait::async_trait] + impl GrpcQueryHandlerWithBoxedError for ContextHandler { + async fn do_query( + &self, + request: Request, + ctx: QueryContextRef, + ) -> std::result::Result { + 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 = 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(); diff --git a/src/frontend/AGENTS.md b/src/frontend/AGENTS.md index 2c8c16b4f84..43ebe894baf 100644 --- a/src/frontend/AGENTS.md +++ b/src/frontend/AGENTS.md @@ -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. diff --git a/src/frontend/src/frontend.rs b/src/frontend/src/frontend.rs index d486c46ab53..7e74d079d97 100644 --- a/src/frontend/src/frontend.rs +++ b/src/frontend/src/frontend.rs @@ -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); diff --git a/src/frontend/src/instance.rs b/src/frontend/src/instance.rs index a200092d740..db7552468c5 100644 --- a/src/frontend/src/instance.rs +++ b/src/frontend/src/instance.rs @@ -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, query_ctx: QueryContextRef, ) -> server_error::Result { + // 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> { + self.query_exemplars_inner(query, ctx).await + } + #[tracing::instrument(skip_all)] async fn do_query( &self, diff --git a/src/frontend/src/instance/exemplar.rs b/src/frontend/src/instance/exemplar.rs new file mode 100644 index 00000000000..fc0f4862cff --- /dev/null +++ b/src/frontend/src/instance/exemplar.rs @@ -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; +// Retain NaN payloads and signed zero as distinct observations, using their stored bits. +type Observations = BTreeMap>; + +impl Instance { + pub(super) async fn query_exemplars_inner( + &self, + query: Query, + ctx: QueryContextRef, + ) -> Result> { + self.check_prom_query_privilege(&ctx)?; + let interceptor = self.plugins.get::>(); + let mut groups = BTreeMap::>::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::>(); + 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 { + 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::>(); + 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 { + 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::() + * 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 = 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); + } +} diff --git a/src/frontend/src/instance/log_handler.rs b/src/frontend/src/instance/log_handler.rs index 7b6a8fcb8ed..9b238b8821c 100644 --- a/src/frontend/src/instance/log_handler.rs +++ b/src/frontend/src/instance/log_handler.rs @@ -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 { self.pipeline_operator .build_pipeline(pipeline) diff --git a/src/frontend/src/instance/otlp.rs b/src/frontend/src/instance/otlp.rs index 0c03d82e4e4..5cc406a45dd 100644 --- a/src/frontend/src/instance/otlp.rs +++ b/src/frontend/src/instance/otlp.rs @@ -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) }; diff --git a/src/frontend/src/instance/prom_store.rs b/src/frontend/src/instance/prom_store.rs index a5e4c30b832..963a8ae22ed 100644 --- a/src/frontend/src/instance/prom_store.rs +++ b/src/frontend/src/instance/prom_store.rs @@ -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?; diff --git a/src/index/src/fulltext_index/create/tantivy.rs b/src/index/src/fulltext_index/create/tantivy.rs index 6f05921e3a6..6a89115908f 100644 --- a/src/index/src/fulltext_index/create/tantivy.rs +++ b/src/index/src/fulltext_index/create/tantivy.rs @@ -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, + /// Retained across awaits so abort can join a cancelled finish operation. + finishing: Option>>, /// 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, + + /// Pauses the real commit at its blocking boundary in lifecycle tests. + #[cfg(test)] + before_commit: Option>, /// 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> { + 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, config: Config, memory_limit: usize) -> Result { - 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 { + 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 { - 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>, + } #[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, ) -> puffin::error::Result { + 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)]) { diff --git a/src/log-store/Cargo.toml b/src/log-store/Cargo.toml index ee147fbcd4b..8d99c168aef 100644 --- a/src/log-store/Cargo.toml +++ b/src/log-store/Cargo.toml @@ -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 diff --git a/src/log-store/src/error.rs b/src/log-store/src/error.rs index 51f4be7677e..2fac46efe56 100644 --- a/src/log-store/src/error.rs +++ b/src/log-store/src/error.rs @@ -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, diff --git a/src/log-store/src/object_store_wal.rs b/src/log-store/src/object_store_wal.rs index 68046487873..3ef6a166c8e 100644 --- a/src/log-store/src/object_store_wal.rs +++ b/src/log-store/src/object_store_wal.rs @@ -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}; diff --git a/src/log-store/src/object_store_wal/history.rs b/src/log-store/src/object_store_wal/history.rs new file mode 100644 index 00000000000..6dfef700d4c --- /dev/null +++ b/src/log-store/src/object_store_wal/history.rs @@ -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 { + 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 + ) + }) +} diff --git a/src/log-store/src/object_store_wal/index.rs b/src/log-store/src/object_store_wal/index.rs new file mode 100644 index 00000000000..7063e1e0449 --- /dev/null +++ b/src/log-store/src/object_store_wal/index.rs @@ -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, + 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, + pub(crate) releases: Option, +} + +/// Verified header and region index of an immutable object. +#[derive(Debug)] +pub(crate) struct FetchedFooter { + pub(crate) header: Header, + pub(crate) footer: Vec, +} + +/// 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) -> Vec { + let mut candidates = headers.iter().collect::>(); + 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, tip: u64) -> Option> { + 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, + tip: u64, + boundary: u64, +) -> Option> { + 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>, + concurrency: usize, +) -> Result { + 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::>() + .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 { + 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 { + 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 { + 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)> { + 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)) +} diff --git a/src/log-store/src/object_store_wal/io.rs b/src/log-store/src/object_store_wal/io.rs index c14a078f833..71fddbf038d 100644 --- a/src/log-store/src/object_store_wal/io.rs +++ b/src/log-store/src/object_store_wal/io.rs @@ -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) -> Result { - 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) -> Result { + 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> { - 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> { + 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::>(); 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 { +pub(crate) fn normalize_prefix(prefix: &str) -> Result { let prefix = prefix.trim(); ensure!( !prefix.is_empty() && !prefix.starts_with('/'), @@ -372,6 +391,90 @@ fn normalize_prefix(prefix: &str) -> Result { 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; + async fn get_range(&self, object_seq: u64, offset: u64, len: u64) -> Result; + async fn list(&self) -> Result>; + + async fn list_from(&self, object_seq: u64) -> Result> { + 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; + 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> { + 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 { + ObjectStoreIo::get(self, object_seq).await + } + + async fn get_range(&self, object_seq: u64, offset: u64, len: u64) -> Result { + ObjectStoreIo::get_range(self, object_seq, offset, len).await + } + + async fn list(&self) -> Result> { + ObjectStoreIo::list(self).await + } + + async fn list_from(&self, object_seq: u64) -> Result> { + 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 { + 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> { + 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; diff --git a/src/log-store/src/object_store_wal/prefetch.rs b/src/log-store/src/object_store_wal/prefetch.rs new file mode 100644 index 00000000000..ec37c9b0505 --- /dev/null +++ b/src/log-store/src/object_store_wal/prefetch.rs @@ -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> { + 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, + entry: &FooterEntry, +) -> Option { + let records = u64::from(entry.entry_count) * std::mem::size_of::() 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, + object_seq: u64, + entry: FooterEntry, + permit: Option, +) -> impl Future>, Option)> + 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, + objects: Vec<(u64, FooterEntry)>, + budget: Arc, +) -> BoxStream<'static, (u64, FooterEntry, Result>)> { + 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); + } + }) +} diff --git a/src/log-store/src/object_store_wal/reader.rs b/src/log-store/src/object_store_wal/reader.rs new file mode 100644 index 00000000000..4f5a1a97469 --- /dev/null +++ b/src/log-store/src/object_store_wal/reader.rs @@ -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: `/datanodes//epochs/`. +/// 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 { + 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::().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>>, + footer_budget: Arc, +} + +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> { + 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, + /// Immutable indexes keyed by listed metadata, sharing loads within this prefix. + indexes: Cache>, + /// Footer-load concurrency shared by all readers in the node's registry. + footer_budget: Arc, + /// Prefetched bytes shared by reads of this source prefix only. + prefetch_budget: Arc, +} + +/// Cached metadata for an immutable WAL object, without recovery release records. +struct CachedObject { + object: ListedObject, + header: Header, + footer: Vec, +} + +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> { + Cache::new( + "object_store_wal_indexes", + 64 * 1024 * 1024, + |key: &ListedObject, value: &Arc| { + let bytes = std::mem::size_of::() + + key.path.capacity() + + std::mem::size_of::() + + value.object.path.capacity() + + value.footer.capacity() * std::mem::size_of::(); + 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 { + 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> { + 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::>(); + 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 { + 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::>(); + // 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::>() + .await?; + let headers = objects + .iter() + .map(|(seq, object)| (*seq, &object.header)) + .collect::>(); + 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; diff --git a/src/log-store/src/object_store_wal/reader/tests.rs b/src/log-store/src/object_store_wal/reader/tests.rs new file mode 100644 index 00000000000..2034784dd90 --- /dev/null +++ b/src/log-store/src/object_store_wal/reader/tests.rs @@ -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>, + lists: Mutex>, + gate: Option>, + 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 { + let _guard = self.begin_read(seq).await; + self.io.get(seq).await + } + + async fn get_range(&self, seq: u64, offset: u64, len: u64) -> Result { + let _guard = self.begin_read(seq).await; + self.io.get_range(seq, offset, len).await + } + + async fn list(&self) -> Result> { + self.lists.lock().unwrap().push(0); + self.io.list().await + } + + async fn list_from(&self, seq: u64) -> Result> { + 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 { + 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, budget: Arc) -> Arc { + 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, + Arc, +) { + 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> { + Ok(reader + .read(region(), after, upper) + .await? + .try_collect::>() + .await? + .into_iter() + .flatten() + .collect()) +} + +fn expected(records: &[Record]) -> Vec { + 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, + ®istry + .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::>().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::>() + ); + 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, ®istry.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) { + 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 { + 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); +} diff --git a/src/log-store/src/object_store_wal/store.rs b/src/log-store/src/object_store_wal/store.rs index 354521f38d2..b1020978893 100644 --- a/src/log-store/src/object_store_wal/store.rs +++ b/src/log-store/src/object_store_wal/store.rs @@ -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> { - 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, - entry: &FooterEntry, -) -> Option { - let records = u64::from(entry.entry_count) * std::mem::size_of::() 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, - object_seq: u64, - entry: FooterEntry, - permit: Option, -) -> impl Future>, Option)> + 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, - 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, - releases: Option, -} - /// 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 { }) } -/// 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) -> Vec { - let mut candidates = headers.iter().collect::>(); - 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, tip: u64) -> Option> { - 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>, - concurrency: usize, -) -> Result { - 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::>() - .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, Option)> { - 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)> { - 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 { let mut entry_ids = HashMap::new(); for (_, footer) in catalog.objects_in_order() { @@ -3539,70 +3193,6 @@ fn durable_entry_ids(catalog: &ObjectCatalog) -> HashMap { 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; - - async fn get(&self, object_seq: u64) -> Result; - - async fn get_range(&self, object_seq: u64, offset: u64, len: u64) -> Result; - - async fn delete(&self, object_seq: u64) -> Result<()>; - - async fn list(&self) -> Result>; - - /// See [`ObjectStoreIo::list_ahead`]; by default the objects - /// [`list`](Self::list) returns. - fn list_ahead(&self) -> BoxStream<'_, Result> { - 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 { - ObjectStoreIo::put_if_absent(self, object_seq, content).await - } - - async fn get(&self, object_seq: u64) -> Result { - ObjectStoreIo::get(self, object_seq).await - } - - async fn get_range(&self, object_seq: u64, offset: u64, len: u64) -> Result { - 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> { - ObjectStoreIo::list(self).await - } - - fn list_ahead(&self) -> BoxStream<'_, Result> { - 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 { + self.inner.get(object_seq).await + } + + async fn get_range(&self, object_seq: u64, offset: u64, len: u64) -> Result { + self.inner.get_range(object_seq, offset, len).await + } + + async fn list(&self) -> Result> { + 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 { @@ -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>, + } + + #[async_trait::async_trait] + impl WalObjectRead for RacingIo { async fn get(&self, object_seq: u64) -> Result { 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> { 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>, + 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 { - self.inner.get(object_seq).await - } - - async fn get_range(&self, object_seq: u64, offset: u64, len: u64) -> Result { - 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> { - 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 { + 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 { + 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> { + 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 { @@ -10095,38 +9743,12 @@ mod tests { self.inner.put_if_absent(object_seq, content).await } - async fn get(&self, object_seq: u64) -> Result { - 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 { - 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> { - 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>>; @@ -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 { - 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 { 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> { 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 { + 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 { - self.inner.put_if_absent(object_seq, content).await - } - + impl WalObjectRead for CountingIo { async fn get(&self, object_seq: u64) -> Result { 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> { self.inner.list().await } - fn list_ahead(&self) -> BoxStream<'_, Result> { - 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 { + 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> { + self.inner.list_ahead() + } } /// The object store a measurement of recovery runs on: a fresh root diff --git a/src/meta-srv/AGENTS.md b/src/meta-srv/AGENTS.md index c687b41980c..0c61c8ebea4 100644 --- a/src/meta-srv/AGENTS.md +++ b/src/meta-srv/AGENTS.md @@ -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 diff --git a/src/meta-srv/src/error.rs b/src/meta-srv/src/error.rs index 8e6c9097dcc..692f440a5c5 100644 --- a/src/meta-srv/src/error.rs +++ b/src/meta-srv/src/error.rs @@ -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, diff --git a/src/meta-srv/src/gc/handler.rs b/src/meta-srv/src/gc/handler.rs index 1e490ebab58..ffcfa387c21 100644 --- a/src/meta-srv/src/gc/handler.rs +++ b/src/meta-srv/src/gc/handler.rs @@ -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, diff --git a/src/meta-srv/src/gc/mock.rs b/src/meta-srv/src/gc/mock.rs index c164c538917..04e70e8d3a7 100644 --- a/src/meta-srv/src/gc/mock.rs +++ b/src/meta-srv/src/gc/mock.rs @@ -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, } diff --git a/src/meta-srv/src/handler/collect_leader_region_handler.rs b/src/meta-srv/src/handler/collect_leader_region_handler.rs index 0b886a489bf..3ec3d8c69ca 100644 --- a/src/meta-srv/src/handler/collect_leader_region_handler.rs +++ b/src/meta-srv/src/handler/collect_leader_region_handler.rs @@ -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, } diff --git a/src/meta-srv/src/handler/failure_handler.rs b/src/meta-srv/src/handler/failure_handler.rs index 243f09caa23..70aa6279a65 100644 --- a/src/meta-srv/src/handler/failure_handler.rs +++ b/src/meta-srv/src/handler/failure_handler.rs @@ -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, diff --git a/src/meta-srv/src/handler/persist_stats_handler.rs b/src/meta-srv/src/handler/persist_stats_handler.rs index b96af08c12f..f3d7c43452d 100644 --- a/src/meta-srv/src/handler/persist_stats_handler.rs +++ b/src/meta-srv/src/handler/persist_stats_handler.rs @@ -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, diff --git a/src/meta-srv/src/handler/region_lease_handler.rs b/src/meta-srv/src/handler/region_lease_handler.rs index e4338720216..a859bf18327 100644 --- a/src/meta-srv/src/handler/region_lease_handler.rs +++ b/src/meta-srv/src/handler/region_lease_handler.rs @@ -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, diff --git a/src/meta-srv/src/metasrv.rs b/src/meta-srv/src/metasrv.rs index 37d8d3ebb2c..2cd84815fb7 100644 --- a/src/meta-srv/src/metasrv.rs +++ b/src/meta-srv/src/metasrv.rs @@ -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 { + &self.leader_cached_kv_backend + } + /// Returns the undecorated peer client. /// /// Its `active_datanodes` does not know about node scheduling states. Use diff --git a/src/meta-srv/src/procedure/drain_datanode/manager.rs b/src/meta-srv/src/procedure/drain_datanode/manager.rs index 7c227610424..b4bad3e66b3 100644 --- a/src/meta-srv/src/procedure/drain_datanode/manager.rs +++ b/src/meta-srv/src/procedure/drain_datanode/manager.rs @@ -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; /// 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>>, } 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 { + 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, + release: Arc, + } + + #[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 { + self.entered.notify_one(); + self.release.notified().await; + Ok(Status::done()) + } + fn dump(&self) -> common_procedure::Result { + 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 { + 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) -> common_procedure::Result<()> { + self.store.put(key, value).await + } + + async fn walk_top_down( + &self, + path: &str, + ) -> common_procedure::Result + { + 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. diff --git a/src/meta-srv/src/procedure/region_migration/upgrade_candidate_region.rs b/src/meta-srv/src/procedure/region_migration/upgrade_candidate_region.rs index 86e1c35c10c..dbd870076af 100644 --- a/src/meta-srv/src/procedure/region_migration/upgrade_candidate_region.rs +++ b/src/meta-srv/src/procedure/region_migration/upgrade_candidate_region.rs @@ -309,19 +309,21 @@ impl UpgradeCandidateRegion { let mut retry = 0; let mut upgraded = false; + // If using Kafka WAL, hold a read lock on each topic for all attempts to prevent WAL + // pruning during the upgrade. Acquire once: re-acquiring a held read lock on retry + // queues behind a waiting `WalPruneProcedure` writer, which waits on the first guard. let mut guards = Vec::with_capacity(topics.len()); + for topic in &topics { + guards.push( + procedure_ctx + .provider + .acquire_lock(&(RemoteWalLock::Read(topic.clone()).into())) + .await, + ); + } + loop { let timer = Instant::now(); - // If using Kafka WAL, acquire a read lock on the topic to prevent WAL pruning during the upgrade. - for topic in &topics { - guards.push( - procedure_ctx - .provider - .acquire_lock(&(RemoteWalLock::Read(topic.clone()).into())) - .await, - ); - } - if let Err(err) = self.upgrade_region(ctx).await { retry += 1; ctx.update_operations_elapsed(timer); @@ -856,3 +858,205 @@ mod tests { assert_matches!(update_metadata, UpdateMetadata::Rollback); } } + +/// Regression tests for a deadlock between the upgrade step's per-retry `RemoteWalLock::Read` +/// (now acquired once before the retry loop) and `WalPruneProcedure`'s `RemoteWalLock::Write` +/// on the same topic. +/// +/// Mirrors a datanode rolling restart: failover sends the upgrade instruction to a candidate +/// datanode that never answers, the mailbox times out (retryable), and the periodic WAL prune +/// for the region's topic starts while the upgrade is waiting. Both procedures share one +/// `ContextProvider`, as they do inside metasrv's procedure manager. +/// +/// Requires a Kafka broker: `GT_KAFKA_ENDPOINTS=127.0.0.1:9092`. +#[cfg(test)] +mod wal_prune_deadlock_tests { + use std::assert_matches; + use std::sync::Arc; + use std::sync::atomic::{AtomicUsize, Ordering}; + + use common_meta::key::table_route::TableRouteValue; + use common_meta::key::test_utils::new_test_table_info; + use common_meta::peer::Peer; + use common_meta::region_registry::LeaderRegionRegistry; + use common_meta::rpc::router::{Region, RegionRoute}; + use common_meta::wal_provider::{RegionWalOptions, build_kafka_client}; + use common_procedure::Procedure; + use common_wal::config::kafka::common::KafkaConnectionConfig; + use common_wal::maybe_skip_kafka_integration_test; + use common_wal::options::KafkaWalOptions; + use common_wal::test_util::get_kafka_endpoints; + use store_api::storage::RegionId; + use tokio::time::timeout; + + use super::*; + use crate::procedure::region_migration::test_util::{TestingEnv, new_procedure_context}; + use crate::procedure::region_migration::{ + ContextFactory, PersistentContext, RegionMigrationTriggerReason, + }; + use crate::procedure::wal_prune::{Context as WalPruneContext, WalPruneProcedure}; + + struct Scenario { + env: TestingEnv, + ctx: Context, + topic: String, + upgrade_instructions: Arc, + } + + /// One region on a Kafka topic, failing over to a datanode that receives the upgrade + /// instruction but never replies (it is restarting). + async fn setup(name: &str) -> Scenario { + let topic = format!("{name}_{}", uuid::Uuid::new_v4()); + let region_id = RegionId::new(1024, 1); + let persistent_ctx = PersistentContext::new( + vec![("greptime".into(), "public".into())], + Peer::empty(1), + Peer::empty(2), + vec![region_id], + // The migration timeout; the first upgrade attempt consumes all of it. + Duration::from_millis(1000), + RegionMigrationTriggerReason::Failover, + ); + let to_peer_id = persistent_ctx.to_peer.id; + + let mut env = TestingEnv::new(); + let ctx = env.context_factory().new_context(persistent_ctx); + let region_routes = vec![RegionRoute { + region: Region::new_test(region_id), + leader_peer: Some(ctx.persistent_ctx.from_peer.clone()), + follower_peers: vec![ctx.persistent_ctx.to_peer.clone()], + ..Default::default() + }]; + let wal_options = RegionWalOptions::from([( + region_id.region_number(), + WalOptions::Kafka(KafkaWalOptions::new(topic.clone())), + )]); + ctx.table_metadata_manager + .create_table_metadata( + new_test_table_info(region_id.table_id()), + TableRouteValue::physical(region_routes), + wal_options, + ) + .await + .unwrap(); + + let (tx, mut rx) = tokio::sync::mpsc::channel(8); + env.mailbox_context() + .insert_heartbeat_response_receiver(Channel::Datanode(to_peer_id), tx) + .await; + let upgrade_instructions = Arc::new(AtomicUsize::new(0)); + let counter = upgrade_instructions.clone(); + common_runtime::spawn_global(async move { + while let Some(Ok(_)) = rx.recv().await { + counter.fetch_add(1, Ordering::SeqCst); + } + }); + + Scenario { + env, + ctx, + topic, + upgrade_instructions, + } + } + + async fn wait_for_first_instruction(counter: &AtomicUsize) { + timeout(Duration::from_secs(5), async { + while counter.load(Ordering::SeqCst) == 0 { + sleep(Duration::from_millis(10)).await; + } + }) + .await + .unwrap(); + } + + #[tokio::test] + async fn test_upgrade_retry_does_not_deadlock_with_wal_prune() { + maybe_skip_kafka_integration_test!(); + let Scenario { + env, + mut ctx, + topic, + upgrade_instructions, + } = setup("upgrade_wal_prune_deadlock").await; + // Metasrv shares one provider (and dynamic key lock) across all procedures. + let procedure_ctx = new_procedure_context(); + + let migration_procedure_ctx = procedure_ctx.clone(); + let migration = tokio::spawn(async move { + let mut state = Box::::default(); + state.next(&mut ctx, &migration_procedure_ctx).await + }); + // The upgrade step now holds `RemoteWalLock::Read(topic)` and waits on the datanode. + wait_for_first_instruction(&upgrade_instructions).await; + + // The periodic WAL prune for the region's topic starts. + let client = build_kafka_client(&KafkaConnectionConfig { + broker_endpoints: get_kafka_endpoints(), + ..Default::default() + }) + .await + .unwrap(); + client + .controller_client() + .unwrap() + .create_topic(&topic, 1, 1, 5000) + .await + .unwrap(); + let mut wal_prune = WalPruneProcedure::new( + WalPruneContext { + client: Arc::new(client), + table_metadata_manager: env.table_metadata_manager().clone(), + leader_region_registry: Arc::new(LeaderRegionRegistry::new()), + }, + None, + topic, + 0, + false, + ); + let wal_prune_procedure_ctx = procedure_ctx.clone(); + let wal_prune = + tokio::spawn(async move { wal_prune.execute(&wal_prune_procedure_ctx).await }); + + // The mailbox times out after ~1s (retryable). The retry keeps the read lock it already + // holds, fails fast with `ExceededDeadline`, and the migration rolls back. Releasing the + // read lock then lets the queued WAL prune run. + let (next, _) = timeout(Duration::from_secs(10), migration) + .await + .expect("upgrade step should not deadlock") + .unwrap() + .unwrap(); + let update_metadata = next.as_any().downcast_ref::().unwrap(); + assert_matches!(update_metadata, UpdateMetadata::Rollback); + assert_eq!(1, upgrade_instructions.load(Ordering::SeqCst)); + + timeout(Duration::from_secs(10), wal_prune) + .await + .expect("WAL prune should not deadlock") + .unwrap() + .unwrap(); + } + + #[tokio::test] + async fn test_upgrade_retry_without_wal_prune_rolls_back() { + maybe_skip_kafka_integration_test!(); + let Scenario { + mut ctx, + upgrade_instructions, + .. + } = setup("upgrade_wal_prune_control").await; + let procedure_ctx = new_procedure_context(); + + let mut state = Box::::default(); + let (next, _) = timeout( + Duration::from_secs(10), + state.next(&mut ctx, &procedure_ctx), + ) + .await + .expect("upgrade step should finish without WAL prune") + .unwrap(); + let update_metadata = next.as_any().downcast_ref::().unwrap(); + assert_matches!(update_metadata, UpdateMetadata::Rollback); + assert_eq!(1, upgrade_instructions.load(Ordering::SeqCst)); + } +} diff --git a/src/meta-srv/src/selector/weight_compute.rs b/src/meta-srv/src/selector/weight_compute.rs index d39fda3b8e5..eda2a0357ad 100644 --- a/src/meta-srv/src/selector/weight_compute.rs +++ b/src/meta-srv/src/selector/weight_compute.rs @@ -200,7 +200,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, @@ -235,7 +235,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, @@ -270,7 +270,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, diff --git a/src/meta-srv/src/service/admin.rs b/src/meta-srv/src/service/admin.rs index 1e977fcd8e8..17aec347364 100644 --- a/src/meta-srv/src/service/admin.rs +++ b/src/meta-srv/src/service/admin.rs @@ -12,6 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. +pub(crate) mod datanode; pub(crate) mod health; pub(crate) mod heartbeat; pub(crate) mod leader; @@ -255,6 +256,24 @@ pub fn admin_axum_router(metasrv: Arc) -> AxumRouter { }; let admin_router = AxumRouter::new() + .nest( + "/datanode", + AxumRouter::new() + .route("/drain", routing::post(datanode::drain)) + .route( + "/mark-schedulable", + routing::post(datanode::mark_schedulable), + ) + .route( + "/scheduling/status", + routing::get(datanode::scheduling_status), + ) + .with_state(metasrv.clone()), + ) + .route( + "/procedure/status", + routing::get(procedure::procedure_status).with_state(metasrv), + ) .route("/health", routing::get(health::health)) .route( "/node-lease", diff --git a/src/meta-srv/src/service/admin/datanode.rs b/src/meta-srv/src/service/admin/datanode.rs new file mode 100644 index 00000000000..aef25805814 --- /dev/null +++ b/src/meta-srv/src/service/admin/datanode.rs @@ -0,0 +1,568 @@ +// 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 axum::Json; +use axum::extract::{Query, State}; +use axum::response::{IntoResponse, Response}; +use common_procedure::ProcedureContext; +use serde::{Deserialize, Serialize}; +use servers::http::result::error_result::ErrorResponse; + +use crate::key::NodeSchedulingRole; +use crate::metasrv::Metasrv; +use crate::procedure::drain_datanode::{ + DEFAULT_DRAIN_TIMEOUT, DEFAULT_PARALLELISM, DrainDatanodeProcedureTask, DrainDatanodeStrategy, +}; +use crate::service::admin::util; + +#[derive(Debug, Deserialize)] +pub(crate) struct DrainDatanodeRequest { + node_id: u64, + target_node_id: Option, + /// Concurrent region budget; defaults to [`DEFAULT_PARALLELISM`]. + #[serde(default = "default_parallelism")] + parallelism: usize, + /// Failure handling; defaults to [`DrainDatanodeStrategy::TryAll`]. + #[serde(default)] + strategy: DrainStrategy, + /// Whole-drain budget; defaults to [`DEFAULT_DRAIN_TIMEOUT`]. + #[serde(default = "default_timeout", with = "humantime_serde")] + timeout: Duration, +} + +/// HTTP strategy names follow the admin API's snake_case convention. +#[derive(Debug, Default, Deserialize)] +#[serde(rename_all = "snake_case")] +enum DrainStrategy { + FailFast, + #[default] + TryAll, +} + +impl From for DrainDatanodeStrategy { + fn from(strategy: DrainStrategy) -> Self { + match strategy { + DrainStrategy::FailFast => Self::FailFast, + DrainStrategy::TryAll => Self::TryAll, + } + } +} + +impl From for DrainDatanodeProcedureTask { + fn from(request: DrainDatanodeRequest) -> Self { + Self { + node_id: request.node_id, + target_node_id: request.target_node_id, + parallelism: request.parallelism, + strategy: request.strategy.into(), + timeout: Some(request.timeout), + } + } +} + +#[derive(Debug, Deserialize)] +pub(crate) struct DatanodeRequest { + node_id: u64, +} + +#[derive(Debug, Serialize)] +pub(crate) struct DrainDatanodeResponse { + procedure_id: String, +} + +#[derive(Debug, Serialize)] +pub(crate) struct DatanodeSchedulingResponse { + node_id: u64, + schedulable: bool, +} + +fn default_parallelism() -> usize { + DEFAULT_PARALLELISM +} + +fn default_timeout() -> Duration { + DEFAULT_DRAIN_TIMEOUT +} + +/// Submits an asynchronous leader-region drain. +/// Rejects requests for a datanode already being drained. +#[axum_macros::debug_handler] +pub(crate) async fn drain( + State(metasrv): State>, + Json(request): Json, +) -> Response { + async { + util::ensure_leader(&metasrv)?; + let procedure_id = metasrv + .drain_datanode_manager() + .submit_procedure(ProcedureContext::default(), request.into()) + .await?; + Ok::<_, crate::error::Error>(DrainDatanodeResponse { + procedure_id: procedure_id.to_string(), + }) + } + .await + .map(Json) + .map_err(ErrorResponse::from_error) + .into_response() +} + +/// Restores scheduling; an active drain must finish before the node can receive regions. +#[axum_macros::debug_handler] +pub(crate) async fn mark_schedulable( + State(metasrv): State>, + Json(request): Json, +) -> Response { + async { + util::ensure_leader(&metasrv)?; + metasrv + .drain_datanode_manager() + .mark_schedulable(request.node_id) + .await?; + Ok::<_, crate::error::Error>(DatanodeSchedulingResponse { + node_id: request.node_id, + schedulable: true, + }) + } + .await + .map(Json) + .map_err(ErrorResponse::from_error) + .into_response() +} + +/// Reads the node's scheduling state from the leader. +#[axum_macros::debug_handler] +pub(crate) async fn scheduling_status( + State(metasrv): State>, + Query(request): Query, +) -> Response { + async { + util::ensure_leader(&metasrv)?; + let schedulable = metasrv + .node_scheduling_manager() + .is_schedulable(NodeSchedulingRole::Datanode, request.node_id) + .await?; + Ok::<_, crate::error::Error>(DatanodeSchedulingResponse { + node_id: request.node_id, + schedulable, + }) + } + .await + .map(Json) + .map_err(ErrorResponse::from_error) + .into_response() +} + +#[cfg(test)] +mod tests { + use std::sync::atomic::{AtomicBool, Ordering}; + + use axum::Router; + use axum::body::{Body, to_bytes}; + use axum::http::{Method, Request, StatusCode}; + use common_meta::election::{Election, LeaderChangeMessage, LeaderValue, MetasrvNodeInfo}; + use serde_json::{Value, json}; + use tower::ServiceExt; + + use super::*; + use crate::metasrv::builder::MetasrvBuilder; + use crate::service::admin::admin_axum_router; + + struct TestElection(AtomicBool); + + #[async_trait::async_trait] + impl Election for TestElection { + type Leader = LeaderValue; + fn is_leader(&self) -> bool { + self.0.load(Ordering::Relaxed) + } + fn in_leader_infancy(&self) -> bool { + false + } + async fn register_candidate(&self, _: &MetasrvNodeInfo) -> common_meta::error::Result<()> { + Ok(()) + } + async fn all_candidates(&self) -> common_meta::error::Result> { + Ok(vec![]) + } + async fn campaign(&self) -> common_meta::error::Result<()> { + Ok(()) + } + async fn leader(&self) -> common_meta::error::Result { + Ok(LeaderValue("leader:3002".into())) + } + async fn resign(&self) -> common_meta::error::Result<()> { + Ok(()) + } + fn subscribe_leader_change(&self) -> tokio::sync::broadcast::Receiver { + tokio::sync::broadcast::channel(1).1 + } + } + + async fn request(app: Router, method: Method, uri: &str, body: Value) -> (StatusCode, Value) { + let response = app + .oneshot( + Request::builder() + .method(method) + .uri(uri) + .header("content-type", "application/json") + .body(Body::from(body.to_string())) + .unwrap(), + ) + .await + .unwrap(); + let status = response.status(); + let bytes = to_bytes(response.into_body(), usize::MAX).await.unwrap(); + (status, serde_json::from_slice(&bytes).unwrap()) + } + + #[test] + fn test_drain_request_options() { + for (body, parallelism, strategy) in [ + (json!({"node_id": 1}), 4, DrainDatanodeStrategy::TryAll), + ( + json!({"node_id": 1, "parallelism": 8}), + 8, + DrainDatanodeStrategy::TryAll, + ), + ( + json!({"node_id": 1, "strategy": "fail_fast"}), + 4, + DrainDatanodeStrategy::FailFast, + ), + ( + json!({"node_id": 1, "parallelism": 1, "strategy": "fail_fast"}), + 1, + DrainDatanodeStrategy::FailFast, + ), + ( + json!({"node_id": 1, "parallelism": 32, "strategy": "try_all"}), + 32, + DrainDatanodeStrategy::TryAll, + ), + ] { + let request: DrainDatanodeRequest = serde_json::from_value(body).unwrap(); + let task: DrainDatanodeProcedureTask = request.into(); + assert_eq!(parallelism, task.parallelism); + assert_eq!(strategy, task.strategy); + assert_eq!(1, task.node_id); + assert_eq!(None, task.target_node_id); + assert_eq!(Some(Duration::from_secs(20 * 60)), task.timeout); + } + } + + #[test] + fn test_drain_request_timeout() { + for (value, expected) in [ + (json!("30m"), Some(Duration::from_secs(1800))), + (json!("1h 30m"), Some(Duration::from_secs(5400))), + (json!("500ms"), Some(Duration::from_millis(500))), + ] { + let request: DrainDatanodeRequest = + serde_json::from_value(json!({"node_id": 1, "timeout": value})).unwrap(); + let task: DrainDatanodeProcedureTask = request.into(); + assert_eq!(expected, task.timeout); + } + } + + #[tokio::test] + async fn test_http_drain_rejects_invalid_options() { + let metasrv = Arc::new(MetasrvBuilder::new().build().await.unwrap()); + metasrv.procedure_manager().start().await.unwrap(); + let app = admin_axum_router(metasrv.clone()); + for (options, expected) in [ + (json!({"timeout": null}), StatusCode::UNPROCESSABLE_ENTITY), + ( + json!({"parallelism": null}), + StatusCode::UNPROCESSABLE_ENTITY, + ), + (json!({"strategy": null}), StatusCode::BAD_REQUEST), + (json!({"timeout": "0s"}), StatusCode::BAD_REQUEST), + ( + json!({"timeout": "9223372036854775s"}), + StatusCode::BAD_REQUEST, + ), + ( + json!({"timeout": "9223372036854776s"}), + StatusCode::BAD_REQUEST, + ), + ( + json!({"timeout": "invalid"}), + StatusCode::UNPROCESSABLE_ENTITY, + ), + (json!({"timeout": "-1s"}), StatusCode::UNPROCESSABLE_ENTITY), + (json!({"parallelism": 0}), StatusCode::BAD_REQUEST), + (json!({"parallelism": 33}), StatusCode::BAD_REQUEST), + (json!({"parallelism": -1}), StatusCode::UNPROCESSABLE_ENTITY), + ( + json!({"parallelism": 1.5}), + StatusCode::UNPROCESSABLE_ENTITY, + ), + ( + json!({"strategy": "unknown"}), + StatusCode::UNPROCESSABLE_ENTITY, + ), + ( + json!({"strategy": "FailFast"}), + StatusCode::UNPROCESSABLE_ENTITY, + ), + ] { + let mut body = options; + body["node_id"] = json!(1); + let response = app + .clone() + .oneshot( + Request::builder() + .method(Method::POST) + .uri("/admin/datanode/drain") + .header("content-type", "application/json") + .body(Body::from(body.to_string())) + .unwrap(), + ) + .await + .unwrap(); + assert_eq!(expected, response.status(), "{body}"); + } + assert!( + metasrv + .procedure_manager() + .list_procedures() + .await + .unwrap() + .is_empty() + ); + assert!( + metasrv + .node_scheduling_manager() + .is_schedulable(NodeSchedulingRole::Datanode, 1) + .await + .unwrap() + ); + metasrv.procedure_manager().stop().await.unwrap(); + } + + #[tokio::test] + async fn test_http_scheduling_is_idempotent() { + let metasrv = Arc::new(MetasrvBuilder::new().build().await.unwrap()); + let app = admin_axum_router(metasrv.clone()); + metasrv.procedure_manager().start().await.unwrap(); + metasrv + .node_scheduling_manager() + .mark_unschedulable(NodeSchedulingRole::Datanode, 1) + .await + .unwrap(); + for _ in 0..2 { + assert_eq!( + (StatusCode::OK, json!({"node_id": 1, "schedulable": true})), + request( + app.clone(), + Method::POST, + "/admin/datanode/mark-schedulable", + json!({"node_id": 1}) + ) + .await + ); + } + assert_eq!( + (StatusCode::OK, json!({"node_id": 1, "schedulable": true})), + request( + app.clone(), + Method::GET, + "/admin/datanode/scheduling/status?node_id=1", + Value::Null + ) + .await + ); + let (status, _) = request( + app, + Method::POST, + "/admin/datanode/drain", + json!({"node_id": 1, "target_node_id": 1}), + ) + .await; + assert_eq!(StatusCode::BAD_REQUEST, status); + metasrv.procedure_manager().stop().await.unwrap(); + } + + #[tokio::test] + async fn test_http_follower_rejects_admin_operations_without_side_effects() { + let election = Arc::new(TestElection(AtomicBool::new(false))); + let metasrv = Arc::new( + MetasrvBuilder::new() + .election(Some(election.clone())) + .build() + .await + .unwrap(), + ); + let app = admin_axum_router(metasrv.clone()); + metasrv.procedure_manager().start().await.unwrap(); + metasrv + .node_scheduling_manager() + .mark_unschedulable(NodeSchedulingRole::Datanode, 1) + .await + .unwrap(); + for (method, uri, body) in [ + ( + Method::POST, + "/admin/datanode/drain", + json!({"node_id": 1, "target_node_id": 2}), + ), + ( + Method::POST, + "/admin/datanode/mark-schedulable", + json!({"node_id": 1}), + ), + ( + Method::GET, + "/admin/datanode/scheduling/status?node_id=1", + Value::Null, + ), + ( + Method::GET, + "/admin/procedure/status?procedure_id=00000000-0000-0000-0000-000000000001", + Value::Null, + ), + ] { + let (status, body) = request(app.clone(), method, uri, body).await; + assert_eq!(StatusCode::INTERNAL_SERVER_ERROR, status, "{body}"); + assert!(body["error"].as_str().unwrap().contains("not leader")); + } + assert!( + metasrv + .procedure_manager() + .list_procedures() + .await + .unwrap() + .is_empty() + ); + assert!( + !metasrv + .node_scheduling_manager() + .is_schedulable(NodeSchedulingRole::Datanode, 1) + .await + .unwrap() + ); + election.0.store(true, Ordering::Relaxed); + assert_eq!( + (StatusCode::OK, json!({"node_id": 1, "schedulable": true})), + request( + app, + Method::POST, + "/admin/datanode/mark-schedulable", + json!({"node_id": 1}) + ) + .await + ); + metasrv.procedure_manager().stop().await.unwrap(); + } + + #[tokio::test] + async fn test_http_procedure_status_and_request_validation() { + let metasrv = Arc::new(MetasrvBuilder::new().build().await.unwrap()); + metasrv.procedure_manager().start().await.unwrap(); + let app = admin_axum_router(metasrv.clone()); + let (status, body) = request( + app.clone(), + Method::POST, + "/admin/datanode/drain", + json!({"node_id": 1}), + ) + .await; + assert_eq!(StatusCode::OK, status, "{body}"); + let pid = body["procedure_id"].as_str().unwrap(); + let uri = format!("/admin/procedure/status?procedure_id={pid}"); + tokio::time::timeout(std::time::Duration::from_secs(5), async { + loop { + let (status, body) = request(app.clone(), Method::GET, &uri, Value::Null).await; + assert_eq!(StatusCode::OK, status); + assert_eq!(pid, body["procedure_id"]); + if body["status"] == "Done" { + assert_eq!( + json!({"procedure_id": pid, "status": "Done", "error": null}), + body + ); + break; + } + tokio::task::yield_now().await; + } + }) + .await + .unwrap(); + for (uri, expected) in [ + ( + "/admin/procedure/status?procedure_id=bad", + StatusCode::BAD_REQUEST, + ), + ( + "/admin/procedure/status?procedure_id=00000000-0000-0000-0000-000000000001", + StatusCode::BAD_REQUEST, + ), + ] { + let (status, body) = request(app.clone(), Method::GET, uri, Value::Null).await; + assert_eq!(expected, status); + if uri.ends_with("=bad") { + assert!( + body["error"] + .as_str() + .unwrap() + .contains("invalid procedure id: bad") + ); + } + } + for (method, uri, body, expected) in [ + ( + Method::GET, + "/admin/datanode/drain", + json!({"node_id": 1}), + StatusCode::METHOD_NOT_ALLOWED, + ), + ( + Method::POST, + "/admin/datanode/drain", + json!({"node_id": -1}), + StatusCode::UNPROCESSABLE_ENTITY, + ), + ( + Method::POST, + "/admin/datanode/drain", + json!({}), + StatusCode::UNPROCESSABLE_ENTITY, + ), + ( + Method::GET, + "/admin/datanode/scheduling/status", + Value::Null, + StatusCode::BAD_REQUEST, + ), + ] { + let response = app + .clone() + .oneshot( + Request::builder() + .method(method) + .uri(uri) + .header("content-type", "application/json") + .body(Body::from(body.to_string())) + .unwrap(), + ) + .await + .unwrap(); + assert_eq!(expected, response.status()); + } + metasrv.procedure_manager().stop().await.unwrap(); + } +} diff --git a/src/meta-srv/src/service/admin/procedure.rs b/src/meta-srv/src/service/admin/procedure.rs index c40b20cab90..2da1f4405f5 100644 --- a/src/meta-srv/src/service/admin/procedure.rs +++ b/src/meta-srv/src/service/admin/procedure.rs @@ -13,18 +13,24 @@ // limitations under the License. use std::collections::HashMap; +use std::sync::Arc; use axum::Json; -use axum::extract::State; +use axum::extract::{Query, State}; use axum::response::{IntoResponse, Response}; use common_meta::key::runtime_switch::RuntimeSwitchManagerRef; +use common_meta::rpc::procedure; +use common_procedure::ProcedureId; use common_telemetry::info; use serde::{Deserialize, Serialize}; -use snafu::ResultExt; +use servers::http::result::error_result::ErrorResponse; +use snafu::{OptionExt, ResultExt}; use tonic::codegen::http; -use crate::error::RuntimeSwitchManagerSnafu; +use crate::error::{self, RuntimeSwitchManagerSnafu}; +use crate::metasrv::Metasrv; use crate::service::admin::HttpHandler; +use crate::service::admin::util; use crate::service::admin::util::{ErrorHandler, to_json_response, to_not_found_response}; #[derive(Clone)] @@ -158,3 +164,50 @@ impl HttpHandler for ProcedureManagerHandler { } } } + +#[derive(Debug, Deserialize)] +pub(crate) struct ProcedureStatusRequest { + procedure_id: String, +} + +#[derive(Debug, Serialize)] +pub(crate) struct ProcedureStatusResponse { + procedure_id: String, + status: String, + error: Option, +} + +/// Queries a submitted procedure, independently of the procedure-manager switch. +#[axum_macros::debug_handler] +pub(crate) async fn procedure_status( + State(metasrv): State>, + Query(request): Query, +) -> Response { + async { + util::ensure_leader(&metasrv)?; + let pid = request.procedure_id.parse::().map_err(|_| { + error::InvalidArgumentsSnafu { + err_msg: format!("invalid procedure id: {}", request.procedure_id), + } + .build() + })?; + let state = metasrv + .procedure_manager() + .procedure_state(pid) + .await + .context(error::QueryProcedureSnafu)? + .with_context(|| error::ProcedureNotFoundSnafu { + pid: request.procedure_id, + })?; + let (_, error) = procedure::procedure_state_to_pb_state(&state); + Ok::<_, error::Error>(ProcedureStatusResponse { + procedure_id: pid.to_string(), + status: state.as_str_name().to_string(), + error: (!error.is_empty()).then_some(error), + }) + } + .await + .map(Json) + .map_err(ErrorResponse::from_error) + .into_response() +} diff --git a/src/meta-srv/src/service/admin/util.rs b/src/meta-srv/src/service/admin/util.rs index 532678b72de..dbd0a28614e 100644 --- a/src/meta-srv/src/service/admin/util.rs +++ b/src/meta-srv/src/service/admin/util.rs @@ -17,10 +17,11 @@ use std::fmt::Debug; use axum::http::StatusCode; use axum::response::{IntoResponse, Response}; use serde::Serialize; -use snafu::ResultExt; +use snafu::{ResultExt, ensure}; use tonic::codegen::http; use crate::error::{self, Result}; +use crate::metasrv::Metasrv; /// Returns a 200 response with a text body. pub fn to_text_response(text: &str) -> Result> { @@ -76,3 +77,14 @@ where (StatusCode::INTERNAL_SERVER_ERROR, self.0.to_string()).into_response() } } + +/// Uses the same leadership predicate as the metasrv gRPC procedure service. +pub(crate) fn ensure_leader(metasrv: &Metasrv) -> Result<()> { + ensure!( + metasrv.is_leader(), + error::IsNotLeaderSnafu { + node_addr: metasrv.options().grpc.server_addr.clone(), + } + ); + Ok(()) +} diff --git a/src/meta-srv/src/service/store/cached_kv.rs b/src/meta-srv/src/service/store/cached_kv.rs index deccf67e021..cf1ab1b32a5 100644 --- a/src/meta-srv/src/service/store/cached_kv.rs +++ b/src/meta-srv/src/service/store/cached_kv.rs @@ -344,7 +344,8 @@ impl TxnService for LeaderCachedKvBackend { async fn txn(&self, txn: Txn) -> Result { let _ = self.create_new_version(); - let res = self.store.txn(txn.clone()).await?; + // A transaction may commit even if the backend returns an error. + let res = self.store.txn(txn.clone()).await; self.create_new_version(); let TxnRequest { success, failure, .. @@ -367,7 +368,10 @@ impl TxnService for LeaderCachedKvBackend { TxnOp::Get(_) => {} } } - self.invalid_keys(keys).await?; + let invalidation = self.invalid_keys(keys).await; + // Preserve the backend error after completing cache invalidation. + let res = res?; + invalidation?; Ok(res) } @@ -420,12 +424,19 @@ mod tests { } } + #[derive(Clone, Copy)] + enum TxnError { + BeforeCommit, + AfterCommit, + } + #[derive(Default)] struct ControlledBackend { inner: MemoryKvBackend, before_write: Pause, after_write: Pause, after_read: Pause, + txn_error: Mutex>, } #[async_trait::async_trait] @@ -433,9 +444,22 @@ mod tests { type Error = Error; async fn txn(&self, txn: Txn) -> Result { + let error = self.txn_error.lock().unwrap().take(); self.before_write.wait().await; + if matches!(error, Some(TxnError::BeforeCommit)) { + return common_meta::error::UnexpectedSnafu { + err_msg: "injected transaction error", + } + .fail(); + } let res = self.inner.txn(txn).await; self.after_write.wait().await; + if matches!(error, Some(TxnError::AfterCommit)) { + return common_meta::error::UnexpectedSnafu { + err_msg: "injected transaction error", + } + .fail(); + } res } @@ -605,6 +629,86 @@ mod tests { } } + #[tokio::test] + async fn test_txn_error_invalidates_both_branches() { + const OTHER_KEY: &[u8] = b"__table_name/2"; + for error in [TxnError::BeforeCommit, TxnError::AfterCommit] { + for success in [false, true] { + let backing = Arc::new(ControlledBackend::default()); + let store = LeaderCachedKvBackend::with_always_leader(backing.clone()); + for key in [KEY, OTHER_KEY] { + store + .put(PutRequest::new().with_key(key).with_value(b"old")) + .await + .unwrap(); + assert!(store.cache.get(key).await.unwrap().is_some()); + } + *backing.txn_error.lock().unwrap() = Some(error); + let txn = Txn::new() + .when(vec![Compare::with_value( + KEY.to_vec(), + CompareOp::Equal, + if success { + b"old".to_vec() + } else { + b"missing".to_vec() + }, + )]) + .and_then(vec![TxnOp::Put(KEY.to_vec(), b"new".to_vec())]) + .or_else(vec![TxnOp::Delete(OTHER_KEY.to_vec())]); + let err = store.txn(txn).await.err().unwrap(); + assert!(matches!(err, Error::Unexpected { err_msg, .. } + if err_msg == "injected transaction error")); + for key in [KEY, OTHER_KEY] { + assert!(store.cache.get(key).await.unwrap().is_none()); + assert_eq!( + store.get(key).await.unwrap(), + backing.inner.get(key).await.unwrap() + ); + } + let expected = if matches!(error, TxnError::AfterCommit) && success { + b"new".as_slice() + } else { + b"old".as_slice() + }; + assert_eq!(store.get(KEY).await.unwrap().unwrap().value(), expected); + assert_eq!( + store.get(OTHER_KEY).await.unwrap().is_none(), + matches!(error, TxnError::AfterCommit) && !success + ); + } + } + } + + #[tokio::test] + async fn test_txn_error_invalidates_overlapping_cache_fill() { + for batch in [false, true] { + let backing = Arc::new(ControlledBackend::default()); + backing + .inner + .put(PutRequest::new().with_key(KEY).with_value(b"old")) + .await + .unwrap(); + let store = LeaderCachedKvBackend::with_always_leader(backing.clone()); + *backing.txn_error.lock().unwrap() = Some(TxnError::AfterCommit); + let commit = backing.before_write.arm(); + let writer = + store.txn(Txn::new().and_then(vec![TxnOp::Put(KEY.to_vec(), b"new".to_vec())])); + tokio::pin!(writer); + assert!(poll!(writer.as_mut()).is_pending()); + + let return_read = backing.after_read.arm(); + let reader = read(&store, batch); + tokio::pin!(reader); + assert!(poll!(reader.as_mut()).is_pending()); + commit.send(()).unwrap(); + assert!(writer.await.is_err()); + return_read.send(()).unwrap(); + assert_eq!(reader.await.unwrap().value(), b"old"); + assert_eq!(read(&store, batch).await.unwrap().value(), b"new"); + } + } + /// A cache miss reads the old value after a writer starts, then returns after /// the writer has committed and updated/invalidated the cache (#9548). #[tokio::test] diff --git a/src/metric-engine/src/engine.rs b/src/metric-engine/src/engine.rs index 319ddc539d2..376d9f4b564 100644 --- a/src/metric-engine/src/engine.rs +++ b/src/metric-engine/src/engine.rs @@ -247,7 +247,7 @@ impl RegionEngine for MetricEngine { .alter_regions(vec![(region_id, alter)], &mut extension_return_value) .await } - RegionRequest::Compact(_) => { + RegionRequest::Compact(_) | RegionRequest::CancelCompaction(_) => { if self.inner.is_physical_region(region_id) { self.inner .mito @@ -661,8 +661,9 @@ mod test { use store_api::metric_engine_consts::PHYSICAL_TABLE_METADATA_KEY; use store_api::mito_engine_options::WAL_OPTIONS_KEY; use store_api::region_request::{ - PathType, RegionCleanUpRequest, RegionCloseRequest, RegionDropRequest, RegionFlushRequest, - RegionOpenRequest, RegionPutRequest, RegionRequest, RegionTruncateRequest, + PathType, RegionCancelCompactionRequest, RegionCleanUpRequest, RegionCloseRequest, + RegionDropRequest, RegionFlushRequest, RegionOpenRequest, RegionPutRequest, RegionRequest, + RegionTruncateRequest, }; use super::*; @@ -702,6 +703,34 @@ mod test { ); } + #[tokio::test] + async fn test_cancel_compaction_physical_and_logical_regions() { + let env = TestEnv::new().await; + env.init_metric_region().await; + let request = || { + RegionRequest::CancelCompaction(RegionCancelCompactionRequest { + task_id: "stale-task-id".to_string(), + }) + }; + // Mito returns zero for an absent task; reaching that result proves forwarding. + let response = env + .metric() + .handle_request(env.default_physical_region_id(), request()) + .await + .unwrap(); + assert_eq!(response.affected_rows, 0); + + let error = env + .metric() + .handle_request(env.default_logical_region_id(), request()) + .await + .unwrap_err(); + assert_eq!( + common_error::status_code::StatusCode::Unsupported, + error.status_code() + ); + } + #[tokio::test] async fn test_discard_unflushed_data_only() { let env = TestEnv::new().await; diff --git a/src/metric-engine/src/utils.rs b/src/metric-engine/src/utils.rs index 64834a3f091..43ec4a13586 100644 --- a/src/metric-engine/src/utils.rs +++ b/src/metric-engine/src/utils.rs @@ -80,8 +80,8 @@ fn merge_region_statistic( metadata_manifest_version: metadata_stat.manifest.data_manifest_version(), }, written_bytes: metadata_stat.written_bytes + data_stat.written_bytes, - flushed_parquet_bytes: metadata_stat.flushed_parquet_bytes - + data_stat.flushed_parquet_bytes, + ingested_parquet_bytes: metadata_stat.ingested_parquet_bytes + + data_stat.ingested_parquet_bytes, query_cpu_time: data_stat.query_cpu_time, query_scanned_bytes: data_stat.query_scanned_bytes, data_topic_latest_entry_id: data_stat.data_topic_latest_entry_id, @@ -153,17 +153,17 @@ mod tests { } #[test] - fn merge_region_statistic_sums_flushed_parquet_bytes() { + fn merge_region_statistic_sums_ingested_parquet_bytes() { let metadata_stat = RegionStatistic { - flushed_parquet_bytes: 123, + ingested_parquet_bytes: 123, ..Default::default() }; let data_stat = RegionStatistic { - flushed_parquet_bytes: 456, + ingested_parquet_bytes: 456, ..Default::default() }; assert_eq!( - merge_region_statistic(&metadata_stat, &data_stat).flushed_parquet_bytes, + merge_region_statistic(&metadata_stat, &data_stat).ingested_parquet_bytes, 579 ); } diff --git a/src/mito2/AGENTS.md b/src/mito2/AGENTS.md index 39aabea1909..9f12cd750cd 100644 --- a/src/mito2/AGENTS.md +++ b/src/mito2/AGENTS.md @@ -24,6 +24,7 @@ snapshot isolation). It implements the `RegionEngine` trait from `store-api`. | `memtable` | `src/mito2/src/memtable/` | In-memory write buffers (time-series / bulk / partition) | | `flush` | `src/mito2/src/flush.rs` | `FlushScheduler`, `WriteBufferManager`, memtable → SST | | `compaction` | `src/mito2/src/compaction/` | Compaction scheduler (`scheduler.rs` + `scheduler/`), TWCS picker, strict-window manual picker, compactor, memory control | +| `compaction/multi_region` | `src/mito2/src/compaction/multi_region.rs` | Enterprise lossless routing by a captured table partition rule; selected SSTs to per-region outputs, without manifest publication | | `access_layer` | `src/mito2/src/access_layer.rs` | SST read/write over the object store | | `sst` | `src/mito2/src/sst/` | Parquet format, file metadata, index layout | | `series_index` | `src/mito2/src/series_index/` | Series index writer/searcher, bucket planning, catalogs, worker-owned reconciliation (`maintenance.rs`), shared approximate usage (`task.rs`), catalogs, and index lifecycle | @@ -57,6 +58,18 @@ Internal series merges use the query runtime pool forwarded through `QueryScanContext`; reader and output-batch accounting uses the separate scan memory tracker. Direct scanner callers default to an unbounded operator pool. +Live compaction queries read shared per-region state directly from `MitoRegion`, +without sending a worker request. The scheduler publishes active and pending task +state together; readers clone task Arcs under a short read lock, then filter and +build rows outside the lock. Execution handles provide live background phases. +There is no second task registry or completed-task history. See +`compaction/scheduler/state.rs`. The datanode provider reuses the lazy inspection scan +path and retains residual SQL filters. +Task cancellation uses `RegionRequest::CancelCompaction` through `Region.Handle`; +the owning worker matches the live task ID without entering the DDL queue. +Task-specific cancellation preserves other pending manual work when no DDL is +pending. DDL cancellation retains its existing scheduling fence and priority. + ## Public surface - Entry: `MitoEngine` in `src/mito2/src/engine.rs`, built via `MitoEngineBuilder`. @@ -66,7 +79,10 @@ memory tracker. Direct scanner callers default to an unbounded operator pool. ## When you change X, also touch Y - **Manifest format** (`manifest/action.rs`): affects crash recovery and - follower replay. Keep it backward compatible. + follower replay. Keep it backward compatible. Compaction task state does not + belong in the manifest; publication uses ordinary file edits after locked input + checks. Shared SSTs require Enterprise capability. Compatibility fixtures: + `tests/compatibility/manifest/table_compaction/`. - **SST/Parquet layout** (`sst/`): readers must stay compatible with existing files. - **Series-index disk limit**: tasks estimate usage from entry sizes in open-region snapshots and defer new builds when the shared estimate is full. Cleanup still prunes obsolete @@ -88,15 +104,25 @@ Tests live next to the code as `*_test.rs` (e.g. `src/mito2/src/engine/flush_tes ## Gotchas +- Parquet row groups have uniform row counts except for the final group + (`sst/parquet/row_selection.rs`). Memory-pressure flushing must not create + arbitrary partial groups: readers and index row IDs rely on this layout. - Sequence numbers are strictly increasing per region; dedup and snapshot reads depend on this. Do not change assignment lightly. - Manifest version is monotonic — never reset or skip it. +- In regions whose writes require a lease and whose WAL is the object store WAL, + each manifest version has one fixed object name and only one writer can create + it (`manifest/storage.rs`). - Lock ordering: take the manifest lock before updating `version_control`; the reverse deadlocks against concurrent flush/compaction. - All region I/O runs on tokio workers; never `block_on` inside a worker. - Loaded regions have resident compaction state, including `Idle` and handed-off DDLs. Publish create/open/catchup results through the worker's `register_region`; only close/drop unregisters them. See `compaction/scheduler/state.rs`. +- Explicit truncate retires shared references too (`worker/handle_truncate.rs`): + `All` removes all data; `ByTimeRanges` removes fully contained files. Other + regions/readers still protect the shared objects. Stale compaction results must + not reinstate truncated inputs. - Local compaction units use the snapshot-free `CompactionContext`. Retaining a full `CompactionRegion` in a unit pins other units' inputs and delays SST purge. - Candidate waiting history is owned by the region scheduler (`scheduler/history.rs`). @@ -104,9 +130,16 @@ Tests live next to the code as `*_test.rs` (e.g. `src/mito2/src/engine/flush_tes resident history, and an accepted plan consumes the fairness turn for each selected key. Execution success or failure must not rewrite waiting ages. TWCS discovery must not mutate scheduler state. +- Compaction admission is engine-wide (`compaction/scheduler/coordinator.rs`), + but pick/DDL state remains worker-owned. Repick only after every batch unit's + `Released`; FIFO submission is not admission and pipeline children share the + parent unit's slot. Keep service accounting across batches until region unload. - In flat batches, equal `__primary_key` dictionary keys imply the same series, but not the reverse: `wrap_pk_binary_to_dict` gives every row its own key. Compare key bytes when grouping rows by series. +- Staging regions never flush: a flush would move rows into the staging manifest and + release their WAL, losing them if staging does not end successfully. Every flush + trigger in `worker/handle_flush.rs` must skip them, and `handle_close` leaves staging first. ## Maintenance contract diff --git a/src/mito2/Cargo.toml b/src/mito2/Cargo.toml index 411cf643145..5265554728d 100644 --- a/src/mito2/Cargo.toml +++ b/src/mito2/Cargo.toml @@ -9,7 +9,7 @@ default = [] test = ["common-test-util", "rstest", "rstest_reuse", "rskafka"] testing = ["test"] test-shared-fs-region-migration = [] -enterprise = [] +enterprise = ["datatypes/enterprise", "tokio-util/rt"] hdfs-object-store = ["object-store/hdfs-object-store"] [lints] diff --git a/src/mito2/src/access_layer.rs b/src/mito2/src/access_layer.rs index c5557d81e20..55e564fb4e7 100644 --- a/src/mito2/src/access_layer.rs +++ b/src/mito2/src/access_layer.rs @@ -46,6 +46,7 @@ use crate::region::options::IndexOptions; use crate::sst::file::{FileHandle, RegionFileId, RegionIndexId}; use crate::sst::index::intermediate::IntermediateManager; use crate::sst::index::puffin_manager::{PuffinManagerFactory, SstPuffinManager}; +use crate::sst::index::registry::IndexRegistry; use crate::sst::index::{IndexerBuilderImpl, build_index_from_parquet_bytes}; use crate::sst::location::{self, region_dir_from_table_dir}; use crate::sst::parquet::reader::ParquetReaderBuilder; @@ -157,6 +158,7 @@ pub struct AccessLayer { puffin_manager_factory: PuffinManagerFactory, /// Intermediate manager for inverted index. intermediate_manager: IntermediateManager, + file_protection: Option, } impl std::fmt::Debug for AccessLayer { @@ -182,6 +184,26 @@ impl AccessLayer { object_store, puffin_manager_factory, intermediate_manager, + file_protection: None, + } + } + + /// Attaches the engine's deletion-time protection provider for local purging. + pub(crate) fn with_file_protection( + mut self, + hook: Option, + ) -> Self { + self.file_protection = hook; + self + } + + pub(crate) async fn is_file_protected(&self, file: RegionFileId) -> crate::error::Result { + match &self.file_protection { + Some(hook) => Ok(hook + .protected_sst_files(self, &[file]) + .await? + .contains(&file)), + None => Ok(false), } } @@ -349,6 +371,36 @@ impl AccessLayer { write_opts: &WriteOptions, metrics: &mut Metrics, ) -> Result { + self.write_sst_inner(request, write_opts, metrics, None) + .await + } + + /// Writes an SST whose output is registered with `context.guard`. + /// + /// The write cache is bypassed, upload concurrency is fixed to one, and + /// the guard runs before either the SST or its index becomes visible. + /// `context.limits` bounds the encoder and footer workspace. + #[cfg(feature = "enterprise")] + pub(crate) async fn write_sst_with_guard( + &self, + request: SstWriteRequest, + write_opts: &WriteOptions, + metrics: &mut Metrics, + context: crate::sst::parquet::writer::SstWriteContext, + ) -> Result { + self.write_sst_inner(request, write_opts, metrics, Some(context)) + .await + } + + async fn write_sst_inner( + &self, + request: SstWriteRequest, + write_opts: &WriteOptions, + metrics: &mut Metrics, + context: Option, + ) -> Result { + let limits = context.as_ref().map(|context| context.limits); + let guard = context.map(|context| context.guard); let op_type = request.op_type; let region_id = request.metadata.region_id; let region_metadata = request.metadata.clone(); @@ -359,7 +411,9 @@ impl AccessLayer { request.max_sequence }; - let sst_info = if let Some(write_cache) = cache_manager.write_cache() { + let sst_info = if let Some(write_cache) = cache_manager.write_cache() + && guard.is_none() + { // Write to the write cache. write_cache .write_and_upload_sst( @@ -376,21 +430,28 @@ impl AccessLayer { ) .await? } else { - // Write cache is disabled. + // Write cache is disabled, or bypassed by an SST write guard. let store = self.object_store.clone(); let path_provider = RegionFilePathFactory::new(self.table_dir.clone(), self.path_type); + let puffin_factory = if limits.is_some() { + self.puffin_manager_factory + .clone() + .with_write_buffer_size(write_opts.write_buffer_size.as_bytes() as usize) + } else { + self.puffin_manager_factory.clone() + }; let indexer_builder = IndexerBuilderImpl { build_type: request.op_type.into(), metadata: request.metadata.clone(), - puffin_manager: self - .puffin_manager_factory - .build(store, path_provider.clone()), + puffin_manager: puffin_factory.build(store, path_provider.clone()), write_cache_enabled: false, intermediate_manager: self.intermediate_manager.clone(), index_options: request.index_options, - inverted_index_config: request.inverted_index_config, - fulltext_index_config: request.fulltext_index_config, - bloom_filter_index_config: request.bloom_filter_index_config, + registry: Arc::new(IndexRegistry::new( + request.inverted_index_config, + request.fulltext_index_config, + request.bloom_filter_index_config, + )), }; // We disable write cache on file system but we still use atomic write. // TODO(yingwen): If we support other non-fs stores without the write cache, then @@ -405,7 +466,14 @@ impl AccessLayer { metrics, ) .await - .with_file_cleaner(cleaner); + .with_file_cleaner(cleaner) + .with_write_concurrency(if guard.is_some() { + 1 + } else { + crate::sst::DEFAULT_WRITE_CONCURRENCY + }) + .with_write_guard(guard) + .with_memory_limits(limits); match request.sst_write_format { FormatType::PrimaryKey => { writer @@ -645,9 +713,11 @@ impl EncodedSstIndexBuildParams { write_cache_enabled, intermediate_manager, index_options: self.index_options, - inverted_index_config: self.inverted_index_config, - fulltext_index_config: self.fulltext_index_config, - bloom_filter_index_config: self.bloom_filter_index_config, + registry: Arc::new(IndexRegistry::new( + self.inverted_index_config, + self.fulltext_index_config, + self.bloom_filter_index_config, + )), } } } diff --git a/src/mito2/src/cache.rs b/src/mito2/src/cache.rs index ab1c49e74f4..aa7a0e56603 100644 --- a/src/mito2/src/cache.rs +++ b/src/mito2/src/cache.rs @@ -1456,7 +1456,10 @@ impl CacheManager { } if let Some(cache) = &self.puffin_metadata_cache { - cache.remove(&file_id.to_string()).await; + // Evict this exact generation across all storage scopes and paths. + if let Err(err) = cache.invalidate_file(&file_id.to_string()) { + warn!(err; "Failed to invalidate Puffin metadata, file_id: {file_id}"); + } } if let Some(write_cache) = &self.write_cache { @@ -3154,27 +3157,71 @@ mod tests { async fn test_evict_puffin_cache_clears_all_entries() { use std::collections::{BTreeMap, HashMap}; - let cache = CacheManager::builder() - .index_metadata_size(128) - .index_content_size(128) - .index_content_page_size(64) - .index_result_cache_size(128) - .puffin_metadata_size(128) - .build(); - let cache = Arc::new(cache); + use puffin::puffin_manager::file_key::{PuffinFileKey, PuffinStorageScope}; let region_id = RegionId::new(1, 1); let index_id = RegionIndexId::new(RegionFileId::new(region_id, FileId::random()), 0); + let file_key = PuffinFileKey::new( + Arc::new(PuffinStorageScope::new( + "memory".into(), + "cache-test".into(), + "/".into(), + )), + "table/index.puffin".into(), + index_id, + ); + let metadata_key = file_key.clone().map_handle(|id| id.to_string()); + let other_scope_key = PuffinFileKey::new( + Arc::new(PuffinStorageScope::new( + "memory".into(), + "other-store".into(), + "/".into(), + )), + "table/index.puffin".into(), + index_id.to_string(), + ); + let newer_metadata_key = file_key.clone().map_handle(|mut id| { + id.version += 1; + id.to_string() + }); let column_id: ColumnId = 1; + // Budget for the actual keys and empty values used below, including all + // three footer entries. Shared scopes are conservatively charged per key. + let index_metadata_size = file_key.estimated_size() + + ::index::target::IndexTarget::ColumnId(column_id).approx_mem_size() + + std::mem::size_of::() + + std::mem::size_of::() + + std::mem::size_of::(); + let puffin_metadata_size: usize = [&metadata_key, &other_scope_key, &newer_metadata_key] + .into_iter() + .map(|key| { + key.estimated_size() + + key.handle().capacity() + + FileMetadata { + blobs: Vec::new(), + properties: HashMap::new(), + } + .memory_usage() + }) + .sum(); + let cache = Arc::new( + CacheManager::builder() + .index_metadata_size(index_metadata_size as u64) + .index_content_size(128) + .index_content_page_size(64) + .index_result_cache_size(128) + .puffin_metadata_size(puffin_metadata_size as u64) + .build(), + ); + let bloom_cache = cache.bloom_filter_index_cache().unwrap().clone(); let inverted_cache = cache.inverted_index_cache().unwrap().clone(); let result_cache = cache.index_result_cache().unwrap(); let puffin_metadata_cache = cache.puffin_metadata_cache().unwrap().clone(); let bloom_key = ( - index_id.file_id(), - index_id.version, + file_key.clone(), Arc::new(::index::target::IndexTarget::ColumnId(column_id)), Tag::Skipping, ); @@ -3182,51 +3229,73 @@ mod tests { .put_metadata(bloom_key.clone(), Arc::new(BloomFilterMeta::default())) .await; inverted_cache - .put_metadata( - (index_id.file_id(), index_id.version), - Arc::new(InvertedIndexMetas::default()), - ) + .put_metadata(file_key.clone(), Arc::new(InvertedIndexMetas::default())) .await; let predicate = PredicateKey::new_bloom(Arc::new(BTreeMap::new())); let selection = Arc::new(RowGroupSelection::default()); result_cache.put(predicate.clone(), index_id.file_id(), selection); - let file_id_str = index_id.to_string(); let metadata = Arc::new(FileMetadata { blobs: Vec::new(), properties: HashMap::new(), }); puffin_metadata_cache - .put_metadata(file_id_str.clone(), metadata) + .put_metadata(metadata_key.clone(), metadata) .await; assert!(bloom_cache.get_metadata(bloom_key.clone()).await.is_some()); assert!( inverted_cache - .get_metadata((index_id.file_id(), index_id.version)) + .get_metadata(file_key.clone()) .await .is_some() ); assert!(result_cache.get(&predicate, index_id.file_id()).is_some()); assert!( puffin_metadata_cache - .get_metadata(&file_id_str) + .get_metadata(&metadata_key) .await .is_some() ); + // Retirement only has the immutable index handle, so matching scopes are + // all invalidated while a different generation remains available. + for key in [&other_scope_key, &newer_metadata_key] { + puffin_metadata_cache + .put_metadata( + key.clone(), + Arc::new(FileMetadata { + blobs: Vec::new(), + properties: HashMap::new(), + }), + ) + .await; + assert!(puffin_metadata_cache.get_metadata(key).await.is_some()); + } cache.evict_puffin_cache(index_id).await; + assert!( + puffin_metadata_cache + .get_metadata(&other_scope_key) + .await + .is_none() + ); + assert!( + puffin_metadata_cache + .get_metadata(&newer_metadata_key) + .await + .is_some() + ); assert!(bloom_cache.get_metadata(bloom_key.clone()).await.is_none()); assert!( inverted_cache - .get_metadata((index_id.file_id(), index_id.version)) + .get_metadata(file_key.clone()) .await .is_none() ); assert!(result_cache.get(&predicate, index_id.file_id()).is_none()); assert!( puffin_metadata_cache - .get_metadata(&file_id_str) + .get_metadata(&metadata_key) .await .is_none() ); @@ -3236,10 +3305,7 @@ mod tests { .put_metadata(bloom_key.clone(), Arc::new(BloomFilterMeta::default())) .await; inverted_cache - .put_metadata( - (index_id.file_id(), index_id.version), - Arc::new(InvertedIndexMetas::default()), - ) + .put_metadata(file_key.clone(), Arc::new(InvertedIndexMetas::default())) .await; result_cache.put( predicate.clone(), @@ -3248,7 +3314,7 @@ mod tests { ); puffin_metadata_cache .put_metadata( - file_id_str.clone(), + metadata_key.clone(), Arc::new(FileMetadata { blobs: Vec::new(), properties: HashMap::new(), @@ -3262,14 +3328,14 @@ mod tests { assert!(bloom_cache.get_metadata(bloom_key.clone()).await.is_none()); assert!( inverted_cache - .get_metadata((index_id.file_id(), index_id.version)) + .get_metadata(file_key.clone()) .await .is_none() ); assert!(result_cache.get(&predicate, index_id.file_id()).is_none()); assert!( puffin_metadata_cache - .get_metadata(&file_id_str) + .get_metadata(&metadata_key) .await .is_none() ); diff --git a/src/mito2/src/cache/index/bloom_filter_index.rs b/src/mito2/src/cache/index/bloom_filter_index.rs index 80f5148185d..d1626cc86e9 100644 --- a/src/mito2/src/cache/index/bloom_filter_index.rs +++ b/src/mito2/src/cache/index/bloom_filter_index.rs @@ -22,11 +22,13 @@ use bytes::Bytes; use index::bloom_filter::error::{Error, IoSnafu, Result, SharedReadSnafu}; use index::bloom_filter::reader::{BloomFilterReadMetrics, BloomFilterReader}; use index::target::IndexTarget; +use puffin::puffin_manager::file_key::PuffinFileKey; use snafu::IntoError; -use store_api::storage::{FileId, IndexVersion}; +use store_api::storage::FileId; use crate::cache::index::{INDEX_METADATA_TYPE, IndexCache}; use crate::metrics::{CACHE_HIT, CACHE_MISS}; +use crate::sst::file::RegionIndexId; const INDEX_TYPE_BLOOM_FILTER_INDEX: &str = "bloom_filter_index"; @@ -37,7 +39,7 @@ pub enum Tag { Fulltext, } -pub type BloomFilterIndexKey = (FileId, IndexVersion, Arc, Tag); +pub type BloomFilterIndexKey = (PuffinFileKey, Arc, Tag); /// Cache for bloom filter index. pub type BloomFilterIndexCache = IndexCache; @@ -59,15 +61,14 @@ impl BloomFilterIndexCache { /// Removes all cached entries for the given `file_id`. pub fn invalidate_file(&self, file_id: FileId) { - self.invalidate_if(move |key| key.0 == file_id); + self.invalidate_if(move |key| key.0.handle().file_id() == file_id); } } /// Calculates weight for bloom filter index metadata. fn bloom_filter_index_metadata_weight(k: &BloomFilterIndexKey, meta: &Arc) -> u32 { - let base = k.0.as_bytes().len() - + std::mem::size_of::() - + k.2.approx_mem_size() + let base = k.0.estimated_size() + + k.1.approx_mem_size() + std::mem::size_of::() + std::mem::size_of::(); @@ -79,13 +80,12 @@ fn bloom_filter_index_metadata_weight(k: &BloomFilterIndexKey, meta: &Arc u32 { - (k.0.as_bytes().len() + k.2.approx_mem_size() + v.len()) as u32 + (k.0.estimated_size() + k.1.approx_mem_size() + v.len()) as u32 } /// Bloom filter index blob reader with cache. pub struct CachedBloomFilterIndexBlobReader { - file_id: FileId, - index_version: IndexVersion, + file_key: PuffinFileKey, target: Arc, tag: Tag, blob_size: u64, @@ -96,8 +96,7 @@ pub struct CachedBloomFilterIndexBlobReader { impl CachedBloomFilterIndexBlobReader { /// Creates a new bloom filter index blob reader with cache. pub fn new( - file_id: FileId, - index_version: IndexVersion, + file_key: PuffinFileKey, target: IndexTarget, tag: Tag, blob_size: u64, @@ -105,8 +104,7 @@ impl CachedBloomFilterIndexBlobReader { cache: BloomFilterIndexCacheRef, ) -> Self { Self { - file_id, - index_version, + file_key, target: Arc::new(target), tag, blob_size, @@ -129,12 +127,7 @@ impl BloomFilterReader for CachedBloomFilterIndexBl let (result, cache_metrics) = self .cache .get_or_load( - ( - self.file_id, - self.index_version, - self.target.clone(), - self.tag, - ), + (self.file_key.clone(), self.target.clone(), self.tag), self.blob_size, offset, size, @@ -167,12 +160,7 @@ impl BloomFilterReader for CachedBloomFilterIndexBl let (pages, total_cache_metrics) = self .cache .get_or_load_vec( - ( - self.file_id, - self.index_version, - self.target.clone(), - self.tag, - ), + (self.file_key.clone(), self.target.clone(), self.tag), self.blob_size, ranges, move |ranges| async move { inner.read_vec(&ranges, None).await }, @@ -197,12 +185,7 @@ impl BloomFilterReader for CachedBloomFilterIndexBl &self, metrics: Option<&mut BloomFilterReadMetrics>, ) -> Result> { - let key = ( - self.file_id, - self.index_version, - self.target.clone(), - self.tag, - ); + let key = (self.file_key.clone(), self.target.clone(), self.tag); if let Some(cached) = self.cache.get_metadata(key.clone()).await { CACHE_HIT.with_label_values(&[INDEX_METADATA_TYPE]).inc(); if let Some(m) = metrics { @@ -251,10 +234,107 @@ fn map_page_error(error: Arc) -> Error { #[cfg(test)] mod test { + use puffin::puffin_manager::file_key::PuffinStorageScope; use rand::{Rng, RngCore}; use store_api::storage::ColumnId; + use store_api::storage::{IndexVersion, RegionId}; use super::*; + use crate::sst::file::RegionFileId; + + fn file_key(file_id: FileId, version: IndexVersion) -> PuffinFileKey { + PuffinFileKey::new( + Arc::new(PuffinStorageScope::new( + "memory".into(), + "test".into(), + "/".into(), + )), + format!("{file_id}.{version}.puffin"), + RegionIndexId::new(RegionFileId::new(RegionId::new(1, 1), file_id), version), + ) + } + + #[tokio::test] + async fn test_cache_keys_isolate_storage_and_generation() { + let cache = BloomFilterIndexCache::new(1024 * 1024, 1024 * 1024, 1024); + let file_id = FileId::random(); + let original = file_key(file_id, 0); + let keys = [ + original.clone(), + file_key(file_id, 1), + PuffinFileKey::new( + Arc::new(PuffinStorageScope::new( + "memory".into(), + "other".into(), + "/".into(), + )), + format!("{file_id}.0.puffin"), + *original.handle(), + ), + PuffinFileKey::new( + Arc::new(PuffinStorageScope::new( + "memory".into(), + "test".into(), + "/".into(), + )), + format!("other/{file_id}.0.puffin"), + *original.handle(), + ), + ]; + let keys = keys.map(|key| (key, Arc::new(IndexTarget::ColumnId(1)), Tag::Skipping)); + let metas: Vec<_> = keys + .iter() + .map(|_| Arc::new(BloomFilterMeta::default())) + .collect(); + for (i, key) in keys.iter().enumerate() { + assert!(cache.get_metadata(key.clone()).await.is_none()); + cache.put_metadata(key.clone(), metas[i].clone()).await; + let (bytes, metrics) = cache + .get_or_load(key.clone(), 1, 0, 1, |_| async move { + Ok::<_, std::io::Error>(vec![bytes::Bytes::from(vec![i as u8])]) + }) + .await + .unwrap(); + assert_eq!(bytes.as_ref(), &[i as u8]); + assert_eq!(metrics.cache_miss, 1); + } + let reconstructed = ( + file_key(file_id, 0), + Arc::new(IndexTarget::ColumnId(1)), + Tag::Skipping, + ); + assert!(Arc::ptr_eq( + &cache.get_metadata(reconstructed).await.unwrap(), + &metas[0] + )); + for (i, key) in keys.iter().enumerate() { + assert!(Arc::ptr_eq( + &cache.get_metadata(key.clone()).await.unwrap(), + &metas[i] + )); + let (bytes, metrics) = cache + .get_or_load(key.clone(), 1, 0, 1, |_| async { + Err::, _>(std::io::Error::other( + "cached page must not reload", + )) + }) + .await + .unwrap(); + assert_eq!(bytes.as_ref(), &[i as u8]); + assert_eq!(metrics.cache_hit, 1); + } + cache.invalidate_file(file_id); + for key in keys { + assert!(cache.get_metadata(key.clone()).await.is_none()); + let (_, metrics) = cache + .get_or_load(key, 1, 0, 1, |_| async { + Ok::<_, std::io::Error>(vec![bytes::Bytes::from_static(&[42])]) + }) + .await + .unwrap(); + assert_eq!(metrics.cache_miss, 1); + } + } const FUZZ_REPEAT_TIMES: usize = 100; @@ -305,8 +385,7 @@ mod test { for fail in [false, true] { let cache = Arc::new(BloomFilterIndexCache::new(4096, 4096, 1024)); let reader = CachedBloomFilterIndexBlobReader::new( - FileId::random(), - 0, + file_key(FileId::random(), 0), IndexTarget::ColumnId(42), Tag::Skipping, 8192, @@ -364,14 +443,12 @@ mod test { let cache = BloomFilterIndexCache::new(1024 * 1024, 1024 * 1024, 1024); let file_id = FileId::random(); let first = ( - file_id, - 0, + file_key(file_id, 0), Arc::new(IndexTarget::new_json_path(1, vec!["a".into(), "b".into()]).unwrap()), Tag::Skipping, ); let second = ( - file_id, - 0, + file_key(file_id, 0), Arc::new(IndexTarget::new_json_path(1, vec!["a.b".into()]).unwrap()), Tag::Skipping, ); @@ -435,16 +512,14 @@ mod test { let weight = bloom_filter_index_metadata_weight( &( - file_id, - version, + file_key(file_id, version), Arc::new(IndexTarget::ColumnId(column_id)), tag, ), &Arc::new(meta.clone()), ); - let base = file_id.as_bytes().len() - + std::mem::size_of::() + let base = file_key(file_id, version).estimated_size() + std::mem::size_of::() + std::mem::size_of::() + std::mem::size_of::(); diff --git a/src/mito2/src/cache/index/inverted_index.rs b/src/mito2/src/cache/index/inverted_index.rs index 34b44e571bb..76f1f82762b 100644 --- a/src/mito2/src/cache/index/inverted_index.rs +++ b/src/mito2/src/cache/index/inverted_index.rs @@ -22,16 +22,18 @@ use bytes::Bytes; use index::inverted_index::error::{CommonIoSnafu, Error, Result, SharedReadSnafu}; use index::inverted_index::format::reader::{InvertedIndexReadMetrics, InvertedIndexReader}; use prost::Message; +use puffin::puffin_manager::file_key::PuffinFileKey; use snafu::IntoError; -use store_api::storage::{FileId, IndexVersion}; +use store_api::storage::FileId; use crate::cache::index::{INDEX_METADATA_TYPE, IndexCache}; use crate::metrics::{CACHE_HIT, CACHE_MISS}; +use crate::sst::file::RegionIndexId; const INDEX_TYPE_INVERTED_INDEX: &str = "inverted_index"; /// Cache for inverted index. -pub type InvertedIndexCache = IndexCache<(FileId, IndexVersion), InvertedIndexMetas>; +pub type InvertedIndexCache = IndexCache, InvertedIndexMetas>; pub type InvertedIndexCacheRef = Arc; impl InvertedIndexCache { @@ -50,24 +52,26 @@ impl InvertedIndexCache { /// Removes all cached entries for the given `file_id`. pub fn invalidate_file(&self, file_id: FileId) { - self.invalidate_if(move |key| key.0 == file_id); + self.invalidate_if(move |key| key.handle().file_id() == file_id); } } /// Calculates weight for inverted index metadata. -fn inverted_index_metadata_weight(k: &(FileId, IndexVersion), v: &Arc) -> u32 { - (k.0.as_bytes().len() + size_of::() + v.encoded_len()) as u32 +fn inverted_index_metadata_weight( + k: &PuffinFileKey, + v: &Arc, +) -> u32 { + (k.estimated_size() + v.encoded_len()) as u32 } /// Calculates weight for inverted index content. -fn inverted_index_content_weight((k, _): &((FileId, IndexVersion), u64), v: &Bytes) -> u32 { - (k.0.as_bytes().len() + size_of::() + v.len()) as u32 +fn inverted_index_content_weight((k, _): &(PuffinFileKey, u64), v: &Bytes) -> u32 { + (k.estimated_size() + v.len()) as u32 } /// Inverted index blob reader with cache. pub struct CachedInvertedIndexBlobReader { - file_id: FileId, - index_version: IndexVersion, + file_key: PuffinFileKey, blob_size: u64, inner: R, cache: InvertedIndexCacheRef, @@ -76,15 +80,13 @@ pub struct CachedInvertedIndexBlobReader { impl CachedInvertedIndexBlobReader { /// Creates a new inverted index blob reader with cache. pub fn new( - file_id: FileId, - index_version: IndexVersion, + file_key: PuffinFileKey, blob_size: u64, inner: R, cache: InvertedIndexCacheRef, ) -> Self { Self { - file_id, - index_version, + file_key, blob_size, inner, cache, @@ -106,7 +108,7 @@ impl InvertedIndexReader for CachedInvertedIndexBlobRead let (result, cache_metrics) = self .cache .get_or_load( - (self.file_id, self.index_version), + self.file_key.clone(), self.blob_size, offset, size, @@ -137,7 +139,7 @@ impl InvertedIndexReader for CachedInvertedIndexBlobRead let (pages, total_cache_metrics) = self .cache .get_or_load_vec( - (self.file_id, self.index_version), + self.file_key.clone(), self.blob_size, ranges, move |ranges| async move { inner.read_vec(&ranges, None).await }, @@ -159,8 +161,8 @@ impl InvertedIndexReader for CachedInvertedIndexBlobRead &self, metrics: Option<&'a mut InvertedIndexReadMetrics>, ) -> Result> { - let key = (self.file_id, self.index_version); - if let Some(cached) = self.cache.get_metadata(key).await { + let key = self.file_key.clone(); + if let Some(cached) = self.cache.get_metadata(key.clone()).await { CACHE_HIT.with_label_values(&[INDEX_METADATA_TYPE]).inc(); if let Some(m) = metrics { m.cache_hit += 1; @@ -216,12 +218,105 @@ mod test { use index::inverted_index::format::reader::{InvertedIndexBlobReader, InvertedIndexReader}; use index::inverted_index::format::writer::{InvertedIndexBlobWriter, InvertedIndexWriter}; use prometheus::register_int_counter_vec; + use puffin::puffin_manager::file_key::PuffinStorageScope; use rand::{Rng, RngCore}; + use store_api::storage::{IndexVersion, RegionId}; use super::*; + use crate::sst::file::RegionFileId; use crate::sst::index::store::InstrumentedStore; use crate::test_util::TestEnv; + fn file_key(file_id: FileId, version: IndexVersion) -> PuffinFileKey { + PuffinFileKey::new( + Arc::new(PuffinStorageScope::new( + "memory".into(), + "test".into(), + "/".into(), + )), + format!("{file_id}.{version}.puffin"), + RegionIndexId::new(RegionFileId::new(RegionId::new(1, 1), file_id), version), + ) + } + + #[tokio::test] + async fn test_cache_keys_isolate_storage_and_generation() { + let cache = InvertedIndexCache::new(1024 * 1024, 1024 * 1024, 1024); + let file_id = FileId::random(); + let original = file_key(file_id, 0); + let keys = [ + original.clone(), + file_key(file_id, 1), + PuffinFileKey::new( + Arc::new(PuffinStorageScope::new( + "memory".into(), + "other".into(), + "/".into(), + )), + format!("{file_id}.0.puffin"), + *original.handle(), + ), + PuffinFileKey::new( + Arc::new(PuffinStorageScope::new( + "memory".into(), + "test".into(), + "/".into(), + )), + format!("other/{file_id}.0.puffin"), + *original.handle(), + ), + ]; + + let metas: Vec<_> = keys + .iter() + .map(|_| Arc::new(InvertedIndexMetas::default())) + .collect(); + for (i, key) in keys.iter().enumerate() { + assert!(cache.get_metadata(key.clone()).await.is_none()); + cache.put_metadata(key.clone(), metas[i].clone()).await; + let (bytes, metrics) = cache + .get_or_load(key.clone(), 1, 0, 1, |_| async move { + Ok::<_, std::io::Error>(vec![bytes::Bytes::from(vec![i as u8])]) + }) + .await + .unwrap(); + assert_eq!(bytes.as_ref(), &[i as u8]); + assert_eq!(metrics.cache_miss, 1); + } + let reconstructed = file_key(file_id, 0); + assert!(Arc::ptr_eq( + &cache.get_metadata(reconstructed).await.unwrap(), + &metas[0] + )); + for (i, key) in keys.iter().enumerate() { + assert!(Arc::ptr_eq( + &cache.get_metadata(key.clone()).await.unwrap(), + &metas[i] + )); + let (bytes, metrics) = cache + .get_or_load(key.clone(), 1, 0, 1, |_| async { + Err::, _>(std::io::Error::other( + "cached page must not reload", + )) + }) + .await + .unwrap(); + assert_eq!(bytes.as_ref(), &[i as u8]); + assert_eq!(metrics.cache_hit, 1); + } + cache.invalidate_file(file_id); + for key in keys { + assert!(cache.get_metadata(key.clone()).await.is_none()); + let (_, metrics) = cache + .get_or_load(key, 1, 0, 1, |_| async { + Ok::<_, std::io::Error>(vec![bytes::Bytes::from_static(&[42])]) + }) + .await + .unwrap(); + assert_eq!(metrics.cache_miss, 1); + } + } + // Repeat times for following little fuzz tests. const FUZZ_REPEAT_TIMES: usize = 100; @@ -272,8 +367,7 @@ mod test { for fail in [false, true] { let cache = Arc::new(InvertedIndexCache::new(4096, 4096, 1024)); let reader = CachedInvertedIndexBlobReader::new( - FileId::random(), - 0, + file_key(FileId::random(), 0), 8192, MetadataReader { release: tokio::sync::Notify::new(), @@ -434,8 +528,7 @@ mod test { let reader = InvertedIndexBlobReader::new(range_reader); let cached_reader = CachedInvertedIndexBlobReader::new( - FileId::random(), - index_version, + file_key(FileId::random(), index_version), file_size, reader, Arc::new(InvertedIndexCache::new(8192, 8192, 50)), @@ -572,7 +665,7 @@ mod test { let (read, _cache_metrics) = cached_reader .cache .get_or_load( - (cached_reader.file_id, cached_reader.index_version), + cached_reader.file_key.clone(), file_size, offset, size, @@ -593,10 +686,10 @@ mod test { rng.fill_bytes(&mut data); let file_size = data.len() as u64; let cache = InvertedIndexCache::new(1024 * 1024, 1024 * 1024, 1000); - let key = (FileId::random(), 0); + let key = file_key(FileId::random(), 0); for _ in 0..FUZZ_REPEAT_TIMES { - cache.invalidate_file(key.0); + cache.invalidate_file(key.handle().file_id()); let ranges = (0..rng.random_range(1..20)) .map(|_| { let start = rng.random_range(0..file_size); @@ -631,7 +724,7 @@ mod test { } }; let (cold, cold_metrics) = cache - .get_or_load_vec(key, file_size, &ranges, load) + .get_or_load_vec(key.clone(), file_size, &ranges, load) .await .unwrap(); assert_eq!(cold, expected); @@ -646,7 +739,7 @@ mod test { ); let (warm, metrics) = cache - .get_or_load_vec(key, file_size, &ranges, load) + .get_or_load_vec(key.clone(), file_size, &ranges, load) .await .unwrap(); assert_eq!(warm, expected); diff --git a/src/mito2/src/cache/index/result_cache.rs b/src/mito2/src/cache/index/result_cache.rs index 75dd9794ef2..982aa4ece71 100644 --- a/src/mito2/src/cache/index/result_cache.rs +++ b/src/mito2/src/cache/index/result_cache.rs @@ -20,7 +20,7 @@ use index::inverted_index::search::predicate::{Predicate, RangePredicate}; use index::target::IndexTarget; use moka::notification::RemovalCause; use moka::sync::Cache; -use store_api::storage::{ColumnId, FileId}; +use store_api::storage::FileId; use crate::metrics::{CACHE_BYTES, CACHE_EVICTION, CACHE_HIT, CACHE_MISS}; use crate::sst::index::fulltext_index::applier::builder::{ @@ -123,7 +123,7 @@ pub enum PredicateKey { impl PredicateKey { /// Creates a new fulltext index key. - pub fn new_fulltext(predicates: Arc>) -> Self { + pub fn new_fulltext(predicates: Arc>) -> Self { Self::Fulltext(FulltextIndexKey::new(predicates)) } @@ -156,17 +156,18 @@ impl PredicateKey { /// Key for fulltext index queries. #[derive(Debug, Clone, PartialEq, Eq, Hash, Default)] pub struct FulltextIndexKey { - predicates: Arc>, + predicates: Arc>, mem_usage: usize, } impl FulltextIndexKey { /// Creates a new fulltext index key with the given predicates. /// Calculates memory usage based on the size of queries and terms. - pub fn new(predicates: Arc>) -> Self { + pub fn new(predicates: Arc>) -> Self { let mem_usage = predicates - .values() - .map(|request| { + .iter() + .map(|(target, request)| { + let target_size = target.approx_mem_size(); let query_size = request .queries .iter() @@ -182,7 +183,7 @@ impl FulltextIndexKey { .iter() .map(|like| like.pattern.len() + size_of::()) .sum::(); - query_size + term_size + like_size + target_size + query_size + term_size + like_size }) .sum(); Self { @@ -377,7 +378,7 @@ mod tests { terms: vec![], likes: vec![], }; - predicates1.insert(1, request1); + predicates1.insert(IndexTarget::ColumnId(1), request1); let key1 = PredicateKey::new_fulltext(Arc::new(predicates1)); let selection1 = Arc::new(RowGroupSelection::default()); @@ -392,7 +393,7 @@ mod tests { terms: vec![], likes: vec![], }; - predicates2.insert(1, request2); + predicates2.insert(IndexTarget::ColumnId(1), request2); let key2 = PredicateKey::new_fulltext(Arc::new(predicates2)); let selection2 = Arc::new(RowGroupSelection::default()); @@ -463,7 +464,7 @@ mod tests { }], likes: vec![], }; - predicates1.insert(1, request1); + predicates1.insert(IndexTarget::ColumnId(1), request1); let key1 = PredicateKey::new_fulltext(Arc::new(predicates1)); let selection1 = Arc::new(RowGroupSelection::new(100, 250)); let weight1 = diff --git a/src/mito2/src/cache/manifest_cache.rs b/src/mito2/src/cache/manifest_cache.rs index f57cc3c06d0..b9acebaa88d 100644 --- a/src/mito2/src/cache/manifest_cache.rs +++ b/src/mito2/src/cache/manifest_cache.rs @@ -237,7 +237,7 @@ impl ManifestCache { join_path(MANIFEST_DIR, key) } - /// Gets a manifest file from cache. + /// Gets the encoded object-store payload from cache. /// Returns the file data if found in cache, None otherwise. pub(crate) async fn get_file(&self, key: &str) -> Option> { if self.get(key).await.is_none() { @@ -259,7 +259,7 @@ impl ManifestCache { } } - /// Puts a manifest file into cache. + /// Caches the object-store payload verbatim, before decompression. pub(crate) async fn put_file(&self, key: String, data: Vec) { let cache_file_path = self.cache_file_path(&key); diff --git a/src/mito2/src/cache/write_cache.rs b/src/mito2/src/cache/write_cache.rs index 24e2e957219..534f0a8c076 100644 --- a/src/mito2/src/cache/write_cache.rs +++ b/src/mito2/src/cache/write_cache.rs @@ -38,6 +38,7 @@ use crate::region::opener::RegionLoadCacheTask; use crate::sst::file::RegionFileId; use crate::sst::index::intermediate::IntermediateManager; use crate::sst::index::puffin_manager::{PuffinManagerFactory, SstPuffinManager}; +use crate::sst::index::registry::IndexRegistry; use crate::sst::index::{IndexerBuilderImpl, build_index_from_parquet_bytes}; use crate::sst::parquet::writer::ParquetWriter; use crate::sst::parquet::{SstInfo, WriteOptions}; @@ -308,9 +309,11 @@ impl WriteCache { write_cache_enabled: true, intermediate_manager: self.intermediate_manager.clone(), index_options: write_request.index_options, - inverted_index_config: write_request.inverted_index_config, - fulltext_index_config: write_request.fulltext_index_config, - bloom_filter_index_config: write_request.bloom_filter_index_config, + registry: Arc::new(IndexRegistry::new( + write_request.inverted_index_config, + write_request.fulltext_index_config, + write_request.bloom_filter_index_config, + )), }; let cleaner = TempFileCleaner::new(region_id, store.clone()); diff --git a/src/mito2/src/compaction.rs b/src/mito2/src/compaction.rs index 0f1b637e096..4686e6c50b4 100644 --- a/src/mito2/src/compaction.rs +++ b/src/mito2/src/compaction.rs @@ -17,6 +17,8 @@ pub mod compactor; mod json2; mod last_non_null; pub mod memory_manager; +#[cfg(feature = "enterprise")] +pub mod multi_region; mod overlap; pub mod picker; mod reader; @@ -41,7 +43,8 @@ pub(crate) use json2::{ }; pub use scheduler::CompactionRequest; pub(crate) use scheduler::{ - CompactionExecution, CompactionPickFinished, CompactionScheduler, CompactionTransition, + CancelCompactionResult, CompactionCoordinator, CompactionExecution, CompactionPickFinished, + CompactionScheduler, CompactionState, CompactionStateRef, CompactionTransition, }; use serde::{Deserialize, Serialize}; use snafu::ResultExt; diff --git a/src/mito2/src/compaction/compactor.rs b/src/mito2/src/compaction/compactor.rs index 3c03b8567b2..d0d2950018b 100644 --- a/src/mito2/src/compaction/compactor.rs +++ b/src/mito2/src/compaction/compactor.rs @@ -26,7 +26,7 @@ use itertools::Itertools; use object_store::manager::ObjectStoreManagerRef; use partition::expr::PartitionExpr; use serde::{Deserialize, Serialize}; -use snafu::{OptionExt, ResultExt}; +use snafu::{OptionExt, ResultExt, ensure}; use store_api::ManifestVersion; use store_api::metadata::RegionMetadataRef; use store_api::region_request::PathType; @@ -53,7 +53,7 @@ use crate::region::version::VersionRef; use crate::region::{ManifestContext, RegionLeaderState, RegionRoleState}; use crate::schedule::scheduler::LocalScheduler; use crate::sst::FormatType; -use crate::sst::file::{FileHandle, FileMeta, UncommittedSsts}; +use crate::sst::file::{self, FileHandle, FileMeta, UncommittedSsts}; use crate::sst::file_purger::LocalFilePurger; use crate::sst::index::intermediate::IntermediateManager; use crate::sst::index::puffin_manager::PuffinManagerFactory; @@ -292,6 +292,7 @@ impl CompactionRegionOpener { manifest_manager, RegionRoleState::Leader(RegionLeaderState::Writable), hook, + Default::default(), )); let file_purger = { @@ -582,16 +583,24 @@ fn output_sequence_metadata( } /// Computes the maximum target-domain sequence bound of the output of merging -/// `inputs`. A bound can be a row maximum or an admission marker; compaction -/// must preserve both for sequence-based pruning. Unknown bounds must remain -/// unknown rather than being replaced with a partial maximum. +/// `inputs`. fn known_max_input_sequence(inputs: &[FileHandle]) -> Option { - let mut max: Option = None; - for input in inputs { - let sequence = input.meta_ref().sequence?; - max = Some(max.map_or(sequence, |current| current.max(sequence))); - } - max + crate::sst::file::known_max_input_sequence(inputs.iter().map(FileHandle::meta_ref)) +} + +fn validate_region_compaction_output(region_id: RegionId, output: &CompactionOutput) -> Result<()> { + ensure!( + output.output_level < file::LEVEL_SHARED + && output + .inputs + .iter() + .all(|file| file.level() < file::LEVEL_SHARED), + error::InvalidRequestSnafu { + region_id, + reason: "Region compaction cannot consume or produce shared SSTs", + } + ); + Ok(()) } #[async_trait::async_trait] @@ -603,6 +612,7 @@ impl SstMerger for DefaultSstMerger { write_opts: WriteOptions, ) -> Result<(Vec, Vec)> { let region_id = context.region_id; + validate_region_compaction_output(region_id, &output)?; let index_options = context.version_options.index_options.clone(); let append_mode = context.version_options.append_mode; let merge_mode = context.version_options.merge_mode(); @@ -689,7 +699,7 @@ impl SstMerger for DefaultSstMerger { None => (None, None), }; - FileMeta { + Ok(FileMeta { region_id, file_id: sst_info.file_id, time_range: sst_info.time_range, @@ -697,7 +707,7 @@ impl SstMerger for DefaultSstMerger { file_size: sst_info.file_size, max_row_group_uncompressed_size: sst_info.max_row_group_uncompressed_size, available_indexes: sst_info.index_metadata.build_available_indexes(), - indexes: sst_info.index_metadata.build_indexes(), + indexes: sst_info.index_metadata.build_indexes()?, index_file_size: sst_info.index_metadata.file_size, index_version: 0, num_rows: sst_info.num_rows as u64, @@ -708,9 +718,9 @@ impl SstMerger for DefaultSstMerger { primary_key_min, primary_key_max, preserve_row_sequence: sequence_metadata.exact_sequence_trusted, - } + }) }) - .collect::>(); + .collect::>>()?; let output_file_names = output_files.iter().map(|f| f.file_id.to_string()).join(","); info!( "Region {} compaction inputs: [{}], outputs: [{}], flat_format: {}, metrics: {:?}", @@ -834,6 +844,19 @@ where compaction_region: &CompactionRegion, mut picker_output: PickerOutput, ) -> Result { + for output in &picker_output.outputs { + validate_region_compaction_output(compaction_region.region_id, output)?; + } + ensure!( + picker_output + .expired_ssts + .iter() + .all(|file| file.level() < file::LEVEL_SHARED), + error::InvalidRequestSnafu { + region_id: compaction_region.region_id, + reason: "Region compaction cannot expire shared SSTs", + } + ); let internal_parallelism = compaction_region.max_parallelism.max(1); let compaction_time_window = picker_output.time_window_size; let region_id = compaction_region.region_id; diff --git a/src/mito2/src/compaction/json2.rs b/src/mito2/src/compaction/json2.rs index faa7eb6c434..cc73d93704d 100644 --- a/src/mito2/src/compaction/json2.rs +++ b/src/mito2/src/compaction/json2.rs @@ -284,6 +284,7 @@ fn select_dynamic_hints( data_type: ConcreteDataType::from_arrow_type(&stat.data_type.as_arrow_type()), inverted_index: false, skipping_index: None, + fulltext_index: None, }) .collect() } @@ -380,6 +381,7 @@ mod tests { data_type: ConcreteDataType::string_datatype(), inverted_index: false, skipping_index: None, + fulltext_index: None, }], Some(2), )?; @@ -437,6 +439,7 @@ mod tests { data_type: ConcreteDataType::string_datatype(), inverted_index: false, skipping_index: None, + fulltext_index: None, }], Some(0), )?; @@ -492,6 +495,7 @@ mod tests { data_type: ConcreteDataType::string_datatype(), inverted_index: false, skipping_index: None, + fulltext_index: None, }], Some(0), )?; @@ -513,12 +517,14 @@ mod tests { data_type: ConcreteDataType::string_datatype(), inverted_index: false, skipping_index: None, + fulltext_index: None, }, JsonTypeHint { path: vec!["source_only".to_string()], data_type: ConcreteDataType::int64_datatype(), inverted_index: false, skipping_index: None, + fulltext_index: None, }, ], None, @@ -586,6 +592,7 @@ mod tests { data_type: ConcreteDataType::string_datatype(), inverted_index: false, skipping_index: None, + fulltext_index: None, }], Some(0), )?; @@ -596,12 +603,14 @@ mod tests { data_type: ConcreteDataType::string_datatype(), inverted_index: false, skipping_index: None, + fulltext_index: None, }, JsonTypeHint { path: vec!["promoted".to_string()], data_type: ConcreteDataType::int64_datatype(), inverted_index: false, skipping_index: None, + fulltext_index: None, }, ], Some(0), diff --git a/src/mito2/src/compaction/last_non_null.rs b/src/mito2/src/compaction/last_non_null.rs index 1e4f8ba450d..5e6c2bb1102 100644 --- a/src/mito2/src/compaction/last_non_null.rs +++ b/src/mito2/src/compaction/last_non_null.rs @@ -24,7 +24,7 @@ use crate::compaction::overlap::FileOverlapIndex; use crate::compaction::picker::{Picker, PickerOutput}; use crate::compaction::twcs::TwcsPicker; use crate::error::{JoinSnafu, Result}; -use crate::sst::file::{FileHandle, RegionFileId}; +use crate::sst::file::{self, FileHandle, RegionFileId}; /// Picker for [`MergeMode::LastNonNull`](crate::region::options::MergeMode). /// @@ -167,7 +167,10 @@ fn build_closed_outputs( }; let output = expand_closure(output, &mut seeds, &seed_by_file, &mut remaining); // Defer the entire closure rather than truncate it around busy files. - if !output.inputs.iter().any(FileHandle::compacting) + if !output + .inputs + .iter() + .any(|file| file.compacting() || file.level() == file::LEVEL_SHARED) && inputs_precede_memtables(&output.inputs, limits.memtable_min_sequence) { outputs.push(output); diff --git a/src/mito2/src/compaction/multi_region.rs b/src/mito2/src/compaction/multi_region.rs new file mode 100644 index 00000000000..2fa6ab1b737 --- /dev/null +++ b/src/mito2/src/compaction/multi_region.rs @@ -0,0 +1,243 @@ +// 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. + +//! Lossless multi-region SST compaction using a captured table partition rule. +//! +//! The caller selects and pins the inputs (for example, from LEVEL_SHARED), and +//! supplies their effective metadata in every target. This primitive deliberately +//! does not select files, change existing persisted levels, publish manifests, or +//! fold row versions. Output protection and eventual publication belong to its +//! caller; see [MultiRegionCompactionOutput::files] for the output level convention. + +mod memory; +mod source; +#[cfg(test)] +mod tests; +mod worker; +mod writer; + +use std::collections::{BTreeMap, HashMap, HashSet}; +use std::sync::Arc; +use std::sync::atomic::AtomicU64; + +use common_base::cancellation::{CancellableFuture, CancellationHandle}; +use common_time::Timestamp; +use partition::PartitionRuleRef; +use snafu::{OptionExt, ensure}; +use store_api::metadata::RegionMetadataRef; +use store_api::storage::RegionId; + +use crate::access_layer::AccessLayerRef; +use crate::cache::CacheManagerRef; +use crate::config::MitoConfig; +use crate::error::{InvalidMultiRegionCompactionSnafu, Result}; +use crate::region::options::RegionOptions; +use crate::sst::file::{FileMeta, RegionFileId}; +use crate::sst::parquet::SstInfo; +use crate::sst::parquet::writer::SstWriteGuard; + +/// A target partition and the source versions currently visible in its sequence domain. +#[derive(Debug, Clone)] +pub struct MultiRegionTarget { + pub metadata: RegionMetadataRef, + pub options: RegionOptions, + /// All selected sources, with the sequence metadata used by this target's reader. + pub inputs: HashMap, +} + +/// Immutable inputs, routing snapshot and execution limits for one compaction. +pub struct MultiRegionCompactionPlan { + /// Captured table routing rule; the executor never fetches mutable routing metadata. + pub partition_rule: PartitionRuleRef, + /// Unique sources. The caller retains their GC protection. + pub sources: Vec, + /// Metadata and routing must belong to the same physical-table snapshot. + pub targets: BTreeMap, + /// Working-set admission budget, including all resident writers and their finish workspace. + /// This bounds managed buffers and estimates codec/index allocations, not process RSS. + /// It must be large enough that the per-buffer share still covers the storage + /// multipart minimum, otherwise the plan is rejected before any output. + pub memory_limit: usize, + /// Soft size limit, in bytes, of one output SST. A file rolls over at the next + /// series boundary after it is exceeded, so a single series may stay in one file. + pub max_output_file_size: usize, + /// Aligned start of the only task window, in seconds since the epoch. + pub window_start: i64, + /// Width of the only task window in seconds; the window is + /// `[window_start, window_start + window_seconds)`. + pub window_seconds: i64, +} + +/// Shared storage services and attempt-owned output resources. +pub struct MultiRegionCompactionContext { + pub access_layer: AccessLayerRef, + pub cache: CacheManagerRef, + pub config: Arc, + pub protection: Arc, + pub cancellation: Arc, +} + +/// Source I/O and lossless output accounting, excluding footer and query reads. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct MultiRegionCompactionStats { + pub source_files: u64, + pub source_rows: u64, + /// Row-group page bytes fetched from object storage, excluding footer traffic and retries. + pub source_store_page_bytes: u64, + pub output_rows: u64, + pub output_bytes: u64, + /// Conservative admission estimate, including reader pages, writers, indexes and finish. + pub estimated_memory_bytes: u64, + /// Peak retained equal-key group storage (including shared buffer capacities). + pub peak_group_bytes: u64, +} + +/// Complete per-target outputs, including explicit empty partitions. +pub struct MultiRegionCompactionOutput { + /// Output files, initially assigned to level 1 (L1). + /// + /// The caller owns publication and must set [FileMeta::level] before + /// publishing if its intended output level differs from L1. + pub files: BTreeMap>, + /// Complete footer/index statistics for target hook delivery; not fabricated from FileMeta. + pub sst_infos: BTreeMap>, + pub stats: MultiRegionCompactionStats, +} + +#[derive(Default)] +struct SourceCounters { + files: AtomicU64, + rows: AtomicU64, + store_page_bytes: AtomicU64, +} + +/// Computes a complete result or an error. Any already-written outputs remain +/// owned by the attempt's durable protection; this function never purges sources. +/// Outputs that legacy reading would reinterpret as newly admitted versions are rejected. +pub async fn compact_regions( + plan: MultiRegionCompactionPlan, + context: MultiRegionCompactionContext, +) -> Result { + let metadata = validate_plan(&plan)?; + if context.cancellation.is_cancelled() { + return crate::error::CompactionCancelledSnafu.fail(); + } + let cancellation = context.cancellation.clone(); + let execution = async move { + let counters = Arc::new(SourceCounters::default()); + let source = + source::SharedSource::build(&plan, &context, metadata, counters.clone()).await?; + worker::execute(plan, context, source, counters).await + }; + CancellableFuture::new(execution, cancellation) + .await + .map_err(|_| crate::error::CompactionCancelledSnafu.build())? +} + +fn validate_plan(plan: &MultiRegionCompactionPlan) -> Result { + ensure!( + !plan.sources.is_empty(), + InvalidMultiRegionCompactionSnafu { + reason: "sources must not be empty" + } + ); + ensure!( + plan.memory_limit >= 1024 * 1024, + InvalidMultiRegionCompactionSnafu { + reason: "memory_limit must be at least 1 MiB" + } + ); + ensure!( + plan.max_output_file_size > 0, + InvalidMultiRegionCompactionSnafu { + reason: "max_output_file_size must be greater than 0" + } + ); + ensure!( + plan.window_seconds > 0, + InvalidMultiRegionCompactionSnafu { + reason: "window_seconds must be greater than 0" + } + ); + let control_bytes = plan.targets.len().saturating_mul(8 * 1024).saturating_add( + plan.sources + .len() + .saturating_mul(std::mem::size_of::()), + ); + ensure!( + control_bytes <= plan.memory_limit, + crate::error::MultiRegionCompactionResourceSnafu { + reason: "Input/target control state exceeds the task budget", + } + ); + let first = plan + .targets + .values() + .next() + .context(InvalidMultiRegionCompactionSnafu { + reason: "No routing targets", + })?; + let window_end = plan.window_start.checked_add(plan.window_seconds).context( + InvalidMultiRegionCompactionSnafu { + reason: "Task window overflow", + }, + )?; + ensure!( + plan.window_start.rem_euclid(plan.window_seconds) == 0, + InvalidMultiRegionCompactionSnafu { + reason: "Task window start is not aligned" + } + ); + let start = Timestamp::new_second(plan.window_start); + let end = Timestamp::new_second(window_end); + let mut sources = HashSet::new(); + for file in &plan.sources { + ensure!( + file.time_range.0 >= start + && file.time_range.1 < end + && file.time_range.0 <= file.time_range.1, + InvalidMultiRegionCompactionSnafu { + reason: "Source is not wholly inside the task window" + } + ); + ensure!( + file.region_id.table_id() == first.metadata.region_id.table_id() + && sources.insert(file.file_id()), + InvalidMultiRegionCompactionSnafu { + reason: "Expected unique source files from one physical table" + } + ); + } + for (id, target) in &plan.targets { + target.options.validate()?; + ensure!( + *id == target.metadata.region_id + && id.table_id() == first.metadata.region_id.table_id() + && target.metadata.column_metadatas == first.metadata.column_metadatas + && target.metadata.primary_key == first.metadata.primary_key + && target.metadata.primary_key_encoding == first.metadata.primary_key_encoding, + InvalidMultiRegionCompactionSnafu { + reason: "Target schemas are not a consistent physical-table snapshot" + } + ); + ensure!( + target.inputs.len() == sources.len() + && target + .inputs + .iter() + .all(|(key, file)| *key == file.file_id() && sources.contains(key)), + InvalidMultiRegionCompactionSnafu { + reason: "Every target must describe the effective metadata of every selected source" + } + ); + } + Ok(first.metadata.clone()) +} diff --git a/src/mito2/src/compaction/multi_region/memory.rs b/src/mito2/src/compaction/multi_region/memory.rs new file mode 100644 index 00000000000..1bc774d7313 --- /dev/null +++ b/src/mito2/src/compaction/multi_region/memory.rs @@ -0,0 +1,221 @@ +// 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 std::sync::Arc; + +use api::v1::SemanticType; +use datatypes::arrow::datatypes::SchemaRef; +use datatypes::schema::{ColumnEncoding, FulltextBackend}; +use index::fulltext_index::create::TantivyFulltextIndexCreator; +use parquet::arrow::ArrowSchemaConverter; +use parquet::file::metadata::ParquetMetaData; +use snafu::{ResultExt, ensure}; + +use crate::compaction::multi_region::{ + MultiRegionCompactionContext, MultiRegionCompactionPlan, MultiRegionTarget, +}; +use crate::config::{FulltextIndexConfig, MitoConfig}; +use crate::error::{IndexOptionsSnafu, MultiRegionCompactionResourceSnafu, Result}; +use crate::sst::parquet::writer::SstWriteLimits; + +pub(crate) const BATCH_SIZE: usize = 64; +/// Cap on the rows of one output row group. +/// +/// Every resident target admits an encoder sized by this count, while readers +/// and index row ids only require uniform groups except for the last one. +/// Ordinary compaction forwards the region option uncapped; this executor caps +/// it so the working set stays inside the task budget. +pub(crate) const MAX_ROW_GROUP_SIZE: usize = 1024; + +/// Admission includes every resident writer, not just concurrently polled tasks. +/// Codec/index thresholds are estimates; Arrow batches and output metadata have +/// separate runtime checks. Neither estimate nor buffer accounting measures RSS. +#[derive(Clone)] +pub(crate) struct MemoryLimits { + pub(crate) batch: usize, + pub(crate) group: usize, + pub(crate) index: usize, + pub(crate) writer: SstWriteLimits, + pub(crate) estimated: u64, +} + +impl MemoryLimits { + pub(crate) fn new(plan: &MultiRegionCompactionPlan, schema: &SchemaRef) -> Result { + let schema = crate::sst::maybe_wrap_schema(schema)?; + let columns = ArrowSchemaConverter::new() + .convert(&schema) + .context(crate::error::WriteParquetSnafu)? + .num_columns(); + let batch = + plan.memory_limit / (64 * (plan.sources.len() + plan.targets.len() + BATCH_SIZE + 4)); + Ok(Self { + batch, + group: plan.memory_limit / 16, + index: plan.memory_limit / (64 * plan.targets.len()), + writer: SstWriteLimits { + // Parquet 59 preallocates a 1 MiB bit writer for each of the + // timestamp/sequence delta encoders. Dictionary interner tables + // also have a nonzero minimum, independent of batch row count. + working_bytes: 2 * 1024 * 1024 + + columns * 128 * 1024 + + batch * (MAX_ROW_GROUP_SIZE / BATCH_SIZE), + metadata_bytes: plan.memory_limit / (8 * plan.targets.len()), + }, + estimated: 0, + }) + } + + pub(crate) fn admit( + &mut self, + plan: &MultiRegionCompactionPlan, + context: &MultiRegionCompactionContext, + footers: &[Arc], + ) -> Result<()> { + self.check_upload_minimum(context)?; + let mut extra_delta = 0; + for target in plan.targets.values() { + extra_delta = extra_delta.max(extra_delta_encoder_bytes(target)?); + } + self.writer.working_bytes = self.writer.working_bytes.saturating_add(extra_delta); + // Merge assembly can retain exhausted batches until an output batch is full. + let mut bytes = 4_u64 + .saturating_mul((plan.sources.len() + BATCH_SIZE + 2) as u64) + .saturating_mul(self.batch as u64) + .saturating_add(6 * self.group as u64); + for footer in footers { + bytes = bytes.saturating_add(reader_bytes(footer)); + } + for target in plan.targets.values() { + bytes = bytes.saturating_add(self.target_bytes(target, &context.config)?); + } + ensure!( + bytes <= plan.memory_limit as u64, + MultiRegionCompactionResourceSnafu { + reason: format!( + "Reader/writer/index minimum working set needs {bytes} bytes, budget is {}", + plan.memory_limit + ), + } + ); + self.estimated = bytes; + Ok(()) + } + + fn check_upload_minimum(&self, context: &MultiRegionCompactionContext) -> Result<()> { + let minimum = context + .access_layer + .object_store() + .info() + .capability() + .write_multi_min_size + .unwrap_or(0); + ensure!( + self.batch >= minimum && self.batch > 0, + MultiRegionCompactionResourceSnafu { + reason: "Storage multipart minimum exceeds the task buffer budget", + } + ); + Ok(()) + } + + fn target_bytes(&self, target: &MultiRegionTarget, config: &MitoConfig) -> Result { + let schema_bytes = target + .metadata + .to_json() + .context(crate::error::InvalidMetadataSnafu)? + .len(); + // Task/channel allocation plus captured schema and input-map copies. + let control = 8 * 1024 + + 3 * schema_bytes + + 3 * target.inputs.len() * std::mem::size_of::(); + // Encoding/finish workspace, SST and index multipart buffers, result metadata. + let writer = self.writer.working_bytes * 2 + self.batch * 4 + self.writer.metadata_bytes; + // Creators are instantiated even in async-index mode. Inverted/skipping + // thresholds are shared within their indexers, fulltext is per column. + Ok((control as u64) + .saturating_add(writer as u64) + .saturating_add(4 * self.index as u64) + .saturating_add(self.fulltext_bytes(target, &config.fulltext_index)?)) + } + + fn fulltext_bytes( + &self, + target: &MultiRegionTarget, + config: &FulltextIndexConfig, + ) -> Result { + if config.create_on_compaction.disabled() { + return Ok(0); + } + let threshold = self.index.min(config.mem_threshold_on_create()); + let mut bytes = 0_u64; + for column in target + .metadata + .column_metadatas + .iter() + .filter(|column| column.semantic_type != SemanticType::Tag) + { + let Some(options) = column + .column_schema + .fulltext_options() + .context(IndexOptionsSnafu { + column_name: &column.column_schema.name, + })? + .filter(|options| options.enable) + else { + continue; + }; + let allocation = match options.backend { + FulltextBackend::Tantivy => { + TantivyFulltextIndexCreator::sanitize_memory_limit(threshold) + } + FulltextBackend::Bloom => threshold, + }; + bytes = bytes.saturating_add(2 * allocation as u64); + } + Ok(bytes) + } +} + +fn extra_delta_encoder_bytes(target: &MultiRegionTarget) -> Result { + let mut bytes = 0; + for column in target + .metadata + .column_metadatas + .iter() + .filter(|column| column.semantic_type != SemanticType::Timestamp) + { + if column + .column_schema + .compression_options() + .context(crate::error::CompressionOptionsSnafu { + column_name: &column.column_schema.name, + })? + .is_some_and(|options| options.encoding == Some(ColumnEncoding::DeltaBinaryPacked)) + { + bytes += 1024 * 1024; + } + } + Ok(bytes) +} + +fn reader_bytes(footer: &ParquetMetaData) -> u64 { + let pages = footer + .row_groups() + .iter() + .map(|group| { + (group.total_byte_size().max(0) as u64) + .saturating_mul(2) + .saturating_add(group.compressed_size().max(0) as u64) + }) + .max() + .unwrap_or(0); + pages.saturating_add(footer.memory_size() as u64) +} diff --git a/src/mito2/src/compaction/multi_region/source.rs b/src/mito2/src/compaction/multi_region/source.rs new file mode 100644 index 00000000000..313f57778f5 --- /dev/null +++ b/src/mito2/src/compaction/multi_region/source.rs @@ -0,0 +1,754 @@ +// 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 std::cmp::Reverse; +use std::collections::BTreeMap; +use std::sync::Arc; +use std::sync::atomic::{AtomicU64, Ordering}; + +use arrow_schema::extension::EXTENSION_TYPE_METADATA_KEY; +use common_time::Timestamp; +use datatypes::arrow::array::{ + Array, ArrayRef, BinaryArray, GenericByteArray, GenericByteDictionaryBuilder, UInt64Array, +}; +use datatypes::arrow::compute::{cast, concat_batches, take_record_batch}; +use datatypes::arrow::datatypes::{ + BinaryType, ByteArrayType, DataType, Field, Schema, SchemaRef, UInt32Type, Utf8Type, +}; +use datatypes::arrow::record_batch::RecordBatch; +use parquet::file::metadata::PageIndexPolicy; +use partition::PartitionRuleRef; +use snafu::{OptionExt, ResultExt, ensure}; +use store_api::metadata::RegionMetadataRef; +use store_api::storage::RegionId; +use tokio_util::sync::CancellationToken; + +use crate::access_layer::AccessLayerRef; +use crate::cache::CacheStrategy; +use crate::compaction::json2::collect_json2_rewrite_plans_from_parquet; +use crate::compaction::multi_region::memory::{BATCH_SIZE, MemoryLimits}; +use crate::compaction::multi_region::{ + MultiRegionCompactionContext, MultiRegionCompactionPlan, MultiRegionTarget, SourceCounters, +}; +use crate::error::{ + ComputeArrowSnafu, InvalidMultiRegionCompactionSnafu, MultiRegionCompactionResourceSnafu, + NewRecordBatchSnafu, Result, +}; +use crate::read::compat::FlatCompatBatch; +use crate::read::flat_merge::FlatMergeReader; +use crate::read::flat_projection::FlatProjectionMapper; +use crate::read::read_columns::ReadColumns; +use crate::read::{BoxedRecordBatchStream, timestamp_array_to_i64_slice}; +use crate::sst::file::{FileHandle, FileMeta}; +use crate::sst::file_purger::NoopFilePurger; +use crate::sst::parquet::flat_format::{ + primary_key_column_index, sequence_column_index, time_index_column_index, +}; +use crate::sst::parquet::format::{PrimaryKeyArray, need_override_sequence}; +use crate::sst::parquet::reader::{MetadataCacheMetrics, ParquetReader, ReaderMetrics}; +use crate::sst::parquet::{Json2RewriteTargets, Json2TargetLayout}; + +pub(crate) struct SourceEvent { + pub(crate) region_id: RegionId, + pub(crate) batch: RecordBatch, +} + +/// Complete leading-key groups, ordered by target, key-group ordinal and version. +/// Only the next bounded fragment is materialized, not one array per destination. +struct RoutedBatch { + batch: RecordBatch, + rows: Vec<(RegionId, usize, Reverse, usize)>, + offset: usize, +} + +impl RoutedBatch { + fn next_fragment(&mut self, source: &SharedSource) -> Result> { + source.check_cancelled()?; + let Some(&(region_id, _, _, _)) = self.rows.get(self.offset) else { + return Ok(None); + }; + let rows = &self.rows[self.offset..]; + let len = rows + .partition_point(|row| row.0 == region_id) + .min(BATCH_SIZE); + let indices = UInt64Array::from_iter_values(rows[..len].iter().map(|row| row.3 as u64)); + let batch = take_record_batch(&self.batch, &indices).context(ComputeArrowSnafu)?; + let batch = compact_dictionaries(batch)?; + ensure!( + batch.get_array_memory_size() <= source.limits.batch, + MultiRegionCompactionResourceSnafu { + reason: "Routed batch exceeds the task buffer budget" + } + ); + self.offset += len; + Ok(Some(SourceEvent { region_id, batch })) + } +} + +pub(crate) struct SharedSource { + layer: AccessLayerRef, + cache: CacheStrategy, + sources: Vec, + legacy_overrides: Vec, + expected_rows: Vec, + targets: BTreeMap, + metadata: RegionMetadataRef, + mapper: FlatProjectionMapper, + json2_targets: Json2RewriteTargets, + schema: SchemaRef, + merge_schema: SchemaRef, + partition_rule: PartitionRuleRef, + window: (Timestamp, Timestamp), + pub(crate) limits: MemoryLimits, + peak_group_bytes: AtomicU64, + cancellation: Arc, + stop: CancellationToken, + counters: Arc, +} + +impl SharedSource { + pub(crate) async fn build( + plan: &MultiRegionCompactionPlan, + context: &MultiRegionCompactionContext, + metadata: RegionMetadataRef, + counters: Arc, + ) -> Result> { + let mut common = (*metadata).clone(); + common.set_partition_expr(None); + let metadata = Arc::new(common); + let cache = CacheStrategy::Compaction(context.cache.clone()); + let mut footers = Vec::with_capacity(plan.sources.len()); + let mut footer_bytes = 0usize; + for file in &plan.sources { + ensure!( + !context.cancellation.is_cancelled(), + crate::error::CompactionCancelledSnafu + ); + let handle = FileHandle::new(file.clone(), Arc::new(NoopFilePurger)); + let path = handle.file_path( + context.access_layer.table_dir(), + context.access_layer.path_type(), + ); + let (sst, _) = context + .access_layer + .read_sst(handle) + .cache(cache.clone()) + .read_parquet_metadata( + &path, + file.file_size, + &mut MetadataCacheMetrics::default(), + PageIndexPolicy::Skip, + ) + .await?; + let footer = sst.parquet_metadata(); + footer_bytes = footer_bytes.saturating_add(footer.memory_size()); + ensure!( + footer_bytes <= plan.memory_limit / 8, + MultiRegionCompactionResourceSnafu { + reason: "Source footer metadata exceeds the task budget", + } + ); + footers.push(footer); + } + let legacy_overrides = footers + .iter() + .map(|footer| need_override_sequence(footer)) + .collect(); + let expected_rows = footers + .iter() + .map(|footer| footer.file_metadata().num_rows()) + .collect(); + let layouts = collect_json2_rewrite_plans_from_parquet(&metadata, &footers)?; + let mut json2 = BTreeMap::new(); + for (name, layout) in layouts { + let column = + metadata + .column_by_name(&name) + .context(InvalidMultiRegionCompactionSnafu { + reason: "JSON2 layout names an unknown column", + })?; + let extension_metadata = column + .column_schema + .metadata() + .get(EXTENSION_TYPE_METADATA_KEY) + .cloned() + .context(InvalidMultiRegionCompactionSnafu { + reason: "JSON2 extension metadata missing", + })?; + json2.insert( + column.column_id, + Json2TargetLayout { + extension_metadata, + target_layout: layout.target_layout, + }, + ); + } + let json2_targets = Arc::new(json2); + let mapper = FlatProjectionMapper::new_with_json2_rewrite_targets( + &metadata, + (0..metadata.column_metadatas.len()).collect(), + ReadColumns::new( + metadata + .column_metadatas + .iter() + .map(|column| column.column_id), + ), + &json2_targets, + )?; + let schema = mapper.input_arrow_schema(false); + let mut limits = MemoryLimits::new(plan, &schema)?; + limits.admit(plan, context, &footers)?; + // Compute routing/version annotations on bounded reader batches, but + // keep physical __sequence as the merge key. The annotations are not + // persisted and fixed-position time/PK/sequence/op columns stay last. + let fields = ["__compaction_region", "__compaction_sequence"] + .into_iter() + .map(|name| Arc::new(Field::new(name, DataType::UInt64, false))) + .chain(schema.fields().iter().cloned()) + .collect::>(); + let merge_schema = Arc::new(Schema::new(fields)); + Ok(Arc::new(Self { + layer: context.access_layer.clone(), + cache, + sources: plan.sources.clone(), + legacy_overrides, + expected_rows, + targets: plan.targets.clone(), + metadata, + mapper, + json2_targets, + schema, + merge_schema, + partition_rule: plan.partition_rule.clone(), + window: ( + Timestamp::new_second(plan.window_start), + Timestamp::new_second(plan.window_start + plan.window_seconds), + ), + limits, + peak_group_bytes: AtomicU64::new(0), + cancellation: context.cancellation.clone(), + stop: CancellationToken::new(), + counters, + })) + } + + pub(crate) fn cancel_on_drop(&self) -> tokio_util::sync::DropGuard { + self.stop.clone().drop_guard() + } + + pub(crate) fn schema(&self) -> SchemaRef { + self.schema.clone() + } + pub(crate) fn peak_group_bytes(&self) -> u64 { + self.peak_group_bytes.load(Ordering::Relaxed) + } + + /// One global merge closes leading (PK,time) groups. Only that group's + /// versions need reordering after applying target-local admission sequences. + /// This also supports field partitions and reversed installation orders. + pub(crate) fn batches( + self: Arc, + ) -> std::pin::Pin> + Send>> { + use futures::TryStreamExt; + Box::pin(async_stream::try_stream! { + let streams = (0..self.sources.len()) + .map(|index| self.clone().source_batches(index)) + .collect(); + let mut merged = + FlatMergeReader::new(self.merge_schema.clone(), streams, BATCH_SIZE, None).await?; + let mut groups = KeyGroups::new(self.limits.group); + while let Some(batch) = merged.next_batch().await? { + self.check_cancelled()?; + let complete = groups.push(batch)?; + self.peak_group_bytes.fetch_max(groups.peak as u64, Ordering::Relaxed); + if let Some(complete) = complete { + let mut fragments = self.clone().route_batches(complete); + while let Some(fragment) = fragments.try_next().await? { yield fragment; } + } + } + if !groups.batches.is_empty() { + let mut fragments = self.clone().route_batches(groups.batches); + while let Some(fragment) = fragments.try_next().await? { yield fragment; } + } + }) + } + + fn route_batches( + self: Arc, + batches: Vec, + ) -> std::pin::Pin> + Send>> { + Box::pin(async_stream::try_stream! { + let router = self.clone(); + let mut routed = common_runtime::spawn_blocking_compact(move || router.route(batches)) + .await + .context(crate::error::JoinSnafu)??; + loop { + let router = self.clone(); + let (event, next) = common_runtime::spawn_blocking_compact(move || { + let event = routed.next_fragment(&router)?; + Ok::<_, crate::error::Error>((event, routed)) + }).await.context(crate::error::JoinSnafu)??; + routed = next; + let Some(event) = event else { break; }; + yield event; + } + }) + } + + fn source_batches(self: Arc, index: usize) -> BoxedRecordBatchStream { + Box::pin(async_stream::try_stream! { + self.check_cancelled()?; + let file = &self.sources[index]; + let mut raw_meta = file.clone(); + raw_meta.sequence = None; + raw_meta.preserve_row_sequence = true; + let builder = self + .layer + .read_sst(FileHandle::new(raw_meta, Arc::new(NoopFilePurger))) + .cache(self.cache.clone()) + .batch_size(BATCH_SIZE) + .expected_metadata(Some(self.metadata.clone())) + .json2_rewrite_targets(self.json2_targets.clone()) + .compaction(false) + .page_index_policy(PageIndexPolicy::Skip); + let mut rows = 0u64; + let input = builder + .build_reader_input(&mut ReaderMetrics::default()) + .await?; + if let Some((input, selection)) = input { + let compat = FlatCompatBatch::try_new(&self.mapper, input.read_format(), false)? + .map(Arc::new); + let mut reader = ParquetReader::new(Arc::new(input), selection).await?; + let mut last_key = None; + while let Some(batch) = reader.next_record_batch().await? { + self.check_cancelled()?; + let preparing = self.clone(); + let compat = compat.clone(); + let (batch, previous) = common_runtime::spawn_blocking_compact(move || { + preparing.check_cancelled()?; + let batch = match compat { + Some(compat) => compat.compat(batch)?, + None => batch, + }; + let batch = compact_dictionaries(batch)?; + let batch_bytes = batch.get_array_memory_size(); + ensure!( + batch_bytes <= preparing.limits.batch, + MultiRegionCompactionResourceSnafu { + reason: format!( + "Decoded source batch uses {} bytes, budget is {}", + batch_bytes, + preparing.limits.batch, + ), + } + ); + preparing.validate_batch(&batch, &mut last_key)?; + let batch = preparing.annotate(batch, index)?; + Ok::<_, crate::error::Error>((batch, last_key)) + }).await.context(crate::error::JoinSnafu)??; + last_key = previous; + rows += batch.num_rows() as u64; + self.counters.rows.fetch_add(batch.num_rows() as u64, Ordering::Relaxed); + yield batch; + } + self.counters + .store_page_bytes + .fetch_add(reader.fetched_store_page_bytes()?, Ordering::Relaxed); + } + let expected = self.expected_rows[index]; + if expected < 0 || rows != expected as u64 { + Err(InvalidMultiRegionCompactionSnafu { + reason: "Shared source scan did not cover its complete footer row count", + } + .build())?; + } + self.counters.files.fetch_add(1, Ordering::Relaxed); + }) + } + + fn validate_batch( + &self, + batch: &RecordBatch, + previous: &mut Option<(Vec, i64, Reverse)>, + ) -> Result<()> { + let time = batch.column(time_index_column_index(batch.num_columns())); + let sequences = batch + .column(sequence_column_index(batch.num_columns())) + .as_any() + .downcast_ref::() + .context(InvalidMultiRegionCompactionSnafu { + reason: "Invalid sequence column", + })?; + ensure!( + time.null_count() == 0 && sequences.null_count() == 0, + InvalidMultiRegionCompactionSnafu { + reason: "Null timestamp or sequence in source" + } + ); + let unit = self + .metadata + .time_index_column() + .column_schema + .data_type + .as_timestamp() + .context(InvalidMultiRegionCompactionSnafu { + reason: "Time index is not a timestamp", + })? + .unit(); + for (row, &value) in timestamp_array_to_i64_slice(time).iter().enumerate() { + let timestamp = Timestamp::new(value, unit); + ensure!( + timestamp >= self.window.0 && timestamp < self.window.1, + InvalidMultiRegionCompactionSnafu { + reason: "Source row is outside the task window" + } + ); + let current = ( + key_at(batch, row)?.to_vec(), + value, + Reverse(sequences.value(row)), + ); + ensure!( + previous + .as_ref() + .is_none_or(|previous| *previous <= current), + InvalidMultiRegionCompactionSnafu { + reason: "Source is not ordered after schema alignment" + } + ); + *previous = Some(current); + } + Ok(()) + } + + fn annotate(&self, batch: RecordBatch, index: usize) -> Result { + // Evaluate masks before adding private columns, avoiding name collisions + // and N-target masks over a potentially much larger equal-key group. + let owners = self.row_owners(&batch)?; + let physical = batch + .column(sequence_column_index(batch.num_columns())) + .as_any() + .downcast_ref::() + .context(InvalidMultiRegionCompactionSnafu { + reason: "Invalid sequence column", + })?; + let source = &self.sources[index]; + let sequences = owners.iter().enumerate().map(|(row, region)| { + let input = &self.targets[region].inputs[&source.file_id()]; + if input.region_id != *region + || (!input.preserve_row_sequence && self.legacy_overrides[index]) + { + input + .sequence + .map(|value| value.get()) + .unwrap_or_else(|| physical.value(row)) + } else { + physical.value(row) + } + }); + let columns = [ + Arc::new(UInt64Array::from_iter_values( + owners.iter().map(RegionId::as_u64), + )) as ArrayRef, + Arc::new(UInt64Array::from_iter_values(sequences)) as ArrayRef, + ] + .into_iter() + .chain(batch.columns().iter().cloned()) + .collect(); + RecordBatch::try_new(self.merge_schema.clone(), columns).context(NewRecordBatchSnafu) + } + + fn route(&self, batches: Vec) -> Result { + self.check_cancelled()?; + let batch = concat_batches(&self.merge_schema, &batches).context(ComputeArrowSnafu)?; + let owners = batch + .column(0) + .as_any() + .downcast_ref::() + .context(InvalidMultiRegionCompactionSnafu { + reason: "Missing routing annotation", + })?; + let sequences = batch + .column(1) + .as_any() + .downcast_ref::() + .context(InvalidMultiRegionCompactionSnafu { + reason: "Missing sequence annotation", + })?; + let mut group = 0usize; + let mut rows = Vec::with_capacity(batch.num_rows()); + for row in 0..batch.num_rows() { + if row > 0 && !same_key(&batch, row - 1, &batch, row)? { + group += 1; + } + rows.push(( + RegionId::from_u64(owners.value(row)), + group, + Reverse(sequences.value(row)), + row, + )); + } + rows.sort_unstable(); + let mut columns = batch.columns()[2..].to_vec(); + let sequence_index = sequence_column_index(columns.len()); + columns[sequence_index] = batch.column(1).clone(); + let batch = + RecordBatch::try_new(self.schema.clone(), columns).context(NewRecordBatchSnafu)?; + Ok(RoutedBatch { + batch, + rows, + offset: 0, + }) + } + + fn row_owners(&self, batch: &RecordBatch) -> Result> { + let rows = batch.num_rows(); + let masks = self + .partition_rule + .split_record_batch(batch) + .context(crate::error::RouteMultiRegionSnafu)?; + let mut owners = vec![None; rows]; + for (number, mask) in masks { + ensure!( + mask.array().len() == rows, + InvalidMultiRegionCompactionSnafu { + reason: "Partition rule returned a mask with the wrong row count" + } + ); + let id = RegionId::new(self.metadata.region_id.table_id(), number); + for (row, selected) in mask.array().iter().enumerate() { + if selected == Some(true) { + ensure!( + owners[row].replace(id).is_none(), + InvalidMultiRegionCompactionSnafu { + reason: "Source row matches multiple target partitions" + } + ); + } + } + } + self.resolve_unassigned(batch, &mut owners)?; + owners + .into_iter() + .map(|owner| { + owner.filter(|id| self.targets.contains_key(id)).context( + InvalidMultiRegionCompactionSnafu { + reason: "Partition rule selected a region outside the captured targets", + }, + ) + }) + .collect() + } + + fn resolve_unassigned( + &self, + batch: &RecordBatch, + owners: &mut [Option], + ) -> Result<()> { + if owners.iter().all(Option::is_some) { + return Ok(()); + } + let columns = self + .partition_rule + .partition_columns() + .iter() + .map(|name| { + let array = + batch + .column_by_name(name) + .context(InvalidMultiRegionCompactionSnafu { + reason: "Partition column missing from the source batch", + })?; + datatypes::vectors::Helper::try_into_vector(array.clone()) + .context(crate::error::ConvertVectorSnafu) + }) + .collect::>>()?; + for (row, owner) in owners + .iter_mut() + .enumerate() + .filter(|(_, owner)| owner.is_none()) + { + let values = columns + .iter() + .map(|column| column.get(row)) + .collect::>(); + let number = self + .partition_rule + .find_region(&values) + .context(crate::error::RouteMultiRegionSnafu)?; + *owner = Some(RegionId::new(self.metadata.region_id.table_id(), number)); + } + Ok(()) + } + + fn check_cancelled(&self) -> Result<()> { + ensure!( + !self.stop.is_cancelled() && !self.cancellation.is_cancelled(), + crate::error::CompactionCancelledSnafu + ); + Ok(()) + } +} + +/// Carries only the trailing equal (PK,time) group. Complete groups can be +/// routed immediately; EOF closes the remaining group without another scan. +struct KeyGroups { + batches: Vec, + bytes: usize, + peak: usize, + limit: usize, +} + +impl KeyGroups { + fn new(limit: usize) -> Self { + Self { + batches: Vec::new(), + bytes: 0, + peak: 0, + limit, + } + } + + fn push(&mut self, batch: RecordBatch) -> Result>> { + let tail = trailing_group_start(&batch)?; + let same_tail = self + .batches + .last() + .map(|previous| { + same_key( + previous, + previous.num_rows() - 1, + &batch, + batch.num_rows() - 1, + ) + }) + .transpose()? + .unwrap_or(false); + let complete = if (!same_tail && !self.batches.is_empty()) || tail > 0 { + if tail > 0 { + self.retain(batch.slice(0, tail))?; + } + self.bytes = 0; + Some(std::mem::take(&mut self.batches)) + } else { + None + }; + self.retain(batch.slice(tail, batch.num_rows() - tail))?; + Ok(complete) + } + + fn retain(&mut self, batch: RecordBatch) -> Result<()> { + self.bytes = self + .bytes + .saturating_add(batch.get_array_memory_size() + std::mem::size_of::()); + ensure!( + self.bytes <= self.limit, + MultiRegionCompactionResourceSnafu { + reason: "Equal-key version group exceeds the task buffer budget" + } + ); + self.peak = self.peak.max(self.bytes); + self.batches.push(batch); + Ok(()) + } +} + +fn trailing_group_start(batch: &RecordBatch) -> Result { + let last = batch.num_rows() - 1; + let mut start = last; + while start > 0 && same_key(batch, start - 1, batch, last)? { + start -= 1; + } + Ok(start) +} + +fn same_key( + left: &RecordBatch, + left_row: usize, + right: &RecordBatch, + right_row: usize, +) -> Result { + let left_time = + timestamp_array_to_i64_slice(left.column(time_index_column_index(left.num_columns()))) + [left_row]; + let right_time = + timestamp_array_to_i64_slice(right.column(time_index_column_index(right.num_columns()))) + [right_row]; + Ok(left_time == right_time && key_at(left, left_row)? == key_at(right, right_row)?) +} + +/// A selected batch must not pin dictionaries for a whole row group or version +/// group. Casting through the value type compacts both tag and PK dictionaries. +fn compact_dictionaries(batch: RecordBatch) -> Result { + let columns = batch + .columns() + .iter() + .map(|array| match array.data_type() { + DataType::Dictionary(key, values) if **key == DataType::UInt32 => match **values { + DataType::Utf8 => compact_dictionary::(array), + DataType::Binary => compact_dictionary::(array), + _ => Ok(array.clone()), + }, + _ => Ok(array.clone()), + }) + .collect::>>()?; + RecordBatch::try_new(batch.schema(), columns).context(NewRecordBatchSnafu) +} + +fn compact_dictionary(array: &ArrayRef) -> Result { + let decoded = cast(array, &T::DATA_TYPE).context(ComputeArrowSnafu)?; + let values = decoded + .as_any() + .downcast_ref::>() + .context(InvalidMultiRegionCompactionSnafu { + reason: "Invalid decoded dictionary", + })?; + let mut builder = GenericByteDictionaryBuilder::::with_capacity( + values.len(), + values.len(), + values.value_data().len(), + ); + for value in values.iter() { + if let Some(value) = value { + builder.append(value).context(ComputeArrowSnafu)?; + } else { + builder.append_null(); + } + } + Ok(Arc::new(builder.finish())) +} + +fn key_at(batch: &RecordBatch, row: usize) -> Result<&[u8]> { + let keys = batch + .column(primary_key_column_index(batch.num_columns())) + .as_any() + .downcast_ref::() + .context(InvalidMultiRegionCompactionSnafu { + reason: "Invalid primary-key column", + })?; + let values = keys + .values() + .as_any() + .downcast_ref::() + .context(InvalidMultiRegionCompactionSnafu { + reason: "Invalid primary-key dictionary", + })?; + let index = keys.key(row).context(InvalidMultiRegionCompactionSnafu { + reason: "Null internal primary key", + })?; + ensure!( + !values.is_null(index), + InvalidMultiRegionCompactionSnafu { + reason: "Null internal primary-key value" + } + ); + Ok(values.value(index)) +} diff --git a/src/mito2/src/compaction/multi_region/tests.rs b/src/mito2/src/compaction/multi_region/tests.rs new file mode 100644 index 00000000000..11829dcca2e --- /dev/null +++ b/src/mito2/src/compaction/multi_region/tests.rs @@ -0,0 +1,2456 @@ +// 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 std::collections::{BTreeMap, HashSet}; +use std::num::NonZeroU64; +use std::sync::{Arc, Mutex}; +use std::time::Duration; + +use api::v1::{OpType, SemanticType}; +use datatypes::arrow::array::{ + Array, ArrayRef, BinaryArray, BinaryDictionaryBuilder, BooleanArray, DictionaryArray, + StringArray, StringDictionaryBuilder, TimestampMillisecondArray, UInt8Array, UInt64Array, +}; +use datatypes::arrow::compute::cast; +use datatypes::arrow::datatypes::{DataType, Field, UInt32Type}; +use datatypes::arrow::record_batch::RecordBatch; +use datatypes::extension::json::{Json2ExtensionType, Json2PhysicalLayout, JsonMetadata}; +use datatypes::json::{JsonSettings, JsonTypeHint}; +use datatypes::prelude::ConcreteDataType; +use datatypes::schema::ColumnSchema; +use datatypes::types::json_type::JsonNativeType; +use datatypes::types::parse_string_to_jsonb; +use datatypes::value::Value; +use datatypes::vectors::json::array::JsonArray; +use datatypes::vectors::json::json2_physical_data_type; +use futures::TryStreamExt; +use object_store::layers::mock::{self, MockLayerBuilder, oio}; +use partition::expr::col; +use partition::multi_dim::MultiDimPartitionRule; +use serde_json::json; +use store_api::codec::PrimaryKeyEncoding; +use store_api::metadata::{ColumnMetadata, RegionMetadataBuilder}; +use store_api::region_request::PathType; +use store_api::storage::RegionId; + +use super::*; +use crate::access_layer::{AccessLayer, Metrics, OperationType, SstWriteRequest, WriteType}; +use crate::cache::{CacheManager, CacheStrategy}; +use crate::error::InvalidMultiRegionCompactionSnafu; +use crate::read::FlatSource; +use crate::sst::file::{FileHandle, RegionFileId}; +use crate::sst::file_purger::NoopFilePurger; +use crate::sst::index::intermediate::IntermediateManager; +use crate::sst::index::puffin_manager::PuffinManagerFactory; +use crate::sst::parquet::WriteOptions; +use crate::sst::parquet::flat_format::{ + primary_key_column_index, sequence_column_index, time_index_column_index, +}; +use crate::sst::{FlatSchemaOptions, FormatType, to_flat_sst_arrow_schema}; +use crate::test_util::scheduler_util::SchedulerEnv; +use crate::test_util::sst_util::{ + new_flat_source_from_record_batches, new_record_batch_with_custom_sequence, + new_sparse_primary_key, sst_region_metadata_with_encoding, +}; + +struct Protection { + layer: AccessLayerRef, + files: Mutex>, + fail_region: Option, + first_protected: tokio::sync::Notify, +} + +#[async_trait::async_trait] +impl SstWriteGuard for Protection { + async fn before_create(&self, file_id: RegionFileId) -> Result<()> { + let path = crate::sst::location::sst_file_path( + self.layer.table_dir(), + file_id, + self.layer.path_type(), + ); + assert!( + !self.layer.object_store().exists(&path).await.unwrap(), + "SST already existed before protection" + ); + if self.fail_region == Some(file_id.region_id()) { + // Failure must occur after another worker has protected an output; + // worker scheduling no longer follows region-id order. + self.first_protected.notified().await; + return InvalidMultiRegionCompactionSnafu { + reason: "injected output protection failure", + } + .fail(); + } + assert!(self.files.lock().unwrap().insert(file_id)); + self.first_protected.notify_one(); + Ok(()) + } +} + +struct Fixture { + env: SchedulerEnv, + layer: AccessLayerRef, + metadata: RegionMetadataRef, + source: FileMeta, + config: Arc, +} + +type TestRow = (u32, i64, u64, u8, Option); + +impl Fixture { + async fn new(encoding: PrimaryKeyEncoding, format: FormatType, physical_sequence: u64) -> Self { + Self::with_source(encoding, format, |metadata| { + (0..31) + .map(|series| source_batch(metadata, series, physical_sequence)) + .collect() + }) + .await + } + + async fn with_source( + encoding: PrimaryKeyEncoding, + format: FormatType, + batches: impl FnOnce(&RegionMetadataRef) -> Vec, + ) -> Self { + let env = SchedulerEnv::new().await; + let aux = env.path.path().join("table-index"); + let layer = Arc::new(AccessLayer::new( + "table/", + if encoding == PrimaryKeyEncoding::Sparse { + PathType::Data + } else { + PathType::Bare + }, + env.access_layer.object_store().clone(), + PuffinManagerFactory::new(&aux, 1024 * 1024, None, None) + .await + .unwrap(), + IntermediateManager::init_fs(aux.to_str().unwrap()) + .await + .unwrap(), + )); + let mut metadata = sst_region_metadata_with_encoding(encoding); + metadata.region_id = RegionId::new(1, 0); + let metadata = Arc::new(metadata); + let mut config = MitoConfig::default(); + config.index.aux_path = aux.display().to_string(); + let config = Arc::new(config); + let mut batches = batches(&metadata); + batches.sort_by_cached_key(|batch| { + let keys = cast( + batch.column(primary_key_column_index(batch.num_columns())), + &DataType::Binary, + ) + .unwrap(); + keys.as_any() + .downcast_ref::() + .unwrap() + .value(0) + .to_vec() + }); + let mut fixture = Self { + env, + layer, + metadata: metadata.clone(), + source: FileMeta::default(), + config, + }; + let info = fixture + .write_source(metadata.clone(), batches, format) + .await; + fixture.source = file_meta(info, metadata.region_id); + fixture + } + + async fn write_source( + &self, + metadata: RegionMetadataRef, + batches: Vec, + format: FormatType, + ) -> SstInfo { + self.layer + .write_sst( + write_request( + metadata, + new_flat_source_from_record_batches(batches), + &self.config, + format, + ), + &WriteOptions::default(), + &mut Metrics::new(WriteType::Flush), + ) + .await + .unwrap() + .remove(0) + } + + async fn write_additional_source(&self, batches: Vec) -> FileMeta { + let info = self + .write_source(self.metadata.clone(), batches, FormatType::Flat) + .await; + file_meta(info, self.metadata.region_id) + } + + fn plan(&self, regions: u32) -> MultiRegionCompactionPlan { + let mut targets = BTreeMap::new(); + for region in 0..regions { + let id = RegionId::new(1, region); + let mut metadata = (*self.metadata).clone(); + metadata.region_id = id; + let start = format!("{:03}", region * 32 / regions); + let end = format!("{:03}", (region + 1) * 32 / regions); + metadata.set_partition_expr(Some( + col("tag_0") + .gt_eq(Value::String(start.into())) + .and(col("tag_0").lt(Value::String(end.into()))) + .as_json_str() + .unwrap(), + )); + let mut input = self.source.clone(); + input.sequence = NonZeroU64::new(100 + region as u64); + let options = RegionOptions { + append_mode: true, + preserve_row_sequence: true, + sst_format: Some(FormatType::Flat), + ..Default::default() + }; + targets.insert( + id, + MultiRegionTarget { + metadata: Arc::new(metadata), + options, + inputs: [(input.file_id(), input)].into_iter().collect(), + }, + ); + } + let exprs = targets + .values() + .map(|target| { + crate::region::parse_partition_expr(target.metadata.partition_expr.as_deref()) + .unwrap() + .unwrap() + }) + .collect(); + let partition_rule = Arc::new( + MultiDimPartitionRule::try_new( + vec!["tag_0".into()], + (0..regions).collect(), + exprs, + false, + ) + .unwrap(), + ); + MultiRegionCompactionPlan { + partition_rule, + sources: vec![self.source.clone()], + targets, + // Includes the fixed Parquet encoder allocations of every resident + // target, unlike the old run-cache-only budget. + memory_limit: (128 + regions as usize * 32) * 1024 * 1024, + max_output_file_size: 1024 * 1024, + window_start: 0, + window_seconds: 3600, + } + } + + fn context( + &self, + fail_region: Option, + ) -> (MultiRegionCompactionContext, Arc) { + let protection = Arc::new(Protection { + layer: self.layer.clone(), + files: Mutex::default(), + fail_region, + first_protected: tokio::sync::Notify::new(), + }); + ( + MultiRegionCompactionContext { + access_layer: self.layer.clone(), + cache: Arc::new(CacheManager::default()), + config: self.config.clone(), + protection: protection.clone(), + cancellation: Arc::new(CancellationHandle::default()), + }, + protection, + ) + } + + async fn compact(&self, plan: MultiRegionCompactionPlan) -> MultiRegionCompactionOutput { + compact_regions(plan, self.context(None).0).await.unwrap() + } + + /// Reads an output exactly as the owning region will once the returned + /// metadata is published: partition filtering and sequence override are + /// both derived from that metadata. + async fn read_published_output( + &self, + file: FileMeta, + metadata: RegionMetadataRef, + ) -> Vec { + let expected_region = file.region_id; + let expected_rows = file.num_rows; + let mut reader = self + .layer + .read_sst(FileHandle::new(file, Arc::new(NoopFilePurger))) + .expected_metadata(Some(metadata.clone())) + .cache(CacheStrategy::Disabled) + .build() + .await + .unwrap() + .unwrap(); + assert_eq!(expected_region, reader.metadata().region_id); + assert_eq!( + metadata.column_metadatas, + reader.metadata().column_metadatas + ); + assert_eq!( + expected_rows, + reader.parquet_metadata().file_metadata().num_rows() as u64 + ); + let mut batches = Vec::new(); + while let Some(batch) = reader.next_record_batch().await.unwrap() { + batches.push(batch); + } + assert_eq!( + expected_rows, + batches + .iter() + .map(|batch| batch.num_rows() as u64) + .sum::() + ); + batches + } + + async fn read_published_output_rows( + &self, + file: FileMeta, + metadata: RegionMetadataRef, + ) -> Vec { + self.decode_base_rows(self.read_published_output(file, metadata).await) + } + + async fn read_output( + &self, + mut file: FileMeta, + metadata: RegionMetadataRef, + ) -> Vec { + // Inspect the physical contents: a partition filter or sequence override + // on read must not hide incorrectly routed/written records. + file.sequence = None; + file.preserve_row_sequence = true; + let mut unfiltered = (*metadata).clone(); + unfiltered.set_partition_expr(None); + self.read_published_output(file, Arc::new(unfiltered)).await + } + + async fn read_output_rows(&self, file: FileMeta, metadata: RegionMetadataRef) -> Vec { + self.decode_base_rows(self.read_output(file, metadata).await) + } + + fn decode_base_rows(&self, batches: Vec) -> Vec { + let mut decoded = Vec::new(); + for batch in batches { + let sequences = batch + .column(sequence_column_index(batch.num_columns())) + .as_any() + .downcast_ref::() + .unwrap(); + let operations = batch + .column(batch.num_columns() - 1) + .as_any() + .downcast_ref::() + .unwrap(); + let keys = cast( + batch.column(primary_key_column_index(batch.num_columns())), + &DataType::Binary, + ) + .unwrap(); + let keys = keys.as_any().downcast_ref::().unwrap(); + let tags = cast(batch.column_by_name("tag_0").unwrap(), &DataType::Utf8).unwrap(); + let tags = tags.as_any().downcast_ref::().unwrap(); + let times = crate::read::timestamp_array_to_i64_slice( + batch.column(time_index_column_index(batch.num_columns())), + ); + let values = batch + .column_by_name("field_0") + .unwrap() + .as_any() + .downcast_ref::() + .unwrap(); + for (row, timestamp) in times.iter().enumerate() { + let series: u32 = tags.value(row).parse().unwrap(); + let expected_key = + if self.metadata.primary_key_encoding == PrimaryKeyEncoding::Sparse { + new_sparse_primary_key( + &[tags.value(row), "series"], + &self.metadata, + 1000 + series % 2, + series as u64, + ) + } else { + crate::test_util::sst_util::new_primary_key(&[tags.value(row), "series"]) + }; + assert_eq!(expected_key, keys.value(row)); + decoded.push(( + series, + *timestamp, + sequences.value(row), + operations.value(row), + values.is_valid(row).then(|| values.value(row)), + )); + } + } + decoded + } +} + +fn expected_source_rows(regions: u32, id: RegionId, sequence: u64) -> Vec { + let mut rows = Vec::new(); + for series in + (id.region_sequence() * 32 / regions)..(((id.region_sequence() + 1) * 32 / regions).min(31)) + { + rows.extend([ + (series, 0, sequence, OpType::Put as u8, Some(10)), + (series, 0, sequence, OpType::Put as u8, Some(20)), + (series, 0, sequence, OpType::Delete as u8, None), + (series, 1_000, sequence, OpType::Put as u8, Some(30)), + ]); + } + rows +} + +fn file_meta(info: SstInfo, region_id: RegionId) -> FileMeta { + FileMeta { + region_id, + file_id: info.file_id, + time_range: info.time_range, + file_size: info.file_size, + num_rows: info.num_rows as u64, + num_row_groups: info.num_row_groups, + max_row_group_uncompressed_size: info.max_row_group_uncompressed_size, + ..Default::default() + } +} + +fn write_request( + metadata: RegionMetadataRef, + source: FlatSource, + config: &MitoConfig, + format: FormatType, +) -> SstWriteRequest { + SstWriteRequest { + op_type: OperationType::Flush, + metadata, + source, + cache_manager: Arc::new(CacheManager::default()), + max_sequence: None, + sst_write_format: format, + preserve_row_sequence: false, + index_options: Default::default(), + index_config: config.index.clone(), + inverted_index_config: config.inverted_index.clone(), + fulltext_index_config: config.fulltext_index.clone(), + bloom_filter_index_config: config.bloom_filter_index.clone(), + } +} + +fn source_batch(metadata: &RegionMetadataRef, series: u32, sequence: u64) -> RecordBatch { + let tag = format!("{series:03}"); + let batch = new_record_batch_with_custom_sequence(&[&tag, "series"], 0, 4, sequence); + let mut arrays = batch.columns().to_vec(); + arrays[2] = Arc::new(UInt64Array::from(vec![Some(10), Some(20), None, Some(30)])); + arrays[3] = Arc::new(TimestampMillisecondArray::from(vec![0, 0, 0, 1_000])); + arrays[6] = Arc::new(UInt8Array::from(vec![ + OpType::Put as u8, + OpType::Put as u8, + OpType::Delete as u8, + OpType::Put as u8, + ])); + if metadata.primary_key_encoding == PrimaryKeyEncoding::Sparse { + let pk = new_sparse_primary_key( + &[&tag, "series"], + metadata, + 1000 + series % 2, + series as u64, + ); + let mut keys = BinaryDictionaryBuilder::::new(); + for _ in 0..4 { + keys.append(&pk).unwrap(); + } + arrays[4] = Arc::new(keys.finish()); + arrays.drain(..2); + } + RecordBatch::try_new( + to_flat_sst_arrow_schema( + metadata, + &FlatSchemaOptions::from_encoding(metadata.primary_key_encoding), + ), + arrays, + ) + .unwrap() +} + +#[rstest::rstest] +#[case::dense_flat_zero(PrimaryKeyEncoding::Dense, FormatType::Flat, 0)] +#[case::dense_primary_native(PrimaryKeyEncoding::Dense, FormatType::PrimaryKey, 7)] +#[case::sparse_flat_zero(PrimaryKeyEncoding::Sparse, FormatType::Flat, 0)] +#[case::sparse_flat_native(PrimaryKeyEncoding::Sparse, FormatType::Flat, 7)] +#[tokio::test] +async fn test_single_scan_routes_all_versions_without_folding( + #[case] encoding: PrimaryKeyEncoding, + #[case] format: FormatType, + #[case] sequence: u64, +) { + let fixture = Fixture::new(encoding, format, sequence).await; + let mut fetched_bytes = None; + for regions in [1, 8, 32] { + let mut plan = fixture.plan(regions); + for target in plan.targets.values_mut() { + target.options.sst_format = Some(format); + } + let targets = plan.targets.clone(); + let (context, protected) = fixture.context(None); + let output = compact_regions(plan, context).await.unwrap(); + assert_eq!(1, output.stats.source_files); + assert_eq!(124, output.stats.source_rows); + assert_eq!(124, output.stats.output_rows); + assert!(output.stats.source_store_page_bytes > 0); + if let Some(bytes) = fetched_bytes { + assert_eq!(bytes, output.stats.source_store_page_bytes); + } + fetched_bytes = Some(output.stats.source_store_page_bytes); + let mut total_deletes = 0; + for (id, files) in output.files { + assert_eq!(files.len(), output.sst_infos[&id].len()); + for (file, footer) in files.iter().zip(&output.sst_infos[&id]) { + assert_eq!(file.file_id, footer.file_id); + assert_eq!(file.file_size, footer.file_size); + assert_eq!(file.num_rows, footer.num_rows as u64); + } + let target = &targets[&id]; + let mut actual_rows = Vec::new(); + if regions == 32 && id.region_sequence() == 31 { + assert!(files.is_empty()); + } + for file in files { + assert!(protected.files.lock().unwrap().contains(&file.file_id())); + assert_eq!(1, file.level); + assert_eq!(id, file.region_id); + assert_eq!(id != fixture.metadata.region_id, file.preserve_row_sequence); + let rows = fixture + .read_output_rows(file, target.metadata.clone()) + .await; + let expected = if id == fixture.metadata.region_id && sequence != 0 { + sequence + } else { + 100 + id.region_sequence() as u64 + }; + assert!(rows.iter().all(|row| row.2 == expected)); + total_deletes += rows + .iter() + .filter(|row| row.3 == OpType::Delete as u8) + .count(); + actual_rows.extend(rows); + } + let expected_sequence = if id == fixture.metadata.region_id && sequence != 0 { + sequence + } else { + 100 + id.region_sequence() as u64 + }; + let mut expected_rows = expected_source_rows(regions, id, expected_sequence); + for series in (id.region_sequence() * 32 / regions) + ..(((id.region_sequence() + 1) * 32 / regions).min(31)) + { + let tied = actual_rows + .iter() + .filter(|row| row.0 == series && row.1 == 0) + .map(|row| (row.3, row.4)) + .collect::>(); + assert_eq!( + vec![ + (OpType::Put as u8, Some(10)), + (OpType::Put as u8, Some(20)), + (OpType::Delete as u8, None) + ], + tied + ); + } + actual_rows.sort(); + expected_rows.sort(); + assert_eq!(expected_rows, actual_rows); + } + assert_eq!(31, total_deletes); + } +} + +#[tokio::test] +async fn test_failed_target_never_returns_a_partial_table_result() { + let fixture = Fixture::new(PrimaryKeyEncoding::Dense, FormatType::Flat, 0).await; + let (context, protection) = fixture.context(Some(RegionId::new(1, 1))); + assert!(compact_regions(fixture.plan(8), context).await.is_err()); + assert!( + !protection.files.lock().unwrap().is_empty(), + "earlier target wrote protected outputs" + ); + let path = crate::sst::location::sst_file_path( + fixture.layer.table_dir(), + fixture.source.file_id(), + fixture.layer.path_type(), + ); + assert!(fixture.layer.object_store().exists(&path).await.unwrap()); + assert_spill_cleaned(&fixture.env.path.path().join("spill")).await; +} + +#[rstest::rstest] +#[case::last_row(false, crate::region::options::MergeMode::LastRow)] +#[case::last_non_null(false, crate::region::options::MergeMode::LastNonNull)] +#[case::preserve_row_sequence(true, crate::region::options::MergeMode::LastRow)] +#[tokio::test] +async fn test_table_stage_does_not_fold_versions( + #[case] preserve_sequence: bool, + #[case] merge_mode: crate::region::options::MergeMode, +) { + let fixture = Fixture::new(PrimaryKeyEncoding::Dense, FormatType::Flat, 0).await; + let mut plan = fixture.plan(8); + for target in plan.targets.values_mut() { + target.options.append_mode = preserve_sequence; + target.options.preserve_row_sequence = preserve_sequence; + target.options.merge_mode = Some(merge_mode); + } + let targets = plan.targets.clone(); + let output = fixture.compact(plan).await; + assert_eq!(124, output.stats.output_rows); + for (id, files) in output.files { + let mut rows = Vec::new(); + for file in files { + assert_eq!( + preserve_sequence && id != fixture.metadata.region_id, + file.preserve_row_sequence + ); + rows.extend( + fixture + .read_output_rows(file, targets[&id].metadata.clone()) + .await, + ); + } + let mut expected = expected_source_rows(8, id, 100 + id.region_sequence() as u64); + rows.sort(); + expected.sort(); + assert_eq!(expected, rows); + } +} + +#[tokio::test] +async fn test_long_tag_stream_is_lossless_and_insufficient_admission_creates_no_output() { + let fixture = Fixture::with_source(PrimaryKeyEncoding::Dense, FormatType::Flat, |_| { + (0..200) + .map(|series| { + new_record_batch_with_custom_sequence( + &[&format!("{series:03}{}", "x".repeat(96)), "series"], + 0, + 512, + 0, + ) + }) + .collect() + }) + .await; + let mut plan = fixture.plan(1); + for target in plan.targets.values_mut() { + Arc::make_mut(&mut target.metadata).set_partition_expr(None); + } + let output = fixture.compact(plan).await; + assert_eq!(102400, output.stats.output_rows); + assert!(output.stats.estimated_memory_bytes <= 128 * 1024 * 1024); + // The long-tag regression still checks every physical row. There is no + // intermediate IPC path or repeated materialization of all destinations. + let mut ordinal = 0; + for file in output.files.into_values().flatten() { + for batch in fixture.read_output(file, fixture.metadata.clone()).await { + let tags = cast(batch.column_by_name("tag_0").unwrap(), &DataType::Utf8).unwrap(); + let tags = tags.as_any().downcast_ref::().unwrap(); + let values = batch + .column_by_name("field_0") + .unwrap() + .as_any() + .downcast_ref::() + .unwrap(); + for row in 0..batch.num_rows() { + assert_eq!( + format!("{:03}{}", ordinal / 512, "x".repeat(96)), + tags.value(row) + ); + assert_eq!(ordinal % 512, values.value(row)); + ordinal += 1; + } + } + } + assert_eq!(102400, ordinal); + let mut plan = fixture.plan(1); + plan.memory_limit = 1024 * 1024; + for target in plan.targets.values_mut() { + Arc::make_mut(&mut target.metadata).set_partition_expr(None); + } + let (context, protected) = fixture.context(None); + let error = compact_regions(plan, context).await.err().unwrap(); + assert!( + matches!( + &error, + crate::error::Error::MultiRegionCompactionResource { .. } + ), + "{error:?}" + ); + assert!(protected.files.lock().unwrap().is_empty()); + assert_spill_cleaned(&fixture.env.path.path().join("spill")).await; +} + +#[tokio::test] +async fn test_schema_defaults_are_materialized_without_losing_old_versions() { + use api::v1::SemanticType; + use datatypes::data_type::ConcreteDataType; + use datatypes::schema::{ColumnDefaultConstraint, ColumnSchema}; + use store_api::metadata::{ColumnMetadata, RegionMetadataBuilder}; + let fixture = Fixture::new(PrimaryKeyEncoding::Dense, FormatType::PrimaryKey, 7).await; + let mut plan = fixture.plan(8); + for target in plan.targets.values_mut() { + let mut builder = RegionMetadataBuilder::from_existing((*target.metadata).clone()); + builder.push_column_metadata(ColumnMetadata { + column_id: 10, + semantic_type: SemanticType::Field, + column_schema: ColumnSchema::new("added", ConcreteDataType::uint64_datatype(), false) + .with_default_constraint(Some(ColumnDefaultConstraint::Value(Value::UInt64(42)))) + .unwrap(), + }); + target.metadata = Arc::new(builder.build().unwrap()); + } + let targets = plan.targets.clone(); + let output = fixture.compact(plan).await; + assert_eq!(124, output.stats.output_rows); + for (region_id, files) in output.files { + for file in files { + for batch in fixture + .read_output(file, targets[®ion_id].metadata.clone()) + .await + { + let added = batch + .column_by_name("added") + .unwrap() + .as_any() + .downcast_ref::() + .unwrap(); + assert_eq!(0, added.null_count()); + assert!(added.values().iter().all(|value| *value == 42)); + } + } + } +} + +#[rstest::rstest] +#[case::known_bounds(false)] +#[case::unknown_bound(true)] +#[tokio::test] +async fn test_multiple_sources_merge_versions_in_each_target_sequence_domain( + #[case] unknown_bound: bool, +) { + let fixture = Fixture::new(PrimaryKeyEncoding::Dense, FormatType::Flat, 3).await; + let batches = (0..31) + .map(|series| source_batch(&fixture.metadata, series, 7)) + .collect(); + let second = fixture.write_additional_source(batches).await; + let mut plan = fixture.plan(2); + plan.sources.push(second.clone()); + for (id, target) in &mut plan.targets { + let mut input = second.clone(); + input.sequence = if unknown_bound && id.region_sequence() == 1 { + None + } else { + NonZeroU64::new(200 + id.region_sequence() as u64) + }; + target.inputs.insert(input.file_id(), input); + } + let targets = plan.targets.clone(); + let output = fixture.compact(plan).await; + assert_eq!(2, output.stats.source_files); + assert_eq!(248, output.stats.source_rows); + assert_eq!(248, output.stats.output_rows); + for (id, files) in output.files { + let expected = if id.region_sequence() == 0 { + [3, 7] + } else { + [101, if unknown_bound { 7 } else { 201 }] + }; + let mut observed = Vec::new(); + let mut published = Vec::new(); + let files_for_publish = files.clone(); + let published_row_count: u64 = files.iter().map(|file| file.num_rows).sum(); + for file in files { + assert_eq!( + if unknown_bound && id.region_sequence() == 1 { + None + } else { + NonZeroU64::new(200 + id.region_sequence() as u64) + }, + file.sequence + ); + assert_eq!( + id.region_sequence() != 0 && !unknown_bound, + file.preserve_row_sequence + ); + observed.extend( + fixture + .read_output_rows(file, targets[&id].metadata.clone()) + .await, + ); + } + assert_eq!( + expected.into_iter().collect::>(), + observed.iter().map(|row| row.2).collect::>() + ); + for pair in observed.windows(2) { + if pair[0].0 == pair[1].0 && pair[0].1 == pair[1].1 { + assert!(pair[0].2 >= pair[1].2); + } + } + // Publishing the returned metadata must not change any complete row, + // including duplicate versions and their payload association. + for file in files_for_publish { + published.extend( + fixture + .read_published_output_rows(file, targets[&id].metadata.clone()) + .await, + ); + } + assert_eq!( + published_row_count, + published.len() as u64, + "published metadata drops rows of region {id}" + ); + observed.sort(); + published.sort(); + assert_eq!( + observed, published, + "published metadata changes rows of region {id}" + ); + } +} + +#[tokio::test] +async fn test_overlapping_partition_masks_are_rejected_before_creating_outputs() { + let fixture = Fixture::new(PrimaryKeyEncoding::Dense, FormatType::Flat, 0).await; + let mut plan = fixture.plan(3); + // Tags "010".."019" satisfy both predicates. `check_exprs = false` keeps + // the rule as the caller supplied it, so only the executor can reject it. + plan.partition_rule = Arc::new( + MultiDimPartitionRule::try_new( + vec!["tag_0".into()], + vec![1, 2], + vec![ + col("tag_0").gt_eq(Value::String("010".into())), + col("tag_0").lt(Value::String("020".into())), + ], + false, + ) + .unwrap(), + ); + let (context, protection) = fixture.context(None); + let error = compact_regions(plan, context).await.err().unwrap(); + assert!( + matches!(&error, crate::error::Error::InvalidMultiRegionCompaction { reason, .. } + if reason.contains("matches multiple target partitions")), + "{error:?}" + ); + assert!(protection.files.lock().unwrap().is_empty()); +} + +/// Partition rule whose mask length cannot be produced by a real rule. +struct WrongMaskSizeRule; + +impl partition::PartitionRule for WrongMaskSizeRule { + fn as_any(&self) -> &dyn std::any::Any { + self + } + + fn partition_columns(&self) -> &[String] { + &[] + } + + fn find_region( + &self, + _values: &[Value], + ) -> partition::error::Result { + Ok(0) + } + + fn split_record_batch( + &self, + _batch: &RecordBatch, + ) -> partition::error::Result< + std::collections::HashMap< + store_api::storage::RegionNumber, + partition::partition::RegionMask, + >, + > { + Ok(std::collections::HashMap::from([( + 0, + partition::partition::RegionMask::new(BooleanArray::from(vec![true]), 1), + )])) + } +} + +#[tokio::test] +async fn test_wrong_length_partition_mask_is_rejected_before_creating_outputs() { + let fixture = Fixture::new(PrimaryKeyEncoding::Dense, FormatType::Flat, 0).await; + let mut plan = fixture.plan(2); + plan.partition_rule = Arc::new(WrongMaskSizeRule); + let (context, protection) = fixture.context(None); + let error = compact_regions(plan, context).await.err().unwrap(); + assert!( + matches!(&error, crate::error::Error::InvalidMultiRegionCompaction { reason, .. } + if reason.contains("wrong row count")), + "{error:?}" + ); + assert!(protection.files.lock().unwrap().is_empty()); +} + +struct Json2Column { + name: &'static str, + column_id: u32, + source_layout: JsonSettings, + target_layout: JsonSettings, + rows: [serde_json::Value; 2], +} + +impl Json2Column { + fn source_array(&self) -> ArrayRef { + let jsonb = Arc::new(BinaryArray::from_iter_values( + self.rows + .iter() + .map(|row| parse_string_to_jsonb(&row.to_string()).unwrap()) + .collect::>() + .iter() + .map(|value| value.as_slice()), + )) as ArrayRef; + let field = Field::new(self.name, DataType::Binary, true) + .with_extension_type(Json2ExtensionType::default()); + JsonArray::from(&jsonb) + .rewrite_to_v2(&field, &self.source_layout, &self.source_layout) + .unwrap() + } + + fn expected_rows(&self) -> [serde_json::Value; 2] { + self.rows.clone().map(|mut row| { + for hint in self.target_layout.type_hints() { + row.as_object_mut() + .unwrap() + .entry(hint.path[0].clone()) + .or_insert(serde_json::Value::Null); + } + row + }) + } +} + +/// Builds dense-encoded metadata with JSON2 fields before `ts`, so the +/// time index stays the last user column as the flat format requires. +fn json2_compaction_metadata( + columns: &[Json2Column], + region_id: RegionId, + target_layout: bool, +) -> RegionMetadataRef { + let mut metadata = sst_region_metadata_with_encoding(PrimaryKeyEncoding::Dense); + metadata.region_id = region_id; + let json_start = metadata.column_metadatas.len() - 1; + for (offset, column) in columns.iter().enumerate() { + let settings = if target_layout { + &column.target_layout + } else { + &column.source_layout + }; + let mut schema = ColumnSchema::new( + column.name, + ConcreteDataType::json2(JsonNativeType::object()), + true, + ); + schema.with_extension_type(&Json2ExtensionType::new(Arc::new(JsonMetadata::new( + settings.clone(), + )))); + metadata.column_metadatas.insert( + json_start + offset, + ColumnMetadata { + column_schema: schema, + semantic_type: SemanticType::Field, + column_id: column.column_id, + }, + ); + } + Arc::new( + RegionMetadataBuilder::from_existing(metadata) + .build() + .unwrap(), + ) +} + +fn json2_settings(hints: Vec) -> JsonSettings { + JsonSettings::try_new(hints, Some(0)).unwrap() +} + +fn json2_hint(path: &str, data_type: ConcreteDataType) -> JsonTypeHint { + JsonTypeHint { + path: vec![path.to_string()], + data_type, + inverted_index: false, + skipping_index: None, + fulltext_index: None, + } +} + +fn read_json2_row(batch: &RecordBatch, column: &Json2Column) -> serde_json::Value { + let field = batch.schema_ref().field_with_name(column.name).unwrap(); + assert!( + Json2PhysicalLayout::try_from_root(field) + .unwrap() + .is_version_2() + ); + assert_eq!( + &json2_physical_data_type(&column.target_layout), + field.data_type() + ); + let projected = JsonArray::from(batch.column_by_name(column.name).unwrap()) + .project_to_v2(field, &DataType::Binary) + .unwrap(); + assert_eq!(1, projected.len()); + JsonArray::from(&projected).try_get_value(0).unwrap() +} + +/// A source SST written with an older JSON2 layout must be rewritten into the +/// target layout, keeping values that lived in the remainder field. +#[tokio::test] +async fn test_json2_rewrite_preserves_values_through_multiregion_compaction() { + let fixture = Fixture::new(PrimaryKeyEncoding::Dense, FormatType::Flat, 0).await; + let json_columns = [ + Json2Column { + name: "j", + column_id: 4, + source_layout: json2_settings(vec![json2_hint( + "a", + ConcreteDataType::int64_datatype(), + )]), + target_layout: json2_settings(vec![ + json2_hint("a", ConcreteDataType::int64_datatype()), + json2_hint("b", ConcreteDataType::string_datatype()), + ]), + rows: [json!({"a": 1, "b": "x"}), json!({"a": 2})], + }, + Json2Column { + name: "k", + column_id: 5, + source_layout: json2_settings(vec![json2_hint( + "left", + ConcreteDataType::string_datatype(), + )]), + target_layout: json2_settings(vec![ + json2_hint("left", ConcreteDataType::string_datatype()), + json2_hint("right", ConcreteDataType::int64_datatype()), + ]), + rows: [ + json!({"left": "first", "right": 7}), + json!({"left": "second"}), + ], + }, + ]; + let source_region = RegionId::new(1, 0); + let source_metadata = json2_compaction_metadata(&json_columns, source_region, false); + let base = new_record_batch_with_custom_sequence(&["000", "series"], 0, 2, 100); + let mut columns = base.columns().to_vec(); + let mut tags = StringDictionaryBuilder::::new(); + let mut primary_keys = BinaryDictionaryBuilder::::new(); + for tag in ["000", "020"] { + tags.append_value(tag); + primary_keys + .append(crate::test_util::sst_util::new_primary_key(&[ + tag, "series", + ])) + .unwrap(); + } + columns[0] = Arc::new(tags.finish()); + columns[4] = Arc::new(primary_keys.finish()); + let mut options = FlatSchemaOptions::from_encoding(PrimaryKeyEncoding::Dense); + for (index, column) in json_columns.iter().enumerate() { + let physical = column.source_array(); + options + .concretized_json_types + .insert(column.name.to_string(), physical.data_type().clone()); + columns.insert(3 + index, physical); + } + let source_batch = RecordBatch::try_new( + to_flat_sst_arrow_schema(&source_metadata, &options), + columns, + ) + .unwrap(); + let info = fixture + .write_source(source_metadata, vec![source_batch], FormatType::Flat) + .await; + let mut source = file_meta(info, source_region); + source.sequence = NonZeroU64::new(100); + + let mut plan = fixture.plan(2); + plan.sources = vec![source.clone()]; + for target in plan.targets.values_mut() { + target.metadata = json2_compaction_metadata(&json_columns, target.metadata.region_id, true); + target.inputs = [(source.file_id(), source.clone())].into_iter().collect(); + } + plan.memory_limit = 256 * 1024 * 1024; + let targets = plan.targets.clone(); + let output = fixture.compact(plan).await; + + for (id, files) in &output.files { + let mut rows = 0; + for file in files { + for batch in fixture + .read_output(file.clone(), targets[id].metadata.clone()) + .await + { + rows += batch.num_rows(); + for column in &json_columns { + assert_eq!( + column.expected_rows()[id.region_sequence() as usize], + read_json2_row(&batch, column) + ); + } + } + } + assert_eq!(1, rows, "one row must route to {id}"); + } + assert_eq!(2, output.stats.output_rows); +} + +#[tokio::test] +async fn test_unmatched_partition_values_use_the_table_default_region() { + let fixture = Fixture::new(PrimaryKeyEncoding::Dense, FormatType::Flat, 0).await; + let mut plan = fixture.plan(2); + let exprs = vec![ + col("tag_0").lt(Value::String("010".into())), + col("tag_0").gt_eq(Value::String("020".into())), + ]; + plan.partition_rule = Arc::new( + MultiDimPartitionRule::try_new(vec!["tag_0".into()], vec![0, 1], exprs.clone(), false) + .unwrap(), + ); + for (id, target) in &mut plan.targets { + Arc::make_mut(&mut target.metadata).set_partition_expr(if id.region_sequence() == 0 { + None + } else { + Some(exprs[1].as_json_str().unwrap()) + }); + } + let targets = plan.targets.clone(); + let output = fixture.compact(plan).await; + assert_eq!(124, output.stats.output_rows); + for (id, files) in output.files { + let mut series = HashSet::new(); + for file in files { + series.extend( + fixture + .read_output_rows(file, targets[&id].metadata.clone()) + .await + .into_iter() + .map(|row| row.0), + ); + } + let range = if id.region_sequence() == 0 { + 0..20 + } else { + 20..31 + }; + assert_eq!(range.collect::>(), series); + } +} + +#[tokio::test] +async fn test_nullable_field_partitioning_preserves_delete_records() { + let fixture = Fixture::new(PrimaryKeyEncoding::Dense, FormatType::Flat, 0).await; + let mut plan = fixture.plan(2); + let exprs = vec![ + col("field_0").lt(Value::UInt64(20)), + col("field_0").gt_eq(Value::UInt64(20)), + ]; + plan.partition_rule = Arc::new( + MultiDimPartitionRule::try_new(vec!["field_0".into()], vec![0, 1], exprs.clone(), false) + .unwrap(), + ); + for (id, target) in &mut plan.targets { + Arc::make_mut(&mut target.metadata).set_partition_expr(if id.region_sequence() == 0 { + None + } else { + Some(exprs[1].as_json_str().unwrap()) + }); + } + let targets = plan.targets.clone(); + let output = fixture.compact(plan).await; + assert_eq!(124, output.stats.output_rows); + for (id, files) in output.files { + let mut counts = (0, 0); + for file in files { + let rows = fixture + .read_output_rows(file, targets[&id].metadata.clone()) + .await; + counts.0 += rows.len(); + counts.1 += rows.iter().filter(|row| row.4.is_none()).count(); + for value in rows.iter().filter_map(|row| row.4) { + assert_eq!(id.region_sequence() == 0, value < 20); + } + } + assert_eq!(62, counts.0); + assert_eq!(if id.region_sequence() == 0 { 31 } else { 0 }, counts.1); + } +} + +#[tokio::test] +async fn test_unknown_partition_target_fails_before_creating_output() { + let fixture = Fixture::new(PrimaryKeyEncoding::Dense, FormatType::Flat, 0).await; + let mut plan = fixture.plan(2); + plan.partition_rule = Arc::new( + MultiDimPartitionRule::try_new(vec!["tag_0".into()], vec![99], vec![], false).unwrap(), + ); + let (context, protection) = fixture.context(None); + let error = compact_regions(plan, context).await.err().unwrap(); + assert!( + format!("{error:?}").contains("Partition rule selected a region outside"), + "{error:?}" + ); + assert!(protection.files.lock().unwrap().is_empty()); +} + +/// A version group crossing reader batches with 32 schema-default columns. +async fn wide_source_fixture() -> (Fixture, MultiRegionCompactionPlan) { + use api::v1::SemanticType; + use datatypes::data_type::ConcreteDataType; + use datatypes::schema::{ColumnDefaultConstraint, ColumnSchema}; + use store_api::metadata::{ColumnMetadata, RegionMetadataBuilder}; + + let fixture = Fixture::with_source(PrimaryKeyEncoding::Dense, FormatType::Flat, |_| { + let batch = new_record_batch_with_custom_sequence(&["000", "series"], 0, 1024, 5); + let mut columns = batch.columns().to_vec(); + columns[3] = Arc::new(TimestampMillisecondArray::from(vec![0; 1024])); + vec![RecordBatch::try_new(batch.schema(), columns).unwrap()] + }) + .await; + let mut plan = fixture.plan(2); + let expressions = vec![ + col("field_0").lt(Value::UInt64(512)), + col("field_0").gt_eq(Value::UInt64(512)), + ]; + plan.partition_rule = Arc::new( + MultiDimPartitionRule::try_new( + vec!["field_0".into()], + vec![0, 1], + expressions.clone(), + false, + ) + .unwrap(), + ); + for (id, target) in &mut plan.targets { + let mut builder = RegionMetadataBuilder::from_existing((*target.metadata).clone()); + for column in 0..32 { + builder.push_column_metadata(ColumnMetadata { + column_id: 10 + column, + semantic_type: SemanticType::Field, + column_schema: ColumnSchema::new( + format!("wide_{column}"), + ConcreteDataType::uint64_datatype(), + false, + ) + .with_default_constraint(Some(ColumnDefaultConstraint::Value(Value::UInt64( + 1000 + column as u64, + )))) + .unwrap(), + }); + } + let mut metadata = builder.build().unwrap(); + metadata.set_partition_expr(Some( + expressions[id.region_sequence() as usize] + .as_json_str() + .unwrap(), + )); + target.metadata = Arc::new(metadata); + } + (fixture, plan) +} + +#[tokio::test] +async fn test_wide_version_group_routes_lazily_without_retaining_fragment_dictionaries() { + let (fixture, plan) = wide_source_fixture().await; + let (context, _) = fixture.context(None); + let counters = Arc::new(SourceCounters::default()); + let source = source::SharedSource::build( + &plan, + &context, + validate_plan(&plan).unwrap(), + counters.clone(), + ) + .await + .unwrap(); + let mut stream = source.batches(); + let mut next_row = 0; + while let Some(source::SourceEvent { region_id, batch }) = stream.try_next().await.unwrap() { + assert_eq!(39, batch.num_columns()); + let keys = batch + .column(primary_key_column_index(batch.num_columns())) + .as_any() + .downcast_ref::>() + .unwrap(); + // Regression R1-C1: a paused consumer must not retain one dictionary + // reference per future fragment. This is ownership, not an RSS metric. + assert!(Arc::strong_count(keys.values()) < 16); + let values = batch + .column_by_name("field_0") + .unwrap() + .as_any() + .downcast_ref::() + .unwrap(); + for row in 0..batch.num_rows() { + assert_eq!(next_row, values.value(row)); + assert_eq!((next_row / 512) as u32, region_id.region_sequence()); + for column in 0..32 { + let defaults = batch + .column_by_name(&format!("wide_{column}")) + .unwrap() + .as_any() + .downcast_ref::() + .unwrap(); + assert_eq!(0, defaults.null_count()); + assert_eq!(1000 + column as u64, defaults.value(row)); + } + next_row += 1; + } + } + assert_eq!(1024, next_row); + assert_eq!(1, counters.files.load(std::sync::atomic::Ordering::Relaxed)); + assert_eq!( + 1024, + counters.rows.load(std::sync::atomic::Ordering::Relaxed) + ); +} + +#[tokio::test] +async fn test_cancelling_between_routed_fragments_stops_the_source() { + let (fixture, plan) = wide_source_fixture().await; + let (context, _) = fixture.context(None); + let source = source::SharedSource::build( + &plan, + &context, + validate_plan(&plan).unwrap(), + Arc::new(SourceCounters::default()), + ) + .await + .unwrap(); + let mut stream = source.batches(); + assert!(stream.try_next().await.unwrap().is_some()); + context.cancellation.cancel(); + assert!(matches!( + stream.try_next().await, + Err(crate::error::Error::CompactionCancelled { .. }) + )); +} + +#[rstest::rstest] +#[case::metadata(false)] +#[case::actual_rows(true)] +#[tokio::test] +async fn test_cross_window_source_is_rejected_without_filtering_away_rows( + #[case] stale_metadata: bool, +) { + let fixture = Fixture::with_source(PrimaryKeyEncoding::Dense, FormatType::Flat, |_| { + let batch = new_record_batch_with_custom_sequence(&["000", "series"], 0, 2, 0); + let mut columns = batch.columns().to_vec(); + columns[3] = Arc::new(TimestampMillisecondArray::from(vec![0, 3_600_000])); + vec![RecordBatch::try_new(batch.schema(), columns).unwrap()] + }) + .await; + let mut plan = fixture.plan(1); + if stale_metadata { + plan.sources[0].time_range.1 = plan.sources[0].time_range.0; + } + let (context, protection) = fixture.context(None); + let error = compact_regions(plan, context).await.err().unwrap(); + assert!( + matches!( + error, + crate::error::Error::InvalidMultiRegionCompaction { .. } + ), + "{error:?}" + ); + assert!(protection.files.lock().unwrap().is_empty()); + let path = crate::sst::location::sst_file_path( + fixture.layer.table_dir(), + fixture.source.file_id(), + fixture.layer.path_type(), + ); + assert!(fixture.layer.object_store().exists(&path).await.unwrap()); +} + +#[tokio::test] +async fn test_negative_subsecond_timestamp_stays_in_its_half_open_window() { + let fixture = Fixture::with_source(PrimaryKeyEncoding::Dense, FormatType::Flat, |_| { + let batch = new_record_batch_with_custom_sequence(&["000", "series"], 0, 2, 0); + let mut columns = batch.columns().to_vec(); + columns[3] = Arc::new(TimestampMillisecondArray::from(vec![-3_600_000, -1])); + vec![RecordBatch::try_new(batch.schema(), columns).unwrap()] + }) + .await; + let mut plan = fixture.plan(1); + plan.window_start = -3600; + let output = fixture.compact(plan).await; + assert_eq!(2, output.stats.output_rows); + let mut times = Vec::new(); + for file in output.files.into_values().flatten() { + times.extend( + fixture + .read_output_rows(file, fixture.metadata.clone()) + .await + .into_iter() + .map(|row| row.1), + ); + } + assert_eq!(vec![-3_600_000, -1], times); +} + +#[tokio::test] +async fn test_equal_key_group_crosses_batches_and_preserves_opposite_target_admission_orders() { + fn versions(start: usize) -> Vec { + let batch = + new_record_batch_with_custom_sequence(&["000", "series"], start, start + 256, 0); + let mut columns = batch.columns().to_vec(); + columns[3] = Arc::new(TimestampMillisecondArray::from(vec![0; 256])); + vec![RecordBatch::try_new(batch.schema(), columns).unwrap()] + } + let fixture = + Fixture::with_source(PrimaryKeyEncoding::Dense, FormatType::Flat, |_| versions(0)).await; + let second = fixture.write_additional_source(versions(256)).await; + let mut plan = fixture.plan(2); + plan.sources.push(second.clone()); + // Both files put the same PK/time into both targets. Source order is not + // a valid version order: R0 installs F1 then F2, R1 installs F2 then F1. + let expressions = vec![ + partition::expr::PartitionExpr::new( + partition::expr::Operand::Expr(col("field_0").lt(Value::UInt64(128))), + partition::expr::RestrictedOp::Or, + partition::expr::Operand::Expr(col("field_0").gt_eq(Value::UInt64(384))), + ), + col("field_0") + .gt_eq(Value::UInt64(128)) + .and(col("field_0").lt(Value::UInt64(384))), + ]; + plan.partition_rule = Arc::new( + MultiDimPartitionRule::try_new( + vec!["field_0".into()], + vec![0, 1], + expressions.clone(), + false, + ) + .unwrap(), + ); + for (id, target) in &mut plan.targets { + let first_sequence = if id.region_sequence() == 0 { 11 } else { 22 }; + target + .inputs + .get_mut(&fixture.source.file_id()) + .unwrap() + .sequence = NonZeroU64::new(first_sequence); + let mut input = second.clone(); + input.sequence = NonZeroU64::new(33 - first_sequence); + target.inputs.insert(input.file_id(), input); + Arc::make_mut(&mut target.metadata).set_partition_expr(Some( + expressions[id.region_sequence() as usize] + .as_json_str() + .unwrap(), + )); + } + let targets = plan.targets.clone(); + let output = fixture.compact(plan).await; + assert_eq!(512, output.stats.output_rows); + for (id, files) in output.files { + let mut rows = Vec::new(); + for file in files { + assert_eq!(NonZeroU64::new(22), file.sequence); + let decoded = fixture + .read_output_rows(file, targets[&id].metadata.clone()) + .await; + rows.extend(decoded.into_iter().map(|row| { + let payload = row.4.unwrap(); + let expected = match (id.region_sequence(), payload < 256) { + (0, true) | (1, false) => 11, + _ => 22, + }; + assert_eq!(expected, row.2); + (row.2, payload) + })); + } + assert!(rows.windows(2).all(|pair| pair[0].0 >= pair[1].0)); + let mut payloads = rows.into_iter().map(|row| row.1).collect::>(); + payloads.sort(); + let expected = (0..512) + .filter(|value| { + if id.region_sequence() == 0 { + *value < 128 || *value >= 384 + } else { + (128..384).contains(value) + } + }) + .collect::>(); + assert_eq!(expected, payloads); + } +} + +/// Five overlapping sources share one window. Every timestamp has tied puts +/// and a tombstone; source-order tie breaking is deliberately not required. +fn overlapping_batches(source: u64) -> Vec { + (0..31) + .map(|series| { + let batch = new_record_batch_with_custom_sequence( + &[&format!("{series:03}"), "series"], + 0, + 512, + 5, + ); + let mut columns = batch.columns().to_vec(); + columns[2] = Arc::new(UInt64Array::from( + (0..512) + .map(|row| (row % 4 != 2).then_some(source * 1000 + row)) + .collect::>(), + )); + columns[3] = Arc::new(TimestampMillisecondArray::from( + (0..512).map(|row| row / 4).collect::>(), + )); + columns[6] = Arc::new(UInt8Array::from( + (0..512) + .map(|row| { + if row % 4 == 2 { + OpType::Delete as u8 + } else { + OpType::Put as u8 + } + }) + .collect::>(), + )); + RecordBatch::try_new(batch.schema(), columns).unwrap() + }) + .collect() +} + +async fn overlapping_fixture() -> (Fixture, MultiRegionCompactionPlan) { + let fixture = Fixture::with_source(PrimaryKeyEncoding::Dense, FormatType::Flat, |_| { + overlapping_batches(0) + }) + .await; + let mut plan = fixture.plan(3); + // Force rolling inside one window; a series must still stay in one SST. + plan.max_output_file_size = 1; + for source in 1..5 { + let file = fixture + .write_additional_source(overlapping_batches(source)) + .await; + for target in plan.targets.values_mut() { + target.inputs.insert(file.file_id(), file.clone()); + } + plan.sources.push(file); + } + for target in plan.targets.values_mut() { + for input in target.inputs.values_mut() { + input.sequence = NonZeroU64::new(777); + } + } + (fixture, plan) +} + +#[rstest::rstest] +#[case::range(false)] +#[case::multi_column(true)] +#[tokio::test] +async fn test_streaming_merge_preserves_overlapping_versions_and_field_routing( + #[case] multi_column: bool, +) { + let (fixture, mut plan) = overlapping_fixture().await; + if multi_column { + // A single primary key can route to different targets across sources + // and versions. Unmatched rows, including tombstones, go to region 0. + let expressions = vec![ + col("tag_0") + .lt(Value::String("010".into())) + .and(col("field_0").gt_eq(Value::UInt64(2000))), + col("tag_0").gt_eq(Value::String("010".into())).and( + col("field_0") + .gt_eq(Value::UInt64(0)) + .and(col("field_0").lt(Value::UInt64(2000))), + ), + ]; + plan.partition_rule = Arc::new( + MultiDimPartitionRule::try_new( + vec!["tag_0".into(), "field_0".into()], + vec![1, 2], + expressions.clone(), + false, + ) + .unwrap(), + ); + for (id, target) in &mut plan.targets { + let expression = id + .region_sequence() + .checked_sub(1) + .map(|index| expressions[index as usize].as_json_str().unwrap()); + Arc::make_mut(&mut target.metadata).set_partition_expr(expression); + } + } + let source_paths: HashSet<_> = plan + .sources + .iter() + .map(|file| { + crate::sst::location::sst_file_path( + fixture.layer.table_dir(), + file.file_id(), + fixture.layer.path_type(), + ) + }) + .collect(); + let targets = plan.targets.clone(); + let memory_limit = plan.memory_limit; + let (context, protection) = fixture.context(None); + let output = tokio::time::timeout(Duration::from_secs(60), compact_regions(plan, context)) + .await + .expect("bounded worker pipeline stalled") + .unwrap(); + assert_eq!(5, output.stats.source_files); + assert_eq!(5 * 31 * 512, output.stats.source_rows); + assert_eq!(output.stats.source_rows, output.stats.output_rows); + assert!(output.stats.estimated_memory_bytes <= memory_limit as u64); + assert!(output.stats.peak_group_bytes <= (memory_limit / 16) as u64); + assert!( + output.stats.peak_group_bytes > 0, + "retained equal-key groups were never charged" + ); + let expected_output_bytes: u64 = output + .files + .values() + .flatten() + .map(|file| file.file_size + file.index_file_size) + .sum(); + assert_eq!(expected_output_bytes, output.stats.output_bytes); + assert_eq!( + targets.keys().collect::>(), + output.files.keys().collect::>() + ); + common_telemetry::info!("multi_column={multi_column}, stats={:?}", output.stats); + let mut output_paths = HashSet::new(); + for (id, files) in output.files { + assert_eq!(files.len(), output.sst_infos[&id].len()); + assert!(files.len() > 1, "expected single-window SST rollover"); + for pair in files.windows(2) { + assert!( + pair[0].primary_key_max.as_ref().unwrap() + < pair[1].primary_key_min.as_ref().unwrap(), + "SST rollover split a series or reordered primary-key ranges" + ); + } + let file_count = files.len(); + let mut actual_rows = Vec::new(); + for (file, info) in files.into_iter().zip(&output.sst_infos[&id]) { + assert!(protection.files.lock().unwrap().contains(&file.file_id())); + assert_eq!(id, file.region_id); + assert_eq!(1, file.level); + assert_eq!(info.file_id, file.file_id); + assert_eq!(info.num_rows as u64, file.num_rows); + assert_eq!(info.file_size, file.file_size); + assert_eq!(info.time_range, file.time_range); + let file_window = file.time_range.0.value().div_euclid(3_600_000); + assert_eq!(file_window, file.time_range.1.value().div_euclid(3_600_000)); + let path = crate::sst::location::sst_file_path( + fixture.layer.table_dir(), + file.file_id(), + fixture.layer.path_type(), + ); + assert!( + !source_paths.contains(&path), + "output overwrote source {path}" + ); + assert!( + output_paths.insert(path.clone()), + "shared output file {path}" + ); + common_telemetry::info!( + "region={id}, window={file_window}, rows={}, file={path}", + file.num_rows + ); + let rows = fixture + .read_output_rows(file, targets[&id].metadata.clone()) + .await; + assert!( + rows.iter() + .all(|row| row.1.div_euclid(3_600_000) == file_window) + ); + actual_rows.extend(rows); + } + let mut expected = Vec::new(); + for series in 0..31 { + for tick in 0..128 { + for source in 0..5 { + for version in 0..4 { + let ordinal = tick * 4 + version; + let payload = (version != 2).then_some(source * 1000 + ordinal as u64); + // Independent oracle: do not reuse PartitionRule to + // compute the expected routing of the physical rows. + let owner = if multi_column { + if series < 10 && payload.is_some_and(|value| value >= 2000) { + 1 + } else if series >= 10 && payload.is_some_and(|value| value < 2000) { + 2 + } else { + 0 + } + } else if series < 10 { + 0 + } else if series < 21 { + 1 + } else { + 2 + }; + if owner != id.region_sequence() { + continue; + } + expected.push(( + series, + tick, + if id.region_sequence() == 0 { 5 } else { 777 }, + if version == 2 { + OpType::Delete as u8 + } else { + OpType::Put as u8 + }, + payload, + )); + } + } + } + } + // Check the actual order before comparing multisets. Equal full keys + // can interleave sources; unequal keys must remain ordered across SSTs. + for pair in actual_rows.windows(2) { + let key = |row: &TestRow| (row.0, row.1, std::cmp::Reverse(row.2)); + assert!(key(&pair[0]) <= key(&pair[1]), "unordered output for {id}"); + } + actual_rows.sort(); + expected.sort(); + assert_eq!(expected, actual_rows, "missing or changed rows for {id}"); + common_telemetry::info!( + "verified region={id}, files={file_count}, rows={}", + actual_rows.len() + ); + } + for path in source_paths { + assert!(fixture.layer.object_store().exists(&path).await.unwrap()); + } + assert_spill_cleaned(&fixture.env.path.path().join("spill")).await; +} + +async fn assert_spill_cleaned(path: &std::path::Path) { + // Stronger than cleanup: the streaming merge must never create this directory. + assert!( + !tokio::fs::try_exists(path).await.unwrap(), + "merge spill directory was created" + ); +} + +struct BlockIndexedSstWrite { + inner: oio::Writer, + started: Arc, +} + +impl oio::Write for BlockIndexedSstWrite { + async fn write(&mut self, buffer: mock::Buffer) -> mock::Result<()> { + self.inner.write(buffer).await?; + self.started.notify_one(); + futures::future::pending().await + } + + async fn close(&mut self) -> mock::Result { + self.inner.close().await + } + + async fn abort(&mut self) -> mock::Result<()> { + self.inner.abort().await + } +} + +fn add_fulltext_column(plan: &mut MultiRegionCompactionPlan) { + use datatypes::data_type::ConcreteDataType; + use datatypes::schema::{ + ColumnDefaultConstraint, ColumnSchema, FulltextAnalyzer, FulltextBackend, FulltextOptions, + }; + use store_api::metadata::{ColumnMetadata, RegionMetadataBuilder}; + let column = ColumnMetadata { + column_id: 10, + semantic_type: api::v1::SemanticType::Field, + column_schema: ColumnSchema::new("text", ConcreteDataType::string_datatype(), false) + .with_default_constraint(Some(ColumnDefaultConstraint::Value(Value::String( + "indexed text".into(), + )))) + .unwrap() + .with_fulltext_options(FulltextOptions::new_unchecked( + true, + FulltextAnalyzer::English, + false, + FulltextBackend::Tantivy, + 1, + 0.01, + )) + .unwrap(), + }; + for target in plan.targets.values_mut() { + let mut builder = RegionMetadataBuilder::from_existing((*target.metadata).clone()); + builder.push_column_metadata(column.clone()); + target.metadata = Arc::new(builder.build().unwrap()); + } +} + +struct FailIndexSibling { + protection: Arc, + fail: Arc, +} + +#[async_trait::async_trait] +impl SstWriteGuard for FailIndexSibling { + async fn before_create(&self, file_id: RegionFileId) -> Result<()> { + if file_id.region_id().region_sequence() == 1 { + self.fail.notified().await; + return InvalidMultiRegionCompactionSnafu { + reason: "injected indexed sibling failure", + } + .fail(); + } + self.protection.before_create(file_id).await + } +} + +#[rstest::rstest] +#[case::cancel(false)] +#[case::sibling_failure(true)] +#[tokio::test] +async fn test_interrupted_indexed_worker_cleans_tantivy_files(#[case] fail_sibling: bool) { + let mut fixture = Fixture::with_source(PrimaryKeyEncoding::Dense, FormatType::Flat, |_| { + ["000", "020"] + .into_iter() + .map(|tag| { + let rows = if tag == "000" { 1 } else { 262_144 }; + let batch = new_record_batch_with_custom_sequence(&[tag, "series"], 0, rows, 5); + let mut columns = batch.columns().to_vec(); + // Exceed both the Arrow writer's internal buffer and the object + // store chunk, forcing a write before EOF/index finish. + let mut rng = 0x1234_5678_9abc_def0_u64; + columns[2] = Arc::new(UInt64Array::from_iter_values((0..rows).map(|_| { + rng ^= rng << 13; + rng ^= rng >> 7; + rng ^= rng << 17; + rng + }))); + RecordBatch::try_new(batch.schema(), columns).unwrap() + }) + .collect() + }) + .await; + let started = Arc::new(tokio::sync::Notify::new()); + let notifying = started.clone(); + let layer = MockLayerBuilder::default() + .writer_factory(Arc::new(move |path, _, inner| { + if path.contains("1_0000000000/") && path.ends_with(".parquet") { + Box::new(BlockIndexedSstWrite { + inner, + started: notifying.clone(), + }) as oio::Writer + } else { + inner + } + })) + .build() + .unwrap(); + fixture.layer = Arc::new(AccessLayer::new( + fixture.layer.table_dir(), + fixture.layer.path_type(), + fixture.layer.object_store().clone().layer(layer), + fixture.layer.puffin_manager_factory().clone(), + fixture.layer.intermediate_manager().clone(), + )); + let mut plan = fixture.plan(2); + // R1 receives its first row before R0 blocks in object storage. This lets + // the sibling fail independently even though input is now consumed online. + let expressions = vec![ + col("tag_0").gt_eq(Value::String("010".into())), + col("tag_0").lt(Value::String("010".into())), + ]; + plan.partition_rule = Arc::new( + MultiDimPartitionRule::try_new( + vec!["tag_0".into()], + vec![0, 1], + expressions.clone(), + false, + ) + .unwrap(), + ); + for (id, target) in &mut plan.targets { + Arc::make_mut(&mut target.metadata).set_partition_expr(Some( + expressions[id.region_sequence() as usize] + .as_json_str() + .unwrap(), + )); + } + // Admission now includes both resident Tantivy writers and finish space. + plan.memory_limit = 256 * 1024 * 1024; + add_fulltext_column(&mut plan); + let (mut context, protection) = fixture.context(None); + let cancellation = context.cancellation.clone(); + let fail = Arc::new(tokio::sync::Notify::new()); + context.protection = Arc::new(FailIndexSibling { + protection: protection.clone(), + fail: fail.clone(), + }); + let execution = compact_regions(plan, context); + tokio::pin!(execution); + tokio::select! { + _ = started.notified() => {} + result = &mut execution => panic!("writer did not block: {}", result.err().map_or("success".into(), |error| error.to_string())), + _ = tokio::time::sleep(Duration::from_secs(60)) => panic!("indexed writer did not reach object storage"), + } + let protected = protection + .files + .lock() + .unwrap() + .iter() + .copied() + .collect::>(); + assert_eq!(1, protected.len()); + let file = protected[0]; + let intm_dir = fixture + .env + .path + .path() + .join("table-index/__intm") + .join(file.region_id().as_u64().to_string()) + .join(file.file_id().to_string()); + let mut entries = tokio::fs::read_dir(&intm_dir).await.unwrap(); + let mut tantivy_dirs = Vec::new(); + while let Some(entry) = entries.next_entry().await.unwrap() { + if entry.file_name().to_string_lossy().starts_with("fulltext-") { + assert!( + tokio::fs::try_exists(entry.path().join("meta.json")) + .await + .unwrap() + ); + tantivy_dirs.push(entry.path()); + } + } + assert_eq!( + 1, + tantivy_dirs.len(), + "the test must cancel AFTER Tantivy initialization" + ); + if fail_sibling { + fail.notify_one(); + } else { + cancellation.cancel(); + } + let error = tokio::time::timeout(Duration::from_secs(60), execution) + .await + .unwrap() + .err() + .unwrap(); + if fail_sibling { + assert!( + matches!(&error, crate::error::Error::InvalidMultiRegionCompaction { reason, .. } if reason == "injected indexed sibling failure"), + "{error:?}" + ); + } else { + assert!(matches!( + error, + crate::error::Error::CompactionCancelled { .. } + )); + } + tokio::time::timeout(Duration::from_secs(10), async { + for path in &tantivy_dirs { + while tokio::fs::try_exists(path).await.unwrap() { + tokio::time::sleep(Duration::from_millis(10)).await; + } + } + }) + .await + .expect("cancelled worker leaked Tantivy intermediate files"); + assert_spill_cleaned(&fixture.env.path.path().join("spill")).await; + // Attempt cleanup must not delete sources or protected SSTs owned by the caller. + for id in [fixture.source.file_id(), file] { + let path = crate::sst::location::sst_file_path( + fixture.layer.table_dir(), + id, + fixture.layer.path_type(), + ); + assert!(fixture.layer.object_store().exists(&path).await.unwrap()); + } +} + +struct CancelBeforeCreate(Arc); + +#[async_trait::async_trait] +impl SstWriteGuard for CancelBeforeCreate { + async fn before_create(&self, _file_id: RegionFileId) -> Result<()> { + self.0.cancel(); + // The coordinator must interrupt a worker waiting on external I/O, + // rather than waiting for its next cooperative batch check. + futures::future::pending().await + } +} + +#[tokio::test] +async fn test_cancelling_a_blocked_writer_preserves_sources_without_merge_spill() { + let (fixture, plan) = overlapping_fixture().await; + let sources = plan.sources.clone(); + let (mut context, _) = fixture.context(None); + context.protection = Arc::new(CancelBeforeCreate(context.cancellation.clone())); + let error = tokio::time::timeout(Duration::from_secs(60), compact_regions(plan, context)) + .await + .expect("cancellation did not interrupt the worker") + .err() + .unwrap(); + assert!(matches!( + error, + crate::error::Error::CompactionCancelled { .. } + )); + assert_spill_cleaned(&fixture.env.path.path().join("spill")).await; + for file in sources { + let path = crate::sst::location::sst_file_path( + fixture.layer.table_dir(), + file.file_id(), + fixture.layer.path_type(), + ); + assert!(fixture.layer.object_store().exists(&path).await.unwrap()); + } +} + +#[tokio::test] +async fn test_private_routing_annotations_do_not_shadow_user_columns() { + use datatypes::data_type::ConcreteDataType; + use datatypes::schema::{ColumnDefaultConstraint, ColumnSchema}; + use store_api::metadata::{ColumnMetadata, RegionMetadataBuilder}; + let fixture = Fixture::new(PrimaryKeyEncoding::Dense, FormatType::Flat, 0).await; + let mut plan = fixture.plan(2); + let expressions = vec![ + col("__compaction_region").lt(Value::UInt64(40)), + col("__compaction_region").gt_eq(Value::UInt64(40)), + ]; + plan.partition_rule = Arc::new( + MultiDimPartitionRule::try_new( + vec!["__compaction_region".into()], + vec![0, 1], + expressions.clone(), + false, + ) + .unwrap(), + ); + for (id, target) in &mut plan.targets { + let mut builder = RegionMetadataBuilder::from_existing((*target.metadata).clone()); + builder.push_column_metadata(ColumnMetadata { + column_id: 10, + semantic_type: api::v1::SemanticType::Field, + column_schema: ColumnSchema::new( + "__compaction_region", + ConcreteDataType::uint64_datatype(), + false, + ) + .with_default_constraint(Some(ColumnDefaultConstraint::Value(Value::UInt64(42)))) + .unwrap(), + }); + let mut metadata = builder.build().unwrap(); + metadata.set_partition_expr(Some( + expressions[id.region_sequence() as usize] + .as_json_str() + .unwrap(), + )); + target.metadata = Arc::new(metadata); + } + let target = plan.targets[&RegionId::new(1, 1)].metadata.clone(); + let output = fixture.compact(plan).await; + assert!(output.files[&RegionId::new(1, 0)].is_empty()); + assert_eq!(124, output.stats.output_rows); + for file in output.files[&RegionId::new(1, 1)].iter().cloned() { + for batch in fixture.read_output(file, target.clone()).await { + let values = batch + .column_by_name("__compaction_region") + .unwrap() + .as_any() + .downcast_ref::() + .unwrap(); + assert!(values.values().iter().all(|value| *value == 42)); + } + } +} + +#[rstest::rstest] +#[case::trusted_zero(true)] +#[case::legacy_override(false)] +#[tokio::test] +async fn test_zero_versions_follow_trust_and_legacy_override(#[case] trusted: bool) { + let fixture = Fixture::with_source(PrimaryKeyEncoding::Dense, FormatType::Flat, |_| { + vec![ + new_record_batch_with_custom_sequence(&["000", "series"], 0, 1, 0), + new_record_batch_with_custom_sequence(&["020", "series"], 0, 1, 7), + ] + }) + .await; + let mut plan = fixture.plan(2); + if trusted { + for target in plan.targets.values_mut() { + for input in target.inputs.values_mut() { + input.preserve_row_sequence = true; + } + } + } + let target = plan.targets[&RegionId::new(1, 0)].clone(); + let input = target.inputs[&fixture.source.file_id()].clone(); + let mut original = fixture + .layer + .read_sst(FileHandle::new(input, Arc::new(NoopFilePurger))) + .expected_metadata(Some(target.metadata.clone())) + .cache(CacheStrategy::Disabled) + .build() + .await + .unwrap() + .unwrap(); + let batch = original.next_record_batch().await.unwrap().unwrap(); + let sequences = batch + .column(sequence_column_index(batch.num_columns())) + .as_any() + .downcast_ref::() + .unwrap(); + assert_eq!( + 0, + sequences.value(0), + "the original target really observes version zero" + ); + if trusted { + let output = fixture.compact(plan).await; + let mut rows = Vec::new(); + for file in &output.files[&RegionId::new(1, 0)] { + assert!(file.preserve_row_sequence); + rows.extend( + fixture + .read_published_output_rows(file.clone(), target.metadata.clone()) + .await, + ); + } + assert_eq!( + vec![(0, 0, 0, OpType::Put as u8, Some(0))], + rows, + "trusted zero versions must survive publication" + ); + return; + } + let error = compact_regions(plan, fixture.context(None).0) + .await + .err() + .expect("must not publish an output that reads version zero as version100"); + assert!( + matches!(&error, crate::error::Error::InvalidMultiRegionCompaction { reason, .. } if reason.contains("zero output versions")), + "{error:?}" + ); + let path = crate::sst::location::sst_file_path( + fixture.layer.table_dir(), + fixture.source.file_id(), + fixture.layer.path_type(), + ); + assert!(fixture.layer.object_store().exists(&path).await.unwrap()); +} + +struct ObserveOnlineOutput { + protection: Arc, + counters: Arc, + expected_rows: u64, + observed: std::sync::atomic::AtomicBool, +} + +#[async_trait::async_trait] +impl SstWriteGuard for ObserveOnlineOutput { + async fn before_create(&self, file: RegionFileId) -> Result<()> { + use std::sync::atomic::Ordering; + if !self.observed.swap(true, Ordering::Relaxed) { + assert_eq!(0, self.counters.files.load(Ordering::Relaxed)); + assert!(self.counters.rows.load(Ordering::Relaxed) < self.expected_rows); + } + self.protection.before_create(file).await + } +} + +#[tokio::test] +async fn test_output_starts_before_the_shared_source_is_exhausted() { + let fixture = Fixture::with_source(PrimaryKeyEncoding::Dense, FormatType::Flat, |_| { + vec![new_record_batch_with_custom_sequence( + &["000", "series"], + 0, + 4096, + 0, + )] + }) + .await; + let plan = fixture.plan(1); + let (mut context, protection) = fixture.context(None); + let counters = Arc::new(SourceCounters::default()); + let observer = Arc::new(ObserveOnlineOutput { + protection, + counters: counters.clone(), + expected_rows: fixture.source.num_rows, + observed: std::sync::atomic::AtomicBool::new(false), + }); + context.protection = observer.clone(); + let source = source::SharedSource::build( + &plan, + &context, + validate_plan(&plan).unwrap(), + counters.clone(), + ) + .await + .unwrap(); + let output = worker::execute(plan, context, source, counters) + .await + .unwrap(); + assert_eq!(4096, output.stats.output_rows); + assert!(observer.observed.load(std::sync::atomic::Ordering::Relaxed)); +} + +#[tokio::test] +async fn test_invalid_target_options_are_rejected_before_creating_outputs() { + let fixture = Fixture::new(PrimaryKeyEncoding::Dense, FormatType::Flat, 0).await; + let mut plan = fixture.plan(2); + plan.targets + .get_mut(&RegionId::new(1, 1)) + .unwrap() + .options + .max_row_group_row_count = Some(0); + let (context, protection) = fixture.context(None); + let error = compact_regions(plan, context).await.err().unwrap(); + assert!( + matches!(error, crate::error::Error::InvalidRegionOptions { .. }), + "{error:?}" + ); + assert!(protection.files.lock().unwrap().is_empty()); +} + +#[tokio::test] +async fn test_all_resident_writers_are_admitted_before_creating_outputs() { + let fixture = Fixture::new(PrimaryKeyEncoding::Dense, FormatType::Flat, 0).await; + let mut plan = fixture.plan(32); + plan.memory_limit = 128 * 1024 * 1024; + let (context, protection) = fixture.context(None); + let error = compact_regions(plan, context).await.err().unwrap(); + assert!( + matches!(&error, crate::error::Error::MultiRegionCompactionResource { reason, .. } if reason.contains("minimum working set")), + "{error:?}" + ); + assert!(protection.files.lock().unwrap().is_empty()); +} + +#[rstest::rstest] +#[case::sync(crate::config::IndexBuildMode::Sync)] +#[case::async_mode(crate::config::IndexBuildMode::Async)] +#[tokio::test] +async fn test_admission_includes_each_tantivy_creator_even_in_async_mode( + #[case] mode: crate::config::IndexBuildMode, +) { + let fixture = Fixture::new(PrimaryKeyEncoding::Dense, FormatType::Flat, 0).await; + let mut baseline = fixture.plan(2); + baseline.memory_limit = 64 * 1024 * 1024; + assert_eq!(124, fixture.compact(baseline).await.stats.output_rows); + let mut plan = fixture.plan(2); + plan.memory_limit = 64 * 1024 * 1024; + add_fulltext_column(&mut plan); + let (mut context, protection) = fixture.context(None); + Arc::make_mut(&mut context.config).index.build_mode = mode; + let error = compact_regions(plan, context).await.err().unwrap(); + assert!( + matches!(&error, crate::error::Error::MultiRegionCompactionResource { reason, .. } if reason.contains("minimum working set")), + "{error:?}" + ); + assert!(protection.files.lock().unwrap().is_empty()); +} + +#[tokio::test] +async fn test_oversized_equal_key_group_fails_without_partial_outputs_or_spill() { + let fixture = Fixture::with_source(PrimaryKeyEncoding::Dense, FormatType::Flat, |_| { + let batch = new_record_batch_with_custom_sequence(&["000", "series"], 0, 262_144, 0); + let mut columns = batch.columns().to_vec(); + columns[3] = Arc::new(TimestampMillisecondArray::from(vec![0; 262_144])); + vec![RecordBatch::try_new(batch.schema(), columns).unwrap()] + }) + .await; + let (context, protection) = fixture.context(None); + let error = compact_regions(fixture.plan(1), context) + .await + .err() + .unwrap(); + assert!( + matches!(&error, crate::error::Error::MultiRegionCompactionResource { reason, .. } if reason.contains("Equal-key version group")), + "{error:?}" + ); + assert!(protection.files.lock().unwrap().is_empty()); + assert_spill_cleaned(&fixture.env.path.path().join("spill")).await; +} + +#[rstest::rstest] +#[case::encoder("encoder")] +#[case::metadata("metadata")] +#[tokio::test] +async fn test_limited_writer_fails_instead_of_publishing_over_budget(#[case] kind: &'static str) { + let fixture = Fixture::new(PrimaryKeyEncoding::Dense, FormatType::Flat, 0).await; + let plan = fixture.plan(1); + let (context, protection) = fixture.context(None); + let source = new_flat_source_from_record_batches(vec![source_batch(&fixture.metadata, 0, 100)]); + let mut limits = memory::MemoryLimits::new(&plan, source.schema()).unwrap(); + match kind { + "encoder" => limits.writer.working_bytes = 1, + "metadata" => limits.writer.metadata_bytes = 1, + _ => unreachable!(), + } + let error = writer::TargetWriter::new( + &plan.targets[&RegionId::new(1, 0)], + &context, + &limits, + plan.max_output_file_size, + ) + .write(source) + .await + .err() + .unwrap(); + assert!( + matches!(&error, crate::error::Error::SstWriteMemoryExceeded { kind: actual, .. } if *actual == kind), + "{error:?}" + ); + assert_eq!(1, protection.files.lock().unwrap().len()); +} + +#[tokio::test] +async fn test_cancelled_execution_does_not_create_output() { + let fixture = Fixture::new(PrimaryKeyEncoding::Dense, FormatType::Flat, 0).await; + let (context, protection) = fixture.context(None); + context.cancellation.cancel(); + assert!(matches!( + compact_regions(fixture.plan(2), context).await, + Err(crate::error::Error::CompactionCancelled { .. }) + )); + assert!(protection.files.lock().unwrap().is_empty()); +} + +/// Mutations applied to a valid plan to reach each `validate_plan` rejection. +#[derive(Clone, Copy, Debug)] +enum InvalidPlan { + NoSources, + TinyBudget, + ZeroFileSize, + ZeroWindow, + NegativeWindow, + OversizedControl, + NoTargets, + WindowOverflow, + UnalignedWindow, + SourceOutsideWindow, + DuplicateSource, + ForeignTable, + MissingInput, + InconsistentSchema, +} + +#[rstest::rstest] +#[case(InvalidPlan::NoSources, "sources must not be empty")] +#[case(InvalidPlan::TinyBudget, "memory_limit must be at least 1 MiB")] +#[case( + InvalidPlan::ZeroFileSize, + "max_output_file_size must be greater than 0" +)] +#[case(InvalidPlan::ZeroWindow, "window_seconds must be greater than 0")] +#[case(InvalidPlan::NegativeWindow, "window_seconds must be greater than 0")] +#[case(InvalidPlan::OversizedControl, "control state exceeds the task budget")] +#[case(InvalidPlan::NoTargets, "No routing targets")] +#[case(InvalidPlan::WindowOverflow, "Task window overflow")] +#[case(InvalidPlan::UnalignedWindow, "not aligned")] +#[case(InvalidPlan::SourceOutsideWindow, "not wholly inside the task window")] +#[case( + InvalidPlan::DuplicateSource, + "unique source files from one physical table" +)] +#[case( + InvalidPlan::ForeignTable, + "unique source files from one physical table" +)] +#[case( + InvalidPlan::MissingInput, + "effective metadata of every selected source" +)] +#[case(InvalidPlan::InconsistentSchema, "consistent physical-table snapshot")] +#[tokio::test] +async fn test_invalid_plan_is_rejected_before_creating_outputs( + #[case] invalid: InvalidPlan, + #[case] reason: &'static str, +) { + let fixture = Fixture::new(PrimaryKeyEncoding::Dense, FormatType::Flat, 0).await; + let mut plan = fixture.plan(2); + match invalid { + InvalidPlan::NoSources => plan.sources.clear(), + InvalidPlan::TinyBudget => plan.memory_limit = 1024 * 1024 - 1, + InvalidPlan::ZeroFileSize => plan.max_output_file_size = 0, + InvalidPlan::ZeroWindow => plan.window_seconds = 0, + InvalidPlan::NegativeWindow => plan.window_seconds = -1, + InvalidPlan::OversizedControl => { + plan.memory_limit = 1024 * 1024; + let source = plan.sources[0].clone(); + let extra = plan.memory_limit / std::mem::size_of::() + 1; + plan.sources = vec![source; extra]; + } + InvalidPlan::NoTargets => plan.targets.clear(), + InvalidPlan::WindowOverflow => { + plan.window_start = i64::MAX - plan.window_seconds + 1; + } + InvalidPlan::UnalignedWindow => plan.window_start += 1, + InvalidPlan::SourceOutsideWindow => { + plan.sources[0].time_range = ( + Timestamp::new_second(plan.window_seconds), + Timestamp::new_second(plan.window_seconds + 1), + ); + } + InvalidPlan::DuplicateSource => { + let source = plan.sources[0].clone(); + plan.sources.push(source); + } + InvalidPlan::ForeignTable => { + plan.sources[0].region_id = RegionId::new(2, 0); + } + InvalidPlan::MissingInput => { + let target = plan.targets.values_mut().next().unwrap(); + target.inputs.clear(); + } + InvalidPlan::InconsistentSchema => { + let target = plan.targets.values_mut().next().unwrap(); + Arc::make_mut(&mut target.metadata).column_metadatas.pop(); + } + } + let (context, protection) = fixture.context(None); + let error = tokio::time::timeout(Duration::from_secs(30), compact_regions(plan, context)) + .await + .expect("invalid plan hung instead of failing") + .err() + .expect("invalid plan must be rejected"); + assert!( + format!("{error:?}").contains(reason), + "expected `{reason}`, got {error:?}" + ); + assert!(protection.files.lock().unwrap().is_empty()); +} diff --git a/src/mito2/src/compaction/multi_region/worker.rs b/src/mito2/src/compaction/multi_region/worker.rs new file mode 100644 index 00000000000..b52bda6367c --- /dev/null +++ b/src/mito2/src/compaction/multi_region/worker.rs @@ -0,0 +1,156 @@ +// 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. + +//! Incremental sinks for the already merged stream. All resident writers are +//! admitted together. No writer holds a work permit while waiting for input, +//! and no sink waits for another source head to consume its channel. + +use std::collections::BTreeMap; +use std::sync::Arc; +use std::sync::atomic::Ordering; + +use datatypes::arrow::record_batch::RecordBatch; +use futures::stream::FuturesUnordered; +use futures::{StreamExt, TryStreamExt}; +use snafu::{OptionExt, ResultExt, ensure}; +use store_api::storage::RegionId; +use tokio::sync::mpsc; +use tokio_util::task::AbortOnDropHandle; + +use crate::compaction::multi_region::source::SharedSource; +use crate::compaction::multi_region::{ + MultiRegionCompactionContext, MultiRegionCompactionOutput, MultiRegionCompactionPlan, + MultiRegionCompactionStats, SourceCounters, writer, +}; +use crate::error::{InvalidMultiRegionCompactionSnafu, Result}; +use crate::read::FlatSource; + +/// Transport closure is failure; only the dispatcher can signal successful EOF. +enum Message { + Batch(RecordBatch), + Finish, +} + +pub(crate) async fn execute( + plan: MultiRegionCompactionPlan, + context: MultiRegionCompactionContext, + source: Arc, + counters: Arc, +) -> Result { + let _cancel_on_drop = source.cancel_on_drop(); + let plan = Arc::new(plan); + let context = Arc::new(context); + let mut senders = BTreeMap::new(); + let mut workers = FuturesUnordered::new(); + for &id in plan.targets.keys() { + let (sender, mut receiver) = mpsc::channel(1); + senders.insert(id, sender); + let schema = source.schema(); + let limits = source.limits.clone(); + let plan = plan.clone(); + let context = context.clone(); + workers.push(AbortOnDropHandle::new(common_runtime::spawn_compact( + async move { + let stream = async_stream::try_stream! { + while let Message::Batch(batch) = receiver + .recv() + .await + .context(InvalidMultiRegionCompactionSnafu { + reason: "Source channel closed without Finish", + })? + { + yield batch; + } + }; + let input = FlatSource::new_stream(schema, Box::pin(stream)); + let (files, infos) = writer::TargetWriter::new( + &plan.targets[&id], + &context, + &limits, + plan.max_output_file_size, + ) + .write(input) + .await?; + Ok::<_, crate::error::Error>((id, files, infos)) + }, + ))); + } + let scan = dispatch(source.clone(), senders); + tokio::pin!(scan); + let mut scan_finished = false; + let mut output = MultiRegionCompactionOutput { + files: BTreeMap::new(), + sst_infos: BTreeMap::new(), + stats: MultiRegionCompactionStats::default(), + }; + while !scan_finished || !workers.is_empty() { + tokio::select! { + biased; + Some(result) = workers.next(), if !workers.is_empty() => { + let (id, files, infos) = result.context(crate::error::JoinSnafu)??; + output.stats.output_rows += files + .iter() + .map(|file| file.num_rows) + .sum::(); + output.stats.output_bytes += files + .iter() + .map(|file| file.file_size + file.index_file_size) + .sum::(); + output.files.insert(id, files); + output.sst_infos.insert(id, infos); + } + result = &mut scan, if !scan_finished => { + result?; + scan_finished = true; + } + } + } + output.stats.source_files = counters.files.load(Ordering::Relaxed); + output.stats.source_rows = counters.rows.load(Ordering::Relaxed); + output.stats.source_store_page_bytes = counters.store_page_bytes.load(Ordering::Relaxed); + output.stats.estimated_memory_bytes = source.limits.estimated; + output.stats.peak_group_bytes = source.peak_group_bytes(); + ensure!( + output.stats.source_files == plan.sources.len() as u64 + && output.stats.output_rows == output.stats.source_rows, + InvalidMultiRegionCompactionSnafu { + reason: "Multi-region compaction did not account for every source row" + } + ); + Ok(output) +} + +async fn dispatch( + source: Arc, + senders: BTreeMap>, +) -> Result<()> { + let mut batches = source.batches(); + while let Some(event) = batches.try_next().await? { + let sender = senders + .get(&event.region_id) + .context(InvalidMultiRegionCompactionSnafu { + reason: "Unknown routing target", + })?; + send(sender, Message::Batch(event.batch)).await; + } + for sender in senders.values() { + send(sender, Message::Finish).await; + } + Ok(()) +} + +async fn send(sender: &mpsc::Sender, message: Message) { + if sender.send(message).await.is_err() { + // The supervisor reports the writer's original error, not a racing + // channel-closed error. It also aborts siblings on failure or drop. + futures::future::pending::<()>().await; + } +} diff --git a/src/mito2/src/compaction/multi_region/writer.rs b/src/mito2/src/compaction/multi_region/writer.rs new file mode 100644 index 00000000000..3c266584167 --- /dev/null +++ b/src/mito2/src/compaction/multi_region/writer.rs @@ -0,0 +1,238 @@ +// 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 std::num::NonZeroU64; +use std::sync::Arc; + +use common_base::readable_size::ReadableSize; +use partition::expr::PartitionExpr; +use snafu::{ResultExt, ensure}; +use store_api::codec::PrimaryKeyEncoding; + +use crate::access_layer::{Metrics, OperationType, SstWriteRequest, WriteType}; +use crate::compaction::multi_region::memory::{self, MemoryLimits}; +use crate::compaction::multi_region::{MultiRegionCompactionContext, MultiRegionTarget}; +use crate::config::MemoryThreshold; +use crate::error::{ComputeArrowSnafu, Result}; +use crate::read::FlatSource; +use crate::sst::FormatType; +use crate::sst::file::FileMeta; +use crate::sst::parquet::metadata::extract_primary_key_range; +use crate::sst::parquet::parallel_writer::EncodeRuntime; +use crate::sst::parquet::{SstInfo, WriteOptions}; + +pub(crate) struct TargetWriter<'a> { + target: &'a MultiRegionTarget, + context: &'a MultiRegionCompactionContext, + limits: &'a MemoryLimits, + max_file_size: usize, + sequence: Option, + preserve_row_sequence: bool, +} + +impl<'a> TargetWriter<'a> { + pub(crate) fn new( + target: &'a MultiRegionTarget, + context: &'a MultiRegionCompactionContext, + limits: &'a MemoryLimits, + max_file_size: usize, + ) -> Self { + let sequence = crate::sst::file::known_max_input_sequence(target.inputs.values()); + let preserve_row_sequence = target.options.preserve_row_sequence + && target + .inputs + .values() + .all(|file| file.is_effective_target_sequence_trusted(target.metadata.region_id)); + Self { + target, + context, + limits, + max_file_size, + sequence, + preserve_row_sequence, + } + } + + pub(crate) async fn write(&self, source: FlatSource) -> Result<(Vec, Vec)> { + ensure!( + !self.context.cancellation.is_cancelled(), + crate::error::CompactionCancelledSnafu + ); + let request = self.request(source)?; + let mut metrics = Metrics::new(WriteType::Compaction); + let infos = self + .context + .access_layer + .write_sst_with_guard( + request, + &self.options(), + &mut metrics, + crate::sst::parquet::writer::SstWriteContext { + guard: self.context.protection.clone(), + limits: self.limits.writer, + }, + ) + .await?; + metrics.observe(); + let expression = + crate::region::parse_partition_expr(self.target.metadata.partition_expr.as_deref())?; + let files = infos + .iter() + .map(|info| { + self.validate_sequence(info)?; + self.file_metadata(info, expression.clone()) + }) + .collect::>>()?; + Ok((files, infos.into_iter().collect())) + } + + fn request(&self, source: FlatSource) -> Result { + let config = &self.context.config; + let mut inverted = config.inverted_index.clone(); + inverted.mem_threshold_on_create = self.index_threshold(inverted.mem_threshold_on_create()); + let mut fulltext = config.fulltext_index.clone(); + fulltext.mem_threshold_on_create = + self.index_threshold(Some(fulltext.mem_threshold_on_create())); + let mut bloom = config.bloom_filter_index.clone(); + bloom.mem_threshold_on_create = self.index_threshold(bloom.mem_threshold_on_create()); + let source = output_projection(self.target, source, self.context.cancellation.clone())?; + Ok(SstWriteRequest { + op_type: OperationType::Compact, + metadata: self.target.metadata.clone(), + source, + cache_manager: self.context.cache.clone(), + max_sequence: None, + sst_write_format: self.target.options.sst_format.unwrap_or( + if config.default_flat_format { + FormatType::Flat + } else { + FormatType::PrimaryKey + }, + ), + preserve_row_sequence: self.preserve_row_sequence, + index_options: self.target.options.index_options.clone(), + index_config: config.index.clone(), + inverted_index_config: inverted, + fulltext_index_config: fulltext, + bloom_filter_index_config: bloom, + }) + } + + fn index_threshold(&self, configured: Option) -> MemoryThreshold { + MemoryThreshold::Size(ReadableSize( + configured + .unwrap_or(self.limits.index) + .min(self.limits.index) as u64, + )) + } + + fn options(&self) -> WriteOptions { + WriteOptions { + write_buffer_size: ReadableSize(self.limits.batch as u64), + max_file_size: Some(self.max_file_size), + // Capped so each admitted encoder stays within the task budget; see + // [memory::MAX_ROW_GROUP_SIZE]. + row_group_size: self + .target + .options + .row_group_size() + .min(memory::MAX_ROW_GROUP_SIZE), + float_field_encoding: self.target.options.float_field_encoding, + // Every resident encoder and its finish workspace are admitted together. + encode_parallelism: 1, + encode_runtime: EncodeRuntime::Compact, + } + } + + fn validate_sequence(&self, info: &SstInfo) -> Result<()> { + // Routing nonzero versions elsewhere can turn a mixed native input into + // an all-zero output. A legacy reader must not replace those zeros with + // the positive file bound; neither trust nor the bound may be fabricated. + ensure!( + self.preserve_row_sequence + || self.sequence.is_none() + || !info.file_metadata.as_ref().is_some_and(|footer| { + crate::sst::parquet::format::need_override_sequence(footer) + }), + crate::error::InvalidMultiRegionCompactionSnafu { + reason: "Legacy sequence override would change zero output versions" + } + ); + Ok(()) + } + + fn file_metadata( + &self, + info: &SstInfo, + partition_expr: Option, + ) -> Result { + let range = info + .file_metadata + .as_ref() + .and_then(|footer| extract_primary_key_range(footer, &self.target.metadata)); + Ok(FileMeta { + region_id: self.target.metadata.region_id, + file_id: info.file_id, + time_range: info.time_range, + level: 1, + file_size: info.file_size, + max_row_group_uncompressed_size: info.max_row_group_uncompressed_size, + available_indexes: info.index_metadata.build_available_indexes(), + indexes: info.index_metadata.build_indexes()?, + index_file_size: info.index_metadata.file_size, + index_version: 0, + num_rows: info.num_rows as u64, + num_row_groups: info.num_row_groups, + sequence: self.sequence, + partition_expr, + num_series: info.num_series, + primary_key_min: range.as_ref().map(|(min, _)| min.clone()), + primary_key_max: range.map(|(_, max)| max), + preserve_row_sequence: self.preserve_row_sequence, + }) + } +} + +fn output_projection( + target: &MultiRegionTarget, + mut source: FlatSource, + cancellation: Arc, +) -> Result { + let projection: Vec<_> = source + .schema() + .fields() + .iter() + .enumerate() + .filter(|(_, field)| { + target.metadata.primary_key_encoding != PrimaryKeyEncoding::Sparse + || !target.metadata.primary_key.iter().any(|id| { + target + .metadata + .column_by_id(*id) + .is_some_and(|column| column.column_schema.name == *field.name()) + }) + }) + .map(|(index, _)| index) + .collect(); + let schema = Arc::new( + source + .schema() + .project(&projection) + .context(ComputeArrowSnafu)?, + ); + let stream = async_stream::try_stream! { + while let Some(batch) = source.next_batch().await? { + if cancellation.is_cancelled() { Err(crate::error::CompactionCancelledSnafu.build())?; } + yield batch.project(&projection).context(ComputeArrowSnafu)?; + } + }; + Ok(FlatSource::new_stream(schema, Box::pin(stream))) +} diff --git a/src/mito2/src/compaction/picker.rs b/src/mito2/src/compaction/picker.rs index f841e8aff07..d0f32212eb5 100644 --- a/src/mito2/src/compaction/picker.rs +++ b/src/mito2/src/compaction/picker.rs @@ -27,7 +27,7 @@ use crate::compaction::window::WindowedCompactionPicker; use crate::compaction::{CompactionOutput, SerializedCompactionOutput}; use crate::error::Result; use crate::region::options::{CompactionOptions, MergeMode, RegionOptions}; -use crate::sst::file::{FileHandle, FileMeta}; +use crate::sst::file::{self, FileHandle, FileMeta}; use crate::sst::file_purger::FilePurger; use crate::sst::version::LevelMeta; @@ -188,6 +188,7 @@ pub(super) fn get_expired_ssts( levels .iter() + .filter(|level| level.level < file::LEVEL_SHARED) .flat_map(|l| l.get_expired_files(&now, &ttl).into_iter()) .collect() } diff --git a/src/mito2/src/compaction/scheduler.rs b/src/mito2/src/compaction/scheduler.rs index 7f2f79a78f5..44886f6ccdb 100644 --- a/src/mito2/src/compaction/scheduler.rs +++ b/src/mito2/src/compaction/scheduler.rs @@ -12,6 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. +mod coordinator; pub(crate) mod history; mod local; mod planning; @@ -24,21 +25,27 @@ use api::v1::region::compact_request; use common_base::Plugins; use common_memory_manager::OnExhaustedPolicy; use common_meta::key::SchemaMetadataManagerRef; +#[cfg(test)] +use common_recordbatch::filter::MetadataFilter; use common_telemetry::{debug, error, info, warn}; use common_time::range::TimestampRange; +pub(crate) use coordinator::{CompactionCoordinator, ReadyUnit}; +#[cfg(test)] +use datafusion_common::ScalarValue; pub(crate) use planning::CompactionPickFinished; pub use planning::CompactionRequest; #[cfg(test)] pub(crate) use planning::pick_automatic_for_test; -pub(crate) use state::CompactionExecution; +pub(crate) use state::{CompactionExecution, CompactionState, CompactionStateRef}; use state::{CompactionStatus, CompactionTrigger, DdlExecution, PendingCompaction}; +#[cfg(test)] +use store_api::compaction_task::{self, CompactionTaskEntry}; use store_api::storage::RegionId; use tokio::sync::mpsc::Sender; use crate::access_layer::AccessLayerRef; use crate::cache::CacheManagerRef; use crate::compaction::memory_manager::CompactionMemoryManager; -use crate::compaction::task::MAX_PARALLEL_COMPACTION; use crate::config::MitoConfig; use crate::error::{ CompactionCancelledSnafu, Error, ManualCompactionAlreadyRunningSnafu, RegionClosedSnafu, @@ -47,11 +54,34 @@ use crate::error::{ use crate::region::version::VersionControlRef; use crate::region::{ManifestContextRef, RegionLeaderState, RegionRoleState}; use crate::request::{DdlRequest, OptionOutputTx, SenderDdlRequest, WorkerRequestWithTime}; -#[cfg(test)] use crate::schedule::RequestCancelResult; -use crate::schedule::scheduler::SchedulerRef; use crate::worker::WorkerListener; +/// Outcome of cancelling one live compaction task by its exact task identity. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum CancelCompactionResult { + /// Cancellation was requested; completion is asynchronous. + CancelIssued, + /// The task is already cancelling. + AlreadyCancelling, + /// The task has crossed its non-cancellable commit boundary. + TooLateToCancel, + /// The task is no longer present on this region. + NotFound, + /// This engine or execution mode does not support cancellation. + Unsupported, +} + +impl From for CancelCompactionResult { + fn from(result: RequestCancelResult) -> Self { + match result { + RequestCancelResult::CancelIssued => Self::CancelIssued, + RequestCancelResult::AlreadyCancelling => Self::AlreadyCancelling, + RequestCancelResult::TooLateToCancel => Self::TooLateToCancel, + } + } +} + /// Internal testing switch to prevent SST compaction from changing file layouts /// during query regression tests. This is not a public configuration option. const DISABLE_COMPACTION_ENV: &str = "GREPTIME_DISABLE_COMPACTION"; @@ -88,7 +118,7 @@ pub(crate) struct CompactionScheduler { /// Initialized from [`DISABLE_COMPACTION`] and fixed for the scheduler's lifetime /// in production; unit tests can override it without changing the process environment. disable_compaction: bool, - scheduler: SchedulerRef, + coordinator: Arc, /// All loaded regions, including idle regions and regions executing DDLs. region_status: HashMap, /// Request sender of the worker that this scheduler belongs to. @@ -154,7 +184,7 @@ impl CompactionScheduler { /// same worker so region state transitions remain serialized. #[allow(clippy::too_many_arguments)] pub(crate) fn new( - scheduler: SchedulerRef, + coordinator: Arc, request_sender: Sender, cache_manager: CacheManagerRef, engine_config: Arc, @@ -165,7 +195,7 @@ impl CompactionScheduler { ) -> Self { Self { disable_compaction: *DISABLE_COMPACTION, - scheduler, + coordinator, region_status: HashMap::new(), request_sender, cache_manager, @@ -183,6 +213,7 @@ impl CompactionScheduler { &mut self, version_control: &VersionControlRef, access_layer: &AccessLayerRef, + shared_state: &CompactionStateRef, ) { let region_id = version_control.region_id(); if let Some(status) = self.region_status.get_mut(®ion_id) { @@ -191,10 +222,22 @@ impl CompactionScheduler { } status.on_failure(Arc::new(RegionClosedSnafu { region_id }.build())); } - self.region_status.insert( - region_id, - CompactionStatus::new(region_id, version_control.clone(), access_layer.clone()), - ); + let mut status = + CompactionStatus::new(region_id, version_control.clone(), access_layer.clone()); + status.shared_state = shared_state.clone(); + self.region_status.insert(region_id, status); + } + + /// Cancels an exact live identity, checking the pending slot before the active cycle. + pub(crate) fn cancel_task( + &mut self, + region_id: RegionId, + task_id: &str, + ) -> CancelCompactionResult { + let Some(status) = self.region_status.get_mut(®ion_id) else { + return CancelCompactionResult::NotFound; + }; + status.cancel_task(task_id) } /// Reports active work rather than the existence of a resident region record. @@ -235,7 +278,7 @@ impl CompactionScheduler { OptionOutputTx::none(), manifest_ctx, schema_metadata_manager, - 1, // Default for automatic compaction + self.engine_config.max_background_compactions, None, ) } @@ -625,6 +668,7 @@ impl CompactionScheduler { // was fetched above. let plan_id = Self::next_plan_id(&mut self.next_plan_id); status.start_picking_with_trigger(plan_id, CompactionTrigger::Manual); + status.active.task_state = status.pending_task_state.take(); self.dispatch_compaction_planning( plan_id, request, @@ -701,7 +745,7 @@ impl CompactionScheduler { manifest_ctx, self.listener.clone(), schema_metadata_manager, - MAX_PARALLEL_COMPACTION, + self.engine_config.max_background_compactions, Some(status.pick_history.clone()), ); // Bump the counter through a disjoint field borrow so the `status` @@ -771,6 +815,7 @@ impl CompactionScheduler { if let Some(mut status) = self.region_status.remove(®ion_id) { status.on_failure(err); } + self.coordinator.forget_region(region_id); } /// Fails a cycle without discarding the loaded region's registration. @@ -780,6 +825,22 @@ impl CompactionScheduler { } } + /// Completes task-specific cancellation without discarding another pending request. + fn finish_cancelled_compaction( + &mut self, + region_id: RegionId, + manifest: &ManifestContextRef, + schemas: SchemaMetadataManagerRef, + ) -> CompactionTransition { + if let Some(status) = self.region_status.get_mut(®ion_id) + && status.finish_task_cancellation() + { + self.handle_pending_compaction_request(region_id, manifest, schemas); + return CompactionTransition::NoAction; + } + CompactionTransition::from_pending_ddls(self.finish_compaction_on_cancel(region_id)) + } + /// Returns the cycle to idle and records any DDL handoff in the same resident entry. fn finish_compaction_on_cancel(&mut self, region_id: RegionId) -> Vec { let Some(status) = self.region_status.get_mut(®ion_id) else { @@ -891,10 +952,41 @@ impl Drop for CompactionScheduler { for (region_id, mut status) in self.region_status.drain() { // We are shutting down so notify all pending tasks. status.on_failure(Arc::new(RegionClosedSnafu { region_id }.build())); + self.coordinator.forget_region(region_id); } } } +impl CompactionScheduler { + /// Reads the same published task state as engine queries. + #[cfg(test)] + pub(crate) fn inspect_tasks( + &self, + filters: &MetadataFilter, + node_id: Option, + ) -> Vec { + let mut entries = Vec::new(); + for (region_id, status) in &self.region_status { + if !filters.matches(|name| match name { + compaction_task::REGION_ID => Some(ScalarValue::UInt64(Some(region_id.as_u64()))), + compaction_task::TABLE_ID => Some(ScalarValue::UInt32(Some(region_id.table_id()))), + compaction_task::NODE_ID => Some(ScalarValue::UInt64(node_id)), + _ => None, + }) { + continue; + } + let (active, pending) = CompactionState::current(&status.shared_state); + for task in active.into_iter().chain(pending) { + let entry = task.snapshot(node_id); + if entry.matches(filters) { + entries.push(entry); + } + } + } + entries + } +} + #[cfg(test)] #[path = "scheduler_test.rs"] mod tests; diff --git a/src/mito2/src/compaction/scheduler/coordinator.rs b/src/mito2/src/compaction/scheduler/coordinator.rs new file mode 100644 index 00000000000..775813a70e8 --- /dev/null +++ b/src/mito2/src/compaction/scheduler/coordinator.rs @@ -0,0 +1,480 @@ +// 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. + +#[cfg(test)] +#[path = "coordinator_test.rs"] +mod tests; + +use std::collections::{BTreeSet, HashMap, VecDeque}; +use std::future::Future; +use std::pin::Pin; +use std::sync::{Arc, Mutex, MutexGuard, Weak}; +use std::task::{Context, Poll}; +use std::time::Instant; + +use common_telemetry::{debug, error}; +use futures::FutureExt; +use store_api::storage::RegionId; +use tokio::sync::Notify; + +use crate::error::{InvalidSchedulerStateSnafu, Result}; +use crate::metrics::{ + COMPACTION_ADMISSION_WAIT, COMPACTION_ADMITTED_UNITS, COMPACTION_READY_UNITS, +}; +use crate::schedule::CancellableTaskState; +use crate::schedule::scheduler::{Job, LocalScheduler, SchedulerRef}; + +/// Prepared work consumed on submission to the coordinator, preventing repeated +/// admission of the same unit. Its task owns the execution ID, cancellation state +/// and input leases. +pub(crate) struct ReadyUnit { + /// Time the unit became ready; feeds [`COMPACTION_ADMISSION_WAIT`]. + queued_at: Instant, + /// Cancellation state shared with the unit's task and the region worker. + state: CancellableTaskState, + /// Immutable merge-work estimate; zero for metadata-only expiration. + input_bytes: u64, + /// Execution future that owns the reserved input leases. + job: Job, + /// Dispatched after `job` and its resources are dropped for accepted units, + /// including withdrawal, executor rejection, panic and shutdown draining. + /// Rejection by a closed coordinator drops this future without running it. + completion: Job, +} + +impl ReadyUnit { + /// Creates ready work whose job owns the reserved inputs. + /// + /// Successful submission to [`CompactionCoordinator::schedule`] transfers + /// completion handling to the coordinator. If submission fails, neither + /// future is run, and the caller must finish its own bookkeeping. + pub(crate) fn new( + state: CancellableTaskState, + input_bytes: u64, + job: Job, + completion: Job, + ) -> Self { + Self { + queued_at: Instant::now(), + state, + input_bytes, + job, + completion, + } + } + + fn release(self) { + drop(self.job); + common_runtime::spawn_global(self.completion); + } +} + +/// Engine-wide compaction admission, in front of the generic FIFO executor. +/// Only admitted jobs enter that executor, so its queue cannot hide contenders. +pub(crate) struct CompactionCoordinator { + /// Executor that runs admitted units. [`Self::new_local`] derives its runner + /// count from the same value as `capacity`. + executor: SchedulerRef, + /// Maximum number of units holding capacity at once, including units the + /// executor has not polled yet. Clamped to at least one. + capacity: usize, + /// Admission accounting shared by every region worker. [`Self::lock`] + /// deliberately ignores poisoning because an unwind leaves the accounting + /// consistent. + state: Mutex, + /// Signal that wakes [`Self::stop`] when `running` or the ready index changes. + drained: Notify, +} + +/// Admission accounting shared by every region worker. +#[derive(Default)] +struct CoordinatorState { + /// Per-region service and ready units. Idle regions stay here until they are + /// unloaded, so batch boundaries cannot erase their service debt. + regions: HashMap, + /// Iteration scales with current ready regions, not a hash table's peak capacity. + /// Idle regions retain service debt in `regions` without participating in admission. + ready_regions: BTreeSet, + /// Units holding capacity from admission through their released future, + /// including work that was authorized but never polled. + running: usize, + /// Set by [`CompactionCoordinator::stop`]; later submissions are rejected. + closed: bool, + /// Non-recursive dispatch guard: only the current drainer admits and submits. + dispatching: bool, + /// Monotonic floor of observed [`RegionQueue::service`], in the same + /// half-byte unit. It clamps a region that slept through a busy period. + virtual_time: u128, + /// Global admission tick. A larger value means a later admission; it breaks + /// service ties and is unrelated to the WAL or row `sequence`. + sequence: u64, +} + +/// One region's ready units and accumulated service. +struct RegionQueue { + /// Prepared units in fair-picker order. Admission pops the front. + ready: VecDeque, + /// Units of this region currently holding capacity. + running: usize, + /// Weighted service consumed so far, in half-byte units: each admission adds + /// its charge, and only work refunded before its first poll is subtracted. + service: u128, + /// [`CoordinatorState::sequence`] of this region's last admission. Service + /// ties go to the region whose last admission is older. + last_served: u64, + /// Set by [`CompactionCoordinator::forget_region`]; the entry is pruned once + /// it has no ready or running work. + retired: bool, +} + +/// The executor owns this future from admission until all task resources exit. +/// Drop ordering also covers rejection, panic and shutdown, not only success. +struct AdmittedUnit { + job: Option, + completion: Option, + state: CancellableTaskState, + coordinator: Weak, + region_id: RegionId, + /// Immutable charge, including admission-time weight; refunded only before first poll. + charged_cost: u128, + started: bool, +} + +impl std::fmt::Debug for CompactionCoordinator { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + let state = self.lock(); + f.debug_struct("CompactionCoordinator") + .field("capacity", &self.capacity) + .field("running", &state.running) + .field("regions", &state.regions.len()) + .finish() + } +} + +impl CompactionCoordinator { + /// Builds a coordinator over `executor` with an independent capacity. + /// + /// Production code should prefer [`Self::new_local`], which derives both + /// numbers from one value; the admission premise only holds while no more + /// units are admitted than the executor can run at once. + pub(crate) fn new(executor: SchedulerRef, capacity: usize) -> Self { + Self { + executor, + capacity: capacity.max(1), + state: Mutex::new(CoordinatorState::default()), + drained: Notify::new(), + } + } + + /// Builds a coordinator whose executor runs at most `concurrency` units. + /// + /// Capacity and runner count come from the same value, so admitted work can + /// never wait in the executor's FIFO behind already-admitted contenders. + pub(crate) fn new_local(concurrency: usize) -> Self { + let concurrency = concurrency.max(1); + Self::new(Arc::new(LocalScheduler::new(concurrency)), concurrency) + } + + fn lock(&self) -> MutexGuard<'_, CoordinatorState> { + self.state + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + } + + /// Accepts a bounded batch's ready work, not an unbounded discovered backlog. + /// + /// # Errors + /// Returns an error if shutdown has started. The rejected unit's job and + /// completion are dropped without running; the caller handles the error. + pub(crate) fn schedule(self: &Arc, region_id: RegionId, unit: ReadyUnit) -> Result<()> { + { + let mut state = self.lock(); + if state.closed { + return InvalidSchedulerStateSnafu.fail(); + } + // A cancelled manual unit can still be in the worker's pending + // list when cancellation withdraws its coordinator-visible siblings. + if unit.state.is_cancelled() { + drop(state); + unit.release(); + return Ok(()); + } + let service = state.virtual_time; + let queue = state + .regions + .entry(region_id) + .or_insert_with(|| RegionQueue { + ready: VecDeque::new(), + running: 0, + service, + last_served: 0, + retired: false, + }); + queue.retired = false; + // Idle periods cannot bank unlimited credit against active regions. + if queue.ready.is_empty() { + queue.service = queue.service.max(service); + } + queue.ready.push_back(unit); + state.ready_regions.insert(region_id); + COMPACTION_READY_UNITS.inc(); + } + self.dispatch(); + Ok(()) + } + + /// Withdraws cancelled queued work without waiting for an execution slot. + /// Only the owning worker can cancel a unit; a reopened region's new units + /// have different cancellation state and are not affected by an old drop. + pub(crate) fn cancel_pending(self: &Arc, region_id: RegionId) { + let cancelled = { + let mut state = self.lock(); + let Some(queue) = state.regions.get_mut(®ion_id) else { + return; + }; + let mut cancelled = Vec::new(); + let mut ready = VecDeque::new(); + for unit in queue.ready.drain(..) { + if unit.state.is_cancelled() { + cancelled.push(unit); + } else { + ready.push_back(unit); + } + } + queue.ready = ready; + if queue.ready.is_empty() { + state.ready_regions.remove(®ion_id); + } + state.prune(region_id); + cancelled + }; + for unit in cancelled { + Self::withdraw(unit); + } + self.drained.notify_one(); + } + + /// Keeps service debt between batches, but not after the region is unloaded. + /// In-flight old work can drain before its accounting entry is reclaimed. + pub(crate) fn forget_region(&self, region_id: RegionId) { + let mut state = self.lock(); + if let Some(queue) = state.regions.get_mut(®ion_id) { + queue.retired = true; + } + state.prune(region_id); + } + + /// Drains the admission queue before stopping its executor. Workers remain + /// alive to acknowledge apply while these jobs drain. + pub(crate) async fn stop(&self) -> Result<()> { + self.lock().closed = true; + loop { + let notified = self.drained.notified(); + let drained = { + let state = self.lock(); + state.running == 0 && state.ready_regions.is_empty() + }; + if drained { + break; + } + notified.await; + } + self.executor.stop(true).await + } + + fn dispatch(self: &Arc) { + { + let mut state = self.lock(); + if state.dispatching { + return; + } + state.dispatching = true; + } + loop { + let next = { + let mut state = self.lock(); + let next = (state.running < self.capacity) + .then(|| state.admit()) + .flatten(); + if next.is_none() { + state.dispatching = false; + } + next + }; + let Some((region_id, unit, charged_cost)) = next else { + break; + }; + let admitted = AdmittedUnit::new(self, region_id, unit, charged_cost); + // Rejection drops the future and returns its credit/resources. The + // existing Released path reports a missing terminal result as failure. + if let Err(err) = self.executor.schedule(Box::pin(admitted)) { + error!(err; "Failed to submit admitted compaction for region {}", region_id); + } + } + } + + fn release(self: &Arc, region_id: RegionId, refund: u128) { + { + let mut state = self.lock(); + state.running -= 1; + if let Some(queue) = state.regions.get_mut(®ion_id) { + queue.running -= 1; + queue.service = queue.service.saturating_sub(refund); + } + state.prune(region_id); + } + self.drained.notify_one(); + // dispatching serializes drainers without holding a lock across executor + // submission. In particular, synchronous rejection cannot recurse here. + self.dispatch(); + } + + fn withdraw(unit: ReadyUnit) { + COMPACTION_READY_UNITS.dec(); + unit.release(); + } +} + +impl Drop for CompactionCoordinator { + fn drop(&mut self) { + let state = self + .state + .get_mut() + .unwrap_or_else(std::sync::PoisonError::into_inner); + for queue in state.regions.values_mut() { + for unit in queue.ready.drain(..) { + Self::withdraw(unit); + } + } + } +} + +impl CoordinatorState { + /// Least-served selection charges bytes at admission, including jobs that + /// have not started. A backlog can boost weight by at most two; no region can + /// obtain unlimited weight. Positive byte cost prevents zero-sized work from + /// monopolizing ties. Queue order retains the region's fair picker priority. + fn admit(&mut self) -> Option<(RegionId, ReadyUnit, u128)> { + let region_id = self + .ready_regions + .iter() + .filter_map(|id| self.regions.get(id).map(|queue| (id, queue))) + .min_by_key(|(id, q)| (q.service, q.last_served, **id)) + .map(|(id, _)| *id)?; + let queue = self.regions.get_mut(®ion_id)?; + let weight = if queue.ready.len() > 1 { 2 } else { 1 }; + let unit = queue.ready.pop_front()?; + if queue.ready.is_empty() { + self.ready_regions.remove(®ion_id); + } + COMPACTION_READY_UNITS.dec(); + COMPACTION_ADMITTED_UNITS.inc(); + self.virtual_time = self.virtual_time.max(queue.service); + let charged_cost = charge(unit.input_bytes, weight); + queue.service = queue.service.saturating_add(charged_cost); + self.sequence = self.sequence.wrapping_add(1); + queue.last_served = self.sequence; + queue.running += 1; + self.running += 1; + debug!( + "Admit compaction unit: region={}, input_bytes={}, weight={}, service={}, ready={}, admitted={}", + region_id, + unit.input_bytes, + weight, + queue.service, + queue.ready.len(), + queue.running, + ); + Some((region_id, unit, charged_cost)) + } + + fn prune(&mut self, region_id: RegionId) { + if self + .regions + .get(®ion_id) + .is_some_and(|q| q.retired && q.running == 0 && q.ready.is_empty()) + { + self.regions.remove(®ion_id); + } + } +} + +fn charge(bytes: u64, weight: u128) -> u128 { + // Half-byte units avoid rounding a small task's cost down to zero. + u128::from(bytes.max(1)) * 2 / weight +} + +impl AdmittedUnit { + fn new( + coordinator: &Arc, + region_id: RegionId, + unit: ReadyUnit, + charged_cost: u128, + ) -> Self { + COMPACTION_ADMISSION_WAIT.observe(unit.queued_at.elapsed().as_secs_f64()); + let job = Box::pin(async move { + if let Err(panic) = std::panic::AssertUnwindSafe(unit.job).catch_unwind().await { + error!( + "Compaction executor panicked: {}", + crate::compaction::format_panic_reason(panic.as_ref()) + ); + } + }); + Self { + job: Some(job), + completion: Some(unit.completion), + state: unit.state, + coordinator: Arc::downgrade(coordinator), + region_id, + charged_cost, + started: false, + } + } +} + +impl Future for AdmittedUnit { + type Output = (); + + fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> { + if !self.started && self.state.is_cancelled() { + return Poll::Ready(()); + } + self.started = true; + let Some(job) = self.job.as_mut() else { + return Poll::Ready(()); + }; + let poll = job.as_mut().poll(cx); + if poll.is_ready() { + // A completed future stays completed if the executor polls it again. + drop(self.job.take()); + } + poll + } +} + +impl Drop for AdmittedUnit { + fn drop(&mut self) { + // This ordering is essential even when the executor rejects the future + // before its first poll: Released must never precede input lease release. + drop(self.job.take()); + COMPACTION_ADMITTED_UNITS.dec(); + if let Some(coordinator) = self.coordinator.upgrade() { + let refund = if self.started { 0 } else { self.charged_cost }; + coordinator.release(self.region_id, refund); + } + if let Some(completion) = self.completion.take() { + common_runtime::spawn_global(completion); + } + } +} diff --git a/src/mito2/src/compaction/scheduler/coordinator_test.rs b/src/mito2/src/compaction/scheduler/coordinator_test.rs new file mode 100644 index 00000000000..84bc5120501 --- /dev/null +++ b/src/mito2/src/compaction/scheduler/coordinator_test.rs @@ -0,0 +1,534 @@ +// 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::{AtomicBool, AtomicUsize, Ordering}; +use std::time::Duration; + +use tokio::sync::{Semaphore, mpsc}; + +use super::*; +use crate::schedule::scheduler::{LocalScheduler, Scheduler}; + +/// Controls the executor boundary, not the policy or region state under test. +#[derive(Default)] +struct ManualExecutor { + jobs: Mutex>, + reject: AtomicBool, +} + +impl ManualExecutor { + async fn run_next(&self) { + let job = self.jobs.lock().unwrap().pop_front().unwrap(); + job.await; + } + + fn len(&self) -> usize { + self.jobs.lock().unwrap().len() + } +} + +#[async_trait::async_trait] +impl Scheduler for ManualExecutor { + fn schedule(&self, job: Job) -> Result<()> { + if self.reject.load(Ordering::Relaxed) { + return InvalidSchedulerStateSnafu.fail(); + } + self.jobs.lock().unwrap().push_back(job); + Ok(()) + } + + async fn stop(&self, _: bool) -> Result<()> { + assert_eq!(0, self.len()); + Ok(()) + } +} + +fn unit(bytes: u64, id: u64, started: &mpsc::UnboundedSender) -> ReadyUnit { + let started = started.clone(); + ReadyUnit::new( + CancellableTaskState::new(), + bytes, + Box::pin(async move { + started.send(id).unwrap(); + }), + Box::pin(async {}), + ) +} + +async fn recv(rx: &mut mpsc::UnboundedReceiver) -> T { + tokio::time::timeout(Duration::from_secs(5), rx.recv()) + .await + .unwrap() + .unwrap() +} + +#[tokio::test] +async fn test_single_region_borrows_all_slots_without_exceeding_global_capacity() { + let coordinator = Arc::new(CompactionCoordinator::new_local(4)); + let running = Arc::new(AtomicUsize::new(0)); + let permits = Arc::new(Semaphore::new(0)); + let (started, mut rx) = mpsc::unbounded_channel(); + for id in 0..12 { + let running = running.clone(); + let permits = permits.clone(); + let started = started.clone(); + coordinator + .schedule( + RegionId::from_u64(1), + ReadyUnit::new( + CancellableTaskState::new(), + 100, + Box::pin(async move { + assert!(running.fetch_add(1, Ordering::SeqCst) < 4); + started.send(id).unwrap(); + permits.acquire().await.unwrap().forget(); + running.fetch_sub(1, Ordering::SeqCst); + }), + Box::pin(async {}), + ), + ) + .unwrap(); + } + for _ in 0..4 { + recv(&mut rx).await; + } + assert_eq!(4, running.load(Ordering::SeqCst)); + assert!(rx.try_recv().is_err()); + permits.add_permits(12); + coordinator.stop().await.unwrap(); + assert_eq!(0, running.load(Ordering::SeqCst)); + assert_eq!(8, rx.len()); +} + +#[tokio::test] +async fn test_late_region_is_not_hidden_behind_an_existing_fifo_backlog() { + let executor = Arc::new(ManualExecutor::default()); + let coordinator = Arc::new(CompactionCoordinator::new(executor.clone(), 4)); + let (tx, mut rx) = mpsc::unbounded_channel(); + let a = RegionId::from_u64(1); + let b = RegionId::from_u64(2); + for id in 0..8 { + coordinator.schedule(a, unit(10, id, &tx)).unwrap(); + } + assert_eq!(4, executor.len()); + coordinator.schedule(b, unit(10, 100, &tx)).unwrap(); + for _ in 0..5 { + executor.run_next().await; + } + assert_eq!( + (0..4).chain([100]).collect::>(), + (0..5).map(|_| rx.try_recv().unwrap()).collect::>() + ); + // Once B drains, A resumes using every slot it has work for. + assert_eq!(4, executor.len()); + for _ in 0..4 { + executor.run_next().await; + } + coordinator.stop().await.unwrap(); +} + +#[tokio::test] +async fn test_backlog_weight_cap_limits_service_boost() { + // Oracle for the capped backlog weight. After region A is served once, its + // next batch is already queued while a six-unit region B backlog advances: + // B must get exactly two admissions before A returns. A constant weight of + // one returns A after the first B unit, while an uncapped weight drains the + // whole B backlog first. + let executor = Arc::new(ManualExecutor::default()); + let coordinator = Arc::new(CompactionCoordinator::new(executor.clone(), 1)); + let (tx, mut rx) = mpsc::unbounded_channel(); + let a = RegionId::from_u64(1); + let b = RegionId::from_u64(2); + coordinator.schedule(a, unit(100, 1, &tx)).unwrap(); + for id in 10..16 { + coordinator.schedule(b, unit(100, id, &tx)).unwrap(); + } + for id in 2..5 { + coordinator.schedule(a, unit(100, id, &tx)).unwrap(); + } + executor.run_next().await; + assert_eq!(1, recv(&mut rx).await); + let mut started = Vec::new(); + for _ in 0..9 { + executor.run_next().await; + started.push(recv(&mut rx).await); + } + assert_eq!(vec![10, 11, 2, 12, 3, 13, 4, 14, 15], started); + assert_eq!(0, executor.len()); + coordinator.stop().await.unwrap(); +} + +#[tokio::test] +async fn test_zero_byte_work_pays_minimum_service() { + // Oracle for the minimum positive charge: a zero-byte backlog must still + // accrue service, so region A returns after two B admissions. Dropping the + // minimum, or scaling the weight without a cap, makes those units free and + // drains the whole B backlog first. + let executor = Arc::new(ManualExecutor::default()); + let coordinator = Arc::new(CompactionCoordinator::new(executor.clone(), 1)); + let (tx, mut rx) = mpsc::unbounded_channel(); + let a = RegionId::from_u64(1); + let b = RegionId::from_u64(2); + coordinator.schedule(a, unit(1, 1, &tx)).unwrap(); + executor.run_next().await; + assert_eq!(1, recv(&mut rx).await); + coordinator.schedule(a, unit(1, 2, &tx)).unwrap(); + for id in 10..20 { + coordinator.schedule(b, unit(0, id, &tx)).unwrap(); + } + coordinator.schedule(a, unit(1, 3, &tx)).unwrap(); + executor.run_next().await; + assert_eq!(2, recv(&mut rx).await); + let mut started = Vec::new(); + for _ in 0..11 { + executor.run_next().await; + started.push(recv(&mut rx).await); + } + assert_eq!(vec![10, 11, 3, 12, 13, 14, 15, 16, 17, 18, 19], started); + assert_eq!(0, executor.len()); + coordinator.stop().await.unwrap(); +} + +#[tokio::test] +async fn test_fairness_accounts_for_bytes_instead_of_task_counts() { + let executor = Arc::new(ManualExecutor::default()); + let coordinator = Arc::new(CompactionCoordinator::new(executor.clone(), 1)); + let (tx, mut rx) = mpsc::unbounded_channel(); + let a = RegionId::from_u64(1); + let b = RegionId::from_u64(2); + coordinator.schedule(a, unit(100, 1, &tx)).unwrap(); + coordinator.schedule(a, unit(100, 2, &tx)).unwrap(); + for id in 10..30 { + coordinator.schedule(b, unit(1, id, &tx)).unwrap(); + } + executor.run_next().await; + assert_eq!(1, recv(&mut rx).await); + for expected in 10..30 { + executor.run_next().await; + assert_eq!(expected, recv(&mut rx).await); + } + executor.run_next().await; + assert_eq!(2, recv(&mut rx).await); + coordinator.stop().await.unwrap(); +} + +#[tokio::test] +async fn test_idle_region_service_is_clamped_to_virtual_time() { + // Oracle for the idle floor. Region A is served once, then sleeps while the + // busy region B advances virtual time past A's stale service. When A returns + // with a three-unit batch, its debt must start at that floor, so B's last + // queued unit interleaves after one A unit instead of after all three. + let executor = Arc::new(ManualExecutor::default()); + let coordinator = Arc::new(CompactionCoordinator::new(executor.clone(), 1)); + let (tx, mut rx) = mpsc::unbounded_channel(); + let a = RegionId::from_u64(1); + let b = RegionId::from_u64(2); + coordinator.schedule(a, unit(100, 1, &tx)).unwrap(); + for id in 10..16 { + coordinator.schedule(b, unit(100, id, &tx)).unwrap(); + } + executor.run_next().await; + assert_eq!(1, recv(&mut rx).await); + for expected in 10..14 { + executor.run_next().await; + assert_eq!(expected, recv(&mut rx).await); + } + for id in [2, 3, 4] { + coordinator.schedule(a, unit(100, id, &tx)).unwrap(); + } + let mut started = Vec::new(); + for _ in 0..5 { + executor.run_next().await; + started.push(recv(&mut rx).await); + } + assert_eq!(vec![14, 2, 15, 3, 4], started); + assert_eq!(0, executor.len()); + coordinator.stop().await.unwrap(); +} + +#[tokio::test] +async fn test_unpolled_cancellation_refunds_service_before_next_admission() { + let executor = Arc::new(ManualExecutor::default()); + let coordinator = Arc::new(CompactionCoordinator::new(executor.clone(), 1)); + let (tx, mut rx) = mpsc::unbounded_channel(); + let a = RegionId::from_u64(1); + let b = RegionId::from_u64(2); + let first = unit(1000, 1, &tx); + let cancelled = first.state.clone(); + coordinator.schedule(a, first).unwrap(); + coordinator.schedule(a, unit(10, 2, &tx)).unwrap(); + coordinator.schedule(b, unit(10, 10, &tx)).unwrap(); + coordinator.schedule(b, unit(10, 11, &tx)).unwrap(); + cancelled.request_cancel(); + executor.run_next().await; + assert!(rx.try_recv().is_err()); + for expected in [10, 2, 11] { + executor.run_next().await; + assert_eq!(expected, recv(&mut rx).await); + } + coordinator.stop().await.unwrap(); +} + +struct DropCount(Arc); + +impl Drop for DropCount { + fn drop(&mut self) { + self.0.fetch_add(1, Ordering::SeqCst); + } +} + +#[rstest::rstest] +#[case::queued(false, false)] +#[case::authorized_not_polled(true, false)] +#[case::cancelled_before_submission(false, true)] +#[tokio::test] +async fn test_cancelled_unit_releases_resources_before_notification_without_running( + #[case] admitted: bool, + #[case] initially_cancelled: bool, +) { + let executor = Arc::new(ManualExecutor::default()); + let coordinator = Arc::new(CompactionCoordinator::new(executor.clone(), 1)); + let a = RegionId::from_u64(1); + let b = RegionId::from_u64(2); + let (started, mut starts) = mpsc::unbounded_channel(); + if !admitted { + coordinator.schedule(a, unit(1, 1, &started)).unwrap(); + } + let dropped = Arc::new(AtomicUsize::new(0)); + let guard = DropCount(dropped.clone()); + let state = CancellableTaskState::new(); + if initially_cancelled { + state.request_cancel(); + } + let (completed, mut completions) = mpsc::unbounded_channel(); + coordinator + .schedule( + b, + ReadyUnit::new( + state.clone(), + 100, + Box::pin(async move { + let _guard = guard; + started.send(2).unwrap(); + }), + Box::pin(async move { + completed.send(dropped.load(Ordering::SeqCst)).unwrap(); + }), + ), + ) + .unwrap(); + state.request_cancel(); + coordinator.cancel_pending(b); + if admitted { + executor.run_next().await; + } + assert_eq!(1, recv(&mut completions).await); + assert!(starts.try_recv().is_err()); + if !admitted { + executor.run_next().await; + } + coordinator.stop().await.unwrap(); +} + +#[tokio::test] +async fn test_executor_rejection_drains_queued_work_without_recursion_or_credit_leaks() { + let executor = Arc::new(ManualExecutor::default()); + let coordinator = Arc::new(CompactionCoordinator::new(executor.clone(), 1)); + let (tx, _rx) = mpsc::unbounded_channel(); + let region = RegionId::from_u64(1); + coordinator.schedule(region, unit(1, 0, &tx)).unwrap(); + let dropped = Arc::new(AtomicUsize::new(0)); + let polled = Arc::new(AtomicUsize::new(0)); + let (completed, mut completions) = mpsc::unbounded_channel(); + for id in 0..128 { + let guard = DropCount(dropped.clone()); + let completed = completed.clone(); + let polled = polled.clone(); + coordinator + .schedule( + region, + ReadyUnit::new( + CancellableTaskState::new(), + 1, + Box::pin(async move { + let _guard = guard; + polled.fetch_add(1, Ordering::SeqCst); + }), + Box::pin(async move { + completed.send(id).unwrap(); + }), + ), + ) + .unwrap(); + } + executor.reject.store(true, Ordering::Relaxed); + executor.run_next().await; + for _ in 0..128 { + recv(&mut completions).await; + } + assert_eq!(128, dropped.load(Ordering::SeqCst)); + assert_eq!(0, polled.load(Ordering::SeqCst)); + assert_eq!(0, executor.len()); + assert_eq!(0, coordinator.lock().running); + coordinator.stop().await.unwrap(); +} + +#[tokio::test] +async fn test_job_panic_does_not_lose_completion_or_the_executor_slot() { + let coordinator = Arc::new(CompactionCoordinator::new( + Arc::new(LocalScheduler::new(1)), + 1, + )); + let (completed, mut rx) = mpsc::unbounded_channel(); + let done = completed.clone(); + coordinator + .schedule( + RegionId::from_u64(1), + ReadyUnit::new( + CancellableTaskState::new(), + 1, + Box::pin(async { + panic!("executor panic fixture"); + }), + Box::pin(async move { + done.send(1).unwrap(); + }), + ), + ) + .unwrap(); + coordinator + .schedule(RegionId::from_u64(2), unit(1, 2, &completed)) + .unwrap(); + let mut results = [recv(&mut rx).await, recv(&mut rx).await]; + results.sort_unstable(); + assert_eq!([1, 2], results); + coordinator.stop().await.unwrap(); + assert!( + coordinator + .schedule(RegionId::from_u64(1), unit(1, 3, &completed)) + .is_err() + ); +} + +#[tokio::test] +async fn test_service_debt_survives_a_region_batch_boundary() { + let executor = Arc::new(ManualExecutor::default()); + let coordinator = Arc::new(CompactionCoordinator::new(executor.clone(), 1)); + let (tx, mut rx) = mpsc::unbounded_channel(); + let a = RegionId::from_u64(1); + let b = RegionId::from_u64(2); + coordinator.schedule(a, unit(100, 1, &tx)).unwrap(); + for id in 10..30 { + coordinator.schedule(b, unit(1, id, &tx)).unwrap(); + } + executor.run_next().await; + assert_eq!(1, recv(&mut rx).await); + // A has no active/ready unit between its batches, but must not erase its debt. + coordinator.schedule(a, unit(100, 2, &tx)).unwrap(); + for expected in (10..30).chain([2]) { + executor.run_next().await; + assert_eq!(expected, recv(&mut rx).await); + } + coordinator.forget_region(a); + coordinator.forget_region(b); + assert!(coordinator.lock().regions.is_empty()); + coordinator.stop().await.unwrap(); +} + +#[tokio::test] +async fn test_old_cancellation_does_not_withdraw_a_reopened_regions_unit() { + let executor = Arc::new(ManualExecutor::default()); + let coordinator = Arc::new(CompactionCoordinator::new(executor.clone(), 1)); + let (tx, mut rx) = mpsc::unbounded_channel(); + let region = RegionId::from_u64(1); + coordinator + .schedule(RegionId::from_u64(2), unit(1, 0, &tx)) + .unwrap(); + let old = unit(1, 1, &tx); + let old_state = old.state.clone(); + coordinator.schedule(region, old).unwrap(); + coordinator.forget_region(region); + coordinator.schedule(region, unit(1, 2, &tx)).unwrap(); + old_state.request_cancel(); + coordinator.cancel_pending(region); + for expected in [0, 2] { + executor.run_next().await; + assert_eq!(expected, recv(&mut rx).await); + } + assert_eq!(0, executor.len()); + coordinator.stop().await.unwrap(); +} + +#[tokio::test] +async fn test_expiration_only_work_does_not_charge_removed_sst_bytes() { + use crate::compaction::picker::PickerOutput; + use crate::compaction::test_util::new_file_handle_with_size_and_sequence; + use crate::compaction::unit::CompactionUnit; + use store_api::storage::FileId; + + let file = new_file_handle_with_size_and_sequence(FileId::random(), 0, 1, 1, 0, 1 << 40); + let expiration = CompactionUnit::from_picker(PickerOutput { + expired_ssts: vec![file], + ..Default::default() + }) + .unwrap() + .pop() + .unwrap(); + let executor = Arc::new(ManualExecutor::default()); + let coordinator = Arc::new(CompactionCoordinator::new(executor.clone(), 1)); + let (tx, mut rx) = mpsc::unbounded_channel(); + let a = RegionId::from_u64(1); + let b = RegionId::from_u64(2); + coordinator + .schedule(a, unit(expiration.estimated_input_bytes(), 1, &tx)) + .unwrap(); + coordinator.schedule(a, unit(10, 2, &tx)).unwrap(); + coordinator.schedule(b, unit(10, 10, &tx)).unwrap(); + coordinator.schedule(b, unit(10, 11, &tx)).unwrap(); + // Removing a TB of expired files must not defer A behind all of B's merges. + for expected in [1, 10, 2, 11] { + executor.run_next().await; + assert_eq!(expected, recv(&mut rx).await); + } + coordinator.stop().await.unwrap(); +} + +#[tokio::test] +async fn test_cancelled_empty_queue_can_reenter_admission_without_losing_debt() { + let executor = Arc::new(ManualExecutor::default()); + let coordinator = Arc::new(CompactionCoordinator::new(executor.clone(), 1)); + let (tx, mut rx) = mpsc::unbounded_channel(); + let a = RegionId::from_u64(1); + let b = RegionId::from_u64(2); + coordinator.schedule(a, unit(100, 1, &tx)).unwrap(); + let queued = unit(100, 2, &tx); + let state = queued.state.clone(); + coordinator.schedule(a, queued).unwrap(); + state.request_cancel(); + coordinator.cancel_pending(a); + coordinator.schedule(b, unit(1, 10, &tx)).unwrap(); + executor.run_next().await; + assert_eq!(1, recv(&mut rx).await); + coordinator.schedule(a, unit(100, 3, &tx)).unwrap(); + coordinator.schedule(b, unit(1, 11, &tx)).unwrap(); + for expected in [10, 11, 3] { + executor.run_next().await; + assert_eq!(expected, recv(&mut rx).await); + } + coordinator.forget_region(a); + coordinator.forget_region(b); + assert!(coordinator.lock().ready_regions.is_empty()); + assert!(coordinator.lock().regions.is_empty()); + coordinator.stop().await.unwrap(); +} diff --git a/src/mito2/src/compaction/scheduler/local.rs b/src/mito2/src/compaction/scheduler/local.rs index 8ff2a6cb150..9286c1232f5 100644 --- a/src/mito2/src/compaction/scheduler/local.rs +++ b/src/mito2/src/compaction/scheduler/local.rs @@ -13,14 +13,22 @@ // limitations under the License. use std::collections::{HashMap, VecDeque}; +use std::future::Future; use std::sync::Arc; +#[cfg(test)] +use std::sync::atomic::AtomicUsize; +use std::sync::atomic::{AtomicBool, Ordering}; use common_meta::key::SchemaMetadataManagerRef; +use prometheus::IntGauge; +use store_api::compaction_task::{self, CompactionTaskEntry}; use store_api::storage::RegionId; use crate::compaction::compactor::{CompactionContext, CompactionRegion}; use crate::compaction::scheduler::state::{CompactingFiles, CompactionExecution, CompactionPhase}; -use crate::compaction::scheduler::{CompactionScheduler, CompactionTransition}; +use crate::compaction::scheduler::{ + CompactionCoordinator, CompactionScheduler, CompactionTransition, ReadyUnit, +}; use crate::compaction::task::CompactionTask; use crate::compaction::unit::CompactionUnit; use crate::error::{self, Error}; @@ -36,25 +44,149 @@ use crate::sst::file::UncommittedSsts; #[derive(Debug)] struct UnitExecution { state: CancellableTaskState, - finished: bool, + /// Observation flags only; they do not publish other fields or form an atomic snapshot. + /// The owning worker is their sole writer. + finished: AtomicBool, + released: AtomicBool, +} + +/// Balances the inflight charge for a polled job on completion, unwind or drop. +/// An unpolled job never acquires a charge. +struct InflightCompaction(IntGauge); + +impl InflightCompaction { + /// Runs the job inside the same accounting scope on every exit path. + async fn run(job: impl Future, gauge: IntGauge) { + let _inflight = Self::start(gauge); + job.await; + } + + fn start(gauge: IntGauge) -> Self { + gauge.inc(); + Self(gauge) + } +} + +impl Drop for InflightCompaction { + fn drop(&mut self) { + self.0.dec(); + } } /// A request's local units. All transitions run on the owning region worker. #[derive(Debug)] pub(crate) struct LocalCompaction { + coordinator: Arc, + region_id: RegionId, /// All pending and submitted units, retained until task exit. Tasks own their input leases. /// Keyed by each unit's execution plan ID, allocated from the scheduler's `next_plan_id`; /// it equals `CompactionExecution::plan_id()` and the `plan_id` in unit notifications. - units: HashMap, + units: HashMap>, + /// Built once after admission. No units are added after this set is published. + /// Shared handles retain execution flags only, never tasks or SST leases. + unit_states: Arc<[Arc]>, + #[cfg(test)] + publication_count: Arc, pending: VecDeque, parallelism: usize, error: Option>, made_progress: bool, + /// Retains accepted cancellation while non-cancellable siblings finish committing. + cancellation_requested: bool, +} + +/// Query-visible local progress with shared background execution flags. +#[derive(Debug, Clone)] +pub(crate) struct LocalCompactionState { + units: Arc<[Arc]>, + cancellation_requested: bool, +} + +impl LocalCompactionState { + /// Aggregates live units: cancellation takes precedence over running and queued states; + /// committing takes precedence over executing and waiting phases. A cancelling cycle + /// can still be committing while non-cancellable siblings finish. + pub(crate) fn inspect(&self, entry: &mut CompactionTaskEntry) { + entry.total_units = Some(self.units.len() as u64); + let mut completed = 0; + let mut cancelling = self.cancellation_requested; + let mut committing = false; + let mut running = false; + for unit in self.units.iter() { + completed += u64::from(unit.finished.load(Ordering::Relaxed)); + if unit.released.load(Ordering::Relaxed) { + continue; + } + cancelling |= unit.state.is_cancelled(); + committing |= unit.state.commit_started(); + running |= unit.state.started(); + } + entry.completed_units = Some(completed); + running |= committing; + entry.state = if cancelling { + compaction_task::STATE_CANCELLING + } else if running { + compaction_task::STATE_RUNNING + } else { + compaction_task::STATE_QUEUED + } + .into(); + entry.phase = if committing { + compaction_task::PHASE_COMMITTING + } else if running { + compaction_task::PHASE_EXECUTING + } else { + compaction_task::PHASE_WAITING + } + .into(); + } } impl LocalCompaction { + /// Clones progress and live task handles without retaining tasks or their SST leases. + pub(crate) fn current_state(&self) -> LocalCompactionState { + #[cfg(test)] + self.publication_count.fetch_add(1, Ordering::Relaxed); + LocalCompactionState { + units: self.unit_states.clone(), + cancellation_requested: self.cancellation_requested, + } + } + + #[cfg(test)] + pub(crate) fn publication_count_for_test(&self) -> Arc { + self.publication_count.clone() + } + + #[cfg(test)] + pub(crate) fn inspection_stats_for_test(&self) -> (usize, usize, usize) { + ( + Arc::as_ptr(&self.unit_states) as *const () as usize, + self.unit_states.len(), + Arc::strong_count(&self.unit_states), + ) + } + + #[cfg(test)] + pub(crate) fn released_units_for_test(&self) -> usize { + self.unit_states + .iter() + .filter(|unit| unit.released.load(Ordering::Relaxed)) + .count() + } + + #[cfg(test)] + pub(crate) fn unit_ids_for_test(&self) -> Vec { + self.units.keys().copied().collect() + } + + #[cfg(test)] + pub(crate) fn inspect(&self, entry: &mut CompactionTaskEntry) { + self.current_state().inspect(entry); + } + /// Requests cancellation for all units that have not started committing. - pub(crate) fn request_cancel(&self) -> RequestCancelResult { + pub(crate) fn request_cancel(&mut self) -> RequestCancelResult { let mut result = RequestCancelResult::TooLateToCancel; for unit in self.units.values() { match unit.state.request_cancel() { @@ -67,6 +199,8 @@ impl LocalCompaction { _ => {} } } + self.cancellation_requested |= result != RequestCancelResult::TooLateToCancel; + self.coordinator.cancel_pending(self.region_id); result } @@ -77,20 +211,27 @@ impl LocalCompaction { /// Checks this attempt's phase without depending on any sibling's apply status. fn can_apply(&self, id: u64) -> bool { - self.units - .get(&id) - .is_some_and(|unit| !unit.finished && unit.state.commit_started()) + self.units.get(&id).is_some_and(|unit| { + !unit.finished.load(Ordering::Relaxed) && unit.state.commit_started() + }) + } + + /// Removes an exited or rejected unit from scheduling and shared phase aggregation. + fn release_unit(&mut self, id: u64) { + if let Some(unit) = self.units.remove(&id) { + unit.released.store(true, Ordering::Relaxed); + } } /// Records a terminal result once, but still awaits task exit. fn finish(&mut self, id: u64, result: std::result::Result>) { - let Some(unit) = self.units.get_mut(&id) else { + let Some(unit) = self.units.get(&id) else { return; }; - if unit.finished { + if unit.finished.load(Ordering::Relaxed) { return; } - unit.finished = true; + unit.finished.store(true, Ordering::Relaxed); match result { Ok(progress) => self.made_progress |= progress, Err(err) => { @@ -120,12 +261,30 @@ impl CompactionScheduler { units: Vec, reserved: CompactingFiles, ) -> CompactionPhase { + // Memory admission may have removed oversized units from the picker output. + // Report only the inputs that this local cycle will actually execute. + if let Some(info) = self + .region_status + .get_mut(®ion.region_id) + .and_then(|status| status.active.task_state.as_mut()) + { + info.set_plan_stats( + units.iter().flat_map(|unit| &unit.inputs), + units.iter().flat_map(|unit| &unit.outputs), + ); + } let mut local = LocalCompaction { + coordinator: self.coordinator.clone(), + region_id: region.region_id, units: HashMap::new(), + unit_states: Arc::from([]), + #[cfg(test)] + publication_count: Arc::new(AtomicUsize::new(0)), pending: VecDeque::new(), parallelism: region.max_parallelism.max(1), error: None, made_progress: false, + cancellation_requested: false, }; let context = CompactionContext::from(®ion); // Planning is complete; unit tasks must not pin the other units' inputs. @@ -137,10 +296,11 @@ impl CompactionScheduler { let state = CancellableTaskState::new(); local.units.insert( id, - UnitExecution { + Arc::new(UnitExecution { state: state.clone(), - finished: false, - }, + finished: AtomicBool::new(false), + released: AtomicBool::new(false), + }), ); local.pending.push_back(CompactionTask { state, @@ -159,6 +319,7 @@ impl CompactionScheduler { ), }); } + local.unit_states = local.units.values().cloned().collect(); CompactionPhase::Units(local) } @@ -172,6 +333,13 @@ impl CompactionScheduler { /// Submits pending units up to the request limit and arranges task-exit notifications. pub(crate) fn dispatch_local_units(&mut self, region_id: RegionId) { + self.submit_local_units(region_id); + if let Some(status) = self.region_status.get(®ion_id) { + status.publish_state(); + } + } + + fn submit_local_units(&mut self, region_id: RegionId) { loop { let Some(local) = self.local_units_mut(region_id) else { return; @@ -183,6 +351,8 @@ impl CompactionScheduler { return; }; let id = task.execution.plan_id(); + let state = task.state.clone(); + let input_bytes = task.unit.estimated_input_bytes(); let sender = self.request_sender.clone(); let completion = Box::pin(async move { let _ = sender @@ -194,17 +364,20 @@ impl CompactionScheduler { })) .await; }); - let job = Box::pin(async move { - INFLIGHT_COMPACTION_COUNT.inc(); - task.run().await; - drop(task); - INFLIGHT_COMPACTION_COUNT.dec(); - }); - if let Err(err) = self.scheduler.schedule_with_completion(job, completion) - && let Some(local) = self.local_units_mut(region_id) + let job = Box::pin(InflightCompaction::run( + async move { + task.run().await; + drop(task); + }, + INFLIGHT_COMPACTION_COUNT.clone(), + )); + if let Err(err) = self.coordinator.schedule( + region_id, + ReadyUnit::new(state, input_bytes, job, completion), + ) && let Some(local) = self.local_units_mut(region_id) { local.finish(id, Err(Arc::new(err))); - local.units.remove(&id); + local.release_unit(id); } } } @@ -227,6 +400,9 @@ impl CompactionScheduler { if let Some(local) = self.local_units_mut(region_id) { local.finish(id, result); } + if let Some(status) = self.region_status.get(®ion_id) { + status.publish_state(); + } } /// Accounts for task exit, starts pending units, and checks request completion. @@ -243,16 +419,16 @@ impl CompactionScheduler { if !local.units.contains_key(&id) { return CompactionTransition::NoAction; } - local.finish( - id, - Err(Arc::new( - error::UnexpectedSnafu { - reason: "Compaction unit exited without a terminal notification", - } - .build(), - )), - ); - local.units.remove(&id); + let missing_result = if local.units[&id].state.is_cancelled() { + error::CompactionCancelledSnafu.build() + } else { + error::UnexpectedSnafu { + reason: "Compaction unit exited without a terminal notification", + } + .build() + }; + local.finish(id, Err(Arc::new(missing_result))); + local.release_unit(id); self.dispatch_local_units(region_id); self.finish_local_units(region_id, manifest, schemas).await } @@ -272,9 +448,7 @@ impl CompactionScheduler { } if let Some(err) = local.error.take() { if matches!(err.as_ref(), Error::CompactionCancelled { .. }) { - return CompactionTransition::from_pending_ddls( - self.finish_compaction_on_cancel(region_id), - ); + return self.finish_cancelled_compaction(region_id, manifest, schemas); } self.on_compaction_failed(region_id, err); return CompactionTransition::NoAction; @@ -292,29 +466,234 @@ impl CompactionScheduler { #[cfg(test)] mod tests { + use futures::FutureExt; + use tokio::sync::oneshot; + use super::*; - #[test] - fn test_compaction_unit_apply_accepts_independent_executions() { - let units = [1, 2] + fn local_compaction() -> LocalCompaction { + let units: HashMap<_, _> = [1, 2] .into_iter() .map(|id| { ( id, - UnitExecution { + Arc::new(UnitExecution { state: CancellableTaskState::new(), - finished: false, - }, + finished: AtomicBool::new(false), + released: AtomicBool::new(false), + }), ) }) .collect(); - let mut local = LocalCompaction { + LocalCompaction { + coordinator: Arc::new(CompactionCoordinator::new( + Arc::new(crate::test_util::scheduler_util::VecScheduler::default()), + 2, + )), + region_id: RegionId::from_u64(1), + unit_states: units.values().cloned().collect(), + publication_count: Arc::new(AtomicUsize::new(0)), units, pending: VecDeque::new(), parallelism: 2, error: None, made_progress: false, - }; + cancellation_requested: false, + } + } + + #[rstest::rstest] + #[case::completed(false)] + #[case::panicked(true)] + #[tokio::test] + async fn test_inflight_job_balances_count_on_exit(#[case] panics: bool) { + let gauge = IntGauge::new("test_inflight_compaction", "isolated inflight gauge").unwrap(); + let (resume, paused) = oneshot::channel(); + let job = InflightCompaction::run( + async move { + paused.await.unwrap(); + if panics { + panic!("inflight job panic fixture"); + } + }, + gauge.clone(), + ); + let mut job = Box::pin(std::panic::AssertUnwindSafe(job).catch_unwind()); + + assert_eq!(0, gauge.get()); + assert!(futures::poll!(job.as_mut()).is_pending()); + // Assertions outside catch_unwind cannot masquerade as the fixture panic. + assert_eq!(1, gauge.get()); + resume.send(()).unwrap(); + let outcome = job.await; + if panics { + let payload = outcome.unwrap_err(); + assert_eq!( + Some("inflight job panic fixture"), + payload.downcast_ref::<&str>().copied() + ); + } else { + assert!(outcome.is_ok()); + } + assert_eq!(0, gauge.get()); + } + + #[rstest::rstest] + #[case::unpolled(false)] + #[case::started(true)] + #[tokio::test] + async fn test_inflight_job_drop_balances_started_count(#[case] started: bool) { + let gauge = IntGauge::new("test_inflight_compaction", "isolated inflight gauge").unwrap(); + let mut job = Box::pin(InflightCompaction::run( + std::future::pending::<()>(), + gauge.clone(), + )); + assert_eq!(0, gauge.get()); + if started { + assert!(futures::poll!(job.as_mut()).is_pending()); + assert_eq!(1, gauge.get()); + } + drop(job); + assert_eq!(0, gauge.get()); + } + + fn task_entry() -> CompactionTaskEntry { + use crate::compaction::scheduler::state::{CompactionTaskState, CompactionTrigger}; + + CompactionTaskState::new( + RegionId::from_u64(1), + &api::v1::region::compact_request::Options::Regular(Default::default()), + 2, + None, + CompactionTrigger::Manual, + ) + .snapshot(None) + } + + #[test] + fn test_shared_units_observe_finish_and_release() { + let mut local = local_compaction(); + let published = local.current_state(); + let mut entry = task_entry(); + for unit in local.units.values() { + assert!( + published + .units + .iter() + .any(|shared| Arc::ptr_eq(shared, unit)) + ); + } + assert!(local.units[&1].state.mark_commit_started()); + local.finish(1, Ok(true)); + local.finish(1, Ok(false)); + published.inspect(&mut entry); + assert_eq!(entry.completed_units, Some(1)); + assert_eq!((&*entry.state, &*entry.phase), ("running", "committing")); + + local.release_unit(1); + local.release_unit(1); + local.release_unit(99); + published.inspect(&mut entry); + assert_eq!(entry.completed_units, Some(1)); + assert_eq!((&*entry.state, &*entry.phase), ("queued", "waiting")); + assert!(Arc::ptr_eq(&published.units, &local.current_state().units)); + + // Rejected scheduling finishes and releases a queued unit through the same path. + local.finish(2, Err(Arc::new(error::CompactionCancelledSnafu.build()))); + local.release_unit(2); + published.inspect(&mut entry); + assert_eq!(entry.total_units, Some(2)); + assert_eq!(entry.completed_units, Some(2)); + assert!(local.units.is_empty()); + assert!(Arc::ptr_eq(&published.units, &local.current_state().units)); + } + + #[test] + fn test_shared_units_match_live_map_aggregation() { + #[derive(Debug, Clone, Copy)] + enum Phase { + Queued, + Running, + Committing, + Finished, + Released, + Cancelled, + CancelledReleased, + } + let phases = [ + Phase::Queued, + Phase::Running, + Phase::Committing, + Phase::Finished, + Phase::Released, + Phase::Cancelled, + Phase::CancelledReleased, + ]; + for first in phases { + for second in phases { + let mut local = local_compaction(); + let published = local.current_state(); + let mut completed = 0; + for (id, phase) in [(1, first), (2, second)] { + let state = &local.units[&id].state; + match phase { + Phase::Queued => {} + Phase::Running => state.mark_started(), + Phase::Committing | Phase::Finished | Phase::Released => { + assert!(state.mark_commit_started()); + } + Phase::Cancelled | Phase::CancelledReleased => { + assert_eq!(state.request_cancel(), RequestCancelResult::CancelIssued); + } + } + if matches!( + phase, + Phase::Finished | Phase::Released | Phase::CancelledReleased + ) { + local.finish(id, Ok(false)); + completed += 1; + } + if matches!(phase, Phase::Released | Phase::CancelledReleased) { + local.release_unit(id); + } + } + // The former implementation aggregated only units remaining in this map. + let cancelling = local.units.values().any(|unit| unit.state.is_cancelled()); + let committing = local.units.values().any(|unit| unit.state.commit_started()); + let running = committing || local.units.values().any(|unit| unit.state.started()); + let expected_state = if cancelling { + "cancelling" + } else if running { + "running" + } else { + "queued" + }; + let expected_phase = if committing { + "committing" + } else if running { + "executing" + } else { + "waiting" + }; + let mut entry = task_entry(); + published.inspect(&mut entry); + assert_eq!( + ( + &*entry.state, + &*entry.phase, + entry.total_units, + entry.completed_units + ), + (expected_state, expected_phase, Some(2), Some(completed)), + "{first:?}, {second:?}", + ); + } + } + } + + #[test] + fn test_compaction_unit_apply_accepts_independent_executions() { + let mut local = local_compaction(); assert!(!local.can_apply(1)); assert!(!local.can_apply(2)); assert!(!local.can_apply(99)); @@ -338,4 +717,44 @@ mod tests { "terminal units remain tracked until task exit" ); } + + #[test] + fn test_compaction_cancelling_survives_cancelled_sibling_release() { + let mut local = local_compaction(); + let mut entry = task_entry(); + // One published view observes background phase changes without republishing. + let published = local.current_state(); + published.inspect(&mut entry); + assert_eq!((&*entry.state, &*entry.phase), ("queued", "waiting")); + local.units[&1].state.mark_started(); + published.inspect(&mut entry); + assert_eq!((&*entry.state, &*entry.phase), ("running", "executing")); + assert!(local.units[&1].state.mark_commit_started()); + published.inspect(&mut entry); + assert_eq!((&*entry.state, &*entry.phase), ("running", "committing")); + assert_eq!(local.request_cancel(), RequestCancelResult::CancelIssued); + published.inspect(&mut entry); + assert_eq!((&*entry.state, &*entry.phase), ("cancelling", "committing")); + + // The cancelled sibling exits first; the committing sibling cannot be cancelled. + local.finish(2, Err(Arc::new(error::CompactionCancelledSnafu.build()))); + local.release_unit(2); + assert!(!local.units[&1].state.is_cancelled()); + local.inspect(&mut entry); + assert_eq!((&*entry.state, &*entry.phase), ("cancelling", "committing")); + assert_eq!(entry.completed_units, Some(1)); + assert_eq!(entry.total_units, Some(2)); + + // A request arriving after every unit crossed the boundary is not accepted. + let mut too_late = local_compaction(); + for unit in too_late.units.values() { + assert!(unit.state.mark_commit_started()); + } + assert_eq!( + too_late.request_cancel(), + RequestCancelResult::TooLateToCancel + ); + too_late.inspect(&mut entry); + assert_eq!((&*entry.state, &*entry.phase), ("running", "committing")); + } } diff --git a/src/mito2/src/compaction/scheduler/planning.rs b/src/mito2/src/compaction/scheduler/planning.rs index 58e622d8d25..47a99b682b4 100644 --- a/src/mito2/src/compaction/scheduler/planning.rs +++ b/src/mito2/src/compaction/scheduler/planning.rs @@ -35,7 +35,7 @@ use crate::compaction::last_non_null; use crate::compaction::picker::{PickerOutput, new_picker, new_twcs_picker}; use crate::compaction::scheduler::history::{PickHistory, PickKey}; use crate::compaction::scheduler::state::{ - CompactingFiles, CompactionExecution, CompactionPhase, CompactionTrigger, + CompactingFiles, CompactionExecution, CompactionPhase, CompactionTaskState, CompactionTrigger, }; use crate::compaction::scheduler::{CompactionScheduler, CompactionTransition}; use crate::compaction::unit::CompactionUnit; @@ -169,13 +169,25 @@ pub(crate) async fn pick_automatic_for_test( impl CompactionScheduler { pub(super) fn dispatch_compaction_planning( - &self, + &mut self, plan_id: u64, request: CompactionRequest, options: compact_request::Options, time_range: Option, trigger: CompactionTrigger, ) { + if let Some(status) = self.region_status.get_mut(&request.region_id()) { + status.active.task_state.get_or_insert_with(|| { + CompactionTaskState::new( + request.region_id(), + &options, + request.max_parallelism, + time_range, + trigger, + ) + }); + status.publish_state(); + } let plugins = self.plugins.clone(); let max_background_compactions = self.engine_config.max_background_compactions; common_runtime::spawn_compact(async move { @@ -360,8 +372,10 @@ impl CompactionScheduler { // Cancellation during Picking is completed by this notification. No // execution callback will follow, so return DDLs released by the fence. if !status.accept_plan(finished.plan_id) { - return CompactionTransition::from_pending_ddls( - self.finish_compaction_on_cancel(region_id), + return self.finish_cancelled_compaction( + region_id, + manifest_ctx, + schema_metadata_manager, ); } @@ -399,6 +413,10 @@ impl CompactionScheduler { let Some(status) = self.region_status.get_mut(®ion_id) else { return CompactionTransition::NoAction; }; + if let Some(info) = &mut status.active.task_state { + info.accept_plan(&prepared.compaction_region, &prepared.picker_output); + } + status.publish_state(); let waiters = status.take_waiters(); match self .prepare_or_submit_compaction(prepared, files, waiters, plan_id) diff --git a/src/mito2/src/compaction/scheduler/state.rs b/src/mito2/src/compaction/scheduler/state.rs index abe95ec8988..3e232138610 100644 --- a/src/mito2/src/compaction/scheduler/state.rs +++ b/src/mito2/src/compaction/scheduler/state.rs @@ -13,7 +13,7 @@ // limitations under the License. use std::collections::{HashMap, HashSet, hash_map}; -use std::sync::Arc; +use std::sync::{Arc, RwLock}; use std::time::Instant; use api::v1::region::compact_request; @@ -21,15 +21,18 @@ use common_meta::key::SchemaMetadataManagerRef; use common_telemetry::debug; use common_time::range::TimestampRange; use snafu::ResultExt; +use store_api::compaction_task::{self, CompactionTaskEntry}; use store_api::storage::RegionId; use tokio::sync::mpsc::Sender; use crate::access_layer::AccessLayerRef; use crate::cache::CacheManagerRef; -use crate::compaction::compactor::CompactionVersion; +use crate::compaction::CompactionOutput; +use crate::compaction::compactor::{CompactionRegion, CompactionVersion}; use crate::compaction::picker::PickerOutput; +use crate::compaction::scheduler::CancelCompactionResult; use crate::compaction::scheduler::history::PickHistory; -use crate::compaction::scheduler::local::LocalCompaction; +use crate::compaction::scheduler::local::{LocalCompaction, LocalCompactionState}; use crate::compaction::scheduler::planning::CompactionRequest; use crate::config::MitoConfig; use crate::error::{ @@ -95,13 +98,15 @@ pub(crate) enum CompactionPhase { /// Describes how the current compaction cycle was triggered. #[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub(super) enum CompactionTrigger { +pub(crate) enum CompactionTrigger { Automatic, Manual, } #[derive(Debug)] pub(super) struct ActiveCompaction { + /// Query metadata owned by this live cycle, dropped when it becomes idle. + pub(crate) task_state: Option, pub(super) phase: CompactionPhase, trigger: CompactionTrigger, /// Waiters satisfied by the current planning or execution cycle. Picking waiters move into @@ -111,16 +116,20 @@ pub(super) struct ActiveCompaction { /// picking cycle after the current cycle finishes. Recorded in every phase so an external /// trigger always resets the continuation scope, even during local/remote execution. pub(super) automatic_followup_required: bool, + /// Records an accepted explicit cancellation of this task. + task_cancel_requested: bool, } impl ActiveCompaction { /// Creates an empty cycle while retaining the region's scheduling record. fn idle() -> Self { Self { + task_state: None, phase: CompactionPhase::Idle, trigger: CompactionTrigger::Automatic, waiters: Vec::new(), automatic_followup_required: false, + task_cancel_requested: false, } } @@ -131,6 +140,7 @@ impl ActiveCompaction { trigger: CompactionTrigger, ) -> Self { Self { + task_state: None, phase: CompactionPhase::Picking { plan_id, cancelled: false, @@ -138,10 +148,13 @@ impl ActiveCompaction { trigger, waiters, automatic_followup_required: false, + task_cancel_requested: false, } } pub(super) fn start_picking(&mut self, plan_id: u64, trigger: CompactionTrigger) { + self.task_state = None; + self.task_cancel_requested = false; self.phase = CompactionPhase::Picking { plan_id, cancelled: false, @@ -220,6 +233,34 @@ impl ActiveCompaction { self.waiters.push(waiter); } } + /// Captures worker-owned metadata while retaining live background task handles. + fn current_task_state(&self) -> Option { + let mut task = self.task_state.clone()?; + let entry = &mut task.entry; + match &self.phase { + CompactionPhase::Idle => return None, + CompactionPhase::Picking { cancelled, .. } => { + entry.state = if *cancelled { + compaction_task::STATE_CANCELLING + } else { + compaction_task::STATE_RUNNING + } + .into(); + entry.phase = compaction_task::PHASE_PLANNING.into(); + } + CompactionPhase::Remote { .. } => { + entry.state = compaction_task::STATE_RUNNING.into(); + entry.phase = compaction_task::PHASE_REMOTE.into(); + } + CompactionPhase::Units(local) => task.local_state = Some(local.current_state()), + #[cfg(test)] + CompactionPhase::Local { .. } => { + entry.state = compaction_task::STATE_RUNNING.into(); + entry.phase = compaction_task::PHASE_EXECUTING.into(); + } + } + Some(task) + } } /// Owns atomic reservations for every SST selected by a compaction plan. @@ -320,6 +361,8 @@ impl DdlExecution { /// Scheduling state retained for the lifetime of a loaded region. pub(super) struct CompactionStatus { + /// Current cycles shared with queries without entering the region worker. + pub(crate) shared_state: CompactionStateRef, /// Resident automatic-pick history, retained across batches until region unload. pub(crate) pick_history: PickHistory, /// Id of the region. @@ -335,6 +378,8 @@ pub(super) struct CompactionStatus { /// A manual request is rejected if the current compaction is also manual. Automatic requests /// are merged into the active compaction instead of using this slot. pub(super) pending_request: Option, + /// Metadata for the pending manual request, moved to the active cycle on promotion. + pub(crate) pending_task_state: Option, /// Pending DDL requests that should run when compaction is done. /// /// Although [`SenderDdlRequest`] can wrap any DDL variant, production code only queues @@ -346,6 +391,57 @@ pub(super) struct CompactionStatus { } impl CompactionStatus { + /// Cancels an exact identity, checking pending work before the active cycle. + pub(crate) fn cancel_task(&mut self, task_id: &str) -> CancelCompactionResult { + if self + .pending_task_state + .as_ref() + .is_some_and(|state| state.entry.task_id.as_ref() == task_id) + { + self.pending_task_state = None; + if let Some(pending) = self.pending_request.take() { + pending.waiter.send(CompactionCancelledSnafu.fail()); + } + self.publish_state(); + return CancelCompactionResult::CancelIssued; + } + if !self + .active + .task_state + .as_ref() + .is_some_and(|state| state.entry.task_id.as_ref() == task_id) + { + return CancelCompactionResult::NotFound; + } + if matches!(self.active.phase, CompactionPhase::Remote { .. }) { + return CancelCompactionResult::Unsupported; + } + if self.active.task_cancel_requested { + return CancelCompactionResult::AlreadyCancelling; + } + let result = self.request_cancel(); + if result != RequestCancelResult::TooLateToCancel { + self.active.task_cancel_requested = true; + } + result.into() + } + + /// Publishes both slots together without holding the lock while building their metadata. + pub(crate) fn publish_state(&self) { + let active = self.active.current_task_state().map(Arc::new); + let pending = self + .pending_request + .as_ref() + .and(self.pending_task_state.as_ref()) + .cloned() + .map(Arc::new); + let previous = { + let mut shared = self.shared_state.write().unwrap(); + std::mem::replace(&mut *shared, CompactionState { active, pending }) + }; + drop(previous); + } + /// Registers an idle region without starting a compaction cycle. pub(super) fn new( region_id: RegionId, @@ -353,12 +449,14 @@ impl CompactionStatus { access_layer: AccessLayerRef, ) -> CompactionStatus { CompactionStatus { + shared_state: Arc::new(RwLock::new(CompactionState::default())), pick_history: PickHistory::default(), region_id, version_control, access_layer, active: ActiveCompaction::idle(), pending_request: None, + pending_task_state: None, pending_ddl_requests: Vec::new(), executing_ddl: None, } @@ -388,6 +486,7 @@ impl CompactionStatus { /// Ends the current cycle without losing region or DDL execution state. pub(crate) fn become_idle(&mut self) { self.active = ActiveCompaction::idle(); + self.publish_state(); } #[cfg(test)] @@ -439,7 +538,9 @@ impl CompactionStatus { } pub(super) fn request_cancel(&mut self) -> RequestCancelResult { - self.active.request_cancel() + let result = self.active.request_cancel(); + self.publish_state(); + result } pub(super) fn mark_automatic_trigger(&mut self) { @@ -461,10 +562,18 @@ impl CompactionStatus { pub(super) fn set_phase(&mut self, phase: CompactionPhase) { self.active.phase = phase; + self.publish_state(); } /// Sets a pending manual compaction request, replacing an older pending request. pub(super) fn set_pending_request(&mut self, pending: PendingCompaction) { + self.pending_task_state = Some(CompactionTaskState::new( + self.region_id, + &pending.options, + pending.max_parallelism, + pending.time_range, + CompactionTrigger::Manual, + )); if let Some(prev) = self.pending_request.replace(pending) { debug!( "Replace pending compaction options with new request {:?} for region: {}", @@ -472,6 +581,7 @@ impl CompactionStatus { ); prev.waiter.send(ManualCompactionOverrideSnafu.fail()); } + self.publish_state(); } pub(super) fn on_failure(&mut self, err: Arc) { @@ -482,6 +592,7 @@ impl CompactionStatus { })); } + self.pending_task_state = None; if let Some(pending_compaction) = self.pending_request.take() { pending_compaction .waiter @@ -497,6 +608,21 @@ impl CompactionStatus { region_id: self.region_id, })); } + self.publish_state(); + } + + /// Ends task-specific cancellation only when no pending DDL takes precedence. + /// Returns whether the caller may promote a different pending compaction. + pub(crate) fn finish_task_cancellation(&mut self) -> bool { + if !self.active.task_cancel_requested || !self.pending_ddl_requests.is_empty() { + return false; + } + let mut active = std::mem::replace(&mut self.active, ActiveCompaction::idle()); + for waiter in active.waiters.drain(..) { + waiter.send(CompactionCancelledSnafu.fail()); + } + self.publish_state(); + true } #[must_use] @@ -506,6 +632,7 @@ impl CompactionStatus { waiter.send(CompactionCancelledSnafu.fail()); } + self.pending_task_state = None; if let Some(pending_compaction) = self.pending_request.take() { pending_compaction.waiter.send( Err(Arc::new(CompactionCancelledSnafu.build())).context(CompactRegionSnafu { @@ -514,6 +641,7 @@ impl CompactionStatus { ); } + self.publish_state(); std::mem::take(&mut self.pending_ddl_requests) } @@ -561,12 +689,352 @@ pub(super) struct PendingCompaction { pub(crate) time_range: Option, } +/// Current cycles of one loaded region, without completed-task history. +#[derive(Debug, Default)] +pub(crate) struct CompactionState { + active: Option>, + pending: Option>, +} + +/// Shared current cycles of a loaded region. +pub(crate) type CompactionStateRef = Arc>; + +impl CompactionState { + /// Clones current cycle handles under a short read lock. + pub(crate) fn current( + state: &CompactionStateRef, + ) -> ( + Option>, + Option>, + ) { + let state = state.read().unwrap(); + (state.active.clone(), state.pending.clone()) + } +} + +/// Per-cycle request metadata and live execution handles, without retaining SSTs. +#[derive(Debug, Clone)] +pub(crate) struct CompactionTaskState { + pub(crate) entry: CompactionTaskEntry, + pub(crate) submitted: Instant, + local_state: Option, +} + +impl CompactionTaskState { + /// Captures request parameters and assigns the identity of a new compaction cycle. + pub(crate) fn new( + region_id: RegionId, + options: &compact_request::Options, + max_parallelism: usize, + time_range: Option, + trigger: CompactionTrigger, + ) -> Self { + let (kind, window) = match options { + compact_request::Options::Regular(_) => ("regular", None), + compact_request::Options::StrictWindow(window) => { + ("strict_window", Some(window.window_seconds)) + } + }; + let request_options = serde_json::json!({ + "type": kind, + "window_seconds": window, + "max_parallelism": max_parallelism, + "time_range": time_range, + }) + .to_string(); + Self { + submitted: Instant::now(), + local_state: None, + entry: CompactionTaskEntry { + task_id: uuid::Uuid::new_v4().to_string().into(), + region_id, + table_id: region_id.table_id(), + node_id: None, + trigger_type: match trigger { + CompactionTrigger::Manual => compaction_task::TRIGGER_TYPE_MANUAL, + CompactionTrigger::Automatic => compaction_task::TRIGGER_TYPE_AUTOMATIC, + } + .into(), + state: compaction_task::STATE_QUEUED.into(), + phase: compaction_task::PHASE_WAITING.into(), + submitted_at: common_time::util::current_time_millis(), + elapsed_millis: 0, + input_files: None, + input_bytes: None, + input_time_start: None, + input_time_end: None, + output_time_start: None, + output_time_end: None, + total_units: None, + completed_units: None, + request_options: request_options.into(), + effective_options: None, + }, + } + } + + /// Captures the resolved parameters and work selected by an accepted plan. + pub(crate) fn accept_plan(&mut self, region: &CompactionRegion, output: &PickerOutput) { + let max_parallelism = region.max_parallelism.max(1); + let max_picker_outputs = region + .engine_config + .max_background_compactions + .min(max_parallelism); + self.entry.effective_options = Some( + serde_json::json!({ + "compaction": region.region_options.compaction, + "ttl": region.ttl, + "merge_mode": region.region_options.merge_mode(), + "max_picker_outputs": max_picker_outputs, + "max_parallelism": max_parallelism, + "time_window_seconds": output.time_window_size, + "max_output_file_size": output.max_file_size, + }) + .to_string() + .into(), + ); + self.set_plan_stats( + output + .outputs + .iter() + .flat_map(|output| &output.inputs) + .chain(&output.expired_ssts), + output.outputs.iter(), + ); + } + + /// Records the cycle's accepted inputs and planned output envelope, without retaining SSTs. + /// Called again after local memory admission to exclude rejected units. These aggregates + /// remain stable as individual units finish; inputs include expired SSTs and output ends + /// retain half-open semantics. If any output lacks a planned range, both output bounds + /// are None (SQL NULL). An unbounded side propagates independently across outputs. + pub(crate) fn set_plan_stats<'a>( + &mut self, + inputs: impl Iterator, + outputs: impl Iterator, + ) { + let mut seen = HashSet::new(); + let mut bytes = 0; + let mut input_start = None; + let mut input_end = None; + for file in inputs { + if !seen.insert(file.file_id()) { + continue; + } + bytes += file.meta_ref().file_size; + let (start, end) = file.time_range(); + input_start = + Some(input_start.map_or(start, |previous| std::cmp::min(previous, start))); + input_end = Some(input_end.map_or(end, |previous| std::cmp::max(previous, end))); + } + self.entry.input_files = Some(seen.len() as u64); + self.entry.input_bytes = Some(bytes); + self.entry.input_time_start = input_start; + self.entry.input_time_end = input_end; + + let envelope = outputs + .map(|output| { + output + .output_time_range + .map(|range| (*range.start(), *range.end())) + .unwrap_or((None, None)) + }) + .reduce(|(start, end), (next_start, next_end)| { + ( + start.zip(next_start).map(|(a, b)| a.min(b)), + end.zip(next_end).map(|(a, b)| a.max(b)), + ) + }); + let (start, end) = envelope.unwrap_or((None, None)); + self.entry.output_time_start = start; + self.entry.output_time_end = end; + } + + /// Copies cycle metadata with the reporting node and current monotonic elapsed time. + pub(crate) fn snapshot(&self, node_id: Option) -> CompactionTaskEntry { + let mut entry = self.entry.clone(); + if let Some(local) = &self.local_state { + local.inspect(&mut entry); + } + entry.node_id = node_id; + entry.elapsed_millis = self.submitted.elapsed().as_millis().min(u64::MAX as u128) as u64; + entry + } +} + #[cfg(test)] mod tests { + use common_time::Timestamp; use store_api::storage::FileId; use super::*; use crate::compaction::test_util::new_file_handle; + use crate::test_util::new_noop_file_purger; + + fn plan_time_range(start: Option, end: Option) -> TimestampRange { + TimestampRange::from(( + start.map_or(std::ops::Bound::Unbounded, std::ops::Bound::Included), + end.map_or(std::ops::Bound::Unbounded, std::ops::Bound::Excluded), + )) + } + + fn plan_stats_fixture() -> (CompactionTaskState, [FileHandle; 3], [CompactionOutput; 2]) { + let file = |start, end, size| { + let original = new_file_handle(FileId::random(), 0, 0, 0); + let mut meta = original.meta_ref().clone(); + meta.time_range = (start, end); + meta.file_size = size; + FileHandle::new(meta, new_noop_file_purger()) + }; + // Compare timestamps in their original units: numeric values alone have the wrong order. + let early = file( + Timestamp::new_second(1), + Timestamp::new_millisecond(1500), + 10, + ); + let late = file( + Timestamp::new_microsecond(3_000_001), + Timestamp::new_second(4), + 20, + ); + let expired = file(Timestamp::new_second(-2), Timestamp::new_second(-1), 30); + let output = |inputs, start, end| CompactionOutput { + output_level: 1, + inputs, + filter_deleted: false, + output_time_range: Some(plan_time_range(start, end)), + }; + let outputs = [ + output( + vec![early.clone()], + Some(Timestamp::new_second(0)), + Some(Timestamp::new_second(2)), + ), + output( + vec![late.clone()], + Some(Timestamp::new_second(3)), + Some(Timestamp::new_second(5)), + ), + ]; + let info = CompactionTaskState::new( + RegionId::new(1, 1), + &compact_request::Options::Regular(Default::default()), + 1, + None, + CompactionTrigger::Manual, + ); + (info, [early, late, expired], outputs) + } + + type PlanStats = ( + Option, + Option, + Option, + Option, + Option, + Option, + ); + + fn plan_stats(info: &CompactionTaskState) -> PlanStats { + let entry = &info.entry; + ( + entry.input_files, + entry.input_bytes, + entry.input_time_start, + entry.input_time_end, + entry.output_time_start, + entry.output_time_end, + ) + } + + #[test] + fn test_compaction_plan_stats_deduplication_and_admission() { + let (mut info, [early, late, expired], outputs) = plan_stats_fixture(); + // Repeated inputs across logical windows count once; expired SSTs extend only inputs. + info.set_plan_stats( + [&early, &late, &early, &expired].into_iter(), + outputs.iter(), + ); + assert_eq!( + plan_stats(&info), + ( + Some(3), + Some(60), + Some(Timestamp::new_second(-2)), + Some(Timestamp::new_second(4)), + Some(Timestamp::new_second(0)), + Some(Timestamp::new_second(5)) + ) + ); + // Recompute after admission excludes a unit, including its output window. + info.set_plan_stats([&early, &expired].into_iter(), outputs[..1].iter()); + assert_eq!( + plan_stats(&info), + ( + Some(2), + Some(40), + Some(Timestamp::new_second(-2)), + Some(Timestamp::new_millisecond(1500)), + Some(Timestamp::new_second(0)), + Some(Timestamp::new_second(2)) + ) + ); + } + + #[test] + fn test_compaction_plan_stats_expiration_and_empty_reset() { + let (mut info, [early, late, expired], outputs) = plan_stats_fixture(); + info.set_plan_stats([&early, &late, &expired].into_iter(), outputs.iter()); + // Expiration-only cycles have input coverage but no output envelope. + info.set_plan_stats([&expired].into_iter(), std::iter::empty()); + assert_eq!( + plan_stats(&info), + ( + Some(1), + Some(30), + Some(Timestamp::new_second(-2)), + Some(Timestamp::new_second(-1)), + None, + None + ) + ); + info.set_plan_stats(std::iter::empty(), std::iter::empty()); + assert_eq!( + plan_stats(&info), + (Some(0), Some(0), None, None, None, None) + ); + } + + #[test] + fn test_compaction_plan_stats_missing_and_unbounded_ranges() { + let (mut info, [early, late, _], outputs) = plan_stats_fixture(); + // An unbounded side of any output remains unbounded in the cycle envelope. + for (range, expected_start, expected_end) in [ + (None, None, None), + ( + Some(plan_time_range(None, Some(Timestamp::new_second(5)))), + None, + Some(Timestamp::new_second(5)), + ), + ( + Some(plan_time_range(Some(Timestamp::new_second(3)), None)), + Some(Timestamp::new_second(0)), + None, + ), + ] { + let mut mixed = outputs.clone(); + mixed[1].output_time_range = range; + // Order must not affect propagation of unbounded ranges. + for reverse in [false, true] { + if reverse { + mixed.reverse(); + } + info.set_plan_stats([&early, &late].into_iter(), mixed.iter()); + assert_eq!(info.entry.output_time_start, expected_start); + assert_eq!(info.entry.output_time_end, expected_end); + } + } + } #[test] fn test_compaction_unit_input_leases_release_independently() { diff --git a/src/mito2/src/compaction/scheduler_test.rs b/src/mito2/src/compaction/scheduler_test.rs index c377f19f605..a14cf1afa88 100644 --- a/src/mito2/src/compaction/scheduler_test.rs +++ b/src/mito2/src/compaction/scheduler_test.rs @@ -19,10 +19,15 @@ use api::v1::region::StrictWindow; use api::v1::region::compact_request::Options; use common_datasource::compression::CompressionType; use common_meta::key::schema_name::SchemaNameValue; +use common_recordbatch::filter::MetadataFilter; use common_time::{DatabaseTimeToLive, Timestamp}; +use datafusion_expr::{col, lit}; use store_api::mito_engine_options::{ COMPACTION_TYPE, TWCS_ACTIVE_WINDOW_TRIGGER_FILE_NUM, TWCS_TRIGGER_FILE_NUM, }; +use store_api::region_request::{ + EnterStagingRequest, RegionTruncateRequest, StagingPartitionDirective, +}; use store_api::storage::FileId; use tokio::sync::{Barrier, mpsc, oneshot}; @@ -40,7 +45,8 @@ use crate::error::InvalidSchedulerStateSnafu; use crate::manifest::manager::{RegionManifestManager, RegionManifestOptions}; use crate::metrics::COMPACTION_MEMORY_REJECTED; use crate::region::ManifestContext; -use crate::request::{BackgroundNotify, OutputTx, WorkerRequest}; +use crate::request::{BackgroundNotify, CompactionUnitNotification, OutputTx, WorkerRequest}; +use crate::schedule::CancellableTaskState; use crate::schedule::remote_job_scheduler::{RemoteJob, RemoteJobSchedulerRef}; use crate::schedule::scheduler::{Job, Scheduler}; use crate::sst::FormatType; @@ -367,7 +373,7 @@ async fn test_resident_region_survives_terminal_cycles_and_truncate() { let mut scheduler = env.mock_compaction_scheduler(tx); let version = Arc::new(VersionControlBuilder::new().build()); let id = version.region_id(); - scheduler.register_region(&version, &env.access_layer); + scheduler.register_region(&version, &env.access_layer, &Default::default()); assert!(!scheduler.is_compacting(id)); assert!(scheduler.region_status.contains_key(&id)); for cancelled in [false, true] { @@ -375,7 +381,7 @@ async fn test_resident_region_survives_terminal_cycles_and_truncate() { status.start_picking(7); let (reply, response) = oneshot::channel(); status.merge_waiter(reply.into()); - scheduler.register_region(&version, &env.access_layer); + scheduler.register_region(&version, &env.access_layer, &Default::default()); assert!( scheduler.is_compacting(id), "duplicate registration must retain the active cycle" @@ -397,13 +403,13 @@ async fn test_resident_region_survives_terminal_cycles_and_truncate() { assert!(!scheduler.is_compacting(id)); scheduler.on_region_closed(id); assert!(!scheduler.region_status.contains_key(&id)); - scheduler.register_region(&version, &env.access_layer); + scheduler.register_region(&version, &env.access_layer, &Default::default()); let (reply, response) = oneshot::channel(); let status = scheduler.region_status.get_mut(&id).unwrap(); status.start_picking(8); status.merge_waiter(reply.into()); let replacement = Arc::new(VersionControlBuilder::new().build()); - scheduler.register_region(&replacement, &env.access_layer); + scheduler.register_region(&replacement, &env.access_layer, &Default::default()); assert!(response.await.unwrap().is_err()); assert!(Arc::ptr_eq( &scheduler.region_status[&id].version_control, @@ -421,7 +427,7 @@ async fn test_pick_history_survives_cycles_but_not_region_replacement() { let mut scheduler = env.mock_compaction_scheduler(tx); let version = Arc::new(VersionControlBuilder::new().build()); let id = version.region_id(); - scheduler.register_region(&version, &env.access_layer); + scheduler.register_region(&version, &env.access_layer, &Default::default()); let key = PickKey { window: 0, class: PickClass::FileReduction, @@ -439,7 +445,7 @@ async fn test_pick_history_survives_cycles_but_not_region_replacement() { .promoted_since_for_test(key, later); assert!(priority.is_some()); scheduler.region_status.get_mut(&id).unwrap().become_idle(); - scheduler.register_region(&version, &env.access_layer); + scheduler.register_region(&version, &env.access_layer, &Default::default()); assert_eq!( priority, scheduler.region_status[&id] @@ -477,7 +483,7 @@ async fn test_pick_history_survives_cycles_but_not_region_replacement() { .promoted_since_for_test(key, later) ); let replacement = Arc::new(VersionControlBuilder::new().build()); - scheduler.register_region(&replacement, &env.access_layer); + scheduler.register_region(&replacement, &env.access_layer, &Default::default()); assert!( scheduler.region_status[&id] .pick_history @@ -500,7 +506,7 @@ async fn test_empty_plan_prunes_history_but_failed_plan_preserves_it(#[case] fai .mock_manifest_context(version.current().version.metadata.clone()) .await; let (schemas, _) = mock_schema_metadata_manager(); - scheduler.register_region(&version, &env.access_layer); + scheduler.register_region(&version, &env.access_layer, &Default::default()); let status = scheduler.region_status.get_mut(&id).unwrap(); let key = PickKey { window: 0, @@ -576,7 +582,7 @@ async fn test_resident_region_ddl_handoff_and_late_replies() { .mock_manifest_context(version.current().version.metadata.clone()) .await; let (schemas, _) = mock_schema_metadata_manager(); - scheduler.register_region(&version, &env.access_layer); + scheduler.register_region(&version, &env.access_layer, &Default::default()); scheduler .region_status .get_mut(&id) @@ -633,7 +639,7 @@ async fn test_resident_region_ddl_handoff_and_late_replies() { scheduler.on_ddl_complete(id, old_generation, first); scheduler.on_ddl_complete(id, old_generation, first); scheduler.on_region_truncated(id); - scheduler.register_region(&version, &env.access_layer); + scheduler.register_region(&version, &env.access_layer, &Default::default()); assert!( scheduler.region_status[&id].has_ddl(), "duplicate replies and truncate must not end the batch" @@ -646,7 +652,7 @@ async fn test_resident_region_ddl_handoff_and_late_replies() { scheduler.on_region_closed(id); let reopened = Arc::new(VersionControlBuilder::new().build()); - scheduler.register_region(&reopened, &env.access_layer); + scheduler.register_region(&reopened, &env.access_layer, &Default::default()); scheduler .region_status .get_mut(&id) @@ -745,7 +751,7 @@ async fn test_schedule_empty() { // Only one file, picker won't compact it. let version_control = Arc::new(builder.push_l0_file(0, 1000).build()); - scheduler.register_region(&version_control, &env.access_layer); + scheduler.register_region(&version_control, &env.access_layer, &Default::default()); let (output_tx, output_rx) = oneshot::channel(); let waiter = OptionOutputTx::from(output_tx); let scheduled = scheduler @@ -997,7 +1003,7 @@ async fn test_pick_result_mismatched_token_keeps_status_and_waiter_untouched() { let mut scheduler = env.mock_compaction_scheduler(tx); let version_control = compactable_version(); let region_id = version_control.current().version.metadata.region_id; - scheduler.register_region(&version_control, &env.access_layer); + scheduler.register_region(&version_control, &env.access_layer, &Default::default()); // Real discovery prunes this obsolete key only in its private snapshot. let key = PickKey { window: -999, @@ -1044,7 +1050,7 @@ async fn test_cancelled_prepared_plan_preserves_resident_history() { let mut scheduler = env.mock_compaction_scheduler(tx); let version = compactable_version(); let id = version.region_id(); - scheduler.register_region(&version, &env.access_layer); + scheduler.register_region(&version, &env.access_layer, &Default::default()); // This obsolete key is pruned by real automatic discovery, but that private // result must not leak into the resident history before/without acceptance. let key = PickKey { @@ -1080,7 +1086,14 @@ async fn test_pick_result_installs_history_after_unrelated_flush() { let job_scheduler = Arc::new(VecScheduler::default()); let env = SchedulerEnv::new().await.scheduler(job_scheduler.clone()); let (tx, mut rx) = mpsc::channel(4); - let mut scheduler = env.mock_compaction_scheduler(tx); + // A single-unit batch keeps the history assertions below focused on plan + // acceptance. Multi-window batching is covered separately by the automatic + // planning tests. + let config = MitoConfig { + max_background_compactions: 1, + ..Default::default() + }; + let mut scheduler = env.mock_compaction_scheduler_with_config(tx, config); let mut builder = VersionControlBuilder::new(); for start in [0, 3_600_000] { for offset in 0..4 { @@ -1092,7 +1105,7 @@ async fn test_pick_result_installs_history_after_unrelated_flush() { options.time_window = Some(Duration::from_secs(3600)); let version_control = Arc::new(crate::region::version::VersionControl::new(version)); let region_id = version_control.region_id(); - scheduler.register_region(&version_control, &env.access_layer); + scheduler.register_region(&version_control, &env.access_layer, &Default::default()); let selected_key = PickKey { window: 0, class: PickClass::L0Merge, @@ -1222,7 +1235,22 @@ async fn test_pick_result_local_submission_failure_releases_and_notifies_once() .merge_waiter(OptionOutputTx::from(waiter_tx)); scheduler - .handle_compaction_pick_finished(finished, &manifest_ctx, schema_metadata_manager) + .handle_compaction_pick_finished(finished, &manifest_ctx, schema_metadata_manager.clone()) + .await; + + let request = tokio::time::timeout(Duration::from_secs(5), rx.recv()) + .await + .unwrap() + .unwrap(); + let WorkerRequest::Background { + notify: BackgroundNotify::CompactionUnit(CompactionUnitNotification::Released { plan_id }), + .. + } = request.request + else { + panic!("expected rejected unit's resource-release notification"); + }; + scheduler + .on_unit_released(region_id, plan_id, &manifest_ctx, schema_metadata_manager) .await; assert!(waiter_rx.await.unwrap().is_err()); @@ -1231,6 +1259,104 @@ async fn test_pick_result_local_submission_failure_releases_and_notifies_once() assert!(!scheduler.is_compacting(region_id)); } +#[rstest::rstest] +#[case::truncate(DdlRequest::Truncate(RegionTruncateRequest::All))] +#[case::enter_staging(DdlRequest::EnterStaging(EnterStagingRequest { + partition_directive: StagingPartitionDirective::RejectAllWrites, +}))] +#[tokio::test] +async fn test_cancelled_queued_unit_releases_fenced_ddl(#[case] ddl_request: DdlRequest) { + let executor = Arc::new(VecScheduler::default()); + let env = SchedulerEnv::new().await.scheduler(executor.clone()); + let (tx, mut rx) = mpsc::channel(4); + let mut scheduler = env.mock_compaction_scheduler_with_config( + tx, + MitoConfig { + max_background_compactions: 1, + ..Default::default() + }, + ); + // Another region holds the only slot without polling its job. The tested + // unit must be withdrawn from the coordinator, not cancelled during execution. + scheduler + .coordinator + .schedule( + RegionId::new(99, 1), + ReadyUnit::new( + CancellableTaskState::new(), + 1, + Box::pin(async {}), + Box::pin(async {}), + ), + ) + .unwrap(); + let version = compactable_version(); + let region_id = version.region_id(); + let (finished, manifest, schemas) = + begin_pick_result(&env, &mut scheduler, &mut rx, &version).await; + let selected = selected_files(&finished); + let (waiter_tx, mut waiter_rx) = oneshot::channel(); + scheduler + .region_status + .get_mut(®ion_id) + .unwrap() + .merge_waiter(waiter_tx.into()); + scheduler + .handle_compaction_pick_finished(finished, &manifest, schemas.clone()) + .await; + assert_eq!(1, executor.num_jobs()); + assert!(!selected.is_empty()); + assert!(selected.iter().all(FileHandle::compacting)); + + let expected_ddl = std::mem::discriminant(&ddl_request); + let (ddl_tx, mut ddl_rx) = oneshot::channel(); + assert!( + scheduler + .try_cancel_and_add_ddl(region_id, ddl_tx.into(), ddl_request, |request| request) + .is_ok() + ); + let request = tokio::time::timeout(Duration::from_secs(5), rx.recv()) + .await + .unwrap() + .unwrap(); + let WorkerRequest::Background { + region_id: released_region, + notify: BackgroundNotify::CompactionUnit(CompactionUnitNotification::Released { plan_id }), + } = request.request + else { + panic!("expected only Released for the withdrawn unit"); + }; + assert_eq!(region_id, released_region); + assert!(selected.iter().all(|file| !file.compacting())); + + let transition = scheduler + .on_unit_released(region_id, plan_id, &manifest, schemas) + .await; + assert_matches!( + waiter_rx.try_recv().unwrap(), + Err(Error::CompactionCancelled { .. }) + ); + assert!(!scheduler.is_compacting(region_id)); + assert_eq!(1, executor.num_jobs()); + let CompactionTransition::DdlReady(mut ddls) = transition else { + panic!("cancelled queued work must hand off its fenced DDL"); + }; + assert_eq!(1, ddls.len()); + let ddl = ddls.pop().unwrap(); + assert_eq!(region_id, ddl.region_id); + assert_eq!(expected_ddl, std::mem::discriminant(&ddl.request)); + assert_matches!(ddl_rx.try_recv(), Err(oneshot::error::TryRecvError::Empty)); + ddl.sender.send(Ok(0)); + assert_eq!( + 0, + tokio::time::timeout(Duration::from_secs(5), ddl_rx) + .await + .unwrap() + .unwrap() + .unwrap() + ); +} + #[tokio::test] async fn test_pick_result_remote_submission_failure_releases_and_notifies_once() { let env = SchedulerEnv::new().await; @@ -1419,7 +1545,14 @@ async fn test_execution_finished_drains_until_no_plan() { let job_scheduler = Arc::new(VecScheduler::default()); let env = SchedulerEnv::new().await.scheduler(job_scheduler.clone()); let (tx, mut rx) = mpsc::channel(4); - let mut scheduler = env.mock_compaction_scheduler(tx); + // This harness never runs the submitted units, so the first batch keeps + // occupying one admission slot. Leave a spare slot so the chained follow-up + // still reaches the executor regardless of the host's CPU-derived capacity. + let config = MitoConfig { + max_background_compactions: 2, + ..Default::default() + }; + let mut scheduler = env.mock_compaction_scheduler_with_config(tx, config); let mut builder = VersionControlBuilder::new(); let purger = builder.file_purger(); let region_id = builder.region_id(); @@ -1602,7 +1735,13 @@ async fn test_time_range_compaction_when_compaction_in_progress() { let job_scheduler = Arc::new(VecScheduler::default()); let env = SchedulerEnv::new().await.scheduler(job_scheduler.clone()); let (tx, mut rx) = mpsc::channel(4); - let mut scheduler = env.mock_compaction_scheduler(tx); + // The first batch is never run here and keeps one admission slot occupied, + // so the pending manual request needs a second slot to reach the executor. + let config = MitoConfig { + max_background_compactions: 2, + ..Default::default() + }; + let mut scheduler = env.mock_compaction_scheduler_with_config(tx, config); let mut builder = VersionControlBuilder::new(); let purger = builder.file_purger(); let region_id = builder.region_id(); @@ -1830,7 +1969,13 @@ async fn test_ranged_compaction_stops_without_followup() { let job_scheduler = Arc::new(VecScheduler::default()); let env = SchedulerEnv::new().await.scheduler(job_scheduler.clone()); let (tx, mut rx) = mpsc::channel(4); - let mut scheduler = env.mock_compaction_scheduler(tx); + // The ranged execution's units are never run here and keep one admission + // slot occupied, so the follow-up pick needs a second slot to be submitted. + let config = MitoConfig { + max_background_compactions: 2, + ..Default::default() + }; + let mut scheduler = env.mock_compaction_scheduler_with_config(tx, config); let mut builder = VersionControlBuilder::new(); for offset in [0, 10, 20, 30] { @@ -1916,14 +2061,20 @@ async fn test_automatic_trigger_during_execution_clears_continuation_scope() { let job_scheduler = Arc::new(VecScheduler::default()); let env = SchedulerEnv::new().await.scheduler(job_scheduler.clone()); let (tx, mut rx) = mpsc::channel(4); - let mut scheduler = env.mock_compaction_scheduler(tx); + let mut scheduler = env.mock_compaction_scheduler_with_config( + tx, + MitoConfig { + max_background_compactions: 4, + ..Default::default() + }, + ); let mut builder = VersionControlBuilder::new(); - for offset in [0, 10, 20, 30] { - builder.push_l0_file(offset, 1_000); - } - for offset in [0, 10, 20, 30] { - builder.push_l0_file(2 * 3_600_000 + offset, 2 * 3_600_000 + 1_000); + // Two windows remain eligible while the manual unit reserves window 0. + for window_start in [0, 2 * 3_600_000, 4 * 3_600_000] { + for offset in [0, 10, 20, 30] { + builder.push_l0_file(window_start + offset, window_start + 1_000); + } } let region_id = builder.region_id(); let version_control = Arc::new(builder.build()); @@ -2001,18 +2152,20 @@ async fn test_automatic_trigger_during_execution_clears_continuation_scope() { let CompactionPlanningResult::Prepared(prepared) = continuation.result else { panic!("expected the unrestricted follow-up to select out-of-range windows"); }; - assert!( - prepared - .picker_output - .outputs - .iter() - .flat_map(|output| &output.inputs) - .any(|file| file.time_range().1 >= Timestamp::new_millisecond(2 * 3_600_000)) - ); + assert_eq!(2, prepared.picker_output.outputs.len()); + assert_eq!(4, prepared.compaction_region.max_parallelism); + let windows: std::collections::HashSet<_> = prepared + .picker_output + .outputs + .iter() + .flat_map(|output| &output.inputs) + .map(|file| file.time_range().0.value() / 3_600_000) + .collect(); + assert_eq!(std::collections::HashSet::from([2, 4]), windows); } #[tokio::test] -async fn test_automatic_planning_picks_one_output_before_repicking() { +async fn test_automatic_planning_prepares_independent_windows_up_to_global_capacity() { let env = SchedulerEnv::new().await; let (tx, mut rx) = mpsc::channel(4); let config = MitoConfig { @@ -2065,13 +2218,98 @@ async fn test_automatic_planning_picks_one_output_before_repicking() { panic!("expected prepared compaction"); }; - assert_eq!(1, prepared.picker_output.outputs.len()); - assert!( - prepared.picker_output.outputs[0] - .inputs - .iter() - .all(|file| { file.time_range().0 >= Timestamp::new_millisecond(2 * 3_600_000) }) - ); + assert_eq!(2, prepared.picker_output.outputs.len()); + assert_eq!(4, prepared.compaction_region.max_parallelism); + let windows: std::collections::HashSet<_> = prepared + .picker_output + .outputs + .iter() + .map(|o| o.inputs[0].time_range().0.value() / 3_600_000) + .collect(); + assert_eq!(std::collections::HashSet::from([0, 2]), windows); +} + +#[rstest::rstest] +#[case::single_runner(1)] +#[case::multiple_runners(4)] +#[tokio::test] +async fn test_scheduler_env_runs_compactions_up_to_configured_capacity(#[case] capacity: usize) { + let env = SchedulerEnv::new().await; + let (tx, _rx) = mpsc::channel(4); + let config = MitoConfig { + max_background_compactions: capacity, + ..Default::default() + }; + let scheduler = env.mock_compaction_scheduler_with_config(tx, config); + let (started, mut starts) = mpsc::unbounded_channel(); + // Dropping the senders also unblocks jobs if an assertion fails. + let mut resumes = Vec::new(); + for id in 0..=capacity { + let (resume, paused) = oneshot::channel(); + resumes.push(resume); + let started = started.clone(); + scheduler + .coordinator + .schedule( + RegionId::from_u64(1), + ReadyUnit::new( + CancellableTaskState::new(), + 1, + Box::pin(async move { + let _ = started.send(id); + let _ = paused.await; + }), + Box::pin(async {}), + ), + ) + .unwrap(); + } + + let mut first_starts = Vec::new(); + for _ in 0..capacity { + first_starts.push( + tokio::time::timeout(Duration::from_secs(5), starts.recv()) + .await + .expect("configured compaction runner did not start") + .unwrap(), + ); + } + first_starts.sort_unstable(); + assert_eq!((0..capacity).collect::>(), first_starts); + assert!(starts.try_recv().is_err()); + + resumes.remove(0).send(()).unwrap(); + let next = tokio::time::timeout(Duration::from_secs(5), starts.recv()) + .await + .unwrap() + .unwrap(); + assert_eq!(capacity, next); + drop(resumes); + tokio::time::timeout(Duration::from_secs(5), scheduler.coordinator.stop()) + .await + .unwrap() + .unwrap(); +} + +#[tokio::test] +async fn test_scheduler_env_submits_compactions_to_injected_executor() { + let injected = Arc::new(VecScheduler::default()); + let env = SchedulerEnv::new().await.scheduler(injected.clone()); + let (tx, _rx) = mpsc::channel(4); + let scheduler = env.mock_compaction_scheduler(tx); + scheduler + .coordinator + .schedule( + RegionId::from_u64(1), + ReadyUnit::new( + CancellableTaskState::new(), + 1, + Box::pin(async {}), + Box::pin(async {}), + ), + ) + .unwrap(); + assert_eq!(1, injected.num_jobs()); } #[tokio::test] @@ -2096,6 +2334,7 @@ async fn test_compaction_bypass_in_staging_mode() { checkpoint_distance: 10, remove_file_options: Default::default(), manifest_cache: None, + conditional_publication: false, }, FormatType::PrimaryKey, false, @@ -2107,6 +2346,7 @@ async fn test_compaction_bypass_in_staging_mode() { manager, RegionRoleState::Leader(RegionLeaderState::Staging), None, + Default::default(), )) }; @@ -2310,7 +2550,7 @@ async fn test_try_cancel_and_add_ddl_returns_request_when_not_running() { let mut scheduler = env.mock_compaction_scheduler(tx); let region_id = RegionId::new(1, 1); let version = Arc::new(VersionControlBuilder::new().build()); - scheduler.register_region(&version, &env.access_layer); + scheduler.register_region(&version, &env.access_layer, &Default::default()); assert!(scheduler.region_status.contains_key(®ion_id)); assert!(!scheduler.is_compacting(region_id)); let (ddl_tx, ddl_rx) = oneshot::channel(); @@ -2897,7 +3137,7 @@ async fn test_disable_compaction_scheduling(#[case] options: Options) { scheduler.disable_compaction = true; let version_control = compactable_version(); let region_id = version_control.region_id(); - scheduler.register_region(&version_control, &env.access_layer); + scheduler.register_region(&version_control, &env.access_layer, &Default::default()); let manifest_ctx = env .mock_manifest_context(version_control.current().version.metadata.clone()) .await; @@ -2961,3 +3201,776 @@ async fn test_disable_compaction_scheduling(#[case] options: Options) { CompactionPlanningResult::Prepared(_) )); } + +#[tokio::test] +async fn test_compaction_tasks_pending_identity_and_lifecycle() { + let env = SchedulerEnv::new().await; + let (tx, mut rx) = mpsc::channel(8); + let mut scheduler = env.mock_compaction_scheduler(tx); + let version = compactable_version(); + let (mut finished, manifest, schemas) = + begin_pick_result(&env, &mut scheduler, &mut rx, &version).await; + let all = MetadataFilter::default(); + let rows = scheduler.inspect_tasks(&all, Some(7)); + assert_eq!(rows.len(), 1); + assert_eq!( + (&*rows[0].trigger_type, &*rows[0].phase), + ("automatic", "planning") + ); + assert!(rows[0].effective_options.is_none()); + let automatic_id = rows[0].task_id.clone(); + scheduler + .schedule_manual_compaction( + Options::StrictWindow(StrictWindow { window_seconds: 60 }), + &version, + &env.access_layer, + OptionOutputTx::none(), + &manifest, + schemas.clone(), + 2, + None, + ) + .unwrap(); + let rows = scheduler.inspect_tasks(&all, Some(7)); + assert_eq!(rows.len(), 2); + assert_ne!(rows[0].task_id, rows[1].task_id); + let phases: Vec<_> = rows + .iter() + .map(|row| { + ( + row.trigger_type.as_ref(), + row.state.as_ref(), + row.phase.as_ref(), + ) + }) + .collect(); + assert_eq!( + phases, + [ + ("automatic", "running", "planning"), + ("manual", "queued", "waiting") + ] + ); + let region_id = version.region_id(); + for (filter, expected_rows) in [ + ( + col(compaction_task::REGION_ID).eq(lit(region_id.as_u64())), + 2, + ), + ( + col(compaction_task::REGION_ID).eq(lit(region_id.as_u64() + 1)), + 0, + ), + ( + col(compaction_task::TABLE_ID).eq(lit(region_id.table_id())), + 2, + ), + ( + col(compaction_task::TABLE_ID).eq(lit(region_id.table_id() + 1)), + 0, + ), + ] { + let rows = scheduler.inspect_tasks(&MetadataFilter::new(&[filter]), Some(7)); + assert_eq!(rows.len(), expected_rows); + assert!(rows.iter().all(|row| row.region_id == region_id)); + } + let manual = MetadataFilter::new(&[col("trigger_type").eq(lit("manual"))]); + let rows = scheduler.inspect_tasks(&manual, Some(7)); + assert_eq!(rows.len(), 1); + assert_eq!(rows[0].state.as_ref(), "queued"); + assert_ne!(rows[0].task_id, automatic_id); + let manual_id = rows[0].task_id.clone(); + let submitted_at = rows[0].submitted_at; + assert!( + scheduler + .inspect_tasks( + &MetadataFilter::new(&[col("node_id").eq(lit(8u64))]), + Some(7) + ) + .is_empty() + ); + // Finish automatic planning without running fake SSTs, promoting the pending request. + finished.result = CompactionPlanningResult::NoPlan(None); + scheduler + .handle_compaction_pick_finished(finished, &manifest, schemas.clone()) + .await; + let rows = scheduler.inspect_tasks(&all, Some(7)); + assert_eq!(rows.len(), 1); + assert_eq!(rows[0].task_id, manual_id); + assert_eq!(rows[0].submitted_at, submitted_at); + assert_eq!(rows[0].phase.as_ref(), "planning"); + assert_eq!( + scheduler + .region_status + .get_mut(&version.region_id()) + .unwrap() + .request_cancel(), + crate::schedule::RequestCancelResult::CancelIssued + ); + assert_eq!( + scheduler.inspect_tasks(&all, Some(7))[0].state.as_ref(), + "cancelling" + ); + let finished = recv_compaction_pick_finished(&mut rx).await; + scheduler + .handle_compaction_pick_finished(finished, &manifest, schemas) + .await; + assert!(scheduler.inspect_tasks(&all, Some(7)).is_empty()); +} + +/// Exercises accepted-plan collection and local memory admission through the scheduler. +#[tokio::test] +async fn test_compaction_tasks_partial_memory_admission() { + let jobs = Arc::new(VecScheduler::default()); + let env = SchedulerEnv::new().await.scheduler(jobs.clone()); + let (tx, mut rx) = mpsc::channel(8); + let mut scheduler = env.mock_compaction_scheduler(tx); + let memory_limit = 1024 * 1024; + scheduler.memory_manager = Arc::new(new_compaction_memory_manager(memory_limit)); + assert_eq!(scheduler.memory_manager.limit_bytes(), memory_limit); + let mut builder = VersionControlBuilder::new(); + let version = Arc::new( + builder + .push_l0_file_with_max_row_group_size(0, 1000, memory_limit) + .push_l0_file_with_max_row_group_size(100, 1000, memory_limit) + .push_l0_file_with_max_row_group_size(200, 1000, memory_limit) + .push_l0_file_with_max_row_group_size(10000, 11000, memory_limit / 4) + .push_l0_file_with_max_row_group_size(10100, 11000, memory_limit / 4) + .build(), + ); + let files_to_add = version.current().version.ssts.levels()[0] + .files + .values() + .map(|file| { + let mut meta = file.meta_ref().clone(); + meta.file_size = match meta.time_range.0.value() { + 10000 => 100, + 10100 => 200, + _ => 1000, + }; + meta + }) + .collect(); + version.apply_edit( + Some(crate::manifest::action::RegionEdit { + files_to_add, + files_to_remove: Vec::new(), + timestamp_ms: None, + compaction_time_window: None, + flushed_entry_id: None, + flushed_sequence: None, + committed_sequence: None, + }), + &[], + builder.file_purger(), + ); + let (mut finished, manifest, schemas) = + begin_pick_result(&env, &mut scheduler, &mut rx, &version).await; + let CompactionPlanningResult::Prepared(prepared) = &mut finished.result else { + panic!("expected prepared plan"); + }; + // Use a deterministic two-unit picker result; acceptance, reservation, memory + // admission, local unit construction and inspection all use the production path. + let files: Vec<_> = version.current().version.ssts.levels()[0] + .files + .values() + .cloned() + .collect(); + let (rejected, accepted): (Vec<_>, Vec<_>) = files + .into_iter() + .partition(|file| file.time_range().0 < Timestamp::new_millisecond(10000)); + assert_eq!(rejected.len(), 3); + assert_eq!(accepted.len(), 2); + let output = |inputs, start, end| CompactionOutput { + output_level: 1, + inputs, + filter_deleted: false, + output_time_range: Some(TimestampRange::from(( + std::ops::Bound::Included(Timestamp::new_millisecond(start)), + std::ops::Bound::Excluded(Timestamp::new_millisecond(end)), + ))), + }; + prepared.picker_output.outputs = vec![ + output(rejected.clone(), 0, 2000), + output(accepted.clone(), 10000, 12000), + ]; + prepared.picker_output.expired_ssts.clear(); + scheduler + .handle_compaction_pick_finished(finished, &manifest, schemas) + .await; + assert_eq!(jobs.num_jobs(), 1); + let rows = scheduler.inspect_tasks(&MetadataFilter::default(), Some(7)); + assert_eq!(rows.len(), 1); + let entry = &rows[0]; + assert_eq!(entry.region_id, version.region_id()); + assert_eq!(entry.total_units, Some(1)); + assert_eq!(entry.input_files, Some(2)); + assert_eq!(entry.input_bytes, Some(300)); + assert_eq!( + entry.input_time_start, + Some(Timestamp::new_millisecond(10000)) + ); + assert_eq!( + entry.input_time_end, + Some(Timestamp::new_millisecond(11000)) + ); + assert_eq!( + entry.output_time_start, + Some(Timestamp::new_millisecond(10000)) + ); + assert_eq!( + entry.output_time_end, + Some(Timestamp::new_millisecond(12000)) + ); + assert!(rejected.iter().all(|file| !file.compacting())); + assert!(accepted.iter().all(|file| file.compacting())); +} + +/// Readers retaining a region's shared state must observe replacement and teardown. +#[tokio::test] +async fn test_compaction_tasks_shared_state_pending_replacement_and_teardown() { + for terminal in ["close", "drop", "truncate", "shutdown"] { + let env = SchedulerEnv::new().await; + let (tx, mut rx) = mpsc::channel(8); + let mut scheduler = env.mock_compaction_scheduler(tx); + let version = compactable_version(); + let (_, manifest, schemas) = + begin_pick_result(&env, &mut scheduler, &mut rx, &version).await; + let region_id = version.region_id(); + let shared = scheduler.region_status[®ion_id].shared_state.clone(); + let (active, pending) = CompactionState::current(&shared); + let automatic_id = active.unwrap().snapshot(Some(7)).task_id; + assert!(pending.is_none()); + + let mut previous_pending_id = None; + for window_seconds in [60, 120] { + scheduler + .schedule_manual_compaction( + Options::StrictWindow(StrictWindow { window_seconds }), + &version, + &env.access_layer, + OptionOutputTx::none(), + &manifest, + schemas.clone(), + 2, + None, + ) + .unwrap(); + let (active, pending) = CompactionState::current(&shared); + assert_eq!(active.unwrap().snapshot(Some(7)).task_id, automatic_id); + let pending = pending.unwrap().snapshot(Some(7)); + assert_ne!(pending.task_id, automatic_id); + assert_ne!(Some(&pending.task_id), previous_pending_id.as_ref()); + assert_eq!((&*pending.state, &*pending.phase), ("queued", "waiting")); + let options: serde_json::Value = + serde_json::from_str(&pending.request_options).unwrap(); + assert_eq!(options["window_seconds"], window_seconds); + previous_pending_id = Some(pending.task_id); + } + + match terminal { + "close" => scheduler.on_region_closed(region_id), + "drop" => scheduler.on_region_dropped(region_id), + "truncate" => scheduler.on_region_truncated(region_id), + "shutdown" => drop(scheduler), + _ => unreachable!(), + } + let (active, pending) = CompactionState::current(&shared); + assert!(active.is_none(), "active task survived {terminal}"); + assert!(pending.is_none(), "pending task survived {terminal}"); + } +} + +/// A many-window cycle publishes progress without rebuilding its live-unit collection. +#[rstest::rstest] +#[case::completed(false)] +#[case::submission_rejected(true)] +#[tokio::test] +async fn test_compaction_tasks_linear_local_publication(#[case] reject_after_first: bool) { + use std::sync::atomic::Ordering; + + struct SubmissionScheduler { + jobs: VecScheduler, + reject_after_first: bool, + } + + #[async_trait::async_trait] + impl Scheduler for SubmissionScheduler { + fn schedule(&self, job: Job) -> Result<()> { + if self.reject_after_first && self.jobs.num_jobs() > 0 { + InvalidSchedulerStateSnafu.fail() + } else { + self.jobs.schedule(job) + } + } + + async fn stop(&self, await_termination: bool) -> Result<()> { + self.jobs.stop(await_termination).await + } + } + + const UNITS: usize = 64; + let jobs = Arc::new(SubmissionScheduler { + jobs: VecScheduler::default(), + reject_after_first, + }); + let env = SchedulerEnv::new().await.scheduler(jobs.clone()); + let (tx, mut rx) = mpsc::channel(8); + let mut scheduler = env.mock_compaction_scheduler_with_config( + tx, + MitoConfig { + max_background_compactions: UNITS, + ..Default::default() + }, + ); + let mut builder = VersionControlBuilder::new(); + for window in 0..UNITS as i64 { + let start = window * 60_000; + builder + .push_l0_file(start, start + 1000) + .push_l0_file(start + 100, start + 1000); + } + let version = Arc::new(builder.build()); + let region_id = version.region_id(); + let manifest = env + .mock_manifest_context(version.current().version.metadata.clone()) + .await; + let (schemas, _kv_backend) = mock_schema_metadata_manager(); + let (waiter_tx, waiter_rx) = oneshot::channel(); + scheduler + .schedule_manual_compaction( + Options::StrictWindow(StrictWindow { window_seconds: 60 }), + &version, + &env.access_layer, + OptionOutputTx::from(waiter_tx), + &manifest, + schemas.clone(), + UNITS, + None, + ) + .unwrap(); + let finished = tokio::time::timeout( + Duration::from_secs(10), + recv_compaction_pick_finished(&mut rx), + ) + .await + .expect("strict-window planning did not finish"); + let CompactionPlanningResult::Prepared(prepared) = &finished.result else { + panic!("expected strict-window plan"); + }; + assert_eq!(prepared.picker_output.outputs.len(), UNITS); + scheduler + .handle_compaction_pick_finished(finished, &manifest, schemas.clone()) + .await; + let shared = scheduler.region_status[®ion_id].shared_state.clone(); + let rejected = if reject_after_first { UNITS - 1 } else { 0 }; + // Admission is engine-wide now: the executor rejects the units it cannot take and + // the worker observes each rejection through the asynchronous Released notification. + for _ in 0..rejected { + let message = tokio::time::timeout(Duration::from_secs(10), rx.recv()) + .await + .expect("rejected unit did not report release") + .expect("request channel closed"); + let WorkerRequest::Background { + region_id: notified_region, + notify: + BackgroundNotify::CompactionUnit(CompactionUnitNotification::Released { plan_id }), + } = message.request + else { + panic!("expected a release notification"); + }; + assert_eq!(notified_region, region_id); + scheduler + .on_unit_released(region_id, plan_id, &manifest, schemas.clone()) + .await; + } + let CompactionPhase::Units(local) = &scheduler.region_status[®ion_id].active.phase else { + panic!("expected admitted local units"); + }; + let publications = local.publication_count_for_test(); + let baseline_publications = publications.load(Ordering::Relaxed); + let (collection, len, references) = local.inspection_stats_for_test(); + assert_eq!(len, UNITS); + // The worker and published task share one collection, not per-publication copies. + assert!(references >= 2); + let mut ids = local.unit_ids_for_test(); + ids.sort_unstable(); + assert_eq!(local.released_units_for_test(), rejected); + assert_eq!(ids.len(), UNITS - rejected); + assert_eq!(jobs.jobs.num_jobs(), UNITS - rejected); + let mut previous = CompactionState::current(&shared).0.unwrap(); + let initial = previous.snapshot(Some(7)); + assert_eq!(initial.total_units, Some(UNITS as u64)); + assert_eq!(initial.completed_units, Some(rejected as u64)); + + let mut legacy_handle_clones = 0; + for (index, id) in ids.iter().copied().enumerate() { + // Replay the same terminal-result/task-exit trace without reading synthetic SSTs. + // The old current_state collected every remaining handle on both publications. + legacy_handle_clones += ids.len() - index; + let before_finish = publications.load(Ordering::Relaxed); + scheduler.on_unit_finished(region_id, id, Ok(false)); + assert_eq!(publications.load(Ordering::Relaxed), before_finish + 1); + let current = CompactionState::current(&shared).0.unwrap(); + assert!(!Arc::ptr_eq(&previous, ¤t)); + assert_eq!( + current.snapshot(Some(7)).completed_units, + Some((rejected + index + 1) as u64) + ); + previous = current; + let CompactionPhase::Units(local) = &scheduler.region_status[®ion_id].active.phase + else { + panic!("finished unit must remain until release"); + }; + let (ptr, len, references) = local.inspection_stats_for_test(); + assert_eq!((ptr, len), (collection, UNITS)); + assert!(references >= 2); + assert_eq!(local.released_units_for_test(), rejected + index); + + legacy_handle_clones += ids.len() - index - 1; + let before_release = publications.load(Ordering::Relaxed); + scheduler + .on_unit_released(region_id, id, &manifest, schemas.clone()) + .await; + assert_eq!(publications.load(Ordering::Relaxed), before_release + 1); + if index + 1 < ids.len() { + let current = CompactionState::current(&shared).0.unwrap(); + assert!(!Arc::ptr_eq(&previous, ¤t)); + previous = current; + let CompactionPhase::Units(local) = &scheduler.region_status[®ion_id].active.phase + else { + panic!("siblings must remain active"); + }; + let (ptr, len, references) = local.inspection_stats_for_test(); + assert_eq!((ptr, len), (collection, UNITS)); + assert!(references >= 2); + assert_eq!(local.released_units_for_test(), rejected + index + 1); + } else { + assert!(CompactionState::current(&shared).0.is_none()); + } + } + let added_publications = publications.load(Ordering::Relaxed) - baseline_publications; + assert_eq!(added_publications, 2 * ids.len()); + assert_eq!(legacy_handle_clones, ids.len() * ids.len()); + if !reject_after_first { + assert_eq!(added_publications, 128); + assert_eq!(legacy_handle_clones, 4096); + } + let result = tokio::time::timeout(Duration::from_secs(10), waiter_rx) + .await + .expect("local compaction waiter did not finish") + .unwrap(); + assert_eq!(result.is_err(), reject_after_first); + assert!(!scheduler.is_compacting(region_id)); +} + +/// Pending task identity survives promotion, but replacement invalidates the old identity. +#[tokio::test] +async fn test_cancel_compaction_task_identity_and_pending() { + let env = SchedulerEnv::new().await; + let (tx, mut rx) = mpsc::channel(8); + let mut scheduler = env.mock_compaction_scheduler(tx); + let version = compactable_version(); + let region_id = version.region_id(); + let (mut finished, manifest, schemas) = + begin_pick_result(&env, &mut scheduler, &mut rx, &version).await; + let active_id = scheduler.inspect_tasks(&MetadataFilter::default(), None)[0] + .task_id + .clone(); + let mut pending_ids = Vec::new(); + let mut waiters = Vec::new(); + for _ in 0..3 { + let (sender, receiver) = oneshot::channel(); + scheduler + .schedule_manual_compaction( + Options::StrictWindow(StrictWindow { window_seconds: 60 }), + &version, + &env.access_layer, + sender.into(), + &manifest, + schemas.clone(), + 2, + None, + ) + .unwrap(); + pending_ids.push( + scheduler.inspect_tasks(&MetadataFilter::default(), None)[1] + .task_id + .clone(), + ); + waiters.push(receiver); + } + assert_eq!( + scheduler.cancel_task(region_id, &pending_ids[0]), + CancelCompactionResult::NotFound + ); + assert_eq!( + scheduler.cancel_task(region_id, &pending_ids[1]), + CancelCompactionResult::NotFound + ); + assert_eq!( + scheduler.cancel_task(region_id, &pending_ids[2]), + CancelCompactionResult::CancelIssued + ); + assert_eq!( + scheduler.cancel_task(region_id, &pending_ids[2]), + CancelCompactionResult::NotFound + ); + for receiver in waiters { + assert!(receiver.await.unwrap().is_err()); + } + let rows = scheduler.inspect_tasks(&MetadataFilter::default(), None); + assert_eq!(rows.len(), 1); + assert_eq!(rows[0].task_id, active_id); + assert_eq!(rows[0].state.as_ref(), "running"); + + scheduler + .schedule_manual_compaction( + Options::StrictWindow(StrictWindow { window_seconds: 60 }), + &version, + &env.access_layer, + OptionOutputTx::none(), + &manifest, + schemas.clone(), + 2, + None, + ) + .unwrap(); + let pending_id = scheduler.inspect_tasks(&MetadataFilter::default(), None)[1] + .task_id + .clone(); + finished.result = CompactionPlanningResult::NoPlan(None); + scheduler + .handle_compaction_pick_finished(finished, &manifest, schemas.clone()) + .await; + assert_eq!( + scheduler.inspect_tasks(&MetadataFilter::default(), None)[0].task_id, + pending_id + ); + assert_eq!( + scheduler.cancel_task(region_id, &pending_id), + CancelCompactionResult::CancelIssued + ); + assert_eq!( + scheduler.cancel_task(region_id, &pending_id), + CancelCompactionResult::AlreadyCancelling + ); + let finished = recv_compaction_pick_finished(&mut rx).await; + scheduler + .handle_compaction_pick_finished(finished, &manifest, schemas) + .await; + assert_eq!( + scheduler.cancel_task(region_id, &pending_id), + CancelCompactionResult::NotFound + ); +} + +#[rstest::rstest] +#[case(false)] +#[case(true)] +#[tokio::test] +async fn test_cancel_active_compaction_preserves_pending(#[case] local_execution: bool) { + let jobs = Arc::new(VecScheduler::default()); + let env = SchedulerEnv::new().await.scheduler(jobs); + let (tx, mut rx) = mpsc::channel(8); + let mut scheduler = env.mock_compaction_scheduler(tx); + let version = compactable_version(); + let region_id = version.region_id(); + let (finished, manifest, schemas) = + begin_pick_result(&env, &mut scheduler, &mut rx, &version).await; + let active_id = scheduler.inspect_tasks(&MetadataFilter::default(), None)[0] + .task_id + .clone(); + let mut finished = Some(finished); + if local_execution { + scheduler + .handle_compaction_pick_finished(finished.take().unwrap(), &manifest, schemas.clone()) + .await; + } + let (sender, mut receiver) = oneshot::channel(); + scheduler + .schedule_manual_compaction( + Options::StrictWindow(StrictWindow { window_seconds: 60 }), + &version, + &env.access_layer, + sender.into(), + &manifest, + schemas.clone(), + 2, + None, + ) + .unwrap(); + let pending_id = scheduler.inspect_tasks(&MetadataFilter::default(), None)[1] + .task_id + .clone(); + assert_eq!( + scheduler.cancel_task(region_id, &active_id), + CancelCompactionResult::CancelIssued + ); + assert_eq!( + scheduler.cancel_task(region_id, &active_id), + CancelCompactionResult::AlreadyCancelling + ); + if local_execution { + let CompactionPhase::Units(local) = &scheduler.region_status[®ion_id].active.phase + else { + panic!("expected local units") + }; + let ids = local.unit_ids_for_test(); + for id in ids { + scheduler.on_unit_finished( + region_id, + id, + Err(Arc::new(CompactionCancelledSnafu.build())), + ); + scheduler + .on_unit_released(region_id, id, &manifest, schemas.clone()) + .await; + } + } else { + scheduler + .handle_compaction_pick_finished(finished.take().unwrap(), &manifest, schemas.clone()) + .await; + } + let rows = scheduler.inspect_tasks(&MetadataFilter::default(), None); + assert_eq!(rows.len(), 1); + assert_eq!(rows[0].task_id, pending_id); + assert_eq!(rows[0].phase.as_ref(), "planning"); + assert!(matches!( + receiver.try_recv(), + Err(oneshot::error::TryRecvError::Empty) + )); + assert_eq!( + scheduler.cancel_task(region_id, &active_id), + CancelCompactionResult::NotFound + ); + assert_eq!( + scheduler.cancel_task(region_id, &pending_id), + CancelCompactionResult::CancelIssued + ); + let finished = recv_compaction_pick_finished(&mut rx).await; + scheduler + .handle_compaction_pick_finished(finished, &manifest, schemas.clone()) + .await; + assert!(receiver.await.unwrap().is_err()); + assert!( + scheduler + .schedule_automatic_compaction( + Options::Regular(Default::default()), + &version, + &env.access_layer, + &manifest, + schemas, + ) + .unwrap() + ); +} + +#[tokio::test] +async fn test_cancel_compaction_remote_and_commit_boundary() { + let env = SchedulerEnv::new().await; + let (tx, mut rx) = mpsc::channel(8); + let mut scheduler = env.mock_compaction_scheduler(tx); + let version = compactable_version(); + let region_id = version.region_id(); + let (_finished, _manifest, _schemas) = + begin_pick_result(&env, &mut scheduler, &mut rx, &version).await; + let id = scheduler.inspect_tasks(&MetadataFilter::default(), None)[0] + .task_id + .clone(); + scheduler + .region_status + .get_mut(®ion_id) + .unwrap() + .start_remote_task(); + assert_eq!( + scheduler.cancel_task(region_id, &id), + CancelCompactionResult::Unsupported + ); + let state = scheduler + .region_status + .get_mut(®ion_id) + .unwrap() + .start_local_task(); + assert!(state.mark_commit_started()); + assert_eq!( + scheduler.cancel_task(region_id, &id), + CancelCompactionResult::TooLateToCancel + ); + assert_eq!( + scheduler.cancel_task(region_id, "stale"), + CancelCompactionResult::NotFound + ); + assert_eq!( + scheduler.cancel_task(RegionId::new(999, 1), &id), + CancelCompactionResult::NotFound + ); +} + +#[rstest::rstest] +#[case(false)] +#[case(true)] +#[tokio::test] +async fn test_cancel_compaction_task_keeps_ddl_priority(#[case] task_first: bool) { + let env = SchedulerEnv::new().await; + let (tx, mut rx) = mpsc::channel(8); + let mut scheduler = env.mock_compaction_scheduler(tx); + let version = compactable_version(); + let region_id = version.region_id(); + let (finished, manifest, schemas) = + begin_pick_result(&env, &mut scheduler, &mut rx, &version).await; + let active_id = scheduler.inspect_tasks(&MetadataFilter::default(), None)[0] + .task_id + .clone(); + let (manual_tx, manual_rx) = oneshot::channel(); + scheduler + .schedule_manual_compaction( + Options::StrictWindow(StrictWindow { window_seconds: 60 }), + &version, + &env.access_layer, + manual_tx.into(), + &manifest, + schemas.clone(), + 2, + None, + ) + .unwrap(); + if task_first { + assert_eq!( + scheduler.cancel_task(region_id, &active_id), + CancelCompactionResult::CancelIssued + ); + } + let (ddl_tx, _ddl_rx) = oneshot::channel(); + assert!( + scheduler + .try_cancel_and_add_ddl( + region_id, + ddl_tx.into(), + store_api::region_request::EnterStagingRequest { + partition_directive: + store_api::region_request::StagingPartitionDirective::RejectAllWrites, + }, + DdlRequest::EnterStaging, + ) + .is_ok() + ); + assert_eq!( + scheduler.cancel_task(region_id, &active_id), + CancelCompactionResult::AlreadyCancelling + ); + let transition = scheduler + .handle_compaction_pick_finished(finished, &manifest, schemas) + .await; + let CompactionTransition::DdlReady(ddls) = transition else { + panic!("DDL must take precedence over the pending compaction"); + }; + assert_eq!(ddls.len(), 1); + assert!(manual_rx.await.unwrap().is_err()); + assert!( + scheduler + .inspect_tasks(&MetadataFilter::default(), None) + .is_empty() + ); + assert!(scheduler.region_status[®ion_id].executing_ddl.is_some()); +} diff --git a/src/mito2/src/compaction/task.rs b/src/mito2/src/compaction/task.rs index cc6c3c9b859..666601fcf85 100644 --- a/src/mito2/src/compaction/task.rs +++ b/src/mito2/src/compaction/task.rs @@ -39,8 +39,6 @@ use crate::schedule::CancellableTaskState; use crate::sst::file::UncommittedSsts; use crate::worker::WorkerListener; -pub const MAX_PARALLEL_COMPACTION: usize = 1; - /// One local atomic unit. The scheduler owns request waiters and sibling units. pub(crate) struct CompactionTask { pub(crate) state: CancellableTaskState, @@ -73,6 +71,7 @@ impl Debug for CompactionTask { impl CompactionTask { /// Executes one unit and retains its resources until worker apply or failure acknowledgement. pub(crate) async fn run(&mut self) { + self.state.mark_started(); let start = std::time::Instant::now(); let result = std::panic::AssertUnwindSafe(self.run_once()) .catch_unwind() diff --git a/src/mito2/src/compaction/twcs.rs b/src/mito2/src/compaction/twcs.rs index 1735716b052..bc58cea9b68 100644 --- a/src/mito2/src/compaction/twcs.rs +++ b/src/mito2/src/compaction/twcs.rs @@ -41,7 +41,7 @@ use crate::compaction::twcs::units::{ClosedMergeOptions, PickLimits}; use crate::error::{JoinSnafu, Result}; use crate::metrics::{TWCS_PICK_ELAPSED, TWCS_SCANNED_WINDOWS}; use crate::region::options::MergeMode; -use crate::sst::file::{FileHandle, Level, overlaps}; +use crate::sst::file::{self, FileHandle, Level, overlaps}; use crate::sst::primary_key::PrimaryKeyRangeMapper; use crate::sst::version::LevelMeta; @@ -392,7 +392,13 @@ impl TwcsPicker { region_sequence, mapper, } = *context; - let mut files: Vec<_> = window.files().cloned().collect(); + // Shared files remain in the window map for overlap/tombstone safety, + // but only the table executor may rewrite them. + let mut files: Vec<_> = window + .files() + .filter(|file| file.level() < file::LEVEL_SHARED) + .cloned() + .collect(); let quiet = is_quiet_window(&files, region_sequence); // Filter out large files in append mode - they won't benefit from compaction @@ -1155,7 +1161,8 @@ impl TwcsPicker { // Compute activity from the candidate files so expired or // compacting files cannot identify a window absent from `windows`. let active_window = find_active_window_by_sequence( - windows.values().flat_map(Window::files), + windows.values().flat_map(Window::files) + .filter(|file| file.level() < file::LEVEL_SHARED), time_window_size, ) .or_else(|| { diff --git a/src/mito2/src/compaction/unit.rs b/src/mito2/src/compaction/unit.rs index 19a2224a9d3..78501e0c0d1 100644 --- a/src/mito2/src/compaction/unit.rs +++ b/src/mito2/src/compaction/unit.rs @@ -109,6 +109,17 @@ impl CompactionUnit { Some(units) } + /// Estimates merge work from distinct input bytes. Expiration-only units do + /// not read SSTs; admission assigns them its minimum positive service charge. + pub(crate) fn estimated_input_bytes(&self) -> u64 { + if self.outputs.is_empty() { + return 0; + } + self.inputs + .iter() + .fold(0u64, |total, file| total.saturating_add(file.size())) + } + /// Estimates merge memory once per input, even when several outputs read it. pub(crate) fn estimated_memory_bytes(&self) -> u64 { if self.outputs.is_empty() { @@ -134,7 +145,7 @@ mod tests { use store_api::storage::FileId; use super::*; - use crate::compaction::test_util::new_file_handle; + use crate::compaction::test_util::{new_file_handle, new_file_handle_with_size_and_sequence}; /// Builds an L1 output that preserves deletion markers for grouping tests. fn output(inputs: Vec) -> CompactionOutput { @@ -149,7 +160,9 @@ mod tests { #[test] fn test_compaction_unit_transitive_inputs() { let files: Vec<_> = (0..3) - .map(|_| new_file_handle(FileId::random(), 0, 100, 0)) + .map(|i| { + new_file_handle_with_size_and_sequence(FileId::random(), 0, 100, 0, 0, (i + 1) * 10) + }) .collect(); let units = CompactionUnit::from_picker(PickerOutput { outputs: vec![ @@ -167,6 +180,8 @@ mod tests { assert_eq!(3, units[0].outputs.len()); assert_eq!(2, units[0].inputs.len()); assert_eq!(files[2].file_id(), units[1].inputs[0].file_id()); + assert_eq!(30, units[0].estimated_input_bytes()); + assert_eq!(30, units[1].estimated_input_bytes()); assert_eq!(Some(1024), units[0].max_file_size); assert_eq!(100, units[1].time_window_size); } diff --git a/src/mito2/src/compaction/window.rs b/src/mito2/src/compaction/window.rs index b2c4ceaa12a..03a452fa636 100644 --- a/src/mito2/src/compaction/window.rs +++ b/src/mito2/src/compaction/window.rs @@ -30,7 +30,7 @@ use crate::compaction::last_non_null::inputs_precede_memtables; use crate::compaction::picker::{Picker, PickerOutput, get_expired_ssts}; use crate::error::{JoinSnafu, Result}; use crate::region::options::{CompactionOptions, MergeMode}; -use crate::sst::file::FileHandle; +use crate::sst::file::{self, FileHandle}; /// Compaction picker that splits input files into disjoint time windows and merges the /// segments within each window. Outputs may be split further by the configured file size @@ -115,7 +115,9 @@ impl WindowedCompactionPicker { .iter() .flat_map(|level| level.files.values()) .filter(|file| !expired_file_ids.contains(&file.file_id())) - .filter(|file| last_non_null || !file.compacting()), + .filter(|file| { + last_non_null || (!file.compacting() && file.level() < file::LEVEL_SHARED) + }), ); let windows = filter_time_windows(windows, self.time_range); @@ -123,7 +125,9 @@ impl WindowedCompactionPicker { // would remove that SST without rewriting all its remaining segments. if last_non_null && windows.values().any(|(_, inputs)| { - inputs.iter().any(FileHandle::compacting) + inputs + .iter() + .any(|file| file.compacting() || file.level() == file::LEVEL_SHARED) || !inputs_precede_memtables(inputs, current_version.memtable_min_sequence) }) { diff --git a/src/mito2/src/config.rs b/src/mito2/src/config.rs index 67df74d7160..4ce536a9508 100644 --- a/src/mito2/src/config.rs +++ b/src/mito2/src/config.rs @@ -120,6 +120,14 @@ pub struct MitoConfig { /// Max number of running background flush jobs (default: 1/2 of cpu cores). pub max_background_flushes: usize, /// Max number of running background compaction jobs (default: 1/4 of cpu cores). + /// + /// The limit applies to the whole engine, not to each region worker. SST compaction + /// and background bulk memtable compaction each have their own budget of this size. + /// For SST compaction, 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`. pub max_background_compactions: usize, /// Max number of running background purge jobs (default: number of cpu cores). pub max_background_purges: usize, diff --git a/src/mito2/src/engine.rs b/src/mito2/src/engine.rs index c628b968b2b..7c426c5e63b 100644 --- a/src/mito2/src/engine.rs +++ b/src/mito2/src/engine.rs @@ -78,6 +78,8 @@ mod sequence_test; #[cfg(test)] mod set_role_state_test; #[cfg(test)] +mod shared_file_test; +#[cfg(test)] mod skip_wal_test; #[cfg(test)] mod staging_test; @@ -123,6 +125,7 @@ use region_hook::RegionHookRef; use snafu::{OptionExt, ResultExt, ensure}; use store_api::ManifestVersion; use store_api::codec::PrimaryKeyEncoding; +use store_api::compaction_task::{self, CompactionTaskEntry}; use store_api::logstore::LogStore; use store_api::logstore::provider::{KafkaProvider, Provider}; use store_api::metadata::{ColumnMetadata, RegionMetadataRef}; @@ -145,6 +148,7 @@ use tokio::sync::{Semaphore, oneshot}; use crate::access_layer::RegionFilePathFactory; use crate::cache::{CacheManagerRef, CacheStrategy}; +use crate::compaction::CompactionState; use crate::config::{MitoConfig, ScanMemoryMode}; use crate::engine::puffin_index::{IndexEntryContext, collect_index_entries_from_puffin}; use crate::error::{ @@ -750,6 +754,40 @@ impl MitoEngine { results } + /// Reads current compaction cycles with conservative metadata predicate pruning. + pub async fn inspect_compaction_tasks( + &self, + filters: &[Expr], + ) -> Result> { + let filters = MetadataFilter::new(filters); + let node_id = self.inner.workers.file_ref_manager().node_id(); + let mut entries = Vec::new(); + for region in self.inner.workers.all_regions() { + if !filters.matches(|column| match column { + compaction_task::REGION_ID => { + Some(ScalarValue::UInt64(Some(region.region_id.as_u64()))) + } + compaction_task::TABLE_ID => { + Some(ScalarValue::UInt32(Some(region.region_id.table_id()))) + } + compaction_task::NODE_ID => Some(ScalarValue::UInt64(node_id)), + _ => None, + }) { + continue; + } + // Clone only task handles under the region's lock. Snapshot materialization + // and residual metadata filtering never hold that lock or queue worker work. + let (active, pending) = CompactionState::current(®ion.compaction_state); + for task in active.into_iter().chain(pending) { + let entry = task.snapshot(node_id); + if entry.matches(&filters) { + entries.push(entry); + } + } + } + Ok(entries) + } + /// Lists region info entries of all regions in the engine. pub async fn all_region_infos(&self) -> Vec { let node_id = self.inner.workers.file_ref_manager().node_id(); diff --git a/src/mito2/src/engine/basic_test.rs b/src/mito2/src/engine/basic_test.rs index 1b3d27120c8..ebc9647adc8 100644 --- a/src/mito2/src/engine/basic_test.rs +++ b/src/mito2/src/engine/basic_test.rs @@ -15,12 +15,16 @@ //! Basic tests for mito engine. use std::collections::HashMap; -use std::sync::atomic::Ordering; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; use std::time::Duration; use api::v1::helper::row; +use api::v1::region::StrictWindow; +use api::v1::region::compact_request::Options; use api::v1::value::ValueData; use api::v1::{ArrowIpc, Rows, SemanticType}; +use async_trait::async_trait; use common_base::readable_size::ReadableSize; use common_error::ext::ErrorExt; use common_error::status_code::StatusCode; @@ -28,6 +32,10 @@ use common_recordbatch::{DfRecordBatch, RecordBatches}; use common_test_util::flight::encode_to_flight_data; use common_time::Timestamp; use common_wal::options::WAL_OPTIONS_KEY; +use datafusion::datasource::empty::EmptyTable; +use datafusion::logical_expr::LogicalPlan; +use datafusion::prelude::SessionContext; +use datafusion_common::tree_node::{TreeNode, TreeNodeRecursion}; use datatypes::arrow::array::{ ArrayRef, DictionaryArray, Float64Array, StringArray, TimestampMillisecondArray, }; @@ -41,12 +49,14 @@ use rstest::rstest; use rstest_reuse::{self, apply}; use store_api::metadata::ColumnMetadata; use store_api::region_request::{ - PathType, RegionBulkInsertsRequest, RegionCreateRequest, RegionFlushRequest, RegionOpenRequest, - RegionPutRequest, RegionRequirements, + PathType, RegionBulkInsertsRequest, RegionCompactRequest, RegionCreateRequest, + RegionFlushRequest, RegionOpenRequest, RegionPutRequest, RegionRequirements, }; use store_api::storage::RegionId; +use tokio::sync::Notify; use super::*; +use crate::engine::listener::{CompactionListener, EventListener}; use crate::region::version::VersionControlData; use crate::region_write_ctx::test_hooks::arm_bulk_install_barrier; use crate::test_util::{ @@ -2291,3 +2301,528 @@ async fn test_manifest_scan_table_filter() { ); drop(guard); } + +#[tokio::test] +async fn test_region_manifest_size_metrics_lifecycle() { + use crate::metrics::manifest_size::remove_region_manifest_size; + use crate::metrics::manifest_size::tests::manifest_metric_sample; + use store_api::region_request::{RegionCloseRequest, RegionDropRequest}; + + let mut env = TestEnv::with_prefix("manifest-size-metrics").await; + let engine = env.create_engine(MitoConfig::default()).await; + let region_id = RegionId::new(u32::MAX, 7); + remove_region_manifest_size(region_id); + let request = CreateRequestBuilder::new().build(); + let table_dir = request.table_dir.clone(); + engine + .handle_request(region_id, RegionRequest::Create(request.clone())) + .await + .unwrap(); + engine + .get_region(region_id) + .unwrap() + .set_manifest_size_metric_threshold(0); + let assert_sample = || { + let expected = engine + .get_region(region_id) + .unwrap() + .region_statistic() + .manifest_size; + assert!(expected > 0); + assert_eq!(manifest_metric_sample(region_id), Some(expected as i64)); + expected + }; + let initial = assert_sample(); + put_rows( + &engine, + region_id, + Rows { + schema: rows_schema(&request), + rows: build_rows(0, 3), + }, + ) + .await; + flush_region(&engine, region_id, None).await; + assert_ne!(assert_sample(), initial); + let old_region = engine.get_region(region_id).unwrap(); + engine + .handle_request( + region_id, + RegionRequest::Close(RegionCloseRequest::default()), + ) + .await + .unwrap(); + assert_eq!(manifest_metric_sample(region_id), None); + reopen_region(&engine, region_id, table_dir, true, HashMap::new()).await; + engine + .get_region(region_id) + .unwrap() + .set_manifest_size_metric_threshold(0); + assert_sample(); + drop(old_region); + assert_sample(); + engine + .handle_request( + region_id, + RegionRequest::Drop(RegionDropRequest { + fast_path: false, + force: false, + partial_drop: false, + }), + ) + .await + .unwrap(); + assert_eq!(manifest_metric_sample(region_id), None); + let stop_id = RegionId::new(u32::MAX, 9); + remove_region_manifest_size(stop_id); + engine + .handle_request(stop_id, RegionRequest::Create(request)) + .await + .unwrap(); + let region = engine.get_region(stop_id).unwrap(); + region.set_manifest_size_metric_threshold(0); + assert!(manifest_metric_sample(stop_id).is_some()); + engine.stop().await.unwrap(); + assert_eq!(manifest_metric_sample(stop_id), None); +} + +#[tokio::test] +async fn test_region_manifest_size_metrics_failed_open() { + use crate::metrics::manifest_size::remove_region_manifest_size; + use crate::metrics::manifest_size::tests::manifest_metric_sample; + use store_api::region_request::RegionCloseRequest; + + let id = RegionId::new(u32::MAX, 10); + remove_region_manifest_size(id); + let mut env = TestEnv::with_prefix("manifest-metric-failed-open").await; + let engine = env.create_engine(MitoConfig::default()).await; + let request = CreateRequestBuilder::new().build(); + let table_dir = request.table_dir.clone(); + engine + .handle_request(id, RegionRequest::Create(request)) + .await + .unwrap(); + let region = engine.get_region(id).unwrap(); + region.set_manifest_size_metric_threshold(0); + assert!(manifest_metric_sample(id).is_some()); + let store = region.access_layer.object_store().clone(); + let dir = crate::manifest::storage::manifest_dir(®ion.access_layer.build_region_dir(id)); + engine + .handle_request(id, RegionRequest::Close(RegionCloseRequest::default())) + .await + .unwrap(); + assert_eq!(manifest_metric_sample(id), None); + let entries = store.list(&dir).await.unwrap(); + let mut corrupted = 0; + for entry in entries { + if entry.metadata().is_file() { + store.write(entry.path(), "invalid manifest").await.unwrap(); + corrupted += 1; + } + } + assert!(corrupted > 0); + assert!( + engine + .handle_request( + id, + RegionRequest::Open(RegionOpenRequest { + engine: String::new(), + table_dir, + options: HashMap::new(), + skip_wal_replay: true, + path_type: PathType::Bare, + checkpoint: None, + requirements: Default::default(), + }) + ) + .await + .is_err() + ); + assert_eq!(manifest_metric_sample(id), None); + engine.stop().await.unwrap(); +} + +/// Reads a real running compaction even while its owning worker is blocked. +#[tokio::test] +async fn test_inspect_compaction_tasks() { + #[derive(Default)] + struct InspectionListener { + compaction: CompactionListener, + block_write: AtomicBool, + write_blocked: Notify, + release_write: Notify, + } + + #[async_trait] + impl EventListener for InspectionListener { + async fn on_merge_ssts_finished(&self, region_id: RegionId) { + self.compaction.on_merge_ssts_finished(region_id).await; + } + + async fn on_write_wal_end(&self) { + if self.block_write.swap(false, Ordering::Relaxed) { + self.write_blocked.notify_one(); + self.release_write.notified().await; + } + } + } + + struct Release(Arc); + + impl Drop for Release { + fn drop(&mut self) { + self.0.release_write.notify_one(); + self.0.compaction.wake(); + } + } + + let listener = Arc::new(InspectionListener::default()); + let release = Release(listener.clone()); + let mut env = TestEnv::with_prefix("inspect-compaction") + .await + .with_node_id(42); + let engine = env + .create_engine_with( + MitoConfig { + min_compaction_interval: Duration::from_secs(3600), + ..Default::default() + }, + None, + Some(listener.clone()), + None, + ) + .await; + let region_id = RegionId::new(123, 1); + let request = CreateRequestBuilder::new() + .insert_option("compaction.type", "twcs") + .insert_option("compaction.twcs.trigger_file_num", "100") + .build(); + let schema = rows_schema(&request); + engine + .handle_request(region_id, RegionRequest::Create(request)) + .await + .unwrap(); + assert!( + engine + .inspect_compaction_tasks(&[]) + .await + .unwrap() + .is_empty() + ); + for _ in 0..2 { + put_rows( + &engine, + region_id, + Rows { + schema: schema.clone(), + rows: build_rows(0, 2), + }, + ) + .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: Options::StrictWindow(StrictWindow { + window_seconds: 3600, + }), + ..Default::default() + }), + ) + .await + .unwrap() + }) + }; + tokio::time::timeout( + Duration::from_secs(20), + listener.compaction.wait_handle_finished(), + ) + .await + .unwrap(); + let tasks = tokio::time::timeout( + Duration::from_secs(10), + engine.inspect_compaction_tasks(&[]), + ) + .await + .unwrap() + .unwrap(); + assert_eq!(tasks.len(), 1); + let task = &tasks[0]; + assert_eq!(task.region_id, region_id); + assert_eq!(task.table_id, region_id.table_id()); + assert_eq!(task.node_id, Some(42)); + assert_eq!(task.state.as_ref(), "running"); + assert_eq!(task.phase.as_ref(), "executing"); + assert_eq!(task.trigger_type.as_ref(), "manual"); + + let context = SessionContext::new(); + context + .register_table( + "compaction_tasks", + Arc::new(EmptyTable::new( + CompactionTaskEntry::schema().arrow_schema().clone(), + )), + ) + .unwrap(); + for (column, value) in [("node_id", 42), ("region_id", region_id.as_u64())] { + for (predicate, expected_count) in [ + (format!("{column} = {value}"), 1), + (format!("{column} = {}", value + 1), 0), + (format!("{value} = {column}"), 1), + (format!("{} = {column}", value + 1), 0), + (format!("{value} <= {column}"), 1), + (format!("{value} < {column}"), 0), + ] { + let sql = format!("SELECT * FROM compaction_tasks WHERE {predicate}"); + let state = context.state(); + let plan = state.create_logical_plan(&sql).await.unwrap(); + let optimized = state.optimize(&plan).unwrap(); + let mut filters = Vec::new(); + optimized + .apply(|plan| { + if let LogicalPlan::Filter(filter) = plan { + filters.push(filter.predicate.clone()); + } + Ok(TreeNodeRecursion::Continue) + }) + .unwrap(); + assert_eq!(filters.len(), 1, "{sql}"); + let mut has_decimal_cast = false; + filters[0] + .apply(|expr| { + if let Expr::Cast(cast) = expr { + has_decimal_cast |= matches!(cast.expr.as_ref(), Expr::Column(_)) + && cast.field.data_type() == &DataType::Decimal128(20, 0); + } + Ok(TreeNodeRecursion::Continue) + }) + .unwrap(); + assert!(!has_decimal_cast, "{sql}: {}", filters[0]); + + // The engine must prune these predicates without a residual SQL filter. + let actual = engine.inspect_compaction_tasks(&filters).await.unwrap(); + assert_eq!(actual.len(), expected_count, "{sql}"); + if let Some(actual) = actual.first() { + assert_eq!(actual.task_id, task.task_id, "{sql}"); + assert_eq!(actual.region_id, region_id, "{sql}"); + assert_eq!(actual.node_id, Some(42), "{sql}"); + } + } + } + // This hook runs on the region worker, unlike the background compaction gate. + listener.block_write.store(true, Ordering::Relaxed); + let write = { + let engine = engine.clone(); + tokio::spawn(async move { + put_rows( + &engine, + region_id, + Rows { + schema, + rows: build_rows(2, 3), + }, + ) + .await; + }) + }; + tokio::time::timeout(Duration::from_secs(10), listener.write_blocked.notified()) + .await + .unwrap(); + let blocked_worker_tasks = tokio::time::timeout( + Duration::from_secs(10), + engine.inspect_compaction_tasks(&[]), + ) + .await + .expect("inspection must not wait for the blocked region worker") + .unwrap(); + assert_eq!(blocked_worker_tasks.len(), 1); + assert_eq!(blocked_worker_tasks[0].task_id, task.task_id); + assert_eq!(blocked_worker_tasks[0].region_id, region_id); + assert_eq!(blocked_worker_tasks[0].state.as_ref(), "running"); + assert!(!write.is_finished()); + + drop(release); + tokio::time::timeout(Duration::from_secs(10), write) + .await + .unwrap() + .unwrap(); + tokio::time::timeout(Duration::from_secs(20), compact) + .await + .unwrap() + .unwrap(); + tokio::time::timeout(Duration::from_secs(10), async { + while !engine + .inspect_compaction_tasks(&[]) + .await + .unwrap() + .is_empty() + { + tokio::task::yield_now().await; + } + }) + .await + .unwrap(); + engine.stop().await.unwrap(); +} + +/// Exercises cancellation through Handle before and after the commit boundary. +#[rstest] +#[case(false)] +#[case(true)] +#[tokio::test] +async fn test_cancel_compaction_task(#[case] commit_gate: bool) { + fn cancel_request(task_id: &str) -> RegionRequest { + RegionRequest::CancelCompaction(store_api::region_request::RegionCancelCompactionRequest { + task_id: task_id.to_string(), + }) + } + + struct CancellationListener { + commit_gate: bool, + gate: CompactionListener, + } + #[async_trait] + impl EventListener for CancellationListener { + async fn on_merge_ssts_finished(&self, region_id: RegionId) { + if !self.commit_gate { + self.gate.on_merge_ssts_finished(region_id).await; + } + } + async fn on_compaction_commit_begin(&self, region_id: RegionId) { + if self.commit_gate { + self.gate.on_merge_ssts_finished(region_id).await; + } + } + } + struct Release(Arc); + impl Drop for Release { + fn drop(&mut self) { + self.0.gate.wake(); + } + } + let listener = Arc::new(CancellationListener { + commit_gate, + gate: CompactionListener::default(), + }); + let release = Release(listener.clone()); + let mut env = TestEnv::with_prefix("cancel-compaction-task").await; + let engine = env + .create_engine_with( + MitoConfig { + min_compaction_interval: Duration::from_secs(3600), + ..Default::default() + }, + None, + Some(listener.clone()), + None, + ) + .await; + let region_id = RegionId::new(124, 1); + let request = CreateRequestBuilder::new() + .insert_option("compaction.type", "twcs") + .insert_option("compaction.twcs.trigger_file_num", "100") + .build(); + let schema = rows_schema(&request); + engine + .handle_request(region_id, RegionRequest::Create(request)) + .await + .unwrap(); + for _ in 0..2 { + put_rows( + &engine, + region_id, + Rows { + schema: schema.clone(), + rows: build_rows(0, 2), + }, + ) + .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: Options::StrictWindow(StrictWindow { + window_seconds: 3600, + }), + ..Default::default() + }), + ) + .await + }) + }; + tokio::time::timeout( + Duration::from_secs(20), + listener.gate.wait_handle_finished(), + ) + .await + .unwrap(); + let tasks = engine.inspect_compaction_tasks(&[]).await.unwrap(); + assert_eq!(tasks.len(), 1); + assert_eq!( + engine + .handle_request(region_id, cancel_request("stale")) + .await + .unwrap() + .affected_rows, + 0 + ); + for _ in 0..2 { + let actual = tokio::time::timeout( + Duration::from_secs(10), + engine.handle_request(region_id, cancel_request(&tasks[0].task_id)), + ) + .await + .unwrap(); + if commit_gate { + assert_eq!( + actual.unwrap_err().status_code(), + StatusCode::InvalidArguments + ); + } else { + assert_eq!(actual.unwrap().affected_rows, 1); + } + } + assert_eq!( + engine.inspect_compaction_tasks(&[]).await.unwrap()[0] + .state + .as_ref(), + if commit_gate { "running" } else { "cancelling" } + ); + drop(release); + let result = tokio::time::timeout(Duration::from_secs(20), compact) + .await + .unwrap() + .unwrap(); + assert_eq!(result.is_err(), !commit_gate); + tokio::time::timeout(Duration::from_secs(10), async { + while !engine + .inspect_compaction_tasks(&[]) + .await + .unwrap() + .is_empty() + { + tokio::task::yield_now().await; + } + }) + .await + .unwrap(); + assert_eq!( + engine + .handle_request(region_id, cancel_request(&tasks[0].task_id)) + .await + .unwrap() + .affected_rows, + 0 + ); + engine.stop().await.unwrap(); +} diff --git a/src/mito2/src/engine/compaction_test.rs b/src/mito2/src/engine/compaction_test.rs index ec9ddc5cf12..62a95c3a774 100644 --- a/src/mito2/src/engine/compaction_test.rs +++ b/src/mito2/src/engine/compaction_test.rs @@ -4053,3 +4053,181 @@ async fn test_open_overwrite_compaction_window_with_format(flat_format: bool) { ); } } + +async fn receive_region_event(rx: &mut tokio::sync::mpsc::UnboundedReceiver) -> RegionId { + tokio::time::timeout(Duration::from_secs(5), rx.recv()) + .await + .expect("timed out waiting for worker progress") + .expect("worker event channel closed") +} + +/// Holds admitted automatic units before I/O while observing real worker progress. +struct AutomaticBatchGate { + starts: tokio::sync::mpsc::UnboundedSender, + flushes: tokio::sync::mpsc::UnboundedSender, + picks: std::sync::Mutex>, + resume: Semaphore, +} + +#[async_trait] +impl EventListener for AutomaticBatchGate { + async fn on_compaction_pick_begin(&self, region_id: RegionId) { + *self.picks.lock().unwrap().entry(region_id).or_default() += 1; + } + + async fn on_compaction_unit_merge_begin(&self, region_id: RegionId, _: u64) { + let _ = self.starts.send(region_id); + self.resume.acquire().await.unwrap().forget(); + } + + fn on_flush_success(&self, region_id: RegionId) { + let _ = self.flushes.send(region_id); + } +} + +struct AutomaticBatchGuard(Arc); + +impl Drop for AutomaticBatchGuard { + fn drop(&mut self) { + self.0.resume.add_permits(100); + } +} + +#[rstest::rstest] +#[case::single_region(1)] +#[case::different_workers(2)] +#[tokio::test] +async fn test_automatic_units_share_engine_capacity_and_wait_for_batch_exit( + #[case] region_count: u32, +) { + let (starts, mut started) = tokio::sync::mpsc::unbounded_channel(); + let (flushes, mut flushed) = tokio::sync::mpsc::unbounded_channel(); + let gate = Arc::new(AutomaticBatchGate { + starts, + flushes, + picks: Default::default(), + resume: Semaphore::new(0), + }); + let guard = AutomaticBatchGuard(gate.clone()); + let time = Arc::new(MockTimeProvider::new(1000)); + let mut env = TestEnv::new().await; + let engine = env + .create_engine_with_time( + MitoConfig { + num_workers: 2, + max_background_compactions: 4, + min_compaction_interval: Duration::from_secs(3600), + ..Default::default() + }, + None, + Some(gate.clone()), + time.clone(), + ) + .await; + let regions: Vec<_> = (0..region_count) + .map(|n| RegionId::new(60 + n, 1)) + .collect(); + let mut schemas = HashMap::new(); + for ®ion_id in ®ions { + env.get_schema_metadata_manager() + .register_region_table_info( + region_id.table_id(), + "automatic_batch", + "test_catalog", + "test_schema", + None, + env.get_kv_backend(), + ) + .await; + let create = CreateRequestBuilder::new() + .insert_option("compaction.type", "twcs") + .insert_option("compaction.twcs.time_window", "1h") + .insert_option("compaction.twcs.trigger_file_num", "4") + .insert_option("compaction.twcs.inactive_window_trigger_file_num", "4") + .build(); + let columns = crate::test_util::rows_schema(&create); + engine + .handle_request(region_id, RegionRequest::Create(create)) + .await + .unwrap(); + for window in 0..4 { + for _ in 0..4 { + put_and_flush( + &engine, + region_id, + &columns, + window * 3600..window * 3600 + 2, + ) + .await; + assert_eq!(region_id, receive_region_event(&mut flushed).await); + } + } + schemas.insert(region_id, columns); + } + time.set_now(3_601_000); + // The first region can occupy all four slots, rather than remaining at P=1. + let first = regions[0]; + put_and_flush(&engine, first, &schemas[&first], 0..2).await; + for _ in 0..4 { + assert_eq!(first, receive_region_event(&mut started).await); + } + assert_eq!(first, receive_region_event(&mut flushed).await); + if region_count == 2 { + let second = regions[1]; + put_and_flush(&engine, second, &schemas[&second], 0..2).await; + assert_eq!(second, receive_region_event(&mut flushed).await); + } + // New flushes add a fifth window, but must not repick while this batch is blocked. + for _ in 0..4 { + put_and_flush(&engine, first, &schemas[&first], 4 * 3600..4 * 3600 + 2).await; + assert_eq!(first, receive_region_event(&mut flushed).await); + } + assert_eq!(1, gate.picks.lock().unwrap()[&first]); + assert!(started.try_recv().is_err()); + // One exit is insufficient to repick the first region. A different worker can + // use the returned slot; if it had its own pool it would already have started. + gate.resume.add_permits(1); + if region_count == 2 { + assert_eq!(regions[1], receive_region_event(&mut started).await); + assert!(started.try_recv().is_err()); + assert_eq!(1, gate.picks.lock().unwrap()[&first]); + } + drop(guard); + let mut followup_starts = HashMap::new(); + for _ in 0..(1 + (region_count - 1) * 3) { + *followup_starts + .entry(receive_region_event(&mut started).await) + .or_insert(0) += 1; + } + assert_eq!(Some(&1), followup_starts.get(&first)); + if region_count == 2 { + assert_eq!(Some(&3), followup_starts.get(®ions[1])); + } + assert!(gate.picks.lock().unwrap()[&first] >= 2); + // Manual waiters join after the automatic cycle. Completion checks actual + // manifest publication and the queued fifth-window follow-up, not just starts. + for ®ion_id in ®ions { + tokio::time::timeout( + Duration::from_secs(10), + engine.handle_request( + region_id, + RegionRequest::Compact(RegionCompactRequest::default()), + ), + ) + .await + .unwrap() + .unwrap(); + let region = engine.get_region(region_id).unwrap(); + assert!(region.version().ssts.levels()[0].files.is_empty()); + let stream = engine + .scan_to_stream(region_id, ScanRequest::default()) + .await + .unwrap(); + let rows = RecordBatches::try_collect(stream).await.unwrap(); + assert_eq!( + if region_id == first { 10 } else { 8 }, + rows.iter().map(|b| b.num_rows()).sum::() + ); + } + engine.stop().await.unwrap(); +} diff --git a/src/mito2/src/engine/copy_region_from_test.rs b/src/mito2/src/engine/copy_region_from_test.rs index 9f4fd6c251f..e4878b3d5f0 100644 --- a/src/mito2/src/engine/copy_region_from_test.rs +++ b/src/mito2/src/engine/copy_region_from_test.rs @@ -28,6 +28,186 @@ use crate::config::MitoConfig; use crate::error::Error; use crate::test_util::{CreateRequestBuilder, TestEnv, build_rows, put_rows, rows_schema}; +#[cfg(feature = "enterprise")] +#[rstest::rstest] +#[case::shared_only(false, false)] +#[case::mixed(true, false)] +#[case::metadata_rejected_before_copy(true, true)] +#[tokio::test] +async fn test_copy_shared_reference_contract(#[case] mixed: bool, #[case] metadata: bool) { + use crate::manifest::action::RegionEdit; + use crate::sst::file::{FileMeta, LEVEL_SHARED, RegionFileId}; + use crate::test_util::flush_region; + use std::collections::HashSet; + use store_api::region_request::PathType; + + let mut env = TestEnv::new().await; + let engine = env + .create_engine(MitoConfig { + schedule_compaction_after_edit: false, + ..Default::default() + }) + .await; + let owner_id = RegionId::new(1, 0); + let source_id = RegionId::new(1, 1); + let target_id = RegionId::new(1, 2); + let path_type = if metadata { + PathType::Metadata + } else { + PathType::Bare + }; + let mut create = CreateRequestBuilder::new().build(); + create.path_type = path_type; + for id in [owner_id, source_id, target_id] { + engine + .handle_request(id, RegionRequest::Create(create.clone())) + .await + .unwrap(); + } + for (id, start) in [(owner_id, 0), (source_id, 10)] { + if id == source_id && !mixed { + continue; + } + put_rows( + &engine, + id, + Rows { + schema: rows_schema(&create), + rows: build_rows(start, start + 3), + }, + ) + .await; + flush_region(&engine, id, None).await; + } + let owner = engine.get_region(owner_id).unwrap(); + let shared = FileMeta { + level: LEVEL_SHARED, + ..owner.version().ssts.levels()[0] + .files() + .next() + .unwrap() + .meta_ref() + .clone() + }; + for id in [owner_id, source_id] { + engine + .edit_region( + id, + RegionEdit { + files_to_add: vec![shared.clone()], + ..Default::default() + }, + ) + .await + .unwrap(); + } + let source = engine + .get_region(source_id) + .unwrap() + .manifest_ctx + .manifest() + .await; + let target = engine.get_region(target_id).unwrap(); + let before = target.manifest_ctx.manifest().await; + let target_path = |file_id| { + crate::sst::location::sst_file_path( + target.access_layer.table_dir(), + RegionFileId::new(target_id, file_id), + path_type, + ) + }; + let result = engine + .copy_region_from( + target_id, + MitoCopyRegionFromRequest { + source_region_id: source_id, + parallelism: 1, + }, + ) + .await; + if metadata { + assert!(matches!(result, Err(Error::InvalidRequest { .. }))); + let after = target.manifest_ctx.manifest().await; + assert_eq!(before.manifest_version, after.manifest_version); + assert_eq!(before.files, after.files); + assert_eq!(0, target.version_control.current().last_sequence); + for id in source.files.keys() { + assert!( + !target + .access_layer + .object_store() + .exists(&target_path(*id)) + .await + .unwrap() + ); + } + return; + } + let expected_ids = source.files.keys().copied().collect::>(); + assert_eq!( + expected_ids, + result + .unwrap() + .copied_file_ids + .into_iter() + .collect::>() + ); + let installed = target.manifest_ctx.manifest().await; + assert_eq!( + expected_ids, + installed.files.keys().copied().collect::>() + ); + for file in installed.files.values() { + assert_eq!( + if file.level == LEVEL_SHARED { + owner_id + } else { + target_id + }, + file.region_id + ); + assert_eq!( + file.level != LEVEL_SHARED, + target + .access_layer + .object_store() + .exists(&target_path(file.file_id)) + .await + .unwrap() + ); + assert_eq!(Some(1), file.sequence.map(|sequence| sequence.get())); + } + let sequence = target.version_control.current().last_sequence; + let retry = engine + .copy_region_from( + target_id, + MitoCopyRegionFromRequest { + source_region_id: source_id, + parallelism: 1, + }, + ) + .await + .unwrap(); + assert_eq!( + expected_ids, + retry.copied_file_ids.into_iter().collect::>() + ); + assert_eq!(installed.files, target.manifest_ctx.manifest().await.files); + assert_eq!(sequence, target.version_control.current().last_sequence); + let rows = RecordBatches::try_collect( + engine + .scan_to_stream(target_id, Default::default()) + .await + .unwrap(), + ) + .await + .unwrap(); + assert_eq!( + if mixed { 6 } else { 3 }, + rows.iter().map(|batch| batch.num_rows()).sum::() + ); +} + #[tokio::test] async fn test_engine_copy_region_from() { common_telemetry::init_default_ut_logging(); diff --git a/src/mito2/src/engine/edit_region_test.rs b/src/mito2/src/engine/edit_region_test.rs index 4ae44196e15..68db3def4cf 100644 --- a/src/mito2/src/engine/edit_region_test.rs +++ b/src/mito2/src/engine/edit_region_test.rs @@ -33,13 +33,15 @@ use store_api::region_request::{ use store_api::storage::{FileId, RegionId}; use tokio::sync::{Barrier, mpsc, oneshot}; +use crate::cache::file_cache::{FileType, IndexKey}; use crate::config::MitoConfig; use crate::engine::MitoEngine; use crate::engine::listener::EventListener; use crate::manifest::action::RegionEdit; use crate::region::{MitoRegionRef, RegionLeaderState, RegionRoleState}; use crate::request::{RegionEditRequest, WorkerRequest}; -use crate::sst::file::FileMeta; +use crate::sst::file::{ColumnIndexMetadata, FileMeta, IndexType}; +use crate::sst::location; use crate::test_util::{CreateRequestBuilder, TestEnv, build_rows, rows_schema}; use crate::time_provider::mock::MockTimeProvider; @@ -171,13 +173,15 @@ async fn test_edit_region_schedule_compaction_with_format( } } +#[rstest::rstest] +#[case::without_index(None)] +#[case::known_index_size(Some(7))] +#[case::unknown_index_size(Some(0))] #[tokio::test] -async fn test_edit_region_fill_cache() { - test_edit_region_fill_cache_with_format(false).await; - test_edit_region_fill_cache_with_format(true).await; -} - -async fn test_edit_region_fill_cache_with_format(flat_format: bool) { +async fn test_edit_region_fill_cache( + #[values(false, true)] flat_format: bool, + #[case] index_file_size: Option, +) { let mut env = TestEnv::new().await; struct EditRegionListener { @@ -229,13 +233,33 @@ async fn test_edit_region_fill_cache_with_format(flat_format: bool) { .await .unwrap(); - let edit = RegionEdit { - files_to_add: vec![FileMeta { - region_id: region.region_id, - file_id, - level: 0, + let mut meta = FileMeta { + region_id, + file_id, + index_version: 3, + ..Default::default() + }; + if let Some(size) = index_file_size { + meta.index_file_size = size; + meta.indexes.push(ColumnIndexMetadata { + column_id: 0, + created_indexes: smallvec::smallvec![IndexType::HllIndex], ..Default::default() - }], + }); + } + let index_path = location::index_file_path( + region.table_dir(), + meta.index_id(), + region.access_layer.path_type(), + ); + region + .access_layer + .object_store() + .write(&index_path, b"payload".as_slice()) + .await + .unwrap(); + let edit = RegionEdit { + files_to_add: vec![meta], files_to_remove: vec![], timestamp_ms: None, compaction_time_window: None, @@ -251,6 +275,21 @@ async fn test_edit_region_fill_cache_with_format(flat_format: bool) { .unwrap() .unwrap(); assert_eq!(file_id, actual); + // The listener runs after both download attempts, including the skipped-index path. + let cache_manager = engine.cache_manager(); + let file_cache = cache_manager.write_cache().unwrap().file_cache(); + let index_key = IndexKey::new(region_id, file_id, FileType::Puffin(3)); + let expected_cached = index_file_size.is_some_and(|size| size > 0); + assert_eq!(file_cache.contains_key(&index_key), expected_cached); + let path = file_cache.cache_file_path(index_key); + if expected_cached { + assert_eq!( + file_cache.local_store().read(&path).await.unwrap().to_vec(), + b"payload" + ); + } else { + assert!(!file_cache.local_store().exists(&path).await.unwrap()); + } } #[tokio::test] @@ -884,3 +923,339 @@ async fn test_edit_region_concurrently_with_format(flat_format: bool) { tasks_count * EDITS_PER_TASK ); } + +#[tokio::test] +async fn test_alter_precedes_edit_backlog() { + use store_api::region_request::{AddColumn, AlterKind, RegionAlterRequest}; + use tokio::sync::Notify; + struct Listener { + tx: mpsc::UnboundedSender, + altering: Notify, + release: Notify, + flushing: Notify, + release_flush: Notify, + } + #[async_trait::async_trait] + impl EventListener for Listener { + fn on_recv_requests(&self, count: usize) { + let _ = self.tx.send(count); + } + async fn on_flush_begin(&self, _: RegionId) { + self.flushing.notify_one(); + self.release_flush.notified().await; + } + async fn on_notify_region_change_result_begin(&self, _: RegionId) { + self.altering.notify_one(); + self.release.notified().await; + } + } + for (dirty, invalid) in [(false, false), (true, false), (false, true)] { + let mut env = TestEnv::new().await; + let (tx, mut rx) = mpsc::unbounded_channel(); + let listener = Arc::new(Listener { + tx, + altering: Notify::new(), + release: Notify::new(), + flushing: Notify::new(), + release_flush: Notify::new(), + }); + let engine = env + .create_engine_with( + MitoConfig { + schedule_compaction_after_edit: false, + ..Default::default() + }, + None, + Some(listener.clone()), + None, + ) + .await; + let region_id = RegionId::new(1, 1); + let create = CreateRequestBuilder::new().build(); + let schema = rows_schema(&create); + engine + .handle_request(region_id, RegionRequest::Create(create)) + .await + .unwrap(); + if dirty { + crate::test_util::put_rows( + &engine, + region_id, + Rows { + schema, + rows: build_rows(0, 1), + }, + ) + .await; + } + let region = engine.get_region(region_id).unwrap(); + let guard = region.manifest_ctx.manifest_manager.write().await; + let e = engine.clone(); + let first = tokio::spawn(async move { + e.edit_region(region_id, test_region_edit(region_id, FileId::random())) + .await + }); + wait_until_region_is_in_editing(®ion).await; + drain_worker_recv_events(&mut rx); + let file_id = FileId::random(); + let e = engine.clone(); + let queued = tokio::spawn(async move { + e.edit_region(region_id, test_region_edit(region_id, file_id)) + .await + }); + wait_worker_recv_event(&mut rx).await; + let e = engine.clone(); + let alter = tokio::spawn(async move { + e.handle_request( + region_id, + RegionRequest::Alter(RegionAlterRequest { + kind: AlterKind::AddColumns { + columns: vec![AddColumn { + column_metadata: store_api::metadata::ColumnMetadata { + column_schema: datatypes::schema::ColumnSchema::new( + if invalid { "ts" } else { "new_field" }, + datatypes::data_type::ConcreteDataType::float64_datatype(), + true, + ), + semantic_type: api::v1::SemanticType::Field, + column_id: 100, + }, + location: None, + }], + }, + }), + ) + .await + }); + wait_worker_recv_event(&mut rx).await; + drop(guard); + let late = if dirty { + tokio::time::timeout(Duration::from_secs(10), listener.flushing.notified()) + .await + .unwrap(); + drain_worker_recv_events(&mut rx); + let e = engine.clone(); + let task = tokio::spawn(async move { + e.edit_region(region_id, test_region_edit(region_id, FileId::random())) + .await + }); + wait_worker_recv_event(&mut rx).await; + listener.release_flush.notify_one(); + Some(task) + } else { + None + }; + if invalid { + assert!(alter.await.unwrap().is_err()); + first.await.unwrap().unwrap(); + tokio::time::timeout(Duration::from_secs(10), queued) + .await + .unwrap() + .unwrap() + .unwrap(); + continue; + } + tokio::time::timeout(Duration::from_secs(10), listener.altering.notified()) + .await + .unwrap(); + assert_eq!(None, region_file_sequence(®ion, file_id)); + assert!(!queued.is_finished()); + assert!(late.as_ref().is_none_or(|task| !task.is_finished())); + // Queue another ALTER while the first is waiting to notify the worker. + drain_worker_recv_events(&mut rx); + let e = engine.clone(); + let second_alter = tokio::spawn(async move { + e.handle_request( + region_id, + RegionRequest::Alter(RegionAlterRequest { + kind: AlterKind::AddColumns { + columns: vec![AddColumn { + column_metadata: store_api::metadata::ColumnMetadata { + column_schema: datatypes::schema::ColumnSchema::new( + "new_field_2", + datatypes::data_type::ConcreteDataType::float64_datatype(), + true, + ), + semantic_type: api::v1::SemanticType::Field, + column_id: 101, + }, + location: None, + }], + }, + }), + ) + .await + }); + wait_worker_recv_event(&mut rx).await; + listener.release.notify_one(); + tokio::time::timeout(Duration::from_secs(10), alter) + .await + .unwrap() + .unwrap() + .unwrap(); + tokio::time::timeout(Duration::from_secs(10), listener.altering.notified()) + .await + .unwrap(); + // Completing the first ALTER must hand off to the next ALTER before edits. + assert_eq!(None, region_file_sequence(®ion, file_id)); + assert!(!queued.is_finished()); + assert!(late.as_ref().is_none_or(|task| !task.is_finished())); + listener.release.notify_one(); + tokio::time::timeout(Duration::from_secs(10), second_alter) + .await + .unwrap() + .unwrap() + .unwrap(); + let metadata = region.metadata(); + assert_eq!(metadata.column_by_name("new_field").unwrap().column_id, 100); + assert_eq!( + metadata.column_by_name("new_field_2").unwrap().column_id, + 101 + ); + first.await.unwrap().unwrap(); + tokio::time::timeout(Duration::from_secs(10), queued) + .await + .unwrap() + .unwrap() + .unwrap(); + assert!(region_file_sequence(®ion, file_id).is_some()); + if let Some(late) = late { + tokio::time::timeout(Duration::from_secs(10), late) + .await + .unwrap() + .unwrap() + .unwrap(); + } + } +} + +#[tokio::test] +async fn test_drop_rejects_alter_and_edit_queues_after_flush_commit() { + use store_api::region_request::{ + AddColumn, AlterKind, RegionAlterRequest, RegionDropRequest, RegionFlushRequest, + }; + use tokio::sync::Notify; + + struct Listener { + tx: mpsc::UnboundedSender, + committing: Notify, + release: Notify, + } + + #[async_trait::async_trait] + impl EventListener for Listener { + fn on_recv_requests(&self, count: usize) { + let _ = self.tx.send(count); + } + + async fn on_flush_commit_begin(&self, _: RegionId) { + self.committing.notify_one(); + self.release.notified().await; + } + } + + let mut env = TestEnv::new().await; + let (tx, mut rx) = mpsc::unbounded_channel(); + let listener = Arc::new(Listener { + tx, + committing: Notify::new(), + release: Notify::new(), + }); + let engine = env + .create_engine_with(MitoConfig::default(), None, Some(listener.clone()), None) + .await; + let region_id = RegionId::new(1, 1); + let create = CreateRequestBuilder::new().build(); + let schema = rows_schema(&create); + engine + .handle_request(region_id, RegionRequest::Create(create)) + .await + .unwrap(); + crate::test_util::put_rows( + &engine, + region_id, + Rows { + schema, + rows: build_rows(0, 1), + }, + ) + .await; + + let e = engine.clone(); + let flush = tokio::spawn(async move { + e.handle_request( + region_id, + RegionRequest::Flush(RegionFlushRequest::default()), + ) + .await + }); + tokio::time::timeout(Duration::from_secs(10), listener.committing.notified()) + .await + .unwrap(); + drain_worker_recv_events(&mut rx); + + // DROP can no longer cancel the flush, so it waits for successful completion. + let e = engine.clone(); + let drop = tokio::spawn(async move { + e.handle_request( + region_id, + RegionRequest::Drop(RegionDropRequest { + fast_path: false, + force: false, + partial_drop: false, + }), + ) + .await + }); + wait_worker_recv_event(&mut rx).await; + + // The first ALTER waits in the flush scheduler; the second uses pending_alters. + let mut alters = Vec::new(); + for _ in 0..2 { + let e = engine.clone(); + alters.push(tokio::spawn(async move { + e.handle_request( + region_id, + RegionRequest::Alter(RegionAlterRequest { + kind: AlterKind::AddColumns { + columns: vec![AddColumn { + column_metadata: store_api::metadata::ColumnMetadata { + column_schema: datatypes::schema::ColumnSchema::new( + "new_field", + datatypes::data_type::ConcreteDataType::float64_datatype(), + true, + ), + semantic_type: api::v1::SemanticType::Field, + column_id: 100, + }, + location: None, + }], + }, + }), + ) + .await + })); + wait_worker_recv_event(&mut rx).await; + } + let e = engine.clone(); + let edit = tokio::spawn(async move { + e.edit_region(region_id, test_region_edit(region_id, FileId::random())) + .await + }); + wait_worker_recv_event(&mut rx).await; + listener.release.notify_one(); + + tokio::time::timeout(Duration::from_secs(10), async { + flush.await.unwrap().unwrap(); + drop.await.unwrap().unwrap(); + assert!(engine.get_region(region_id).is_none()); + for alter in alters { + let err = alter.await.unwrap().unwrap_err(); + assert_eq!(err.status_code(), StatusCode::RegionNotFound); + } + let err = edit.await.unwrap().unwrap_err(); + assert_eq!(err.status_code(), StatusCode::RegionNotFound); + }) + .await + .expect("DROP left queued ALTER or edit requests unresolved"); +} diff --git a/src/mito2/src/engine/flush_test.rs b/src/mito2/src/engine/flush_test.rs index 40b4cce0dbc..399b5857700 100644 --- a/src/mito2/src/engine/flush_test.rs +++ b/src/mito2/src/engine/flush_test.rs @@ -352,7 +352,7 @@ async fn test_manual_flush_with_format(flat_format: bool) { } #[tokio::test] -async fn test_flushed_parquet_bytes() { +async fn test_ingested_parquet_bytes() { for flat_format in [false, true] { let mut env = TestEnv::with_prefix("flushed-parquet-bytes").await; let engine = env @@ -374,7 +374,7 @@ async fn test_flushed_parquet_bytes() { .await .unwrap(); let statistic = || engine.get_region_statistic(region_id).unwrap(); - assert_eq!(statistic().flushed_parquet_bytes, 0); + assert_eq!(statistic().ingested_parquet_bytes, 0); let mut previous_bytes = 0; for start in [0, 10] { @@ -387,7 +387,7 @@ async fn test_flushed_parquet_bytes() { }, ) .await; - assert_eq!(statistic().flushed_parquet_bytes, previous_bytes); + assert_eq!(statistic().ingested_parquet_bytes, previous_bytes); flush_region(&engine, region_id, None).await; let manifest = engine .get_region(region_id) @@ -397,11 +397,11 @@ async fn test_flushed_parquet_bytes() { .await; let parquet_bytes: u64 = manifest.files.values().map(|file| file.file_size).sum(); assert!(parquet_bytes > previous_bytes); - assert_eq!(statistic().flushed_parquet_bytes, parquet_bytes); + assert_eq!(statistic().ingested_parquet_bytes, parquet_bytes); previous_bytes = parquet_bytes; } flush_region(&engine, region_id, None).await; - assert_eq!(statistic().flushed_parquet_bytes, previous_bytes); + assert_eq!(statistic().ingested_parquet_bytes, previous_bytes); // A generic edit can add the same file metadata without producing a flush. let file = engine @@ -430,7 +430,7 @@ async fn test_flushed_parquet_bytes() { ) .await .unwrap(); - assert_eq!(statistic().flushed_parquet_bytes, previous_bytes); + assert_eq!(statistic().ingested_parquet_bytes, previous_bytes); engine .handle_request( @@ -446,11 +446,11 @@ async fn test_flushed_parquet_bytes() { ) .await .unwrap(); - assert_eq!(statistic().flushed_parquet_bytes, previous_bytes); + assert_eq!(statistic().ingested_parquet_bytes, previous_bytes); assert_eq!(statistic().sst_num, 1); reopen_region(&engine, region_id, table_dir, true, HashMap::new()).await; assert!(statistic().sst_size > 0); - assert_eq!(statistic().flushed_parquet_bytes, 0); + assert_eq!(statistic().ingested_parquet_bytes, 0); } } diff --git a/src/mito2/src/engine/object_store_wal_recovery_test.rs b/src/mito2/src/engine/object_store_wal_recovery_test.rs index 0c028e067db..d5ae88b1d9b 100644 --- a/src/mito2/src/engine/object_store_wal_recovery_test.rs +++ b/src/mito2/src/engine/object_store_wal_recovery_test.rs @@ -755,7 +755,7 @@ async fn test_open_on_an_empty_prefix_requires_accepting_the_missing_history() { assert_missing_history( &err, REGION_A, - "the prefix held no object when the WAL opened", + "the prefix held no object when the prefix was listed", ); assert!(!engine.is_region_exists(REGION_A)); assert!(wal_object_seqs(&new_location).await.is_empty()); @@ -923,7 +923,7 @@ async fn test_moving_the_wal_keeps_the_history_only_with_its_objects() { // nor through a catch-up after an open that skipped the replay. let store = open_store(&memory_store(), AckMode::Durable).await; let engine = new_engine(&mut env, store.clone()).await; - let reason = "the prefix held no object when the WAL opened"; + let reason = "the prefix held no object when the prefix was listed"; let err = open_region(&engine, REGION_A, &table_dir, &[]) .await .unwrap_err(); @@ -1046,7 +1046,7 @@ async fn test_open_region_fails_when_its_watermark_is_above_the_wal_objects() { .await .unwrap_err(); let reason = format!( - "its watermark, entry {watermark}, names object {}, but the prefix held entries only in objects below 2 when the WAL opened", + "its watermark, entry {watermark}, names object {}, but the prefix held entries only in objects below 2 when the prefix was listed", watermark >> 20 ); assert_missing_history(&err, region_id, &reason); @@ -1866,7 +1866,7 @@ async fn test_flush_does_not_publish_a_frontier_for_a_lost_enqueued_backlog() { engine .get_region_statistic(REGION_A) .unwrap() - .flushed_parquet_bytes, + .ingested_parquet_bytes, 0 ); assert!(store.stop().await.is_err()); diff --git a/src/mito2/src/engine/object_store_wal_test.rs b/src/mito2/src/engine/object_store_wal_test.rs index 5a61d8b6733..6a600958bf9 100644 --- a/src/mito2/src/engine/object_store_wal_test.rs +++ b/src/mito2/src/engine/object_store_wal_test.rs @@ -17,8 +17,11 @@ use std::collections::HashMap; use std::sync::Arc; use std::sync::atomic::Ordering; +use std::time::{Duration, Instant}; -use api::v1::Rows; +use api::v1::region::{StrictWindow, compact_request}; +use api::v1::{ColumnSchema, Rows}; +use common_datasource::compression::CompressionType; use common_error::ext::ErrorExt; use common_error::status_code::StatusCode; use common_recordbatch::RecordBatches; @@ -26,19 +29,24 @@ use common_wal::config::object_store::{ObjectStoreWalConfig, STANDALONE_GENERATI use common_wal::options::{ObjectStoreWalOptions, WAL_OPTIONS_KEY, WalOptions}; use futures::TryStreamExt; use log_store::ObjectStoreLogStore; +use object_store::ObjectStore; +use rstest::rstest; use store_api::logstore::LogStore; use store_api::logstore::provider::Provider; -use store_api::region_engine::RegionEngine; +use store_api::region_engine::{RegionEngine, RegionRole}; use store_api::region_request::{ - PathType, RegionCleanUpRequest, RegionCloseRequest, RegionDropRequest, RegionOpenRequest, - RegionRequest, + PathType, RegionCleanUpRequest, RegionCloseRequest, RegionCompactRequest, RegionDropRequest, + RegionFlushRequest, RegionOpenRequest, RegionRequest, RegionTruncateRequest, }; use store_api::storage::{RegionId, ScanRequest}; use crate::config::MitoConfig; use crate::engine::MitoEngine; +use crate::manifest::storage::{delta_file, gen_path, manifest_dir}; +use crate::sst::location::region_dir_from_table_dir; use crate::test_util::{ - CreateRequestBuilder, TestEnv, build_rows, flush_region, put_rows, reopen_region, rows_schema, + CheckpointTaskBlocker, CreateRequestBuilder, TestEnv, build_rows, flush_region, nop_action, + put_rows, reopen_region, rows_schema, }; use crate::wal::EntryId; @@ -377,3 +385,187 @@ async fn test_object_store_wal_options_reject_raft_engine_log_store() { .unwrap_err(); assert_eq!(StatusCode::InvalidArguments, err.status_code()); } + +/// Returns a config that starts a checkpoint on every commit. +fn checkpoint_every_commit_config() -> MitoConfig { + MitoConfig { + manifest_checkpoint_distance: 1, + ..Default::default() + } +} + +/// Creates a region whose writes require a lease. Returns the lease deadline, which the frozen +/// clock of the lease checks has not reached. +async fn create_leased_region( + env: &mut TestEnv, + region_id: RegionId, +) -> ( + MitoEngine, + Arc, + String, + Vec, + Instant, +) { + let (engine, log_store) = env + .create_engine_with_object_store_wal(checkpoint_every_commit_config(), &wal_config()) + .await; + engine.require_write_lease(); + engine.freeze_lease_clock(Instant::now()); + let (table_dir, schema) = create_region(&engine, region_id).await; + let deadline = Instant::now() + Duration::from_secs(10); + engine + .set_region_role_with_lease(region_id, RegionRole::Leader, Instant::now(), deadline) + .unwrap(); + (engine, log_store, table_dir, schema, deadline) +} + +async fn count_ssts(store: &ObjectStore, region_dir: &str) -> usize { + let entries = store.list(region_dir).await.unwrap(); + entries + .iter() + .filter(|e| e.name().ends_with(".parquet")) + .count() +} + +#[rstest] +#[case::flush(RegionRequest::Flush(RegionFlushRequest::default()), 1)] +#[case::compaction( + RegionRequest::Compact(RegionCompactRequest { + options: compact_request::Options::StrictWindow(StrictWindow { window_seconds: 3600 }), + ..Default::default() + }), + 1 +)] +#[case::truncate(RegionRequest::Truncate(RegionTruncateRequest::All), 0)] +#[tokio::test] +async fn test_stale_commit_on_deleted_delta_name_conflicts( + #[case] commit: RegionRequest, + #[case] new_ssts: usize, +) { + common_telemetry::init_default_ut_logging(); + // The creation is version 0 and the flushes below are versions 1 and 2. + const VERSION: u64 = 3; + let (blocker, layer) = CheckpointTaskBlocker::block_delta_write(VERSION); + let mut env = TestEnv::with_prefix("stale-manifest-commit") + .await + .with_mock_layer(layer); + let region_id = RegionId::new(1, 1); + let (old_leader, log_store, table_dir, schema, deadline) = + create_leased_region(&mut env, region_id).await; + let rows = |start| Rows { + schema: schema.clone(), + rows: build_rows(start, start + 3), + }; + for start in [0, 3] { + put_rows(&old_leader, region_id, rows(start)).await; + flush_region(&old_leader, region_id, None).await; + } + put_rows(&old_leader, region_id, rows(6)).await; + + let region = old_leader.get_region(region_id).unwrap(); + let (manifest, checkpoint) = { + let mut manager = region.manifest_ctx.manifest_manager.write().await; + manager.wait_for_pending_checkpoint().await; + ( + manager.manifest(), + manager.checkpointer().last_checkpoint_version(), + ) + }; + let store = env.get_object_store().unwrap(); + let region_dir = region_dir_from_table_dir(&table_dir, region_id, PathType::Bare); + let ssts = count_ssts(&store, ®ion_dir).await; + + let engine = old_leader.clone(); + let commit = tokio::spawn(async move { engine.handle_request(region_id, commit).await }); + blocker.wait_until_blocked().await; + let version = region.version_control.current().version; + let entry_ids = stored_entry_ids(&log_store, region_id).await; + + let new_holder = env + .create_engine_with_log_store(checkpoint_every_commit_config(), log_store.clone()) + .await; + new_holder.require_write_lease(); + let open = RegionRequest::Open(open_request(table_dir.clone())); + new_holder.handle_request(region_id, open).await.unwrap(); + let delta = gen_path( + &manifest_dir(®ion_dir), + &delta_file(VERSION), + CompressionType::Gzip, + ); + { + let held = new_holder.get_region(region_id).unwrap(); + let mut manager = held.manifest_ctx.manifest_manager.write().await; + assert_eq!(VERSION - 1, manager.last_version()); + while manager.last_version() < VERSION || store.exists(&delta).await.unwrap() { + manager + .update_with_verification(nop_action(), false, true, || false) + .await + .unwrap(); + manager.wait_for_pending_checkpoint().await; + } + } + + old_leader.freeze_lease_clock(deadline); + blocker.release(); + let error = commit.await.unwrap().unwrap_err(); + assert!(error.retry_hint().is_retryable(), "{error:?}"); + assert!(format!("{error:?}").contains("conflicts"), "{error:?}"); + + let manager = region.manifest_ctx.manifest_manager.read().await; + assert_eq!(VERSION - 1, manager.last_version()); + assert!(Arc::ptr_eq(&manifest, &manager.manifest())); + assert_eq!(checkpoint, manager.checkpointer().last_checkpoint_version()); + assert!(!manager.checkpointer().is_doing_checkpoint()); + drop(manager); + assert!(Arc::ptr_eq( + &version, + ®ion.version_control.current().version + )); + assert_eq!(ssts + new_ssts, count_ssts(&store, ®ion_dir).await); + assert!(store.exists(&delta).await.unwrap()); + assert_eq!(entry_ids, stored_entry_ids(&log_store, region_id).await); + + reopen_region(&new_holder, region_id, table_dir, false, wal_options()).await; + assert_eq!(9, count_rows(&new_holder, region_id).await); +} + +#[tokio::test] +async fn test_commit_crossing_deadline_applies_without_checkpoint() { + common_telemetry::init_default_ut_logging(); + let (blocker, layer) = CheckpointTaskBlocker::block_delta_write(1); + let mut env = TestEnv::with_prefix("commit-crossing-deadline") + .await + .with_mock_layer(layer); + let region_id = RegionId::new(1, 1); + let (engine, log_store, table_dir, schema, deadline) = + create_leased_region(&mut env, region_id).await; + let rows = Rows { + schema, + rows: build_rows(0, 3), + }; + put_rows(&engine, region_id, rows).await; + + let flush = { + let engine = engine.clone(); + tokio::spawn(async move { + let request = RegionRequest::Flush(RegionFlushRequest::default()); + engine.handle_request(region_id, request).await + }) + }; + blocker.wait_until_blocked().await; + engine.freeze_lease_clock(deadline); + blocker.release(); + flush.await.unwrap().unwrap(); + + let region = engine.get_region(region_id).unwrap(); + let manager = region.manifest_ctx.manifest_manager.read().await; + assert_eq!(1, manager.last_version()); + assert_eq!(1, region.version().ssts.levels()[0].files.len()); + assert_eq!(0, manager.checkpointer().last_checkpoint_version()); + assert!(!manager.checkpointer().is_doing_checkpoint()); + assert!(stored_entry_ids(&log_store, region_id).await.is_empty()); + drop(manager); + + reopen_region(&engine, region_id, table_dir, false, wal_options()).await; + assert_eq!(3, count_rows(&engine, region_id).await); +} diff --git a/src/mito2/src/engine/open_test.rs b/src/mito2/src/engine/open_test.rs index 13915dc1ef7..d566e56ccd8 100644 --- a/src/mito2/src/engine/open_test.rs +++ b/src/mito2/src/engine/open_test.rs @@ -1366,3 +1366,66 @@ async fn test_region_hook_on_open() { assert_eq!(hook.closed_count.load(Ordering::Relaxed), 1); assert_eq!(hook.dropped_count.load(Ordering::Relaxed), 0); } + +#[tokio::test] +async fn test_reopen_region_with_compressed_manifest_cache() { + let mut env = TestEnv::new().await; + let engine = env + .create_engine(MitoConfig { + enable_write_cache: true, + compress_manifest: true, + manifest_checkpoint_distance: 1, + ..Default::default() + }) + .await; + let region_id = RegionId::new(1, 1); + let request = CreateRequestBuilder::new().build(); + let table_dir = request.table_dir.clone(); + let schema = rows_schema(&request); + engine + .handle_request(region_id, RegionRequest::Create(request)) + .await + .unwrap(); + for i in 0..3 { + put_rows( + &engine, + region_id, + Rows { + schema: schema.clone(), + rows: build_rows(i * 3, (i + 1) * 3), + }, + ) + .await; + flush_region(&engine, region_id, None).await; + } + let region = engine.get_region(region_id).unwrap(); + let mut manager = region.manifest_ctx.manifest_manager.write().await; + tokio::time::timeout( + Duration::from_secs(10), + manager.wait_for_pending_checkpoint(), + ) + .await + .unwrap(); + assert!(manager.checkpointer().last_checkpoint_version() > 0); + drop(manager); + let stream = engine + .scan_to_stream(region_id, ScanRequest::default()) + .await + .unwrap(); + let expected = RecordBatches::try_collect(stream) + .await + .unwrap() + .pretty_print() + .unwrap(); + reopen_region(&engine, region_id, table_dir, true, HashMap::new()).await; + let stream = engine + .scan_to_stream(region_id, ScanRequest::default()) + .await + .unwrap(); + let actual = RecordBatches::try_collect(stream) + .await + .unwrap() + .pretty_print() + .unwrap(); + assert_eq!(expected, actual); +} diff --git a/src/mito2/src/engine/partition_filter_test.rs b/src/mito2/src/engine/partition_filter_test.rs index 70a4b7c487f..9e02d59e46e 100644 --- a/src/mito2/src/engine/partition_filter_test.rs +++ b/src/mito2/src/engine/partition_filter_test.rs @@ -20,13 +20,15 @@ use datatypes::arrow::array::AsArray; use datatypes::value::Value; use partition::expr::{Operand, col}; use partition::function::IcebergHash; -use store_api::region_engine::RegionEngine; +use store_api::region_engine::{RegionEngine, RemapManifestsRequest}; use store_api::region_request::{ - EnterStagingRequest, RegionFlushRequest, RegionRequest, StagingPartitionDirective, + ApplyStagingManifestRequest, EnterStagingRequest, RegionFlushRequest, RegionRequest, + StagingPartitionDirective, }; use store_api::storage::{RegionId, ScanRequest}; use crate::config::MitoConfig; +use crate::engine::MitoEngine; use crate::test_util::{CreateRequestBuilder, TestEnv, build_rows, put_rows, rows_schema}; /// Helper to create a partition expression for testing. @@ -39,6 +41,30 @@ fn range_expr_string(col_name: &str, start: f64, end: f64) -> String { .unwrap() } +/// Ends staging the way repartition does, importing the region's own files. +async fn apply_staging(engine: &MitoEngine, region_id: RegionId, partition_expr: String) { + let result = engine + .remap_manifests(RemapManifestsRequest { + region_id, + input_regions: vec![region_id], + region_mapping: [(region_id, vec![region_id])].into_iter().collect(), + new_partition_exprs: [(region_id, partition_expr.clone())].into_iter().collect(), + }) + .await + .unwrap(); + engine + .handle_request( + region_id, + RegionRequest::ApplyStagingManifest(ApplyStagingManifestRequest { + partition_expr, + central_region_id: region_id, + manifest_path: result.manifest_paths[®ion_id].clone(), + }), + ) + .await + .unwrap(); +} + #[tokio::test] async fn test_partition_filter_basic() { test_partition_filter_basic_with_format(false).await; @@ -51,7 +77,7 @@ async fn test_partition_filter_basic() { /// 1. Creates a region with partition expr `tag_0 >= "0"` (covers all data) /// 2. Writes data (tag_0 = "0"..="9") and flushes - SST has old partition expr /// 3. Enters staging mode with partition expr `tag_0 >= "5"` (narrower) -/// 4. Writes more data and flushes in staging mode +/// 4. Writes more data in staging mode /// 5. Exits staging mode - region now has new partition expr /// 6. Scans all data - old SST data not matching new expr should be filtered async fn test_partition_filter_basic_with_format(flat_format: bool) { @@ -118,16 +144,7 @@ async fn test_partition_filter_basic_with_format(flat_format: bool) { }; put_rows(&engine, region_id, rows_data).await; - // Flush in staging mode - engine - .handle_request( - region_id, - RegionRequest::Flush(RegionFlushRequest::default()), - ) - .await - .unwrap(); - - // Scan data in staging mode - should only see initial 5 rows (staging SST not visible) + // Scan data in staging mode - rows written in staging stay readable in the memtable let projection = Some(vec![1]); let request = ScanRequest { projection, @@ -138,20 +155,16 @@ async fn test_partition_filter_basic_with_format(flat_format: bool) { let batches = RecordBatches::try_collect(stream).await.unwrap(); let total_rows: usize = batches.iter().map(|rb| rb.num_rows()).sum(); assert_eq!( - total_rows, 5, - "Should see 5 rows before exiting staging mode" + total_rows, 11, + "Should see 11 rows before exiting staging mode" ); // Exit staging mode - use store_api::region_engine::SettableRegionRoleState; - engine - .set_region_role_state_gracefully(region_id, SettableRegionRoleState::Leader) - .await - .unwrap(); + apply_staging(&engine, region_id, new_partition_expr).await; // Scan after exiting staging - the old SST (tag_0 = "0".."4") should have // rows filtered by partition expr (tag_0 >= "5"), which means none of them pass. - // But the staging SST (tag_0 = "5".."10") satisfies the partition expr. + // But the memtable rows (tag_0 = "5".."10") satisfy the partition expr. let projection = Some(vec![1]); let request = ScanRequest { projection, @@ -163,10 +176,10 @@ async fn test_partition_filter_basic_with_format(flat_format: bool) { let total_rows: usize = batches.iter().map(|rb| rb.num_rows()).sum(); // After exit: // - Old SST (rows 0-4): partition expr is "tag_0 >= 5", so these are filtered out - // - Staging SST (rows 5-10): These satisfy partition expr, so they're visible + // - Memtable (rows 5-10): These satisfy partition expr, so they're visible assert_eq!( total_rows, 6, - "Should see 6 rows after exiting staging (rows 5-10 from staging SST), flat_format: {}", + "Should see 6 rows after exiting staging (rows 5-10 from the memtable), flat_format: {}", flat_format ); } @@ -220,13 +233,16 @@ async fn test_partition_filter_iceberg_hash_with_format(flat_format: bool) { IcebergHash::evaluate_value(&Value::String(i.to_string().as_str().into())).unwrap() < Value::Int32(0) }; - let hash_expr = Operand::IcebergHash(IcebergHash::new("tag_0")).lt(Value::Int32(0)); + let hash_expr = Operand::IcebergHash(IcebergHash::new("tag_0")) + .lt(Value::Int32(0)) + .as_json_str() + .unwrap(); engine .handle_request( region_id, RegionRequest::EnterStaging(EnterStagingRequest { partition_directive: StagingPartitionDirective::UpdatePartitionExpr( - hash_expr.as_json_str().unwrap(), + hash_expr.clone(), ), }), ) @@ -244,12 +260,7 @@ async fn test_partition_filter_iceberg_hash_with_format(flat_format: bool) { }, ) .await; - flush().await; - use store_api::region_engine::SettableRegionRoleState; - engine - .set_region_role_state_gracefully(region_id, SettableRegionRoleState::Leader) - .await - .unwrap(); + apply_staging(&engine, region_id, hash_expr).await; let request = ScanRequest { projection: Some(vec![0]), diff --git a/src/mito2/src/engine/puffin_index.rs b/src/mito2/src/engine/puffin_index.rs index 975569aa213..0e908427db8 100644 --- a/src/mito2/src/engine/puffin_index.rs +++ b/src/mito2/src/engine/puffin_index.rs @@ -24,6 +24,7 @@ use index::fulltext_index::Config as FulltextConfig; use index::inverted_index::format::reader::{InvertedIndexBlobReader, InvertedIndexReader}; use index::target::IndexTarget; use puffin::blob_metadata::BlobMetadata; +use puffin::puffin_manager::file_key::PuffinFileKey; use puffin::puffin_manager::{PuffinManager, PuffinReader}; use serde_json::{Map, Value, json}; use store_api::sst_entry::{ @@ -75,6 +76,7 @@ pub(crate) async fn collect_index_entries_from_puffin( ) -> Vec { let mut entries = Vec::new(); + let file_key = manager.file_key(®ion_index_id); let reader = match manager.reader(®ion_index_id).await { Ok(reader) => reader, Err(err) => { @@ -106,7 +108,7 @@ pub(crate) async fn collect_index_entries_from_puffin( Some(BlobIndexTypeTargetKey::BloomFilter(target_key)) => { let bloom_meta = try_read_bloom_meta( &reader, - region_index_id, + &file_key, blob.blob_type.as_str(), target_key, bloom_filter_cache.as_ref(), @@ -132,7 +134,7 @@ pub(crate) async fn collect_index_entries_from_puffin( Some(BlobIndexTypeTargetKey::FulltextBloom(target_key, bloom_version)) => { let bloom_meta = try_read_bloom_meta( &reader, - region_index_id, + &file_key, blob.blob_type.as_str(), target_key, bloom_filter_cache.as_ref(), @@ -174,7 +176,7 @@ pub(crate) async fn collect_index_entries_from_puffin( Some(BlobIndexTypeTargetKey::Inverted) => { let mut inverted_entries = collect_inverted_entries( &reader, - region_index_id, + &file_key, inverted_index_cache.as_ref(), &context, ) @@ -190,13 +192,11 @@ pub(crate) async fn collect_index_entries_from_puffin( async fn collect_inverted_entries( reader: &SstPuffinReader, - region_index_id: RegionIndexId, + file_key: &PuffinFileKey, cache: Option<&InvertedIndexCacheRef>, context: &IndexEntryContext<'_>, ) -> Vec { // Read the inverted index blob and surface its per-column metadata entries. - let file_id = region_index_id.file_id(); - let guard = match reader.blob(INVERTED_BLOB_TYPE).await { Ok(guard) => guard, Err(err) => { @@ -230,8 +230,7 @@ async fn collect_inverted_entries( .map(|meta| meta.content_length); let metas = if let (Some(cache), Some(blob_size)) = (cache, blob_size) { let reader = CachedInvertedIndexBlobReader::new( - file_id, - region_index_id.version, + file_key.clone(), blob_size, InvertedIndexBlobReader::new(blob_reader), cache.clone(), @@ -292,7 +291,7 @@ fn build_inverted_entries( async fn try_read_bloom_meta( reader: &SstPuffinReader, - region_index_id: RegionIndexId, + file_key: &PuffinFileKey, blob_type: &str, target_key: &str, cache: Option<&BloomFilterIndexCacheRef>, @@ -314,8 +313,7 @@ async fn try_read_bloom_meta( let result = match (cache, column_id, blob_size) { (Some(cache), Some(column_id), Some(blob_size)) => { CachedBloomFilterIndexBlobReader::new( - region_index_id.file_id(), - region_index_id.version, + file_key.clone(), IndexTarget::ColumnId(column_id), tag, blob_size, diff --git a/src/mito2/src/engine/region_hook.rs b/src/mito2/src/engine/region_hook.rs index c8b736d2894..b3ecb4a1cdc 100644 --- a/src/mito2/src/engine/region_hook.rs +++ b/src/mito2/src/engine/region_hook.rs @@ -120,8 +120,8 @@ //! immediately after SST files are written but **before** the manifest is committed. //! //! `on_manifest_updated` is funneled through [`ManifestContext::update_locked`], -//! the sole caller of the low-level [`RegionManifestManager::update`], which -//! packages each successful write into a [`PendingManifestHook`]. The caller +//! which calls the low-level [`RegionManifestManager::update_with_verification`] +//! and packages each successful write into a [`PendingManifestHook`]. The caller //! owns the write lock, drops it, and *then* fires the receipt — the hook must //! never run under the lock. [`ManifestContext::update_manifest`] is the common //! case: it acquires the lock, delegates to `update_locked`, and fires the @@ -148,10 +148,11 @@ //! [`on_region_dropped`]: RegionHook::on_region_dropped //! [`on_region_files_removed`]: RegionHook::on_region_files_removed //! [`on_region_gc`]: RegionHook::on_region_gc -//! [`RegionManifestManager::update`]: crate::manifest::manager::RegionManifestManager::update +//! [`RegionManifestManager::update_with_verification`]: crate::manifest::manager::RegionManifestManager::update_with_verification //! [`ManifestContext::update_locked`]: crate::region::ManifestContext::update_locked //! [`ManifestContext::update_manifest`]: crate::region::ManifestContext::update_manifest +use std::collections::HashSet; use std::fmt::Debug; use std::sync::Arc; @@ -160,10 +161,10 @@ use store_api::ManifestVersion; use store_api::metadata::RegionMetadataRef; use store_api::storage::RegionId; -use crate::access_layer::AccessLayerRef; +use crate::access_layer::{AccessLayer, AccessLayerRef}; use crate::error::Result; use crate::manifest::action::{RegionMetaActionList, RemovedFile}; -use crate::sst::file::FileMeta; +use crate::sst::file::{FileMeta, RegionFileId}; use crate::sst::parquet::SstInfo; /// A deferred [`RegionHook::on_manifest_updated`] notification produced by a @@ -299,6 +300,21 @@ pub trait RegionHook: Send + Sync + Debug { let _ = (region_id, region_metadata, files); } + /// Queries durable file protections immediately before deletion. Implementations + /// must include pending uploads, inputs and undecided outputs, and fail on + /// unavailable/uncertain state. File identities are scoped by the access layer's + /// storage, table directory and PathType; protection covers all index generations. + /// GC rechecks the manifest after this await. This is not `on_region_gc`, which + /// is too late to protect anything. Calls must not retain a manifest lock. + async fn protected_sst_files( + &self, + access: &AccessLayer, + files: &[RegionFileId], + ) -> Result> { + let _ = (access, files); + Ok(HashSet::new()) + } + /// Called after the region manifest is successfully committed to the **live** /// (normal) manifest directory. /// diff --git a/src/mito2/src/engine/shared_file_test.rs b/src/mito2/src/engine/shared_file_test.rs new file mode 100644 index 00000000000..36e32697f38 --- /dev/null +++ b/src/mito2/src/engine/shared_file_test.rs @@ -0,0 +1,499 @@ +// 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 store_api::region_engine::RegionEngine; +use store_api::region_request::RegionRequest; +use store_api::storage::{FileId, RegionId}; + +use crate::config::MitoConfig; +use crate::manifest::action::{RegionEdit, RegionMetaAction, RegionMetaActionList}; +use crate::sst::file::{FileMeta, LEVEL_SHARED, SHARED_LEVEL_SLOT}; +use crate::test_util::{CreateRequestBuilder, TestEnv}; + +#[tokio::test] +async fn test_shared_import_preserves_visible_sequence_and_rejects_overwrite() { + let mut env = TestEnv::new().await; + let engine = env + .create_engine(MitoConfig { + schedule_compaction_after_edit: false, + ..Default::default() + }) + .await; + let region_id = RegionId::new(1, 1); + engine + .handle_request( + region_id, + RegionRequest::Create(CreateRequestBuilder::new().build()), + ) + .await + .unwrap(); + let region = engine.get_region(region_id).unwrap(); + let source = FileMeta { + region_id: RegionId::new(1, 0), + file_id: FileId::random(), + level: LEVEL_SHARED, + ..Default::default() + }; + let import = RegionEdit { + files_to_add: vec![source.clone()], + ..Default::default() + }; + let first = engine.edit_region(region_id, import.clone()).await; + if !cfg!(feature = "enterprise") { + assert!(first.is_err()); + assert!( + region.version().ssts.levels()[SHARED_LEVEL_SLOT] + .files + .is_empty() + ); + return; + } + first.unwrap(); + let admitted = region.version().ssts.levels()[SHARED_LEVEL_SLOT].files[&source.file_id] + .meta_ref() + .clone(); + assert_eq!(source.file_id(), admitted.file_id()); + assert_eq!(Some(1), admitted.sequence.map(|s| s.get())); + engine.edit_region(region_id, import).await.unwrap(); + assert_eq!(1, region.version_control.current().last_sequence); + assert_eq!( + &admitted, + region.version().ssts.levels()[SHARED_LEVEL_SLOT].files[&source.file_id].meta_ref() + ); + + let manifest_version = region.manifest_ctx.manifest_version().await; + let changed = FileMeta { + num_rows: 1, + ..admitted.clone() + }; + assert!( + engine + .edit_region( + region_id, + RegionEdit { + files_to_add: vec![changed], + ..Default::default() + } + ) + .await + .is_err() + ); + assert!( + engine + .edit_region( + region_id, + RegionEdit { + files_to_remove: vec![admitted.clone()], + ..Default::default() + } + ) + .await + .is_err() + ); + // A plan captured before a file became shared must also fail at publication, + // even if it bypasses the import queue and still calls the ordinary L0 path. + let stale = FileMeta { + level: 0, + ..admitted + }; + assert!( + region + .manifest_ctx + .update_manifest_for_compaction(RegionMetaActionList::with_action( + RegionMetaAction::Edit(RegionEdit { + files_to_remove: vec![stale], + ..Default::default() + }) + )) + .await + .is_err() + ); + assert_eq!( + manifest_version, + region.manifest_ctx.manifest_version().await + ); + assert_eq!(1, region.version_control.current().last_sequence); +} + +#[cfg(feature = "enterprise")] +#[tokio::test] +async fn test_shared_reclassification_requires_add_only() { + use api::v1::Rows; + use common_recordbatch::RecordBatches; + + use crate::test_util::{build_rows, flush_region, put_rows, reopen_region, rows_schema}; + + let mut env = TestEnv::new().await; + let engine = env + .create_engine(MitoConfig { + schedule_compaction_after_edit: false, + ..Default::default() + }) + .await; + let region_id = RegionId::new(1, 1); + let create = CreateRequestBuilder::new().build(); + engine + .handle_request(region_id, RegionRequest::Create(create.clone())) + .await + .unwrap(); + put_rows( + &engine, + region_id, + Rows { + schema: rows_schema(&create), + rows: build_rows(0, 3), + }, + ) + .await; + flush_region(&engine, region_id, None).await; + let scan = || async { + RecordBatches::try_collect( + engine + .scan_to_stream(region_id, Default::default()) + .await + .unwrap(), + ) + .await + .unwrap() + .pretty_print() + .unwrap() + }; + let expected_rows = scan().await; + let region = engine.get_region(region_id).unwrap(); + let before = region.manifest_ctx.manifest().await; + let sequence = region.version_control.current().last_sequence; + let source = region.version().ssts.levels()[0] + .files() + .next() + .unwrap() + .meta_ref() + .clone(); + let shared = FileMeta { + level: LEVEL_SHARED, + ..source.clone() + }; + let invalid = RegionEdit { + files_to_add: vec![shared.clone()], + files_to_remove: vec![source.clone()], + ..Default::default() + }; + assert!( + engine + .edit_region(region_id, invalid.clone()) + .await + .is_err() + ); + // The final manifest guard must also reject callers that bypass admission. + let error = region + .manifest_ctx + .update_manifest_for_compaction(RegionMetaActionList::with_action(RegionMetaAction::Edit( + invalid, + ))) + .await + .unwrap_err(); + assert!(matches!(error, crate::error::Error::InvalidRequest { .. })); + let unchanged = region.manifest_ctx.manifest().await; + assert_eq!(before.manifest_version, unchanged.manifest_version); + assert_eq!(before.files, unchanged.files); + assert_eq!(sequence, region.version_control.current().last_sequence); + assert!(std::sync::Arc::ptr_eq( + ®ion, + &engine.get_region(region_id).unwrap() + )); + assert_eq!( + &source, + region.version().ssts.levels()[0].files[&source.file_id].meta_ref() + ); + + engine + .edit_region( + region_id, + RegionEdit { + files_to_add: vec![shared], + ..Default::default() + }, + ) + .await + .unwrap(); + let installed = region.manifest_ctx.manifest().await; + assert_eq!(LEVEL_SHARED, installed.files[&source.file_id].level); + assert!(region.version().ssts.levels()[0].files.is_empty()); + assert_eq!( + &installed.files[&source.file_id], + region.version().ssts.levels()[SHARED_LEVEL_SLOT].files[&source.file_id].meta_ref() + ); + reopen_region( + &engine, + region_id, + create.table_dir, + true, + Default::default(), + ) + .await; + let reopened = engine.get_region(region_id).unwrap(); + assert_eq!( + installed.files, + reopened.manifest_ctx.manifest().await.files + ); + assert!(reopened.version().ssts.levels()[0].files.is_empty()); + assert_eq!( + &installed.files[&source.file_id], + reopened.version().ssts.levels()[SHARED_LEVEL_SLOT].files[&source.file_id].meta_ref() + ); + assert_eq!(expected_rows, scan().await); +} + +#[cfg(feature = "enterprise")] +#[tokio::test] +async fn test_shared_adoption_rejects_existing_l1_reference() { + use api::v1::Rows; + + use crate::test_util::{build_rows, flush_region, put_rows, rows_schema}; + + let mut env = TestEnv::new().await; + let engine = env + .create_engine(MitoConfig { + schedule_compaction_after_edit: false, + ..Default::default() + }) + .await; + let region_id = RegionId::new(1, 1); + let create = CreateRequestBuilder::new().build(); + engine + .handle_request(region_id, RegionRequest::Create(create.clone())) + .await + .unwrap(); + put_rows( + &engine, + region_id, + Rows { + schema: rows_schema(&create), + rows: build_rows(0, 3), + }, + ) + .await; + flush_region(&engine, region_id, None).await; + let region = engine.get_region(region_id).unwrap(); + let source = region.version().ssts.levels()[0] + .files() + .next() + .unwrap() + .meta_ref() + .clone(); + // Install the same FileId as an ordinary L1 reference. The manifest is + // keyed by FileId, so this leaves the file classified as L1. + engine + .edit_region( + region_id, + RegionEdit { + files_to_add: vec![FileMeta { + level: 1, + ..source.clone() + }], + ..Default::default() + }, + ) + .await + .unwrap(); + assert_eq!( + 1, + engine + .get_region(region_id) + .unwrap() + .manifest_ctx + .manifest() + .await + .files[&source.file_id] + .level + ); + + let region = engine.get_region(region_id).unwrap(); + let before = region.manifest_ctx.manifest().await; + let sequence = region.version_control.current().last_sequence; + let shared = FileMeta { + level: LEVEL_SHARED, + ..source.clone() + }; + let error = engine + .edit_region( + region_id, + RegionEdit { + files_to_add: vec![shared], + ..Default::default() + }, + ) + .await + .unwrap_err(); + assert!(matches!( + error, + crate::error::Error::EditRegion { source, .. } + if matches!(*source, crate::error::Error::InvalidRequest { .. }) + )); + let unchanged = region.manifest_ctx.manifest().await; + assert_eq!(before.manifest_version, unchanged.manifest_version); + assert_eq!(before.files, unchanged.files); + assert_eq!(1, unchanged.files[&source.file_id].level); + assert_eq!(sequence, region.version_control.current().last_sequence); + assert!(std::sync::Arc::ptr_eq( + ®ion, + &engine.get_region(region_id).unwrap() + )); +} + +#[cfg(feature = "enterprise")] +#[rstest::rstest] +#[case::all(true)] +#[case::time_range(false)] +#[tokio::test] +async fn test_truncate_shared_references_preserves_other_readers(#[case] truncate_all: bool) { + use api::v1::Rows; + use common_recordbatch::RecordBatches; + use common_time::Timestamp; + use store_api::region_request::RegionTruncateRequest; + + use crate::test_util::{build_rows, flush_region, put_rows, reopen_region, rows_schema}; + + let mut env = TestEnv::new().await; + let engine = env + .create_engine(MitoConfig { + schedule_compaction_after_edit: false, + ..Default::default() + }) + .await; + let owner_id = RegionId::new(1, 0); + let target_id = RegionId::new(1, 1); + let other_id = RegionId::new(1, 2); + let create = CreateRequestBuilder::new().build(); + for id in [owner_id, target_id, other_id] { + engine + .handle_request(id, RegionRequest::Create(create.clone())) + .await + .unwrap(); + } + for start in [0, 10] { + put_rows( + &engine, + owner_id, + Rows { + schema: rows_schema(&create), + rows: build_rows(start, start + 3), + }, + ) + .await; + flush_region(&engine, owner_id, None).await; + } + let owner = engine.get_region(owner_id).unwrap(); + let shared_files = owner.version().ssts.levels()[0] + .files() + .map(|file| FileMeta { + level: LEVEL_SHARED, + ..file.meta_ref().clone() + }) + .collect::>(); + assert_eq!(2, shared_files.len()); + for id in [owner_id, target_id, other_id] { + engine + .edit_region( + id, + RegionEdit { + files_to_add: shared_files.clone(), + ..Default::default() + }, + ) + .await + .unwrap(); + } + let target = engine.get_region(target_id).unwrap(); + let before = target.manifest_ctx.manifest().await; + let expected = before + .files + .iter() + .filter(|(_, file)| !truncate_all && file.time_range.0 > Timestamp::new_millisecond(5_000)) + .map(|(id, file)| (*id, file.clone())) + .collect::>(); + // Pin an actual query before the DDL, not just a copy of its file metadata. + let old_reader = engine + .scan_to_stream(target_id, Default::default()) + .await + .unwrap(); + let request = if truncate_all { + RegionTruncateRequest::All + } else { + RegionTruncateRequest::ByTimeRanges { + time_ranges: vec![( + Timestamp::new_millisecond(0), + Timestamp::new_millisecond(5_000), + )], + } + }; + engine + .handle_request(target_id, RegionRequest::Truncate(request)) + .await + .unwrap(); + assert_eq!(expected, target.manifest_ctx.manifest().await.files); + let visible = target.version().ssts.levels()[SHARED_LEVEL_SLOT] + .files() + .map(|file| (file.file_id().file_id(), file.meta_ref().clone())) + .collect::>(); + assert_eq!(expected, visible); + let old_rows = RecordBatches::try_collect(old_reader).await.unwrap(); + assert_eq!( + 6, + old_rows.iter().map(|batch| batch.num_rows()).sum::() + ); + reopen_region( + &engine, + target_id, + create.table_dir, + true, + Default::default(), + ) + .await; + assert_eq!( + expected, + engine + .get_region(target_id) + .unwrap() + .manifest_ctx + .manifest() + .await + .files + ); + for (id, expected_rows) in [(target_id, if truncate_all { 0 } else { 3 }), (other_id, 6)] { + let rows = RecordBatches::try_collect( + engine.scan_to_stream(id, Default::default()).await.unwrap(), + ) + .await + .unwrap(); + assert_eq!( + expected_rows, + rows.iter().map(|batch| batch.num_rows()).sum::() + ); + } + for file in shared_files { + let path = crate::sst::location::sst_file_path( + owner.access_layer.table_dir(), + file.file_id(), + owner.access_layer.path_type(), + ); + assert!( + owner + .access_layer + .object_store() + .exists(&path) + .await + .unwrap() + ); + } +} diff --git a/src/mito2/src/engine/staging_test.rs b/src/mito2/src/engine/staging_test.rs index 08c272be6ab..10351f918d9 100644 --- a/src/mito2/src/engine/staging_test.rs +++ b/src/mito2/src/engine/staging_test.rs @@ -14,16 +14,20 @@ //! Integration tests for staging state functionality. +use std::collections::HashMap; use std::sync::Arc; +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use std::time::Duration; use std::{assert_matches, fs}; -use api::v1::{ArrowIpc, Rows}; +use api::v1::{ArrowIpc, ColumnSchema, Rows}; +use async_trait::async_trait; use common_error::ext::{ErrorExt, RetryHint}; use common_error::status_code::StatusCode; use common_function::utils::partition_expr_version; use common_grpc::flight; use common_recordbatch::RecordBatches; +use common_time::util::current_time_millis; use datatypes::arrow::array::{ArrayRef, Float64Array, StringArray, TimestampMillisecondArray}; use datatypes::arrow::record_batch::RecordBatch; use datatypes::value::Value; @@ -33,28 +37,36 @@ use object_store::layers::mock::{ MockLayerBuilder, OpDelete, Result as MockResult, Write, Writer, }; use partition::expr::{PartitionExpr, col}; +use store_api::mito_engine_options::WRITE_BUFFER_SIZE_KEY; use store_api::region_engine::{ - RegionEngine, RemapManifestsRequest, SetRegionRoleStateResponse, SettableRegionRoleState, + RegionEngine, RegionRole, RemapManifestsRequest, SetRegionRoleStateResponse, + SettableRegionRoleState, }; use store_api::region_request::{ ApplyStagingManifestRequest, EnterStagingRequest, RegionAlterRequest, RegionBulkInsertsRequest, - RegionFlushRequest, RegionPutRequest, RegionRequest, RegionTruncateRequest, - StagingPartitionDirective, + RegionCloseRequest, RegionFlushReason, RegionFlushRequest, RegionPutRequest, RegionRequest, + RegionTruncateRequest, StagingPartitionDirective, }; -use store_api::storage::{RegionId, ScanRequest}; +use store_api::storage::{FileId, RegionId, ScanRequest}; use crate::config::MitoConfig; -use crate::engine::listener::NotifyEnterStagingResultListener; +use crate::engine::MitoEngine; +use crate::engine::listener::{EventListener, FlushListener, NotifyEnterStagingResultListener}; use crate::error::Error; +use crate::flush::WriteBufferManager; use crate::manifest::action::{ RegionChange, RegionEdit, RegionMetaAction, RegionMetaActionList, RegionPartitionExprChange, }; -use crate::region::{RegionLeaderState, RegionRoleState, parse_partition_expr}; -use crate::request::WorkerRequest; +use crate::region::{MitoRegionRef, RegionLeaderState, RegionRoleState}; +use crate::request::{RegionEditRequest, WorkerRequest}; use crate::sst::FormatType; +use crate::sst::file::FileMeta; use crate::test_util::{ - CheckpointTaskBlocker, CreateRequestBuilder, TestEnv, build_rows, put_rows, rows_schema, + CheckpointTaskBlocker, CreateRequestBuilder, MockWriteBufferManager, TestEnv, build_rows, + flush_region, put_rows, reopen_region, rows_schema, }; +use crate::time_provider::mock::MockTimeProvider; +use crate::worker::MAX_INITIAL_CHECK_DELAY_SECS; fn range_expr(col_name: &str, start: i64, end: i64) -> PartitionExpr { col(col_name) @@ -436,13 +448,6 @@ async fn test_staging_write_partition_expr_version_with_format(flat_format: bool .await .unwrap(); assert_eq!(result.affected_rows, 3); - engine - .handle_request( - region_id, - RegionRequest::Flush(RegionFlushRequest::default()), - ) - .await - .unwrap(); let result = engine .remap_manifests(RemapManifestsRequest { @@ -551,9 +556,6 @@ async fn test_staging_manifest_directory_with_format(flat_format: bool) { let region_id = RegionId::new(1024, 0); let request = CreateRequestBuilder::new().build(); - // Get column schemas before consuming the request - let column_schemas = rows_schema(&request); - // Check manifest files after region creation (before staging mode) // Create region engine @@ -637,22 +639,6 @@ async fn test_staging_manifest_directory_with_format(flat_format: bool) { Error::StagingPartitionExprMismatch { .. } ); - // Put some data and flush in staging mode - let rows_data = Rows { - schema: column_schemas.clone(), - rows: build_rows(0, 3), - }; - put_rows(&engine, region_id, rows_data).await; - - // Force flush to generate manifest files in staging mode - engine - .handle_request( - region_id, - RegionRequest::Flush(RegionFlushRequest::default()), - ) - .await - .unwrap(); - // Check that manifest files are in staging directory let staging_manifest_dir = format!("{}/staging/manifest", region_dir); assert!( @@ -708,7 +694,7 @@ async fn test_staging_exit_success_with_manifests_with_format(flat_format: bool) .await .unwrap(); - // Add some data and flush in staging mode to generate staging manifests + // This data is flushed when entering staging mode. let rows_data = Rows { schema: column_schemas.clone(), rows: build_rows(0, 3), @@ -728,55 +714,55 @@ async fn test_staging_exit_success_with_manifests_with_format(flat_format: bool) .await .unwrap(); - // Add some data and flush in staging mode to generate staging manifests + // Rows written during staging stay in the memtable. let rows_data = Rows { schema: column_schemas.clone(), - rows: build_rows(3, 8), + rows: build_rows(3, 10), }; put_rows(&engine, region_id, rows_data).await; - // Force flush to generate staging manifests + // A source region provides the files that staging imports. + let source_region_id = RegionId::new(1024, 1); engine .handle_request( - region_id, - RegionRequest::Flush(RegionFlushRequest::default()), + source_region_id, + RegionRequest::Create(CreateRequestBuilder::new().build()), ) .await .unwrap(); - - // Add more data and flush again to generate multiple staging manifests - let rows_data2 = Rows { - schema: column_schemas.clone(), - rows: build_rows(8, 10), - }; - put_rows(&engine, region_id, rows_data2).await; - + for (start, end) in [(10, 13), (13, 15)] { + let rows_data = Rows { + schema: column_schemas.clone(), + rows: build_rows(start, end), + }; + put_rows(&engine, source_region_id, rows_data).await; + flush_region(&engine, source_region_id, None).await; + } + let source_files = engine + .get_region(source_region_id) + .unwrap() + .manifest_ctx + .manifest() + .await + .files + .values() + .cloned() + .collect::>(); engine .handle_request( - region_id, - RegionRequest::Flush(RegionFlushRequest::default()), + source_region_id, + RegionRequest::Close(RegionCloseRequest::default()), ) .await .unwrap(); let region = engine.get_region(region_id).unwrap(); - let file = { - let manager = region.manifest_ctx.manifest_manager.read().await; - manager - .staging_manifest() - .unwrap() - .files - .values() - .next() - .unwrap() - .clone() - }; - for expected in [11, 12] { + for (file, expected) in source_files.into_iter().zip([11, 12]) { engine .edit_region( region_id, RegionEdit { - files_to_add: vec![file.clone()], + files_to_add: vec![file], files_to_remove: vec![], timestamp_ms: None, compaction_time_window: None, @@ -803,37 +789,19 @@ async fn test_staging_exit_success_with_manifests_with_format(flat_format: bool) .unwrap(); assert_eq!( staging_files_before.len(), - // Two flushes, two edits and entering staging mode. - 5, - "Staging manifest directory should contain 5 files before exit, got: {:?}", + // Two edits and entering staging mode. + 3, + "Staging manifest directory should contain 3 files before exit, got: {:?}", staging_files_before ); { let manager = region.manifest_ctx.manifest_manager.read().await; let staging_manifest = manager.staging_manifest().unwrap(); assert_eq!(staging_manifest.files.len(), 3); - let parquet_bytes: u64 = staging_manifest - .files - .values() - .map(|file| file.file_size) - .sum(); - assert_eq!( - region.region_statistic().flushed_parquet_bytes, - parquet_bytes - ); assert_eq!( staging_manifest.metadata.partition_expr.as_ref().unwrap(), &partition_expr ); - let expr = parse_partition_expr(Some(partition_expr.as_str())) - .unwrap() - .unwrap(); - for file in staging_manifest.files.values() { - let Some(file_expr) = file.partition_expr.as_ref() else { - continue; - }; - assert_eq!(*file_expr, expr); - } } // Count normal manifest files before exit @@ -851,7 +819,7 @@ async fn test_staging_exit_success_with_manifests_with_format(flat_format: bool) "Normal manifest directory should initially contain 2 files" ); - // Try read data before exiting staging, SST files should be invisible + // Try read data before exiting staging, imported SST files should be invisible let request = ScanRequest::default(); let scanner = engine.scanner(region_id, request).await.unwrap(); assert_eq!( @@ -861,15 +829,15 @@ async fn test_staging_exit_success_with_manifests_with_format(flat_format: bool) ); assert_eq!( scanner.num_memtables(), - 0, - "Memtables should be removed in staging before exit" + 1, + "Memtables should be kept in staging before exit" ); let stream = scanner.scan().await.unwrap(); let batches = RecordBatches::try_collect(stream).await.unwrap(); let total_rows: usize = batches.iter().map(|rb| rb.num_rows()).sum(); assert_eq!( - total_rows, 3, - "3 rows should be readable before exit staging mode" + total_rows, 10, + "10 rows should be readable before exit staging mode" ); // Inspect SSTs from manifest @@ -883,8 +851,8 @@ async fn test_staging_exit_success_with_manifests_with_format(flat_format: bool) assert_eq!(sst_entries.iter().filter(|e| e.visible).count(), 1); assert_eq!(sst_entries.iter().filter(|e| !e.visible).count(), 2); - let flushed_parquet_bytes = region.region_statistic().flushed_parquet_bytes; - assert!(flushed_parquet_bytes > 0); + let ingested_parquet_bytes = region.region_statistic().ingested_parquet_bytes; + assert!(ingested_parquet_bytes > 0); // Streaming inspection must retain staging entries and their visibility. { @@ -1004,8 +972,8 @@ async fn test_staging_exit_success_with_manifests_with_format(flat_format: bool) ); assert_eq!( - region.region_statistic().flushed_parquet_bytes, - flushed_parquet_bytes + region.region_statistic().ingested_parquet_bytes, + ingested_parquet_bytes ); // Verify staging manifests have been cleared @@ -1048,7 +1016,7 @@ async fn test_staging_exit_success_with_manifests_with_format(flat_format: bool) let stream = scanner.scan().await.unwrap(); let batches = RecordBatches::try_collect(stream).await.unwrap(); let total_rows: usize = batches.iter().map(|rb| rb.num_rows()).sum(); - assert_eq!(total_rows, 10, "Expected to read all staged rows"); + assert_eq!(total_rows, 15, "Expected to read all staged rows"); // Inspect SSTs from manifest let sst_entries = engine.all_ssts_from_manifest().await; @@ -1430,6 +1398,30 @@ impl Write for MockWriter { } } +/// Fails closing Parquet files while `fail_parquet` is set. +struct ParquetFailWriter { + path: String, + inner: Writer, + fail_parquet: Arc, +} + +impl Write for ParquetFailWriter { + async fn write(&mut self, bs: Buffer) -> MockResult<()> { + self.inner.write(bs).await + } + + async fn close(&mut self) -> MockResult { + if self.fail_parquet.load(Ordering::Relaxed) && self.path.ends_with(".parquet") { + return Err(MockError::new(ErrorKind::Unexpected, "mock error")); + } + self.inner.close().await + } + + async fn abort(&mut self) -> MockResult<()> { + self.inner.abort().await + } +} + struct MockDeleter { inner: Deleter, } @@ -1523,3 +1515,934 @@ async fn test_enter_staging_save_staging_manifest_error_with_format(flat_format: let mut env = TestEnv::new().await.with_mock_layer(mock_layer); test_enter_staging_error(&mut env, flat_format).await; } + +async fn enter_staging(engine: &MitoEngine, region_id: RegionId) { + engine + .handle_request( + region_id, + RegionRequest::EnterStaging(EnterStagingRequest { + partition_directive: StagingPartitionDirective::UpdatePartitionExpr( + float_range_expr("field_0", 0., 100.).as_json_str().unwrap(), + ), + }), + ) + .await + .unwrap(); +} + +/// Creates a region and enters staging, returning its schema and table dir. +async fn create_staging_region( + engine: &MitoEngine, + region_id: RegionId, +) -> (Vec, String) { + let request = CreateRequestBuilder::new().build(); + let schema = rows_schema(&request); + let table_dir = request.table_dir.clone(); + engine + .handle_request(region_id, RegionRequest::Create(request)) + .await + .unwrap(); + enter_staging(engine, region_id).await; + (schema, table_dir) +} + +async fn create_writable_region(engine: &MitoEngine, region_id: RegionId) { + engine + .handle_request( + region_id, + RegionRequest::Create(CreateRequestBuilder::new().build()), + ) + .await + .unwrap(); +} + +async fn put_range( + engine: &MitoEngine, + region_id: RegionId, + schema: &[ColumnSchema], + range: (usize, usize), +) { + let rows = Rows { + schema: schema.to_vec(), + rows: build_rows(range.0, range.1), + }; + put_rows(engine, region_id, rows).await; +} + +/// Sends a put that the engine is expected to refuse with a retryable error. +async fn assert_put_rejected(engine: &MitoEngine, region_id: RegionId, schema: &[ColumnSchema]) { + let err = engine + .handle_request( + region_id, + RegionRequest::Put(RegionPutRequest { + rows: Rows { + schema: schema.to_vec(), + rows: build_rows(50, 51), + }, + hint: None, + partition_expr_version: None, + skip_wal: false, + }), + ) + .await + .unwrap_err(); + assert_eq!(RetryHint::Retryable, err.retry_hint()); +} + +async fn put_range_skip_wal( + engine: &MitoEngine, + region_id: RegionId, + schema: &[ColumnSchema], + range: (usize, usize), +) { + engine + .handle_request( + region_id, + RegionRequest::Put(RegionPutRequest { + rows: Rows { + schema: schema.to_vec(), + rows: build_rows(range.0, range.1), + }, + hint: None, + partition_expr_version: None, + skip_wal: true, + }), + ) + .await + .unwrap(); +} + +/// Returns one of the files in the region's manifest. +async fn first_file(region: &MitoRegionRef) -> FileMeta { + let manifest = region.manifest_ctx.manifest().await; + manifest.files.values().next().unwrap().clone() +} + +fn edit_adding(file: FileMeta) -> RegionEdit { + RegionEdit { + files_to_add: vec![file], + files_to_remove: vec![], + timestamp_ms: None, + compaction_time_window: None, + flushed_entry_id: None, + flushed_sequence: None, + committed_sequence: None, + } +} + +/// Spawns an edit importing `file`. +fn spawn_edit( + engine: &MitoEngine, + region_id: RegionId, + file: FileMeta, +) -> tokio::task::JoinHandle> { + let edit_engine = engine.clone(); + tokio::spawn(async move { edit_engine.edit_region(region_id, edit_adding(file)).await }) +} + +/// Starts an edit importing `file` and waits until the region is `Editing`. +/// The caller holds the manifest write lock so that the edit cannot finish. +async fn start_staged_edit( + engine: &MitoEngine, + region: &MitoRegionRef, + file: FileMeta, +) -> tokio::task::JoinHandle> { + let edit = spawn_edit(engine, region.region_id, file); + tokio::time::timeout(Duration::from_secs(5), async { + while region.state() != RegionRoleState::Leader(RegionLeaderState::Editing) { + tokio::time::sleep(Duration::from_millis(1)).await; + } + }) + .await + .unwrap(); + edit +} + +async fn count_rows(engine: &MitoEngine, region_id: RegionId) -> usize { + let scanner = engine + .scanner(region_id, ScanRequest::default()) + .await + .unwrap(); + let batches = RecordBatches::try_collect(scanner.scan().await.unwrap()) + .await + .unwrap(); + batches.iter().map(|batch| batch.num_rows()).sum() +} + +/// Returns the numbers of SST files and memtables that a scan reads. +async fn scan_inputs(engine: &MitoEngine, region_id: RegionId) -> (usize, usize) { + let scanner = engine + .scanner(region_id, ScanRequest::default()) + .await + .unwrap(); + (scanner.num_files(), scanner.num_memtables()) +} + +/// Asserts that no flush has been scheduled for the rows in the region's memtable. +async fn assert_unflushed(engine: &MitoEngine, region_id: RegionId) { + let version = engine.get_region(region_id).unwrap().version(); + assert!(version.memtables.immutables().is_empty()); + assert_eq!((0, 1), scan_inputs(engine, region_id).await); +} + +#[tokio::test] +async fn test_memory_pressure_keeps_staging_rows_after_rollback() { + let mut write_buffer_manager = MockWriteBufferManager::default(); + write_buffer_manager.set_flush_limit(1 << 20); + write_buffer_manager.reserve_mem(1 << 25); + let write_buffer_manager = Arc::new(write_buffer_manager); + let listener = Arc::new(FlushListener::default()); + let mut env = TestEnv::new().await; + let engine = env + .create_engine_with( + MitoConfig { + num_workers: 1, + ..Default::default() + }, + Some(write_buffer_manager.clone()), + Some(listener.clone()), + None, + ) + .await; + let staging_region_id = RegionId::new(1024, 0); + let writable_region_id = RegionId::new(1024, 1); + let (schema, table_dir) = create_staging_region(&engine, staging_region_id).await; + create_writable_region(&engine, writable_region_id).await; + put_range(&engine, writable_region_id, &schema, (0, 3)).await; + put_range(&engine, staging_region_id, &schema, (0, 3)).await; + + write_buffer_manager.set_should_flush(true); + put_range(&engine, staging_region_id, &schema, (3, 5)).await; + listener.wait().await; + write_buffer_manager.set_should_flush(false); + + assert_eq!((1, 0), scan_inputs(&engine, writable_region_id).await); + assert_unflushed(&engine, staging_region_id).await; + + engine + .set_region_role(staging_region_id, RegionRole::Leader) + .unwrap(); + assert_eq!(5, count_rows(&engine, staging_region_id).await); + reopen_region(&engine, staging_region_id, table_dir, true, HashMap::new()).await; + assert_eq!(5, count_rows(&engine, staging_region_id).await); +} + +#[tokio::test] +async fn test_periodic_flush_skips_staging_region() { + let listener = Arc::new(FlushListener::default()); + let now = current_time_millis(); + let time_provider = Arc::new(MockTimeProvider::new(now)); + let mut env = TestEnv::new().await; + let engine = env + .create_engine_with_time( + MitoConfig { + auto_flush_interval: Duration::from_secs(300), + num_workers: 1, + ..Default::default() + }, + None, + Some(listener.clone()), + time_provider.clone(), + ) + .await; + let staging_region_id = RegionId::new(1024, 0); + let writable_region_id = RegionId::new(1024, 1); + let (schema, _) = create_staging_region(&engine, staging_region_id).await; + create_writable_region(&engine, writable_region_id).await; + put_range(&engine, staging_region_id, &schema, (0, 3)).await; + put_range(&engine, writable_region_id, &schema, (0, 3)).await; + + time_provider.set_now(now + 600_000); + time_provider.set_elapsed((MAX_INITIAL_CHECK_DELAY_SECS as i64 + 1) * 1000); + tokio::time::timeout(Duration::from_secs(3), listener.wait()) + .await + .unwrap(); + + assert_eq!((1, 0), scan_inputs(&engine, writable_region_id).await); + assert_unflushed(&engine, staging_region_id).await; +} + +#[tokio::test] +async fn test_region_write_buffer_limit_rejects_staging_writes_without_flush() { + let mut env = TestEnv::new().await; + let engine = env.create_engine(MitoConfig::default()).await; + let region_id = RegionId::new(1024, 0); + let request = CreateRequestBuilder::new() + .insert_option(WRITE_BUFFER_SIZE_KEY, "1B") + .build(); + let schema = rows_schema(&request); + engine + .handle_request(region_id, RegionRequest::Create(request)) + .await + .unwrap(); + enter_staging(&engine, region_id).await; + + put_range(&engine, region_id, &schema, (0, 3)).await; + assert_put_rejected(&engine, region_id, &schema).await; + + assert_unflushed(&engine, region_id).await; +} + +#[tokio::test] +async fn test_region_write_buffer_limit_does_not_queue_staging_writes() { + let mut env = TestEnv::new().await; + let engine = env.create_engine(MitoConfig::default()).await; + let probe_region_id = RegionId::new(1024, 0); + let (schema, _) = create_staging_region(&engine, probe_region_id).await; + put_range(&engine, probe_region_id, &schema, (0, 3)).await; + let usage = engine + .get_region(probe_region_id) + .unwrap() + .region_statistic() + .memtable_size; + + let region_id = RegionId::new(1024, 1); + let request = CreateRequestBuilder::new() + .insert_option(WRITE_BUFFER_SIZE_KEY, &format!("{usage}B")) + .build(); + engine + .handle_request(region_id, RegionRequest::Create(request)) + .await + .unwrap(); + enter_staging(&engine, region_id).await; + put_range(&engine, region_id, &schema, (0, 3)).await; + + tokio::time::timeout( + Duration::from_secs(5), + put_range(&engine, region_id, &schema, (3, 6)), + ) + .await + .unwrap(); + assert_unflushed(&engine, region_id).await; + assert_eq!(6, count_rows(&engine, region_id).await); +} + +#[tokio::test] +async fn test_staging_memtable_cap_rejects_only_staging_writes() { + let mut write_buffer_manager = MockWriteBufferManager::default(); + // Staging writes are rejected once the node's staging memtables hold one byte. + write_buffer_manager.set_flush_limit(2); + let mut env = TestEnv::new().await; + let engine = env + .create_engine_with( + MitoConfig { + num_workers: 2, + ..Default::default() + }, + Some(Arc::new(write_buffer_manager)), + None, + None, + ) + .await; + // The two staging regions belong to different workers. + let first_region_id = RegionId::new(1024, 0); + let second_region_id = RegionId::new(1024, 1); + let writable_region_id = RegionId::new(1024, 2); + let (schema, _) = create_staging_region(&engine, first_region_id).await; + create_staging_region(&engine, second_region_id).await; + create_writable_region(&engine, writable_region_id).await; + + put_range(&engine, first_region_id, &schema, (0, 3)).await; + assert_put_rejected(&engine, second_region_id, &schema).await; + put_range(&engine, writable_region_id, &schema, (0, 3)).await; + + engine + .set_region_role(first_region_id, RegionRole::Leader) + .unwrap(); + put_range(&engine, second_region_id, &schema, (0, 3)).await; +} + +#[tokio::test] +async fn test_staging_memtable_cap_counts_region_during_staged_edit() { + let mut write_buffer_manager = MockWriteBufferManager::default(); + write_buffer_manager.set_flush_limit(2); + let mut env = TestEnv::new().await; + let engine = env + .create_engine_with( + MitoConfig { + num_workers: 2, + ..Default::default() + }, + Some(Arc::new(write_buffer_manager)), + None, + None, + ) + .await; + let edited_region_id = RegionId::new(1024, 0); + let other_region_id = RegionId::new(1024, 1); + let request = CreateRequestBuilder::new().build(); + let schema = rows_schema(&request); + engine + .handle_request(edited_region_id, RegionRequest::Create(request)) + .await + .unwrap(); + put_range(&engine, edited_region_id, &schema, (0, 3)).await; + flush_region(&engine, edited_region_id, None).await; + enter_staging(&engine, edited_region_id).await; + put_range(&engine, edited_region_id, &schema, (3, 5)).await; + create_staging_region(&engine, other_region_id).await; + + let region = engine.get_region(edited_region_id).unwrap(); + let file = first_file(®ion).await; + let manager = region.manifest_ctx.manifest_manager.write().await; + let edit = start_staged_edit(&engine, ®ion, file).await; + assert_put_rejected(&engine, other_region_id, &schema).await; + + drop(manager); + edit.await.unwrap().unwrap(); + assert!(region.is_staging()); + assert_put_rejected(&engine, other_region_id, &schema).await; +} + +#[tokio::test] +async fn test_flush_request_on_staging_region_with_data_is_retryable() { + let mut env = TestEnv::new().await; + let engine = env.create_engine(MitoConfig::default()).await; + let region_id = RegionId::new(1024, 0); + let (schema, _) = create_staging_region(&engine, region_id).await; + flush_region(&engine, region_id, None).await; + put_range(&engine, region_id, &schema, (0, 3)).await; + + for reason in [None, Some(RegionFlushReason::Repartition)] { + let err = engine + .handle_request( + region_id, + RegionRequest::Flush(RegionFlushRequest { + reason, + ..Default::default() + }), + ) + .await + .unwrap_err(); + assert_eq!(RetryHint::Retryable, err.retry_hint()); + assert_matches!( + err.into_inner().as_any().downcast_ref::().unwrap(), + Error::RegionBusy { .. } + ); + } + + assert_unflushed(&engine, region_id).await; +} + +#[tokio::test] +async fn test_migration_and_wal_prune_flushes_leave_staging_region_unflushed() { + let mut env = TestEnv::new().await; + let engine = env.create_engine(MitoConfig::default()).await; + let region_id = RegionId::new(1024, 0); + let (schema, _) = create_staging_region(&engine, region_id).await; + put_range(&engine, region_id, &schema, (0, 3)).await; + + for reason in [ + RegionFlushReason::RegionMigration, + RegionFlushReason::RemoteWalPrune, + ] { + engine + .handle_request( + region_id, + RegionRequest::Flush(RegionFlushRequest { + reason: Some(reason), + ..Default::default() + }), + ) + .await + .unwrap(); + } + + assert_unflushed(&engine, region_id).await; +} + +#[tokio::test] +async fn test_successful_staging_end_keeps_rows_of_rejected_flush() { + let mut env = TestEnv::new().await; + let engine = env.create_engine(MitoConfig::default()).await; + let region_id = RegionId::new(1024, 0); + let request = CreateRequestBuilder::new().build(); + let schema = rows_schema(&request); + let table_dir = request.table_dir.clone(); + engine + .handle_request(region_id, RegionRequest::Create(request)) + .await + .unwrap(); + put_range(&engine, region_id, &schema, (0, 3)).await; + enter_staging(&engine, region_id).await; + put_range(&engine, region_id, &schema, (3, 5)).await; + engine + .handle_request( + region_id, + RegionRequest::Flush(RegionFlushRequest::default()), + ) + .await + .unwrap_err(); + + let imported_file = first_file(&engine.get_region(region_id).unwrap()).await; + engine + .edit_region( + region_id, + RegionEdit { + files_to_add: vec![imported_file], + files_to_remove: vec![], + timestamp_ms: None, + compaction_time_window: None, + flushed_entry_id: None, + flushed_sequence: None, + committed_sequence: None, + }, + ) + .await + .unwrap(); + engine + .set_region_role_state_gracefully(region_id, SettableRegionRoleState::Leader) + .await + .unwrap(); + + assert_eq!(5, count_rows(&engine, region_id).await); + reopen_region(&engine, region_id, table_dir, true, HashMap::new()).await; + assert_eq!(5, count_rows(&engine, region_id).await); +} + +#[tokio::test] +async fn test_downgrade_flushes_staging_rows_to_normal_manifest() { + let mut env = TestEnv::new().await; + let engine = env.create_engine(MitoConfig::default()).await; + let region_id = RegionId::new(1024, 0); + let (schema, table_dir) = create_staging_region(&engine, region_id).await; + put_range(&engine, region_id, &schema, (0, 3)).await; + + engine + .set_region_role_state_gracefully(region_id, SettableRegionRoleState::DowngradingLeader) + .await + .unwrap(); + flush_region(&engine, region_id, None).await; + + assert_eq!((1, 0), scan_inputs(&engine, region_id).await); + reopen_region(&engine, region_id, table_dir, true, HashMap::new()).await; + assert_eq!(3, count_rows(&engine, region_id).await); +} + +#[tokio::test] +async fn test_staging_rows_survive_restart() { + let mut env = TestEnv::new().await; + let engine = env.create_engine(MitoConfig::default()).await; + let region_id = RegionId::new(1024, 0); + let (schema, table_dir) = create_staging_region(&engine, region_id).await; + put_range(&engine, region_id, &schema, (0, 3)).await; + + let engine = env.reopen_engine(engine, MitoConfig::default()).await; + reopen_region(&engine, region_id, table_dir, true, HashMap::new()).await; + + assert_eq!(3, count_rows(&engine, region_id).await); +} + +#[tokio::test] +async fn test_close_flushes_skip_wal_rows_of_staging_region() { + let mut env = TestEnv::new().await; + let engine = env.create_engine(MitoConfig::default()).await; + let region_id = RegionId::new(1024, 0); + let (schema, table_dir) = create_staging_region(&engine, region_id).await; + put_range_skip_wal(&engine, region_id, &schema, (0, 3)).await; + + reopen_region(&engine, region_id, table_dir, true, HashMap::new()).await; + + assert_eq!((1, 0), scan_inputs(&engine, region_id).await); + assert_eq!(3, count_rows(&engine, region_id).await); +} + +#[derive(Default)] +struct RequestCountListener { + count: AtomicUsize, + /// A flush waits here before it starts while a test holds the write side. + flush_gate: tokio::sync::RwLock<()>, +} + +impl RequestCountListener { + /// Waits until a worker has received a request batch after the count reached `received`. + async fn wait_received_after(&self, received: usize) { + tokio::time::timeout(Duration::from_secs(5), async { + while self.count.load(Ordering::Relaxed) == received { + tokio::time::sleep(Duration::from_millis(1)).await; + } + }) + .await + .unwrap(); + } +} + +#[async_trait] +impl EventListener for RequestCountListener { + fn on_recv_requests(&self, request_num: usize) { + self.count.fetch_add(request_num, Ordering::Relaxed); + } + + async fn on_flush_begin(&self, _region_id: RegionId) { + let _open = self.flush_gate.read().await; + } +} + +#[tokio::test] +async fn test_edit_returns_to_staging_after_staging_leader_role() { + let mut env = TestEnv::new().await; + let engine = env.create_engine(MitoConfig::default()).await; + let region_id = RegionId::new(1024, 0); + let request = CreateRequestBuilder::new().build(); + let schema = rows_schema(&request); + engine + .handle_request(region_id, RegionRequest::Create(request)) + .await + .unwrap(); + put_range(&engine, region_id, &schema, (0, 3)).await; + flush_region(&engine, region_id, None).await; + engine + .set_region_role_state_gracefully(region_id, SettableRegionRoleState::StagingLeader) + .await + .unwrap(); + + let region = engine.get_region(region_id).unwrap(); + let file = first_file(®ion).await; + spawn_edit(&engine, region_id, file).await.unwrap().unwrap(); + + assert!(region.is_staging()); +} + +#[tokio::test] +async fn test_close_time_flush_rejects_queued_and_late_edits() { + let mut env = TestEnv::new().await; + let listener = Arc::new(RequestCountListener::default()); + let engine = env + .create_engine_with( + MitoConfig { + num_workers: 1, + ..Default::default() + }, + None, + Some(listener.clone()), + None, + ) + .await; + let region_id = RegionId::new(1024, 0); + let request = CreateRequestBuilder::new().build(); + let schema = rows_schema(&request); + let table_dir = request.table_dir.clone(); + engine + .handle_request(region_id, RegionRequest::Create(request)) + .await + .unwrap(); + put_range(&engine, region_id, &schema, (0, 3)).await; + flush_region(&engine, region_id, None).await; + enter_staging(&engine, region_id).await; + put_range_skip_wal(&engine, region_id, &schema, (3, 5)).await; + + let region = engine.get_region(region_id).unwrap(); + let file = first_file(®ion).await; + let queued_file = FileMeta { + file_id: FileId::random(), + ..file.clone() + }; + let late_file = FileMeta { + file_id: FileId::random(), + ..file.clone() + }; + let flush_gate = listener.flush_gate.write().await; + let manager = region.manifest_ctx.manifest_manager.write().await; + let edit = start_staged_edit(&engine, ®ion, file).await; + + let received = listener.count.load(Ordering::Relaxed); + let queued = spawn_edit(&engine, region_id, queued_file.clone()); + listener.wait_received_after(received).await; + + let received = listener.count.load(Ordering::Relaxed); + let close_engine = engine.clone(); + let close = tokio::spawn(async move { + close_engine + .handle_request( + region_id, + RegionRequest::Close(RegionCloseRequest::default()), + ) + .await + }); + listener.wait_received_after(received).await; + drop(manager); + + // The close-time flush is held back, so both edits arrive while the region waits for it. + let _ = edit.await; + let err = queued.await.unwrap().unwrap_err(); + assert_eq!(StatusCode::RegionNotFound, err.status_code()); + let err = spawn_edit(&engine, region_id, late_file.clone()) + .await + .unwrap() + .unwrap_err(); + assert_eq!(StatusCode::RegionBusy, err.status_code()); + + drop(flush_gate); + close.await.unwrap().unwrap(); + + reopen_region(&engine, region_id, table_dir, true, HashMap::new()).await; + let region = engine.get_region(region_id).unwrap(); + let manifest = region.manifest_ctx.manifest_manager.read().await.manifest(); + assert!(!manifest.files.contains_key(&queued_file.file_id)); + assert!(!manifest.files.contains_key(&late_file.file_id)); + assert_eq!(5, count_rows(&engine, region_id).await); +} + +#[tokio::test] +async fn test_stale_staging_edit_rejected_after_close_time_flush_fails() { + let fail_parquet = Arc::new(AtomicBool::new(false)); + let writer_flag = fail_parquet.clone(); + let mock_layer = MockLayerBuilder::default() + .writer_factory(Arc::new(move |path, _args, inner| { + Box::new(ParquetFailWriter { + path: path.to_string(), + inner, + fail_parquet: writer_flag.clone(), + }) + })) + .build() + .unwrap(); + let mut env = TestEnv::new().await.with_mock_layer(mock_layer); + let engine = env.create_engine(MitoConfig::default()).await; + let region_id = RegionId::new(1024, 0); + let request = CreateRequestBuilder::new().build(); + let schema = rows_schema(&request); + engine + .handle_request(region_id, RegionRequest::Create(request)) + .await + .unwrap(); + put_range(&engine, region_id, &schema, (0, 3)).await; + flush_region(&engine, region_id, None).await; + enter_staging(&engine, region_id).await; + put_range_skip_wal(&engine, region_id, &schema, (3, 5)).await; + + fail_parquet.store(true, Ordering::Relaxed); + engine + .handle_request( + region_id, + RegionRequest::Close(RegionCloseRequest::default()), + ) + .await + .unwrap_err(); + + // The close failed, so the region is open, writable and no longer in staging. + let region = engine.get_region(region_id).unwrap(); + assert_eq!( + RegionRoleState::Leader(RegionLeaderState::Writable), + region.state() + ); + let file = FileMeta { + file_id: FileId::random(), + ..first_file(®ion).await + }; + let file_id = file.file_id; + let stale_expr = float_range_expr("field_0", 0., 100.).as_json_str().unwrap(); + let result = submit_staging_edit(&engine, region_id, file.clone(), stale_expr.clone()).await; + assert_matches!(result.unwrap_err(), Error::RegionState { .. }); + + // A later staging for another partition expression does not take the stale edit either. + fail_parquet.store(false, Ordering::Relaxed); + engine + .handle_request( + region_id, + RegionRequest::EnterStaging(EnterStagingRequest { + partition_directive: StagingPartitionDirective::UpdatePartitionExpr( + float_range_expr("field_0", 0., 50.).as_json_str().unwrap(), + ), + }), + ) + .await + .unwrap(); + let result = submit_staging_edit(&engine, region_id, file, stale_expr).await; + assert_matches!(result.unwrap_err(), Error::RegionState { .. }); + + let manager = region.manifest_ctx.manifest_manager.read().await; + assert!(!manager.manifest().files.contains_key(&file_id)); + assert!( + manager + .staging_manifest() + .is_none_or(|staging| !staging.files.contains_key(&file_id)) + ); +} + +async fn submit_staging_edit( + engine: &MitoEngine, + region_id: RegionId, + file: FileMeta, + partition_expr: String, +) -> crate::error::Result<()> { + let (tx, rx) = tokio::sync::oneshot::channel(); + engine + .inner + .workers + .submit_to_worker( + region_id, + WorkerRequest::EditRegion( + RegionEditRequest::new(region_id, edit_adding(file), false, tx) + .for_staging(partition_expr), + ), + ) + .await + .unwrap(); + rx.await.unwrap() +} + +#[tokio::test] +async fn test_close_during_staged_edit_flushes_skip_wal_rows() { + let mut env = TestEnv::new().await; + let listener = Arc::new(RequestCountListener::default()); + let engine = env + .create_engine_with( + MitoConfig { + num_workers: 1, + ..Default::default() + }, + None, + Some(listener.clone()), + None, + ) + .await; + let region_id = RegionId::new(1024, 0); + let request = CreateRequestBuilder::new().build(); + let schema = rows_schema(&request); + let table_dir = request.table_dir.clone(); + engine + .handle_request(region_id, RegionRequest::Create(request)) + .await + .unwrap(); + put_range(&engine, region_id, &schema, (0, 3)).await; + flush_region(&engine, region_id, None).await; + enter_staging(&engine, region_id).await; + put_range_skip_wal(&engine, region_id, &schema, (3, 5)).await; + + let region = engine.get_region(region_id).unwrap(); + let file = first_file(®ion).await; + let manager = region.manifest_ctx.manifest_manager.write().await; + let edit = start_staged_edit(&engine, ®ion, file).await; + let received = listener.count.load(Ordering::Relaxed); + let close_engine = engine.clone(); + let close = tokio::spawn(async move { + close_engine + .handle_request( + region_id, + RegionRequest::Close(RegionCloseRequest::default()), + ) + .await + }); + // The worker has the close request before the edit, still waiting for the lock, can finish. + listener.wait_received_after(received).await; + drop(manager); + close.await.unwrap().unwrap(); + let _ = edit.await; + + reopen_region(&engine, region_id, table_dir, true, HashMap::new()).await; + assert_eq!(5, count_rows(&engine, region_id).await); +} + +/// Waits until a writer is queued on the region's manifest lock while the caller holds it shared. +async fn wait_for_queued_manifest_writer(region: &MitoRegionRef) { + tokio::time::timeout(Duration::from_secs(5), async { + while region.manifest_ctx.manifest_manager.try_read().is_ok() { + tokio::time::sleep(Duration::from_millis(1)).await; + } + }) + .await + .unwrap(); +} + +#[tokio::test] +async fn test_close_waits_for_manifest_lock_before_leaving_staging() { + let mut env = TestEnv::new().await; + let engine = env.create_engine(MitoConfig::default()).await; + let region_id = RegionId::new(1024, 0); + create_staging_region(&engine, region_id).await; + let region = engine.get_region(region_id).unwrap(); + + let manager = region.manifest_ctx.manifest_manager.read().await; + let close_engine = engine.clone(); + let close = tokio::spawn(async move { + close_engine + .handle_request( + region_id, + RegionRequest::Close(RegionCloseRequest::default()), + ) + .await + }); + wait_for_queued_manifest_writer(®ion).await; + assert!(region.is_staging()); + + drop(manager); + close.await.unwrap().unwrap(); + assert!(!region.is_staging()); +} + +#[tokio::test] +async fn test_close_after_end_of_staging_is_queued_keeps_committed_result() { + let mut env = TestEnv::new().await; + let listener = Arc::new(RequestCountListener::default()); + let engine = env + .create_engine_with( + MitoConfig { + num_workers: 1, + ..Default::default() + }, + None, + Some(listener.clone()), + None, + ) + .await; + let region_id = RegionId::new(1024, 0); + let request = CreateRequestBuilder::new().build(); + let schema = rows_schema(&request); + let table_dir = request.table_dir.clone(); + engine + .handle_request(region_id, RegionRequest::Create(request)) + .await + .unwrap(); + put_range(&engine, region_id, &schema, (0, 3)).await; + enter_staging(&engine, region_id).await; + put_range(&engine, region_id, &schema, (3, 5)).await; + let region = engine.get_region(region_id).unwrap(); + let file = first_file(®ion).await; + engine + .edit_region( + region_id, + RegionEdit { + files_to_add: vec![file], + files_to_remove: vec![], + timestamp_ms: None, + compaction_time_window: None, + flushed_entry_id: None, + flushed_sequence: None, + committed_sequence: None, + }, + ) + .await + .unwrap(); + + let manager = region.manifest_ctx.manifest_manager.read().await; + let end_engine = engine.clone(); + let end = tokio::spawn(async move { + end_engine + .set_region_role_state_gracefully(region_id, SettableRegionRoleState::Leader) + .await + }); + wait_for_queued_manifest_writer(®ion).await; + let received = listener.count.load(Ordering::Relaxed); + let close_engine = engine.clone(); + let close = tokio::spawn(async move { + close_engine + .handle_request( + region_id, + RegionRequest::Close(RegionCloseRequest::default()), + ) + .await + }); + listener.wait_received_after(received).await; + drop(manager); + + end.await.unwrap().unwrap(); + close.await.unwrap().unwrap(); + reopen_region(&engine, region_id, table_dir, true, HashMap::new()).await; + let reopened = engine.get_region(region_id).unwrap(); + assert_eq!( + Some(float_range_expr("field_0", 0., 100.).as_json_str().unwrap()), + reopened.metadata().partition_expr + ); + assert_eq!(5, count_rows(&engine, region_id).await); +} diff --git a/src/mito2/src/error.rs b/src/mito2/src/error.rs index 155978aa5b2..5085ca8f78c 100644 --- a/src/mito2/src/error.rs +++ b/src/mito2/src/error.rs @@ -44,6 +44,40 @@ use crate::worker::WorkerId; #[snafu(visibility(pub))] #[stack_trace_debug] pub enum Error { + #[cfg(feature = "enterprise")] + #[snafu(display("Failed to route multi-region compaction input"))] + RouteMultiRegion { + #[snafu(source)] + source: PartitionError, + #[snafu(implicit)] + location: Location, + }, + + #[cfg(feature = "enterprise")] + #[snafu(display("Invalid multi-region compaction: {reason}"))] + InvalidMultiRegionCompaction { + reason: String, + #[snafu(implicit)] + location: Location, + }, + + #[cfg(feature = "enterprise")] + #[snafu(display("Multi-region compaction resource limit: {reason}"))] + MultiRegionCompactionResource { + reason: String, + #[snafu(implicit)] + location: Location, + }, + + #[snafu(display("SST writer {kind} needs {bytes} bytes, budget is {limit}"))] + SstWriteMemoryExceeded { + kind: &'static str, + bytes: usize, + limit: usize, + #[snafu(implicit)] + location: Location, + }, + #[snafu(display("Unexpected data type"))] DataTypeMismatch { source: datatypes::error::Error, @@ -113,6 +147,25 @@ pub enum Error { location: Location, }, + #[snafu(display("Manifest version {version} conflicts in {manifest_dir}: {reason}"))] + ManifestVersionConflict { + version: ManifestVersion, + manifest_dir: String, + reason: String, + #[snafu(implicit)] + location: Location, + }, + + #[snafu(display( + "Manifest checkpoint {version} in {manifest_dir} was removed after it was listed" + ))] + ManifestCheckpointVanished { + version: ManifestVersion, + manifest_dir: String, + #[snafu(implicit)] + location: Location, + }, + #[snafu(display("Failed to serialize manifest, region_id: {}", region_id))] SerializeManifest { region_id: RegionId, @@ -1491,7 +1544,9 @@ impl Error { /// from a revoked key, a changed bucket policy or clock skew) never proves nothing was written. pub(crate) fn may_have_persisted_manifest_update(&self) -> bool { match self { - Error::UpdateManifest { .. } + // Applicability and capability checks reject the edit before storage I/O. + Error::InvalidRequest { .. } + | Error::UpdateManifest { .. } | Error::RegionState { .. } | Error::RegionTruncated { .. } | Error::RegionStopped { .. } @@ -1519,10 +1574,19 @@ impl ErrorExt for Error { use Error::*; match self { + #[cfg(feature = "enterprise")] + RouteMultiRegion { source, .. } => source.status_code(), + #[cfg(feature = "enterprise")] + InvalidMultiRegionCompaction { .. } => StatusCode::InvalidArguments, + #[cfg(feature = "enterprise")] + MultiRegionCompactionResource { .. } => StatusCode::RuntimeResourcesExhausted, + SstWriteMemoryExceeded { .. } => StatusCode::RuntimeResourcesExhausted, DataTypeMismatch { source, .. } => source.status_code(), - OpenDal { .. } | ManifestDeltaNotFound { .. } | ReadParquet { .. } => { - StatusCode::StorageUnavailable - } + OpenDal { .. } + | ManifestDeltaNotFound { .. } + | ManifestVersionConflict { .. } + | ManifestCheckpointVanished { .. } + | ReadParquet { .. } => StatusCode::StorageUnavailable, WriteWal { source, .. } | ReadWal { source, .. } | DeleteWal { source, .. } @@ -1743,7 +1807,9 @@ impl ErrorExt for Error { | RegionBusy { .. } | ManualCompactionAlreadyRunning { .. } | FlushableRegionState { .. } - | ManifestDeltaNotFound { .. } => RetryHint::Retryable, + | ManifestDeltaNotFound { .. } + | ManifestVersionConflict { .. } + | ManifestCheckpointVanished { .. } => RetryHint::Retryable, OpenDal { error, .. } | DeleteSsts { error, .. } @@ -1957,9 +2023,24 @@ mod tests { let region_id = RegionId::new(1, 1); let error = RegionTruncatedSnafu { region_id }.build(); assert!(!error.may_have_persisted_manifest_update()); + let error = InvalidRequestSnafu { + region_id, + reason: "manifest applicability check rejected the edit", + } + .build(); + assert!(!error.may_have_persisted_manifest_update()); // This can be raised while applying an edit after its manifest file was saved. let error = RegionMetadataNotFoundSnafu {}.build(); assert!(error.may_have_persisted_manifest_update()); + + let error = ManifestVersionConflictSnafu { + version: 1u64, + manifest_dir: "manifest/", + reason: "test", + } + .build(); + assert!(error.may_have_persisted_manifest_update()); + assert!(error.retry_hint().is_retryable()); } } diff --git a/src/mito2/src/flush.rs b/src/mito2/src/flush.rs index 0a4f1765f39..97bdf6dbb47 100644 --- a/src/mito2/src/flush.rs +++ b/src/mito2/src/flush.rs @@ -60,7 +60,7 @@ use crate::read::flat_dedup::{FlatDedupIterator, FlatLastNonNull, FlatLastRow}; use crate::read::flat_merge::FlatMergeIterator; use crate::region::options::{IndexOptions, MergeMode, RegionOptions}; use crate::region::version::{VersionControlData, VersionControlRef, VersionRef}; -use crate::region::{ManifestContextRef, RegionLeaderState, RegionRoleState, parse_partition_expr}; +use crate::region::{ManifestContextRef, RegionLeaderState, parse_partition_expr}; use crate::request::{ BackgroundNotify, DdlRequest, FlushFailed, FlushFinished, OnFailure, OptionOutputTx, OutputTx, SenderBulkRequest, SenderDdlRequest, SenderWriteRequest, WorkerRequest, WorkerRequestWithTime, @@ -281,8 +281,6 @@ pub(crate) struct RegionFlushTask { pub(crate) index_options: IndexOptions, /// Semaphore to control flush concurrency. pub(crate) flush_semaphore: Arc, - /// Whether the region is in staging mode. - pub(crate) is_staging: bool, /// Partition expression of the region. /// /// This is used to generate the file meta. @@ -412,7 +410,6 @@ impl RegionFlushTask { _timer: timer, edit, memtables_to_remove, - is_staging: self.is_staging, }; WorkerRequest::Background { region_id: self.region_id, @@ -537,10 +534,7 @@ impl RegionFlushTask { flushed_sequence: Some(version_data.committed_sequence), committed_sequence: None, }; - info!( - "Applying {edit:?} to region {}, is_staging: {}", - self.region_id, self.is_staging - ); + info!("Applying {edit:?} to region {}", self.region_id); let action_list = RegionMetaActionList::with_action(RegionMetaAction::Edit(edit.clone())); @@ -553,17 +547,11 @@ impl RegionFlushTask { let expected_state = if matches!(self.reason, FlushReason::Downgrading) { RegionLeaderState::Downgrading } else { - // Check if region is in staging mode - let current_state = self.manifest_ctx.current_state(); - if current_state == RegionRoleState::Leader(RegionLeaderState::Staging) { - RegionLeaderState::Staging - } else { - RegionLeaderState::Writable - } + RegionLeaderState::Writable }; let manifest_version = match self .manifest_ctx - .update_manifest(expected_state, action_list, self.is_staging) + .update_manifest(expected_state, action_list, false) .await { Ok(manifest_version) => { @@ -584,9 +572,8 @@ impl RegionFlushTask { } }; info!( - "Successfully update manifest version to {manifest_version}, region: {}, is_staging: {}, reason: {}", + "Successfully update manifest version to {manifest_version}, region: {}, reason: {}", self.region_id, - self.is_staging, self.reason.as_str() ); @@ -681,7 +668,7 @@ impl RegionFlushTask { partition_expr.clone(), pk_range, version.options.preserve_row_sequence, - )); + )?); } if hook.is_some() { all_sst_infos.extend(ssts_written); @@ -824,12 +811,12 @@ impl RegionFlushTask { partition_expr: Option, primary_key_range: Option<(Bytes, Bytes)>, preserve_row_sequence: bool, - ) -> FileMeta { + ) -> Result { let (primary_key_min, primary_key_max) = match primary_key_range { Some((min, max)) => (Some(min), Some(max)), None => (None, None), }; - FileMeta { + Ok(FileMeta { region_id, file_id: sst_info.file_id, time_range: sst_info.time_range, @@ -837,7 +824,7 @@ impl RegionFlushTask { file_size: sst_info.file_size, max_row_group_uncompressed_size: sst_info.max_row_group_uncompressed_size, available_indexes: sst_info.index_metadata.build_available_indexes(), - indexes: sst_info.index_metadata.build_indexes(), + indexes: sst_info.index_metadata.build_indexes()?, index_file_size: sst_info.index_metadata.file_size, index_version: 0, num_rows: sst_info.num_rows as u64, @@ -848,7 +835,7 @@ impl RegionFlushTask { primary_key_min, primary_key_max, preserve_row_sequence, - } + }) } fn new_write_request( @@ -1497,6 +1484,23 @@ impl FlushScheduler { status.pending_bulk_writes.push(request); } + /// Whether an ALTER owns a turn while waiting for its memtables to flush. + pub(crate) fn has_pending_alter(&self, region_id: RegionId) -> bool { + self.region_status.get(®ion_id).is_some_and(|status| { + status + .pending_ddls + .iter() + .any(|ddl| matches!(ddl.request, DdlRequest::Alter(_))) + }) + } + + /// Returns true if the region has a close-time flush. + pub(crate) fn has_close_time_flush(&self, region_id: RegionId) -> bool { + self.region_status + .get(®ion_id) + .is_some_and(|status| status.closing) + } + /// Returns true if the region has pending DDLs or a close-time flush. pub(crate) fn has_pending_ddls(&self, region_id: RegionId) -> bool { self.region_status @@ -1703,7 +1707,6 @@ mod tests { manifest_ctx, index_options: IndexOptions::default(), flush_semaphore: Arc::new(Semaphore::new(2)), - is_staging: false, partition_expr: None, durability_barrier: DurabilityBarrier::noop(), } @@ -1854,7 +1857,6 @@ mod tests { .await, index_options: IndexOptions::default(), flush_semaphore: Arc::new(Semaphore::new(2)), - is_staging: false, partition_expr: None, durability_barrier: DurabilityBarrier::noop(), }; @@ -1940,7 +1942,6 @@ mod tests { committed_sequence: None, }, memtables_to_remove: smallvec![], - is_staging: false, }), }; @@ -2156,7 +2157,6 @@ mod tests { manifest_ctx: manifest_ctx.clone(), index_options: IndexOptions::default(), flush_semaphore: Arc::new(Semaphore::new(2)), - is_staging: false, partition_expr: None, durability_barrier: DurabilityBarrier::noop(), }) @@ -2463,7 +2463,6 @@ mod tests { manifest_ctx: manifest_ctx.clone(), index_options: IndexOptions::default(), flush_semaphore: Arc::new(Semaphore::new(2)), - is_staging: false, partition_expr: None, durability_barrier: DurabilityBarrier::noop(), }) diff --git a/src/mito2/src/gc.rs b/src/mito2/src/gc.rs index 8d917fbcffb..227875ef3ff 100644 --- a/src/mito2/src/gc.rs +++ b/src/mito2/src/gc.rs @@ -66,7 +66,6 @@ fn should_delete_file( is_in_tmp_ref: bool, is_linger: bool, is_eligible_for_delete: bool, - is_region_dropped: bool, entry: &Entry, unknown_file_may_linger_until: chrono::DateTime, ) -> bool { @@ -79,17 +78,12 @@ fn should_delete_file( return is_eligible_for_delete; } - // Unknown file: not in manifest, tmp_ref, or known removed records. - // For dropped regions, unknown files not protected by manifest/tmp refs/cross-region refs - // are deleted immediately. This relies on meta collecting FileRefsManifest from related - // active regions before issuing dropped-region GC; preserving young unknown files would - // also require keeping the table_repart tombstone for retry. - // For active/open regions, only delete if the object's last-modified time exceeds the - // unknown_file_lingering_time TTL. - if is_region_dropped { - return true; - } - + // Unknown file: not in manifest, tmp refs, or known removed records. This also + // covers a directory whose manifest is gone (region dropped or not hosted here): + // there is no version to fence against, so a young object may still belong to an + // unpublished table-compaction attempt. Always require the object to be older + // than `unknown_file_lingering_time`; deleting immediately would race with an + // attempt that has not published yet. entry .metadata() .last_modified() @@ -99,6 +93,29 @@ fn should_delete_file( .unwrap_or(false) } +/// Whether an unknown (untracked) entry is withheld only by the young-object +/// rule. Such objects must be revisited later; a dropped region depends on its +/// meta tombstone to be discovered by a later GC pass at all. +fn is_deferred_unknown_file( + is_in_manifest: bool, + is_in_tmp_ref: bool, + is_linger: bool, + is_eligible_for_delete: bool, + entry: &Entry, + unknown_file_may_linger_until: chrono::DateTime, +) -> bool { + let unknown = !is_in_manifest && !is_in_tmp_ref && !is_linger && !is_eligible_for_delete; + unknown + && !should_delete_file( + is_in_manifest, + is_in_tmp_ref, + is_linger, + is_eligible_for_delete, + entry, + unknown_file_may_linger_until, + ) +} + /// Limit the amount of concurrent GC jobs on the datanode pub struct GcLimiter { pub gc_job_limit: Arc, @@ -343,7 +360,7 @@ impl LocalGcWorker { .await?; let RegionGcOutcome { removed_files, - extension_cleanup_failed, + needs_retry, } = outcome; let index_files = removed_files .iter() @@ -356,9 +373,9 @@ impl LocalGcWorker { RemovedFile::Index(_, _) => None, }) .collect(); - // Don't acknowledge the region as processed until extension cleanup - // succeeds; retry it next pass instead. - if extension_cleanup_failed { + // A deferred deletion batch or failed extension cleanup must not + // acknowledge the region as fully processed. + if needs_retry { need_retry_regions.insert(*region_id); } else { deleted_files.insert(*region_id, data_files); @@ -387,15 +404,12 @@ impl LocalGcWorker { /// Per-region outcome of [`LocalGcWorker::do_region_gc`]. /// -/// `extension_cleanup_failed` records whether a registered extension's -/// [`RegionHook::on_region_gc`] could not finish; the caller must then keep the -/// region un-acknowledged (retry set) so the next GC pass replays the callback. +/// Unfinished deletion or extension cleanup keeps the region in the retry set. pub(crate) struct RegionGcOutcome { /// Files physically deleted this pass. pub removed_files: Vec, - /// `true` if a registered extension's `on_region_gc` returned `Err`; the - /// caller retries the region next pass. - pub extension_cleanup_failed: bool, + /// The snapshot changed while the protection lookup ran, or extension cleanup failed. + pub needs_retry: bool, } impl LocalGcWorker { @@ -470,7 +484,7 @@ impl LocalGcWorker { .inc(); return Ok(RegionGcOutcome { removed_files: vec![], - extension_cleanup_failed: false, + needs_retry: false, }); } Some(manifest) @@ -529,10 +543,9 @@ impl LocalGcWorker { .map(|file_ref| (file_ref.file_id, file_ref.index_version)) .collect::>(); - let deletable_files = self + let (mut deletable_files, deferred_unknown_files) = self .list_to_be_deleted_files( region_id, - is_region_dropped, &in_manifest, &in_tmp_ref, recently_removed_files, @@ -540,8 +553,20 @@ impl LocalGcWorker { ) .await?; - let unused_file_cnt = deletable_files.len(); - + let mut hook_deferred_files = false; + if let Some(hook) = &self.hook { + let candidates = deletable_files + .iter() + .map(|file| RegionFileId::new(region_id, file.file_id())) + .collect::>(); + let protected = hook + .protected_sst_files(&self.access_layer, &candidates) + .await?; + let before_filtering = deletable_files.len(); + deletable_files + .retain(|file| !protected.contains(&RegionFileId::new(region_id, file.file_id()))); + hook_deferred_files = deletable_files.len() < before_filtering; + } info!( "gc: for region{}{region_id}: In manifest file cnt: {}, Tmp ref file cnt: {}, recently removed files: {}, Unused files to delete count: {}", if region.is_none() { @@ -568,12 +593,33 @@ impl LocalGcWorker { let _delete_timer = GC_DURATION_SECONDS .with_label_values(&["delete_files"]) .start_timer(); - self.delete_files(region_id, &deletable_files).await?; - - debug!( - "Successfully deleted {} unused files for region {}", - unused_file_cnt, region_id - ); + // The protection lookup above awaits, so a queued publication may have + // changed the region since the candidate set was computed. Recheck once + // without holding the manifest lock across remote deletion. An empty + // candidate set takes neither the lock nor the recheck. + let publication_changed = !deletable_files.is_empty() + && if let (Some(region), Some(snapshot)) = (®ion, &manifest) { + let manifest_guard = region.manifest_ctx.manifest_manager.read().await; + manifest_guard.is_stopped() + || manifest_guard.manifest().manifest_version != snapshot.manifest_version + || !matches!(region.state(), RegionRoleState::Leader(_)) + } else { + false + }; + if publication_changed { + debug!( + "gc: region {} changed during the protection lookup, deferring deletion", + region_id + ); + deletable_files.clear(); + } else { + self.delete_files(region_id, &deletable_files).await?; + debug!( + "Successfully deleted {} unused files for region {}", + deletable_files.len(), + region_id + ); + } // Notify extensions so they can clean up sidecar files. Fire when there // are removed files, or on a full-listing pass (lets extensions reconcile @@ -620,9 +666,16 @@ impl LocalGcWorker { .await?; } + // A dropped region is rediscovered only through its meta-srv tombstone. + // Young unknown objects and hook-protected candidates must keep that + // tombstone (needs_retry) until they are actually reclaimed; reporting + // success here would let the procedure drop the tombstone and leak them. + let dropped_files_deferred = + region.is_none() && (deferred_unknown_files || hook_deferred_files); + Ok(RegionGcOutcome { removed_files: deletable_files, - extension_cleanup_failed, + needs_retry: extension_cleanup_failed || publication_changed || dropped_files_deferred, }) } @@ -920,15 +973,15 @@ impl LocalGcWorker { #[allow(clippy::too_many_arguments)] fn filter_deletable_files( &self, - is_region_dropped: bool, entries: Vec, in_manifest: &HashMap>, in_tmp_ref: &HashSet<(FileId, Option)>, may_linger_files: &HashSet<&RemovedFile>, eligible_for_delete: &HashSet<&RemovedFile>, unknown_file_may_linger_until: chrono::DateTime, - ) -> Vec { + ) -> (Vec, bool) { let mut ready_for_delete = vec![]; + let mut deferred_unknown = false; // Every index-version reader needs the same Parquet file. let referenced_ssts: HashSet<_> = in_tmp_ref.iter().map(|(file_id, _)| *file_id).collect(); @@ -971,12 +1024,19 @@ impl LocalGcWorker { let is_linger = may_linger_files.contains_key(&file_id); let is_eligible_for_delete = eligible_for_delete.contains_key(&file_id); + deferred_unknown |= is_deferred_unknown_file( + is_in_manifest, + is_in_tmp_ref, + is_linger, + is_eligible_for_delete, + &entry, + unknown_file_may_linger_until, + ); should_delete_file( is_in_manifest, is_in_tmp_ref, is_linger, is_eligible_for_delete, - is_region_dropped, &entry, unknown_file_may_linger_until, ) @@ -993,12 +1053,19 @@ impl LocalGcWorker { .map(|files| files.contains(&&RemovedFile::Index(file_id, version))) .unwrap_or(false); + deferred_unknown |= is_deferred_unknown_file( + is_in_manifest, + is_in_tmp_ref, + is_linger, + is_eligible_for_delete, + &entry, + unknown_file_may_linger_until, + ); should_delete_file( is_in_manifest, is_in_tmp_ref, is_linger, is_eligible_for_delete, - is_region_dropped, &entry, unknown_file_may_linger_until, ) @@ -1020,11 +1087,12 @@ impl LocalGcWorker { ready_for_delete.push(removed_file); } } - ready_for_delete + (ready_for_delete, deferred_unknown) } /// List files to be deleted based on their presence in the manifest, temporary references, and recently removed files. - /// Returns a vector of `RemovedFile` that are eligible for deletion. + /// Returns the `RemovedFile`s that are eligible for deletion and whether any + /// unknown object was withheld by the young-object rule and needs a later pass. /// /// When `full_file_listing` is false, this method will only delete (subset of) files tracked in /// `recently_removed_files`, which significantly @@ -1034,12 +1102,11 @@ impl LocalGcWorker { pub async fn list_to_be_deleted_files( &self, region_id: RegionId, - is_region_dropped: bool, in_manifest: &HashMap>, in_tmp_ref: &HashSet<(FileId, Option)>, recently_removed_files: BTreeMap>, all_entries: Vec, - ) -> Result> { + ) -> Result<(Vec, bool)> { let now = chrono::Utc::now(); let may_linger_until = self .opt @@ -1113,14 +1180,13 @@ impl LocalGcWorker { files_to_delete.len() ); - return Ok(files_to_delete); + return Ok((files_to_delete, false)); } // Full file listing mode: get the full list of files from object store // Step 3: Filter files to determine which ones can be deleted let all_unused_files_ready_for_delete = self.filter_deletable_files( - is_region_dropped, all_entries, in_manifest, in_tmp_ref, diff --git a/src/mito2/src/gc/worker_test.rs b/src/mito2/src/gc/worker_test.rs index f439e01a951..55a04dbad5e 100644 --- a/src/mito2/src/gc/worker_test.rs +++ b/src/mito2/src/gc/worker_test.rs @@ -39,7 +39,7 @@ use crate::gc::{GcConfig, LocalGcWorker, should_delete_file}; use crate::manifest::action::{RegionEdit, RegionMetaAction, RegionMetaActionList, RemovedFile}; use crate::metrics::GC_SKIPPED_UNPARSABLE_FILES; use crate::region::{MitoRegionRef, RegionLeaderState}; -use crate::sst::file::{FileHandle, FileMeta, IndexType, RegionIndexId}; +use crate::sst::file::{ColumnIndexMetadata, FileHandle, FileMeta, IndexType, RegionIndexId}; use crate::sst::location; use crate::test_util::{ CreateRequestBuilder, TestEnv, build_rows, flush_region, put_rows, rows_schema, @@ -213,20 +213,18 @@ async fn test_gc_keeps_sst_across_index_versions( .into_iter() .map(|f| (f.file_id, f.index_version)) .collect(); - let deleted: HashSet<_> = env + let (deleted, _deferred_unknown) = env .worker .list_to_be_deleted_files( region_id, - false, &HashMap::new(), &tmp_refs, env.removed_files.clone(), env.entries.clone(), ) .await - .unwrap() - .into_iter() - .collect(); + .unwrap(); + let deleted: HashSet<_> = deleted.into_iter().collect(); let expected = match released { 0 => HashSet::new(), 1 => HashSet::from([RemovedFile::Index(meta.file_id, released_version)]), @@ -258,11 +256,10 @@ async fn test_gc_reference_protects_parquet_and_only_its_index( } else { (HashMap::new(), HashSet::from([(file_id, index_version)])) }; - let deleted = env + let (deleted, _deferred_unknown) = env .worker .list_to_be_deleted_files( env.meta.region_id, - false, &manifest_refs, &tmp_refs, env.removed_files.clone(), @@ -283,8 +280,17 @@ async fn test_gc_reference_protects_parquet_and_only_its_index( async fn test_gc_reclaims_obsolete_index_after_readers_and_linger_release( #[values(false, true)] full_file_listing: bool, #[values(false, true)] linger_expired: bool, + #[values(false, true)] column_only: bool, ) { - let env = IndexGcTestEnv::new(full_file_listing).await; + let mut env = IndexGcTestEnv::new(full_file_listing).await; + if column_only { + env.meta.available_indexes.clear(); + env.meta.indexes = vec![ColumnIndexMetadata { + column_id: 0, + created_indexes: smallvec::smallvec![IndexType::HllIndex], + ..Default::default() + }]; + } let region_id = env.meta.region_id; env.engine .set_region_role(region_id, RegionRole::Leader) @@ -846,279 +852,108 @@ async fn write_and_list_entry(store: &ObjectStore, path: &str) -> Entry { } } -/// Test: active/open region unknown file within TTL (last_modified newer than -/// threshold) should NOT be deleted. -/// NOTE: Memory backend leaves `last_modified` as `None`, so this test also -/// covers the "missing last_modified → keep" conservative behavior. +/// Unknown file with a missing `last_modified`: keep it (conservative). #[tokio::test] async fn test_unknown_file_within_ttl_not_deleted() { - let builder = services::Memory::default(); - let store = ObjectStore::new(builder).unwrap(); - + let store = ObjectStore::new(services::Memory::default()).unwrap(); let entry = write_and_list_entry(&store, "test/1.parquet").await; + assert!(entry.metadata().last_modified().is_none()); - // unknown_file_may_linger_until set to epoch (very old) → file is "too young" - // since last_modified is ~now. let threshold = chrono::DateTime::from_timestamp(0, 0).unwrap(); - - let should_delete = should_delete_file( - false, // not in manifest - false, // not in tmp_ref - false, // not in may_linger - false, // not eligible for delete - false, // active region (not dropped) - &entry, threshold, - ); - assert!( - !should_delete, - "Active-region unknown file within TTL should NOT be deleted" - ); + assert!(!should_delete_file( + false, false, false, false, &entry, threshold + )); } -/// Test: active/open region unknown file exceeding TTL (last_modified older -/// than threshold) should be deleted. +/// Unknown file older than the lingering window: reclaim it. #[tokio::test] async fn test_unknown_file_exceeded_ttl_deleted() { - // Use Fs backend so that last_modified is properly set on file metadata. let tmp_dir = common_test_util::temp_dir::create_temp_dir("gc_unknown_ttl"); let root = tmp_dir.path().to_string_lossy().to_string(); - let builder = services::Fs::default().root(&root); - let store = ObjectStore::new(builder).unwrap(); - + let store = ObjectStore::new(services::Fs::default().root(&root)).unwrap(); let entry = write_and_list_entry(&store, "2.parquet").await; - // threshold set far into the future → any file with last_modified before now - // is guaranteed to be older than the threshold. + let threshold = chrono::Utc::now() + chrono::Duration::days(1); + assert!(should_delete_file( + false, false, false, false, &entry, threshold + )); +} + +/// Without a region manifest (dropped, or not hosted here) an unknown file must +/// still pass `unknown_file_lingering_time` instead of being deleted immediately, +/// because a young object may still belong to an unpublished table-compaction +/// attempt. +#[tokio::test] +async fn test_unknown_file_without_region_manifest_lingers() { + let tmp_dir = common_test_util::temp_dir::create_temp_dir("gc_no_manifest"); + let root = tmp_dir.path().to_string_lossy().to_string(); + let store = ObjectStore::new(services::Fs::default().root(&root)).unwrap(); + let entry = write_and_list_entry(&store, "no_manifest.parquet").await; + + let young_cutoff = chrono::DateTime::from_timestamp(0, 0).unwrap(); + assert!( + !should_delete_file(false, false, false, false, &entry, young_cutoff), + "a young unknown file must be kept even without a region manifest" + ); + + let old_cutoff = chrono::Utc::now() + chrono::Duration::days(1); + assert!( + should_delete_file(false, false, false, false, &entry, old_cutoff), + "an unknown file older than the lingering window is reclaimed" + ); +} + +/// A live or referenced file is never deleted, even when its object is old. +#[tokio::test] +async fn test_referenced_file_kept_with_old_mtime() { + let tmp_dir = common_test_util::temp_dir::create_temp_dir("gc_referenced_old"); + let root = tmp_dir.path().to_string_lossy().to_string(); + let store = ObjectStore::new(services::Fs::default().root(&root)).unwrap(); + let entry = write_and_list_entry(&store, "referenced.parquet").await; let threshold = chrono::Utc::now() + chrono::Duration::days(1); - let should_delete = should_delete_file( - false, // not in manifest - false, // not in tmp_ref - false, // not in may_linger - false, // not eligible for delete - false, // active region (not dropped) - &entry, threshold, + assert!( + !should_delete_file(true, false, false, false, &entry, threshold), + "a file in the manifest must be kept" ); assert!( - should_delete, - "Active-region unknown file exceeding TTL should be deleted" + !should_delete_file(false, true, false, false, &entry, threshold), + "a file referenced by a temporary reader must be kept" ); } -/// Test: dropped region unknown file should always be deleted regardless of TTL. +/// A known removed file is only deleted once its lingering period elapsed. #[tokio::test] -async fn test_unknown_file_dropped_region_deleted() { - let builder = services::Memory::default(); - let store = ObjectStore::new(builder).unwrap(); - - let entry = write_and_list_entry(&store, "test/3.parquet").await; - - // Even with threshold far in the past (epoch), dropped region deletes immediately. - let threshold = chrono::DateTime::from_timestamp(0, 0).unwrap(); - - let should_delete = should_delete_file( - false, // not in manifest - false, // not in tmp_ref - false, // not in may_linger - false, // not eligible for delete - true, // region dropped - &entry, threshold, - ); - assert!( - should_delete, - "Dropped region unknown file should be deleted immediately" - ); -} - -/// Test: file in manifest should NOT be deleted even if unknown. -#[tokio::test] -async fn test_file_in_manifest_not_deleted() { - let builder = services::Memory::default(); - let store = ObjectStore::new(builder).unwrap(); - - let entry = write_and_list_entry(&store, "test/4.parquet").await; - let threshold = chrono::Utc::now() + chrono::Duration::days(1); - - let should_delete = should_delete_file( - true, // in manifest - false, // not in tmp_ref - false, false, false, // active region - &entry, threshold, - ); - assert!(!should_delete, "File in manifest should NOT be deleted"); -} - -/// Test: file in tmp_ref should NOT be deleted even if unknown. -#[tokio::test] -async fn test_file_in_tmp_ref_not_deleted() { - let builder = services::Memory::default(); - let store = ObjectStore::new(builder).unwrap(); - - let entry = write_and_list_entry(&store, "test/5.parquet").await; - let threshold = chrono::Utc::now() + chrono::Duration::days(1); - - let should_delete = should_delete_file( - false, true, // in tmp_ref - false, false, false, // active region - &entry, threshold, - ); - assert!(!should_delete, "File in tmp_ref should NOT be deleted"); -} - -/// Test: known removed file that is still lingering should NOT be deleted. -/// (is_linger=true but is_eligible_for_delete=false) -#[tokio::test] -async fn test_known_file_still_lingering_not_deleted() { - let builder = services::Memory::default(); - let store = ObjectStore::new(builder).unwrap(); - +async fn test_known_removed_file_respects_linger() { + let store = ObjectStore::new(services::Memory::default()).unwrap(); let entry = write_and_list_entry(&store, "test/6.parquet").await; let threshold = chrono::Utc::now() + chrono::Duration::days(1); - let should_delete = should_delete_file( - false, false, true, // is_linger - false, // not yet eligible for delete - false, &entry, threshold, + assert!( + !should_delete_file(false, false, true, false, &entry, threshold), + "a removed file that is still lingering must be kept" ); assert!( - !should_delete, - "Known file still in lingering period should NOT be deleted" + should_delete_file(false, false, true, true, &entry, threshold), + "a removed file past its lingering period is reclaimed" ); } -/// Test: known removed file eligible for delete should be deleted. -/// (is_linger=true and is_eligible_for_delete=true) +/// Files at or after the cutoff are kept (`strict <` comparison). #[tokio::test] -async fn test_known_file_eligible_for_delete_deleted() { - let builder = services::Memory::default(); - let store = ObjectStore::new(builder).unwrap(); - - let entry = write_and_list_entry(&store, "test/7.parquet").await; - let threshold = chrono::DateTime::from_timestamp(0, 0).unwrap(); - - let should_delete = should_delete_file( - false, false, true, // is_linger - true, // eligible for delete - false, &entry, threshold, - ); - assert!( - should_delete, - "Known file eligible for delete should be deleted" - ); -} - -// --- Tests for boundary conditions and explicit "keep" semantics --- - -/// Test: when `last_modified` equals the cutoff exactly, the file should be -/// kept (strict `<` comparison, not `<=`). -#[tokio::test] -async fn test_unknown_file_at_cutoff_not_deleted() { - // Use Fs backend for real last_modified - let tmp_dir = common_test_util::temp_dir::create_temp_dir("gc_at_cutoff"); +async fn test_unknown_file_at_cutoff_kept() { + let tmp_dir = common_test_util::temp_dir::create_temp_dir("gc_cutoff"); let root = tmp_dir.path().to_string_lossy().to_string(); - let builder = services::Fs::default().root(&root); - let store = ObjectStore::new(builder).unwrap(); - + let store = ObjectStore::new(services::Fs::default().root(&root)).unwrap(); let entry = write_and_list_entry(&store, "cutoff.parquet").await; + let last_modified = entry.metadata().last_modified().unwrap(); + let threshold = + chrono::DateTime::from_timestamp_millis(last_modified.into_inner().as_millisecond()) + .unwrap(); - // Set threshold to the actual last_modified → should NOT be deleted (strict <) - let actual_mtime_millis = entry - .metadata() - .last_modified() - .map(|ts| ts.into_inner().as_millisecond()) - .expect("Fs backend must provide last_modified"); - // Construct a chrono::DateTime at exactly the same millisecond - let threshold = chrono::DateTime::from_timestamp_millis(actual_mtime_millis).unwrap(); - - let should_delete = should_delete_file( - false, // not in manifest - false, // not in tmp_ref - false, // not in may_linger - false, // not eligible for delete - false, // active region - &entry, threshold, - ); assert!( - !should_delete, - "File at exact cutoff (last_modified == threshold) should NOT be deleted (strict < comparison)" - ); -} - -/// Test: active unknown file with missing `last_modified` (e.g. object store -/// that does not provide the timestamp) should be conservatively kept. -#[tokio::test] -async fn test_missing_last_modified_unknown_kept() { - // Memory backend does NOT set last_modified - let builder = services::Memory::default(); - let store = ObjectStore::new(builder).unwrap(); - - let entry = write_and_list_entry(&store, "test/missing_mtime.parquet").await; - // Verify that last_modified is indeed None - assert!( - entry.metadata().last_modified().is_none(), - "Memory backend must not provide last_modified for this test" - ); - - // threshold in the far past → should still NOT delete - let threshold = chrono::DateTime::from_timestamp(0, 0).unwrap(); - - let should_delete = should_delete_file( - false, false, false, false, // active unknown - false, // active region - &entry, threshold, - ); - assert!( - !should_delete, - "Missing last_modified should keep the file (conservative behavior)" - ); -} - -/// Test: file in manifest should NOT be deleted even when its object -/// `last_modified` is very old (far below the TTL cutoff). -#[tokio::test] -async fn test_file_in_manifest_old_mtime_kept() { - let tmp_dir = common_test_util::temp_dir::create_temp_dir("gc_manifest_old"); - let root = tmp_dir.path().to_string_lossy().to_string(); - let builder = services::Fs::default().root(&root); - let store = ObjectStore::new(builder).unwrap(); - - let entry = write_and_list_entry(&store, "in_manifest.parquet").await; - // threshold far in the future → mtime is definitely old, but manifest protects - let threshold = chrono::Utc::now() + chrono::Duration::days(1); - - let should_delete = should_delete_file( - true, // in manifest - false, // not in tmp_ref - false, false, false, // not linger/eligible, active - &entry, threshold, - ); - assert!( - !should_delete, - "File in manifest should NOT be deleted even with old last-modified time" - ); -} - -/// Test: file in tmp_ref should NOT be deleted even when its object -/// `last_modified` is very old (far below the TTL cutoff). -#[tokio::test] -async fn test_file_in_tmp_ref_old_mtime_kept() { - let tmp_dir = common_test_util::temp_dir::create_temp_dir("gc_tmpref_old"); - let root = tmp_dir.path().to_string_lossy().to_string(); - let builder = services::Fs::default().root(&root); - let store = ObjectStore::new(builder).unwrap(); - - let entry = write_and_list_entry(&store, "in_tmp_ref.parquet").await; - // threshold far in the future → mtime is definitely old, but tmp_ref protects - let threshold = chrono::Utc::now() + chrono::Duration::days(1); - - let should_delete = should_delete_file( - false, true, // in tmp_ref - false, false, false, // not linger/eligible, active - &entry, threshold, - ); - assert!( - !should_delete, - "File in tmp_ref should NOT be deleted even with old last-modified time" + !should_delete_file(false, false, false, false, &entry, threshold), + "a file at the exact cutoff is kept" ); } @@ -1157,6 +992,177 @@ impl RegionHook for GcCountingHook { } } +#[derive(Debug, Clone, Copy)] +enum ProtectionOutcome { + Protected, + Unavailable, + PublishedDuringLookup, + Unprotected, +} + +#[derive(Debug)] +struct BlockingProtectionHook { + outcome: ProtectionOutcome, + entered: tokio::sync::Notify, + resume: tokio::sync::Notify, +} + +#[async_trait] +impl RegionHook for BlockingProtectionHook { + async fn protected_sst_files( + &self, + _access: &crate::access_layer::AccessLayer, + files: &[crate::sst::file::RegionFileId], + ) -> crate::error::Result> { + self.entered.notify_one(); + self.resume.notified().await; + match self.outcome { + ProtectionOutcome::Protected => Ok(files.iter().copied().collect()), + ProtectionOutcome::Unavailable => UnexpectedSnafu { + reason: "protection service unavailable", + } + .fail(), + _ => Ok(HashSet::new()), + } + } +} + +#[rstest::rstest] +#[case::protected(ProtectionOutcome::Protected)] +#[case::unavailable(ProtectionOutcome::Unavailable)] +#[case::published(ProtectionOutcome::PublishedDuringLookup)] +#[case::unprotected(ProtectionOutcome::Unprotected)] +#[tokio::test] +async fn test_gc_protection_and_manifest_recheck(#[case] outcome: ProtectionOutcome) { + let mut env = TestEnv::new().await; + let hook = Arc::new(BlockingProtectionHook { + outcome, + entered: Default::default(), + resume: Default::default(), + }); + let plugins = Plugins::new(); + plugins.insert(hook.clone() as RegionHookRef); + let engine = env + .create_engine_with_plugins( + MitoConfig { + schedule_compaction_after_edit: false, + gc: GcConfig { + enable: true, + lingering_time: None, + ..Default::default() + }, + ..Default::default() + }, + plugins, + ) + .await; + let region_id = RegionId::new(1, 1); + env.get_schema_metadata_manager() + .register_region_table_info( + region_id.table_id(), + "test_table", + "test_catalog", + "test_schema", + None, + env.get_kv_backend(), + ) + .await; + engine + .handle_request( + region_id, + RegionRequest::Create(CreateRequestBuilder::new().build()), + ) + .await + .unwrap(); + let region = engine.get_region(region_id).unwrap(); + let file = crate::sst::file::FileMeta { + region_id, + file_id: store_api::storage::FileId::random(), + ..Default::default() + }; + let path = crate::sst::location::sst_file_path( + region.access_layer.table_dir(), + file.file_id(), + region.access_layer.path_type(), + ); + region + .access_layer + .object_store() + .write(&path, Bytes::from_static(b"unreferenced SST")) + .await + .unwrap(); + engine + .edit_region( + region_id, + crate::manifest::action::RegionEdit { + files_to_add: vec![file.clone()], + ..Default::default() + }, + ) + .await + .unwrap(); + engine + .edit_region( + region_id, + crate::manifest::action::RegionEdit { + files_to_remove: vec![file.clone()], + ..Default::default() + }, + ) + .await + .unwrap(); + let refs = FileRefsManifest { + manifest_version: [(region_id, region.manifest_ctx.manifest_version().await)].into(), + file_refs: Default::default(), + cross_region_refs: Default::default(), + }; + let worker = create_gc_worker( + &engine, + [(region_id, Some(region.clone()))].into(), + &refs, + false, + ) + .await; + let temporary_refs = HashSet::new(); + let (gc, ()) = tokio::join!( + worker.do_region_gc(region_id, Some(region.clone()), &temporary_refs), + async { + hook.entered.notified().await; + if matches!(outcome, ProtectionOutcome::PublishedDuringLookup) { + engine + .edit_region( + region_id, + crate::manifest::action::RegionEdit { + files_to_add: vec![file], + ..Default::default() + }, + ) + .await + .unwrap(); + } + hook.resume.notify_one(); + } + ); + if matches!(outcome, ProtectionOutcome::Unavailable) { + assert!(gc.is_err()); + } else { + let gc = gc.unwrap(); + assert_eq!( + usize::from(matches!(outcome, ProtectionOutcome::Unprotected)), + gc.removed_files.len() + ); + } + assert_eq!( + !matches!(outcome, ProtectionOutcome::Unprotected), + region + .access_layer + .object_store() + .exists(&path) + .await + .unwrap() + ); +} + /// `on_region_gc` is **skipped** for a live region in **fast mode** (no full /// listing) when the GC pass deleted no files — the common case for a periodic /// pass — to avoid unnecessary hook overhead/I/O. A freshly-flushed region has @@ -1423,6 +1429,189 @@ async fn test_on_region_gc_fires_for_dropped_region() { ); } +/// Protects every candidate it is asked about; used to exercise deferrals on +/// the dropped-region reclamation path. +#[derive(Debug)] +struct ProtectAllHook; + +#[async_trait] +impl RegionHook for ProtectAllHook { + async fn protected_sst_files( + &self, + _access: &crate::access_layer::AccessLayer, + files: &[crate::sst::file::RegionFileId], + ) -> crate::error::Result> { + Ok(files.iter().copied().collect()) + } +} + +/// Shared setup: create a region with one flushed SST, then hand its access +/// layer to a dropped-region GC worker (region absent) built from `config` and +/// `hook`. Returns the worker and the region's SST/index object paths. +async fn dropped_region_gc_env( + config: GcConfig, + hook: Option, +) -> (TestEnv, MitoEngine, LocalGcWorker, RegionId, Vec) { + let mut env = TestEnv::new().await; + let engine = env + .create_engine(MitoConfig { + schedule_compaction_after_edit: false, + gc: config, + ..Default::default() + }) + .await; + let region_id = RegionId::new(3, 1); + env.get_schema_metadata_manager() + .register_region_table_info( + region_id.table_id(), + "test_table", + "test_catalog", + "test_schema", + None, + env.get_kv_backend(), + ) + .await; + let request = CreateRequestBuilder::new().build(); + engine + .handle_request(region_id, RegionRequest::Create(request.clone())) + .await + .unwrap(); + put_rows( + &engine, + region_id, + Rows { + schema: rows_schema(&request), + rows: build_rows(0, 3), + }, + ) + .await; + flush_region(&engine, region_id, None).await; + + let region = engine.get_region(region_id).unwrap(); + let access_layer = region.access_layer.clone(); + let manifest = region.manifest_ctx.manifest().await; + let version = manifest.manifest_version; + let store = access_layer.object_store(); + let mut paths = Vec::new(); + for meta in manifest.files.values() { + for path in [ + location::sst_file_path( + access_layer.table_dir(), + crate::sst::file::RegionFileId::new(meta.region_id, meta.file_id), + access_layer.path_type(), + ), + location::index_file_path( + access_layer.table_dir(), + meta.index_id(), + access_layer.path_type(), + ), + ] { + if store.exists(&path).await.unwrap() { + paths.push(path); + } + } + } + assert!(!paths.is_empty(), "the flushed SST objects must be listed"); + let file_ref_manifest = FileRefsManifest { + file_refs: Default::default(), + manifest_version: [(region_id, version)].into(), + cross_region_refs: HashMap::new(), + }; + let worker = LocalGcWorker::try_new( + access_layer, + Some(engine.cache_manager()), + BTreeMap::from([(region_id, None)]), + engine.mito_config().gc.clone(), + file_ref_manifest, + &engine.gc_limiter(), + true, + hook, + ) + .await + .unwrap(); + // Keep the env (and its data-home TempDir) alive for the caller: dropping + // it removes the on-disk objects that the dropped-region pass must list. + (env, engine, worker, region_id, paths) +} + +/// A dropped region's young unknown objects are deferred by +/// `unknown_file_lingering_time`; the pass must report `needs_retry` so the +/// meta tombstone survives and a later pass can reclaim them. +#[tokio::test] +async fn test_dropped_region_young_unknown_files_need_retry() { + init_default_ut_logging(); + let (_env, _engine, worker, region_id, paths) = dropped_region_gc_env( + GcConfig { + enable: true, + ..Default::default() + }, + None, + ) + .await; + + let outcome = worker + .do_region_gc(region_id, None, &HashSet::new()) + .await + .unwrap(); + + assert!(outcome.removed_files.is_empty()); + assert!( + outcome.needs_retry, + "deferred young unknown objects must keep the dropped-region tombstone" + ); + let store = worker.access_layer.object_store(); + for path in &paths { + assert!(store.exists(path).await.unwrap(), "{path} must survive"); + } +} + +/// Hook-protected candidates on a dropped region must also keep the tombstone; +/// once nothing defers the pass any longer the report clears so the procedure +/// can drop the tombstone. +#[tokio::test] +async fn test_dropped_region_hook_deferral_needs_retry_until_reclaimed() { + init_default_ut_logging(); + let config = GcConfig { + enable: true, + lingering_time: None, + unknown_file_lingering_time: std::time::Duration::ZERO, + ..Default::default() + }; + let (_env, _engine, worker, region_id, paths) = + dropped_region_gc_env(config.clone(), Some(Arc::new(ProtectAllHook))).await; + + let store = worker.access_layer.object_store(); + let protected = worker + .do_region_gc(region_id, None, &HashSet::new()) + .await + .unwrap(); + assert!(protected.removed_files.is_empty()); + assert!( + protected.needs_retry, + "hook-deferred candidates must keep the dropped-region tombstone" + ); + for path in &paths { + assert!(store.exists(path).await.unwrap(), "{path} must survive"); + } + + // Nothing defers any more: objects are old enough and no hook retains them, + // so this pass reclaims them and clears the retry flag. + let (_env, _engine, worker, region_id, paths) = dropped_region_gc_env(config, None).await; + let store = worker.access_layer.object_store(); + let reclaimed = worker + .do_region_gc(region_id, None, &HashSet::new()) + .await + .unwrap(); + assert!( + !reclaimed.needs_retry, + "nothing defers any more, so the tombstone can be dropped" + ); + assert!(!reclaimed.removed_files.is_empty()); + for path in &paths { + assert!(!store.exists(path).await.unwrap(), "{path} must be gone"); + } +} + /// `on_region_gc` **fires** on a full-listing pass even when mito itself deleted /// no files, so an extension can reconcile sidecar-only orphans (failed writes, /// leftovers from a previous cleanup). Contrast with the fast-mode skip in diff --git a/src/mito2/src/manifest.rs b/src/mito2/src/manifest.rs index 99cd93282cb..3eb66053575 100644 --- a/src/mito2/src/manifest.rs +++ b/src/mito2/src/manifest.rs @@ -16,6 +16,7 @@ pub mod action; mod checkpointer; +mod compat; pub mod manager; pub mod storage; #[cfg(test)] diff --git a/src/mito2/src/manifest/action.rs b/src/mito2/src/manifest/action.rs index 2d0c17137a8..5d5620bdab8 100644 --- a/src/mito2/src/manifest/action.rs +++ b/src/mito2/src/manifest/action.rs @@ -30,7 +30,7 @@ use crate::error::{RegionMetadataNotFoundSnafu, Result, SerdeJsonSnafu, Utf8Snaf use crate::manifest::manager::RemoveFileOptions; use crate::region::ManifestStats; use crate::sst::FormatType; -use crate::sst::file::FileMeta; +use crate::sst::file::{self, FileMeta}; use crate::wal::EntryId; /// Actions that can be applied to region manifest. @@ -83,7 +83,7 @@ pub struct RegionChange { pub append_mode: Option, } -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] +#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq, Eq)] pub struct RegionEdit { pub files_to_add: Vec, pub files_to_remove: Vec, @@ -97,6 +97,31 @@ pub struct RegionEdit { pub committed_sequence: Option, } +impl RegionEdit { + /// Shared reclassification must be add-only for a file ID: the manifest removes + /// by ID, while the in-memory Version removes from the specified level. + pub(crate) fn validate_shared_reclassification(&self, region_id: RegionId) -> Result<()> { + let shared_ids: HashSet<_> = self + .files_to_add + .iter() + .filter(|file| file.level == file::LEVEL_SHARED) + .map(|file| file.file_id) + .collect(); + snafu::ensure!( + shared_ids.is_empty() + || self + .files_to_remove + .iter() + .all(|file| !shared_ids.contains(&file.file_id)), + crate::error::InvalidRequestSnafu { + region_id, + reason: "Cannot add and remove the same shared SST in one edit", + } + ); + Ok(()) + } +} + #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] pub struct RegionRemove { pub region_id: RegionId, @@ -182,6 +207,15 @@ impl PartialEq for RegionManifest { } } +impl RegionManifest { + /// Rejects prototype task state before deserializing, so callers cannot + /// silently drop recovery evidence that this build cannot interpret. + pub(crate) fn decode(bytes: &[u8]) -> Result { + crate::manifest::compat::validate_manifest(bytes)?; + serde_json::from_slice(bytes).context(SerdeJsonSnafu) + } +} + #[derive(Debug, Default)] pub struct RegionManifestBuilder { metadata: Option, @@ -526,7 +560,7 @@ impl RegionCheckpoint { pub fn decode(bytes: &[u8]) -> Result { let data = std::str::from_utf8(bytes).context(Utf8Snafu)?; - + crate::manifest::compat::validate_checkpoint(data)?; serde_json::from_str(data).context(SerdeJsonSnafu) } } @@ -614,7 +648,7 @@ impl RegionMetaActionList { pub fn decode(bytes: &[u8]) -> Result { let data = std::str::from_utf8(bytes).context(Utf8Snafu)?; - + crate::manifest::compat::validate_actions(data)?; serde_json::from_str(data).context(SerdeJsonSnafu) } } @@ -629,6 +663,51 @@ mod tests { // These tests are used to ensure backward compatibility of manifest files. // DO NOT modify the serialized string when they fail, check if your // modification to manifest-related structs is compatible with older manifests. + #[test] + fn test_sketch_index_manifest_fixture() { + use crate::sst::file::IndexType; + + // Frozen persisted names. Keep this fixture unchanged when extending the format. + let fixture = r#"{"actions":[{"Edit":{"files_to_add":[{ + "region_id":0,"file_id":"bc5896ec-e4d8-4017-a80d-f2de73188d55", + "time_range":[{"value":0,"unit":"Millisecond"},{"value":1,"unit":"Millisecond"}], + "level":0,"index_version":7,"index_file_size":128, + "available_indexes":["InvertedIndex","HllIndex","KllIndex","MgIndex"], + "indexes":[{"column_id":3,"created_indexes":["InvertedIndex","HllIndex","KllIndex","MgIndex"]}] + }],"files_to_remove":[],"compaction_time_window":null}}]}"#; + let actions = RegionMetaActionList::decode(fixture.as_bytes()).unwrap(); + let RegionMetaAction::Edit(edit) = &actions.actions[0] else { + panic!("expected a file edit"); + }; + assert_eq!(actions.actions.len(), 1); + assert_eq!(edit.files_to_add.len(), 1); + let file = &edit.files_to_add[0]; + let expected = [ + IndexType::InvertedIndex, + IndexType::HllIndex, + IndexType::KllIndex, + IndexType::MgIndex, + ]; + assert_eq!(file.available_indexes.as_slice(), expected); + assert_eq!(file.indexes.len(), 1); + assert_eq!(file.indexes[0].column_id, 3); + assert_eq!(file.indexes[0].created_indexes.as_slice(), expected); + assert_eq!(file.index_version(), Some(7)); + assert_eq!(file.index_file_size, 128); + let encoded = actions.encode().unwrap(); + assert_eq!(RegionMetaActionList::decode(&encoded).unwrap(), actions); + let encoded: serde_json::Value = serde_json::from_slice(&encoded).unwrap(); + let names = serde_json::json!(["InvertedIndex", "HllIndex", "KllIndex", "MgIndex"]); + assert_eq!( + encoded["actions"][0]["Edit"]["files_to_add"][0]["available_indexes"], + names + ); + assert_eq!( + encoded["actions"][0]["Edit"]["files_to_add"][0]["indexes"][0]["created_indexes"], + names + ); + } + #[test] fn test_region_action_compatibility() { let region_edit = r#"{ diff --git a/src/mito2/src/manifest/checkpointer.rs b/src/mito2/src/manifest/checkpointer.rs index 232421a2621..3d33942a2f9 100644 --- a/src/mito2/src/manifest/checkpointer.rs +++ b/src/mito2/src/manifest/checkpointer.rs @@ -78,6 +78,9 @@ impl Inner { self.last_checkpoint_version .store(version, Ordering::Relaxed); + // Logical retention changes when the checkpoint is published, even if cleanup fails. + self.manifest_store.retain_manifest_size_after(version); + if let Err(e) = self.manifest_store.delete_until(version, true).await { warn!(e; "Failed to delete manifest actions until version {} for region {}, leftover files will be ignored on recovery", version, region_id); } diff --git a/src/mito2/src/manifest/compat.rs b/src/mito2/src/manifest/compat.rs new file mode 100644 index 00000000000..a81656e0e49 --- /dev/null +++ b/src/mito2/src/manifest/compat.rs @@ -0,0 +1,84 @@ +// 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. + +//! Reject unpublished prototype task-state records without adding persisted fields. +//! IgnoredAny skips file metadata without allocating a second manifest tree. + +#[cfg(test)] +mod tests; + +use std::collections::HashMap; + +use serde::Deserialize; +use serde::de::IgnoredAny; +use snafu::{ResultExt, ensure}; + +use crate::error::{Result, SerdeJsonSnafu, UnsupportedOperationSnafu, Utf8Snafu}; + +/// Serialized tag of [`crate::manifest::action::RegionMetaAction::Edit`]. +/// +/// The delta guard inspects raw JSON, so serde cannot select the variant for it. +/// Keep in sync with the enum; `compat::tests` fails if the tag drifts. +const EDIT_ACTION_TAG: &str = "Edit"; + +#[derive(Deserialize)] +struct TaskStateGuard { + table_compaction: Option, + extensions: Option, +} + +impl TaskStateGuard { + fn validate(&self) -> Result<()> { + ensure!(self.table_compaction.is_none() && self.extensions.is_none(), UnsupportedOperationSnafu { + err_msg: "Legacy compaction task state requires explicit migration; it cannot be discarded".to_string(), + }); + Ok(()) + } +} + +/// Validates a standalone manifest, such as a staging blob. +/// +/// Staging manifests are recovery evidence like checkpoints and deltas, so they +/// must not silently drop prototype task state either. +pub(crate) fn validate_manifest(bytes: &[u8]) -> Result<()> { + let data = std::str::from_utf8(bytes).context(Utf8Snafu)?; + let state: TaskStateGuard = serde_json::from_str(data).context(SerdeJsonSnafu)?; + state.validate() +} + +pub(crate) fn validate_checkpoint(json: &str) -> Result<()> { + #[derive(Deserialize)] + struct CheckpointGuard { + checkpoint: Option, + } + let guard: CheckpointGuard = serde_json::from_str(json).context(SerdeJsonSnafu)?; + if let Some(state) = guard.checkpoint { + state.validate()?; + } + Ok(()) +} + +pub(crate) fn validate_actions(json: &str) -> Result<()> { + #[derive(Deserialize)] + struct ActionListGuard { + actions: Vec>, + } + let guard: ActionListGuard = serde_json::from_str(json).context(SerdeJsonSnafu)?; + for action in guard.actions { + if let Some(edit) = action.get(EDIT_ACTION_TAG) { + edit.validate()?; + } + } + Ok(()) +} diff --git a/src/mito2/src/manifest/compat/tests.rs b/src/mito2/src/manifest/compat/tests.rs new file mode 100644 index 00000000000..52a115a6727 --- /dev/null +++ b/src/mito2/src/manifest/compat/tests.rs @@ -0,0 +1,26 @@ +// 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 crate::manifest::action::{RegionEdit, RegionMetaAction}; + +#[test] +fn test_edit_action_tag_matches_serialized_enum() { + let encoded = serde_json::to_value(RegionMetaAction::Edit(RegionEdit::default())).unwrap(); + let object = encoded.as_object().unwrap(); + assert_eq!(1, object.len(), "action must stay externally tagged"); + assert!( + object.contains_key(super::EDIT_ACTION_TAG), + "the delta guard reads raw JSON by tag; keep EDIT_ACTION_TAG in sync with RegionMetaAction" + ); +} diff --git a/src/mito2/src/manifest/manager.rs b/src/mito2/src/manifest/manager.rs index 5471b1883a9..7531c433191 100644 --- a/src/mito2/src/manifest/manager.rs +++ b/src/mito2/src/manifest/manager.rs @@ -17,7 +17,7 @@ use std::sync::atomic::{AtomicU64, Ordering}; use std::time::Instant; use common_datasource::compression::CompressionType; -use common_telemetry::{debug, info}; +use common_telemetry::{debug, info, warn}; use futures::TryStreamExt; use object_store::ObjectStore; use snafu::{OptionExt, ResultExt, ensure}; @@ -40,7 +40,7 @@ use crate::manifest::storage::{ }; use crate::metrics::MANIFEST_OP_ELAPSED; use crate::region::{ManifestStats, RegionLeaderState, RegionRoleState}; -use crate::sst::FormatType; +use crate::sst::{FormatType, file}; /// Options for [RegionManifestManager]. #[derive(Debug, Clone)] @@ -55,6 +55,9 @@ pub struct RegionManifestOptions { pub remove_file_options: RemoveFileOptions, /// Optional cache for manifest files. pub manifest_cache: Option, + /// Whether two writers can race for a version, so that deltas are published by conditional + /// create under a fixed name and recovery starts from the highest listed checkpoint. + pub(crate) conditional_publication: bool, } impl RegionManifestOptions { @@ -71,8 +74,16 @@ impl RegionManifestOptions { enable_gc: config.gc.enable, }, manifest_cache: None, + conditional_publication: false, } } + + /// Sets whether deltas are published by conditional create and recovery starts from the + /// highest listed checkpoint. + pub(crate) fn with_conditional_publication(mut self, enabled: bool) -> Self { + self.conditional_publication = enabled; + self + } } /// Options for updating `removed_files` field in [RegionManifest]. @@ -174,13 +185,15 @@ impl RegionManifestManager { stats: &ManifestStats, ) -> Result { // construct storage - let mut store = ManifestObjectStore::new( + let mut store = ManifestObjectStore::new_with_metric( &options.manifest_dir, options.object_store.clone(), options.compress_type, stats.total_manifest_size.clone(), + stats.metric().cloned(), options.manifest_cache.clone(), - ); + ) + .with_conditional_publication(options.conditional_publication)?; let manifest_version = stats.manifest_version.clone(); info!( @@ -236,7 +249,7 @@ impl RegionManifestManager { manifest .removed_files .update_file_removed_cnt_to_stats(stats); - Ok(Self { + let manager = Self { store, last_version: manifest_version, checkpointer, @@ -244,7 +257,8 @@ impl RegionManifestManager { staging_manifest: None, stats: stats.clone(), stopped: false, - }) + }; + Ok(manager) } /// Opens an existing manifest. @@ -260,13 +274,15 @@ impl RegionManifestManager { let open_start = Instant::now(); // construct storage - let mut store = ManifestObjectStore::new( + let mut store = ManifestObjectStore::new_with_metric( &options.manifest_dir, options.object_store.clone(), options.compress_type, stats.total_manifest_size.clone(), + stats.metric().cloned(), options.manifest_cache.clone(), - ); + ) + .with_conditional_publication(options.conditional_publication)?; let manifest_version = stats.manifest_version.clone(); // recover from storage @@ -276,9 +292,9 @@ impl RegionManifestManager { let checkpoint = Self::last_checkpoint(&mut store).await?; let last_checkpoint_version = checkpoint .as_ref() - .map(|(checkpoint, _)| checkpoint.last_version) + .map(|checkpoint| checkpoint.last_version) .unwrap_or(MIN_VERSION); - let mut manifest_builder = if let Some((checkpoint, _)) = checkpoint { + let mut manifest_builder = if let Some(checkpoint) = checkpoint { info!( "Recover region manifest {} from checkpoint version {}", options.manifest_dir, checkpoint.last_version @@ -305,8 +321,6 @@ impl RegionManifestManager { for (manifest_version, raw_action_list) in manifests { let action_list = RegionMetaActionList::decode(&raw_action_list)?; - // set manifest size after last checkpoint - store.set_delta_file_size(manifest_version, raw_action_list.len() as u64); for action in action_list.actions { match action { RegionMetaAction::Change(action) => { @@ -365,7 +379,7 @@ impl RegionManifestManager { version, open_start.elapsed(), ); - Ok(Some(Self { + let manager = Self { store, last_version: manifest_version, checkpointer, @@ -374,7 +388,8 @@ impl RegionManifestManager { staging_manifest: None, stats: stats.clone(), stopped: false, - })) + }; + Ok(Some(manager)) } /// Stops the manager. @@ -396,18 +411,30 @@ impl RegionManifestManager { &mut self, target_version: ManifestVersion, ) -> Result { + let (version, loaded_checkpoint) = self.install_manifest_to_inner(target_version).await?; + if !loaded_checkpoint && let Err(error) = self.store.update_manifest_size(version).await { + warn!(error; "Failed to update manifest size after sync for region {}", self.manifest.metadata.region_id); + } + Ok(version) + } + + async fn install_manifest_to_inner( + &mut self, + target_version: ManifestVersion, + ) -> Result<(ManifestVersion, bool)> { let _t = MANIFEST_OP_ELAPSED .with_label_values(&["install_manifest_to"]) .start_timer(); let last_version = self.last_version(); + let mut loaded_checkpoint = false; // Case 1: If the target version is less than the current version, return the current version. if last_version >= target_version { debug!( "Target version {} is less than or equal to the current version {}, region: {}, skip install", target_version, last_version, self.manifest.metadata.region_id ); - return Ok(last_version); + return Ok((last_version, false)); } ensure!( @@ -437,9 +464,10 @@ impl RegionManifestManager { last_version, self.manifest.metadata.region_id ); let last_version = self.install_last_checkpoint().await?; + loaded_checkpoint = true; // Case 2.1: If the installed checkpoint version is greater than or equal to the target version, return the last version. if last_version >= target_version { - return Ok(last_version); + return Ok((last_version, true)); } // Fetches manifests from the installed version strictly. @@ -465,8 +493,6 @@ impl RegionManifestManager { RegionManifestBuilder::with_checkpoint(Some(self.manifest.as_ref().clone())); for (manifest_version, raw_action_list) in manifests { - self.store - .set_delta_file_size(manifest_version, raw_action_list.len() as u64); let action_list = RegionMetaActionList::decode(&raw_action_list)?; for action in action_list.actions { match action { @@ -514,23 +540,19 @@ impl RegionManifestManager { version, last_version, self.manifest.metadata.region_id ); - Ok(last_version) + Ok((last_version, loaded_checkpoint)) } /// Installs the last checkpoint. pub(crate) async fn install_last_checkpoint(&mut self) -> Result { let last_version = self.last_version(); - let Some((checkpoint, checkpoint_size)) = Self::last_checkpoint(&mut self.store).await? - else { + let Some(checkpoint) = Self::last_checkpoint(&mut self.store).await? else { return NoCheckpointSnafu { region_id: self.manifest.metadata.region_id, last_version, } .fail(); }; - self.store.reset_manifest_size(); - self.store - .set_checkpoint_file_size(checkpoint.last_version, checkpoint_size); let builder = RegionManifestBuilder::with_checkpoint(checkpoint.checkpoint); let manifest = builder.try_build()?; let last_version = self.set_version(manifest.manifest_version); @@ -547,32 +569,30 @@ impl RegionManifestManager { } /// Updates the manifest. Returns the current manifest version number. + /// + /// The caller has no Leader deadline to show that its commit returned in time, so a normal + /// commit under conditional publication is always verified and starts no checkpoint. pub async fn update( &mut self, action_list: RegionMetaActionList, is_staging: bool, ) -> Result { - self.update_inner(action_list, is_staging, !is_staging) + self.update_with_verification(action_list, is_staging, !is_staging, || true) .await } - /// Updates the normal manifest without starting a checkpoint. + /// Updates the manifest. Returns the current manifest version number. /// - /// This is only used while a leader is downgrading. The final flush still - /// publishes its manifest edit, but must not start cleanup after the - /// downgrade checkpoint barrier. - pub(crate) async fn update_normal_without_checkpoint( - &mut self, - action_list: RegionMetaActionList, - ) -> Result { - self.update_inner(action_list, false, false).await - } - - async fn update_inner( + /// `allow_checkpoint` tells whether a normal commit may start a checkpoint. `must_verify` is + /// evaluated after the save returns, for a normal commit under conditional publication. If it + /// returns true, the commit may have landed on a name that checkpoint cleanup freed, so it + /// only applies when LIST finds no checkpoint that covers it, and it starts no checkpoint. + pub(crate) async fn update_with_verification( &mut self, action_list: RegionMetaActionList, is_staging: bool, - allow_checkpoint: bool, + mut allow_checkpoint: bool, + must_verify: impl FnOnce() -> bool, ) -> Result { let _t = MANIFEST_OP_ELAPSED .with_label_values(&["update"]) @@ -585,10 +605,35 @@ impl RegionManifestManager { } ); - let version = self.increase_version(); + for action in &action_list.actions { + if let RegionMetaAction::Edit(edit) = action { + for file in edit.files_to_add.iter().chain(&edit.files_to_remove) { + ensure!( + file::is_supported_level(file.level), + crate::error::InvalidRequestSnafu { + region_id: self.manifest.metadata.region_id, + reason: format!("Unsupported SST level {}", file.level), + } + ); + } + } + } + let conditional = self.store.is_conditional_publication(); + let version = if conditional { + self.last_version() + 1 + } else { + self.increase_version() + }; self.store .save(version, &action_list.encode()?, is_staging) .await?; + if conditional { + if !is_staging && must_verify() { + self.store.ensure_version_not_checkpointed(version).await?; + allow_checkpoint = false; + } + self.set_version(version); + } // For a staging region, the manifest is initially inherited from the previous manifest(i.e., `self.manifest`). // When the staging manifest becomes available, it will be used to construct the new manifest. @@ -736,15 +781,15 @@ impl RegionManifestManager { /// Fetches the last [RegionCheckpoint] from storage. /// /// If the checkpoint is not found, returns `None`. - /// Otherwise, returns the checkpoint and the size of the checkpoint. + /// Otherwise, returns the decoded checkpoint. pub(crate) async fn last_checkpoint( store: &mut ManifestObjectStore, - ) -> Result> { + ) -> Result> { let last_checkpoint = store.load_last_checkpoint().await?; if let Some((_, bytes)) = last_checkpoint { let checkpoint = RegionCheckpoint::decode(&bytes)?; - Ok(Some((checkpoint, bytes.len() as u64))) + Ok(Some(checkpoint)) } else { Ok(None) } @@ -856,7 +901,7 @@ mod test { use super::*; use crate::manifest::action::{RegionChange, RegionEdit}; - use crate::manifest::tests::utils::basic_region_metadata; + use crate::manifest::tests::utils::{basic_region_metadata, manifest_recovery_usage}; use crate::test_util::TestEnv; #[tokio::test] @@ -972,26 +1017,6 @@ mod test { manager.validate_manifest(&new_metadata, 1); } - /// Just for test, refer to wal_dir_usage in src/store-api/src/logstore.rs. - async fn manifest_dir_usage(path: &str) -> u64 { - let mut size = 0; - let mut read_dir = tokio::fs::read_dir(path).await.unwrap(); - while let Ok(dir_entry) = read_dir.next_entry().await { - let Some(entry) = dir_entry else { - break; - }; - if entry.file_type().await.unwrap().is_file() { - let file_name = entry.file_name().into_string().unwrap(); - if file_name.contains(".checkpoint") || file_name.contains(".json") { - let file_size = entry.metadata().await.unwrap().len() as usize; - debug!("File: {file_name:?}, size: {file_size}"); - size += file_size; - } - } - } - size as u64 - } - #[tokio::test] async fn test_manifest_size() { let metadata = Arc::new(basic_region_metadata()); @@ -1028,7 +1053,7 @@ mod test { // get manifest size let manifest_size = manager.manifest_usage(); - assert_eq!(manifest_size, manifest_dir_usage(&manifest_dir).await); + assert_eq!(manifest_size, manifest_recovery_usage(&manifest_dir).await); // update 10 times nop_action to trigger checkpoint for _ in 0..10 { @@ -1055,10 +1080,9 @@ mod test { // check manifest size again let manifest_size = manager.manifest_usage(); - assert_eq!(manifest_size, manifest_dir_usage(&manifest_dir).await); + assert_eq!(manifest_size, manifest_recovery_usage(&manifest_dir).await); - // Reopen the manager, - // we just calculate the size from the latest checkpoint file + // Reopening reconstructs the same logical recovery set from stored bytes. manager.stop().await; let manager = env .create_manifest_manager(CompressionType::Uncompressed, 10, None) @@ -1068,7 +1092,9 @@ mod test { manager.validate_manifest(&new_metadata, 11); // get manifest size again - let manifest_size = manager.manifest_usage(); - assert_eq!(manifest_size, 1398); + assert_eq!( + manager.manifest_usage(), + manifest_recovery_usage(&manifest_dir).await + ); } } diff --git a/src/mito2/src/manifest/storage.rs b/src/mito2/src/manifest/storage.rs index 9ebeef2e9ab..7de29a319df 100644 --- a/src/mito2/src/manifest/storage.rs +++ b/src/mito2/src/manifest/storage.rs @@ -24,27 +24,29 @@ use std::sync::Arc; use std::sync::atomic::AtomicU64; use common_datasource::compression::CompressionType; +use common_error::ext::ErrorExt; use common_telemetry::{debug, warn}; use crc32fast::Hasher; +use futures::TryStreamExt; use lazy_static::lazy_static; use object_store::util::join_dir; use object_store::{Lister, ObjectStore, util}; use regex::Regex; -#[cfg(test)] -use snafu::ResultExt; -use snafu::ensure; -use store_api::ManifestVersion; +use snafu::{ResultExt, ensure}; use store_api::storage::RegionId; +use store_api::{MIN_VERSION, ManifestVersion}; use crate::cache::manifest_cache::ManifestCache; -#[cfg(test)] -use crate::error::OpenDalSnafu; -use crate::error::{ChecksumMismatchSnafu, Result}; +use crate::error::{ + ChecksumMismatchSnafu, ManifestVersionConflictSnafu, OpenDalSnafu, Result, + UnsupportedOperationSnafu, +}; use crate::manifest::storage::checkpoint::CheckpointStorage; use crate::manifest::storage::delta::DeltaStorage; use crate::manifest::storage::size_tracker::{CheckpointTracker, DeltaTracker, SizeTracker}; use crate::manifest::storage::staging::StagingStorage; use crate::manifest::storage::utils::remove_from_cache; +use crate::metrics::manifest_size::RegionManifestSizeMetric; lazy_static! { static ref DELTA_RE: Regex = Regex::new("^\\d+\\.json").unwrap(); @@ -166,6 +168,8 @@ pub struct ManifestObjectStore { delta_storage: DeltaStorage, /// The staging file storage. staging_storage: StagingStorage, + /// Whether deltas are created conditionally and the last checkpoint is found by LIST. + conditional_publication: bool, } impl ManifestObjectStore { @@ -175,11 +179,30 @@ impl ManifestObjectStore { compress_type: CompressionType, total_manifest_size: Arc, manifest_cache: Option, + ) -> Self { + Self::new_with_metric( + path, + object_store, + compress_type, + total_manifest_size, + None, + manifest_cache, + ) + } + + /// Constructs a store sharing the region instance's publication state. + pub(crate) fn new_with_metric( + path: &str, + object_store: ObjectStore, + compress_type: CompressionType, + total_manifest_size: Arc, + metric: Option, + manifest_cache: Option, ) -> Self { common_telemetry::info!("Create manifest store, cache: {}", manifest_cache.is_some()); let path = util::normalize_dir(path); - let size_tracker = SizeTracker::new(total_manifest_size); + let size_tracker = SizeTracker::new(total_manifest_size, metric); let checkpoint_tracker = Arc::new(size_tracker.checkpoint_tracker()); let delta_tracker = Arc::new(size_tracker.manifest_tracker()); let checkpoint_storage = CheckpointStorage::new( @@ -207,9 +230,34 @@ impl ManifestObjectStore { checkpoint_storage, delta_storage, staging_storage, + conditional_publication: false, } } + /// Sets whether this store publishes deltas by conditional create and recovers from the + /// highest checkpoint found by LIST. + /// + /// Returns an error if the mode is enabled on a backend without conditional create. + pub(crate) fn with_conditional_publication(mut self, enabled: bool) -> Result { + let capability = self.object_store.info().capability(); + ensure!( + !enabled || capability.write_with_if_not_exists, + UnsupportedOperationSnafu { + err_msg: format!( + "conditional create is required for manifest {} of a region whose writes need a lease", + self.path + ), + } + ); + self.conditional_publication = enabled; + Ok(self) + } + + /// Returns whether this store publishes deltas by conditional create. + pub(crate) fn is_conditional_publication(&self) -> bool { + self.conditional_publication + } + /// Returns the manifest dir pub(crate) fn manifest_dir(&self) -> &str { &self.path @@ -262,7 +310,7 @@ impl ManifestObjectStore { /// Delete manifest files that version < end. /// If keep_last_checkpoint is true, the last checkpoint file will be kept. /// ### Return - /// The number of deleted files. + /// The number of files whose deletion was acknowledged by the object store. pub async fn delete_until( &self, end: ManifestVersion, @@ -336,9 +384,9 @@ impl ManifestObjectStore { // Try batch delete first. On failure, fall back to per-file deletes. // This is a workaround for S3-compatible object stores that do not support batch delete. See issue #7986. - let mut succeeded = vec![false; del_entries.len()]; + let mut deleted = 0; match self.object_store.delete_iter(paths.clone()).await { - Ok(()) => succeeded.fill(true), + Ok(()) => deleted = total, Err(batch_err) => { warn!( batch_err; @@ -354,26 +402,11 @@ impl ManifestObjectStore { ); break; } - succeeded[i] = true; + deleted += 1; } } } - let mut deleted = 0usize; - for (i, (_, is_checkpoint, version)) in del_entries.iter().enumerate() { - if !succeeded[i] { - continue; - } - deleted += 1; - if *is_checkpoint { - self.size_tracker - .remove(&size_tracker::FileKey::Checkpoint(*version)); - } else { - self.size_tracker - .remove(&size_tracker::FileKey::Delta(*version)); - } - } - Ok(deleted) } @@ -386,11 +419,35 @@ impl ManifestObjectStore { ) -> Result<()> { if is_staging { self.staging_storage.save(version, bytes).await + } else if self.conditional_publication { + self.delta_storage.save_conditional(version, bytes).await } else { self.delta_storage.save(version, bytes).await } } + /// Fails with a version conflict unless LIST proves that no checkpoint at or above `version` + /// exists. + /// + /// Cleanup deletes a delta only after a checkpoint that covers it is saved, and never deletes + /// the highest checkpoint. So a late create that landed on a deleted name always finds one. + pub(crate) async fn ensure_version_not_checkpointed( + &self, + version: ManifestVersion, + ) -> Result<()> { + let reason = match self.list_highest_checkpoint(version).await { + Ok(None) => return Ok(()), + Ok(Some((checkpoint, _))) => format!("covered by checkpoint {checkpoint}"), + Err(e) => format!("cannot list the checkpoints: {}", e.output_msg()), + }; + ManifestVersionConflictSnafu { + version, + manifest_dir: &self.path, + reason, + } + .fail() + } + /// Save the checkpoint manifest file. pub(crate) async fn save_checkpoint( &self, @@ -404,8 +461,27 @@ impl ManifestObjectStore { /// Load the latest checkpoint. /// Return manifest version and the raw [RegionCheckpoint](crate::manifest::action::RegionCheckpoint) content if any + /// Also applies the checkpoint retention rule to the tracked size. pub async fn load_last_checkpoint(&mut self) -> Result)>> { - self.checkpoint_storage.load_last_checkpoint().await + let checkpoint = if self.conditional_publication { + match self.list_highest_checkpoint(MIN_VERSION).await { + Ok(Some((version, compress_type))) => Some( + self.checkpoint_storage + .load_listed_checkpoint(version, compress_type) + .await?, + ), + Ok(None) => None, + // A region that does not exist yet can have no manifest directory. + Err(e) if e.is_object_not_found() => None, + Err(e) => return Err(e), + } + } else { + self.checkpoint_storage.load_last_checkpoint().await? + }; + if let Some((version, _)) = &checkpoint { + self.retain_manifest_size_after(*version); + } + Ok(checkpoint) } /// Compute the size(Byte) in manifest size map. @@ -413,19 +489,36 @@ impl ManifestObjectStore { self.size_tracker.total() } - /// Resets the size of all files. - pub(crate) fn reset_manifest_size(&mut self) { - self.size_tracker.reset(); + /// Accounts for the latest checkpoint already covered by this follower's replay. + /// Only a changed or previously unaccounted checkpoint needs a stat. + pub(crate) async fn update_manifest_size( + &self, + replayed_version: ManifestVersion, + ) -> Result<()> { + let Some(metadata) = self + .checkpoint_storage + .read_last_checkpoint_metadata() + .await? + else { + return Ok(()); + }; + if metadata.version > replayed_version { + // Pruning now would stop counting deltas still in this follower's recovery set. + // Retention applies once replay covers this version or sync installs the checkpoint. + return Ok(()); + } + if !self.size_tracker.contains_checkpoint(metadata.version) { + self.checkpoint_storage + .record_checkpoint_size(metadata.version) + .await?; + } + self.retain_manifest_size_after(metadata.version); + Ok(()) } - /// Set the size of the delta file by delta version. - pub(crate) fn set_delta_file_size(&mut self, version: ManifestVersion, size: u64) { - self.size_tracker.record_delta(version, size); - } - - /// Set the size of the checkpoint file by checkpoint version. - pub(crate) fn set_checkpoint_file_size(&self, version: ManifestVersion, size: u64) { - self.size_tracker.record_checkpoint(version, size); + /// Prunes logical accounting independently of physical cleanup success. + pub(crate) fn retain_manifest_size_after(&self, version: ManifestVersion) { + self.size_tracker.retain_after(version); } /// Fetch all staging manifest files and return them as (version, action_list) pairs. @@ -442,6 +535,31 @@ impl ManifestObjectStore { pub(crate) fn staging_storage(&self) -> &StagingStorage { &self.staging_storage } + + /// Returns the version and compression of the highest checkpoint at or above `min_version` + /// found by LIST. + async fn list_highest_checkpoint( + &self, + min_version: ManifestVersion, + ) -> Result> { + let mut lister = self + .object_store + .lister_with(&self.path) + .start_after(&list_start_after(&self.path, min_version)) + .await + .context(OpenDalSnafu)?; + let mut highest = None; + while let Some(entry) = lister.try_next().await.context(OpenDalSnafu)? { + let file_name = entry.name(); + if is_checkpoint_file(file_name) { + let version = file_version(file_name); + if version >= min_version && highest.is_none_or(|(v, _)| v < version) { + highest = Some((version, file_compress_type(file_name))); + } + } + } + Ok(highest) + } } #[cfg(test)] @@ -701,8 +819,10 @@ mod tests { // delete 3 manifest files assert_eq!(log_store.delete_until(3, false).await.unwrap(), 3); - // manifest files size after delete - assert_eq!(log_store.total_manifest_size(), 39); + // Physical deletion does not define the logical recovery set. + assert_eq!(log_store.total_manifest_size(), 63); + log_store.retain_manifest_size_after(5); + assert_eq!(log_store.total_manifest_size(), 23); // delete all manifest files assert_eq!( @@ -713,7 +833,7 @@ mod tests { 3 ); - assert_eq!(log_store.total_manifest_size(), 0); + assert_eq!(log_store.total_manifest_size(), 23); } #[tokio::test] @@ -739,8 +859,10 @@ mod tests { // delete 3 manifest files assert_eq!(log_store.delete_until(3, false).await.unwrap(), 3); - // manifest files size after delete - assert_eq!(log_store.total_manifest_size(), 97); + // Physical deletion does not define the logical recovery set. + assert_eq!(log_store.total_manifest_size(), 181); + log_store.retain_manifest_size_after(5); + assert_eq!(log_store.total_manifest_size(), 41); // delete all manifest files assert_eq!( @@ -751,7 +873,7 @@ mod tests { 3 ); - assert_eq!(log_store.total_manifest_size(), 0); + assert_eq!(log_store.total_manifest_size(), 41); } #[tokio::test] @@ -815,4 +937,243 @@ mod tests { .unwrap(); assert!(entries.is_empty()); } + + #[derive(Debug, Clone, Copy, PartialEq, Eq)] + enum CacheSource { + WriteThrough, + RemoteFill, + LegacyDecoded, + Truncated, + } + + #[derive(Debug, Clone, Copy)] + enum PayloadKind { + Delta, + Checkpoint { checksum: bool }, + } + + // Exercise both representations left by older versions, as well as new writes + // and remote fills. Truncation only applies to compression envelopes. + #[rstest::rstest] + #[case::write_through_uncompressed(CacheSource::WriteThrough, CompressionType::Uncompressed)] + #[case::write_through_gzip(CacheSource::WriteThrough, CompressionType::Gzip)] + #[case::write_through_zstd(CacheSource::WriteThrough, CompressionType::Zstd)] + #[case::write_through_xz(CacheSource::WriteThrough, CompressionType::Xz)] + #[case::write_through_bzip2(CacheSource::WriteThrough, CompressionType::Bzip2)] + #[case::remote_fill_uncompressed(CacheSource::RemoteFill, CompressionType::Uncompressed)] + #[case::remote_fill_gzip(CacheSource::RemoteFill, CompressionType::Gzip)] + #[case::remote_fill_zstd(CacheSource::RemoteFill, CompressionType::Zstd)] + #[case::remote_fill_xz(CacheSource::RemoteFill, CompressionType::Xz)] + #[case::remote_fill_bzip2(CacheSource::RemoteFill, CompressionType::Bzip2)] + #[case::legacy_decoded_uncompressed(CacheSource::LegacyDecoded, CompressionType::Uncompressed)] + #[case::legacy_decoded_gzip(CacheSource::LegacyDecoded, CompressionType::Gzip)] + #[case::legacy_decoded_zstd(CacheSource::LegacyDecoded, CompressionType::Zstd)] + #[case::legacy_decoded_xz(CacheSource::LegacyDecoded, CompressionType::Xz)] + #[case::legacy_decoded_bzip2(CacheSource::LegacyDecoded, CompressionType::Bzip2)] + #[case::truncated_gzip(CacheSource::Truncated, CompressionType::Gzip)] + #[case::truncated_zstd(CacheSource::Truncated, CompressionType::Zstd)] + #[case::truncated_xz(CacheSource::Truncated, CompressionType::Xz)] + #[case::truncated_bzip2(CacheSource::Truncated, CompressionType::Bzip2)] + #[tokio::test] + async fn test_manifest_cache_payload( + #[case] source: CacheSource, + #[case] compression: CompressionType, + #[values(PayloadKind::Delta, PayloadKind::Checkpoint { checksum: false }, PayloadKind::Checkpoint { checksum: true })] + payload: PayloadKind, + ) { + use std::sync::atomic::{AtomicUsize, Ordering}; + + use common_base::readable_size::ReadableSize; + use object_store::layers::mock::MockLayerBuilder; + + let remote_dir = create_temp_dir("manifest-cache-remote"); + let cache_dir = create_temp_dir("manifest-cache-local"); + let remote = + ObjectStore::new(Fs::default().root(remote_dir.path().to_str().unwrap())).unwrap(); + let local = + ObjectStore::new(Fs::default().root(cache_dir.path().to_str().unwrap())).unwrap(); + let reads = Arc::new(AtomicUsize::new(0)); + let observed = reads.clone(); + let remote = remote.layer( + MockLayerBuilder::default() + .reader_factory(Arc::new(move |_, _, reader| { + observed.fetch_add(1, Ordering::Relaxed); + reader + })) + .build() + .unwrap(), + ); + let mut cache = ManifestCache::new(local.clone(), ReadableSize::mb(32), None, true).await; + let mut store = ManifestObjectStore::new( + "region/manifest/", + remote.clone(), + compression, + Default::default(), + (source != CacheSource::RemoteFill).then(|| cache.clone()), + ); + let data = br#"{"manifest":"persistent cache payload"}"#; + let key = gen_path( + "region/manifest/", + &if matches!(payload, PayloadKind::Checkpoint { .. }) { + checkpoint_file(3) + } else { + delta_file(3) + }, + compression, + ); + if matches!(payload, PayloadKind::Checkpoint { .. }) { + store.save_checkpoint(3, data).await.unwrap(); + } else { + store.save(3, data, false).await.unwrap(); + } + let encoded = remote.read(&key).await.unwrap().to_vec(); + if source == CacheSource::LegacyDecoded { + cache.put_file(key.clone(), data.to_vec()).await; + } else if source == CacheSource::Truncated { + cache + .put_file(key.clone(), encoded[..encoded.len() / 2].to_vec()) + .await; + } + drop(store); + for iteration in 0..2 { + drop(cache); + cache = ManifestCache::new(local.clone(), ReadableSize::mb(32), None, true).await; + if source != CacheSource::RemoteFill || iteration > 0 { + assert!( + cache.get(&key).await.is_some(), + "cache recovery missed {key}" + ); + } + store = ManifestObjectStore::new( + "region/manifest/", + remote.clone(), + compression, + Default::default(), + Some(cache.clone()), + ); + let before = reads.load(Ordering::Relaxed); + let actual = if let PayloadKind::Checkpoint { checksum } = payload { + let metadata = CheckpointMetadata { + size: data.len(), + version: 3, + checksum: checksum.then(|| checkpoint_checksum(data)), + extend_metadata: Default::default(), + }; + store + .checkpoint_storage + .load_checkpoint(metadata) + .await + .unwrap() + .unwrap() + } else { + let mut deltas = store.fetch_manifests(3, 4).await.unwrap(); + assert_eq!(1, deltas.len()); + deltas.remove(0) + }; + assert_eq!((3, data.to_vec()), actual); + // A successful roundtrip alone could hide a decoded refill that causes + // repeated cache misses. Check both the bytes and remote read count. + assert_eq!(encoded, cache.get_file(&key).await.unwrap()); + let must_refill = iteration == 0 + && (source == CacheSource::RemoteFill + || (compression != CompressionType::Uncompressed + && (source == CacheSource::LegacyDecoded + || source == CacheSource::Truncated))); + assert_eq!( + usize::from(must_refill), + reads.load(Ordering::Relaxed) - before + ); + drop(store); + } + } + + #[rstest::rstest] + #[case::checksum(false)] + #[case::decompression(true)] + #[tokio::test] + async fn test_manifest_cache_corrupted_remote(#[case] invalid_encoding: bool) { + use crate::error::Error; + use common_base::readable_size::ReadableSize; + + let remote_dir = create_temp_dir("manifest-cache-remote"); + let cache_dir = create_temp_dir("manifest-cache-local"); + let remote = + ObjectStore::new(Fs::default().root(remote_dir.path().to_str().unwrap())).unwrap(); + let local = + ObjectStore::new(Fs::default().root(cache_dir.path().to_str().unwrap())).unwrap(); + let cache = ManifestCache::new(local, ReadableSize::mb(32), None, true).await; + let mut store = ManifestObjectStore::new( + "region/", + remote.clone(), + CompressionType::Gzip, + Default::default(), + Some(cache.clone()), + ); + store.save_checkpoint(3, b"checkpoint").await.unwrap(); + let key = gen_path("region/", &checkpoint_file(3), CompressionType::Gzip); + let corrupted = if invalid_encoding { + b"invalid gzip".to_vec() + } else { + CompressionType::Gzip + .encode(b"other".as_slice()) + .await + .unwrap() + }; + remote.write(&key, corrupted).await.unwrap(); + // A legacy decoded cache entry must not hide the remote error on refill. + cache.put_file(key.clone(), b"checkpoint".to_vec()).await; + let error = store.load_last_checkpoint().await.unwrap_err(); + if invalid_encoding { + assert!(matches!(error, Error::DecompressObject { .. }), "{error}"); + } else { + assert!(matches!(error, Error::ChecksumMismatch { .. }), "{error}"); + } + assert!(cache.get(&key).await.is_none()); + } + + #[tokio::test] + async fn test_manifest_cache_uncompressed_fallback() { + use common_base::readable_size::ReadableSize; + + let remote_dir = create_temp_dir("manifest-cache-remote"); + let cache_dir = create_temp_dir("manifest-cache-local"); + let remote = + ObjectStore::new(Fs::default().root(remote_dir.path().to_str().unwrap())).unwrap(); + let local = + ObjectStore::new(Fs::default().root(cache_dir.path().to_str().unwrap())).unwrap(); + let cache = ManifestCache::new(local.clone(), ReadableSize::mb(32), None, true).await; + let store = ManifestObjectStore::new( + "region/", + remote.clone(), + CompressionType::Uncompressed, + Default::default(), + Some(cache.clone()), + ); + store.save_checkpoint(3, b"checkpoint").await.unwrap(); + drop(store); + drop(cache); + let cache = ManifestCache::new(local, ReadableSize::mb(32), None, true).await; + assert!( + cache + .get("region/00000000000000000003.checkpoint") + .await + .is_some() + ); + // Keep _last_checkpoint, but remove its payload to prove the fallback hit. + remote + .delete("region/00000000000000000003.checkpoint") + .await + .unwrap(); + let mut store = ManifestObjectStore::new( + "region/", + remote, + CompressionType::Gzip, + Default::default(), + Some(cache), + ); + assert_eq!( + Some((3, b"checkpoint".to_vec())), + store.load_last_checkpoint().await.unwrap() + ); + } } diff --git a/src/mito2/src/manifest/storage/checkpoint.rs b/src/mito2/src/manifest/storage/checkpoint.rs index 77b4ff9ac68..9016195ce11 100644 --- a/src/mito2/src/manifest/storage/checkpoint.rs +++ b/src/mito2/src/manifest/storage/checkpoint.rs @@ -16,18 +16,19 @@ use std::collections::HashMap; use std::sync::Arc; use common_datasource::compression::CompressionType; -use common_telemetry::debug; +use common_telemetry::{debug, warn}; use object_store::{ErrorKind, ObjectStore}; use serde::{Deserialize, Serialize}; -use snafu::ResultExt; +use snafu::{OptionExt, ResultExt}; use store_api::ManifestVersion; use crate::cache::manifest_cache::ManifestCache; use crate::error::{ - CompressObjectSnafu, DecompressObjectSnafu, OpenDalSnafu, Result, SerdeJsonSnafu, Utf8Snafu, + CompressObjectSnafu, DecompressObjectSnafu, ManifestCheckpointVanishedSnafu, OpenDalSnafu, + Result, SerdeJsonSnafu, Utf8Snafu, }; use crate::manifest::storage::size_tracker::Tracker; -use crate::manifest::storage::utils::{get_from_cache, put_to_cache, write_and_put_cache}; +use crate::manifest::storage::utils::{get_from_cache_decoded, write_and_put_cache}; use crate::manifest::storage::{ FALL_BACK_COMPRESS_TYPE, LAST_CHECKPOINT_FILE, checkpoint_checksum, checkpoint_file, gen_path, verify_checksum, @@ -102,8 +103,11 @@ impl CheckpointStorage { let path = self.checkpoint_file_path(version); // Try to get from cache first - if let Some(data) = get_from_cache(self.manifest_cache.as_ref(), &path).await { + if let Some(data) = + get_from_cache_decoded(self.manifest_cache.as_ref(), &path, self.compress_type).await + { verify_checksum(&data, metadata.checksum)?; + self.record_cached_checkpoint_size(version, &path).await; return Ok(Some((version, data))); } @@ -112,19 +116,21 @@ impl CheckpointStorage { let checkpoint_data = match self.object_store.read(&path).await { Ok(checkpoint) => { let checkpoint_size = checkpoint.len(); - let decompress_data = - self.compress_type - .decode(checkpoint) - .await - .with_context(|_| DecompressObjectSnafu { - compress_type: self.compress_type, - path: path.clone(), - })?; + let decompress_data = self + .compress_type + .decode(checkpoint.clone()) + .await + .with_context(|_| DecompressObjectSnafu { + compress_type: self.compress_type, + path: path.clone(), + })?; verify_checksum(&decompress_data, metadata.checksum)?; // set the checkpoint size self.size_tracker.record(version, checkpoint_size as u64); // Add to cache - put_to_cache(self.manifest_cache.as_ref(), path, &decompress_data).await; + if let Some(cache) = &self.manifest_cache { + cache.put_file(path, checkpoint.to_vec()).await; + } Ok(Some(decompress_data)) } Err(e) => { @@ -141,10 +147,16 @@ impl CheckpointStorage { ); // Try to get fallback from cache first - if let Some(data) = - get_from_cache(self.manifest_cache.as_ref(), &fall_back_path).await + if let Some(data) = get_from_cache_decoded( + self.manifest_cache.as_ref(), + &fall_back_path, + FALL_BACK_COMPRESS_TYPE, + ) + .await { verify_checksum(&data, metadata.checksum)?; + self.record_cached_checkpoint_size(version, &fall_back_path) + .await; return Ok(Some((version, data))); } @@ -152,7 +164,7 @@ impl CheckpointStorage { Ok(checkpoint) => { let checkpoint_size = checkpoint.len(); let decompress_data = FALL_BACK_COMPRESS_TYPE - .decode(checkpoint) + .decode(checkpoint.clone()) .await .with_context(|_| DecompressObjectSnafu { compress_type: FALL_BACK_COMPRESS_TYPE, @@ -161,12 +173,9 @@ impl CheckpointStorage { verify_checksum(&decompress_data, metadata.checksum)?; self.size_tracker.record(version, checkpoint_size as u64); // Add fallback to cache - put_to_cache( - self.manifest_cache.as_ref(), - fall_back_path, - &decompress_data, - ) - .await; + if let Some(cache) = &self.manifest_cache { + cache.put_file(fall_back_path, checkpoint.to_vec()).await; + } Ok(Some(decompress_data)) } Err(e) if e.kind() == ErrorKind::NotFound => Ok(None), @@ -186,6 +195,52 @@ impl CheckpointStorage { /// Load the latest checkpoint. /// Return manifest version and the raw [RegionCheckpoint](crate::manifest::action::RegionCheckpoint) content if any pub async fn load_last_checkpoint(&mut self) -> Result)>> { + let Some(metadata) = self.read_last_checkpoint_metadata().await? else { + return Ok(None); + }; + self.load_checkpoint(metadata).await + } + + /// Loads the checkpoint that LIST found at `version` with `compress_type`. + /// + /// The checkpoint pointer only provides the checksum, when it points at the same version: the + /// checkpoint task of a stale writer can leave it at an older one. + /// + /// Fails if cleanup removed the checkpoint after the LIST, because the deltas it covered can + /// be gone too. + pub(crate) async fn load_listed_checkpoint( + &self, + version: ManifestVersion, + compress_type: CompressionType, + ) -> Result<(ManifestVersion, Vec)> { + let checksum = self + .read_last_checkpoint_metadata() + .await? + .filter(|metadata| metadata.version == version) + .and_then(|metadata| metadata.checksum); + let mut storage = Self::new( + self.path.clone(), + self.object_store.clone(), + compress_type, + self.manifest_cache.clone(), + self.size_tracker.clone(), + ); + storage + .load_checkpoint(CheckpointMetadata { + size: 0, + version, + checksum, + extend_metadata: HashMap::new(), + }) + .await? + .context(ManifestCheckpointVanishedSnafu { + version, + manifest_dir: &self.path, + }) + } + + /// Reads the small checkpoint pointer without loading its payload. + pub(crate) async fn read_last_checkpoint_metadata(&self) -> Result> { let last_checkpoint_path = self.last_checkpoint_path(); // Fetch from remote object store without cache @@ -206,7 +261,37 @@ impl CheckpointStorage { last_checkpoint_path, checkpoint_metadata ); - self.load_checkpoint(checkpoint_metadata).await + Ok(Some(checkpoint_metadata)) + } + + /// Records the remote object size; accounting failures must not prevent recovery. + async fn record_cached_checkpoint_size(&self, version: ManifestVersion, path: &str) { + match self.object_store.stat(path).await { + Ok(metadata) => self.size_tracker.record(version, metadata.content_length()), + Err(error) => warn!(error; "Failed to account for cached checkpoint {}", path), + } + } + + /// Records stored checkpoint bytes, including the legacy uncompressed path. + pub(crate) async fn record_checkpoint_size(&self, version: ManifestVersion) -> Result<()> { + let path = self.checkpoint_file_path(version); + let metadata = match self.object_store.stat(&path).await { + Ok(metadata) => metadata, + Err(error) + if error.kind() == ErrorKind::NotFound + && self.compress_type != FALL_BACK_COMPRESS_TYPE => + { + let path = gen_path( + &self.path, + &checkpoint_file(version), + FALL_BACK_COMPRESS_TYPE, + ); + self.object_store.stat(&path).await.context(OpenDalSnafu)? + } + Err(error) => return Err(error).context(OpenDalSnafu), + }; + self.size_tracker.record(version, metadata.content_length()); + Ok(()) } /// Save the checkpoint manifest file. @@ -234,7 +319,6 @@ impl CheckpointStorage { data, ) .await?; - self.size_tracker.record(version, checkpoint_size as u64); // Because last checkpoint file only contain size and version, which is tiny, so we don't compress it. let last_checkpoint_path = self.last_checkpoint_path(); @@ -257,6 +341,7 @@ impl CheckpointStorage { .await .context(OpenDalSnafu)?; + self.size_tracker.record(version, checkpoint_size as u64); Ok(()) } } diff --git a/src/mito2/src/manifest/storage/delta.rs b/src/mito2/src/manifest/storage/delta.rs index 8f9962a3c69..8b3a0a1d34a 100644 --- a/src/mito2/src/manifest/storage/delta.rs +++ b/src/mito2/src/manifest/storage/delta.rs @@ -15,10 +15,10 @@ use std::sync::Arc; use common_datasource::compression::CompressionType; -use common_telemetry::debug; +use common_telemetry::{debug, warn}; use futures::TryStreamExt; use futures::future::try_join_all; -use object_store::{Entry, ErrorKind, Lister, ObjectStore}; +use object_store::{Buffer, Entry, ErrorKind, Lister, ObjectStore}; use snafu::{ResultExt, ensure}; use store_api::ManifestVersion; use store_api::storage::RegionId; @@ -27,11 +27,11 @@ use tokio::sync::Semaphore; use crate::cache::manifest_cache::ManifestCache; use crate::error::{ CompressObjectSnafu, DecompressObjectSnafu, InvalidScanIndexSnafu, ManifestDeltaNotFoundSnafu, - OpenDalSnafu, Result, + ManifestVersionConflictSnafu, OpenDalSnafu, Result, }; use crate::manifest::storage::size_tracker::Tracker; use crate::manifest::storage::utils::{ - get_from_cache, put_to_cache, sort_manifests, write_and_put_cache, + get_from_cache_decoded, sort_manifests, write_and_put_cache, }; use crate::manifest::storage::{ FETCH_MANIFEST_PARALLELISM, delta_file, file_compress_type, file_version, gen_path, @@ -206,13 +206,22 @@ impl DeltaStorage { let _permit = semaphore.acquire().await.unwrap(); let cache_key = entry.path(); + let compress_type = file_compress_type(entry.name()); // Try to get from cache first - if let Some(data) = get_from_cache(self.manifest_cache.as_ref(), cache_key).await { + if let Some(data) = get_from_cache_decoded(self.manifest_cache.as_ref(), cache_key, compress_type).await { + let size = entry.metadata().content_length(); + if size > 0 { + self.delta_tracker.record(*v, size); + } else { + match self.object_store.stat(entry.path()).await { + Ok(metadata) => self.delta_tracker.record(*v, metadata.content_length()), + Err(error) => warn!(error; "Failed to account for cached manifest delta {}", entry.path()), + } + } return Ok((*v, data)); } // Fetch from remote object store - let compress_type = file_compress_type(entry.name()); let bytes = match self.object_store.read(entry.path()).await { Ok(bytes) => bytes, Err(error) if error.kind() == ErrorKind::NotFound => { @@ -223,8 +232,9 @@ impl DeltaStorage { } Err(error) => return Err(error).context(OpenDalSnafu), }; + self.delta_tracker.record(*v, bytes.len() as u64); let data = compress_type - .decode(bytes) + .decode(bytes.clone()) .await .context(DecompressObjectSnafu { compress_type, @@ -232,7 +242,9 @@ impl DeltaStorage { })?; // Add to cache - put_to_cache(self.manifest_cache.as_ref(), cache_key.to_string(), &data).await; + if let Some(cache) = &self.manifest_cache { + cache.put_file(cache_key.to_string(), bytes.to_vec()).await; + } Ok((*v, data)) }); @@ -278,6 +290,90 @@ impl DeltaStorage { Ok(()) } + + /// Creates the delta of `version` under its fixed `.json.gz` name, so that only one writer can + /// commit the version. + /// + /// An existing object with the same decoded content is a retry of an earlier write that + /// landed. Any other existing object fails with a version conflict. + pub(crate) async fn save_conditional( + &mut self, + version: ManifestVersion, + bytes: &[u8], + ) -> Result<()> { + let path = gen_path(&self.path, &delta_file(version), CompressionType::Gzip); + // Every writer has to use one object name, so `compress_manifest = false` is honoured + // with gzip level 0, which stores the bytes without compressing them. + let data = if self.compress_type.is_compressed() { + CompressionType::Gzip.encode(bytes).await + } else { + CompressionType::encode_gzip_stored(bytes).await + } + .context(CompressObjectSnafu { + compress_type: CompressionType::Gzip, + path: &path, + })?; + let data = Buffer::from(data); + + let stored_size = match self + .object_store + .write_with(&path, data.clone()) + .if_not_exists(true) + .await + { + Ok(_) => data.len(), + Err(error) + if matches!( + error.kind(), + ErrorKind::AlreadyExists | ErrorKind::ConditionNotMatch + ) => + { + self.ensure_same_delta(version, &path, bytes).await? + } + Err(error) => return Err(error).context(OpenDalSnafu), + }; + + self.delta_tracker.record(version, stored_size as u64); + if let Some(cache) = &self.manifest_cache { + cache.put_file(path, data.to_vec()).await; + } + + Ok(()) + } + + /// Checks that the object at `path` decodes to `bytes`, reading it directly from storage. + /// Returns the size of the stored object. + async fn ensure_same_delta( + &self, + version: ManifestVersion, + path: &str, + bytes: &[u8], + ) -> Result { + let conflict = |reason: String| { + ManifestVersionConflictSnafu { + version, + manifest_dir: &self.path, + reason, + } + .build() + }; + let existing = self + .object_store + .read(path) + .await + .map_err(|e| conflict(format!("cannot read the existing delta: {e}")))?; + let stored_size = existing.len(); + let existing = CompressionType::Gzip + .decode(existing) + .await + .map_err(|e| conflict(format!("cannot decode the existing delta: {e}")))?; + if existing != bytes { + return Err(conflict( + "the existing delta has different content".to_string(), + )); + } + Ok(stored_size) + } } #[cfg(test)] diff --git a/src/mito2/src/manifest/storage/size_tracker.rs b/src/mito2/src/manifest/storage/size_tracker.rs index 184839e74b0..b28f898094d 100644 --- a/src/mito2/src/manifest/storage/size_tracker.rs +++ b/src/mito2/src/manifest/storage/size_tracker.rs @@ -19,6 +19,8 @@ use std::sync::{Arc, RwLock}; use store_api::ManifestVersion; +use crate::metrics::manifest_size::RegionManifestSizeMetric; + /// Key to identify a manifest file. #[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)] pub(crate) enum FileKey { @@ -65,16 +67,24 @@ impl Tracker for NoopTracker { #[derive(Debug, Clone, Default)] pub(crate) struct SizeTracker { - file_sizes: Arc>>, + inventory: Arc>, total_size: Arc, + metric: Option, +} + +#[derive(Debug, Default)] +struct Inventory { + file_sizes: HashMap, + checkpoint_version: Option, } impl SizeTracker { /// Returns a new [SizeTracker]. - pub fn new(total_size: Arc) -> Self { + pub fn new(total_size: Arc, metric: Option) -> Self { Self { - file_sizes: Arc::new(RwLock::new(HashMap::new())), + inventory: Arc::default(), total_size, + metric, } } @@ -92,39 +102,184 @@ impl SizeTracker { } } - /// Records a delta file size. - pub(crate) fn record_delta(&self, version: ManifestVersion, size: u64) { - self.record(FileKey::Delta(version), size); - } - - /// Records a checkpoint file size. - pub(crate) fn record_checkpoint(&self, version: ManifestVersion, size: u64) { - self.record(FileKey::Checkpoint(version), size); - } - - /// Removes a file from tracking. - pub(crate) fn remove(&self, key: &FileKey) { - if let Some(size) = self.file_sizes.write().unwrap().remove(key) { - self.total_size.fetch_sub(size, Ordering::Relaxed); - } - } - /// Returns the total tracked size. pub(crate) fn total(&self) -> u64 { self.total_size.load(Ordering::Relaxed) } - /// Resets all tracking. - pub(crate) fn reset(&self) { - self.file_sizes.write().unwrap().clear(); - self.total_size.store(0, Ordering::Relaxed); + /// Whether this checkpoint's stored size is already known. + pub(crate) fn contains_checkpoint(&self, version: ManifestVersion) -> bool { + self.inventory + .read() + .unwrap() + .file_sizes + .contains_key(&FileKey::Checkpoint(version)) + } + + /// Keeps the latest observed checkpoint and deltas after it, regardless of cleanup. + /// Physical storage may retain older checkpoints and deltas for longer. + pub(crate) fn retain_after(&self, version: ManifestVersion) { + let mut inventory = self.inventory.write().unwrap(); + if inventory + .checkpoint_version + .is_some_and(|current| current > version) + { + return; + } + inventory.checkpoint_version = Some(version); + inventory.file_sizes.retain(|key, _| match key { + FileKey::Delta(v) => *v > version, + FileKey::Checkpoint(v) => *v >= version, + }); + self.total_size + .store(inventory.file_sizes.values().sum(), Ordering::Relaxed); + self.publish_locked(); + } + + /// Called with the inventory write lock held, preserving publication order. + fn publish_locked(&self) { + if let Some(metric) = &self.metric { + metric.publish(self.total_size.load(Ordering::Relaxed)); + } } fn record(&self, key: FileKey, size: u64) { - // Remove the old size if present - if let Some(old_size) = self.file_sizes.write().unwrap().insert(key, size) { + let mut inventory = self.inventory.write().unwrap(); + // Manifest versions are monotonic: deltas at or below the checkpoint watermark + // are superseded, even if a read started before publication finishes afterward. + // Such a late read must not resurrect old entries. + if inventory + .checkpoint_version + .is_some_and(|version| match key { + FileKey::Delta(v) => v <= version, + FileKey::Checkpoint(v) => v < version, + }) + { + return; + } + if let Some(old_size) = inventory.file_sizes.insert(key, size) { self.total_size.fetch_sub(old_size, Ordering::Relaxed); } self.total_size.fetch_add(size, Ordering::Relaxed); + self.publish_locked(); + } +} + +#[cfg(test)] +mod tests { + use store_api::storage::RegionId; + + use super::*; + use crate::metrics::manifest_size::remove_region_manifest_size; + use crate::metrics::manifest_size::tests::manifest_metric_sample; + + #[test] + fn manifest_metric_tracks_mutations_and_activation() { + let id = RegionId::new(u32::MAX, 30); + remove_region_manifest_size(id); + let total = Arc::new(AtomicU64::new(0)); + let metric = RegionManifestSizeMetric::with_threshold(id, 0); + let tracker = SizeTracker::new(total.clone(), Some(metric.clone())); + tracker.manifest_tracker().record(0, 10); + assert_eq!(manifest_metric_sample(id), None); + metric.activate(&total); + assert_eq!(manifest_metric_sample(id), Some(10)); + tracker.manifest_tracker().record(0, 20); + tracker.checkpoint_tracker().record(1, 30); + assert_eq!(manifest_metric_sample(id), Some(tracker.total() as i64)); + assert_eq!(tracker.total(), 50); + tracker.retain_after(1); + assert_eq!(manifest_metric_sample(id), Some(30)); + // Late reads and stale retention cannot resurrect superseded bytes or gauges. + tracker.manifest_tracker().record(0, 999); + tracker.retain_after(0); + assert_eq!(manifest_metric_sample(id), Some(30)); + // An unregistered opener with the same id has no right to publish. + let candidate = RegionManifestSizeMetric::with_threshold(id, 0); + let candidate_tracker = SizeTracker::new(Arc::new(AtomicU64::new(0)), Some(candidate)); + candidate_tracker.manifest_tracker().record(2, 999); + assert_eq!(manifest_metric_sample(id), Some(30)); + tracker.retain_after(2); + assert_eq!(manifest_metric_sample(id), Some(0)); + metric.deactivate(); + remove_region_manifest_size(id); + tracker.manifest_tracker().record(3, 99); + assert_eq!(manifest_metric_sample(id), None); + } + + #[test] + fn manifest_metric_retention_removes_series_below_threshold() { + let id = RegionId::new(u32::MAX, 44); + let total = Arc::new(AtomicU64::new(0)); + let metric = RegionManifestSizeMetric::with_threshold(id, 100); + let tracker = SizeTracker::new(total.clone(), Some(metric.clone())); + metric.activate(&total); + tracker.manifest_tracker().record(0, 80); + assert_eq!(tracker.total(), 80); + assert_eq!(manifest_metric_sample(id), None); + tracker.checkpoint_tracker().record(1, 30); + assert_eq!(manifest_metric_sample(id), Some(110)); + tracker.retain_after(1); + assert_eq!(tracker.total(), 30); + assert_eq!(manifest_metric_sample(id), None); + tracker.manifest_tracker().record(0, 999); + assert_eq!(tracker.total(), 30); + assert_eq!(manifest_metric_sample(id), None); + metric.deactivate(); + } + + #[test] + fn manifest_metric_publishes_with_inventory_locked() { + use crate::metrics::manifest_size::TestHook; + let id = RegionId::new(u32::MAX, 31); + remove_region_manifest_size(id); + let total = Arc::new(AtomicU64::new(0)); + let metric = RegionManifestSizeMetric::with_threshold(id, 0); + let tracker = SizeTracker::new(total.clone(), Some(metric.clone())); + metric.activate(&total); + let sizes = tracker.inventory.clone(); + metric.set_test_hook(Some(TestHook::new(move || { + assert!( + matches!(sizes.try_write(), Err(std::sync::TryLockError::WouldBlock)), + "inventory must remain locked through gauge publication" + ); + }))); + tracker.manifest_tracker().record(0, 10); + tracker.manifest_tracker().record(0, 20); + tracker.checkpoint_tracker().record(1, 30); + tracker.retain_after(1); + tracker.retain_after(2); + assert_eq!(manifest_metric_sample(id), Some(tracker.total() as i64)); + metric.deactivate(); + remove_region_manifest_size(id); + } + + #[test] + fn retain_checkpoint_and_later_deltas() { + let tracker = SizeTracker::default(); + tracker.retain_after(0); + assert_eq!(tracker.total(), 0); + for (key, size) in [ + (FileKey::Delta(1), 10), + (FileKey::Delta(2), 20), + (FileKey::Delta(3), 30), + (FileKey::Checkpoint(1), 40), + (FileKey::Checkpoint(2), 50), + ] { + tracker.record(key, size); + } + tracker.retain_after(2); + assert_eq!(tracker.total(), 80); + assert_eq!( + tracker.inventory.read().unwrap().file_sizes, + HashMap::from([(FileKey::Delta(3), 30), (FileKey::Checkpoint(2), 50)]) + ); + // Late reads and an older retention request cannot roll accounting back. + tracker.record(FileKey::Delta(2), 20); + tracker.record(FileKey::Checkpoint(1), 40); + tracker.retain_after(1); + assert_eq!(tracker.total(), 80); + tracker.record(FileKey::Delta(3), 35); + assert_eq!(tracker.total(), 85); } } diff --git a/src/mito2/src/manifest/storage/utils.rs b/src/mito2/src/manifest/storage/utils.rs index 18fd351acec..9726caf4c1f 100644 --- a/src/mito2/src/manifest/storage/utils.rs +++ b/src/mito2/src/manifest/storage/utils.rs @@ -12,6 +12,8 @@ // See the License for the specific language governing permissions and // limitations under the License. +use common_datasource::compression::CompressionType; +use common_telemetry::debug; use object_store::{Entry, ObjectStore}; use snafu::ResultExt; use store_api::ManifestVersion; @@ -21,19 +23,29 @@ use crate::error::{OpenDalSnafu, Result}; const CHUNK_SIZE: usize = 64 * 1024 * 1024; // 64MB -/// Gets a manifest file from cache. -/// Returns the file data if found in cache, None otherwise. -pub(crate) async fn get_from_cache(cache: Option<&ManifestCache>, key: &str) -> Option> { +/// Gets and decodes the object payload cached under `key`. +/// +/// Older remote fills cached decoded content. If decoding fails, discard the +/// entry and let the caller refill it from object storage. Remote decode and +/// checksum errors are still returned by the caller. +pub(crate) async fn get_from_cache_decoded( + cache: Option<&ManifestCache>, + key: &str, + compress_type: CompressionType, +) -> Option> { let cache = cache?; - cache.get_file(key).await -} - -/// Puts a manifest file into cache. -pub(crate) async fn put_to_cache(cache: Option<&ManifestCache>, key: String, data: &[u8]) { - let Some(cache) = cache else { - return; - }; - cache.put_file(key, data.to_vec()).await + let raw = cache.get_file(key).await?; + match compress_type.decode(raw.as_slice()).await { + Ok(data) => Some(data), + Err(error) => { + debug!( + "Failed to decode cached manifest {}, removing entry: {}", + key, error + ); + cache.remove(key).await; + None + } + } } /// Removes a manifest file from cache. @@ -44,19 +56,15 @@ pub(crate) async fn remove_from_cache(cache: Option<&ManifestCache>, key: &str) cache.remove(key).await } -/// Writes data to object store and puts it into cache. +/// Writes data to object store and caches the same encoded payload. pub(crate) async fn write_and_put_cache( object_store: &ObjectStore, cache: Option<&ManifestCache>, path: &str, data: Vec, ) -> Result<()> { - // Clone data for cache before writing, only if cache is enabled. - let cache_data = if cache.is_some() { - Some(data.clone()) - } else { - None - }; + // Clone only when caching is enabled; retain the owner for the cache write. + let cache_data = cache.map(|cache| (cache, data.clone())); // Write to object store object_store @@ -66,8 +74,8 @@ pub(crate) async fn write_and_put_cache( .context(OpenDalSnafu)?; // Put to cache if we cloned the data - if let Some(data) = cache_data { - put_to_cache(cache, path.to_string(), &data).await; + if let Some((cache, data)) = cache_data { + cache.put_file(path.to_string(), data).await; } Ok(()) diff --git a/src/mito2/src/manifest/tests.rs b/src/mito2/src/manifest/tests.rs index 01ab6e16a0c..577bd08f9da 100644 --- a/src/mito2/src/manifest/tests.rs +++ b/src/mito2/src/manifest/tests.rs @@ -13,4 +13,6 @@ // limitations under the License. mod checkpoint; +mod compatibility; +mod conditional; pub mod utils; diff --git a/src/mito2/src/manifest/tests/checkpoint.rs b/src/mito2/src/manifest/tests/checkpoint.rs index 0fe77502e16..72f4377221f 100644 --- a/src/mito2/src/manifest/tests/checkpoint.rs +++ b/src/mito2/src/manifest/tests/checkpoint.rs @@ -21,8 +21,7 @@ use common_datasource::compression::CompressionType; use common_error::ext::{ErrorExt, RetryHint}; use common_error::status_code::StatusCode; use object_store::layers::mock::{ - BytesRange, Error as MockError, ErrorKind, MockLayer, MockLayerBuilder, OpDelete, - Result as MockResult, RpRead, oio, + Error as MockError, ErrorKind, MockLayerBuilder, OpDelete, Result as MockResult, oio, }; use store_api::storage::{FileId, RegionId}; use strum::IntoEnumIterator; @@ -33,10 +32,14 @@ use crate::manifest::action::{ }; use crate::manifest::manager::RegionManifestManager; use crate::manifest::storage::checkpoint::CheckpointMetadata; -use crate::manifest::storage::is_delta_file; -use crate::manifest::tests::utils::basic_region_metadata; +use crate::manifest::storage::{ + checkpoint_file, delta_file, file_version, gen_path, is_delta_file, +}; +use crate::manifest::tests::utils::{ + basic_region_metadata, fail_manifest_reads_layer, manifest_dir_usage, manifest_recovery_usage, +}; use crate::sst::file::FileMeta; -use crate::test_util::{CheckpointTaskBlocker, TestEnv}; +use crate::test_util::{CheckpointTaskBlocker, TestEnv, nop_action}; async fn build_manager( checkpoint_distance: u64, @@ -76,43 +79,6 @@ async fn reopen_manager( .unwrap() } -fn nop_action() -> RegionMetaActionList { - RegionMetaActionList::new(vec![RegionMetaAction::Edit(RegionEdit { - files_to_add: vec![], - files_to_remove: vec![], - timestamp_ms: None, - compaction_time_window: None, - flushed_entry_id: None, - flushed_sequence: None, - committed_sequence: None, - })]) -} - -struct NotFoundReader; - -impl oio::StreamRead for NotFoundReader { - async fn open(&self, _: BytesRange) -> MockResult<(RpRead, Box)> { - Err(MockError::new( - ErrorKind::NotFound, - "mock listed manifest delta not found", - )) - } -} - -fn fail_manifest_delta_reads_layer() -> MockLayer { - MockLayerBuilder::default() - .reader_factory(Arc::new(|path, _args, inner| { - let file_name = path.rsplit('/').next().unwrap_or(path); - if is_delta_file(file_name) { - Box::new(oio::StreamReader::new(NotFoundReader)) - } else { - inner - } - })) - .build() - .unwrap() -} - #[tokio::test] async fn manager_without_checkpoint() { let (_env, mut manager) = build_manager(0, CompressionType::Uncompressed).await; @@ -332,7 +298,6 @@ async fn generate_checkpoint_with_compression_types( .await .unwrap() .unwrap() - .0 } fn generate_action_lists(num: usize) -> (Vec, Vec) { @@ -480,7 +445,10 @@ async fn manifest_install_manifest_to_with_checkpoint() { for file_id in files.iter() { assert!(another_manager.manifest().files.contains_key(file_id)); } - assert!(another_manager.store().total_manifest_size() > 4000); + assert_eq!( + another_manager.manifest_usage(), + manifest_recovery_usage(env.data_home().join("manifest")).await + ); } #[tokio::test] @@ -525,20 +493,27 @@ async fn test_checkpoint_bypass_in_staging_mode() { assert_eq!(last_version, 16); } -/// A deleter that fails on `close`, simulating the S3 batch-delete failure -/// described in issue #7986. +/// Simulates both a rejected delete and a close failure after eager deletion. struct FailingDeleter { inner: oio::Deleter, - close_calls: Arc, + failure_calls: Arc, + fail_delete: bool, } impl oio::Delete for FailingDeleter { async fn delete(&mut self, path: &str, args: OpDelete) -> MockResult<()> { + if self.fail_delete { + self.failure_calls.fetch_add(1, Ordering::Relaxed); + return Err(MockError::new( + ErrorKind::Unexpected, + "mock rejected delete", + )); + } self.inner.delete(path, args).await } async fn close(&mut self) -> MockResult<()> { - self.close_calls.fetch_add(1, Ordering::Relaxed); + self.failure_calls.fetch_add(1, Ordering::Relaxed); Err(MockError::new( ErrorKind::Unexpected, "mock manifest delete close failure", @@ -546,17 +521,21 @@ impl oio::Delete for FailingDeleter { } } +#[rstest::rstest] +#[case::close_failure(false)] +#[case::delete_failure(true)] #[tokio::test] -async fn checkpoint_advances_and_recovery_works_when_delete_fails() { +async fn manifest_size_ignores_leftover_files_after_failed_delete(#[case] fail_delete: bool) { common_telemetry::init_default_ut_logging(); - let close_calls = Arc::new(AtomicUsize::new(0)); - let factory_close_calls = close_calls.clone(); + let failure_calls = Arc::new(AtomicUsize::new(0)); + let factory_failure_calls = failure_calls.clone(); let mock_layer = MockLayerBuilder::default() .deleter_factory(Arc::new(move |inner| { Box::new(FailingDeleter { inner, - close_calls: factory_close_calls.clone(), + failure_calls: factory_failure_calls.clone(), + fail_delete, }) })) .build() @@ -578,7 +557,7 @@ async fn checkpoint_advances_and_recovery_works_when_delete_fails() { } // The checkpointer must have attempted to delete stale files at least once. - assert!(close_calls.load(Ordering::Relaxed) > 0); + assert!(failure_calls.load(Ordering::Relaxed) > 0); // Despite delete failures, the in-memory checkpoint marker advances so // subsequent `maybe_do_checkpoint` calls compute correct ranges. @@ -593,22 +572,25 @@ async fn checkpoint_advances_and_recovery_works_when_delete_fails() { .expect("checkpoint should be durable"); assert_eq!(last_version, 10); - // Stale deltas below the checkpoint version must still be present because - // the mocked deleter refused them. + // A rejected delete preserves stale files; a close failure after eager FS + // deletion does not. Exclude the current delta from the stale-file count. let file_names: Vec = manager .store() .delta_storage() .get_paths(None, |e| Some(e.name().to_string())) .await .unwrap(); - let stale_delta_count = file_names.iter().filter(|name| is_delta_file(name)).count(); - assert!( - stale_delta_count > 0, - "expected leftover delta files after failed delete, got {:?}", - file_names, + let stale_delta_count = file_names + .iter() + .filter(|name| is_delta_file(name) && file_version(name) < 10) + .count(); + assert_eq!(stale_delta_count > 0, fail_delete, "{file_names:?}"); + assert_eq!( + manager.manifest_usage(), + manifest_recovery_usage(env.data_home().join("manifest")).await ); - // Recovery must succeed despite the leftover deltas. + // Recovery must succeed in both failure modes. manager.stop().await; let reopened = env .create_manifest_manager(CompressionType::Uncompressed, 1, None) @@ -616,13 +598,22 @@ async fn checkpoint_advances_and_recovery_works_when_delete_fails() { .unwrap() .expect("manifest should be recoverable"); assert_eq!(reopened.manifest().manifest_version, 10); + assert_eq!( + manager.manifest_usage(), + manifest_recovery_usage(env.data_home().join("manifest")).await + ); + assert_eq!( + reopened.manifest_usage(), + manifest_recovery_usage(env.data_home().join("manifest")).await + ); + assert!(manifest_dir_usage(env.data_home().join("manifest")).await > reopened.manifest_usage()); } #[tokio::test] async fn open_preserves_listed_delta_not_found_retry_hint() { let env = TestEnv::new() .await - .with_mock_layer(fail_manifest_delta_reads_layer()); + .with_mock_layer(fail_manifest_reads_layer(is_delta_file)); let metadata = Arc::new(basic_region_metadata()); let mut manager = env .create_manifest_manager(CompressionType::Uncompressed, 0, Some(metadata.clone())) @@ -653,7 +644,7 @@ async fn open_preserves_listed_delta_not_found_retry_hint() { async fn install_preserves_listed_delta_not_found_retry_hint() { let env = TestEnv::new() .await - .with_mock_layer(fail_manifest_delta_reads_layer()); + .with_mock_layer(fail_manifest_reads_layer(is_delta_file)); let metadata = Arc::new(basic_region_metadata()); let mut manager = env .create_manifest_manager(CompressionType::Uncompressed, 0, Some(metadata)) @@ -781,3 +772,336 @@ async fn completed_checkpoint_is_reaped_before_scheduling_the_next_one() { assert_eq!(2, manager.checkpointer().last_checkpoint_version()); } + +/// Retention runs inside the checkpoint task, so waiting for task completion also +/// makes logical size accounting observable to the assertions below. +async fn wait_for_manifest_checkpoint(manager: &RegionManifestManager) { + tokio::time::timeout(Duration::from_secs(10), async { + while manager.checkpointer().is_doing_checkpoint() { + tokio::time::sleep(Duration::from_millis(10)).await; + } + }) + .await + .unwrap(); +} + +#[tokio::test] +async fn manifest_size_matches_recovery_bytes_after_open() { + for compress_type in [ + CompressionType::Uncompressed, + CompressionType::Gzip, + CompressionType::Zstd, + ] { + for checkpoint_distance in [0, 3] { + let (env, mut manager) = build_manager(checkpoint_distance, compress_type).await; + for _ in 0..7 { + manager.update(nop_action(), false).await.unwrap(); + wait_for_manifest_checkpoint(&manager).await; + } + let expected = manifest_recovery_usage(env.data_home().join("manifest")).await; + assert_eq!(manager.manifest_usage(), expected); + manager.stop().await; + let reopened = reopen_manager(&env, checkpoint_distance, compress_type).await; + assert_eq!(reopened.manifest_usage(), expected); + } + } +} + +#[rstest::rstest] +#[case::without_checkpoints(0)] +#[case::with_checkpoints(3)] +#[tokio::test] +async fn manifest_size_follower_converges_after_sync(#[case] distance: u64) { + for compression in [ + CompressionType::Uncompressed, + CompressionType::Gzip, + CompressionType::Zstd, + ] { + let (env, mut leader) = build_manager(distance, compression).await; + let mut follower = reopen_manager(&env, distance, compression).await; + for _ in 0..12 { + leader.update(nop_action(), false).await.unwrap(); + leader.wait_for_pending_checkpoint().await; + let expected = manifest_recovery_usage(env.data_home().join("manifest")).await; + assert_eq!(leader.manifest_usage(), expected); + follower + .install_manifest_to(leader.last_version()) + .await + .unwrap(); + assert_eq!(follower.manifest_usage(), expected); + } + // Promotion requires no accounting hook. New leader writes and checkpoints + // continue from the same logical recovery set. + leader.stop().await; + for _ in 0..4 { + follower.update(nop_action(), false).await.unwrap(); + follower.wait_for_pending_checkpoint().await; + assert_eq!( + follower.manifest_usage(), + manifest_recovery_usage(env.data_home().join("manifest")).await + ); + } + } +} + +#[tokio::test] +async fn noop_sync_accounts_for_new_checkpoint_without_listing() { + let lists = Arc::new(AtomicUsize::new(0)); + let counter = lists.clone(); + let layer = MockLayerBuilder::default() + .lister_factory(Arc::new(move |_, _, inner| { + counter.fetch_add(1, Ordering::Relaxed); + inner + })) + .build() + .unwrap(); + let env = TestEnv::new().await.with_mock_layer(layer); + let mut leader = build_manager_with_initial_metadata(&env, 0, CompressionType::Gzip).await; + for _ in 0..3 { + leader.update(nop_action(), false).await.unwrap(); + } + let mut follower = reopen_manager(&env, 0, CompressionType::Gzip).await; + let version = leader.last_version(); + let checkpoint = RegionCheckpoint { + last_version: version, + compacted_actions: 4, + checkpoint: Some(leader.manifest().as_ref().clone()), + }; + leader + .store() + .save_checkpoint(version, &checkpoint.encode().unwrap()) + .await + .unwrap(); + let expected = manifest_recovery_usage(env.data_home().join("manifest")).await; + assert_ne!(follower.manifest_usage(), expected); + let before = lists.load(Ordering::Relaxed); + // Pointer decoding and checkpoint stat failures are diagnostic only. The + // next request must retry the missing accounting rather than prune blindly. + let previous = follower.manifest_usage(); + let directory = env.data_home().join("manifest"); + let pointer = directory.join("_last_checkpoint"); + let bytes = tokio::fs::read(&pointer).await.unwrap(); + tokio::fs::write(&pointer, b"invalid checkpoint metadata") + .await + .unwrap(); + follower.install_manifest_to(version).await.unwrap(); + assert_eq!(follower.manifest_usage(), previous); + tokio::fs::write(&pointer, bytes).await.unwrap(); + let checkpoint_path = directory.join(gen_path( + "", + &checkpoint_file(version), + CompressionType::Gzip, + )); + let hidden = env.data_home().join("temporarily-hidden-checkpoint"); + tokio::fs::rename(&checkpoint_path, &hidden).await.unwrap(); + follower.install_manifest_to(version).await.unwrap(); + assert_eq!(follower.manifest_usage(), previous); + tokio::fs::rename(&hidden, &checkpoint_path).await.unwrap(); + for _ in 0..3 { + follower.install_manifest_to(version).await.unwrap(); + assert_eq!(follower.manifest_usage(), expected); + } + assert_eq!(lists.load(Ordering::Relaxed), before); +} + +#[rstest::rstest] +#[case::listed_sizes(false, false, false)] +#[case::unknown_sizes(true, false, false)] +#[case::fallback_cache(false, true, false)] +#[case::missing_checkpoint(false, false, true)] +#[tokio::test] +async fn manifest_size_warm_cache_matches_recovery_bytes( + #[case] unknown_sizes: bool, + #[case] fallback: bool, + #[case] missing_checkpoint: bool, +) { + use common_base::readable_size::ReadableSize; + use object_store::ObjectStore; + use object_store::services::Fs; + + use crate::cache::manifest_cache::ManifestCache; + use crate::manifest::manager::RegionManifestOptions; + + for compress_type in [ + CompressionType::Uncompressed, + CompressionType::Gzip, + CompressionType::Zstd, + ] { + let stored_compression = if fallback { + CompressionType::Uncompressed + } else { + compress_type + }; + let (env, mut leader) = build_manager(3, stored_compression).await; + for _ in 0..7 { + leader.update(nop_action(), false).await.unwrap(); + wait_for_manifest_checkpoint(&leader).await; + } + let object_store = ObjectStore::new( + Fs::default().root(env.data_home().join("manifest").to_str().unwrap()), + ) + .unwrap(); + let object_store = if unknown_sizes { + object_store.layer( + MockLayerBuilder::default() + .lister_factory(Arc::new(|_, _, inner| Box::new(ZeroSizeLister(inner)))) + .build() + .unwrap(), + ) + } else { + object_store + }; + let local_store = + ObjectStore::new(Fs::default().root(env.data_home().join("cache").to_str().unwrap())) + .unwrap(); + let cache = ManifestCache::new(local_store, ReadableSize::mb(10), None, true).await; + let options = RegionManifestOptions { + manifest_dir: "/".to_string(), + object_store, + compress_type, + checkpoint_distance: 3, + remove_file_options: Default::default(), + manifest_cache: Some(cache.clone()), + conditional_publication: false, + }; + let expected = manifest_recovery_usage(env.data_home().join("manifest")).await; + // First open fills the cache; the second reuses the cached checkpoint and deltas. + for iteration in 0..2 { + if iteration == 1 { + let checkpoint_version = leader.checkpointer().last_checkpoint_version(); + let checkpoint_key = gen_path( + "/", + &checkpoint_file(checkpoint_version), + stored_compression, + ); + assert!( + cache.get(&checkpoint_key).await.is_some(), + "{checkpoint_key}" + ); + for version in checkpoint_version + 1..=leader.manifest().manifest_version { + let delta_key = gen_path("/", &delta_file(version), stored_compression); + assert!( + cache.get(delta_key.trim_start_matches('/')).await.is_some(), + "{delta_key}" + ); + } + } + let checkpoint_path = env.data_home().join("manifest").join(gen_path( + "", + &checkpoint_file(leader.checkpointer().last_checkpoint_version()), + stored_compression, + )); + let hidden = env.data_home().join("temporarily-hidden-checkpoint"); + let missing_size = if missing_checkpoint && iteration == 1 { + let size = tokio::fs::metadata(&checkpoint_path).await.unwrap().len(); + tokio::fs::rename(&checkpoint_path, &hidden).await.unwrap(); + size + } else { + 0 + }; + let mut reopened = RegionManifestManager::open(options.clone(), &Default::default()) + .await + .unwrap() + .unwrap(); + assert_eq!(reopened.manifest_usage(), expected - missing_size); + if missing_size != 0 { + tokio::fs::rename(&hidden, &checkpoint_path).await.unwrap(); + reopened + .install_manifest_to(reopened.last_version()) + .await + .unwrap(); + assert_eq!(reopened.manifest_usage(), expected); + } + reopened.install_last_checkpoint().await.unwrap(); + assert_eq!(reopened.manifest_usage(), expected); + } + } +} + +/// Exercises cache-hit accounting on backends whose LIST omits object sizes. +struct ZeroSizeLister(oio::Lister); + +impl oio::List for ZeroSizeLister { + async fn next(&mut self) -> MockResult> { + let Some(entry) = self.0.next().await? else { + return Ok(None); + }; + let (path, metadata) = entry.into_parts(); + if !metadata.is_file() { + return Ok(Some(oio::Entry::new(&path, metadata))); + } + let mut builder = metadata.into_builder(); + builder.set_file(0); + Ok(Some(oio::Entry::new(&path, builder.build()))) + } +} + +#[rstest::rstest] +#[case(CompressionType::Uncompressed)] +#[case(CompressionType::Gzip)] +#[case(CompressionType::Zstd)] +#[tokio::test] +async fn manifest_cache_write_through_survives_reopen(#[case] compression: CompressionType) { + use common_base::readable_size::ReadableSize; + use common_test_util::temp_dir::create_temp_dir; + use object_store::ObjectStore; + use object_store::services::Fs; + + use crate::cache::manifest_cache::ManifestCache; + use crate::manifest::manager::RegionManifestOptions; + use crate::sst::FormatType; + + let remote_dir = create_temp_dir("manifest-manager-remote"); + let cache_dir = create_temp_dir("manifest-manager-cache"); + let remote = ObjectStore::new(Fs::default().root(remote_dir.path().to_str().unwrap())).unwrap(); + let local = ObjectStore::new(Fs::default().root(cache_dir.path().to_str().unwrap())).unwrap(); + let cache = ManifestCache::new(local.clone(), ReadableSize::mb(32), None, true).await; + // Use a relative prefix, matching production keys and the recovered index. + let mut options = RegionManifestOptions { + manifest_dir: "region/".to_string(), + object_store: remote, + compress_type: compression, + checkpoint_distance: 3, + remove_file_options: Default::default(), + manifest_cache: Some(cache.clone()), + conditional_publication: false, + }; + let mut writer = RegionManifestManager::new( + Arc::new(basic_region_metadata()), + 0, + options.clone(), + FormatType::PrimaryKey, + false, + &Default::default(), + ) + .await + .unwrap(); + for _ in 0..7 { + writer.update(nop_action(), false).await.unwrap(); + wait_for_manifest_checkpoint(&writer).await; + } + let key = gen_path( + "region/", + &checkpoint_file(writer.checkpointer().last_checkpoint_version()), + compression, + ); + assert!(cache.get(&key).await.is_some()); + let version = writer.manifest().manifest_version; + let usage = writer.manifest_usage(); + drop(writer); + drop(cache); + // Release the final old cache handle before recovering a new index. + drop(options.manifest_cache.take()); + let cache = ManifestCache::new(local, ReadableSize::mb(32), None, true).await; + assert!( + cache.get(&key).await.is_some(), + "cache recovery missed {key}" + ); + options.manifest_cache = Some(cache); + let reopened = RegionManifestManager::open(options, &Default::default()) + .await + .unwrap() + .unwrap(); + assert_eq!(version, reopened.manifest().manifest_version); + assert_eq!(usage, reopened.manifest_usage()); +} diff --git a/src/mito2/src/manifest/tests/compatibility.rs b/src/mito2/src/manifest/tests/compatibility.rs new file mode 100644 index 00000000000..2ae562d1474 --- /dev/null +++ b/src/mito2/src/manifest/tests/compatibility.rs @@ -0,0 +1,108 @@ +// 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 serde_json::json; + +use crate::manifest::action::{ + RegionCheckpoint, RegionManifest, RegionMetaAction, RegionMetaActionList, +}; +use crate::sst::file::FileMeta; + +const EDIT: &str = + include_str!("../../../../../tests/compatibility/manifest/table_compaction/legacy-edit.json"); +const MANIFEST: &str = include_str!( + "../../../../../tests/compatibility/manifest/table_compaction/legacy-manifest.json" +); + +#[test] +fn test_file_only_manifest_compatibility() { + let mut json: serde_json::Value = serde_json::from_str(EDIT).unwrap(); + json["actions"][0]["Edit"]["future_core_option"] = json!(true); + let actions = RegionMetaActionList::decode(&serde_json::to_vec(&json).unwrap()).unwrap(); + let RegionMetaAction::Edit(edit) = &actions.actions[0] else { + panic!("expected edit") + }; + assert_eq!( + vec![0, 1], + edit.files_to_add + .iter() + .map(|f| f.level) + .collect::>() + ); + assert_eq!( + vec![7, 8], + edit.files_to_add + .iter() + .map(|f| f.sequence.unwrap().get()) + .collect::>() + ); + assert_eq!(Some(8), edit.committed_sequence); + let encoded = String::from_utf8(actions.encode().unwrap()).unwrap(); + assert!(!encoded.contains("table_compaction") && !encoded.contains("extensions")); + let mut manifest: serde_json::Value = serde_json::from_str(MANIFEST).unwrap(); + manifest["future_core_option"] = json!(true); + let checkpoint = json!({"last_version":12,"compacted_actions":1,"checkpoint":manifest}); + let decoded = RegionCheckpoint::decode(&serde_json::to_vec(&checkpoint).unwrap()).unwrap(); + let manifest = decoded.checkpoint.as_ref().unwrap(); + assert_eq!(12, manifest.manifest_version); + assert_eq!(5, manifest.flushed_entry_id); + assert_eq!(8, manifest.flushed_sequence); + let encoded = String::from_utf8(decoded.encode().unwrap()).unwrap(); + assert!(!encoded.contains("table_compaction") && !encoded.contains("extensions")); + for level in [0, 1, 2, 3, 255] { + let mut file = serde_json::to_value(&edit.files_to_add[0]).unwrap(); + file["level"] = level.into(); + assert_eq!( + crate::sst::file::is_supported_level(level), + serde_json::from_value::(file).is_ok(), + "level {level}" + ); + } +} + +#[rstest::rstest] +#[case("table_compaction")] +#[case("extensions")] +#[test] +fn test_staging_manifest_prototype_state_is_rejected(#[case] field: &str) { + // Staging blobs are parsed as standalone manifests, so they need the same gate + // as checkpoints and deltas instead of silently dropping recovery evidence. + assert!(RegionManifest::decode(MANIFEST.as_bytes()).is_ok()); + let mut manifest: serde_json::Value = serde_json::from_str(MANIFEST).unwrap(); + manifest[field] = json!({"legacy_state": true}); + assert!(matches!( + RegionManifest::decode(&serde_json::to_vec(&manifest).unwrap()), + Err(crate::error::Error::UnsupportedOperation { .. }) + )); +} + +#[rstest::rstest] +#[case("table_compaction")] +#[case("extensions")] +#[test] +fn test_prototype_task_state_is_not_silently_discarded(#[case] field: &str) { + let mut actions: serde_json::Value = serde_json::from_str(EDIT).unwrap(); + actions["actions"][0]["Edit"][field] = json!({"legacy_state":true}); + assert!(matches!( + RegionMetaActionList::decode(&serde_json::to_vec(&actions).unwrap()), + Err(crate::error::Error::UnsupportedOperation { .. }) + )); + let mut manifest: serde_json::Value = serde_json::from_str(MANIFEST).unwrap(); + manifest[field] = json!({"legacy_state":true}); + let checkpoint = json!({"last_version":12,"compacted_actions":1,"checkpoint":manifest}); + assert!(matches!( + RegionCheckpoint::decode(&serde_json::to_vec(&checkpoint).unwrap()), + Err(crate::error::Error::UnsupportedOperation { .. }) + )); +} diff --git a/src/mito2/src/manifest/tests/conditional.rs b/src/mito2/src/manifest/tests/conditional.rs new file mode 100644 index 00000000000..e270d205475 --- /dev/null +++ b/src/mito2/src/manifest/tests/conditional.rs @@ -0,0 +1,372 @@ +// 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. + +//! Tests for manifests published by conditional create. + +use std::sync::Arc; +use std::sync::atomic::{AtomicUsize, Ordering}; + +use common_datasource::compression::CompressionType; +use common_error::ext::ErrorExt; +use common_error::status_code::StatusCode; +use common_test_util::temp_dir::{TempDir, create_temp_dir}; +use object_store::ObjectStore; +use object_store::layers::CapabilityOverrideLayer; +use object_store::layers::mock::{ + Error as MockError, ErrorKind, MockLayer, MockLayerBuilder, Result as MockResult, oio, +}; +use object_store::services::Fs; +use rstest::rstest; +use store_api::ManifestVersion; + +use crate::error::{Error, Result}; +use crate::manifest::manager::{RegionManifestManager, RegionManifestOptions}; +use crate::manifest::storage::{ + LAST_CHECKPOINT_FILE, ManifestObjectStore, delta_file, gen_path, is_checkpoint_file, + is_delta_file, +}; +use crate::manifest::tests::utils::{basic_region_metadata, fail_manifest_reads_layer}; +use crate::sst::FormatType; +use crate::test_util::nop_action; + +fn temp_store() -> (TempDir, ObjectStore) { + let dir = create_temp_dir(""); + let store = ObjectStore::new(Fs::default().root(dir.path().to_str().unwrap())).unwrap(); + (dir, store) +} + +fn options( + store: &ObjectStore, + compress_type: CompressionType, + checkpoint_distance: u64, + conditional_publication: bool, +) -> RegionManifestOptions { + RegionManifestOptions { + manifest_dir: "/".to_string(), + object_store: store.clone(), + compress_type, + checkpoint_distance, + remove_file_options: Default::default(), + manifest_cache: None, + conditional_publication, + } +} + +async fn create_manager(options: RegionManifestOptions) -> RegionManifestManager { + RegionManifestManager::new( + Arc::new(basic_region_metadata()), + 0, + options, + FormatType::PrimaryKey, + false, + &Default::default(), + ) + .await + .unwrap() +} + +async fn open_manager(options: RegionManifestOptions) -> RegionManifestManager { + RegionManifestManager::open(options, &Default::default()) + .await + .unwrap() + .unwrap() +} + +async fn commit(manager: &mut RegionManifestManager) -> Result { + manager + .update_with_verification(nop_action(), false, true, || false) + .await +} + +fn delta_key(version: ManifestVersion) -> String { + gen_path("/", &delta_file(version), CompressionType::Gzip) +} + +fn conditional_store(store: &ObjectStore, compress_type: CompressionType) -> ManifestObjectStore { + ManifestObjectStore::new("/", store.clone(), compress_type, Default::default(), None) + .with_conditional_publication(true) + .unwrap() +} + +/// Returns a store that counts object writes and LIST requests. +fn counting_store() -> (TempDir, ObjectStore, Arc, Arc) { + let (dir, store) = temp_store(); + let writes = Arc::new(AtomicUsize::new(0)); + let lists = Arc::new(AtomicUsize::new(0)); + let (observed_writes, observed_lists) = (writes.clone(), lists.clone()); + let layer = MockLayerBuilder::default() + .writer_factory(Arc::new(move |_, _, inner| { + observed_writes.fetch_add(1, Ordering::Relaxed); + inner + })) + .lister_factory(Arc::new(move |_, _, inner| { + observed_lists.fetch_add(1, Ordering::Relaxed); + inner + })) + .build() + .unwrap(); + (dir, store.layer(layer), writes, lists) +} + +struct FailingLister(ErrorKind); + +impl oio::List for FailingLister { + async fn next(&mut self) -> MockResult> { + Err(MockError::new(self.0, "mock list failure")) + } +} + +fn failing_list_layer(kind: ErrorKind) -> MockLayer { + MockLayerBuilder::default() + .lister_factory(Arc::new(move |_, _, _| Box::new(FailingLister(kind)))) + .build() + .unwrap() +} + +fn assert_conflict(error: &Error) { + assert!( + matches!(error, Error::ManifestVersionConflict { .. }), + "{error:?}" + ); +} + +#[rstest] +#[case::conditional(true)] +#[case::legacy(false)] +#[tokio::test] +async fn test_ordinary_commit_writes_once_without_listing(#[case] conditional: bool) { + let (_dir, store, writes, lists) = counting_store(); + let mut manager = create_manager(options(&store, CompressionType::Gzip, 0, conditional)).await; + writes.store(0, Ordering::Relaxed); + + manager + .update_with_verification(nop_action(), false, true, || !conditional) + .await + .unwrap(); + + assert_eq!(1, writes.load(Ordering::Relaxed)); + assert_eq!(0, lists.load(Ordering::Relaxed)); +} + +#[tokio::test] +async fn test_commit_without_deadline_is_verified() { + let (_dir, store, _writes, lists) = counting_store(); + let mut manager = create_manager(options(&store, CompressionType::Gzip, 1, true)).await; + + manager.update(nop_action(), false).await.unwrap(); + manager.wait_for_pending_checkpoint().await; + + assert_eq!(1, lists.load(Ordering::Relaxed)); + assert_eq!(1, manager.last_version()); + assert_eq!(0, manager.checkpointer().last_checkpoint_version()); +} + +#[rstest] +#[tokio::test] +async fn test_list_error_during_verification_conflicts( + #[values(ErrorKind::Unexpected, ErrorKind::NotFound)] kind: ErrorKind, +) { + let (_dir, store) = temp_store(); + let store = store.layer(failing_list_layer(kind)); + let mut manager = create_manager(options(&store, CompressionType::Gzip, 1, true)).await; + + let error = manager + .update_with_verification(nop_action(), false, true, || true) + .await + .unwrap_err(); + + assert_conflict(&error); + assert!(error.to_string().contains("mock list failure"), "{error}"); + assert_eq!(0, manager.last_version()); + assert_eq!(0, manager.manifest().manifest_version); + assert!(store.exists(&delta_key(1)).await.unwrap()); +} + +#[tokio::test] +async fn test_recovery_treats_missing_directory_as_no_checkpoint() { + let (_dir, store) = temp_store(); + let store = store.layer(failing_list_layer(ErrorKind::NotFound)); + + let checkpoint = conditional_store(&store, CompressionType::Gzip) + .load_last_checkpoint() + .await; + + assert!(checkpoint.unwrap().is_none()); +} + +#[tokio::test] +async fn test_compression_settings_share_one_name() { + let (_dir, store) = temp_store(); + let mut stored = conditional_store(&store, CompressionType::Uncompressed); + let mut compressed = conditional_store(&store, CompressionType::Gzip); + let data = vec![b'a'; 1024]; + + stored.save(1, &data, false).await.unwrap(); + let stored_object = store.read(&delta_key(1)).await.unwrap().to_vec(); + assert!(stored_object.len() > data.len()); + + // A retry by a writer with the other setting succeeds and leaves the object alone. + compressed.save(1, &data, false).await.unwrap(); + let retried_object = store.read(&delta_key(1)).await.unwrap().to_vec(); + assert_eq!(stored_object, retried_object); + assert_eq!(stored_object.len() as u64, compressed.total_manifest_size()); + + compressed.save(2, &data, false).await.unwrap(); + assert!(store.read(&delta_key(2)).await.unwrap().len() < data.len()); + assert_eq!( + vec![(1, data.clone()), (2, data)], + stored.fetch_manifests(1, 3).await.unwrap() + ); +} + +#[rstest] +#[case::different_content(false, false)] +#[case::undecodable(true, false)] +#[case::unreadable(false, true)] +#[tokio::test] +async fn test_existing_delta_conflicts(#[case] undecodable: bool, #[case] unreadable: bool) { + let (_dir, store) = temp_store(); + let existing = if undecodable { + b"not gzip".to_vec() + } else { + let other = b"other".as_slice(); + CompressionType::Gzip.encode(other).await.unwrap() + }; + store.write(&delta_key(1), existing.clone()).await.unwrap(); + let writer_store = if unreadable { + store + .clone() + .layer(fail_manifest_reads_layer(is_delta_file)) + } else { + store.clone() + }; + + let error = conditional_store(&writer_store, CompressionType::Gzip) + .save(1, b"mine", false) + .await + .unwrap_err(); + + assert_conflict(&error); + assert!(error.may_have_persisted_manifest_update()); + assert_eq!(existing, store.read(&delta_key(1)).await.unwrap().to_vec()); +} + +#[tokio::test] +async fn test_failed_write_does_not_skip_version() { + let (_dir, store) = temp_store(); + let mut manager = create_manager(options(&store, CompressionType::Gzip, 0, true)).await; + let key = delta_key(1); + store.write(&key, b"not gzip".to_vec()).await.unwrap(); + + assert_conflict(&commit(&mut manager).await.unwrap_err()); + assert_eq!(0, manager.last_version()); + + store.delete(&key).await.unwrap(); + assert_eq!(1, commit(&mut manager).await.unwrap()); + assert_eq!(1, manager.manifest().manifest_version); +} + +#[tokio::test] +async fn test_stale_checkpoint_pointer_does_not_hide_newer_edits() { + let (_dir, store) = temp_store(); + let pointer = format!("/{LAST_CHECKPOINT_FILE}"); + let region_options = options(&store, CompressionType::Uncompressed, 1, true); + let mut manager = create_manager(region_options.clone()).await; + commit(&mut manager).await.unwrap(); + manager.wait_for_pending_checkpoint().await; + let stale_pointer = store.read(&pointer).await.unwrap().to_vec(); + for _ in 0..2 { + commit(&mut manager).await.unwrap(); + manager.wait_for_pending_checkpoint().await; + } + manager + .update_with_verification(nop_action(), false, false, || false) + .await + .unwrap(); + store.write(&pointer, stale_pointer).await.unwrap(); + + let reopened = open_manager(region_options).await; + + assert_eq!(4, reopened.last_version()); + assert_eq!(3, reopened.checkpointer().last_checkpoint_version()); +} + +#[tokio::test] +async fn test_recovery_fails_when_listed_checkpoint_is_gone() { + let (_dir, store) = temp_store(); + let compress_type = CompressionType::Gzip; + let mut manager = create_manager(options(&store, compress_type, 1, true)).await; + commit(&mut manager).await.unwrap(); + manager.wait_for_pending_checkpoint().await; + let unreadable = store.layer(fail_manifest_reads_layer(is_checkpoint_file)); + + let conditional = options(&unreadable, compress_type, 1, true); + let error = RegionManifestManager::open(conditional, &Default::default()) + .await + .unwrap_err(); + + assert!( + matches!(error, Error::ManifestCheckpointVanished { .. }), + "{error:?}" + ); + assert_eq!(StatusCode::StorageUnavailable, error.status_code()); + assert!(error.retry_hint().is_retryable()); +} + +#[tokio::test] +async fn test_backend_without_conditional_create_is_refused_at_open() { + let (_dir, store) = temp_store(); + let compress_type = CompressionType::Gzip; + create_manager(options(&store, compress_type, 0, false)).await; + let unsupported = store.layer(CapabilityOverrideLayer::new(|mut capability| { + capability.write_with_if_not_exists = false; + capability + })); + + let conditional = options(&unsupported, compress_type, 0, true); + let error = RegionManifestManager::open(conditional, &Default::default()) + .await + .unwrap_err(); + + assert_eq!(StatusCode::Unsupported, error.status_code()); + open_manager(options(&unsupported, compress_type, 0, false)).await; +} + +#[tokio::test] +async fn test_open_writes_nothing() { + let (_dir, store, writes, _lists) = counting_store(); + let region_options = options(&store, CompressionType::Gzip, 0, true); + create_manager(region_options.clone()).await; + writes.store(0, Ordering::Relaxed); + + open_manager(region_options).await; + + assert_eq!(0, writes.load(Ordering::Relaxed)); +} + +#[rstest] +#[tokio::test] +async fn test_deltas_are_readable_across_modes( + #[values(false, true)] written_conditionally: bool, + #[values(CompressionType::Uncompressed, CompressionType::Gzip)] compress_type: CompressionType, +) { + let (_dir, store) = temp_store(); + let mut writer = create_manager(options(&store, compress_type, 0, written_conditionally)).await; + commit(&mut writer).await.unwrap(); + + let mut reader = open_manager(options(&store, compress_type, 0, !written_conditionally)).await; + + assert_eq!(1, reader.last_version()); + assert_eq!(2, commit(&mut reader).await.unwrap()); +} diff --git a/src/mito2/src/manifest/tests/utils.rs b/src/mito2/src/manifest/tests/utils.rs index 8f41f245812..8629d6b413b 100644 --- a/src/mito2/src/manifest/tests/utils.rs +++ b/src/mito2/src/manifest/tests/utils.rs @@ -12,9 +12,16 @@ // See the License for the specific language governing permissions and // limitations under the License. +use std::path::Path; +use std::sync::Arc; + use api::v1::SemanticType; use datatypes::prelude::ConcreteDataType; use datatypes::schema::ColumnSchema; +use object_store::layers::mock::{ + BytesRange, Error as MockError, ErrorKind, MockLayer, MockLayerBuilder, Result as MockResult, + RpRead, oio, +}; use store_api::metadata::{ColumnMetadata, RegionMetadata, RegionMetadataBuilder}; use store_api::storage::RegionId; @@ -48,3 +55,83 @@ pub fn basic_region_metadata() -> RegionMetadata { .primary_key(vec![36]); builder.build().unwrap() } + +/// Returns a layer that fails reads of the files `is_target` selects with `NotFound` and leaves +/// other reads untouched. +pub(crate) fn fail_manifest_reads_layer(is_target: fn(&str) -> bool) -> MockLayer { + MockLayerBuilder::default() + .reader_factory(Arc::new(move |path, _args, inner| { + let file_name = path.rsplit('/').next().unwrap_or(path); + if is_target(file_name) { + Box::new(oio::StreamReader::new(NotFoundReader)) + } else { + inner + } + })) + .build() + .unwrap() +} + +/// Measures stored delta and checkpoint bytes independently of the size tracker. +pub async fn manifest_dir_usage(path: impl AsRef) -> u64 { + let mut entries = tokio::fs::read_dir(path).await.unwrap(); + let mut total = 0; + while let Some(entry) = entries.next_entry().await.unwrap() { + let name = entry.file_name(); + let name = name.to_str().unwrap(); + if crate::manifest::storage::is_delta_file(name) + || crate::manifest::storage::is_checkpoint_file(name) + { + total += entry.metadata().await.unwrap().len(); + } + } + total +} + +/// Independently measures the logical recovery set described by the persisted pointer. +/// Older physical files (including the previous checkpoint) are deliberately excluded. +pub async fn manifest_recovery_usage(path: impl AsRef) -> u64 { + let path = path.as_ref(); + let checkpoint = match tokio::fs::read(path.join("_last_checkpoint")).await { + Ok(bytes) => Some( + serde_json::from_slice::(&bytes).unwrap()["version"] + .as_u64() + .unwrap(), + ), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => None, + Err(error) => panic!("Cannot read checkpoint pointer: {error}"), + }; + let mut entries = tokio::fs::read_dir(path).await.unwrap(); + let mut total = 0; + while let Some(entry) = entries.next_entry().await.unwrap() { + let name = entry.file_name(); + let Some((version, suffix)) = name.to_str().unwrap().split_once('.') else { + continue; + }; + let Ok(version) = version.parse::() else { + continue; + }; + let keep = if suffix.starts_with("json") { + checkpoint.is_none_or(|checkpoint| version > checkpoint) + } else if suffix.starts_with("checkpoint") { + checkpoint == Some(version) + } else { + false + }; + if keep { + total += entry.metadata().await.unwrap().len(); + } + } + total +} + +struct NotFoundReader; + +impl oio::StreamRead for NotFoundReader { + async fn open(&self, _: BytesRange) -> MockResult<(RpRead, Box)> { + Err(MockError::new( + ErrorKind::NotFound, + "mock listed manifest file not found", + )) + } +} diff --git a/src/mito2/src/memtable.rs b/src/mito2/src/memtable.rs index 691ba1c5623..a63423cc92d 100644 --- a/src/mito2/src/memtable.rs +++ b/src/mito2/src/memtable.rs @@ -462,9 +462,8 @@ impl MemtableBuilderProvider { pub(crate) fn new( write_buffer_manager: Option, config: Arc, + compact_dispatcher: Arc, ) -> Self { - let compact_dispatcher = - Arc::new(CompactDispatcher::new(config.max_background_compactions)); let default_bulk_memtable_config = BulkMemtableConfig::default_for_write_buffer_size( config.global_write_buffer_size.as_bytes() as usize, ); @@ -916,7 +915,11 @@ mod tests { #[test] fn test_forced_bulk_memtable_preserves_bulk_config() { - let provider = MemtableBuilderProvider::new(None, Arc::new(MitoConfig::default())); + let provider = MemtableBuilderProvider::new( + None, + Arc::new(MitoConfig::default()), + Arc::new(CompactDispatcher::new(1)), + ); let config = BulkMemtableConfig { merge_threshold: 7, encode_row_threshold: 11, @@ -941,7 +944,11 @@ mod tests { global_write_buffer_size: ReadableSize::gb(8), ..Default::default() }; - let provider = MemtableBuilderProvider::new(None, Arc::new(config)); + let provider = MemtableBuilderProvider::new( + None, + Arc::new(config), + Arc::new(CompactDispatcher::new(1)), + ); let options = RegionOptions::default(); let builder = @@ -956,7 +963,11 @@ mod tests { global_write_buffer_size: ReadableSize::gb(8), ..Default::default() }; - let provider = MemtableBuilderProvider::new(None, Arc::new(config)); + let provider = MemtableBuilderProvider::new( + None, + Arc::new(config), + Arc::new(CompactDispatcher::new(1)), + ); let options = HashMap::from([("memtable.type".to_string(), "bulk".to_string())]); let options = provider @@ -975,7 +986,11 @@ mod tests { global_write_buffer_size: ReadableSize::gb(8), ..Default::default() }; - let provider = MemtableBuilderProvider::new(None, Arc::new(config)); + let provider = MemtableBuilderProvider::new( + None, + Arc::new(config), + Arc::new(CompactDispatcher::new(1)), + ); let options = HashMap::from([ ("memtable.type".to_string(), "bulk".to_string()), ( diff --git a/src/mito2/src/memtable/bulk.rs b/src/mito2/src/memtable/bulk.rs index e1de64c1122..ef7e89171ea 100644 --- a/src/mito2/src/memtable/bulk.rs +++ b/src/mito2/src/memtable/bulk.rs @@ -2054,6 +2054,7 @@ mod tests { data_type: ConcreteDataType::int64_datatype(), inverted_index: false, skipping_index: None, + fulltext_index: None, }], Some(0), )?; diff --git a/src/mito2/src/metrics.rs b/src/mito2/src/metrics.rs index 0fa43ffaea6..18903abc661 100644 --- a/src/mito2/src/metrics.rs +++ b/src/mito2/src/metrics.rs @@ -12,6 +12,8 @@ // See the License for the specific language governing permissions and // limitations under the License. +pub(crate) mod manifest_size; + use std::time::Duration; use lazy_static::lazy_static; @@ -179,6 +181,18 @@ lazy_static! { pub static ref COMPACTION_FAILURE_COUNT: IntCounter = register_int_counter!("greptime_mito_compaction_failure_total", "mito compaction failure total").unwrap(); + /// Prepared compaction units waiting for global admission. + pub static ref COMPACTION_READY_UNITS: IntGauge = register_int_gauge!( + "greptime_mito_compaction_ready_units", "prepared units waiting for global admission" + ).unwrap(); + /// Includes authorized work not yet polled, through task exit and lease release. + pub static ref COMPACTION_ADMITTED_UNITS: IntGauge = register_int_gauge!( + "greptime_mito_compaction_admitted_units", "compaction units holding global execution capacity" + ).unwrap(); + pub static ref COMPACTION_ADMISSION_WAIT: Histogram = register_histogram!( + "greptime_mito_compaction_admission_wait_seconds", "time prepared units wait for admission", + exponential_buckets(0.001, 4.0, 10).unwrap() + ).unwrap(); /// Gauge for inflight compaction tasks: local units and remote jobs. pub static ref INFLIGHT_COMPACTION_COUNT: IntGauge = register_int_gauge!( @@ -853,6 +867,7 @@ pub(crate) fn cache_page_fetch_metrics( #[cfg(test)] mod tests { + use super::*; use common_cache::paged::{PageEvent, PageFetchStats}; diff --git a/src/mito2/src/metrics/manifest_size.rs b/src/mito2/src/metrics/manifest_size.rs new file mode 100644 index 00000000000..0edf73648a4 --- /dev/null +++ b/src/mito2/src/metrics/manifest_size.rs @@ -0,0 +1,371 @@ +// 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::{AtomicU64, Ordering}; +use std::sync::{Arc, LazyLock, Mutex, MutexGuard}; + +use common_base::readable_size::ReadableSize; +use lazy_static::lazy_static; +use prometheus::{IntGaugeVec, register_int_gauge_vec}; +use store_api::metrics::REGION_LABEL; +use store_api::storage::RegionId; + +const MANIFEST_SIZE_METRIC_THRESHOLD_ENV: &str = + "GREPTIME_REGION_MANIFEST_SIZE_METRIC_THRESHOLD_BYTES"; +const DEFAULT_MANIFEST_SIZE_METRIC_THRESHOLD: ReadableSize = ReadableSize::mb(512); + +/// Manifest metrics are enabled independently of the logging query-metrics switch. +/// The process-wide env threshold is read once on first use; changes require a restart. +/// Zero exposes all live regions. +static MANIFEST_SIZE_METRIC_THRESHOLD: LazyLock = LazyLock::new(|| { + let value = std::env::var(MANIFEST_SIZE_METRIC_THRESHOLD_ENV).ok(); + parse_manifest_size_metric_threshold(value.as_deref()) +}); + +fn parse_manifest_size_metric_threshold(value: Option<&str>) -> u64 { + match value { + None => DEFAULT_MANIFEST_SIZE_METRIC_THRESHOLD.as_bytes(), + Some(value) => value.parse().unwrap_or_else(|error| { + common_telemetry::warn!( + "Invalid {MANIFEST_SIZE_METRIC_THRESHOLD_ENV}={value:?}: {error}; expected non-negative bytes; using {DEFAULT_MANIFEST_SIZE_METRIC_THRESHOLD}" + ); + DEFAULT_MANIFEST_SIZE_METRIC_THRESHOLD.as_bytes() + }), + } +} + +lazy_static! { + /// Manifest size of live regions above the threshold, from the region statistics counter. + /// Falling to or below the threshold removes the series; it may reappear later. + /// An absent series does not imply a zero size. + pub(crate) static ref REGION_MANIFEST_SIZE: IntGaugeVec = register_int_gauge_vec!( + "greptime_mito_region_manifest_size_bytes", + "mito region manifest size in bytes", + &[REGION_LABEL] + ).unwrap(); +} + +/// Publishes the manifest size of `region_id`. +fn set_region_manifest_size(region_id: RegionId, size: u64) { + let region_id = region_id.as_u64().to_string(); + REGION_MANIFEST_SIZE + .with_label_values(&[®ion_id]) + .set(size as i64); +} + +/// Removes the per-region series. Idempotent. +pub(crate) fn remove_region_manifest_size(region_id: RegionId) { + let region_id = region_id.as_u64().to_string(); + let _ = REGION_MANIFEST_SIZE.remove_label_values(&[®ion_id]); +} + +/// Shared publishing state of one region's manifest size gauge. +/// +/// Publishing can run on the worker or the background checkpoint task +/// (`common_runtime::spawn_global`). Activation, deactivation and publishing share one +/// mutex, so a late publish can neither resurrect a series removed by +/// close/drop nor overwrite a successor instance's value. +#[derive(Debug)] +struct MetricState { + active: bool, + published: bool, + threshold: u64, + /// Test-only pause point between the active check and the gauge write. + #[cfg(test)] + hook: Option, +} + +#[cfg(test)] +#[derive(Clone)] +pub(crate) struct TestHook(Arc); + +#[cfg(test)] +impl std::fmt::Debug for TestHook { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("TestHook") + } +} + +#[cfg(test)] +impl TestHook { + pub(crate) fn new(hook: impl Fn() + Send + Sync + 'static) -> Self { + Self(Arc::new(hook)) + } + + fn call(&self) { + (self.0)(); + } +} + +/// Publishing state of one region's manifest size gauge. +/// +/// Clones share publication rights. Only the instance in the live map may publish; +/// a replacement revokes the old instance's rights before publishing its size. +#[derive(Debug, Clone)] +pub(crate) struct RegionManifestSizeMetric { + region_id: RegionId, + state: Arc>, +} + +impl RegionManifestSizeMetric { + pub(crate) fn new(region_id: RegionId) -> Self { + Self::with_threshold(region_id, *MANIFEST_SIZE_METRIC_THRESHOLD) + } + + pub(crate) fn with_threshold(region_id: RegionId, threshold: u64) -> Self { + Self { + region_id, + state: Arc::new(Mutex::new(MetricState { + active: false, + published: false, + threshold, + #[cfg(test)] + hook: None, + })), + } + } + + /// Overrides the threshold without changing the process environment. + #[cfg(test)] + pub(crate) fn set_test_threshold(&self, threshold: u64) { + let mut state = self.lock(); + assert!(state.active, "test region must already be live"); + state.threshold = threshold; + } + + /// Installs a pause hook used by the deterministic concurrency tests. + #[cfg(test)] + pub(crate) fn set_test_hook(&self, hook: Option) { + self.lock().hook = hook; + } + + fn lock(&self) -> MutexGuard<'_, MetricState> { + // Metrics must keep working after an unrelated panic poisons the lock. + self.state.lock().unwrap_or_else(|e| e.into_inner()) + } + + /// Activates publication and applies the threshold to the current total. + /// + /// The total is read while holding the lock: a concurrent writer that + /// skipped publishing because the gauge was not active yet cannot be lost. + /// Does not call [`Self::publish`] to avoid taking the lock twice. + pub(crate) fn activate(&self, total: &AtomicU64) { + let mut state = self.lock(); + state.active = true; + let total = total.load(Ordering::Relaxed); + self.write(&mut state, total); + } + + /// Stops publishing. Called when the instance leaves the live map or is replaced. + /// + /// Removes the series before a successor instance can publish. + pub(crate) fn deactivate(&self) { + let mut state = self.lock(); + state.active = false; + if state.published { + remove_region_manifest_size(self.region_id); + state.published = false; + } + } + + /// Writes `total` when active. + /// + /// Callers must hold the size tracker's write lock so a concurrent publisher + /// cannot publish an older total afterwards. + pub(crate) fn publish(&self, total: u64) { + let mut state = self.lock(); + if state.active { + self.write(&mut state, total); + } + } + + /// Writes the gauge. The caller keeps the state lock alive across this call, + /// so the pause hook (and the write) cannot interleave with activate/deactivate. + fn write(&self, state: &mut MetricState, total: u64) { + #[cfg(test)] + if let Some(hook) = &state.hook { + hook.call(); + } + if state.threshold == 0 || total > state.threshold { + set_region_manifest_size(self.region_id, total); + state.published = true; + } else if state.published { + remove_region_manifest_size(self.region_id); + state.published = false; + } + } +} + +#[cfg(test)] +pub(crate) mod tests { + use std::sync::mpsc; + use std::time::Duration; + + use super::*; + + /// Looks up a sample without creating a series. Region ids must be unique per test. + /// + /// Shared by the engine lifecycle, size tracker, and metrics tests. + pub(crate) fn manifest_metric_sample(region_id: RegionId) -> Option { + use prometheus::core::Collector; + let label = region_id.as_u64().to_string(); + let samples: Vec<_> = REGION_MANIFEST_SIZE + .collect() + .into_iter() + .flat_map(|family| family.get_metric().to_vec()) + .filter(|metric| { + metric + .get_label() + .iter() + .any(|pair| pair.name() == REGION_LABEL && pair.value() == label) + }) + .collect(); + assert!(samples.len() <= 1); + samples + .first() + .map(|metric| metric.get_gauge().as_ref().unwrap().value() as i64) + } + + #[test] + fn manifest_metric_threshold_parsing() { + for (input, expected) in [ + (None, 536_870_912), + (Some("536870912"), 536_870_912), + (Some("123"), 123), + (Some("0"), 0), + (Some(""), 536_870_912), + (Some("-1"), 536_870_912), + (Some("512MiB"), 536_870_912), + (Some("18446744073709551616"), 536_870_912), + ] { + assert_eq!(parse_manifest_size_metric_threshold(input), expected); + } + } + + #[rstest::rstest] + #[case::filtered(100, 40)] + #[case::unfiltered(0, 41)] + fn manifest_metric_threshold_transitions(#[case] threshold: u64, #[case] sequence: u32) { + let id = RegionId::new(u32::MAX, sequence); + let metric = RegionManifestSizeMetric::with_threshold(id, threshold); + metric.publish(101); + assert_eq!(manifest_metric_sample(id), None); + metric.activate(&AtomicU64::new(99)); + assert_eq!(manifest_metric_sample(id), (threshold == 0).then_some(99)); + for total in [100, 101, 150, 100, 99, 0, 101] { + metric.publish(total); + let expected = (threshold == 0 || total > threshold).then_some(total as i64); + assert_eq!(manifest_metric_sample(id), expected); + assert_eq!(metric.lock().published, expected.is_some()); + } + metric.deactivate(); + assert_eq!(manifest_metric_sample(id), None); + metric.publish(200); + assert_eq!(manifest_metric_sample(id), None); + } + + #[test] + fn manifest_metric_replacement_below_threshold() { + let id = RegionId::new(u32::MAX, 42); + let old = RegionManifestSizeMetric::with_threshold(id, 100); + old.activate(&AtomicU64::new(200)); + assert_eq!(manifest_metric_sample(id), Some(200)); + let new = RegionManifestSizeMetric::with_threshold(id, 100); + // An inactive opener must not remove the live instance's series. + new.publish(50); + new.deactivate(); + assert_eq!(manifest_metric_sample(id), Some(200)); + old.deactivate(); + new.activate(&AtomicU64::new(50)); + assert_eq!(manifest_metric_sample(id), None); + new.publish(150); + old.publish(300); + old.deactivate(); + assert_eq!(manifest_metric_sample(id), Some(150)); + new.deactivate(); + } + + #[rstest::rstest] + #[case::remove(false, false)] + #[case::replace(true, false)] + #[case::threshold_removal(true, true)] + fn publishing_holds_lock_through_gauge_write( + #[case] replace: bool, + #[case] below_threshold: bool, + ) { + let id = RegionId::new( + u32::MAX, + if below_threshold { + 43 + } else if replace { + 21 + } else { + 20 + }, + ); + remove_region_manifest_size(id); + let old = RegionManifestSizeMetric::with_threshold(id, 5); + old.activate(&AtomicU64::new(10)); + let new = RegionManifestSizeMetric::with_threshold(id, 0); + let (paused_tx, paused_rx) = mpsc::channel(); + let (go_tx, go_rx) = mpsc::channel(); + let go_rx = Mutex::new(go_rx); + old.set_test_hook(Some(TestHook::new(move || { + paused_tx.send(()).unwrap(); + go_rx + .lock() + .unwrap() + .recv_timeout(Duration::from_secs(5)) + .unwrap(); + }))); + let publisher = std::thread::spawn({ + let old = old.clone(); + move || old.publish(if below_threshold { 5 } else { 11 }) + }); + paused_rx.recv_timeout(Duration::from_secs(5)).unwrap(); + // Directly prove the lock is held at the gauge write boundary. This fails + // deterministically if publication releases its guard before writing. + let held = matches!( + old.state.try_lock(), + Err(std::sync::TryLockError::WouldBlock) + ); + let (started_tx, started_rx) = mpsc::channel(); + let successor = std::thread::spawn({ + let old = old.clone(); + let new = new.clone(); + move || { + started_tx.send(()).unwrap(); + old.deactivate(); + if replace { + new.activate(&AtomicU64::new(20)); + } + } + }); + let started = started_rx.recv_timeout(Duration::from_secs(5)); + // Release before assertions so a failing assertion cannot strand threads. + go_tx.send(()).unwrap(); + publisher.join().unwrap(); + successor.join().unwrap(); + assert!( + held, + "publication must hold the descriptor lock through the write" + ); + started.unwrap(); + old.set_test_hook(None); + old.publish(1); + assert_eq!(manifest_metric_sample(id), replace.then_some(20)); + new.deactivate(); + remove_region_manifest_size(id); + } +} diff --git a/src/mito2/src/read/pruner.rs b/src/mito2/src/read/pruner.rs index e4d5bc129e2..075c110f537 100644 --- a/src/mito2/src/read/pruner.rs +++ b/src/mito2/src/read/pruner.rs @@ -227,9 +227,13 @@ struct PrunerInner { /// Positive manifest-prune cache shared across all scan partitions. /// /// SAFETY: cached positives are valid because dynamic filters only tighten; - /// negative decisions are not cached. Reset by `add_partition_ranges()` for + /// dynamic negative decisions are not cached. Reset by `add_partition_ranges()` for /// each fresh batch of partition ranges. manifest_pruned_files: Vec, + // Static predicates and file metadata remain unchanged for this pruner. + static_manifest_kept_files: Vec, + #[cfg(test)] + manifest_check_count: AtomicUsize, /// Keeps file range builders until the query-scoped pruner is dropped. retain_builders: bool, /// Whether FileRanges should execute the reduced-column predicate prefilter. @@ -262,7 +266,23 @@ impl PrunerInner { return true; } let file = &self.stream_ctx.input.files[file_index]; + // Dynamic filters may arrive or tighten after a static keep decision. + let has_dynamic_filters = self + .stream_ctx + .input + .predicate_for_file(file) + .is_some_and(|predicate| !predicate.dyn_filters().is_empty()); + if !has_dynamic_filters + && self.static_manifest_kept_files[file_index].load(Ordering::Relaxed) + { + return false; + } + #[cfg(test)] + self.manifest_check_count.fetch_add(1, Ordering::Relaxed); if !self.stream_ctx.input.can_manifest_prune_file(file) { + if !has_dynamic_filters { + self.static_manifest_kept_files[file_index].store(true, Ordering::Relaxed); + } return false; } if self.manifest_pruned_files[file_index] @@ -348,6 +368,9 @@ impl Pruner { file_entries, stream_ctx, manifest_pruned_files, + static_manifest_kept_files: (0..num_files).map(|_| AtomicBool::new(false)).collect(), + #[cfg(test)] + manifest_check_count: AtomicUsize::new(0), retain_builders, enable_predicate_prefilter, }); @@ -1288,4 +1311,53 @@ mod tests { assert!(marked2); assert_eq!(reader_metrics2.filter_metrics.files_time_range_pruned, 0); } + + #[tokio::test] + async fn cached_builder_checks_late_and_tightened_dynamic_filters() { + use datafusion::physical_plan::expressions::{ + DynamicFilterPhysicalExpr, lit as physical_lit, + }; + + let expressions = [col("ts").gt(lit(ScalarValue::TimestampMillisecond(Some(500), None)))]; + let (_env, pruner) = make_test_pruner_with_predicate(1, 3, &expressions).await; + let ranges = pruner.inner.stream_ctx.partition_ranges(); + pruner.add_partition_ranges(&ranges); + let mut metrics = ReaderMetrics::default(); + assert!(!pruner.inner.try_mark_manifest_pruned(0, &mut metrics)); + cache_builder_if_needed( + &mut pruner.inner.file_entries[0].lock().unwrap(), + &Arc::new(FileRangeBuilder::default()), + &mut metrics, + ); + assert!(!pruner.inner.try_mark_manifest_pruned(0, &mut metrics)); + let dynamic = Arc::new(DynamicFilterPhysicalExpr::new(vec![], physical_lit(true))); + pruner + .inner + .stream_ctx + .input + .predicate + .add_dyn_filters(vec![dynamic.clone()]); + assert!(!pruner.inner.try_mark_manifest_pruned(0, &mut metrics)); + assert_eq!(pruner.inner.manifest_check_count.load(Ordering::Relaxed), 2); + dynamic.update(physical_lit(false)).unwrap(); + assert!(pruner.inner.try_mark_manifest_pruned(0, &mut metrics)); + assert_eq!(pruner.inner.manifest_check_count.load(Ordering::Relaxed), 3); + assert_eq!(metrics.filter_metrics.files_time_range_pruned, 1); + } + + #[tokio::test] + async fn static_manifest_keep_is_reused_without_builder() { + let expressions = [col("ts").gt(lit(ScalarValue::TimestampMillisecond(Some(500), None)))]; + let (_env, pruner) = make_test_pruner_with_predicate(1, 3, &expressions).await; + let ranges = pruner.inner.stream_ctx.partition_ranges(); + pruner.add_partition_ranges(&ranges); + let mut metrics = ReaderMetrics::default(); + for _ in 0..3 { + assert!(!pruner.inner.try_mark_manifest_pruned(0, &mut metrics)); + } + assert_eq!(pruner.inner.manifest_check_count.load(Ordering::Relaxed), 1); + pruner.add_partition_ranges(&ranges); + assert!(!pruner.inner.try_mark_manifest_pruned(0, &mut metrics)); + assert_eq!(pruner.inner.manifest_check_count.load(Ordering::Relaxed), 1); + } } diff --git a/src/mito2/src/read/scan_util.rs b/src/mito2/src/read/scan_util.rs index 945dafb55fe..69366015155 100644 --- a/src/mito2/src/read/scan_util.rs +++ b/src/mito2/src/read/scan_util.rs @@ -1280,7 +1280,10 @@ pub(crate) fn should_split_flat_batches_for_merge( let file_index = index.index - stream_ctx.input.num_memtables(); let file = &stream_ctx.input.files[file_index]; let file_meta = file.meta_ref(); - if file_meta.level == 0 { + // Only L1 compaction outputs guarantee a published, non-overlapping layout. + // L0 and shared inputs may carry short series whose tiny batches + // would otherwise be retained by the merge. + if file_meta.level != 1 { // Short series can leave too many tiny batches retained by the merge. if file_meta.num_series > 0 { if !can_split_series(file_meta.num_rows, file_meta.num_series) { @@ -1656,7 +1659,6 @@ pub fn build_flat_file_range_scan_stream( // Reports metrics. reader_metrics.observe_rows(read_type); - reader_metrics.filter_metrics.observe(); part_metrics.merge_reader_metrics(reader_metrics, per_file_metrics.as_ref()); } } diff --git a/src/mito2/src/read/series_reader.rs b/src/mito2/src/read/series_reader.rs index bddac735d11..fb6086fb41b 100644 --- a/src/mito2/src/read/series_reader.rs +++ b/src/mito2/src/read/series_reader.rs @@ -586,7 +586,6 @@ fn scan_series_file_ranges( } reader_metrics.observe_rows("series_data"); - reader_metrics.filter_metrics.observe(); part_metrics.merge_reader_metrics(&reader_metrics, None); } } diff --git a/src/mito2/src/region.rs b/src/mito2/src/region.rs index c13083fb9b7..c092c7ef4e7 100644 --- a/src/mito2/src/region.rs +++ b/src/mito2/src/region.rs @@ -54,20 +54,22 @@ use tokio::sync::RwLockWriteGuard; pub use utils::*; use crate::access_layer::AccessLayerRef; +use crate::compaction::CompactionStateRef; use crate::engine::region_hook::{PendingManifestHook, RegionHookRef}; use crate::error::{ - FlushableRegionStateSnafu, InvalidPartitionExprSnafu, RegionNotFoundSnafu, RegionStateSnafu, - RegionTruncatedSnafu, Result, UnexpectedSnafu, UpdateManifestSnafu, + FlushableRegionStateSnafu, InvalidPartitionExprSnafu, InvalidRequestSnafu, RegionNotFoundSnafu, + RegionStateSnafu, RegionTruncatedSnafu, Result, UnexpectedSnafu, UpdateManifestSnafu, }; -use crate::lease::Deadline; +use crate::lease::{Deadline, NodeLease}; use crate::manifest::action::{ RegionChange, RegionManifest, RegionMetaAction, RegionMetaActionList, }; use crate::manifest::manager::RegionManifestManager; +use crate::metrics::manifest_size::RegionManifestSizeMetric; use crate::region::version::{VersionControlRef, VersionRef}; use crate::request::{OnFailure, OptionOutputTx}; use crate::series_index::{SeriesIndexVersion, SeriesIndexVersionControl}; -use crate::sst::file::FileMeta; +use crate::sst::file::{self, FileMeta}; use crate::sst::file_purger::FilePurgerRef; use crate::sst::location::{index_file_path, sst_file_path}; use crate::time_provider::TimeProviderRef; @@ -94,7 +96,7 @@ impl RegionUsage { pub enum RegionLeaderState { /// The region is opened and is writable. Writable, - /// The region is in staging mode - writable but no checkpoint/compaction. + /// The region is in staging mode - writable but no checkpoint/compaction/flush. Staging, /// The region is entering staging mode. - write requests will be stalled. EnteringStaging, @@ -154,6 +156,8 @@ pub struct MitoRegion { /// Accessing region id from the version control is inconvenient so /// we also store it here. pub(crate) region_id: RegionId, + /// Live compaction state shared with readers without routing through the worker. + pub(crate) compaction_state: CompactionStateRef, /// Version controller for this region. /// @@ -199,7 +203,7 @@ pub(crate) struct RegionStats { /// The total bytes written to the region. pub(crate) written_bytes: Arc, /// Parquet bytes committed by flushes since this region instance was opened. - pub(crate) flushed_parquet_bytes: AtomicU64, + pub(crate) ingested_parquet_bytes: AtomicU64, /// The total query CPU time of the region in nanoseconds. pub(crate) query_cpu_time: Arc, /// The total scanned bytes of the region. @@ -210,7 +214,7 @@ impl RegionStats { pub(crate) fn new() -> Self { Self { written_bytes: Arc::new(AtomicU64::new(0)), - flushed_parquet_bytes: AtomicU64::new(0), + ingested_parquet_bytes: AtomicU64::new(0), query_cpu_time: Arc::new(AtomicU64::new(0)), query_scanned_bytes: Arc::new(AtomicU64::new(0)), } @@ -254,6 +258,28 @@ impl StagingPartitionInfo { } impl MitoRegion { + /// Publishes the current size when this instance enters the live map. + pub(crate) fn activate_region_manifest_size_metric(&self) { + if let Some(metric) = self.stats.metric() { + metric.activate(&self.stats.total_manifest_size); + } + } + + /// Injects a metric threshold for lifecycle tests without changing process env. + #[cfg(test)] + pub(crate) fn set_manifest_size_metric_threshold(&self, threshold: u64) { + let metric = self.stats.metric().unwrap(); + metric.set_test_threshold(threshold); + metric.publish(self.stats.total_manifest_size()); + } + + /// Revokes publication before removal or replacement of this instance. + pub(crate) fn deactivate_region_manifest_size_metric(&self) { + if let Some(metric) = self.stats.metric() { + metric.deactivate(); + } + } + /// Returns the current immutable series-index snapshot. pub(crate) fn series_index_version(&self) -> Arc { self.series_index_version_control.current() @@ -381,6 +407,17 @@ impl MitoRegion { self.manifest_ctx.state.load() == RegionRoleState::Leader(RegionLeaderState::Staging) } + /// Returns whether the region is in staging mode, counting a staged edit in progress. + pub(crate) fn is_staging_or_staged_edit(&self) -> bool { + match self.manifest_ctx.state.load() { + RegionRoleState::Leader(RegionLeaderState::Staging) => true, + RegionRoleState::Leader(RegionLeaderState::Editing) => { + self.manifest_ctx.staging_partition_info().is_some() + } + _ => false, + } + } + /// Returns whether the region is entering staging mode. pub(crate) fn is_enter_staging(&self) -> bool { self.manifest_ctx.state.load() @@ -501,6 +538,29 @@ impl MitoRegion { ) } + /// Leaves staging without committing it, abandoning a staged edit in progress. + /// + /// You should call this method in the worker loop, which is what restores the state of an + /// edit, and only when [Self::is_staging_or_staged_edit] holds. + pub(crate) fn abort_staging(&self) { + let aborted = self + .manifest_ctx + .state + .fetch_update(|state| { + matches!( + state, + RegionRoleState::Leader( + RegionLeaderState::Staging | RegionLeaderState::Editing + ) + ) + .then_some(RegionRoleState::Leader(RegionLeaderState::Writable)) + }) + .is_ok(); + if aborted { + self.manifest_ctx.clear_staging_partition_info(); + } + } + /// Sets the region role state gracefully. This acquires the manifest write lock. pub(crate) async fn set_role_state_gracefully( &self, @@ -711,6 +771,11 @@ impl MitoRegion { } } + /// Returns the current manifest byte count without computing other region statistics. + pub(crate) fn manifest_size(&self) -> u64 { + self.stats.total_manifest_size() + } + /// Returns the region statistic. pub(crate) fn region_statistic(&self) -> RegionStatistic { let version = self.version(); @@ -722,7 +787,7 @@ impl MitoRegion { let flushed_entry_id = version.flushed_entry_id; let wal_usage = self.estimated_wal_usage(memtable_usage); - let manifest_usage = self.stats.total_manifest_size(); + let manifest_usage = self.manifest_size(); let num_rows = version.ssts.owned_num_rows(self.region_id) + version.memtables.num_rows(); let num_files = version.ssts.owned_num_files(self.region_id); let manifest_version = self.stats.manifest_version(); @@ -759,9 +824,9 @@ impl MitoRegion { data_topic_latest_entry_id: topic_latest_entry_id, metadata_topic_latest_entry_id: topic_latest_entry_id, written_bytes, - flushed_parquet_bytes: self + ingested_parquet_bytes: self .region_stats - .flushed_parquet_bytes + .ingested_parquet_bytes .load(Ordering::Relaxed), query_cpu_time, query_scanned_bytes, @@ -1111,30 +1176,6 @@ impl MitoRegion { Ok(Some(pending)) } - /// Returns the partition expression string for this region. - /// - /// If the region is currently in staging state, this returns the partition expression held in - /// the staging partition field. Otherwise, it returns the partition expression from the primary - /// region metadata (current committed version). - pub fn maybe_staging_partition_expr_str(&self) -> Option { - let is_staging = self.is_staging(); - if is_staging { - let staging_partition_info = self.manifest_ctx.staging_partition_info(); - if staging_partition_info.is_none() { - warn!( - "Staging partition expr is none for region {} in staging state", - self.region_id - ); - } - staging_partition_info - .as_ref() - .and_then(|info| info.partition_expr().map(ToString::to_string)) - } else { - let version = self.version(); - version.metadata.partition_expr.clone() - } - } - pub fn expected_partition_expr_version(&self) -> u64 { if self.is_staging() { self.manifest_ctx @@ -1233,6 +1274,8 @@ pub(crate) struct ManifestContext { /// long the Leader role stays valid. The engine extends it from those leases, and writes check /// it. pub(crate) leader_deadline: Deadline, + /// The clock of [`Self::leader_deadline`]. + node_lease: Arc, /// Partition info of the region in staging mode. /// /// During the staging mode, the region metadata in [`VersionControlRef`] is not updated, @@ -1247,12 +1290,14 @@ impl ManifestContext { manager: RegionManifestManager, state: RegionRoleState, hook: Option, + node_lease: Arc, ) -> Self { ManifestContext { manifest_manager: tokio::sync::RwLock::new(manager), state: AtomicCell::new(state), downgrade_started_at: Mutex::new(Instant::now()), leader_deadline: Deadline::default(), + node_lease, staging_partition_info: Mutex::new(None), hook, } @@ -1476,9 +1521,9 @@ impl ManifestContext { /// Performs a manifest write under a caller-held write lock and returns a /// [`PendingManifestHook`] to [`fire`](PendingManifestHook::fire) after - /// dropping the lock. This is the sole caller of - /// [`RegionManifestManager::update`], so it is the funnel through which all - /// logical manifest writes notify the hook. + /// dropping the lock. It calls + /// [`RegionManifestManager::update_with_verification`] and is the funnel + /// through which all logical manifest writes notify the hook. /// /// Does not validate state or edit applicability — the caller must do so /// while still holding the lock (see `update_manifest_with_state_check` @@ -1490,17 +1535,19 @@ impl ManifestContext { is_staging: bool, ) -> Result { let region_id = manager.manifest().metadata.region_id; - // Clone before `action_list` is moved into `update` so the hook still - // sees what was written. + // Clone before `action_list` is moved into `update_with_verification` + // so the hook still sees what was written. let action_list_for_hook = self.hook.as_ref().map(|_| action_list.clone()); - let version = if !is_staging - && self.state.load() == RegionRoleState::Leader(RegionLeaderState::Downgrading) - { - manager.update_normal_without_checkpoint(action_list).await - } else { - manager.update(action_list, is_staging).await - } - .inspect_err(|e| error!(e; "Failed to update manifest, region_id: {}", region_id))?; + // The final flush of a downgrading leader must not start cleanup after the downgrade + // checkpoint barrier. + let allow_checkpoint = !is_staging + && self.state.load() != RegionRoleState::Leader(RegionLeaderState::Downgrading); + let version = manager + .update_with_verification(action_list, is_staging, allow_checkpoint, || { + self.is_leader_lease_expired() + }) + .await + .inspect_err(|e| error!(e; "Failed to update manifest, region_id: {}", region_id))?; Ok(PendingManifestHook::new( region_id, @@ -1511,6 +1558,11 @@ impl ManifestContext { )) } + /// Returns whether the region's Leader deadline has passed. No deadline counts as passed. + fn is_leader_lease_expired(&self) -> bool { + self.node_lease.now() >= self.leader_deadline.get() + } + /// Updates the manifest using a caller-held write lock, releases the lock, /// and then fires the manifest hook. /// @@ -1564,6 +1616,27 @@ impl ManifestContext { continue; }; + edit.validate_shared_reclassification(manifest.metadata.region_id)?; + // Imports may add shared references, but ordinary edits must not retire + // or overwrite them. Table publication performs its own locked input check. + ensure!( + edit.files_to_remove.iter().all(|file| { + file.level != file::LEVEL_SHARED + && manifest + .files + .get(&file.file_id) + .is_none_or(|current| current.level != file::LEVEL_SHARED) + }) && edit.files_to_add.iter().all(|file| { + manifest.files.get(&file.file_id).is_none_or(|current| { + current.level != file::LEVEL_SHARED || current == file + }) + }), + InvalidRequestSnafu { + region_id: manifest.metadata.region_id, + reason: "Ordinary manifest edits cannot modify shared SSTs", + } + ); + // Checks whether the region is truncated. let Some(truncated_entry_id) = manifest.truncated_entry_id else { continue; @@ -1737,7 +1810,18 @@ impl ManifestContext { region_id, state ), Err(state) => { - if state != RegionRoleState::Leader(RegionLeaderState::Writable) { + // These states already have the leader role; keep their ongoing operation. + if !matches!( + state, + RegionRoleState::Leader( + RegionLeaderState::Writable + | RegionLeaderState::Altering + | RegionLeaderState::Dropping + | RegionLeaderState::Truncating + | RegionLeaderState::Editing + | RegionLeaderState::EnteringStaging + ) + ) { warn!( "Failed to convert region {} to leader, current role state: {:?}", region_id, state @@ -2058,12 +2142,25 @@ pub(crate) type CatchupRegionsRef = Arc; /// Manifest stats. #[derive(Default, Debug, Clone)] pub struct ManifestStats { + metric: Option, pub(crate) total_manifest_size: Arc, pub(crate) manifest_version: Arc, pub(crate) file_removed_cnt: Arc, } impl ManifestStats { + /// Creates an inactive descriptor; opening a region does not publish a series. + pub(crate) fn with_region_metrics(region_id: RegionId) -> Self { + Self { + metric: Some(RegionManifestSizeMetric::new(region_id)), + ..Default::default() + } + } + + pub(crate) fn metric(&self) -> Option<&RegionManifestSizeMetric> { + self.metric.as_ref() + } + fn total_manifest_size(&self) -> u64 { self.total_manifest_size.load(Ordering::Relaxed) } @@ -2287,6 +2384,7 @@ mod tests { checkpoint_distance: 10, remove_file_options: Default::default(), manifest_cache: None, + conditional_publication: false, }, FormatType::PrimaryKey, false, @@ -2299,10 +2397,12 @@ mod tests { manager, RegionRoleState::Leader(RegionLeaderState::Writable), None, + Default::default(), )); MitoRegion { region_id: metadata.region_id, + compaction_state: Default::default(), version_control, series_index_version_control: Default::default(), series_index_store: None, @@ -2841,6 +2941,7 @@ mod tests { checkpoint_distance: 10, remove_file_options: Default::default(), manifest_cache: None, + conditional_publication: false, }, FormatType::PrimaryKey, false, @@ -2852,6 +2953,7 @@ mod tests { manager, RegionRoleState::Leader(RegionLeaderState::Staging), None, + Default::default(), )) }; @@ -2910,6 +3012,7 @@ mod tests { checkpoint_distance: 10, remove_file_options: Default::default(), manifest_cache: None, + conditional_publication: false, }, FormatType::PrimaryKey, false, @@ -2922,10 +3025,12 @@ mod tests { manager, RegionRoleState::Leader(RegionLeaderState::Writable), None, + Default::default(), )); let region = MitoRegion { region_id: metadata.region_id, + compaction_state: Default::default(), version_control, series_index_version_control: Default::default(), series_index_store: None, diff --git a/src/mito2/src/region/opener.rs b/src/mito2/src/region/opener.rs index 30eb6b99cbc..85881028ab9 100644 --- a/src/mito2/src/region/opener.rs +++ b/src/mito2/src/region/opener.rs @@ -55,6 +55,7 @@ use crate::error::{ DataTypeMismatchSnafu, EmptyRegionDirSnafu, InvalidMetadataSnafu, InvalidRegionOptionsSnafu, ObjectStoreNotFoundSnafu, RegionCorruptedSnafu, Result, StaleLogEntrySnafu, }; +use crate::lease::NodeLease; use crate::manifest::action::RegionManifest; use crate::manifest::manager::{RegionManifestManager, RegionManifestOptions}; use crate::memtable::bulk::part::BulkPart; @@ -157,6 +158,7 @@ pub(crate) struct RegionOpener { options: Option, cache_manager: Option, skip_wal_replay: bool, + node_lease: Arc, puffin_manager_factory: PuffinManagerFactory, intermediate_manager: IntermediateManager, time_provider: TimeProviderRef, @@ -178,6 +180,7 @@ impl RegionOpener { region_id: RegionId, table_dir: &str, path_type: PathType, + node_lease: Arc, memtable_builder_provider: MemtableBuilderProvider, object_store_manager: ObjectStoreManagerRef, purge_scheduler: SchedulerRef, @@ -198,10 +201,11 @@ impl RegionOpener { options: None, cache_manager: None, skip_wal_replay: false, + node_lease, puffin_manager_factory, intermediate_manager, time_provider, - stats: Default::default(), + stats: ManifestStats::with_region_metrics(region_id), wal_entry_reader: None, replay_checkpoint: None, file_ref_manager, @@ -386,7 +390,10 @@ impl RegionOpener { wal.start_region_history(region_id, &provider)?; // Create a manifest manager for this region and writes regions to the manifest file. let mut region_manifest_options = - RegionManifestOptions::new(config, ®ion_dir, &object_store); + RegionManifestOptions::new(config, ®ion_dir, &object_store) + .with_conditional_publication( + options.requires_conditional_manifest_publication(self.node_lease.is_enabled()), + ); // Set manifest cache if available region_manifest_options.manifest_cache = self .cache_manager @@ -424,17 +431,21 @@ impl RegionOpener { .flushed_entry_id(flushed_entry_id) .build(); let version_control = Arc::new(VersionControl::new(version)); - let access_layer = Arc::new(AccessLayer::new( - self.table_dir.clone(), - self.path_type, - object_store, - self.puffin_manager_factory, - self.intermediate_manager, - )); + let access_layer = Arc::new( + AccessLayer::new( + self.table_dir.clone(), + self.path_type, + object_store, + self.puffin_manager_factory, + self.intermediate_manager, + ) + .with_file_protection(self.hook.clone()), + ); let now = self.time_provider.current_time_millis(); Ok(Arc::new(MitoRegion { region_id, + compaction_state: Default::default(), version_control, series_index_version_control: Default::default(), series_index_store: self.series_index_store.clone(), @@ -444,6 +455,7 @@ impl RegionOpener { manifest_manager, RegionRoleState::Leader(RegionLeaderState::Writable), self.hook.clone(), + self.node_lease.clone(), )), file_purger: create_file_purger( config.gc.enable, @@ -513,7 +525,11 @@ impl RegionOpener { let mut region_options = self.options.as_ref().unwrap().clone(); let object_storage = get_object_store(®ion_options.storage, &self.object_store_manager)?; let mut region_manifest_options = - RegionManifestOptions::new(config, &self.region_dir(), &object_storage); + RegionManifestOptions::new(config, &self.region_dir(), &object_storage) + .with_conditional_publication( + region_options + .requires_conditional_manifest_publication(self.node_lease.is_enabled()), + ); // Set manifest cache if available region_manifest_options.manifest_cache = self .cache_manager @@ -558,13 +574,16 @@ impl RegionOpener { region_id, self.table_dir, self.options ); - let access_layer = Arc::new(AccessLayer::new( - self.table_dir.clone(), - self.path_type, - object_store, - self.puffin_manager_factory.clone(), - self.intermediate_manager.clone(), - )); + let access_layer = Arc::new( + AccessLayer::new( + self.table_dir.clone(), + self.path_type, + object_store, + self.puffin_manager_factory.clone(), + self.intermediate_manager.clone(), + ) + .with_file_protection(self.hook.clone()), + ); let file_purger = create_file_purger( config.gc.enable, self.path_type, @@ -682,6 +701,7 @@ impl RegionOpener { let region = MitoRegion { region_id: self.region_id, + compaction_state: Default::default(), version_control: version_control.clone(), series_index_version_control, series_index_store: self.series_index_store.clone(), @@ -691,6 +711,7 @@ impl RegionOpener { manifest_manager, RegionRoleState::Follower, self.hook.clone(), + self.node_lease.clone(), )), file_purger, provider: provider.clone(), @@ -1094,7 +1115,7 @@ impl RegionLoadCacheTask { for level in version.ssts.levels() { for file_handle in level.files.values() { let file_meta = file_handle.meta_ref(); - if file_meta.exists_index() { + if file_meta.has_downloadable_index() { let puffin_key = IndexKey::new( file_meta.region_id, file_meta.file_id, @@ -1726,6 +1747,95 @@ mod tests { parquet_bytes } + #[rstest::rstest] + #[case::known_size(7, true)] + #[case::unknown_size(0, false)] + #[tokio::test] + async fn test_preload_column_only_index( + #[case] index_file_size: u64, + #[case] expected_cached: bool, + ) { + use store_api::region_engine::RegionEngine; + use store_api::region_request::RegionRequest; + + use crate::manifest::action::RegionEdit; + use crate::sst::file::{ColumnIndexMetadata, IndexType}; + use crate::test_util::CreateRequestBuilder; + + let mut env = TestEnv::new().await; + let engine = env.create_engine(Default::default()).await; + let region_id = RegionId::new(1, 1); + engine + .handle_request( + region_id, + RegionRequest::Create(CreateRequestBuilder::new().build()), + ) + .await + .unwrap(); + let region = engine.get_region(region_id).unwrap(); + let write_cache = env + .create_write_cache( + ObjectStore::new(Memory::default()).unwrap(), + ReadableSize::mb(1), + ) + .await; + let meta = FileMeta { + region_id, + file_id: FileId::random(), + index_file_size, + index_version: 3, + indexes: vec![ColumnIndexMetadata { + column_id: 0, + created_indexes: smallvec::smallvec![IndexType::HllIndex], + ..Default::default() + }], + ..Default::default() + }; + assert!(meta.available_indexes.is_empty()); + assert!(meta.exists_index()); + assert_eq!(meta.index_version(), Some(3)); + let key = IndexKey::new(region_id, meta.file_id, FileType::Puffin(3)); + let path = crate::sst::location::index_file_path( + region.access_layer.table_dir(), + meta.index_id(), + region.access_layer.path_type(), + ); + region + .access_layer + .object_store() + .write(&path, b"payload".as_slice()) + .await + .unwrap(); + region.version_control.apply_edit( + Some(RegionEdit { + files_to_add: vec![meta], + ..Default::default() + }), + &[], + region.file_purger.clone(), + ); + + super::RegionLoadCacheTask::new(region) + .fill_cache(&write_cache.file_cache()) + .await; + let file_cache = write_cache.file_cache(); + assert_eq!(file_cache.contains_key(&key), expected_cached); + let cached_path = file_cache.cache_file_path(key); + if expected_cached { + assert_eq!( + file_cache + .local_store() + .read(&cached_path) + .await + .unwrap() + .to_vec(), + b"payload" + ); + } else { + assert!(!file_cache.local_store().exists(&cached_path).await.unwrap()); + } + } + #[tokio::test] async fn test_preload_parquet_meta_cache_uses_file_cache() { let env = TestEnv::new().await; diff --git a/src/mito2/src/region/options.rs b/src/mito2/src/region/options.rs index 85cb79928cd..ca696137f40 100644 --- a/src/mito2/src/region/options.rs +++ b/src/mito2/src/region/options.rs @@ -265,6 +265,12 @@ impl RegionOptions { pub fn primary_key_encoding(&self) -> PrimaryKeyEncoding { self.primary_key_encoding.unwrap_or_default() } + + /// Returns whether the manifest of this region is published conditionally, which it is when + /// the region's writes require a lease and its WAL is the object store WAL. + pub(crate) fn requires_conditional_manifest_publication(&self, lease_enabled: bool) -> bool { + lease_enabled && matches!(self.wal_options, WalOptions::ObjectStore(_)) + } } impl RegionOptions { @@ -696,7 +702,7 @@ fn validate_enum_options( mod tests { use common_error::ext::ErrorExt; use common_error::status_code::StatusCode; - use common_wal::options::KafkaWalOptions; + use common_wal::options::{KafkaWalOptions, ObjectStoreWalOptions}; use store_api::mito_engine_options::{ EXPERIMENTAL_SST_FLOAT_FIELD_ENCODING, SKIP_WAL_KEY, WRITE_BUFFER_SIZE_KEY, }; @@ -717,6 +723,21 @@ mod tests { assert_eq!(RegionOptions::default(), options); } + #[test] + fn test_conditional_manifest_requires_lease_and_object_store_wal() { + let options = |wal_options| RegionOptions { + wal_options, + ..Default::default() + }; + let object_store_wal = options(WalOptions::ObjectStore(ObjectStoreWalOptions::new( + "wal".to_string(), + ))); + + assert!(object_store_wal.requires_conditional_manifest_publication(true)); + assert!(!object_store_wal.requires_conditional_manifest_publication(false)); + assert!(!options(WalOptions::RaftEngine).requires_conditional_manifest_publication(true)); + } + #[test] fn test_float_field_encoding_defaults_and_parses() { let options = RegionOptions::try_from_options(RegionId::new(0, 0), &make_map(&[])).unwrap(); diff --git a/src/mito2/src/region/utils.rs b/src/mito2/src/region/utils.rs index 7dfaad72aa7..496668cfce0 100644 --- a/src/mito2/src/region/utils.rs +++ b/src/mito2/src/region/utils.rs @@ -39,14 +39,20 @@ use crate::sst::location; pub struct RegionMetadataLoader { config: Arc, object_store_manager: ObjectStoreManagerRef, + lease_enabled: bool, } impl RegionMetadataLoader { /// Creates a new `RegionMetadataLoader`. - pub fn new(config: Arc, object_store_manager: ObjectStoreManagerRef) -> Self { + pub fn new( + config: Arc, + object_store_manager: ObjectStoreManagerRef, + lease_enabled: bool, + ) -> Self { Self { config, object_store_manager, + lease_enabled, } } @@ -56,9 +62,7 @@ impl RegionMetadataLoader { region_dir: &str, region_options: &RegionOptions, ) -> Result> { - let manifest = self - .load_manifest(region_dir, ®ion_options.storage) - .await?; + let manifest = self.load_manifest(region_dir, region_options).await?; Ok(manifest.map(|m| m.metadata.clone())) } @@ -66,11 +70,14 @@ impl RegionMetadataLoader { pub async fn load_manifest( &self, region_dir: &str, - storage: &Option, + region_options: &RegionOptions, ) -> Result>> { - let object_store = get_object_store(storage, &self.object_store_manager)?; + let object_store = get_object_store(®ion_options.storage, &self.object_store_manager)?; let region_manifest_options = - RegionManifestOptions::new(&self.config, region_dir, &object_store); + RegionManifestOptions::new(&self.config, region_dir, &object_store) + .with_conditional_publication( + region_options.requires_conditional_manifest_publication(self.lease_enabled), + ); let Some(manifest_manager) = RegionManifestManager::open(region_manifest_options, &Default::default()).await? else { diff --git a/src/mito2/src/request.rs b/src/mito2/src/request.rs index 9c0178710f1..123133d4be0 100644 --- a/src/mito2/src/request.rs +++ b/src/mito2/src/request.rs @@ -793,6 +793,13 @@ pub(crate) enum WorkerRequest { sender: Sender, }, + /// Cancels one live compaction on its owning worker. + CancelCompaction { + region_id: RegionId, + task_id: String, + sender: OptionOutputTx, + }, + /// Notify a worker to stop. Stop, @@ -924,6 +931,11 @@ impl WorkerRequest { sender: sender.into(), request: DdlRequest::Compact(v), }), + RegionRequest::CancelCompaction(v) => WorkerRequest::CancelCompaction { + region_id, + task_id: v.task_id, + sender: sender.into(), + }, RegionRequest::BuildIndex(v) => WorkerRequest::Ddl(SenderDdlRequest { region_id, sender: sender.into(), @@ -1152,8 +1164,6 @@ pub(crate) struct FlushFinished { pub(crate) edit: RegionEdit, /// Memtables to remove. pub(crate) memtables_to_remove: SmallVec<[MemtableId; 2]>, - /// Whether the region is in staging mode. - pub(crate) is_staging: bool, } impl FlushFinished { @@ -1372,6 +1382,9 @@ pub(crate) struct RegionEditRequest { pub(crate) preload_sst_cache: bool, /// The waiters that are waiting for this region edit's result. pub(crate) waiters: Waiters, + /// The partition expression of the staging this edit belongs to, if any. + /// The edit must not run unless the region is staging for that expression. + pub(crate) staging_partition_expr: Option, } impl RegionEditRequest { @@ -1386,8 +1399,15 @@ impl RegionEditRequest { edit, preload_sst_cache, waiters: Waiters::one(waiter), + staging_partition_expr: None, } } + + /// Binds the edit to the staging for `partition_expr`. + pub(crate) fn for_staging(mut self, partition_expr: String) -> Self { + self.staging_partition_expr = Some(partition_expr); + self + } } /// Notifies the regin the result of editing region. @@ -1395,6 +1415,8 @@ impl RegionEditRequest { pub(crate) struct RegionEditResult { /// Region id. pub(crate) region_id: RegionId, + /// Prevents a delayed completion from mutating a reopened region with the same id. + pub(crate) origin: MitoRegionRef, /// Result waiters. pub(crate) waiters: Waiters, /// Region edit to apply. @@ -1467,6 +1489,33 @@ mod tests { use crate::error::Error; use crate::test_util::ts_ms_value; + #[tokio::test] + async fn test_cancel_compaction_is_worker_control_request() { + let region_id = RegionId::new(7, 3); + let (request, receiver) = WorkerRequest::try_from_region_request( + region_id, + RegionRequest::CancelCompaction( + store_api::region_request::RegionCancelCompactionRequest { + task_id: "task-1".to_string(), + }, + ), + None, + ) + .unwrap(); + let WorkerRequest::CancelCompaction { + region_id: actual_region_id, + task_id, + sender, + } = request + else { + panic!("cancellation must bypass the DDL queue"); + }; + assert_eq!(actual_region_id, region_id); + assert_eq!(task_id, "task-1"); + sender.send(Ok(1)); + assert_eq!(receiver.await.unwrap().unwrap(), 1); + } + fn new_column_schema( name: &str, data_type: ColumnDataType, diff --git a/src/mito2/src/schedule.rs b/src/mito2/src/schedule.rs index a4f9cb60522..e0b91e1ad59 100644 --- a/src/mito2/src/schedule.rs +++ b/src/mito2/src/schedule.rs @@ -12,6 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. +use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Mutex}; use common_base::cancellation::CancellationHandle; @@ -24,6 +25,7 @@ pub mod scheduler; pub(crate) struct CancellableTaskState { cancel_handle: Arc, commit_started: Arc>, + started: Arc, } impl CancellableTaskState { @@ -31,9 +33,20 @@ impl CancellableTaskState { Self { cancel_handle: Arc::new(CancellationHandle::default()), commit_started: Arc::new(Mutex::new(false)), + started: Arc::new(AtomicBool::new(false)), } } + /// Records that the executor has started this task. + pub(crate) fn mark_started(&self) { + self.started.store(true, Ordering::Relaxed); + } + + /// Returns whether the executor has started this task. + pub(crate) fn started(&self) -> bool { + self.started.load(Ordering::Relaxed) + } + pub(crate) fn cancel_handle(&self) -> Arc { self.cancel_handle.clone() } diff --git a/src/mito2/src/sst/file.rs b/src/mito2/src/sst/file.rs index 337d22699ae..ba29db1736f 100644 --- a/src/mito2/src/sst/file.rs +++ b/src/mito2/src/sst/file.rs @@ -114,8 +114,38 @@ where /// Type to store SST level. pub type Level = u8; -/// Maximum level of SSTs. -pub const MAX_LEVEL: Level = 2; +/// Shared inputs owned by table compaction, not a deeper region-compaction level. +/// This sentinel is persisted; L0=0 and L1=1 retain their original meanings, and +/// taking the maximum value keeps every future ordinary level below it. +pub const LEVEL_SHARED: Level = Level::MAX; +/// Storage slot that holds shared references inside the fixed level array. +pub(crate) const SHARED_LEVEL_SLOT: usize = 2; +/// Number of level storage slots: L0, L1 and the shared slot. +pub(crate) const LEVEL_SLOT_COUNT: usize = SHARED_LEVEL_SLOT + 1; + +/// Maps a persisted level to its storage slot, if the level is representable. +pub(crate) const fn level_slot(level: Level) -> Option { + match level { + 0 | 1 => Some(level as usize), + LEVEL_SHARED => Some(SHARED_LEVEL_SLOT), + _ => None, + } +} + +pub(crate) const fn is_supported_level(level: Level) -> bool { + level <= 1 || (cfg!(feature = "enterprise") && level == LEVEL_SHARED) +} + +fn deserialize_level<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Result { + let level = Level::deserialize(deserializer)?; + if !is_supported_level(level) { + return Err(serde::de::Error::custom(format!( + "Unsupported SST level {level}" + ))); + } + Ok(level) +} + /// Type to store index types for a column. pub type IndexTypes = SmallVec<[IndexType; 4]>; @@ -213,6 +243,7 @@ pub struct FileMeta { /// data in the SST. pub time_range: FileTimeRange, /// SST level of the file. + #[serde(deserialize_with = "deserialize_level")] pub level: Level, /// Size of the file. pub file_size: u64, @@ -335,7 +366,7 @@ impl Debug for FileMeta { "max_row_group_uncompressed_size", &ReadableSize(self.max_row_group_uncompressed_size), ); - if !self.available_indexes.is_empty() { + if self.exists_index() { debug_struct .field("available_indexes", &self.available_indexes) .field("indexes", &self.indexes) @@ -383,6 +414,12 @@ pub enum IndexType { BloomFilterIndex, /// Retained for manifests written with the removed experimental vector index. VectorIndex, + /// HyperLogLog distinct-value estimate. + HllIndex, + /// KLL rank estimate. + KllIndex, + /// Misra–Gries frequency estimate. + MgIndex, } /// Metadata of indexes created for a specific column in an SST file. @@ -413,6 +450,18 @@ fn is_zero(version: &u8) -> bool { } impl FileMeta { + /// Returns whether this file's row sequences are trusted in the target region. + /// + /// Foreign files use their target-local sequence barrier; local files require + /// the preserve marker because their physical sequences belong to this region. + pub(crate) fn is_effective_target_sequence_trusted(&self, target_region_id: RegionId) -> bool { + if self.region_id != target_region_id { + self.sequence.is_some() + } else { + self.preserve_row_sequence + } + } + /// Returns the primary key range if both min and max are present. pub fn primary_key_range(&self) -> Option<(Bytes, Bytes)> { match (&self.primary_key_min, &self.primary_key_max) { @@ -423,6 +472,16 @@ impl FileMeta { pub fn exists_index(&self) -> bool { !self.available_indexes.is_empty() + || self + .indexes + .iter() + .any(|index| !index.created_indexes.is_empty()) + } + + /// Returns whether the index has a known readable length for cache downloads. + /// A zero size does not remove the descriptor or its cleanup obligations. + pub fn has_downloadable_index(&self) -> bool { + self.exists_index() && self.index_file_size > 0 } pub fn index_version(&self) -> Option { @@ -557,6 +616,22 @@ impl fmt::Debug for FileHandle { } } +/// Folds file-level sequence bounds into the output sequence bound of a merge. +/// +/// A bound can be a row maximum or an admission marker; compaction must +/// preserve both for sequence-based pruning. Unknown bounds must remain +/// unknown rather than being replaced with a partial maximum. +pub(crate) fn known_max_input_sequence<'a>( + inputs: impl IntoIterator, +) -> Option { + let mut max: Option = None; + for input in inputs { + let sequence = input.sequence?; + max = Some(max.map_or(sequence, |current| current.max(sequence))); + } + max +} + impl FileHandle { /// Creates a new logical SST reference. Index replacements must reuse its lifetime. pub fn new(meta: FileMeta, file_purger: FilePurgerRef) -> FileHandle { @@ -604,11 +679,8 @@ impl FileHandle { /// Foreign files use their target-local sequence barrier; local files require /// the preserve marker because their physical sequences belong to this region. pub(crate) fn is_effective_target_sequence_trusted(&self, target_region_id: RegionId) -> bool { - if self.region_id() != target_region_id { - self.meta_ref().sequence.is_some() - } else { - self.meta_ref().preserve_row_sequence - } + self.meta_ref() + .is_effective_target_sequence_trusted(target_region_id) } /// Returns the cross-region file id. @@ -1152,6 +1224,50 @@ mod tests { } } + #[test] + fn test_sketch_manifest_compatibility() { + let legacy = r#"{ + "region_id": 0, + "file_id": "bc5896ec-e4d8-4017-a80d-f2de73188d55", + "time_range": [ + {"value": 0, "unit": "Millisecond"}, + {"value": 0, "unit": "Millisecond"} + ], + "available_indexes": [], + "indexes": [], + "level": 0 + }"#; + let legacy: FileMeta = serde_json::from_str(legacy).unwrap(); + assert!(legacy.indexes.is_empty()); + assert!(!legacy.exists_index()); + let old_column = r#"{"column_id":3,"created_indexes":["InvertedIndex"]}"#; + let column: ColumnIndexMetadata = serde_json::from_str(old_column).unwrap(); + assert_eq!( + serde_json::to_value(&column).unwrap(), + serde_json::from_str::(old_column).unwrap() + ); + let mut metadata = legacy.clone(); + metadata.index_version = 7; + metadata.indexes = vec![ColumnIndexMetadata { + column_id: 3, + created_indexes: SmallVec::from_iter([ + IndexType::HllIndex, + IndexType::KllIndex, + IndexType::MgIndex, + ]), + ..Default::default() + }]; + let encoded = serde_json::to_string(&metadata).unwrap(); + let decoded: FileMeta = serde_json::from_str(&encoded).unwrap(); + assert_eq!(metadata, decoded); + assert!(decoded.exists_index()); + assert_eq!(decoded.index_version(), Some(7)); + assert_eq!( + serde_json::to_value(&decoded.indexes[0].created_indexes).unwrap(), + serde_json::json!(["HllIndex", "KllIndex", "MgIndex"]) + ); + } + #[test] fn test_deserialize_file_meta() { let file_meta = create_file_meta(FileId::random(), 0); diff --git a/src/mito2/src/sst/file_purger.rs b/src/mito2/src/sst/file_purger.rs index 83147088e15..2b9732bda40 100644 --- a/src/mito2/src/sst/file_purger.rs +++ b/src/mito2/src/sst/file_purger.rs @@ -23,7 +23,7 @@ use crate::access_layer::AccessLayerRef; use crate::cache::CacheManagerRef; use crate::error::Result; use crate::schedule::scheduler::SchedulerRef; -use crate::sst::file::{FileMeta, delete_files}; +use crate::sst::file::{self, FileMeta, delete_files}; use crate::sst::file_ref::FileReferenceManagerRef; use crate::sst::range_index::RangeIndexDeleter; @@ -36,8 +36,8 @@ pub trait FilePurger: Send + Sync + fmt::Debug { /// Retire cached scan results immediately, without waiting for physical deletion. fn invalidate_file(&self, _: &FileMeta) {} - /// Returns the object-store reference manager used by SST metadata views. - /// Local and no-op purgers do not track GC references. + /// Returns the reference manager used by SST metadata views. + /// Purgers without a manager do not track GC references. fn file_ref_manager(&self) -> Option { None } @@ -59,6 +59,7 @@ pub struct LocalFilePurger { sst_layer: AccessLayerRef, cache_manager: Option, range_index_deleter: Option, + file_ref_manager: Option, } impl fmt::Debug for LocalFilePurger { @@ -91,6 +92,7 @@ pub fn should_enable_gc(global_gc_enabled: bool, _object_store_scheme: &'static /// If the storage is an object store, an `ObjectStoreFilePurger` is created, which /// only manages SST file references. Companion range indexes are deleted directly in either /// mode on final handle release when the SST is marked deleted and a deleter is provided. +/// Shared SSTs and their indexes are retained for global GC. /// pub fn create_file_purger( gc_enabled: bool, @@ -116,6 +118,7 @@ pub fn create_file_purger( } else { Arc::new( LocalFilePurger::new(scheduler, sst_layer, cache_manager) + .with_file_ref_manager(file_ref_manager) .with_range_index_deleter(range_index_deleter), ) } @@ -126,11 +129,12 @@ pub fn create_local_file_purger( scheduler: SchedulerRef, sst_layer: AccessLayerRef, cache_manager: Option, - _file_ref_manager: FileReferenceManagerRef, + file_ref_manager: FileReferenceManagerRef, range_index_deleter: Option, ) -> FilePurgerRef { Arc::new( LocalFilePurger::new(scheduler, sst_layer, cache_manager) + .with_file_ref_manager(file_ref_manager) .with_range_index_deleter(range_index_deleter), ) } @@ -147,9 +151,15 @@ impl LocalFilePurger { sst_layer, cache_manager, range_index_deleter: None, + file_ref_manager: None, } } + fn with_file_ref_manager(mut self, manager: FileReferenceManagerRef) -> Self { + self.file_ref_manager = Some(manager); + self + } + /// Attaches deletion of companion range indexes. pub fn with_range_index_deleter(mut self, deleter: Option) -> Self { self.range_index_deleter = deleter; @@ -165,7 +175,16 @@ impl LocalFilePurger { fn delete_file(&self, file_meta: FileMeta) { let sst_layer = self.sst_layer.clone(); let cache_manager = self.cache_manager.clone(); + let range_index_deleter = self.range_index_deleter.clone(); if let Err(e) = self.scheduler.schedule(Box::pin(async move { + match sst_layer.is_file_protected(file_meta.file_id()).await { + Ok(false) => {} + Ok(true) => return, + Err(error) => { + error!(error; "File protection unavailable; retaining SST {}", file_meta.file_id()); + return; + } + } if let Err(e) = delete_files( file_meta.region_id, &[(file_meta.file_id, file_meta.index_id().version)], @@ -176,6 +195,12 @@ impl LocalFilePurger { .await { error!(e; "Failed to delete file {:?} from storage", file_meta); + return; + } + if let Some(deleter) = range_index_deleter + && let Err(error) = deleter.delete(file_meta.file_id).await + { + error!(error; "Failed to delete companion range index"); } })) { error!(e; "Failed to schedule the file purge request"); @@ -191,13 +216,23 @@ impl FilePurger for LocalFilePurger { } fn purge_file(&self, file_meta: FileMeta) { - schedule_range_index_deletion( - &self.scheduler, - self.range_index_deleter.as_ref(), - file_meta.file_id, - ); + if file_meta.level == file::LEVEL_SHARED { + // This lifetime covers one logical reference, not other targets sharing the SST, + // so the SST object itself is left to global GC. The range index is keyed by + // this region and all of its readers are gone, so it must not leak. + schedule_range_index_deletion( + &self.scheduler, + self.range_index_deleter.as_ref(), + file_meta.file_id, + ); + return; + } self.delete_file(file_meta); } + + fn file_ref_manager(&self) -> Option { + self.file_ref_manager.clone() + } } pub struct ObjectStoreFilePurger { @@ -271,8 +306,8 @@ mod tests { use crate::access_layer::AccessLayer; use crate::schedule::scheduler::{LocalScheduler, Scheduler}; use crate::sst::file::{ - ColumnIndexMetadata, FileHandle, FileMeta, FileTimeRange, IndexType, RegionFileId, - RegionIndexId, + ColumnIndexMetadata, FileHandle, FileMeta, FileTimeRange, IndexType, LEVEL_SHARED, + RegionFileId, RegionIndexId, }; use crate::sst::index::intermediate::IntermediateManager; use crate::sst::index::puffin_manager::PuffinManagerFactory; @@ -413,6 +448,7 @@ mod tests { #[case] gc_enabled: bool, #[values(false, true)] is_delete: bool, #[values(false, true)] update_index: bool, + #[values(0, LEVEL_SHARED)] level: u8, ) { let env = PurgeTestEnv::new().await; let object_store = env.layer.object_store(); @@ -448,6 +484,7 @@ mod tests { let meta = FileMeta { region_id: sst_file_id.region_id(), file_id: sst_file_id.file_id(), + level, file_size: 4096, max_row_group_uncompressed_size: 4096, ..Default::default() @@ -456,7 +493,9 @@ mod tests { crate::test_util::memtable_util::metadata_for_test(), ); version.add_files(file_purger, [meta].into_iter()); - let reader = version.levels()[0].files[&sst_file_id.file_id()].clone(); + let reader = version.levels()[crate::sst::file::level_slot(level).unwrap()].files + [&sst_file_id.file_id()] + .clone(); if update_index { for index_version in 1..=2 { let mut meta = reader.meta_ref().clone(); @@ -489,22 +528,30 @@ mod tests { assert_eq!( object_store.exists(&path).await.unwrap(), - gc_enabled || !is_delete + gc_enabled || !is_delete || level == LEVEL_SHARED + ); + assert_eq!( + index_store.exists(&index_path).await.unwrap(), + !is_delete, + "range index is region-scoped and must be deleted with the last reader" ); - assert_eq!(index_store.exists(&index_path).await.unwrap(), !is_delete); if update_index { for index_version in 1..=2 { let path = env.index_path(index_version); assert_eq!( object_store.exists(&path).await.unwrap(), - gc_enabled || !is_delete + gc_enabled || !is_delete || level == LEVEL_SHARED ); } } } + #[rstest::rstest] #[tokio::test] - async fn test_file_purge_with_index() { + async fn test_file_purge_with_index( + #[values(0, LEVEL_SHARED)] level: u8, + #[values(false, true)] sketch_only: bool, + ) { let env = PurgeTestEnv::new().await; let object_store = env.layer.object_store(); let sst_file_id = env.file_id; @@ -528,13 +575,21 @@ mod tests { region_id: sst_file_id.region_id(), file_id: sst_file_id.file_id(), time_range: FileTimeRange::default(), - level: 0, + level, file_size: 4096, max_row_group_uncompressed_size: 4096, - available_indexes: SmallVec::from_iter([IndexType::InvertedIndex]), + available_indexes: if sketch_only { + SmallVec::new() + } else { + SmallVec::from_iter([IndexType::InvertedIndex]) + }, indexes: vec![ColumnIndexMetadata { column_id: 0, - created_indexes: SmallVec::from_iter([IndexType::InvertedIndex]), + created_indexes: SmallVec::from_iter([if sketch_only { + IndexType::HllIndex + } else { + IndexType::InvertedIndex + }]), ..Default::default() }], index_file_size: 4096, @@ -548,13 +603,27 @@ mod tests { }, file_purger, ); - // mark file as deleted and drop the handle, we expect the sst file and the index file are deleted. + assert!(handle.meta_ref().exists_index()); + assert_eq!(handle.meta_ref().available_indexes.is_empty(), sketch_only); + assert_eq!( + handle.meta_ref().indexes[0] + .created_indexes + .contains(&IndexType::HllIndex), + sketch_only + ); + // Shared SSTs and their indexes require global GC even after local release. handle.mark_deleted(); } scheduler.stop(true).await.unwrap(); - assert!(!object_store.exists(&path).await.unwrap()); - assert!(!object_store.exists(&index_path).await.unwrap()); + assert_eq!( + level == LEVEL_SHARED, + object_store.exists(&path).await.unwrap() + ); + assert_eq!( + level == LEVEL_SHARED, + object_store.exists(&index_path).await.unwrap() + ); } } diff --git a/src/mito2/src/sst/index.rs b/src/mito2/src/sst/index.rs index 881a72ead83..4fb0f08e217 100644 --- a/src/mito2/src/sst/index.rs +++ b/src/mito2/src/sst/index.rs @@ -17,28 +17,27 @@ mod column; #[cfg(test)] mod column_test; pub(crate) mod fulltext_index; +pub(crate) mod handler; mod indexer; pub mod intermediate; pub(crate) mod inverted_index; +pub(crate) mod kind; mod primary_key; pub mod puffin_manager; +pub(crate) mod registry; #[cfg(test)] mod sparse_test; mod statistics; pub(crate) mod store; use std::cmp::Ordering; -use std::collections::{HashMap, HashSet}; -use std::num::NonZeroUsize; +use std::collections::{BTreeMap, HashMap, HashSet}; use std::ops::ControlFlow; use std::sync::Arc; -use arrow_schema::extension::ExtensionType; -use bloom_filter::creator::BloomFilterIndexer; use bytes::Bytes; use common_telemetry::{debug, error, info, warn}; use datatypes::arrow::record_batch::RecordBatch; -use datatypes::extension::json::Json2ExtensionType; use index::target::IndexTarget; use mito_codec::row_converter::DensePrimaryKeyCodec; use object_store::ObjectStore; @@ -46,7 +45,8 @@ use parquet::arrow::arrow_reader::ParquetRecordBatchReaderBuilder; use puffin_manager::SstPuffinManager; use smallvec::SmallVec; use snafu::ResultExt; -use statistics::{ByteCount, RowCount}; +#[cfg(feature = "enterprise")] +pub use statistics::{Statistics, TimerGuard}; use store_api::codec::PrimaryKeyEncoding; use store_api::metadata::RegionMetadataRef; use store_api::storage::{ColumnId, FileId, RegionId}; @@ -58,10 +58,11 @@ use crate::batch_size::{estimate_batch_size, largest_row_group_statistic}; use crate::cache::file_cache::{FileCacheRef, FileType, IndexKey}; use crate::cache::write_cache::{UploadOptions, UploadTracker, WriteCacheRef}; use crate::cache::{CacheManagerRef, CacheStrategy}; -use crate::config::{BloomFilterConfig, FulltextIndexConfig, InvertedIndexConfig}; +#[cfg(test)] +use crate::config::{BloomFilterConfig, InvertedIndexConfig}; use crate::error::{ - BuildIndexAsyncSnafu, Error, JoinSnafu, RegionClosedSnafu, RegionDroppedSnafu, - RegionTruncatedSnafu, Result, + BuildIndexAsyncSnafu, Error, InvalidConfigSnafu, JoinSnafu, RegionClosedSnafu, + RegionDroppedSnafu, RegionTruncatedSnafu, Result, }; use crate::metrics::{ INDEX_ARTIFACT_CLEANUP_FAILURE_TOTAL, INDEX_CREATE_MEMORY_USAGE, INDEX_PUBLICATION_STALE_TOTAL, @@ -77,20 +78,21 @@ use crate::request::{ WorkerRequestWithTime, }; use crate::schedule::scheduler::{Job, SchedulerRef}; -use crate::sst::file::{ - ColumnIndexMetadata, FileHandle, IndexType, IndexTypes, RegionFileId, RegionIndexId, -}; +use crate::sst::file::{ColumnIndexMetadata, FileHandle, IndexType, RegionFileId, RegionIndexId}; use crate::sst::file_purger::FilePurgerRef; +#[cfg(feature = "testing")] +use crate::sst::index::bloom_filter::creator::BloomFilterIndexer; +#[cfg(test)] use crate::sst::index::fulltext_index::FULLTEXT_BLOOM_VERSION; -use crate::sst::index::fulltext_index::creator::FulltextIndexer; use crate::sst::index::intermediate::IntermediateManager; +#[cfg(feature = "testing")] use crate::sst::index::inverted_index::creator::InvertedIndexer; use crate::sst::parquet::SstInfo; use crate::worker::WorkerListener; -pub(crate) const TYPE_INVERTED_INDEX: &str = "inverted_index"; -pub(crate) const TYPE_FULLTEXT_INDEX: &str = "fulltext_index"; -pub(crate) const TYPE_BLOOM_FILTER_INDEX: &str = "bloom_filter_index"; +pub(crate) const TYPE_INVERTED_INDEX: &str = kind::IndexKind::Inverted.as_str(); +pub(crate) const TYPE_FULLTEXT_INDEX: &str = kind::IndexKind::Fulltext.as_str(); +pub(crate) const TYPE_BLOOM_FILTER_INDEX: &str = kind::IndexKind::Bloom.as_str(); /// Evicts local state for a stale index artifact. /// @@ -157,117 +159,98 @@ pub(crate) fn trigger_index_background_download( } } -/// Output of the index creation. +/// One index successfully written into the enclosing Puffin file. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) struct CompletedEntry { + /// Indexed column. `None` is reserved for file-level built-in indexes, such as + /// JSON-path-only indexes; these appear only in `available_indexes`. + pub column_id: Option, + /// Registered index identity. + pub kind: crate::sst::index::kind::IndexKind, + /// Fulltext bloom version published in column metadata. + pub format_version: u32, +} + +impl CompletedEntry { + fn fulltext_bloom_version(&self) -> Result { + u8::try_from(self.format_version).map_err(|_| { + InvalidConfigSnafu { + reason: format!("fulltext bloom version {} exceeds u8", self.format_version), + } + .build() + }) + } + + fn validate(&self) -> Result<()> { + if self.kind.index_type() == IndexType::FulltextIndex { + self.fulltext_bloom_version()?; + } + Ok(()) + } +} + +/// Output published only after the enclosing Puffin file finishes. #[derive(Debug, Clone, Default)] pub struct IndexOutput { /// Size of the file. pub file_size: u64, /// Index version. pub version: u64, - /// Inverted index output. - pub inverted_index: InvertedIndexOutput, - /// Fulltext index output. - pub fulltext_index: FulltextIndexOutput, - /// Columns of `fulltext_index` that use the bloom backend. - pub fulltext_bloom_columns: Vec, - /// Bloom filter output. - pub bloom_filter: BloomFilterOutput, + /// Successfully written column indexes. + pub(crate) entries: Vec, } impl IndexOutput { pub fn build_available_indexes(&self) -> SmallVec<[IndexType; 4]> { - let mut indexes = SmallVec::new(); - if self.inverted_index.is_available() { - indexes.push(IndexType::InvertedIndex); - } - if self.fulltext_index.is_available() { - indexes.push(IndexType::FulltextIndex); - } - if self.bloom_filter.is_available() { - indexes.push(IndexType::BloomFilterIndex); - } - indexes + // Preserve the established order independently of handler registration. + [ + IndexType::InvertedIndex, + IndexType::FulltextIndex, + IndexType::BloomFilterIndex, + ] + .into_iter() + .filter(|kind| { + self.entries + .iter() + .any(|entry| entry.kind.index_type() == *kind) + }) + .collect() } - pub fn build_indexes(&self) -> Vec { - let mut map: HashMap = HashMap::new(); - - if self.inverted_index.is_available() { - for &col in &self.inverted_index.columns { - map.entry(col).or_default().push(IndexType::InvertedIndex); + /// Builds column metadata, rejecting values that cannot be represented on disk. + pub fn build_indexes(&self) -> Result> { + let mut map: BTreeMap = BTreeMap::new(); + for kind in self.build_available_indexes() { + for entry in self + .entries + .iter() + .filter(|entry| entry.kind.index_type() == kind) + { + let Some(column_id) = entry.column_id else { + continue; + }; + let metadata = map.entry(column_id).or_default(); + metadata.column_id = column_id; + metadata.created_indexes.push(kind); + if kind == IndexType::FulltextIndex { + metadata.fulltext_bloom_version = entry.fulltext_bloom_version()?; + } } } - if self.fulltext_index.is_available() { - for &col in &self.fulltext_index.columns { - map.entry(col).or_default().push(IndexType::FulltextIndex); - } - } - if self.bloom_filter.is_available() { - for &col in &self.bloom_filter.columns { - map.entry(col) - .or_default() - .push(IndexType::BloomFilterIndex); - } - } - - map.into_iter() - .map(|(column_id, created_indexes)| ColumnIndexMetadata { - column_id, - fulltext_bloom_version: if self.fulltext_index.is_available() - && self.fulltext_bloom_columns.contains(&column_id) - { - FULLTEXT_BLOOM_VERSION - } else { - 0 - }, - created_indexes, - }) - .collect::>() + Ok(map.into_values().collect()) } } -/// Base output of the index creation. -#[derive(Debug, Clone, Default)] -pub struct IndexBaseOutput { - /// Size of the index. - pub index_size: ByteCount, - /// Number of rows in the index. - pub row_count: RowCount, - /// Available columns in the index. - pub columns: Vec, -} - -impl IndexBaseOutput { - pub fn is_available(&self) -> bool { - self.index_size > 0 - } -} - -/// Output of the inverted index creation. -pub type InvertedIndexOutput = IndexBaseOutput; -/// Output of the fulltext index creation. -pub type FulltextIndexOutput = IndexBaseOutput; -/// Output of the bloom filter creation. -pub type BloomFilterOutput = IndexBaseOutput; - -/// The index creator that hides the error handling details. +/// Executes planned creators through the existing Puffin lifecycle. #[derive(Default)] pub struct Indexer { file_id: FileId, - /// The logical region used for metadata and intermediate index files. region_id: RegionId, - /// The region that owns the physical SST and Puffin files. physical_region_id: RegionId, index_version: u64, puffin_manager: Option, write_cache_enabled: bool, - inverted_indexer: Option, - last_mem_inverted_index: usize, - fulltext_indexer: Option, - last_mem_fulltext_index: usize, - bloom_filter_indexer: Option, - last_mem_bloom_filter: usize, - /// Present only when the active creators together need every Dense PK field. + creators: Vec, dense_pk_decoder: Option, intermediate_manager: Option, } @@ -275,9 +258,23 @@ pub struct Indexer { impl Indexer { /// Returns true if no index creator is active. pub(crate) fn is_empty(&self) -> bool { - self.inverted_indexer.is_none() - && self.fulltext_indexer.is_none() - && self.bloom_filter_indexer.is_none() + self.creators.is_empty() + } + + #[cfg(test)] + fn has_kind(&self, kind: kind::IndexKind) -> bool { + self.creators.iter().any(|active| active.kind == kind) + } + + fn push_creator(&mut self, kind: kind::IndexKind, creator: Box) { + self.creators.push(ActiveIndex { + kind, + creator, + memory: IndexMemoryUsage { + label: kind.as_str(), + bytes: 0, + }, + }); } /// Wraps real creators for update-only benchmarks without a Puffin output. @@ -289,16 +286,18 @@ impl Indexer { ) -> Self { let mut indexer = Self { region_id: metadata.region_id, - inverted_indexer, - bloom_filter_indexer, ..Default::default() }; + if let Some(creator) = inverted_indexer { + indexer.push_creator(kind::IndexKind::Inverted, Box::new(creator)); + } + if let Some(creator) = bloom_filter_indexer { + indexer.push_creator(kind::IndexKind::Bloom, Box::new(creator)); + } indexer.prepare_dense_pk_decoder(metadata); indexer } - /// Computes demand once from active creators. Field columns and duplicate - /// requests across creators cannot turn a partial PK projection into a full one. fn prepare_dense_pk_decoder(&mut self, metadata: &RegionMetadataRef) { if metadata.primary_key_encoding != PrimaryKeyEncoding::Dense || metadata.primary_key.is_empty() @@ -306,16 +305,12 @@ impl Indexer { return; } let requested: HashSet<_> = self - .inverted_indexer + .creators .iter() - .flat_map(|indexer| indexer.indexed_targets()) - .chain( - self.bloom_filter_indexer - .iter() - .flat_map(|indexer| indexer.indexed_targets()), - ) + .filter(|active| active.creator.needs_dense_pk()) + .flat_map(|active| active.creator.indexed_targets()) .filter_map(|target| match target { - IndexTarget::ColumnId(id) => Some(*id), + IndexTarget::ColumnId(id) => Some(id), IndexTarget::JsonPath(_) => None, }) .collect(); @@ -324,7 +319,6 @@ impl Indexer { } } - /// Called before any creator consumes the batch, so the full decode is shared. fn prepare_primary_key(&self, batch: &mut Batch) -> Result<()> { if let Some(codec) = &self.dense_pk_decoder { batch.ensure_dense_pk_decoded(codec)?; @@ -332,24 +326,21 @@ impl Indexer { Ok(()) } - /// Updates the index with the given batch. + /// Updates all active creators using the borrowed batch. pub async fn update(&mut self, batch: &mut Batch) { self.do_update(batch).await; - self.flush_mem_metrics(); } - /// Updates the index with the given flat format RecordBatch. + /// Updates all active creators using the borrowed flat batch. pub async fn update_flat(&mut self, batch: &RecordBatch) { self.do_update_flat(batch).await; - self.flush_mem_metrics(); } /// Finalizes the index creation. pub async fn finish(&mut self) -> IndexOutput { let output = self.do_finish().await; - self.flush_mem_metrics(); output } @@ -357,37 +348,38 @@ impl Indexer { /// Aborts the index creation. pub async fn abort(&mut self) { self.do_abort().await; - self.flush_mem_metrics(); } fn flush_mem_metrics(&mut self) { - let inverted_mem = self - .inverted_indexer - .as_ref() - .map_or(0, |creator| creator.memory_usage()); - INDEX_CREATE_MEMORY_USAGE - .with_label_values(&[TYPE_INVERTED_INDEX]) - .add(inverted_mem as i64 - self.last_mem_inverted_index as i64); - self.last_mem_inverted_index = inverted_mem; + for active in &mut self.creators { + let bytes = active.creator.memory_usage(); + INDEX_CREATE_MEMORY_USAGE + .with_label_values(&[active.memory.label]) + .add(bytes as i64 - active.memory.bytes as i64); + active.memory.bytes = bytes; + } + } +} - let fulltext_mem = self - .fulltext_indexer - .as_ref() - .map_or(0, |creator| creator.memory_usage()); - INDEX_CREATE_MEMORY_USAGE - .with_label_values(&[TYPE_FULLTEXT_INDEX]) - .add(fulltext_mem as i64 - self.last_mem_fulltext_index as i64); - self.last_mem_fulltext_index = fulltext_mem; +/// One handler's active creator and its shared memory accounting. +struct ActiveIndex { + kind: kind::IndexKind, + creator: Box, + memory: IndexMemoryUsage, +} - let bloom_filter_mem = self - .bloom_filter_indexer - .as_ref() - .map_or(0, |creator| creator.memory_usage()); +/// Releases each creator's gauge contribution on completion or cancellation. +struct IndexMemoryUsage { + label: &'static str, + bytes: usize, +} + +impl Drop for IndexMemoryUsage { + fn drop(&mut self) { INDEX_CREATE_MEMORY_USAGE - .with_label_values(&[TYPE_BLOOM_FILTER_INDEX]) - .add(bloom_filter_mem as i64 - self.last_mem_bloom_filter as i64); - self.last_mem_bloom_filter = bloom_filter_mem; + .with_label_values(&[self.label]) + .sub(self.bytes as i64); } } @@ -401,17 +393,16 @@ pub trait IndexerBuilder { row_group_size: Option, ) -> Indexer; } + #[derive(Clone)] pub(crate) struct IndexerBuilderImpl { + pub(crate) registry: registry::IndexRegistryRef, pub(crate) build_type: IndexBuildType, pub(crate) metadata: RegionMetadataRef, pub(crate) puffin_manager: SstPuffinManager, pub(crate) write_cache_enabled: bool, pub(crate) intermediate_manager: IntermediateManager, pub(crate) index_options: IndexOptions, - pub(crate) inverted_index_config: InvertedIndexConfig, - pub(crate) fulltext_index_config: FulltextIndexConfig, - pub(crate) bloom_filter_index_config: BloomFilterConfig, } #[async_trait::async_trait] @@ -432,16 +423,38 @@ impl IndexerBuilder for IndexerBuilderImpl { ..Default::default() }; - indexer.inverted_indexer = - self.build_inverted_indexer(region_file_id.file_id(), row_group_size); - indexer.fulltext_indexer = self.build_fulltext_indexer(region_file_id.file_id()).await; - indexer.bloom_filter_indexer = self.build_bloom_filter_indexer(region_file_id.file_id()); + let context = handler::PlanContext { + metadata: &self.metadata, + index_options: &self.index_options, + build_type: self.build_type.clone(), + }; + let plan = self.registry.plan(&context); + let context = handler::BuildContext { + metadata: &self.metadata, + output: RegionIndexId::new(region_file_id, index_version), + intermediate_manager: &self.intermediate_manager, + row_group_size, + }; + for planned in plan.planned() { + match planned.build(&context).await { + Ok(Some(creator)) => { + indexer.push_creator(planned.kind(), creator); + } + Ok(None) => {} + Err(err) => { + if cfg!(any(test, feature = "test")) { + panic!("Failed to create index: {err:?}"); + } + warn!(err; "Failed to create index, region_id: {}, kind: {:?}", self.metadata.region_id, planned.kind()); + } + } + } indexer.prepare_dense_pk_decoder(&self.metadata); indexer.intermediate_manager = Some(self.intermediate_manager.clone()); if indexer.is_empty() { indexer.abort().await; - return Indexer::default(); + return indexer; } indexer.puffin_manager = Some(self.puffin_manager.clone()); @@ -523,222 +536,6 @@ pub(crate) async fn build_index_from_parquet_bytes( indexer.finish().await } -impl IndexerBuilderImpl { - fn build_inverted_indexer( - &self, - file_id: FileId, - row_group_size: Option, - ) -> Option { - let create = match self.build_type { - IndexBuildType::Flush => self.inverted_index_config.create_on_flush.auto(), - IndexBuildType::Compact => self.inverted_index_config.create_on_compaction.auto(), - _ => true, - }; - - if !create { - debug!( - "Skip creating inverted index due to config, region_id: {}, file_id: {}", - self.metadata.region_id, file_id, - ); - return None; - } - - let indexed_column_ids = self.metadata.inverted_indexed_column_ids( - self.index_options.inverted_index.ignore_column_ids.iter(), - ); - let mut index_targets: Vec<_> = indexed_column_ids - .into_iter() - .map(IndexTarget::ColumnId) - .collect(); - index_targets.extend(self.collect_json_inverted_index_targets()); - - if index_targets.is_empty() { - debug!( - "No columns to be indexed, skip creating inverted index, region_id: {}, file_id: {}", - self.metadata.region_id, file_id, - ); - return None; - } - - let Some(mut segment_row_count) = - NonZeroUsize::new(self.index_options.inverted_index.segment_row_count) - else { - warn!( - "Segment row count is 0, skip creating index, region_id: {}, file_id: {}", - self.metadata.region_id, file_id, - ); - return None; - }; - - // if segment row count not aligned with row group size, adjust it to be aligned. - if let Some(row_group_size) = row_group_size.and_then(NonZeroUsize::new) - && row_group_size.get() % segment_row_count.get() != 0 - { - segment_row_count = row_group_size; - } - - let indexer = InvertedIndexer::new( - file_id, - &self.metadata, - self.intermediate_manager.clone(), - self.inverted_index_config.mem_threshold_on_create(), - segment_row_count, - index_targets, - ); - - Some(indexer) - } - - /// Collects inverted index targets for JSON type hints with indexing enabled. - /// - /// Only flush and compaction builds collect these targets; manual and schema-change - /// rebuilds return no JSON targets. - fn collect_json_inverted_index_targets(&self) -> Vec { - // FIXME: Rebuilds replace the whole Puffin file and can drop existing JSON path indexes. - if !matches!( - self.build_type, - IndexBuildType::Flush | IndexBuildType::Compact - ) { - return Vec::new(); - } - - let mut index_targets = Vec::new(); - for col in &self.metadata.column_metadatas { - if !col.column_schema.data_type.is_json2() { - continue; - } - let Ok(Some(extension)) = col.column_schema.extension_type::() - else { - continue; - }; - for hint in extension.metadata().json_settings().type_hints() { - if !hint.inverted_index { - continue; - } - // JSON hints may also describe containers through non-SQL ingestion. - if !(hint.data_type.is_numeric() - || hint.data_type.is_boolean() - || hint.data_type.is_string()) - { - continue; - } - match IndexTarget::new_json_path(col.column_id, hint.path.clone()) { - Ok(target) => index_targets.push(target), - Err(err) => warn!(err; "Skipping invalid JSON inverted index target"), - } - } - } - - index_targets - } - - async fn build_fulltext_indexer(&self, file_id: FileId) -> Option { - let create = match self.build_type { - IndexBuildType::Flush => self.fulltext_index_config.create_on_flush.auto(), - IndexBuildType::Compact => self.fulltext_index_config.create_on_compaction.auto(), - _ => true, - }; - - if !create { - debug!( - "Skip creating full-text index due to config, region_id: {}, file_id: {}", - self.metadata.region_id, file_id, - ); - return None; - } - - let mem_limit = self.fulltext_index_config.mem_threshold_on_create(); - let creator = FulltextIndexer::new( - &self.metadata.region_id, - &file_id, - &self.intermediate_manager, - &self.metadata, - self.fulltext_index_config.compress, - mem_limit, - ) - .await; - - let err = match creator { - Ok(creator) => { - if creator.is_none() { - debug!( - "Skip creating full-text index due to no columns require indexing, region_id: {}, file_id: {}", - self.metadata.region_id, file_id, - ); - } - return creator; - } - Err(err) => err, - }; - - if cfg!(any(test, feature = "test")) { - panic!( - "Failed to create full-text indexer, region_id: {}, file_id: {}, err: {:?}", - self.metadata.region_id, file_id, err - ); - } else { - warn!( - err; "Failed to create full-text indexer, region_id: {}, file_id: {}", - self.metadata.region_id, file_id, - ); - } - - None - } - - fn build_bloom_filter_indexer(&self, file_id: FileId) -> Option { - let create = match self.build_type { - IndexBuildType::Flush => self.bloom_filter_index_config.create_on_flush.auto(), - IndexBuildType::Compact => self.bloom_filter_index_config.create_on_compaction.auto(), - _ => true, - }; - - if !create { - debug!( - "Skip creating bloom filter due to config, region_id: {}, file_id: {}", - self.metadata.region_id, file_id, - ); - return None; - } - - let mem_limit = self.bloom_filter_index_config.mem_threshold_on_create(); - let indexer = BloomFilterIndexer::new( - file_id, - &self.metadata, - self.intermediate_manager.clone(), - mem_limit, - self.build_type.clone(), - ); - - let err = match indexer { - Ok(indexer) => { - if indexer.is_none() { - debug!( - "Skip creating bloom filter due to no columns require indexing, region_id: {}, file_id: {}", - self.metadata.region_id, file_id, - ); - } - return indexer; - } - Err(err) => err, - }; - - if cfg!(any(test, feature = "test")) { - panic!( - "Failed to create bloom filter, region_id: {}, file_id: {}, err: {:?}", - self.metadata.region_id, file_id, err - ); - } else { - warn!( - err; "Failed to create bloom filter, region_id: {}, file_id: {}", - self.metadata.region_id, file_id, - ); - } - - None - } -} - /// Type of an index build task. #[derive(Debug, Clone, IntoStaticStr, PartialEq)] pub enum IndexBuildType { @@ -1271,7 +1068,7 @@ impl IndexBuildTask { ) -> Result { let mut updated = self.source.file_meta.clone(); updated.available_indexes = output.build_available_indexes(); - updated.indexes = output.build_indexes(); + updated.indexes = output.build_indexes()?; updated.index_file_size = output.file_size; updated.index_version = new_index_version; let publication = self @@ -1892,7 +1689,7 @@ mod tests { async fn mock_indexer_builder( metadata: RegionMetadataRef, env: &SchedulerEnv, - ) -> Arc { + ) -> Arc { let (dir, factory) = PuffinManagerFactory::new_for_test_async("mock_indexer_builder").await; let intm_manager = mock_intm_mgr(dir.path().to_string_lossy()).await; let puffin_manager = factory.build( @@ -1909,12 +1706,123 @@ mod tests { write_cache_enabled: false, intermediate_manager: intm_manager, index_options: IndexOptions::default(), - inverted_index_config: InvertedIndexConfig::default(), - fulltext_index_config: FulltextIndexConfig::default(), - bloom_filter_index_config: BloomFilterConfig::default(), + registry: Arc::new(crate::sst::index::registry::IndexRegistry::new( + InvertedIndexConfig::default(), + FulltextIndexConfig::default(), + BloomFilterConfig::default(), + )), }) } + #[test] + fn test_file_level_completion_preserves_json_only_index() { + let output = IndexOutput { + entries: vec![CompletedEntry { + column_id: None, + kind: kind::IndexKind::Inverted, + format_version: 0, + }], + ..Default::default() + }; + assert_eq!( + output.build_available_indexes().as_slice(), + &[IndexType::InvertedIndex] + ); + assert!(output.build_indexes().unwrap().is_empty()); + } + + #[test] + fn test_completed_entries_preserve_builtin_metadata() { + use crate::sst::index::kind::IndexKind; + + // Deliberately reverse creator order: the published builtin order is contractual. + let output = IndexOutput { + entries: vec![ + CompletedEntry { + column_id: Some(2), + kind: IndexKind::Bloom, + format_version: 0, + }, + CompletedEntry { + column_id: Some(2), + kind: IndexKind::Fulltext, + format_version: u32::from(FULLTEXT_BLOOM_VERSION), + }, + CompletedEntry { + column_id: Some(2), + kind: IndexKind::Inverted, + format_version: 0, + }, + CompletedEntry { + column_id: Some(3), + kind: IndexKind::Fulltext, + format_version: 0, + }, + ], + ..Default::default() + }; + let expected_kinds = vec![ + IndexType::InvertedIndex, + IndexType::FulltextIndex, + IndexType::BloomFilterIndex, + ]; + assert_eq!( + output.build_available_indexes().as_slice(), + expected_kinds.as_slice() + ); + let actual = output.build_indexes().unwrap(); + assert_eq!( + actual, + vec![ + ColumnIndexMetadata { + column_id: 2, + created_indexes: expected_kinds.into(), + fulltext_bloom_version: FULLTEXT_BLOOM_VERSION, + }, + ColumnIndexMetadata { + column_id: 3, + created_indexes: vec![IndexType::FulltextIndex].into(), + fulltext_bloom_version: 0, + }, + ] + ); + } + + #[test] + fn test_build_indexes_rejects_unrepresentable_fulltext_version() { + let mut output = IndexOutput { + entries: vec![CompletedEntry { + column_id: Some(7), + kind: kind::IndexKind::Fulltext, + format_version: u8::MAX.into(), + }], + ..Default::default() + }; + assert_eq!( + output.build_indexes().unwrap()[0].fulltext_bloom_version, + u8::MAX + ); + output.entries[0].format_version += 1; + let error = output.build_indexes().unwrap_err(); + assert!( + error + .to_string() + .contains("fulltext bloom version 256 exceeds u8") + ); + } + + #[test] + fn test_completed_entry_validation() { + let mut entry = CompletedEntry { + column_id: Some(1), + kind: kind::IndexKind::Fulltext, + format_version: u8::MAX.into(), + }; + assert!(entry.validate().is_ok()); + entry.format_version += 1; + assert!(entry.validate().is_err()); + } + #[tokio::test] async fn test_build_indexer_basic() { let (dir, factory) = @@ -1933,16 +1841,18 @@ mod tests { write_cache_enabled: false, intermediate_manager: intm_manager, index_options: IndexOptions::default(), - inverted_index_config: InvertedIndexConfig::default(), - fulltext_index_config: FulltextIndexConfig::default(), - bloom_filter_index_config: BloomFilterConfig::default(), + registry: Arc::new(crate::sst::index::registry::IndexRegistry::new( + InvertedIndexConfig::default(), + FulltextIndexConfig::default(), + BloomFilterConfig::default(), + )), } .build(random_region_file_id(), 0, Some(1024)) .await; - assert!(indexer.inverted_indexer.is_some()); - assert!(indexer.fulltext_indexer.is_some()); - assert!(indexer.bloom_filter_indexer.is_some()); + assert!(indexer.has_kind(kind::IndexKind::Inverted)); + assert!(indexer.has_kind(kind::IndexKind::Fulltext)); + assert!(indexer.has_kind(kind::IndexKind::Bloom)); } #[tokio::test] @@ -1963,19 +1873,21 @@ mod tests { write_cache_enabled: false, intermediate_manager: intm_manager.clone(), index_options: IndexOptions::default(), - inverted_index_config: InvertedIndexConfig { - create_on_flush: Mode::Disable, - ..Default::default() - }, - fulltext_index_config: FulltextIndexConfig::default(), - bloom_filter_index_config: BloomFilterConfig::default(), + registry: Arc::new(crate::sst::index::registry::IndexRegistry::new( + InvertedIndexConfig { + create_on_flush: Mode::Disable, + ..Default::default() + }, + FulltextIndexConfig::default(), + BloomFilterConfig::default(), + )), } .build(random_region_file_id(), 0, Some(1024)) .await; - assert!(indexer.inverted_indexer.is_none()); - assert!(indexer.fulltext_indexer.is_some()); - assert!(indexer.bloom_filter_indexer.is_some()); + assert!(!indexer.has_kind(kind::IndexKind::Inverted)); + assert!(indexer.has_kind(kind::IndexKind::Fulltext)); + assert!(indexer.has_kind(kind::IndexKind::Bloom)); let indexer = IndexerBuilderImpl { build_type: IndexBuildType::Compact, @@ -1984,19 +1896,21 @@ mod tests { write_cache_enabled: false, intermediate_manager: intm_manager.clone(), index_options: IndexOptions::default(), - inverted_index_config: InvertedIndexConfig::default(), - fulltext_index_config: FulltextIndexConfig { - create_on_compaction: Mode::Disable, - ..Default::default() - }, - bloom_filter_index_config: BloomFilterConfig::default(), + registry: Arc::new(crate::sst::index::registry::IndexRegistry::new( + InvertedIndexConfig::default(), + FulltextIndexConfig { + create_on_compaction: Mode::Disable, + ..Default::default() + }, + BloomFilterConfig::default(), + )), } .build(random_region_file_id(), 0, Some(1024)) .await; - assert!(indexer.inverted_indexer.is_some()); - assert!(indexer.fulltext_indexer.is_none()); - assert!(indexer.bloom_filter_indexer.is_some()); + assert!(indexer.has_kind(kind::IndexKind::Inverted)); + assert!(!indexer.has_kind(kind::IndexKind::Fulltext)); + assert!(indexer.has_kind(kind::IndexKind::Bloom)); let indexer = IndexerBuilderImpl { build_type: IndexBuildType::Compact, @@ -2005,19 +1919,21 @@ mod tests { write_cache_enabled: false, intermediate_manager: intm_manager, index_options: IndexOptions::default(), - inverted_index_config: InvertedIndexConfig::default(), - fulltext_index_config: FulltextIndexConfig::default(), - bloom_filter_index_config: BloomFilterConfig { - create_on_compaction: Mode::Disable, - ..Default::default() - }, + registry: Arc::new(crate::sst::index::registry::IndexRegistry::new( + InvertedIndexConfig::default(), + FulltextIndexConfig::default(), + BloomFilterConfig { + create_on_compaction: Mode::Disable, + ..Default::default() + }, + )), } .build(random_region_file_id(), 0, Some(1024)) .await; - assert!(indexer.inverted_indexer.is_some()); - assert!(indexer.fulltext_indexer.is_some()); - assert!(indexer.bloom_filter_indexer.is_none()); + assert!(indexer.has_kind(kind::IndexKind::Inverted)); + assert!(indexer.has_kind(kind::IndexKind::Fulltext)); + assert!(!indexer.has_kind(kind::IndexKind::Bloom)); } #[tokio::test] @@ -2038,16 +1954,18 @@ mod tests { write_cache_enabled: false, intermediate_manager: intm_manager.clone(), index_options: IndexOptions::default(), - inverted_index_config: InvertedIndexConfig::default(), - fulltext_index_config: FulltextIndexConfig::default(), - bloom_filter_index_config: BloomFilterConfig::default(), + registry: Arc::new(crate::sst::index::registry::IndexRegistry::new( + InvertedIndexConfig::default(), + FulltextIndexConfig::default(), + BloomFilterConfig::default(), + )), } .build(random_region_file_id(), 0, Some(1024)) .await; - assert!(indexer.inverted_indexer.is_none()); - assert!(indexer.fulltext_indexer.is_some()); - assert!(indexer.bloom_filter_indexer.is_some()); + assert!(!indexer.has_kind(kind::IndexKind::Inverted)); + assert!(indexer.has_kind(kind::IndexKind::Fulltext)); + assert!(indexer.has_kind(kind::IndexKind::Bloom)); let metadata = mock_region_metadata(MetaConfig { with_inverted: true, @@ -2061,16 +1979,18 @@ mod tests { write_cache_enabled: false, intermediate_manager: intm_manager.clone(), index_options: IndexOptions::default(), - inverted_index_config: InvertedIndexConfig::default(), - fulltext_index_config: FulltextIndexConfig::default(), - bloom_filter_index_config: BloomFilterConfig::default(), + registry: Arc::new(crate::sst::index::registry::IndexRegistry::new( + InvertedIndexConfig::default(), + FulltextIndexConfig::default(), + BloomFilterConfig::default(), + )), } .build(random_region_file_id(), 0, Some(1024)) .await; - assert!(indexer.inverted_indexer.is_some()); - assert!(indexer.fulltext_indexer.is_none()); - assert!(indexer.bloom_filter_indexer.is_some()); + assert!(indexer.has_kind(kind::IndexKind::Inverted)); + assert!(!indexer.has_kind(kind::IndexKind::Fulltext)); + assert!(indexer.has_kind(kind::IndexKind::Bloom)); let metadata = mock_region_metadata(MetaConfig { with_inverted: true, @@ -2084,16 +2004,18 @@ mod tests { write_cache_enabled: false, intermediate_manager: intm_manager, index_options: IndexOptions::default(), - inverted_index_config: InvertedIndexConfig::default(), - fulltext_index_config: FulltextIndexConfig::default(), - bloom_filter_index_config: BloomFilterConfig::default(), + registry: Arc::new(crate::sst::index::registry::IndexRegistry::new( + InvertedIndexConfig::default(), + FulltextIndexConfig::default(), + BloomFilterConfig::default(), + )), } .build(random_region_file_id(), 0, Some(1024)) .await; - assert!(indexer.inverted_indexer.is_some()); - assert!(indexer.fulltext_indexer.is_some()); - assert!(indexer.bloom_filter_indexer.is_none()); + assert!(indexer.has_kind(kind::IndexKind::Inverted)); + assert!(indexer.has_kind(kind::IndexKind::Fulltext)); + assert!(!indexer.has_kind(kind::IndexKind::Bloom)); } #[tokio::test] @@ -2114,14 +2036,16 @@ mod tests { write_cache_enabled: false, intermediate_manager: intm_manager, index_options: IndexOptions::default(), - inverted_index_config: InvertedIndexConfig::default(), - fulltext_index_config: FulltextIndexConfig::default(), - bloom_filter_index_config: BloomFilterConfig::default(), + registry: Arc::new(crate::sst::index::registry::IndexRegistry::new( + InvertedIndexConfig::default(), + FulltextIndexConfig::default(), + BloomFilterConfig::default(), + )), } .build(random_region_file_id(), 0, Some(0)) .await; - assert!(indexer.inverted_indexer.is_some()); + assert!(indexer.has_kind(kind::IndexKind::Inverted)); } #[tokio::test] @@ -2514,9 +2438,11 @@ mod tests { write_cache_enabled: true, intermediate_manager: write_cache.intermediate_manager().clone(), index_options: IndexOptions::default(), - inverted_index_config: InvertedIndexConfig::default(), - fulltext_index_config: FulltextIndexConfig::default(), - bloom_filter_index_config: BloomFilterConfig::default(), + registry: Arc::new(crate::sst::index::registry::IndexRegistry::new( + InvertedIndexConfig::default(), + FulltextIndexConfig::default(), + BloomFilterConfig::default(), + )), }); let sst_info = mock_sst_file(metadata.clone(), &env, IndexBuildMode::Async).await; diff --git a/src/mito2/src/sst/index/bloom_filter/applier.rs b/src/mito2/src/sst/index/bloom_filter/applier.rs index 0f97e89a0fa..eacf1f0202b 100644 --- a/src/mito2/src/sst/index/bloom_filter/applier.rs +++ b/src/mito2/src/sst/index/bloom_filter/applier.rs @@ -29,6 +29,7 @@ use index::bloom_filter::reader::{ use index::target::IndexTarget; use object_store::ObjectStore; use puffin::puffin_manager::cache::PuffinMetadataCacheRef; +use puffin::puffin_manager::file_key::PuffinFileKey; use puffin::puffin_manager::{PuffinManager, PuffinReader}; use snafu::ResultExt; use store_api::metadata::RegionMetadataRef; @@ -47,7 +48,8 @@ use crate::metrics::INDEX_APPLY_ELAPSED; use crate::sst::file::RegionIndexId; use crate::sst::index::bloom_filter::INDEX_BLOB_TYPE; pub use crate::sst::index::bloom_filter::applier::builder::BloomFilterIndexApplierBuilder; -use crate::sst::index::puffin_manager::{BlobReader, PuffinManagerFactory}; +use crate::sst::index::column::skipping_target_data_type; +use crate::sst::index::puffin_manager::{BlobReader, PuffinManagerFactory, SstPuffinManager}; use crate::sst::index::{TYPE_BLOOM_FILTER_INDEX, trigger_index_background_download}; /// Metrics for tracking bloom filter index apply operations. @@ -125,6 +127,10 @@ pub struct BloomFilterIndexApplier { /// Factory to create puffin manager. puffin_manager_factory: PuffinManagerFactory, + /// Managers keep backend identity resolution out of per-blob reads. + remote_puffin_manager: SstPuffinManager, + cached_puffin_manager: Option, + /// Cache for puffin metadata. puffin_metadata_cache: Option, @@ -151,6 +157,10 @@ impl BloomFilterIndexApplier { predicates: BTreeMap>, expected_predicate_target_types: BTreeMap, ) -> Self { + let remote_puffin_manager = puffin_manager_factory.build( + object_store.clone(), + RegionFilePathFactory::new(table_dir.clone(), path_type), + ); let default_predicates = Arc::new(predicates); Self { table_dir, @@ -158,6 +168,8 @@ impl BloomFilterIndexApplier { object_store, file_cache: None, puffin_manager_factory, + remote_puffin_manager, + cached_puffin_manager: None, puffin_metadata_cache: None, bloom_filter_index_cache: None, default_predicates, @@ -166,6 +178,13 @@ impl BloomFilterIndexApplier { } pub fn with_file_cache(mut self, file_cache: Option) -> Self { + self.cached_puffin_manager = file_cache.as_ref().map(|cache| { + self.puffin_manager_factory.build_cached( + &self.remote_puffin_manager, + cache.local_store(), + WriteCachePathProvider::new(cache.clone()), + ) + }); self.file_cache = file_cache; self } @@ -232,9 +251,9 @@ impl BloomFilterIndexApplier { .map(|(i, range)| (*i, vec![range.clone()])) .collect::>(); - for (column_id, predicates) in predicates { - let blob = match self - .blob_reader(file_id, column_id, file_size_hint, metrics.as_deref_mut()) + for (target, predicates) in predicates { + let (file_key, blob) = match self + .blob_reader(file_id, target, file_size_hint, metrics.as_deref_mut()) .await? { Some(blob) => blob, @@ -248,9 +267,8 @@ impl BloomFilterIndexApplier { m.blob_read_bytes += blob_size; } let reader = CachedBloomFilterIndexBlobReader::new( - file_id.file_id(), - file_id.version, - column_id.clone(), + file_key, + target.clone(), Tag::Skipping, blob_size, BloomFilterReaderImpl::new(blob), @@ -291,16 +309,16 @@ impl BloomFilterIndexApplier { /// Creates a blob reader from the cached or remote index file. /// - /// Returus `None` if the column does not have an index. + /// Returns `None` if the target does not have an index. async fn blob_reader( &self, file_id: RegionIndexId, - column_id: &IndexTarget, + target: &IndexTarget, file_size_hint: Option, metrics: Option<&mut BloomFilterIndexApplyMetrics>, - ) -> Result> { + ) -> Result, BlobReader)>> { let reader = match self - .cached_blob_reader(file_id, column_id, file_size_hint) + .cached_blob_reader(file_id, target, file_size_hint) .await { Ok(Some(puffin_reader)) => puffin_reader, @@ -309,17 +327,17 @@ impl BloomFilterIndexApplier { m.blob_cache_miss += 1; } if let Err(err) = other { - // Blob not found means no index for this column + // Blob not found means no index for this target. if is_blob_not_found(&err) { return Ok(None); } warn!(err; "An unexpected error occurred while reading the cached index file. Fallback to remote index file.") } let res = self - .remote_blob_reader(file_id, column_id, file_size_hint) + .remote_blob_reader(file_id, target, file_size_hint) .await; if let Err(err) = res { - // Blob not found means no index for this column + // Blob not found means no index for this target. if is_blob_not_found(&err) { return Ok(None); } @@ -337,10 +355,12 @@ impl BloomFilterIndexApplier { async fn cached_blob_reader( &self, file_id: RegionIndexId, - column_id: &IndexTarget, + target: &IndexTarget, file_size_hint: Option, - ) -> Result> { - let Some(file_cache) = &self.file_cache else { + ) -> Result, BlobReader)>> { + let (Some(file_cache), Some(puffin_manager)) = + (&self.file_cache, &self.cached_puffin_manager) + else { return Ok(None); }; @@ -353,11 +373,7 @@ impl BloomFilterIndexApplier { return Ok(None); }; - let puffin_manager = self.puffin_manager_factory.build( - file_cache.local_store(), - WriteCachePathProvider::new(file_cache.clone()), - ); - let blob_name = Self::target_blob_name(column_id); + let blob_name = Self::target_blob_name(target); let reader = puffin_manager .reader(&file_id) @@ -370,12 +386,12 @@ impl BloomFilterIndexApplier { .reader() .await .context(PuffinBuildReaderSnafu)?; - Ok(Some(reader)) + Ok(Some((puffin_manager.file_key(&file_id), reader))) } // TODO(ruihang): use the same util with the code in creator - fn target_blob_name(column_id: &IndexTarget) -> String { - let target_key = column_id.encode(); + fn target_blob_name(target: &IndexTarget) -> String { + let target_key = target.encode(); format!("{INDEX_BLOB_TYPE}-{target_key}") } @@ -383,9 +399,9 @@ impl BloomFilterIndexApplier { async fn remote_blob_reader( &self, file_id: RegionIndexId, - column_id: &IndexTarget, + target: &IndexTarget, file_size_hint: Option, - ) -> Result { + ) -> Result<(PuffinFileKey, BlobReader)> { let path_factory = RegionFilePathFactory::new(self.table_dir.clone(), self.path_type); // Trigger background download if file cache and file size are available @@ -398,13 +414,13 @@ impl BloomFilterIndexApplier { ); let puffin_manager = self - .puffin_manager_factory - .build(self.object_store.clone(), path_factory) + .remote_puffin_manager + .clone() .with_puffin_metadata_cache(self.puffin_metadata_cache.clone()); - let blob_name = Self::target_blob_name(column_id); + let blob_name = Self::target_blob_name(target); - puffin_manager + let reader = puffin_manager .reader(&file_id) .await .context(PuffinBuildReaderSnafu)? @@ -414,7 +430,8 @@ impl BloomFilterIndexApplier { .context(PuffinReadBlobSnafu)? .reader() .await - .context(PuffinBuildReaderSnafu) + .context(PuffinBuildReaderSnafu)?; + Ok((puffin_manager.file_key(&file_id), reader)) } async fn apply_predicates( @@ -440,19 +457,17 @@ impl BloomFilterIndexApplier { sst_metadata: &RegionMetadataRef, ) -> Option>>> { let mut has_type_mismatch = false; - let mut compatible_col_ids = Vec::new(); + let mut compatible_targets = Vec::new(); - for (col_id, expected) in &self.expected_predicate_target_types { - if crate::sst::index::column::skipping_target_data_type(sst_metadata, col_id).as_ref() - != Some(expected) - { + for (target, expected) in &self.expected_predicate_target_types { + if skipping_target_data_type(sst_metadata, target).as_ref() != Some(expected) { has_type_mismatch = true; continue; } - compatible_col_ids.push(col_id.clone()); + compatible_targets.push(target.clone()); } - if compatible_col_ids.is_empty() { + if compatible_targets.is_empty() { return None; } @@ -461,9 +476,9 @@ impl BloomFilterIndexApplier { } let mut compatible_predicates = BTreeMap::new(); - for col_id in compatible_col_ids { - if let Some(predicates) = self.default_predicates.get(&col_id) { - compatible_predicates.insert(col_id, predicates.clone()); + for target in compatible_targets { + if let Some(predicates) = self.default_predicates.get(&target) { + compatible_predicates.insert(target, predicates.clone()); } } @@ -531,6 +546,7 @@ mod tests { path: vec!["value".into()], data_type: ConcreteDataType::int64_datatype(), inverted_index: false, + fulltext_index: None, skipping_index: Some( SkippingIndexOptions::new(2, 0.01, Default::default()).unwrap(), ), diff --git a/src/mito2/src/sst/index/bloom_filter/applier/builder.rs b/src/mito2/src/sst/index/bloom_filter/applier/builder.rs index 29012c951f8..97e9e96d5af 100644 --- a/src/mito2/src/sst/index/bloom_filter/applier/builder.rs +++ b/src/mito2/src/sst/index/bloom_filter/applier/builder.rs @@ -35,6 +35,7 @@ use crate::cache::file_cache::FileCacheRef; use crate::cache::index::bloom_filter_index::BloomFilterIndexCacheRef; use crate::error::{ColumnNotFoundSnafu, ConvertValueSnafu, EncodeSnafu, Result}; use crate::sst::index::bloom_filter::applier::BloomFilterIndexApplier; +use crate::sst::index::column::{json_index_target, skipping_target_data_type}; use crate::sst::index::puffin_manager::PuffinManagerFactory; pub struct BloomFilterIndexApplierBuilder<'a> { @@ -143,15 +144,14 @@ impl<'a> BloomFilterIndexApplierBuilder<'a> { fn expected_predicate_target_types(&self) -> BTreeMap { self.predicates .keys() - .filter_map(|col_id| { - let ty = - crate::sst::index::column::skipping_target_data_type(self.metadata, col_id)?; - Some((col_id.clone(), ty)) + .filter_map(|target| { + let ty = skipping_target_data_type(self.metadata, target)?; + Some((target.clone(), ty)) }) .collect() } - /// Helper function to get the column id and type + /// Returns a column target and its type. fn column_target_and_type( &self, column_name: &str, @@ -173,9 +173,7 @@ impl<'a> BloomFilterIndexApplierBuilder<'a> { if let Expr::Column(column) = expr { return self.column_target_and_type(&column.name); } - crate::sst::index::column::json_index_target(self.metadata, expr, |hint| { - hint.skipping_index.is_some() - }) + json_index_target(self.metadata, expr, |hint| hint.skipping_index.is_some()) } /// Collects an equality expression (column = value) @@ -186,12 +184,12 @@ impl<'a> BloomFilterIndexApplierBuilder<'a> { if lit.is_null() { return Ok(()); } - let Some((column_id, data_type)) = self.expr_to_index_target(col)? else { + let Some((target, data_type)) = self.expr_to_index_target(col)? else { return Ok(()); }; let value = encode_lit(lit, data_type)?; self.predicates - .entry(column_id) + .entry(target) .or_default() .push(InListPredicate { list: BTreeSet::from([value]), @@ -206,7 +204,7 @@ impl<'a> BloomFilterIndexApplierBuilder<'a> { return Ok(()); } - let Some((column_id, data_type)) = self.expr_to_index_target(&in_list.expr)? else { + let Some((target, data_type)) = self.expr_to_index_target(&in_list.expr)? else { return Ok(()); }; @@ -222,7 +220,7 @@ impl<'a> BloomFilterIndexApplierBuilder<'a> { if !valid_predicates.is_empty() { self.predicates - .entry(column_id) + .entry(target) .or_default() .push(InListPredicate { list: valid_predicates, @@ -258,7 +256,7 @@ impl<'a> BloomFilterIndexApplierBuilder<'a> { if lit.is_null() { return Ok(()); } - let Some((column_id, data_type)) = self.expr_to_index_target(col)? else { + let Some((target, data_type)) = self.expr_to_index_target(col)? else { return Ok(()); }; @@ -266,7 +264,7 @@ impl<'a> BloomFilterIndexApplierBuilder<'a> { inlist.insert(encode_lit(lit, data_type.clone())?); if Self::collect_or_eq_list_rec(col, &data_type, or_list, &mut inlist)? { self.predicates - .entry(column_id) + .entry(target) .or_default() .push(InListPredicate { list: inlist }); } diff --git a/src/mito2/src/sst/index/bloom_filter/creator.rs b/src/mito2/src/sst/index/bloom_filter/creator.rs index cc96e596866..a694c822b03 100644 --- a/src/mito2/src/sst/index/bloom_filter/creator.rs +++ b/src/mito2/src/sst/index/bloom_filter/creator.rs @@ -84,12 +84,34 @@ pub struct BloomFilterIndexer { impl BloomFilterIndexer { /// Creates a new bloom filter indexer. /// JSON paths are included only for flush and compaction builds. + #[cfg(any(test, feature = "testing"))] pub fn new( sst_file_id: FileId, metadata: &RegionMetadataRef, intermediate_manager: IntermediateManager, memory_usage_threshold: Option, build_type: IndexBuildType, + ) -> Result> { + let mut targets = Vec::new(); + for column in &metadata.column_metadatas { + targets.extend(Self::targets(column, &build_type)?); + } + Self::new_with_targets( + sst_file_id, + metadata, + intermediate_manager, + memory_usage_threshold, + targets, + ) + } + + /// Creates one file-level creator from already resolved targets. + pub(crate) fn new_with_targets( + sst_file_id: FileId, + metadata: &RegionMetadataRef, + intermediate_manager: IntermediateManager, + memory_usage_threshold: Option, + targets: Vec<(IndexTarget, datatypes::schema::SkippingIndexOptions)>, ) -> Result> { let mut creators = HashMap::new(); @@ -99,48 +121,15 @@ impl BloomFilterIndexer { )); let global_memory_usage = Arc::new(AtomicUsize::new(0)); - for column in &metadata.column_metadatas { - let options = - column - .column_schema - .skipping_index_options() - .context(IndexOptionsSnafu { - column_name: &column.column_schema.name, - })?; - - let mut targets = Vec::new(); - if let Some(options) = options { - targets.push((IndexTarget::ColumnId(column.column_id), options)); - } - // Only flush and compaction builds collect JSON targets; manual and schema-change - // rebuilds skip them because existing SSTs may not materialize the current hints. - // FIXME: Rebuilds replace the whole Puffin file and can drop existing JSON path indexes. - if matches!(build_type, IndexBuildType::Flush | IndexBuildType::Compact) - && column.column_schema.data_type.is_json2() - && let Ok(Some(extension)) = - column.column_schema.extension_type::() - { - for hint in extension.metadata().json_settings().type_hints() { - let Some(options) = &hint.skipping_index else { - continue; - }; - if let Ok(target) = - IndexTarget::new_json_path(column.column_id, hint.path.clone()) - { - targets.push((target, options.clone())); - } - } - } - for (target, options) in targets { - let creator = BloomFilterCreator::new( - options.granularity as _, - options.false_positive_rate(), - temp_file_provider.clone(), - global_memory_usage.clone(), - memory_usage_threshold, - ); - creators.insert(target, creator); - } + for (target, options) in targets { + let creator = BloomFilterCreator::new( + options.granularity as _, + options.false_positive_rate(), + temp_file_provider.clone(), + global_memory_usage.clone(), + memory_usage_threshold, + ); + creators.insert(target, creator); } if creators.is_empty() { @@ -165,6 +154,42 @@ impl BloomFilterIndexer { Ok(Some(indexer)) } + /// Resolves all targets of one column without creating index state. + pub(crate) fn targets( + column: &store_api::metadata::ColumnMetadata, + build_type: &IndexBuildType, + ) -> Result> { + let options = column + .column_schema + .skipping_index_options() + .context(IndexOptionsSnafu { + column_name: &column.column_schema.name, + })?; + + let mut targets = Vec::new(); + if let Some(options) = options { + targets.push((IndexTarget::ColumnId(column.column_id), options)); + } + // Only flush and compaction builds collect JSON targets; manual and schema-change + // rebuilds skip them because existing SSTs may not materialize the current hints. + // FIXME: Rebuilds replace the whole Puffin file and can drop existing JSON path indexes. + if matches!(build_type, IndexBuildType::Flush | IndexBuildType::Compact) + && column.column_schema.data_type.is_json2() + && let Ok(Some(extension)) = column.column_schema.extension_type::() + { + for hint in extension.metadata().json_settings().type_hints() { + let Some(options) = &hint.skipping_index else { + continue; + }; + if let Ok(target) = IndexTarget::new_json_path(column.column_id, hint.path.clone()) + { + targets.push((target, options.clone())); + } + } + } + Ok(targets) + } + /// Updates index with a batch of rows. /// Garbage will be cleaned up if failed to update. /// diff --git a/src/mito2/src/sst/index/column.rs b/src/mito2/src/sst/index/column.rs index ea1993fc33c..b892cd4436c 100644 --- a/src/mito2/src/sst/index/column.rs +++ b/src/mito2/src/sst/index/column.rs @@ -20,13 +20,15 @@ use datatypes::arrow::array::{Array, ArrayRef, StructArray}; use datatypes::arrow::record_batch::RecordBatch; use datatypes::data_type::{ConcreteDataType, DataType}; use datatypes::extension::json::Json2ExtensionType; +use datatypes::json::JsonTypeHint; +use datatypes::schema::FulltextOptions; use datatypes::vectors::{Helper, VectorRef}; use index::target::IndexTarget; use snafu::{OptionExt, ResultExt}; use store_api::metadata::RegionMetadata; use store_api::storage::consts::PRIMARY_KEY_COLUMN_NAME; -use crate::error::{ConvertVectorSnafu, InvalidRecordBatchSnafu, Result}; +use crate::error::{ConvertVectorSnafu, IndexOptionsSnafu, InvalidRecordBatchSnafu, Result}; use crate::sst::parquet::format::PrimaryKeyArray; /// Extracts leaf values for a JSON type hint at the given path. @@ -94,7 +96,7 @@ pub(crate) fn column_index_rows( pub(crate) fn json_index_target( metadata: &RegionMetadata, expr: &Expr, - enabled: impl Fn(&datatypes::json::JsonTypeHint) -> bool, + enabled: impl Fn(&JsonTypeHint) -> bool, ) -> Result> { let Expr::ScalarFunction(func) = expr else { return Ok(None); @@ -193,6 +195,54 @@ pub(crate) fn skipping_target_data_type( .map(|hint| hint.data_type.clone()) } +/// Resolves enabled fulltext options using a column or string hint's metadata. +pub(crate) fn fulltext_target_options( + metadata: &RegionMetadata, + target: &IndexTarget, +) -> Result> { + let path = match target { + IndexTarget::ColumnId(id) => { + let Some(column) = metadata.column_by_id(*id) else { + return Ok(None); + }; + if !column.column_schema.data_type.is_string() { + return Ok(None); + } + return column + .column_schema + .fulltext_options() + .with_context(|_| IndexOptionsSnafu { + column_name: &column.column_schema.name, + }) + .map(|options| options.filter(|options| options.enable)); + } + IndexTarget::JsonPath(path) => path, + }; + let Some(column) = metadata.column_by_id(path.column_id()) else { + return Ok(None); + }; + if !column.column_schema.data_type.is_json2() { + return Ok(None); + } + let Some(extension) = column + .column_schema + .extension_type::() + .with_context(|_| IndexOptionsSnafu { + column_name: &column.column_schema.name, + })? + else { + return Ok(None); + }; + Ok(extension + .metadata() + .json_settings() + .type_hints() + .iter() + .find(|hint| hint.path == path.path() && hint.data_type.is_string()) + .and_then(|hint| hint.fulltext_index.clone()) + .filter(|options| options.enable)) +} + #[cfg(test)] mod tests { use std::sync::Arc; @@ -200,10 +250,49 @@ mod tests { use datatypes::arrow::array::{Int64Array, NullArray}; use datatypes::arrow::buffer::NullBuffer; use datatypes::arrow::datatypes::Field; + use datatypes::schema::{ColumnSchema, FulltextOptions}; use datatypes::value::Value; + use store_api::metadata::{ColumnMetadata, RegionMetadataBuilder}; + use store_api::storage::RegionId; use super::*; + #[test] + fn test_fulltext_target_options_requires_string_column() { + let options = FulltextOptions { + enable: true, + ..Default::default() + }; + for data_type in [ + ConcreteDataType::string_datatype(), + ConcreteDataType::int64_datatype(), + ] { + let expected = data_type.is_string().then_some(options.clone()); + let mut builder = RegionMetadataBuilder::new(RegionId::new(1, 1)); + builder.push_column_metadata(ColumnMetadata { + column_schema: ColumnSchema::new("value", data_type, true) + .with_fulltext_options(options.clone()) + .unwrap(), + column_id: 1, + semantic_type: SemanticType::Field, + }); + builder.push_column_metadata(ColumnMetadata { + column_schema: ColumnSchema::new( + "ts", + ConcreteDataType::timestamp_millisecond_datatype(), + false, + ), + column_id: 2, + semantic_type: SemanticType::Timestamp, + }); + let metadata = builder.build().unwrap(); + assert_eq!( + fulltext_target_options(&metadata, &IndexTarget::ColumnId(1)).unwrap(), + expected + ); + } + } + #[test] fn test_extract_json_type_hint_values_null_type() { let nulls: ArrayRef = Arc::new(NullArray::new(2)); diff --git a/src/mito2/src/sst/index/column_test.rs b/src/mito2/src/sst/index/column_test.rs index fb7677eff58..db6e3f58dd4 100644 --- a/src/mito2/src/sst/index/column_test.rs +++ b/src/mito2/src/sst/index/column_test.rs @@ -196,9 +196,11 @@ async fn materialized_runs_match_legacy_index_bytes_and_bloom_lookups() { .await .unwrap(), index_options: options, - inverted_index_config: Default::default(), - fulltext_index_config: Default::default(), - bloom_filter_index_config: Default::default(), + registry: Arc::new(crate::sst::index::registry::IndexRegistry::new( + Default::default(), + Default::default(), + Default::default(), + )), }; let mut expected = None; // Demand is the union of active creators' PK columns, not their counts or @@ -227,7 +229,14 @@ async fn materialized_runs_match_legacy_index_bytes_and_bloom_lookups() { let mut case_builder = builder.clone(); case_builder.metadata = Arc::new(case_metadata.build().unwrap()); if disable_bloom { - case_builder.bloom_filter_index_config.create_on_flush = crate::config::Mode::Disable; + case_builder.registry = Arc::new(crate::sst::index::registry::IndexRegistry::new( + Default::default(), + Default::default(), + crate::config::BloomFilterConfig { + create_on_flush: crate::config::Mode::Disable, + ..Default::default() + }, + )); } let mut indexer = case_builder .build( @@ -313,8 +322,7 @@ async fn materialized_runs_match_legacy_index_bytes_and_bloom_lookups() { } } let output = indexer.finish().await; - assert_eq!(output.inverted_index.row_count, batch.num_rows(), "{mode}"); - assert_eq!(output.bloom_filter.row_count, batch.num_rows(), "{mode}"); + assert!(output.file_size > 0, "{mode}"); let reader = puffin.reader(&RegionIndexId::new(file, 0)).await.unwrap(); let blob = reader.blob("greptime-inverted-index-v1").await.unwrap(); let inverted = InvertedIndexBlobReader::new(blob.reader().await.unwrap()); diff --git a/src/mito2/src/sst/index/fulltext_index/applier.rs b/src/mito2/src/sst/index/fulltext_index/applier.rs index 792c6319f85..7fb551ff72a 100644 --- a/src/mito2/src/sst/index/fulltext_index/applier.rs +++ b/src/mito2/src/sst/index/fulltext_index/applier.rs @@ -21,6 +21,7 @@ use std::time::Instant; use common_base::range_read::RangeReader; use common_base::term_token::{extract_like_probes, extract_term_probes}; use common_telemetry::{tracing, warn}; +use datatypes::schema::{FulltextBackend, FulltextOptions}; use index::bloom_filter::applier::{BloomFilterApplier, InListPredicate}; use index::bloom_filter::reader::{BloomFilterReadMetrics, BloomFilterReaderImpl}; use index::fulltext_index::Config; @@ -28,27 +29,28 @@ use index::fulltext_index::search::{FulltextIndexSearcher, RowId, TantivyFulltex use index::target::IndexTarget; use object_store::ObjectStore; use puffin::puffin_manager::cache::PuffinMetadataCacheRef; +use puffin::puffin_manager::file_key::PuffinFileKey; use puffin::puffin_manager::{GuardWithMetadata, PuffinManager, PuffinReader}; use snafu::ResultExt; +use store_api::metadata::RegionMetadata; use store_api::region_request::PathType; -use store_api::storage::ColumnId; use crate::access_layer::{RegionFilePathFactory, WriteCachePathProvider}; use crate::cache::file_cache::{FileCacheRef, FileType, IndexKey}; use crate::cache::index::bloom_filter_index::{ BloomFilterIndexCacheRef, CachedBloomFilterIndexBlobReader, Tag, }; -use crate::cache::index::result_cache::PredicateKey; use crate::error::{ ApplyBloomFilterIndexSnafu, ApplyFulltextIndexSnafu, MetadataSnafu, PuffinBuildReaderSnafu, PuffinReadBlobSnafu, Result, }; use crate::metrics::INDEX_APPLY_ELAPSED; use crate::sst::file::RegionIndexId; +use crate::sst::index::column::fulltext_target_options; use crate::sst::index::fulltext_index::applier::builder::FulltextRequest; use crate::sst::index::fulltext_index::{INDEX_BLOB_TYPE_BLOOM, INDEX_BLOB_TYPE_TANTIVY}; use crate::sst::index::puffin_manager::{ - PuffinManagerFactory, SstPuffinBlob, SstPuffinDir, SstPuffinReader, + PuffinManagerFactory, SstPuffinBlob, SstPuffinDir, SstPuffinManager, SstPuffinReader, }; use crate::sst::index::{TYPE_FULLTEXT_INDEX, trigger_index_background_download}; @@ -146,16 +148,16 @@ impl FulltextIndexApplyMetrics { /// `FulltextIndexApplier` is responsible for applying fulltext index to the provided SST files pub struct FulltextIndexApplier { /// Requests to be applied. - requests: Arc>, + requests: Arc>, + + /// Expected fulltext settings from the current schema. + expected_options: BTreeMap, /// The source of the index. index_source: IndexSource, /// Cache for bloom filter index. bloom_filter_index_cache: Option, - - /// Predicate key. Used to identify the predicate and fetch result from cache. - predicate_key: PredicateKey, } pub type FulltextIndexApplierRef = Arc; @@ -166,20 +168,56 @@ impl FulltextIndexApplier { table_dir: String, path_type: PathType, store: ObjectStore, - requests: BTreeMap, + requests: BTreeMap, puffin_manager_factory: PuffinManagerFactory, + metadata: &RegionMetadata, ) -> Self { + let expected_options = requests + .keys() + .filter_map(|target| { + fulltext_target_options(metadata, target) + .inspect_err(|err| warn!(err; "Failed to resolve expected fulltext options for {target:?}")) + .ok() + .flatten() + .map(|options| (target.clone(), options)) + }) + .collect(); let requests = Arc::new(requests); let index_source = IndexSource::new(table_dir, path_type, puffin_manager_factory, store); Self { - predicate_key: PredicateKey::new_fulltext(requests.clone()), requests, + expected_options, index_source, bloom_filter_index_cache: None, } } + /// Keeps ordinary string columns and JSON paths with compatible saved fulltext settings. + /// Returns `None` when no compatible request remains for this SST. + pub fn compatible_requests_for_sst( + &self, + metadata: &RegionMetadata, + ) -> Option>> { + if self + .requests + .keys() + .all(|target| self.is_target_compatible(metadata, target)) + { + return Some(self.requests.clone()); + } + let requests: BTreeMap<_, _> = self + .requests + .iter() + .filter(|(target, _)| self.is_target_compatible(metadata, target)) + .map(|(target, request)| (target.clone(), request.clone())) + .collect(); + if requests.is_empty() { + return None; + } + Some(Arc::new(requests)) + } + /// Sets the file cache. pub fn with_file_cache(mut self, file_cache: Option) -> Self { self.index_source.set_file_cache(file_cache); @@ -205,9 +243,28 @@ impl FulltextIndexApplier { self } - /// Returns the predicate key. - pub fn predicate_key(&self) -> &PredicateKey { - &self.predicate_key + fn is_target_compatible(&self, metadata: &RegionMetadata, target: &IndexTarget) -> bool { + let Some(expected) = self.expected_options.get(target) else { + return false; + }; + if let IndexTarget::ColumnId(id) = target { + // Rebuilding an ordinary column's index does not update Parquet metadata. + // Check only its type here; index readers use the actual blob's config. + return metadata + .column_by_id(*id) + .is_some_and(|column| column.column_schema.data_type.is_string()); + } + let Some(actual) = fulltext_target_options(metadata, target) + .inspect_err(|err| warn!(err; "Failed to resolve SST fulltext options for {target:?}")) + .ok() + .flatten() + else { + return false; + }; + // JSON path hints can change backend, case sensitivity, and analyzer. + expected.backend == actual.backend + && expected.case_sensitive == actual.case_sensitive + && (expected.backend == FulltextBackend::Bloom || expected.analyzer == actual.analyzer) } } @@ -218,6 +275,7 @@ impl FulltextIndexApplier { /// # Arguments /// * `file_id` - The region file ID to apply predicates to /// * `file_size_hint` - Optional hint for file size to avoid extra metadata reads + /// * `requests` - Compatible requests for this SST /// * `metrics` - Optional mutable reference to collect metrics on demand #[tracing::instrument( skip_all, @@ -227,12 +285,13 @@ impl FulltextIndexApplier { &self, file_id: RegionIndexId, file_size_hint: Option, + requests: &BTreeMap, mut metrics: Option<&mut FulltextIndexApplyMetrics>, ) -> Result>> { let apply_start = Instant::now(); let mut row_ids: Option> = None; - for (column_id, request) in self.requests.iter() { + for (target, request) in requests.iter() { // Tantivy tokens don't follow `matches_term` boundaries, e.g. `SimpleTokenizer` // keeps "错误error日志" as one token, so terms and patterns are left to the // bloom backend. @@ -244,7 +303,7 @@ impl FulltextIndexApplier { .apply_fine_one_column( file_size_hint, file_id, - *column_id, + target, request, metrics.as_deref_mut(), ) @@ -283,11 +342,11 @@ impl FulltextIndexApplier { &self, file_size_hint: Option, file_id: RegionIndexId, - column_id: ColumnId, + target: &IndexTarget, request: &FulltextRequest, metrics: Option<&mut FulltextIndexApplyMetrics>, ) -> Result>> { - let target_key = IndexTarget::ColumnId(column_id).encode(); + let target_key = target.encode(); let blob_key = format!("{INDEX_BLOB_TYPE_TANTIVY}-{target_key}"); let dir = self .index_source @@ -342,6 +401,7 @@ impl FulltextIndexApplier { /// * `file_id` - The region file ID to apply predicates to /// * `file_size_hint` - Optional hint for file size to avoid extra metadata reads /// * `row_groups` - Iterator of row group lengths and whether to search in the row group + /// * `requests` - Compatible requests for this SST /// * `metrics` - Optional mutable reference to collect metrics on demand #[allow(clippy::type_complexity)] #[tracing::instrument( @@ -353,6 +413,7 @@ impl FulltextIndexApplier { file_id: RegionIndexId, file_size_hint: Option, row_groups: impl Iterator, + requests: &BTreeMap, mut metrics: Option<&mut FulltextIndexApplyMetrics>, ) -> Result>)>>> { let apply_start = Instant::now(); @@ -360,7 +421,7 @@ impl FulltextIndexApplier { let (input, mut output) = Self::init_coarse_output(row_groups); let mut applied = false; - for (column_id, request) in self.requests.iter() { + for (target, request) in requests.iter() { if request.terms.is_empty() && request.likes.is_empty() { continue; } @@ -369,7 +430,7 @@ impl FulltextIndexApplier { .apply_coarse_one_column( file_id, file_size_hint, - *column_id, + target, request, &mut output, metrics.as_deref_mut(), @@ -400,14 +461,14 @@ impl FulltextIndexApplier { &self, file_id: RegionIndexId, file_size_hint: Option, - column_id: ColumnId, + target: &IndexTarget, request: &FulltextRequest, output: &mut [(usize, Vec>)], mut metrics: Option<&mut FulltextIndexApplyMetrics>, ) -> Result { - let target_key = IndexTarget::ColumnId(column_id).encode(); + let target_key = target.encode(); let blob_key = format!("{INDEX_BLOB_TYPE_BLOOM}-{target_key}"); - let Some(reader) = self + let Some((file_key, reader)) = self .index_source .blob(file_id, &blob_key, file_size_hint, metrics.as_deref_mut()) .await? @@ -430,9 +491,8 @@ impl FulltextIndexApplier { .context(MetadataSnafu)? .content_length; let reader = CachedBloomFilterIndexBlobReader::new( - file_id.file_id(), - file_id.version, - IndexTarget::ColumnId(column_id), + file_key, + target.clone(), Tag::Fulltext, blob_size, BloomFilterReaderImpl::new(range_reader), @@ -542,6 +602,7 @@ impl FulltextIndexApplier { } /// The source of the index. +#[derive(Clone)] struct IndexSource { table_dir: String, @@ -551,6 +612,10 @@ struct IndexSource { /// The puffin manager factory. puffin_manager_factory: PuffinManagerFactory, + /// Managers keep backend identity resolution out of per-blob reads. + remote_puffin_manager: SstPuffinManager, + cached_puffin_manager: Option, + /// Store responsible for accessing remote index files. remote_store: ObjectStore, @@ -568,10 +633,16 @@ impl IndexSource { puffin_manager_factory: PuffinManagerFactory, remote_store: ObjectStore, ) -> Self { + let remote_puffin_manager = puffin_manager_factory.build( + remote_store.clone(), + RegionFilePathFactory::new(table_dir.clone(), path_type), + ); Self { table_dir, path_type, puffin_manager_factory, + remote_puffin_manager, + cached_puffin_manager: None, remote_store, file_cache: None, puffin_metadata_cache: None, @@ -579,6 +650,13 @@ impl IndexSource { } fn set_file_cache(&mut self, file_cache: Option) { + self.cached_puffin_manager = file_cache.as_ref().map(|cache| { + self.puffin_manager_factory.build_cached( + &self.remote_puffin_manager, + cache.local_store(), + WriteCachePathProvider::new(cache.clone()), + ) + }); self.file_cache = file_cache; } @@ -595,7 +673,12 @@ impl IndexSource { key: &str, file_size_hint: Option, metrics: Option<&mut FulltextIndexApplyMetrics>, - ) -> Result>> { + ) -> Result< + Option<( + PuffinFileKey, + GuardWithMetadata, + )>, + > { let (reader, fallbacked) = self.ensure_reader(file_id, file_size_hint).await?; // Track cache miss if fallbacked to remote @@ -605,7 +688,7 @@ impl IndexSource { let res = reader.blob(key).await; match res { - Ok(blob) => Ok(Some(blob)), + Ok(blob) => Ok(Some((reader.file_key(), blob))), Err(err) if err.is_blob_not_found() => Ok(None), Err(err) => { if fallbacked { @@ -615,7 +698,7 @@ impl IndexSource { let reader = self.build_remote(file_id, file_size_hint).await?; let res = reader.blob(key).await; match res { - Ok(blob) => Ok(Some(blob)), + Ok(blob) => Ok(Some((reader.file_key(), blob))), Err(err) if err.is_blob_not_found() => Ok(None), Err(err) => Err(err).context(PuffinReadBlobSnafu), } @@ -694,7 +777,9 @@ impl IndexSource { file_id: RegionIndexId, file_size_hint: Option, ) -> Result> { - let Some(file_cache) = &self.file_cache else { + let (Some(file_cache), Some(puffin_manager)) = + (&self.file_cache, &self.cached_puffin_manager) + else { return Ok(None); }; @@ -707,12 +792,8 @@ impl IndexSource { return Ok(None); }; - let puffin_manager = self - .puffin_manager_factory - .build( - file_cache.local_store(), - WriteCachePathProvider::new(file_cache.clone()), - ) + let puffin_manager = puffin_manager + .clone() .with_puffin_metadata_cache(self.puffin_metadata_cache.clone()); let reader = puffin_manager .reader(&file_id) @@ -739,8 +820,8 @@ impl IndexSource { ); let puffin_manager = self - .puffin_manager_factory - .build(self.remote_store.clone(), path_factory) + .remote_puffin_manager + .clone() .with_puffin_metadata_cache(self.puffin_metadata_cache.clone()); let reader = puffin_manager @@ -755,17 +836,159 @@ impl IndexSource { #[cfg(test)] mod tests { + use api::v1::SemanticType; use common_function::scalars::matches_term::MatchesTermFinder; use datatypes::arrow::array::{Scalar, StringArray}; use datatypes::arrow::compute::kernels::comparison::like; + use datatypes::data_type::ConcreteDataType; + use datatypes::extension::json::{Json2ExtensionType, JsonMetadata}; + use datatypes::json::{JsonSettings, JsonTypeHint}; + use datatypes::schema::{ColumnSchema, FulltextAnalyzer}; use index::fulltext_index::Analyzer; use index::fulltext_index::tokenizer::{self, ScriptTokenizer}; use rand::rngs::StdRng; use rand::{Rng, SeedableRng}; + use store_api::metadata::{ColumnMetadata, RegionMetadataBuilder}; + use store_api::storage::RegionId; use super::*; + use crate::cache::index::result_cache::PredicateKey; use crate::sst::index::fulltext_index::applier::builder::{FulltextLike, FulltextTerm}; + #[test] + fn test_json_fulltext_sst_compatibility() { + let (_dir, factory) = PuffinManagerFactory::new_for_test_block("json_fulltext_plan"); + let ordinary = IndexTarget::ColumnId(1); + let path = IndexTarget::new_json_path(3, vec!["message".into()]).unwrap(); + let other = IndexTarget::new_json_path(3, vec!["other".into()]).unwrap(); + let missing = IndexTarget::new_json_path(3, vec!["missing".into()]).unwrap(); + for backend in [FulltextBackend::Bloom, FulltextBackend::Tantivy] { + let options = FulltextOptions { + enable: true, + backend: backend.clone(), + ..Default::default() + }; + let metadata = json_metadata(Some(options.clone())); + let requests = BTreeMap::from([ + (ordinary.clone(), FulltextRequest::default()), + (path.clone(), FulltextRequest::default()), + (other.clone(), FulltextRequest::default()), + ]); + let applier = FulltextIndexApplier::new( + "test".into(), + PathType::Bare, + object_store::ObjectStore::new(object_store::services::Memory::default()).unwrap(), + requests, + factory.clone(), + &metadata, + ); + let unchanged = applier.compatible_requests_for_sst(&metadata).unwrap(); + assert!(Arc::ptr_eq(&unchanged, &applier.requests)); + for name in [ + "granularity", + "false_positive_rate", + "analyzer", + "case_sensitive", + "backend", + "disabled", + "missing", + ] { + let mut changed = options.clone(); + match name { + "granularity" => changed.granularity += 1, + "false_positive_rate" => changed.false_positive_rate_in_10000 += 1, + "analyzer" => changed.analyzer = FulltextAnalyzer::Chinese, + "case_sensitive" => changed.case_sensitive = true, + "backend" => { + changed.backend = if backend == FulltextBackend::Bloom { + FulltextBackend::Tantivy + } else { + FulltextBackend::Bloom + }; + } + "disabled" => changed.enable = false, + "missing" => {} + _ => unreachable!(), + } + let compatible = matches!(name, "granularity" | "false_positive_rate") + || (name == "analyzer" && backend == FulltextBackend::Bloom); + let sst = json_metadata((name != "missing").then_some(changed)); + let requests = applier.compatible_requests_for_sst(&sst).unwrap(); + assert!(requests.contains_key(&ordinary)); + assert!(requests.contains_key(&other)); + assert_eq!( + requests.contains_key(&path), + compatible, + "{backend:?}, {name}" + ); + assert_eq!(Arc::ptr_eq(&requests, &applier.requests), compatible); + assert_eq!( + PredicateKey::new_fulltext(requests) + == PredicateKey::new_fulltext(applier.requests.clone()), + compatible, + ); + } + // An unresolved query-side target must not become compatible merely + // because the expected options map has no entry for it. + let applier = FulltextIndexApplier::new( + "test".into(), + PathType::Bare, + object_store::ObjectStore::new(object_store::services::Memory::default()).unwrap(), + BTreeMap::from([(missing.clone(), FulltextRequest::default())]), + factory.clone(), + &metadata, + ); + assert!(applier.compatible_requests_for_sst(&metadata).is_none()); + // Missing current options are also fail-closed even if the SST has them. + let applier = FulltextIndexApplier::new( + "test".into(), + PathType::Bare, + object_store::ObjectStore::new(object_store::services::Memory::default()).unwrap(), + BTreeMap::from([(path.clone(), FulltextRequest::default())]), + factory.clone(), + &json_metadata(None), + ); + assert!(applier.compatible_requests_for_sst(&metadata).is_none()); + } + } + + #[test] + fn test_ordinary_fulltext_sst_compatibility() { + let (_dir, factory) = PuffinManagerFactory::new_for_test_block("ordinary_fulltext_plan"); + let metadata = mock_metadata_with_fulltext(FulltextBackend::Bloom); + let applier = FulltextIndexApplier::new( + "test".into(), + PathType::Bare, + object_store::ObjectStore::new(object_store::services::Memory::default()).unwrap(), + BTreeMap::from([(IndexTarget::ColumnId(1), FulltextRequest::default())]), + factory, + &metadata, + ); + assert!(applier.compatible_requests_for_sst(&metadata).is_some()); + assert!( + applier + .compatible_requests_for_sst(&mock_metadata_with_fulltext(FulltextBackend::Tantivy)) + .is_some() + ); + let mut non_string = metadata.clone(); + non_string.column_metadatas[0].column_schema.data_type = ConcreteDataType::int64_datatype(); + assert!(applier.compatible_requests_for_sst(&non_string).is_none()); + assert!( + applier + .compatible_requests_for_sst(&mock_metadata_without_fulltext()) + .is_some() + ); + let mut disabled = metadata.clone(); + disabled.column_metadatas[0] + .column_schema + .set_fulltext_options(&FulltextOptions { + enable: false, + ..Default::default() + }) + .unwrap(); + assert!(applier.compatible_requests_for_sst(&disabled).is_some()); + } + /// A `matches_term` or `LIKE` predicate on `col`, or on `lower(col)` when `lowered`. enum Predicate<'a> { Term(&'a str), @@ -995,4 +1218,78 @@ mod tests { } } } + pub(crate) fn json_metadata(options: Option) -> RegionMetadata { + let mut builder = RegionMetadataBuilder::from_existing(mock_metadata_with_fulltext( + FulltextBackend::Bloom, + )); + let mut column = + ColumnSchema::new("attrs", ConcreteDataType::json2(Default::default()), true); + column.with_extension_type(&Json2ExtensionType::new(Arc::new(JsonMetadata::new( + JsonSettings::try_new( + vec![ + JsonTypeHint { + path: vec!["message".into()], + data_type: ConcreteDataType::string_datatype(), + inverted_index: false, + skipping_index: None, + fulltext_index: options, + }, + JsonTypeHint { + path: vec!["other".into()], + data_type: ConcreteDataType::string_datatype(), + inverted_index: false, + skipping_index: None, + fulltext_index: Some(FulltextOptions { + enable: true, + ..Default::default() + }), + }, + ], + Some(0), + ) + .unwrap(), + )))); + builder.push_column_metadata(ColumnMetadata { + column_schema: column, + semantic_type: SemanticType::Field, + column_id: 3, + }); + builder.build().unwrap() + } + + pub(crate) fn mock_metadata_without_fulltext() -> RegionMetadata { + let mut builder = RegionMetadataBuilder::new(RegionId::new(1, 2)); + builder + .push_column_metadata(ColumnMetadata { + column_schema: ColumnSchema::new("text", ConcreteDataType::string_datatype(), true), + semantic_type: SemanticType::Field, + column_id: 1, + }) + .push_column_metadata(ColumnMetadata { + column_schema: ColumnSchema::new( + "ts", + ConcreteDataType::timestamp_millisecond_datatype(), + false, + ), + semantic_type: SemanticType::Timestamp, + column_id: 2, + }); + + builder.build().unwrap() + } + + pub(crate) fn mock_metadata_with_fulltext(backend: FulltextBackend) -> RegionMetadata { + let mut metadata = mock_metadata_without_fulltext(); + metadata.column_metadatas[0] + .column_schema + .set_fulltext_options(&FulltextOptions { + enable: true, + backend, + ..Default::default() + }) + .unwrap(); + RegionMetadataBuilder::from_existing(metadata) + .build() + .unwrap() + } } diff --git a/src/mito2/src/sst/index/fulltext_index/applier/builder.rs b/src/mito2/src/sst/index/fulltext_index/applier/builder.rs index 23122bc5416..ee3fe243f72 100644 --- a/src/mito2/src/sst/index/fulltext_index/applier/builder.rs +++ b/src/mito2/src/sst/index/fulltext_index/applier/builder.rs @@ -15,19 +15,21 @@ use std::collections::BTreeMap; use common_base::term_token::extract_like_probes; +use common_telemetry::warn; use datafusion_common::ScalarValue; use datafusion_expr::expr::{Like, ScalarFunction}; use datafusion_expr::{BinaryExpr, Expr, Operator}; use datatypes::schema::FulltextBackend; +use index::target::IndexTarget; use object_store::ObjectStore; use puffin::puffin_manager::cache::PuffinMetadataCacheRef; use store_api::metadata::RegionMetadata; use store_api::region_request::PathType; -use store_api::storage::{ColumnId, ConcreteDataType}; use crate::cache::file_cache::FileCacheRef; use crate::cache::index::bloom_filter_index::BloomFilterIndexCacheRef; use crate::error::Result; +use crate::sst::index::column::{fulltext_target_options, json_index_target}; use crate::sst::index::fulltext_index::applier::FulltextIndexApplier; use crate::sst::index::puffin_manager::PuffinManagerFactory; @@ -143,6 +145,7 @@ impl<'a> FulltextIndexApplierBuilder<'a> { self.store, requests, self.puffin_manager_factory, + self.metadata, ) .with_file_cache(self.file_cache) .with_puffin_metadata_cache(self.puffin_metadata_cache) @@ -153,135 +156,132 @@ impl<'a> FulltextIndexApplierBuilder<'a> { fn extract_requests( expr: &Expr, metadata: &'a RegionMetadata, - requests: &mut BTreeMap, + requests: &mut BTreeMap, ) { + if let Expr::BinaryExpr(BinaryExpr { + left, + op: Operator::And, + right, + }) = expr + { + Self::extract_requests(left, metadata, requests); + Self::extract_requests(right, metadata, requests); + return; + } + if let Err(err) = Self::extract_request(expr, metadata, requests) { + warn!(err; "Failed to extract fulltext index predicate from {expr}"); + } + } + + fn extract_request( + expr: &Expr, + metadata: &RegionMetadata, + requests: &mut BTreeMap, + ) -> Result<()> { match expr { - Expr::BinaryExpr(BinaryExpr { - left, - op: Operator::And, - right, - }) => { - Self::extract_requests(left, metadata, requests); - Self::extract_requests(right, metadata, requests); - } Expr::Like(like) => { - if let Some((column_id, like)) = Self::expr_to_like(metadata, like) { - requests.entry(column_id).or_default().likes.push(like); + if let Some((target, like)) = Self::expr_to_like(metadata, like)? { + requests.entry(target).or_default().likes.push(like); } } Expr::ScalarFunction(func) => { - if let Some((column_id, query)) = Self::expr_to_query(metadata, func) { - requests.entry(column_id).or_default().queries.push(query); - } else if let Some((column_id, term)) = Self::expr_to_term(metadata, func) { - requests.entry(column_id).or_default().terms.push(term); + if let Some((target, query)) = Self::expr_to_query(metadata, func)? { + requests.entry(target).or_default().queries.push(query); + } else if let Some((target, term)) = Self::expr_to_term(metadata, func)? { + requests.entry(target).or_default().terms.push(term); } } _ => {} } + Ok(()) } fn expr_to_query( metadata: &RegionMetadata, f: &ScalarFunction, - ) -> Option<(ColumnId, FulltextQuery)> { + ) -> Result> { if f.name() != "matches" { - return None; + return Ok(None); } if f.args.len() != 2 { - return None; + return Ok(None); } - let Expr::Column(c) = &f.args[0] else { - return None; - }; - let column = metadata.column_by_name(&c.name)?; - - if column.column_schema.data_type != ConcreteDataType::string_datatype() { - return None; - } - - let Expr::Literal(ScalarValue::Utf8(Some(query)), _) = &f.args[1] else { - return None; + let Some(target) = Self::index_target_from_expr(metadata, &f.args[0])? else { + return Ok(None); }; - Some((column.column_id, FulltextQuery(query.clone()))) + let Expr::Literal( + ScalarValue::Utf8(Some(query)) + | ScalarValue::LargeUtf8(Some(query)) + | ScalarValue::Utf8View(Some(query)), + _, + ) = &f.args[1] + else { + return Ok(None); + }; + + Ok(Some((target, FulltextQuery(query.clone())))) } fn expr_to_term( metadata: &RegionMetadata, f: &ScalarFunction, - ) -> Option<(ColumnId, FulltextTerm)> { + ) -> Result> { if f.name() != "matches_term" { - return None; + return Ok(None); } if f.args.len() != 2 { - return None; + return Ok(None); } - let mut lowered = false; - let column; - match &f.args[0] { - Expr::Column(c) => { - column = c; - } - Expr::ScalarFunction(f) => { - let lower_arg = Self::extract_lower_arg(f)?; - lowered = true; - if let Expr::Column(c) = lower_arg { - column = c; - } else { - return None; - } - } - _ => return None, - } - - let column = metadata.column_by_name(&column.name)?; - if column.column_schema.data_type != ConcreteDataType::string_datatype() { - return None; - } - - let Expr::Literal(ScalarValue::Utf8(Some(term)), _) = &f.args[1] else { - return None; + let (expr, lowered) = Self::unwrap_lower(&f.args[0]); + let Some(target) = Self::index_target_from_expr(metadata, expr)? else { + return Ok(None); }; - Some(( - column.column_id, + let Expr::Literal( + ScalarValue::Utf8(Some(term)) + | ScalarValue::LargeUtf8(Some(term)) + | ScalarValue::Utf8View(Some(term)), + _, + ) = &f.args[1] + else { + return Ok(None); + }; + + Ok(Some(( + target, FulltextTerm { col_lowered: lowered, term: term.clone(), }, - )) + ))) } - fn expr_to_like(metadata: &RegionMetadata, like: &Like) -> Option<(ColumnId, FulltextLike)> { + fn expr_to_like( + metadata: &RegionMetadata, + like: &Like, + ) -> Result> { // `ILIKE` uses Unicode case folding, which disagrees with the index's // `to_lowercase` on characters like 'ſ', so its probes could miss rows. if like.negated || like.case_insensitive { - return None; + return Ok(None); } // Probes assume arrow's default `\` escape. if !matches!(like.escape_char, None | Some('\\')) { - return None; + return Ok(None); } - let (c, col_lowered) = match like.expr.as_ref() { - Expr::Column(c) => (c, false), - Expr::ScalarFunction(f) => match Self::extract_lower_arg(f)? { - Expr::Column(c) => (c, true), - _ => return None, - }, - _ => return None, + let (expr, col_lowered) = Self::unwrap_lower(&like.expr); + let Some(target) = Self::index_target_from_expr(metadata, expr)? else { + return Ok(None); }; - let column = metadata.column_by_name(&c.name)?; - if column.column_schema.data_type != ConcreteDataType::string_datatype() { - return None; - } - // `LIKE` is common on unindexed columns and with patterns like '%word%' that have - // no probe; skip them instead of opening every SST's index for nothing. - let options = column.column_schema.fulltext_options().ok()??; - if !options.enable || options.backend != FulltextBackend::Bloom { - return None; + let Some(options) = fulltext_target_options(metadata, &target)? else { + return Ok(None); + }; + if options.backend != FulltextBackend::Bloom { + return Ok(None); } let Expr::Literal( @@ -291,19 +291,57 @@ impl<'a> FulltextIndexApplierBuilder<'a> { _, ) = like.pattern.as_ref() else { - return None; + return Ok(None); }; if extract_like_probes(pattern).is_empty() { - return None; + return Ok(None); } - Some(( - column.column_id, + Ok(Some(( + target, FulltextLike { col_lowered, pattern: pattern.clone(), }, - )) + ))) + } + + /// Resolves a column reference or JSON path expression to a single index target. + /// Returns `None` for unsupported expressions without traversing their children. + fn index_target_from_expr( + metadata: &RegionMetadata, + expr: &Expr, + ) -> Result> { + if let Expr::Column(col) = expr { + let Some(col) = metadata.column_by_name(&col.name) else { + return Ok(None); + }; + if !col.column_schema.data_type.is_string() { + return Ok(None); + } + let target = IndexTarget::ColumnId(col.column_id); + return Ok(fulltext_target_options(metadata, &target)?.map(|_| target)); + } + let Some((target, ty)) = json_index_target(metadata, expr, |hint| { + hint.fulltext_index + .as_ref() + .is_some_and(|options| options.enable) + })? + else { + return Ok(None); + }; + Ok(ty.is_string().then_some(target)) + } + + /// Returns the inner expression and `true` for `lower(expr)`, or the original + /// expression and `false` otherwise. + fn unwrap_lower(expr: &Expr) -> (&Expr, bool) { + if let Expr::ScalarFunction(func) = expr + && let Some(inner) = Self::extract_lower_arg(func) + { + return (inner, true); + } + (expr, false) } fn extract_lower_arg(lower_func: &ScalarFunction) -> Option<&Expr> { @@ -315,10 +353,6 @@ impl<'a> FulltextIndexApplierBuilder<'a> { return None; } - if lower_func.args.len() != 1 { - return None; - } - Some(&lower_func.args[0]) } } @@ -327,40 +361,125 @@ impl<'a> FulltextIndexApplierBuilder<'a> { mod tests { use std::sync::Arc; - use api::v1::SemanticType; use common_function::function::FunctionRef; use common_function::function_factory::ScalarFunctionFactory; + use common_function::scalars::json::json_get::JsonGetWithType; use common_function::scalars::matches::MatchesFunction; use common_function::scalars::matches_term::MatchesTermFunction; + use common_function::scalars::udf::create_udf; use datafusion::functions::string::lower; use datafusion_common::Column; use datafusion_expr::expr::{Like, ScalarFunction}; use datafusion_expr::{Literal, ScalarUDF}; - use datatypes::schema::{ColumnSchema, FulltextAnalyzer, FulltextOptions}; - use store_api::metadata::{ColumnMetadata, RegionMetadataBuilder}; - use store_api::storage::RegionId; + use datatypes::schema::{FULLTEXT_KEY, FulltextOptions}; + use store_api::metadata::RegionMetadataBuilder; use super::*; + use crate::sst::index::fulltext_index::applier::tests::{ + json_metadata, mock_metadata_with_fulltext, mock_metadata_without_fulltext, + }; + + #[test] + fn test_json_fulltext_predicate_extraction() { + let options = FulltextOptions { + enable: true, + ..Default::default() + }; + let metadata = json_metadata(Some(options)); + let target = IndexTarget::new_json_path(3, vec!["message".into()]).unwrap(); + for literal in [ + ScalarValue::Utf8(Some("error timeout".into())), + ScalarValue::LargeUtf8(Some("error timeout".into())), + ScalarValue::Utf8View(Some("error timeout".into())), + ] { + let expr = json_expr("$.message", Some(ScalarValue::Utf8View(None))); + let query = ScalarFunction::new_udf( + matches_func(), + vec![expr.clone(), Expr::Literal(literal.clone(), None)], + ); + assert_eq!( + FulltextIndexApplierBuilder::expr_to_query(&metadata, &query).unwrap(), + Some((target.clone(), FulltextQuery("error timeout".into()))) + ); + for lowered in [false, true] { + let expr = if lowered { + lower().call(vec![expr.clone()]) + } else { + expr.clone() + }; + let term = ScalarFunction::new_udf( + matches_term_func(), + vec![expr.clone(), Expr::Literal(literal.clone(), None)], + ); + let (actual, term) = FulltextIndexApplierBuilder::expr_to_term(&metadata, &term) + .unwrap() + .unwrap(); + assert_eq!(actual, target); + assert_eq!( + term, + FulltextTerm { + col_lowered: lowered, + term: "error timeout".into() + } + ); + let like = Like::new( + false, + Box::new(expr), + Box::new(Expr::Literal(literal.clone(), None)), + None, + false, + ); + let (actual, like) = FulltextIndexApplierBuilder::expr_to_like(&metadata, &like) + .unwrap() + .unwrap(); + assert_eq!(actual, target); + assert_eq!( + like, + FulltextLike { + col_lowered: lowered, + pattern: "error timeout".into() + } + ); + } + } + for expr in [ + json_expr("$.missing", None), + json_expr("$.message", Some(ScalarValue::Int64(None))), + ] { + assert!( + FulltextIndexApplierBuilder::index_target_from_expr(&metadata, &expr) + .unwrap() + .is_none() + ); + } + for options in [None, Some(FulltextOptions::default())] { + let metadata = json_metadata(options); + let path = json_expr("$.message", None); + for expr in [ + matches_func().call(vec![path.clone(), "error".lit()]), + matches_term_func().call(vec![path.clone(), "error".lit()]), + path.like("%error timeout%".lit()), + ] { + let mut requests = BTreeMap::new(); + FulltextIndexApplierBuilder::extract_requests(&expr, &metadata, &mut requests); + assert!(requests.is_empty(), "{expr}"); + } + } + } + + fn json_expr(path: &str, ty: Option) -> Expr { + let mut args = vec![datafusion_expr::col("attrs"), datafusion_expr::lit(path)]; + if let Some(ty) = ty { + args.push(Expr::Literal(ty, None)); + } + Expr::ScalarFunction(ScalarFunction::new_udf( + Arc::new(create_udf(Arc::new(JsonGetWithType::default()))), + args, + )) + } fn mock_metadata() -> RegionMetadata { - let mut builder = RegionMetadataBuilder::new(RegionId::new(1, 2)); - builder - .push_column_metadata(ColumnMetadata { - column_schema: ColumnSchema::new("text", ConcreteDataType::string_datatype(), true), - semantic_type: SemanticType::Field, - column_id: 1, - }) - .push_column_metadata(ColumnMetadata { - column_schema: ColumnSchema::new( - "ts", - ConcreteDataType::timestamp_millisecond_datatype(), - false, - ), - semantic_type: SemanticType::Timestamp, - column_id: 2, - }); - - builder.build().unwrap() + mock_metadata_with_fulltext(FulltextBackend::Bloom) } fn matches_func() -> Arc { @@ -377,19 +496,74 @@ mod tests { ) } + #[test] + fn test_ordinary_fulltext_requests_require_enabled_index() { + for options in [ + None, + Some(FulltextOptions::default()), + Some(FulltextOptions { + enable: true, + ..Default::default() + }), + Some(FulltextOptions { + enable: true, + backend: FulltextBackend::Tantivy, + ..Default::default() + }), + ] { + let enabled = options.as_ref().is_some_and(|options| options.enable); + let bloom_enabled = options + .as_ref() + .is_some_and(|options| options.enable && options.backend == FulltextBackend::Bloom); + let mut metadata = mock_metadata_without_fulltext(); + if let Some(options) = options { + metadata.column_metadatas[0] + .column_schema + .set_fulltext_options(&options) + .unwrap(); + } + let column = datafusion_expr::col("text"); + let expressions = [ + ( + matches_func().call(vec![column.clone(), "error".lit()]), + enabled, + ), + ( + matches_term_func().call(vec![column.clone(), "error".lit()]), + enabled, + ), + ( + matches_term_func() + .call(vec![lower().call(vec![column.clone()]), "error".lit()]), + enabled, + ), + (column.like("%error timeout retry%".lit()), bloom_enabled), + ]; + for (expr, expected) in expressions { + let mut requests = BTreeMap::new(); + FulltextIndexApplierBuilder::extract_requests(&expr, &metadata, &mut requests); + assert_eq!(!requests.is_empty(), expected, "{expr}"); + } + } + } + #[test] fn test_expr_to_query_basic() { let metadata = mock_metadata(); - - let func = ScalarFunction { - args: vec![Expr::Column(Column::from_name("text")), "foo".lit()], - func: matches_func(), - }; - - let (column_id, query) = - FulltextIndexApplierBuilder::expr_to_query(&metadata, &func).unwrap(); - assert_eq!(column_id, 1); - assert_eq!(query, FulltextQuery("foo".to_string())); + for literal in [ + ScalarValue::Utf8(Some("foo".into())), + ScalarValue::LargeUtf8(Some("foo".into())), + ScalarValue::Utf8View(Some("foo".into())), + ] { + let func = ScalarFunction::new_udf( + matches_func(), + vec![datafusion_expr::col("text"), Expr::Literal(literal, None)], + ); + assert_eq!( + FulltextIndexApplierBuilder::expr_to_query(&metadata, &func).unwrap(), + Some((IndexTarget::ColumnId(1), FulltextQuery("foo".into()))) + ); + } } #[test] @@ -401,7 +575,11 @@ mod tests { func: matches_func(), }; - assert!(FulltextIndexApplierBuilder::expr_to_query(&metadata, &func).is_none()); + assert!( + FulltextIndexApplierBuilder::expr_to_query(&metadata, &func) + .unwrap() + .is_none() + ); } #[test] @@ -413,7 +591,11 @@ mod tests { func: matches_func(), }; - assert!(FulltextIndexApplierBuilder::expr_to_query(&metadata, &func).is_none()); + assert!( + FulltextIndexApplierBuilder::expr_to_query(&metadata, &func) + .unwrap() + .is_none() + ); } #[test] @@ -425,7 +607,11 @@ mod tests { func: matches_func(), }; - assert!(FulltextIndexApplierBuilder::expr_to_query(&metadata, &func).is_none()); + assert!( + FulltextIndexApplierBuilder::expr_to_query(&metadata, &func) + .unwrap() + .is_none() + ); } #[test] @@ -437,28 +623,36 @@ mod tests { func: matches_func(), }; - assert!(FulltextIndexApplierBuilder::expr_to_query(&metadata, &func).is_none()); + assert!( + FulltextIndexApplierBuilder::expr_to_query(&metadata, &func) + .unwrap() + .is_none() + ); } #[test] fn test_expr_to_term_basic() { let metadata = mock_metadata(); - - let func = ScalarFunction { - args: vec![Expr::Column(Column::from_name("text")), "foo".lit()], - func: matches_term_func(), - }; - - let (column_id, term) = - FulltextIndexApplierBuilder::expr_to_term(&metadata, &func).unwrap(); - assert_eq!(column_id, 1); - assert_eq!( - term, - FulltextTerm { - col_lowered: false, - term: "foo".to_string(), - } - ); + for literal in [ + ScalarValue::Utf8(Some("foo".into())), + ScalarValue::LargeUtf8(Some("foo".into())), + ScalarValue::Utf8View(Some("foo".into())), + ] { + let func = ScalarFunction::new_udf( + matches_term_func(), + vec![datafusion_expr::col("text"), Expr::Literal(literal, None)], + ); + assert_eq!( + FulltextIndexApplierBuilder::expr_to_term(&metadata, &func).unwrap(), + Some(( + IndexTarget::ColumnId(1), + FulltextTerm { + col_lowered: false, + term: "foo".into() + } + )) + ); + } } #[test] @@ -475,9 +669,10 @@ mod tests { func: matches_term_func(), }; - let (column_id, term) = - FulltextIndexApplierBuilder::expr_to_term(&metadata, &func).unwrap(); - assert_eq!(column_id, 1); + let (target, term) = FulltextIndexApplierBuilder::expr_to_term(&metadata, &func) + .unwrap() + .unwrap(); + assert_eq!(target, IndexTarget::ColumnId(1)); assert_eq!( term, FulltextTerm { @@ -496,7 +691,11 @@ mod tests { func: matches_term_func(), }; - assert!(FulltextIndexApplierBuilder::expr_to_term(&metadata, &func).is_none()); + assert!( + FulltextIndexApplierBuilder::expr_to_term(&metadata, &func) + .unwrap() + .is_none() + ); } #[test] @@ -508,7 +707,11 @@ mod tests { func: matches_func(), // Using 'matches' instead of 'matches_term' }; - assert!(FulltextIndexApplierBuilder::expr_to_term(&metadata, &func).is_none()); + assert!( + FulltextIndexApplierBuilder::expr_to_term(&metadata, &func) + .unwrap() + .is_none() + ); } #[test] @@ -551,42 +754,12 @@ mod tests { FulltextIndexApplierBuilder::extract_requests(&matches_expr, &metadata, &mut requests); assert_eq!(requests.len(), 1); - let request = requests.get(&1).unwrap(); + let request = requests.get(&IndexTarget::ColumnId(1)).unwrap(); assert_eq!(request.queries.len(), 1); assert_eq!(request.terms.len(), 0); assert_eq!(request.queries[0], FulltextQuery("foo".to_string())); } - fn mock_metadata_with_fulltext(backend: FulltextBackend) -> RegionMetadata { - let mut builder = RegionMetadataBuilder::new(RegionId::new(1, 2)); - builder - .push_column_metadata(ColumnMetadata { - column_schema: ColumnSchema::new("text", ConcreteDataType::string_datatype(), true) - .with_fulltext_options(FulltextOptions::new_unchecked( - true, - FulltextAnalyzer::English, - false, - backend, - 10240, - 0.01, - )) - .unwrap(), - semantic_type: SemanticType::Field, - column_id: 1, - }) - .push_column_metadata(ColumnMetadata { - column_schema: ColumnSchema::new( - "ts", - ConcreteDataType::timestamp_millisecond_datatype(), - false, - ), - semantic_type: SemanticType::Timestamp, - column_id: 2, - }); - - builder.build().unwrap() - } - #[test] fn test_expr_to_like() { let like = |negated, case_insensitive, escape_char, pattern: &str| Like { @@ -603,9 +776,10 @@ mod tests { FulltextIndexApplierBuilder::expr_to_like( &bloom, &like(false, false, escape_char, "%foo bar baz%") - ), + ) + .unwrap(), Some(( - 1, + IndexTarget::ColumnId(1), FulltextLike { col_lowered: false, pattern: "%foo bar baz%".to_string(), @@ -621,9 +795,9 @@ mod tests { ..like(false, false, None, "%foo bar baz%") }; assert_eq!( - FulltextIndexApplierBuilder::expr_to_like(&bloom, &lowered), + FulltextIndexApplierBuilder::expr_to_like(&bloom, &lowered).unwrap(), Some(( - 1, + IndexTarget::ColumnId(1), FulltextLike { col_lowered: true, pattern: "%foo bar baz%".to_string(), @@ -639,25 +813,105 @@ mod tests { like(false, false, None, "%foo%"), ] { assert_eq!( - FulltextIndexApplierBuilder::expr_to_like(&bloom, &like), + FulltextIndexApplierBuilder::expr_to_like(&bloom, &like).unwrap(), None ); } // Only columns with a bloom fulltext index. for metadata in [ - mock_metadata(), + mock_metadata_without_fulltext(), mock_metadata_with_fulltext(FulltextBackend::Tantivy), ] { assert_eq!( FulltextIndexApplierBuilder::expr_to_like( &metadata, &like(false, false, None, "%foo bar baz%") - ), + ) + .unwrap(), None ); } } + #[test] + fn test_extract_requests_boolean_boundaries() { + let metadata = json_metadata(Some(FulltextOptions { + enable: true, + ..Default::default() + })); + let ordinary = matches_func().call(vec![datafusion_expr::col("text"), "error".lit()]); + let json = matches_term_func().call(vec![json_expr("$.message", None), "error".lit()]); + let ordinary_target = IndexTarget::ColumnId(1); + let json_target = IndexTarget::new_json_path(3, vec!["message".into()]).unwrap(); + for (expr, expected) in [ + ( + ordinary.clone().and(json.clone()), + vec![ordinary_target.clone(), json_target], + ), + (ordinary.clone().or(json.clone()), vec![]), + (Expr::Not(Box::new(json.clone())), vec![]), + ( + ordinary.clone().and(json.or(ordinary.clone())), + vec![ordinary_target], + ), + ] { + let mut requests = BTreeMap::new(); + FulltextIndexApplierBuilder::extract_requests(&expr, &metadata, &mut requests); + assert_eq!( + requests.keys().cloned().collect::>(), + expected, + "{expr}" + ); + } + } + + #[test] + fn test_extract_requests_keeps_valid_conjunct_on_error() { + let mut metadata = json_metadata(Some(FulltextOptions { + enable: true, + ..Default::default() + })); + let column = &mut metadata.column_metadatas[0].column_schema; + let mut options = column.metadata().clone(); + options.insert(FULLTEXT_KEY.into(), "invalid json".into()); + *column = column.clone().with_metadata(options); + let metadata = RegionMetadataBuilder::from_existing(metadata) + .build() + .unwrap(); + let column = datafusion_expr::col("text"); + let valid = matches_term_func().call(vec![json_expr("$.message", None), "error".lit()]); + let expected = BTreeMap::from([( + IndexTarget::new_json_path(3, vec!["message".into()]).unwrap(), + FulltextRequest { + terms: vec![FulltextTerm { + col_lowered: false, + term: "error".into(), + }], + ..Default::default() + }, + )]); + for invalid in [ + matches_func().call(vec![column.clone(), "error".lit()]), + matches_term_func().call(vec![column.clone(), "error".lit()]), + column.like("%error timeout%".lit()), + ] { + let mut requests = BTreeMap::new(); + assert!( + FulltextIndexApplierBuilder::extract_request(&invalid, &metadata, &mut requests) + .is_err() + ); + assert!(requests.is_empty()); + for expr in [ + invalid.clone().and(valid.clone()), + valid.clone().and(invalid), + ] { + FulltextIndexApplierBuilder::extract_requests(&expr, &metadata, &mut requests); + assert_eq!(requests, expected, "{expr}"); + requests.clear(); + } + } + } + #[test] fn test_extract_multiple_requests() { let metadata = mock_metadata(); @@ -685,7 +939,7 @@ mod tests { FulltextIndexApplierBuilder::extract_requests(&binary_expr, &metadata, &mut requests); assert_eq!(requests.len(), 1); - let request = requests.get(&1).unwrap(); + let request = requests.get(&IndexTarget::ColumnId(1)).unwrap(); assert_eq!(request.queries.len(), 1); assert_eq!(request.terms.len(), 1); assert_eq!(request.queries[0], FulltextQuery("foo".to_string())); diff --git a/src/mito2/src/sst/index/fulltext_index/creator.rs b/src/mito2/src/sst/index/fulltext_index/creator.rs index df2b314b5d1..2253360d5ce 100644 --- a/src/mito2/src/sst/index/fulltext_index/creator.rs +++ b/src/mito2/src/sst/index/fulltext_index/creator.rs @@ -17,11 +17,14 @@ use std::sync::Arc; use std::sync::atomic::AtomicUsize; use api::v1::SemanticType; +use arrow_schema::extension::ExtensionType; use common_telemetry::warn; use datatypes::arrow::array::{Array, LargeStringArray, StringArray}; use datatypes::arrow::datatypes::DataType; use datatypes::arrow::record_batch::RecordBatch; +use datatypes::extension::json::Json2ExtensionType; use datatypes::schema::{FulltextAnalyzer, FulltextBackend}; +use datatypes::vectors::VectorRef; use index::fulltext_index::create::{ BloomFilterFulltextIndexCreator, FulltextIndexCreator, TantivyFulltextIndexCreator, }; @@ -29,28 +32,37 @@ use index::fulltext_index::{Analyzer, Config}; use index::target::IndexTarget; use puffin::blob_metadata::CompressionCodec; use puffin::puffin_manager::PutOptions; -use snafu::{ResultExt, ensure}; +use snafu::{OptionExt, ResultExt, ensure}; use store_api::metadata::RegionMetadataRef; -use store_api::storage::{ColumnId, ConcreteDataType, FileId, RegionId}; +use store_api::storage::{ConcreteDataType, FileId, RegionId}; use crate::error::{ CastVectorSnafu, ComputeArrowSnafu, CreateFulltextCreatorSnafu, DataTypeMismatchSnafu, - FulltextFinishSnafu, FulltextPushTextSnafu, IndexOptionsSnafu, OperateAbortedIndexSnafu, - Result, + FulltextFinishSnafu, FulltextPushTextSnafu, IndexOptionsSnafu, InvalidRecordBatchSnafu, + OperateAbortedIndexSnafu, Result, }; use crate::read::Batch; -use crate::sst::index::TYPE_FULLTEXT_INDEX; +use crate::sst::index::column::extract_json_type_hint_values; use crate::sst::index::fulltext_index::{INDEX_BLOB_TYPE_BLOOM, INDEX_BLOB_TYPE_TANTIVY}; use crate::sst::index::intermediate::{ IntermediateLocation, IntermediateManager, TempFileProvider, }; use crate::sst::index::puffin_manager::SstPuffinWriter; use crate::sst::index::statistics::{ByteCount, RowCount, Statistics}; +use crate::sst::index::{IndexBuildType, TYPE_FULLTEXT_INDEX}; + +/// Resolved column identity, name, target and options retained by a build plan. +pub(crate) type FulltextTarget = ( + store_api::storage::ColumnId, + String, + IndexTarget, + datatypes::schema::FulltextOptions, +); /// `FulltextIndexer` is responsible for creating fulltext indexes for SST files. pub struct FulltextIndexer { /// Creators for each column. - creators: HashMap, + creators: HashMap, /// Whether the index creation was aborted. aborted: bool, /// Statistics of index creation. @@ -59,6 +71,7 @@ pub struct FulltextIndexer { impl FulltextIndexer { /// Creates a new `FulltextIndexer`. + #[cfg(test)] pub async fn new( region_id: &RegionId, sst_file_id: &FileId, @@ -66,36 +79,47 @@ impl FulltextIndexer { metadata: &RegionMetadataRef, compress: bool, mem_limit: usize, + build_type: IndexBuildType, + ) -> Result> { + let mut targets = Vec::new(); + for column in &metadata.column_metadatas { + for (target, options) in Self::targets(column, &build_type)? { + targets.push(( + column.column_id, + column.column_schema.name.clone(), + target, + options, + )); + } + } + Self::new_with_targets( + region_id, + sst_file_id, + intermediate_manager, + metadata, + compress, + mem_limit, + targets, + ) + .await + } + + /// Creates one file-level creator from already resolved targets. + pub(crate) async fn new_with_targets( + region_id: &RegionId, + sst_file_id: &FileId, + intermediate_manager: &IntermediateManager, + metadata: &RegionMetadataRef, + compress: bool, + mem_limit: usize, + targets: Vec, ) -> Result> { let mut creators = HashMap::new(); + let global_memory_usage = Arc::new(AtomicUsize::new(0)); - for column in &metadata.column_metadatas { - // Tag columns don't support fulltext index now. - // If we need to support fulltext index for tag columns, we also need to parse - // the codec and handle sparse encoding for flat format specially. - if column.semantic_type == SemanticType::Tag { - common_telemetry::debug!( - "Skip creating fulltext index for tag column {}", - column.column_schema.name - ); - continue; - } - - let options = column - .column_schema - .fulltext_options() - .context(IndexOptionsSnafu { - column_name: &column.column_schema.name, - })?; - - // Relax the type constraint here as many types can be casted to string. - - let options = match options { - Some(options) if options.enable => options, - _ => continue, - }; - - let column_id = column.column_id; + for (column_id, column_name, target, options) in targets { + // fulltext_path generates a fresh UUID for each target, so JSON paths + // in the same column use separate intermediate directories. let intm_path = intermediate_manager.fulltext_path(region_id, sst_file_id, column_id); let config = Config { @@ -118,13 +142,12 @@ impl FulltextIndexer { IntermediateLocation::new(&metadata.region_id, sst_file_id), intermediate_manager.clone(), )); - let global_memory_usage = Arc::new(AtomicUsize::new(0)); let creator = BloomFilterFulltextIndexCreator::new( config, options.granularity as _, options.false_positive_rate(), temp_file_provider, - global_memory_usage, + global_memory_usage.clone(), Some(mem_limit), ); AltFulltextCreator::Bloom(creator) @@ -132,16 +155,15 @@ impl FulltextIndexer { }; creators.insert( - column_id, + target.clone(), SingleCreator { - column_id, - column_name: column.column_schema.name.clone(), + target, + column_name, inner, compress, }, ); } - Ok((!creators.is_empty()).then(move || Self { creators, aborted: false, @@ -149,6 +171,65 @@ impl FulltextIndexer { })) } + /// Resolves all targets of one column without creating index state. + pub(crate) fn targets( + column: &store_api::metadata::ColumnMetadata, + build_type: &IndexBuildType, + ) -> Result> { + // Tag columns don't support fulltext index now. + // If we need to support fulltext index for tag columns, we also need to parse + // the codec and handle sparse encoding for flat format specially. + if column.semantic_type == SemanticType::Tag { + common_telemetry::debug!( + "Skip creating fulltext index for tag column {}", + column.column_schema.name + ); + return Ok(Vec::new()); + } + + let options = column + .column_schema + .fulltext_options() + .context(IndexOptionsSnafu { + column_name: &column.column_schema.name, + })?; + + let mut targets = Vec::new(); + if let Some(options) = options.filter(|options| options.enable) { + targets.push((IndexTarget::ColumnId(column.column_id), options)); + } + // Only flush and compaction builds collect JSON targets; manual and schema-change + // rebuilds skip them because existing SSTs may not materialize the current hints. + // FIXME: Rebuilds replace the whole Puffin file and can drop existing JSON path indexes. + if matches!(build_type, IndexBuildType::Flush | IndexBuildType::Compact) + && column.column_schema.data_type.is_json2() + && let Some(extension) = column + .column_schema + .extension_type::() + .context(IndexOptionsSnafu { + column_name: &column.column_schema.name, + })? + { + for hint in extension.metadata().json_settings().type_hints() { + let Some(options) = hint.fulltext_index.as_ref().filter(|o| o.enable) else { + continue; + }; + match IndexTarget::new_json_path(column.column_id, hint.path.clone()) { + Ok(target) => targets.push((target, options.clone())), + Err(err) => { + warn!( + err; + "Skip invalid JSON fulltext index target, column_id: {}, path: {:?}", + column.column_id, + hint.path + ); + } + } + } + } + Ok(targets) + } + /// Updates the index with the given batch. pub async fn update(&mut self, batch: &mut Batch) -> Result<()> { ensure!(!self.aborted, OperateAbortedIndexSnafu); @@ -225,17 +306,17 @@ impl FulltextIndexer { self.creators.values().map(|c| c.inner.memory_usage()).sum() } - /// Returns IDs of columns that the creator is responsible for. - pub fn column_ids(&self) -> impl Iterator + '_ { - self.creators.keys().copied() + /// Returns the targets indexed by this creator. + pub fn indexed_targets(&self) -> impl Iterator { + self.creators.keys() } - /// Returns IDs of columns indexed with the bloom backend. - pub fn bloom_column_ids(&self) -> impl Iterator + '_ { + /// Returns the targets indexed with the bloom backend. + pub fn bloom_indexed_targets(&self) -> impl Iterator { self.creators .values() .filter(|c| matches!(c.inner, AltFulltextCreator::Bloom(_))) - .map(|c| c.column_id) + .map(|c| &c.target) } } @@ -289,8 +370,8 @@ impl FulltextIndexer { /// `SingleCreator` is a creator for a single column. struct SingleCreator { - /// Column ID. - column_id: ColumnId, + /// Column or JSON path to index. + target: IndexTarget, /// Column name. column_name: String, /// Inner creator. @@ -301,10 +382,21 @@ struct SingleCreator { impl SingleCreator { async fn update(&mut self, batch: &mut Batch) -> Result<()> { - let text_column = batch - .fields() - .iter() - .find(|c| c.column_id == self.column_id); + let column_id = match &self.target { + IndexTarget::ColumnId(id) => *id, + IndexTarget::JsonPath(path) => { + let root = batch + .field_col_value(path.column_id()) + .with_context(|| InvalidRecordBatchSnafu { + reason: format!("Missing JSON fulltext column {}", path.column_id()), + })? + .data + .to_arrow_array(); + let values = extract_json_type_hint_values(&root, path.path())?; + return self.push_json_values(values).await; + } + }; + let text_column = batch.fields().iter().find(|c| c.column_id == column_id); match text_column { Some(column) => { let data = column @@ -338,6 +430,15 @@ impl SingleCreator { } async fn update_flat(&mut self, batch: &RecordBatch) -> Result<()> { + if let IndexTarget::JsonPath(path) = &self.target { + let root = batch.column_by_name(&self.column_name).with_context(|| { + InvalidRecordBatchSnafu { + reason: format!("Missing JSON fulltext column {}", self.column_name), + } + })?; + let values = extract_json_type_hint_values(root, path.path())?; + return self.push_json_values(values).await; + } // Find the column in the RecordBatch by name if let Some(column_array) = batch.column_by_name(&self.column_name) { // Convert Arrow array to string array. @@ -383,17 +484,29 @@ impl SingleCreator { Ok(()) } + async fn push_json_values(&mut self, values: VectorRef) -> Result<()> { + for row in 0..values.len() { + let text = values + .get_ref(row) + .try_into_string() + .context(DataTypeMismatchSnafu)? + .unwrap_or_default(); + self.inner.push_text(text).await?; + } + Ok(()) + } + async fn finish(&mut self, puffin_writer: &mut SstPuffinWriter) -> Result { let options = PutOptions { compression: self.compress.then_some(CompressionCodec::Zstd), }; self.inner - .finish(puffin_writer, &self.column_id, options) + .finish(puffin_writer, &self.target, options) .await } async fn abort(&mut self) -> Result<()> { - self.inner.abort(&self.column_id).await; + self.inner.abort(&self.target).await; Ok(()) } } @@ -423,10 +536,10 @@ impl AltFulltextCreator { async fn finish( &mut self, puffin_writer: &mut SstPuffinWriter, - column_id: &ColumnId, + target: &IndexTarget, put_options: PutOptions, ) -> Result { - let target_key = IndexTarget::ColumnId(*column_id).encode(); + let target_key = target.encode(); match self { Self::Tantivy(creator) => { let blob_key = format!("{INDEX_BLOB_TYPE_TANTIVY}-{target_key}"); @@ -445,16 +558,16 @@ impl AltFulltextCreator { } } - async fn abort(&mut self, column_id: &ColumnId) { + async fn abort(&mut self, target: &IndexTarget) { match self { Self::Tantivy(creator) => { if let Err(err) = creator.abort().await { - warn!(err; "Failed to abort the fulltext index creator in the Tantivy flavor, col_id: {:?}", column_id); + warn!(err; "Failed to abort the fulltext index creator in the Tantivy flavor, target: {:?}", target); } } Self::Bloom(creator) => { if let Err(err) = creator.abort().await { - warn!(err; "Failed to abort the fulltext index creator in the Bloom Filter flavor, col_id: {:?}", column_id); + warn!(err; "Failed to abort the fulltext index creator in the Bloom Filter flavor, target: {:?}", target); } } } @@ -468,9 +581,15 @@ mod tests { use api::v1::SemanticType; use common_base::BitVec; + use datatypes::arrow::array::{ArrayRef, StructArray}; + use datatypes::arrow::buffer::NullBuffer; + use datatypes::arrow::datatypes::{Field, Schema}; use datatypes::data_type::DataType; + use datatypes::extension::json::{Json2ExtensionType, JsonMetadata}; + use datatypes::json::{JsonSettings, JsonTypeHint}; use datatypes::schema::{ColumnSchema, FulltextAnalyzer, FulltextOptions}; - use datatypes::vectors::{UInt8Vector, UInt64Vector}; + use datatypes::types::json_type::{JsonNativeType, JsonObjectType}; + use datatypes::vectors::{Helper, UInt8Vector, UInt64Vector}; use futures::FutureExt; use futures::future::BoxFuture; use index::fulltext_index::search::RowId; @@ -479,7 +598,7 @@ mod tests { use puffin::puffin_manager::{PuffinManager, PuffinWriter}; use store_api::metadata::{ColumnMetadata, RegionMetadataBuilder, RegionMetadataRef}; use store_api::region_request::PathType; - use store_api::storage::{ConcreteDataType, FileId, RegionId}; + use store_api::storage::{ColumnId, ConcreteDataType, FileId, RegionId}; use super::*; use crate::access_layer::RegionFilePathFactory; @@ -491,6 +610,279 @@ mod tests { }; use crate::sst::index::puffin_manager::PuffinManagerFactory; + #[tokio::test] + async fn test_json_fulltext_build_and_prune_both_formats() { + for backend in [FulltextBackend::Bloom, FulltextBackend::Tantivy] { + for (flat, build_type) in [ + (false, IndexBuildType::Flush), + (false, IndexBuildType::Compact), + (true, IndexBuildType::Flush), + (true, IndexBuildType::Compact), + ] { + let (dir, factory) = + PuffinManagerFactory::new_for_test_async("json_fulltext").await; + let options = FulltextOptions::new( + true, + FulltextAnalyzer::English, + false, + backend.clone(), + 1, + 0.01, + ) + .unwrap(); + let hints = ["message", "other/\".field"].map(|name| JsonTypeHint { + path: vec![name.into()], + data_type: ConcreteDataType::string_datatype(), + inverted_index: false, + skipping_index: None, + fulltext_index: Some(options.clone()), + }); + let mut column = ColumnSchema::new( + "attrs", + ConcreteDataType::json2(JsonNativeType::Object(JsonObjectType::new())), + true, + ); + column.with_extension_type(&Json2ExtensionType::new(Arc::new(JsonMetadata::new( + JsonSettings::try_new(hints.to_vec(), Some(0)).unwrap(), + )))); + let mut builder = RegionMetadataBuilder::new(RegionId::new(1, 2)); + builder.push_column_metadata(ColumnMetadata { + column_schema: column, + semantic_type: SemanticType::Field, + column_id: 1, + }); + builder.push_column_metadata(ColumnMetadata { + column_schema: ColumnSchema::new( + "ts", + ConcreteDataType::timestamp_millisecond_datatype(), + false, + ), + semantic_type: SemanticType::Timestamp, + column_id: 2, + }); + let metadata = Arc::new(builder.build().unwrap()); + let file_id = FileId::random(); + let manager = new_intm_mgr(dir.path().to_string_lossy()).await; + for rebuild_type in [IndexBuildType::Manual, IndexBuildType::SchemaChange] { + assert!( + FulltextIndexer::new( + &metadata.region_id, + &file_id, + &manager, + &metadata, + false, + 1024, + rebuild_type, + ) + .await + .unwrap() + .is_none() + ); + } + let mut creator = FulltextIndexer::new( + &metadata.region_id, + &file_id, + &manager, + &metadata, + false, + 1024, + build_type, + ) + .await + .unwrap() + .unwrap(); + let messages: ArrayRef = Arc::new(StringArray::from(vec![ + Some("alpha"), + None, + Some("beta"), + Some("alpha"), + ])); + let other: ArrayRef = Arc::new(StringArray::from(vec![ + Some("beta"), + None, + Some("alpha"), + Some(""), + ])); + let root: ArrayRef = Arc::new(StructArray::new( + vec![ + Field::new("message", messages.data_type().clone(), true), + Field::new("other/\".field", other.data_type().clone(), true), + ] + .into(), + vec![messages, other], + Some(NullBuffer::from(vec![true, false, true, true])), + )); + for start in [0, 2] { + let array = root.slice(start, 2); + if flat { + let batch = RecordBatch::try_new( + Arc::new(Schema::new(vec![Field::new( + "attrs", + array.data_type().clone(), + true, + )])), + vec![array], + ) + .unwrap(); + creator.update_flat(&batch).await.unwrap(); + } else { + let mut batch = Batch::new( + vec![], + Arc::new(UInt64Vector::from_vec(vec![0, 1])), + Arc::new(UInt64Vector::from_vec(vec![0, 0])), + Arc::new(UInt8Vector::from_vec(vec![1, 1])), + vec![BatchColumn { + column_id: 1, + data: Helper::try_into_vector(array).unwrap(), + }], + ) + .unwrap(); + creator.update(&mut batch).await.unwrap(); + } + } + assert_eq!(creator.indexed_targets().count(), hints.len()); + assert!( + creator + .indexed_targets() + .all(|target| matches!(target, IndexTarget::JsonPath(_))) + ); + let bloom_targets: BTreeSet<_> = creator.bloom_indexed_targets().collect(); + if backend == FulltextBackend::Bloom { + assert_eq!(bloom_targets, creator.indexed_targets().collect()); + } else { + assert!(bloom_targets.is_empty()); + } + let store = mock_object_store(); + let puffin = factory.build( + store.clone(), + RegionFilePathFactory::new("json_test".into(), PathType::Bare), + ); + let index_id = + RegionIndexId::new(RegionFileId::new(metadata.region_id, file_id), 0); + let mut writer = puffin.writer(&index_id).await.unwrap(); + let (rows, bytes) = creator.finish(&mut writer).await.unwrap(); + assert_eq!(rows, 4); + assert!(bytes > 0); + writer.finish().await.unwrap(); + let cache = Arc::new( + crate::cache::index::bloom_filter_index::BloomFilterIndexCache::new( + 1024 * 1024, + 1024 * 1024, + 1024, + ), + ); + for (path, term, expected) in [ + ("message", "alpha", vec![0, 3]), + ("other/\".field", "alpha", vec![2]), + ("message", "hidden", vec![]), + ("message", "absent", vec![]), + ] { + let target = IndexTarget::new_json_path(1, vec![path.into()]).unwrap(); + let request = match backend { + FulltextBackend::Tantivy => FulltextRequest { + queries: vec![FulltextQuery(term.into())], + ..Default::default() + }, + FulltextBackend::Bloom => FulltextRequest { + terms: vec![FulltextTerm { + col_lowered: false, + term: term.into(), + }], + ..Default::default() + }, + }; + let applier = FulltextIndexApplier::new( + "json_test".into(), + PathType::Bare, + store.clone(), + BTreeMap::from([ + (target, request.clone()), + ( + IndexTarget::new_json_path(1, vec!["missing".into()]).unwrap(), + request, + ), + ]), + factory.clone(), + &metadata, + ) + .with_bloom_filter_cache(Some(cache.clone())); + let requests = applier.compatible_requests_for_sst(&metadata).unwrap(); + assert_eq!(requests.len(), 1); + for change in 0..3 { + let mut changed_hints = hints.to_vec(); + for hint in &mut changed_hints { + let options = hint.fulltext_index.as_mut().unwrap(); + match change { + 0 => options.analyzer = FulltextAnalyzer::Chinese, + 1 => options.case_sensitive = true, + _ => { + options.backend = match backend { + FulltextBackend::Bloom => FulltextBackend::Tantivy, + FulltextBackend::Tantivy => FulltextBackend::Bloom, + } + } + } + } + let mut changed = (*metadata).clone(); + changed.column_metadatas[0] + .column_schema + .with_extension_type(&Json2ExtensionType::new(Arc::new( + JsonMetadata::new( + JsonSettings::try_new(changed_hints, Some(0)).unwrap(), + ), + ))); + assert_eq!( + applier.compatible_requests_for_sst(&changed).is_some(), + change == 0 && backend == FulltextBackend::Bloom, + ); + } + assert!( + applier + .compatible_requests_for_sst(&mock_region_metadata(backend.clone())) + .is_none() + ); + for _ in 0..2 { + match backend { + FulltextBackend::Tantivy => { + let rows = applier + .apply_fine(index_id, None, &requests, None) + .await + .unwrap() + .unwrap(); + assert_eq!( + rows.into_iter().collect::>(), + expected.iter().map(|v| *v as RowId).collect::>() + ); + } + FulltextBackend::Bloom => { + let ranges = applier + .apply_coarse( + index_id, + None, + [(4, true)].into_iter(), + &requests, + None, + ) + .await + .unwrap() + .unwrap(); + let rows: Vec<_> = ranges[0].1.iter().cloned().flatten().collect(); + // A Bloom filter may retain extra rows, but must retain every match. + assert!(expected.iter().all(|row| rows.contains(row))); + if expected.is_empty() { + assert!( + rows.len() < 4, + "path={path}, term={term}, flat={flat}, rows={rows:?}" + ); + } + } + } + } + } + } + } + } + fn mock_object_store() -> ObjectStore { ObjectStore::new(Memory::default()).unwrap() } @@ -662,6 +1054,7 @@ mod tests { ®ion_metadata, true, 1024, + IndexBuildType::Flush, ) .await .unwrap() @@ -688,12 +1081,12 @@ mod tests { let object_store = object_store.clone(); let factory = factory.clone(); - let mut requests: BTreeMap = BTreeMap::new(); + let mut requests: BTreeMap = BTreeMap::new(); // Add queries for (column_id, query) in queries { requests - .entry(column_id) + .entry(IndexTarget::ColumnId(column_id)) .or_default() .queries .push(FulltextQuery(query.to_string())); @@ -710,7 +1103,7 @@ mod tests { .collect::>(); requests - .entry(column_id) + .entry(IndexTarget::ColumnId(column_id)) .or_default() .terms .extend(fulltext_terms); @@ -722,20 +1115,25 @@ mod tests { object_store, requests, factory, + ®ion_metadata, ); + let requests = applier + .compatible_requests_for_sst(®ion_metadata) + .unwrap(); let backend = backend.clone(); async move { match backend { - FulltextBackend::Tantivy => { - applier.apply_fine(index_id, None, None).await.unwrap() - } + FulltextBackend::Tantivy => applier + .apply_fine(index_id, None, &requests, None) + .await + .unwrap(), FulltextBackend::Bloom => { let coarse_mask = coarse_mask.unwrap_or_default(); let row_groups = (0..coarse_mask.len()).map(|i| (1, coarse_mask[i])); // row group id == row id let resp = applier - .apply_coarse(index_id, None, row_groups, None) + .apply_coarse(index_id, None, row_groups, &requests, None) .await .unwrap(); resp.map(|r| { @@ -755,6 +1153,46 @@ mod tests { row_ids.into_iter().collect() } + #[tokio::test] + async fn test_fulltext_bloom_shared_memory_spills() { + let dir = common_test_util::temp_dir::create_temp_dir("shared_fulltext_memory"); + let metadata = mock_region_metadata(FulltextBackend::Bloom); + let manager = new_intm_mgr(dir.path().to_string_lossy()).await; + let mut indexer = FulltextIndexer::new( + &metadata.region_id, + &FileId::random(), + &manager, + &metadata, + false, + 2 * 1024 * 1024, + IndexBuildType::Flush, + ) + .await + .unwrap() + .unwrap(); + // Each target stays below 2 MB on its own; together they exceed the + // shared threshold and must spill finalized Bloom filters to disk. + for creator in indexer.creators.values_mut() { + for row in 0..20_000 { + creator.inner.push_text(&format!("row{row}")).await.unwrap(); + } + } + let mut directories = vec![dir.path().join("__intm")]; + let mut spilled = false; + while let Some(directory) = directories.pop() { + for entry in std::fs::read_dir(directory).unwrap() { + let entry = entry.unwrap(); + if entry.file_type().unwrap().is_dir() { + directories.push(entry.path()); + } else { + spilled = true; + } + } + } + assert!(spilled, "combined memory usage must trigger spilling"); + indexer.abort().await.unwrap(); + } + #[tokio::test] async fn test_fulltext_index_basic_case_sensitive_tantivy() { let applier_factory = build_fulltext_applier_factory( diff --git a/src/mito2/src/sst/index/handler.rs b/src/mito2/src/sst/index/handler.rs new file mode 100644 index 00000000000..31ff82d3bb5 --- /dev/null +++ b/src/mito2/src/sst/index/handler.rs @@ -0,0 +1,113 @@ +// 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. + +//! Planning and creation contracts for built-in indexes. + +pub(crate) mod builtin; + +use std::fmt::Debug; +use std::sync::Arc; + +use async_trait::async_trait; +use common_error::ext::BoxedError; +use datatypes::arrow::record_batch::RecordBatch; +use index::target::IndexTarget; +use store_api::metadata::RegionMetadataRef; + +use crate::read::Batch; +use crate::region::options::IndexOptions; +use crate::sst::file::RegionIndexId; +use crate::sst::index::intermediate::IntermediateManager; +use crate::sst::index::kind::IndexKind; +use crate::sst::index::puffin_manager::SstPuffinWriter; +use crate::sst::index::{CompletedEntry, IndexBuildType}; + +/// Schema and options used to prepare work without reading input files. +pub(crate) struct PlanContext<'a> { + /// Shared region schema. + pub metadata: &'a RegionMetadataRef, + /// Region index options. + pub index_options: &'a IndexOptions, + /// Lifecycle event requesting the build. + pub build_type: IndexBuildType, +} + +/// Inputs for constructing all of one handler's indexes in a single output file. +pub(crate) struct BuildContext<'a> { + /// Shared output schema. + pub metadata: &'a RegionMetadataRef, + /// Physical output index identity. + pub output: RegionIndexId, + /// Existing intermediate-file facility shared by built-in creators. + pub intermediate_manager: &'a IntermediateManager, + /// Actual output row-group size used to align inverted-index segments. + pub row_group_size: Option, +} + +/// Prepares one built-in index implementation. +pub(crate) trait IndexKindHandler: Send + Sync + Debug { + /// Built-in implementation owned by this handler. + fn kind(&self) -> IndexKind; + + /// Prepares typed parameters. `None` means no work. + fn plan(&self, context: &PlanContext<'_>) -> Result>, BoxedError>; +} + +/// An immutable typed plan shared by output files of an operation. +#[async_trait] +pub(crate) trait PlannedIndex: Send + Sync + Debug { + /// Built-in implementation owned by this plan. + fn kind(&self) -> IndexKind; + + /// Creates a per-file index creator before any output batch is consumed. + async fn build( + &self, + context: &BuildContext<'_>, + ) -> Result>, BoxedError>; +} + +/// Accumulates rows and writes blobs into the engine-owned Puffin lifecycle. +/// Implementations release retained state on drop, including cancellation. +#[async_trait] +pub(crate) trait IndexCreator: Send { + /// Borrows a batch and its reusable primary-key decode cache. + async fn update(&mut self, batch: &mut Batch) -> Result<(), BoxedError>; + + /// Borrows array data; cloning shared array handles is allowed. + async fn update_flat(&mut self, batch: &RecordBatch) -> Result<(), BoxedError>; + + /// Writes completed entries. Publication waits for the engine to close Puffin. + /// The creator is dropped afterward, including on error, without calling its + /// `abort` method; implementations must finalize their own temporary resources. + async fn finish( + &mut self, + writer: &mut SstPuffinWriter, + ) -> Result, BoxedError>; + + /// Releases temporary resources; the engine owns final-file cleanup. + async fn abort(&mut self) -> Result<(), BoxedError>; + + /// Estimated retained memory, not exact allocator or process RSS accounting. + fn memory_usage(&self) -> usize; + + /// Targets needed when preparing the shared dense primary-key decoder. + fn indexed_targets(&self) -> Vec { + Vec::new() + } + + /// Whether this creator participates in existing dense-key predecoding. + fn needs_dense_pk(&self) -> bool { + false + } +} diff --git a/src/mito2/src/sst/index/handler/builtin.rs b/src/mito2/src/sst/index/handler/builtin.rs new file mode 100644 index 00000000000..ec21eaf00f2 --- /dev/null +++ b/src/mito2/src/sst/index/handler/builtin.rs @@ -0,0 +1,110 @@ +// 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. + +//! Dispatches built-in planning and shares column metadata policy. + +mod bloom; +mod fulltext; +mod inverted; + +use std::sync::Arc; + +use common_error::ext::BoxedError; +use index::target::IndexTarget; + +use crate::config::{BloomFilterConfig, FulltextIndexConfig, InvertedIndexConfig}; +use crate::sst::index::handler::builtin::bloom::BloomPlan; +use crate::sst::index::handler::builtin::fulltext::FulltextPlan; +use crate::sst::index::handler::builtin::inverted::InvertedPlan; +use crate::sst::index::handler::{IndexKindHandler, PlanContext, PlannedIndex}; +use crate::sst::index::kind::IndexKind; + +/// Configuration for one of the existing file-level built-in creators. +#[derive(Debug, Clone)] +pub(crate) enum BuiltinIndexHandler { + Inverted(InvertedIndexConfig), + Fulltext(FulltextIndexConfig), + Bloom(BloomFilterConfig), +} + +impl IndexKindHandler for BuiltinIndexHandler { + fn kind(&self) -> IndexKind { + match self { + Self::Inverted(_) => IndexKind::Inverted, + Self::Fulltext(_) => IndexKind::Fulltext, + Self::Bloom(_) => IndexKind::Bloom, + } + } + + fn plan(&self, context: &PlanContext<'_>) -> Result>, BoxedError> { + match self { + Self::Inverted(config) => InvertedPlan::plan(config, context) + .map(|plan| plan.map(|plan| plan as Arc)), + Self::Fulltext(config) => FulltextPlan::plan(config, context), + Self::Bloom(config) => BloomPlan::plan(config, context), + } + } +} + +fn column_target_id(target: &IndexTarget) -> Option { + match target { + IndexTarget::ColumnId(id) => Some(*id), + IndexTarget::JsonPath(_) => None, + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::region::options::IndexOptions; + use crate::sst::index::IndexBuildType; + use crate::test_util::sst_util; + + #[test] + fn test_builtin_planning_reports_invalid_options() { + for (handler, key) in [ + ( + BuiltinIndexHandler::Fulltext(FulltextIndexConfig::default()), + datatypes::schema::FULLTEXT_KEY, + ), + ( + BuiltinIndexHandler::Bloom(BloomFilterConfig::default()), + datatypes::schema::SKIPPING_INDEX_KEY, + ), + ] { + let mut metadata = sst_util::sst_region_metadata(); + let column = metadata + .column_metadatas + .iter_mut() + .find(|column| column.semantic_type == api::v1::SemanticType::Field) + .unwrap(); + column.column_schema = + column + .column_schema + .clone() + .with_metadata(std::collections::HashMap::from([( + key.to_string(), + "invalid json".to_string(), + )])); + let metadata = Arc::new(metadata); + let options = IndexOptions::default(); + let context = PlanContext { + metadata: &metadata, + index_options: &options, + build_type: IndexBuildType::Flush, + }; + assert!(handler.plan(&context).is_err()); + } + } +} diff --git a/src/mito2/src/sst/index/handler/builtin/bloom.rs b/src/mito2/src/sst/index/handler/builtin/bloom.rs new file mode 100644 index 00000000000..1b011b79086 --- /dev/null +++ b/src/mito2/src/sst/index/handler/builtin/bloom.rs @@ -0,0 +1,149 @@ +// 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. + +//! Planning and creator adapter for the bloom index. + +use std::sync::Arc; + +use async_trait::async_trait; +use common_error::ext::BoxedError; +use datatypes::arrow::record_batch::RecordBatch; +use datatypes::schema::SkippingIndexOptions; +use index::target::IndexTarget; + +use crate::config::BloomFilterConfig; +use crate::read::Batch; +use crate::sst::index::bloom_filter::creator::BloomFilterIndexer; +use crate::sst::index::handler::builtin::column_target_id; +use crate::sst::index::handler::{BuildContext, IndexCreator, PlanContext, PlannedIndex}; +use crate::sst::index::kind::IndexKind; +use crate::sst::index::puffin_manager::SstPuffinWriter; +use crate::sst::index::{CompletedEntry, IndexBuildType}; + +/// Resolved column targets and configuration shared across output files. +#[derive(Debug)] +pub(crate) struct BloomPlan { + config: BloomFilterConfig, + targets: Vec<(IndexTarget, SkippingIndexOptions)>, +} + +impl BloomPlan { + /// Resolves targets without opening SST data or creating output files. + pub(crate) fn plan( + config: &BloomFilterConfig, + context: &PlanContext<'_>, + ) -> Result>, BoxedError> { + let create = match context.build_type { + IndexBuildType::Flush => config.create_on_flush.auto(), + IndexBuildType::Compact => config.create_on_compaction.auto(), + _ => true, + }; + if !create { + return Ok(None); + } + let mut targets = Vec::new(); + for column in &context.metadata.column_metadatas { + for (target, options) in + BloomFilterIndexer::targets(column, &context.build_type).map_err(BoxedError::new)? + { + targets.push((target, options)); + } + } + if targets.is_empty() { + return Ok(None); + } + Ok(Some(Arc::new(Self { + config: config.clone(), + targets, + }))) + } +} + +#[async_trait] +impl PlannedIndex for BloomPlan { + fn kind(&self) -> IndexKind { + IndexKind::Bloom + } + + async fn build( + &self, + context: &BuildContext<'_>, + ) -> Result>, BoxedError> { + BloomFilterIndexer::new_with_targets( + context.output.file_id(), + context.metadata, + context.intermediate_manager.clone(), + self.config.mem_threshold_on_create(), + self.targets.clone(), + ) + .map(|creator| creator.map(|c| Box::new(c) as Box)) + .map_err(BoxedError::new) + } +} + +#[async_trait] +impl IndexCreator for BloomFilterIndexer { + async fn update(&mut self, batch: &mut Batch) -> Result<(), BoxedError> { + Self::update(self, batch).await.map_err(BoxedError::new) + } + + async fn update_flat(&mut self, batch: &RecordBatch) -> Result<(), BoxedError> { + Self::update_flat(self, batch) + .await + .map_err(BoxedError::new) + } + + async fn finish( + &mut self, + writer: &mut SstPuffinWriter, + ) -> Result, BoxedError> { + let mut columns: Vec<_> = Self::indexed_targets(self) + .filter_map(column_target_id) + .map(Some) + .collect(); + let (_, bytes) = Self::finish(self, writer).await.map_err(BoxedError::new)?; + if bytes == 0 { + return Ok(Vec::new()); + } + if columns.is_empty() { + columns.push(None); + } + columns.sort_unstable(); + columns.dedup(); + Ok(columns + .into_iter() + .map(|column_id| CompletedEntry { + column_id, + kind: IndexKind::Bloom, + format_version: 0, + }) + .collect()) + } + + async fn abort(&mut self) -> Result<(), BoxedError> { + Self::abort(self).await.map_err(BoxedError::new) + } + + fn memory_usage(&self) -> usize { + Self::memory_usage(self) + } + + fn indexed_targets(&self) -> Vec { + Self::indexed_targets(self).cloned().collect() + } + + fn needs_dense_pk(&self) -> bool { + true + } +} diff --git a/src/mito2/src/sst/index/handler/builtin/fulltext.rs b/src/mito2/src/sst/index/handler/builtin/fulltext.rs new file mode 100644 index 00000000000..160b7923f49 --- /dev/null +++ b/src/mito2/src/sst/index/handler/builtin/fulltext.rs @@ -0,0 +1,161 @@ +// 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. + +//! Planning and creator adapter for the fulltext index. + +use std::sync::Arc; + +use async_trait::async_trait; +use common_error::ext::BoxedError; +use datatypes::arrow::record_batch::RecordBatch; +use index::target::IndexTarget; + +use crate::config::FulltextIndexConfig; +use crate::read::Batch; +use crate::sst::index::fulltext_index; +use crate::sst::index::fulltext_index::creator::{FulltextIndexer, FulltextTarget}; +use crate::sst::index::handler::builtin::column_target_id; +use crate::sst::index::handler::{BuildContext, IndexCreator, PlanContext, PlannedIndex}; +use crate::sst::index::kind::IndexKind; +use crate::sst::index::puffin_manager::SstPuffinWriter; +use crate::sst::index::{CompletedEntry, IndexBuildType}; + +/// Resolved column targets and configuration shared across output files. +#[derive(Debug)] +pub(crate) struct FulltextPlan { + config: FulltextIndexConfig, + targets: Vec, +} + +impl FulltextPlan { + /// Resolves targets without opening SST data or creating output files. + pub(crate) fn plan( + config: &FulltextIndexConfig, + context: &PlanContext<'_>, + ) -> Result>, BoxedError> { + let create = match context.build_type { + IndexBuildType::Flush => config.create_on_flush.auto(), + IndexBuildType::Compact => config.create_on_compaction.auto(), + _ => true, + }; + if !create { + return Ok(None); + } + let mut targets = Vec::new(); + for column in &context.metadata.column_metadatas { + for (target, options) in + FulltextIndexer::targets(column, &context.build_type).map_err(BoxedError::new)? + { + targets.push(( + column.column_id, + column.column_schema.name.clone(), + target, + options, + )); + } + } + if targets.is_empty() { + return Ok(None); + } + Ok(Some(Arc::new(Self { + config: config.clone(), + targets, + }))) + } +} + +#[async_trait] +impl PlannedIndex for FulltextPlan { + fn kind(&self) -> IndexKind { + IndexKind::Fulltext + } + + async fn build( + &self, + context: &BuildContext<'_>, + ) -> Result>, BoxedError> { + FulltextIndexer::new_with_targets( + &context.metadata.region_id, + &context.output.file_id(), + context.intermediate_manager, + context.metadata, + self.config.compress, + self.config.mem_threshold_on_create(), + self.targets.clone(), + ) + .await + .map(|creator| creator.map(|c| Box::new(c) as Box)) + .map_err(BoxedError::new) + } +} + +#[async_trait] +impl IndexCreator for FulltextIndexer { + async fn update(&mut self, batch: &mut Batch) -> Result<(), BoxedError> { + Self::update(self, batch).await.map_err(BoxedError::new) + } + + async fn update_flat(&mut self, batch: &RecordBatch) -> Result<(), BoxedError> { + Self::update_flat(self, batch) + .await + .map_err(BoxedError::new) + } + + async fn finish( + &mut self, + writer: &mut SstPuffinWriter, + ) -> Result, BoxedError> { + let mut columns: Vec<_> = Self::indexed_targets(self) + .filter_map(column_target_id) + .map(Some) + .collect(); + let bloom_columns: Vec<_> = self + .bloom_indexed_targets() + .filter_map(column_target_id) + .collect(); + let (_, bytes) = Self::finish(self, writer).await.map_err(BoxedError::new)?; + if bytes == 0 { + return Ok(Vec::new()); + } + if columns.is_empty() { + columns.push(None); + } + columns.sort_unstable(); + columns.dedup(); + Ok(columns + .into_iter() + .map(|column_id| CompletedEntry { + column_id, + kind: IndexKind::Fulltext, + format_version: if column_id.is_some_and(|id| bloom_columns.contains(&id)) { + u32::from(fulltext_index::FULLTEXT_BLOOM_VERSION) + } else { + 0 + }, + }) + .collect()) + } + + async fn abort(&mut self) -> Result<(), BoxedError> { + Self::abort(self).await.map_err(BoxedError::new) + } + + fn memory_usage(&self) -> usize { + Self::memory_usage(self) + } + + fn indexed_targets(&self) -> Vec { + Self::indexed_targets(self).cloned().collect() + } +} diff --git a/src/mito2/src/sst/index/handler/builtin/inverted.rs b/src/mito2/src/sst/index/handler/builtin/inverted.rs new file mode 100644 index 00000000000..baf87f93258 --- /dev/null +++ b/src/mito2/src/sst/index/handler/builtin/inverted.rs @@ -0,0 +1,266 @@ +// 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. + +//! Planning and creator adapter for the inverted index. + +use std::num::NonZeroUsize; +use std::sync::Arc; + +use arrow_schema::extension::ExtensionType; +use async_trait::async_trait; +use common_error::ext::BoxedError; +use common_telemetry::warn; +use datatypes::arrow::record_batch::RecordBatch; +use datatypes::extension::json::Json2ExtensionType; +use index::target::IndexTarget; + +use crate::config::InvertedIndexConfig; +use crate::read::Batch; +use crate::sst::index::handler::builtin::column_target_id; +use crate::sst::index::handler::{BuildContext, IndexCreator, PlanContext, PlannedIndex}; +use crate::sst::index::inverted_index::creator::InvertedIndexer; +use crate::sst::index::kind::IndexKind; +use crate::sst::index::puffin_manager::SstPuffinWriter; +use crate::sst::index::{CompletedEntry, IndexBuildType}; + +/// Resolved column targets and configuration shared across output files. +#[derive(Debug)] +pub(crate) struct InvertedPlan { + config: InvertedIndexConfig, + targets: Vec, + segment_row_count: NonZeroUsize, +} + +impl InvertedPlan { + /// Resolves targets without opening SST data or creating output files. + pub(crate) fn plan( + config: &InvertedIndexConfig, + context: &PlanContext<'_>, + ) -> Result>, BoxedError> { + let create = match context.build_type { + IndexBuildType::Flush => config.create_on_flush.auto(), + IndexBuildType::Compact => config.create_on_compaction.auto(), + _ => true, + }; + if !create { + return Ok(None); + } + let mut targets: Vec<_> = context + .metadata + .inverted_indexed_column_ids( + context + .index_options + .inverted_index + .ignore_column_ids + .iter(), + ) + .into_iter() + .map(IndexTarget::ColumnId) + .collect(); + targets.extend(json_inverted_targets(context)); + let Some(segment_row_count) = + NonZeroUsize::new(context.index_options.inverted_index.segment_row_count) + else { + warn!( + "Skip creating inverted index with zero segment row count, region_id: {}", + context.metadata.region_id + ); + return Ok(None); + }; + if targets.is_empty() { + return Ok(None); + } + Ok(Some(Arc::new(Self { + config: config.clone(), + targets, + segment_row_count, + }))) + } +} + +#[async_trait] +impl PlannedIndex for InvertedPlan { + fn kind(&self) -> IndexKind { + IndexKind::Inverted + } + + async fn build( + &self, + context: &BuildContext<'_>, + ) -> Result>, BoxedError> { + let mut segment = self.segment_row_count; + if let Some(row_group_size) = context.row_group_size.and_then(NonZeroUsize::new) + && row_group_size.get() % segment.get() != 0 + { + segment = row_group_size; + } + Ok(Some(Box::new(InvertedIndexer::new( + context.output.file_id(), + context.metadata, + context.intermediate_manager.clone(), + self.config.mem_threshold_on_create(), + segment, + self.targets.clone(), + )))) + } +} + +fn json_inverted_targets(context: &PlanContext<'_>) -> Vec { + // FIXME: Rebuilds replace the whole Puffin file and can drop existing JSON path indexes. + if !matches!( + context.build_type, + IndexBuildType::Flush | IndexBuildType::Compact + ) { + return Vec::new(); + } + + let mut targets = Vec::new(); + for column in &context.metadata.column_metadatas { + if !column.column_schema.data_type.is_json2() { + continue; + } + let Ok(Some(extension)) = column.column_schema.extension_type::() + else { + continue; + }; + for hint in extension.metadata().json_settings().type_hints() { + if !hint.inverted_index + || !(hint.data_type.is_numeric() + || hint.data_type.is_boolean() + || hint.data_type.is_string()) + { + continue; + } + match IndexTarget::new_json_path(column.column_id, hint.path.clone()) { + Ok(target) => targets.push(target), + Err(err) => warn!(err; "Skipping invalid JSON inverted index target"), + } + } + } + targets +} + +#[async_trait] +impl IndexCreator for InvertedIndexer { + async fn update(&mut self, batch: &mut Batch) -> Result<(), BoxedError> { + Self::update(self, batch).await.map_err(BoxedError::new) + } + + async fn update_flat(&mut self, batch: &RecordBatch) -> Result<(), BoxedError> { + Self::update_flat(self, batch) + .await + .map_err(BoxedError::new) + } + + async fn finish( + &mut self, + writer: &mut SstPuffinWriter, + ) -> Result, BoxedError> { + let mut columns: Vec<_> = Self::indexed_targets(self) + .filter_map(column_target_id) + .map(Some) + .collect(); + let (_, bytes) = Self::finish(self, writer).await.map_err(BoxedError::new)?; + if bytes == 0 { + return Ok(Vec::new()); + } + if columns.is_empty() { + columns.push(None); + } + columns.sort_unstable(); + columns.dedup(); + Ok(columns + .into_iter() + .map(|column_id| CompletedEntry { + column_id, + kind: IndexKind::Inverted, + format_version: 0, + }) + .collect()) + } + + async fn abort(&mut self) -> Result<(), BoxedError> { + Self::abort(self).await.map_err(BoxedError::new) + } + + fn memory_usage(&self) -> usize { + Self::memory_usage(self) + } + + fn indexed_targets(&self) -> Vec { + Self::indexed_targets(self).cloned().collect() + } + + fn needs_dense_pk(&self) -> bool { + true + } +} + +#[cfg(test)] +mod tests { + use datatypes::data_type::ConcreteDataType; + use datatypes::extension::json::JsonMetadata; + use datatypes::json::{JsonSettings, JsonTypeHint}; + use datatypes::types::json_type::{JsonNativeType, JsonObjectType}; + + use super::*; + use crate::region::options::IndexOptions; + use crate::test_util::sst_util; + + #[test] + fn test_json_inverted_plan_preserves_build_scope() { + let mut metadata = sst_util::sst_region_metadata(); + let column = &mut metadata.column_metadatas[2].column_schema; + column.data_type = ConcreteDataType::json2(JsonNativeType::Object(JsonObjectType::new())); + column.with_extension_type(&Json2ExtensionType::new(Arc::new(JsonMetadata::new( + JsonSettings::try_new( + vec![JsonTypeHint { + path: vec!["value".into()], + data_type: ConcreteDataType::int64_datatype(), + inverted_index: true, + skipping_index: None, + fulltext_index: None, + }], + Some(0), + ) + .unwrap(), + )))); + let metadata = Arc::new(metadata); + let options = IndexOptions::default(); + let config = InvertedIndexConfig::default(); + + for (build_type, expected_columns) in [ + (IndexBuildType::Flush, vec![0, 2]), + (IndexBuildType::Compact, vec![0, 2]), + (IndexBuildType::Manual, vec![0]), + (IndexBuildType::SchemaChange, vec![0]), + ] { + let context = PlanContext { + metadata: &metadata, + index_options: &options, + build_type: build_type.clone(), + }; + let plan = InvertedPlan::plan(&config, &context).unwrap().unwrap(); + let columns: Vec<_> = plan + .targets + .iter() + .map(|target| match target { + IndexTarget::ColumnId(id) => *id, + IndexTarget::JsonPath(path) => path.column_id(), + }) + .collect(); + assert_eq!(columns, expected_columns, "{build_type:?}"); + } + } +} diff --git a/src/mito2/src/sst/index/indexer/abort.rs b/src/mito2/src/sst/index/indexer/abort.rs index 36c002f13f0..e34b8ba4e7f 100644 --- a/src/mito2/src/sst/index/indexer/abort.rs +++ b/src/mito2/src/sst/index/indexer/abort.rs @@ -19,11 +19,21 @@ use crate::sst::file::{RegionFileId, RegionIndexId}; use crate::sst::index::Indexer; impl Indexer { + pub(crate) async fn abort_creator(&mut self, position: usize) { + let mut active = self.creators.remove(position); + if let Err(err) = active.creator.abort().await { + if cfg!(any(test, feature = "test")) { + panic!("Failed to abort index: {err:?}"); + } + warn!(err; "Failed to abort index, region_id: {}, file_id: {}, kind: {:?}", self.region_id, self.file_id, active.kind); + } + } + pub(crate) async fn do_abort(&mut self) { self.dense_pk_decoder = None; - self.do_abort_inverted_index().await; - self.do_abort_fulltext_index().await; - self.do_abort_bloom_filter().await; + while !self.creators.is_empty() { + self.abort_creator(0).await; + } self.do_prune_intm_sst_dir().await; if self.write_cache_enabled { self.do_abort_clean_fs_temp_dir().await; @@ -31,69 +41,6 @@ impl Indexer { self.puffin_manager = None; } - async fn do_abort_inverted_index(&mut self) { - let Some(mut indexer) = self.inverted_indexer.take() else { - return; - }; - let Err(err) = indexer.abort().await else { - return; - }; - - if cfg!(any(test, feature = "test")) { - panic!( - "Failed to abort inverted index, region_id: {}, file_id: {}, err: {:?}", - self.region_id, self.file_id, err - ); - } else { - warn!( - err; "Failed to abort inverted index, region_id: {}, file_id: {}", - self.region_id, self.file_id, - ); - } - } - - async fn do_abort_fulltext_index(&mut self) { - let Some(mut indexer) = self.fulltext_indexer.take() else { - return; - }; - let Err(err) = indexer.abort().await else { - return; - }; - - if cfg!(any(test, feature = "test")) { - panic!( - "Failed to abort full-text index, region_id: {}, file_id: {}, err: {:?}", - self.region_id, self.file_id, err - ); - } else { - warn!( - err; "Failed to abort full-text index, region_id: {}, file_id: {}", - self.region_id, self.file_id, - ); - } - } - - async fn do_abort_bloom_filter(&mut self) { - let Some(mut indexer) = self.bloom_filter_indexer.take() else { - return; - }; - let Err(err) = indexer.abort().await else { - return; - }; - - if cfg!(any(test, feature = "test")) { - panic!( - "Failed to abort bloom filter, region_id: {}, file_id: {}, err: {:?}", - self.region_id, self.file_id, err - ); - } else { - warn!( - err; "Failed to abort bloom filter, region_id: {}, file_id: {}", - self.region_id, self.file_id, - ); - } - } - async fn do_abort_clean_fs_temp_dir(&mut self) { let Some(puffin_manager) = &self.puffin_manager else { return; diff --git a/src/mito2/src/sst/index/indexer/finish.rs b/src/mito2/src/sst/index/indexer/finish.rs index 801b3a8eeb2..366bde9a196 100644 --- a/src/mito2/src/sst/index/indexer/finish.rs +++ b/src/mito2/src/sst/index/indexer/finish.rs @@ -12,54 +12,50 @@ // See the License for the specific language governing permissions and // limitations under the License. -use common_telemetry::{debug, warn}; -use index::target::IndexTarget; +use common_telemetry::warn; use puffin::puffin_manager::{PuffinManager, PuffinWriter}; -use store_api::storage::ColumnId; use crate::sst::file::{RegionFileId, RegionIndexId}; use crate::sst::index::puffin_manager::SstPuffinWriter; -use crate::sst::index::statistics::{ByteCount, RowCount}; -use crate::sst::index::{ - BloomFilterOutput, FulltextIndexOutput, IndexOutput, Indexer, InvertedIndexOutput, -}; +use crate::sst::index::statistics::ByteCount; +use crate::sst::index::{IndexOutput, Indexer}; impl Indexer { pub(crate) async fn do_finish(&mut self) -> IndexOutput { self.dense_pk_decoder = None; - let mut output = IndexOutput::default(); - + if self.is_empty() { + return IndexOutput::default(); + } let Some(mut writer) = self.build_puffin_writer().await else { self.do_abort().await; - return output; + return IndexOutput::default(); }; - - let success = self - .do_finish_inverted_index(&mut writer, &mut output) - .await; - if !success { - self.do_abort().await; - return IndexOutput::default(); + let mut output = IndexOutput::default(); + while !self.creators.is_empty() { + let mut active = self.creators.remove(0); + match active.creator.finish(&mut writer).await { + Ok(entries) => { + if let Err(err) = entries.iter().try_for_each(|entry| entry.validate()) { + warn!(err; "Invalid index completion, region_id: {}, file_id: {}", self.region_id, self.file_id); + drop(active); + self.do_abort().await; + return IndexOutput::default(); + } + output.entries.extend(entries); + } + Err(err) => { + if cfg!(any(test, feature = "test")) { + panic!("Failed to finish index: {err:?}"); + } + warn!(err; "Failed to finish index, region_id: {}, file_id: {}, kind: {:?}", self.region_id, self.file_id, active.kind); + drop(active); + self.do_abort().await; + return IndexOutput::default(); + } + } } - - let success = self - .do_finish_fulltext_index(&mut writer, &mut output) - .await; - if !success { - self.do_abort().await; - return IndexOutput::default(); - } - - let success = self.do_finish_bloom_filter(&mut writer, &mut output).await; - if !success { - self.do_abort().await; - return IndexOutput::default(); - } - self.do_prune_intm_sst_dir().await; output.file_size = self.do_finish_puffin_writer(writer).await; - // A failed puffin file must not advertise the indexes written into it. Not covered by - // tests: `do_finish_puffin_writer` panics on failure in test builds. if output.file_size == 0 { return IndexOutput::default(); } @@ -102,200 +98,16 @@ impl Indexer { Err(err) => err, }; - if cfg!(any(test, feature = "test")) { - panic!( - "Failed to finish puffin writer, region_id: {}, file_id: {}, err: {:?}", - self.region_id, self.file_id, err - ); - } else { - warn!( - err; "Failed to finish puffin writer, region_id: {}, file_id: {}", - self.region_id, self.file_id, - ); - } + // Use the production best-effort path in tests as well, so injected + // close failures can verify that no index descriptors are published. + warn!( + err; "Failed to finish puffin writer, region_id: {}, file_id: {}", + self.region_id, self.file_id, + ); 0 } - /// Returns false if the finish failed. - async fn do_finish_inverted_index( - &mut self, - puffin_writer: &mut SstPuffinWriter, - index_output: &mut IndexOutput, - ) -> bool { - let Some(mut indexer) = self.inverted_indexer.take() else { - return true; - }; - - let column_ids = indexer - .indexed_targets() - .filter_map(|target| match target { - IndexTarget::ColumnId(id) => Some(*id), - IndexTarget::JsonPath(_) => None, - }) - .collect(); - let err = match indexer.finish(puffin_writer).await { - Ok((row_count, byte_count)) => { - self.fill_inverted_index_output( - &mut index_output.inverted_index, - row_count, - byte_count, - column_ids, - ); - return true; - } - Err(err) => err, - }; - - if cfg!(any(test, feature = "test")) { - panic!( - "Failed to finish inverted index, region_id: {}, file_id: {}, err: {:?}", - self.region_id, self.file_id, err - ); - } else { - warn!( - err; "Failed to finish inverted index, region_id: {}, file_id: {}", - self.region_id, self.file_id, - ); - } - - false - } - - async fn do_finish_fulltext_index( - &mut self, - puffin_writer: &mut SstPuffinWriter, - index_output: &mut IndexOutput, - ) -> bool { - let Some(mut indexer) = self.fulltext_indexer.take() else { - return true; - }; - - let column_ids = indexer.column_ids().collect(); - index_output.fulltext_bloom_columns = indexer.bloom_column_ids().collect(); - let err = match indexer.finish(puffin_writer).await { - Ok((row_count, byte_count)) => { - self.fill_fulltext_index_output( - &mut index_output.fulltext_index, - row_count, - byte_count, - column_ids, - ); - return true; - } - Err(err) => err, - }; - - if cfg!(any(test, feature = "test")) { - panic!( - "Failed to finish full-text index, region_id: {}, file_id: {}, err: {:?}", - self.region_id, self.file_id, err - ); - } else { - warn!( - err; "Failed to finish full-text index, region_id: {}, file_id: {}", - self.region_id, self.file_id, - ); - } - - false - } - - async fn do_finish_bloom_filter( - &mut self, - puffin_writer: &mut SstPuffinWriter, - index_output: &mut IndexOutput, - ) -> bool { - let Some(mut indexer) = self.bloom_filter_indexer.take() else { - return true; - }; - - let column_ids = indexer - .indexed_targets() - .filter_map(|target| match target { - IndexTarget::ColumnId(id) => Some(*id), - IndexTarget::JsonPath(_) => None, - }) - .collect(); - let err = match indexer.finish(puffin_writer).await { - Ok((row_count, byte_count)) => { - self.fill_bloom_filter_output( - &mut index_output.bloom_filter, - row_count, - byte_count, - column_ids, - ); - return true; - } - Err(err) => err, - }; - - if cfg!(any(test, feature = "test")) { - panic!( - "Failed to finish bloom filter, region_id: {}, file_id: {}, err: {:?}", - self.region_id, self.file_id, err - ); - } else { - warn!( - err; "Failed to finish bloom filter, region_id: {}, file_id: {}", - self.region_id, self.file_id, - ); - } - - false - } - - fn fill_inverted_index_output( - &mut self, - output: &mut InvertedIndexOutput, - row_count: RowCount, - byte_count: ByteCount, - column_ids: Vec, - ) { - debug!( - "Inverted index created, region_id: {}, file_id: {}, written_bytes: {}, written_rows: {}, columns: {:?}", - self.region_id, self.file_id, byte_count, row_count, column_ids - ); - - output.index_size = byte_count; - output.row_count = row_count; - output.columns = column_ids; - } - - fn fill_fulltext_index_output( - &mut self, - output: &mut FulltextIndexOutput, - row_count: RowCount, - byte_count: ByteCount, - column_ids: Vec, - ) { - debug!( - "Full-text index created, region_id: {}, file_id: {}, written_bytes: {}, written_rows: {}, columns: {:?}", - self.region_id, self.file_id, byte_count, row_count, column_ids - ); - - output.index_size = byte_count; - output.row_count = row_count; - output.columns = column_ids; - } - - fn fill_bloom_filter_output( - &mut self, - output: &mut BloomFilterOutput, - row_count: RowCount, - byte_count: ByteCount, - column_ids: Vec, - ) { - debug!( - "Bloom filter created, region_id: {}, file_id: {}, written_bytes: {}, written_rows: {}, columns: {:?}", - self.region_id, self.file_id, byte_count, row_count, column_ids - ); - - output.index_size = byte_count; - output.row_count = row_count; - output.columns = column_ids; - } - pub(crate) async fn do_prune_intm_sst_dir(&mut self) { if let Some(manager) = self.intermediate_manager.take() && let Err(e) = manager.prune_sst_dir(&self.region_id, &self.file_id).await diff --git a/src/mito2/src/sst/index/indexer/update.rs b/src/mito2/src/sst/index/indexer/update.rs index 7e2e1e35022..54cdf254586 100644 --- a/src/mito2/src/sst/index/indexer/update.rs +++ b/src/mito2/src/sst/index/indexer/update.rs @@ -23,203 +23,47 @@ impl Indexer { if batch.is_empty() { return; } - - if !self.do_prepare_primary_key(batch) { + if let Err(err) = self.prepare_primary_key(batch) { + if cfg!(any(test, feature = "test")) { + panic!("Failed to decode primary key for indexes: {err:?}"); + } + warn!(err; "Failed to decode primary key for indexes, region_id: {}, file_id: {}", self.region_id, self.file_id); self.do_abort().await; return; } - - if !self.do_update_inverted_index(batch).await { - self.do_abort().await; + let mut position = 0; + while position < self.creators.len() { + match self.creators[position].creator.update(batch).await { + Ok(()) => position += 1, + Err(err) => { + if cfg!(any(test, feature = "test")) { + panic!("Failed to update index: {err:?}"); + } + warn!(err; "Failed to update index, region_id: {}, file_id: {}, kind: {:?}", self.region_id, self.file_id, self.creators[position].kind); + self.do_abort().await; + return; + } + } } - if !self.do_update_fulltext_index(batch).await { - self.do_abort().await; - } - if !self.do_update_bloom_filter(batch).await { - self.do_abort().await; - } - } - - /// Handles decode errors before entering asynchronous cleanup, following the - /// creators' update policy without carrying a decode error across an await. - fn do_prepare_primary_key(&self, batch: &mut Batch) -> bool { - let Err(err) = self.prepare_primary_key(batch) else { - return true; - }; - if cfg!(any(test, feature = "test")) { - panic!( - "Failed to decode primary key for indexes, region_id: {}, file_id: {}, err: {:?}", - self.region_id, self.file_id, err - ); - } else { - warn!(err; "Failed to decode primary key for indexes, region_id: {}, file_id: {}", self.region_id, self.file_id); - } - false - } - - /// Returns false if the update failed. - async fn do_update_inverted_index(&mut self, batch: &mut Batch) -> bool { - let Some(creator) = self.inverted_indexer.as_mut() else { - return true; - }; - - let Err(err) = creator.update(batch).await else { - return true; - }; - - if cfg!(any(test, feature = "test")) { - panic!( - "Failed to update inverted index, region_id: {}, file_id: {}, err: {:?}", - self.region_id, self.file_id, err - ); - } else { - warn!( - err; "Failed to update inverted index, region_id: {}, file_id: {}", - self.region_id, self.file_id, - ); - } - - false - } - - /// Returns false if the update failed. - async fn do_update_fulltext_index(&mut self, batch: &mut Batch) -> bool { - let Some(creator) = self.fulltext_indexer.as_mut() else { - return true; - }; - - let Err(err) = creator.update(batch).await else { - return true; - }; - - if cfg!(any(test, feature = "test")) { - panic!( - "Failed to update full-text index, region_id: {}, file_id: {}, err: {:?}", - self.region_id, self.file_id, err - ); - } else { - warn!( - err; "Failed to update full-text index, region_id: {}, file_id: {}", - self.region_id, self.file_id, - ); - } - - false - } - - /// Returns false if the update failed. - async fn do_update_bloom_filter(&mut self, batch: &mut Batch) -> bool { - let Some(creator) = self.bloom_filter_indexer.as_mut() else { - return true; - }; - - let Err(err) = creator.update(batch).await else { - return true; - }; - - if cfg!(any(test, feature = "test")) { - panic!( - "Failed to update bloom filter, region_id: {}, file_id: {}, err: {:?}", - self.region_id, self.file_id, err - ); - } else { - warn!( - err; "Failed to update bloom filter, region_id: {}, file_id: {}", - self.region_id, self.file_id, - ); - } - - false } pub(crate) async fn do_update_flat(&mut self, batch: &RecordBatch) { if batch.num_rows() == 0 { return; } - - if !self.do_update_flat_inverted_index(batch).await { - self.do_abort().await; + let mut position = 0; + while position < self.creators.len() { + match self.creators[position].creator.update_flat(batch).await { + Ok(()) => position += 1, + Err(err) => { + if cfg!(any(test, feature = "test")) { + panic!("Failed to update flat index: {err:?}"); + } + warn!(err; "Failed to update flat index, region_id: {}, file_id: {}, kind: {:?}", self.region_id, self.file_id, self.creators[position].kind); + self.do_abort().await; + return; + } + } } - if !self.do_update_flat_fulltext_index(batch).await { - self.do_abort().await; - } - if !self.do_update_flat_bloom_filter(batch).await { - self.do_abort().await; - } - } - - /// Returns false if the update failed. - async fn do_update_flat_inverted_index(&mut self, batch: &RecordBatch) -> bool { - let Some(creator) = self.inverted_indexer.as_mut() else { - return true; - }; - - let Err(err) = creator.update_flat(batch).await else { - return true; - }; - - if cfg!(any(test, feature = "test")) { - panic!( - "Failed to update inverted index with flat format, region_id: {}, file_id: {}, err: {:?}", - self.region_id, self.file_id, err - ); - } else { - warn!( - err; "Failed to update inverted index with flat format, region_id: {}, file_id: {}", - self.region_id, self.file_id, - ); - } - - false - } - - /// Returns false if the update failed. - async fn do_update_flat_fulltext_index(&mut self, batch: &RecordBatch) -> bool { - let Some(creator) = self.fulltext_indexer.as_mut() else { - return true; - }; - - let Err(err) = creator.update_flat(batch).await else { - return true; - }; - - if cfg!(any(test, feature = "test")) { - panic!( - "Failed to update full-text index with flat format, region_id: {}, file_id: {}, err: {:?}", - self.region_id, self.file_id, err - ); - } else { - warn!( - err; "Failed to update full-text index with flat format, region_id: {}, file_id: {}", - self.region_id, self.file_id, - ); - } - - false - } - - /// Returns false if the update failed. - async fn do_update_flat_bloom_filter(&mut self, batch: &RecordBatch) -> bool { - let Some(creator) = self.bloom_filter_indexer.as_mut() else { - return true; - }; - - let Err(err) = creator.update_flat(batch).await else { - return true; - }; - - if cfg!(any(test, feature = "test")) { - panic!( - "Failed to update bloom filter with flat format, region_id: {}, file_id: {}, err: {:?}", - self.region_id, self.file_id, err - ); - } else { - warn!( - err; "Failed to update bloom filter with flat format, region_id: {}, file_id: {}", - self.region_id, self.file_id, - ); - } - - false } } diff --git a/src/mito2/src/sst/index/inverted_index/applier.rs b/src/mito2/src/sst/index/inverted_index/applier.rs index 15b97b68348..fe8814b090c 100644 --- a/src/mito2/src/sst/index/inverted_index/applier.rs +++ b/src/mito2/src/sst/index/inverted_index/applier.rs @@ -31,6 +31,7 @@ use index::inverted_index::search::predicate::Predicate; use index::target::IndexTarget; use object_store::ObjectStore; use puffin::puffin_manager::cache::PuffinMetadataCacheRef; +use puffin::puffin_manager::file_key::PuffinFileKey; use puffin::puffin_manager::{PuffinManager, PuffinReader}; use snafu::ResultExt; use store_api::metadata::{RegionMetadata, RegionMetadataRef}; @@ -47,7 +48,7 @@ use crate::error::{ use crate::metrics::{INDEX_APPLY_ELAPSED, INDEX_APPLY_MEMORY_USAGE}; use crate::sst::file::RegionIndexId; use crate::sst::index::inverted_index::INDEX_BLOB_TYPE; -use crate::sst::index::puffin_manager::{BlobReader, PuffinManagerFactory}; +use crate::sst::index::puffin_manager::{BlobReader, PuffinManagerFactory, SstPuffinManager}; use crate::sst::index::{TYPE_INVERTED_INDEX, trigger_index_background_download}; /// Metrics for tracking inverted index apply operations. @@ -129,6 +130,10 @@ pub(crate) struct InvertedIndexApplier { /// The puffin manager factory. puffin_manager_factory: PuffinManagerFactory, + /// Managers keep backend identity resolution out of per-blob reads. + remote_puffin_manager: SstPuffinManager, + cached_puffin_manager: Option, + /// In-memory cache for inverted index. inverted_index_cache: Option, @@ -163,6 +168,10 @@ impl InvertedIndexApplier { predicates: BTreeMap>, expected_predicate_target_types: BTreeMap, ) -> Result { + let remote_puffin_manager = puffin_manager_factory.build( + store.clone(), + RegionFilePathFactory::new(table_dir.clone(), path_type), + ); let default_plan = Self::build_apply_plan(&predicates)?; INDEX_APPLY_MEMORY_USAGE.add(default_plan.index_applier.memory_usage() as i64); @@ -172,6 +181,8 @@ impl InvertedIndexApplier { store, file_cache: None, puffin_manager_factory, + remote_puffin_manager, + cached_puffin_manager: None, inverted_index_cache: None, puffin_metadata_cache: None, predicates, @@ -182,6 +193,13 @@ impl InvertedIndexApplier { /// Sets the file cache. pub fn with_file_cache(mut self, file_cache: Option) -> Self { + self.cached_puffin_manager = file_cache.as_ref().map(|cache| { + self.puffin_manager_factory.build_cached( + &self.remote_puffin_manager, + cache.local_store(), + WriteCachePathProvider::new(cache.clone()), + ) + }); self.file_cache = file_cache; self } @@ -228,7 +246,7 @@ impl InvertedIndexApplier { }; let mut cache_miss = 0; - let blob = match self.cached_blob_reader(file_id, file_size_hint).await { + let (file_key, blob) = match self.cached_blob_reader(file_id, file_size_hint).await { Ok(Some(puffin_reader)) => puffin_reader, other => { cache_miss += 1; @@ -243,8 +261,7 @@ impl InvertedIndexApplier { let result = if let Some(index_cache) = &self.inverted_index_cache { let mut index_reader = CachedInvertedIndexBlobReader::new( - file_id.file_id(), - file_id.version, + file_key, blob_size, InvertedIndexBlobReader::new(blob), index_cache.clone(), @@ -293,8 +310,10 @@ impl InvertedIndexApplier { &self, file_id: RegionIndexId, file_size_hint: Option, - ) -> Result> { - let Some(file_cache) = &self.file_cache else { + ) -> Result, BlobReader)>> { + let (Some(file_cache), Some(puffin_manager)) = + (&self.file_cache, &self.cached_puffin_manager) + else { return Ok(None); }; @@ -307,11 +326,6 @@ impl InvertedIndexApplier { return Ok(None); }; - let puffin_manager = self.puffin_manager_factory.build( - file_cache.local_store(), - WriteCachePathProvider::new(file_cache.clone()), - ); - // Adds file size hint to the puffin reader to avoid extra metadata read. let reader = puffin_manager .reader(&file_id) @@ -324,7 +338,7 @@ impl InvertedIndexApplier { .reader() .await .context(PuffinBuildReaderSnafu)?; - Ok(Some(reader)) + Ok(Some((puffin_manager.file_key(&file_id), reader))) } /// Creates a blob reader from the remote index file. @@ -332,7 +346,7 @@ impl InvertedIndexApplier { &self, file_id: RegionIndexId, file_size_hint: Option, - ) -> Result { + ) -> Result<(PuffinFileKey, BlobReader)> { let path_factory = RegionFilePathFactory::new(self.table_dir.clone(), self.path_type); // Trigger background download if file cache and file size are available @@ -345,11 +359,11 @@ impl InvertedIndexApplier { ); let puffin_manager = self - .puffin_manager_factory - .build(self.store.clone(), path_factory) + .remote_puffin_manager + .clone() .with_puffin_metadata_cache(self.puffin_metadata_cache.clone()); - puffin_manager + let reader = puffin_manager .reader(&file_id) .await .context(PuffinBuildReaderSnafu)? @@ -359,7 +373,8 @@ impl InvertedIndexApplier { .context(PuffinReadBlobSnafu)? .reader() .await - .context(PuffinBuildReaderSnafu) + .context(PuffinBuildReaderSnafu)?; + Ok((puffin_manager.file_key(&file_id), reader)) } /// Builds a per-SST apply plan. diff --git a/src/mito2/src/sst/index/inverted_index/applier/builder.rs b/src/mito2/src/sst/index/inverted_index/applier/builder.rs index 501f90a082e..4266734a011 100644 --- a/src/mito2/src/sst/index/inverted_index/applier/builder.rs +++ b/src/mito2/src/sst/index/inverted_index/applier/builder.rs @@ -390,6 +390,7 @@ mod tests { data_type: ConcreteDataType::float64_datatype(), inverted_index: true, skipping_index: None, + fulltext_index: None, }], vec![], vec![JsonTypeHint { @@ -397,6 +398,7 @@ mod tests { data_type: ConcreteDataType::int64_datatype(), inverted_index: false, skipping_index: None, + fulltext_index: None, }], ] { let mut sst = metadata.clone(); @@ -656,12 +658,14 @@ mod tests { data_type: ConcreteDataType::string_datatype(), inverted_index, skipping_index: None, + fulltext_index: None, }) .chain(std::iter::once(JsonTypeHint { path: vec!["n".into()], data_type: ConcreteDataType::int64_datatype(), inverted_index: true, skipping_index: None, + fulltext_index: None, })) .collect(); column.with_extension_type(&Json2ExtensionType::new(Arc::new(JsonMetadata::new( diff --git a/src/mito2/src/sst/index/inverted_index/creator.rs b/src/mito2/src/sst/index/inverted_index/creator.rs index 8c12eba6348..3ba073c32d2 100644 --- a/src/mito2/src/sst/index/inverted_index/creator.rs +++ b/src/mito2/src/sst/index/inverted_index/creator.rs @@ -713,6 +713,7 @@ mod tests { data_type: ConcreteDataType::int64_datatype(), inverted_index: true, skipping_index: None, + fulltext_index: None, }], Some(0), ) diff --git a/src/mito2/src/sst/index/kind.rs b/src/mito2/src/sst/index/kind.rs new file mode 100644 index 00000000000..e55c837bc55 --- /dev/null +++ b/src/mito2/src/sst/index/kind.rs @@ -0,0 +1,45 @@ +// 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. + +//! Index identities shared by planning, execution and publication. + +use crate::sst::file::IndexType; + +/// Index implementations supplied by the storage engine. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub(crate) enum IndexKind { + Inverted, + Fulltext, + Bloom, +} + +impl IndexKind { + /// Stable label used by the existing index metrics. + pub(crate) const fn as_str(self) -> &'static str { + match self { + Self::Inverted => "inverted_index", + Self::Fulltext => "fulltext_index", + Self::Bloom => "bloom_filter_index", + } + } + + /// Returns the identity recorded in file and column index metadata. + pub(crate) fn index_type(self) -> IndexType { + match self { + Self::Inverted => IndexType::InvertedIndex, + Self::Fulltext => IndexType::FulltextIndex, + Self::Bloom => IndexType::BloomFilterIndex, + } + } +} diff --git a/src/mito2/src/sst/index/puffin_manager.rs b/src/mito2/src/sst/index/puffin_manager.rs index 26471b4ea32..ea0cb368533 100644 --- a/src/mito2/src/sst/index/puffin_manager.rs +++ b/src/mito2/src/sst/index/puffin_manager.rs @@ -13,14 +13,15 @@ // limitations under the License. use std::path::Path; -use std::sync::Arc; +use std::sync::{Arc, Mutex}; use std::time::Duration; use async_trait::async_trait; use common_error::ext::BoxedError; -use object_store::{FuturesAsyncWriter, ObjectStore}; +use object_store::{FuturesAsyncWriter, ObjectStore, Service, ServiceInfo, Servicer}; use puffin::error::{self as puffin_error, Result as PuffinResult}; use puffin::puffin_manager::file_accessor::PuffinFileAccessor; +use puffin::puffin_manager::file_key::{PuffinFileKey, PuffinStorageScope}; use puffin::puffin_manager::fs_puffin_manager::FsPuffinManager; use puffin::puffin_manager::stager::{BoundedStager, Stager}; use puffin::puffin_manager::{BlobGuard, PuffinManager, PuffinReader}; @@ -38,16 +39,58 @@ use crate::sst::index::store::{self, InstrumentedStore}; type InstrumentedRangeReader = store::InstrumentedRangeReader<'static>; type InstrumentedAsyncWrite = store::InstrumentedAsyncWrite<'static, FuturesAsyncWriter>; -pub(crate) type SstPuffinManager = +pub type SstPuffinManager = FsPuffinManager>, ObjectStorePuffinFileAccessor>; -pub(crate) type SstPuffinReader = ::Reader; -pub(crate) type SstPuffinWriter = ::Writer; -pub(crate) type SstPuffinBlob = ::Blob; -pub(crate) type SstPuffinDir = ::Dir; -pub(crate) type BlobReader = ::Reader; +pub type SstPuffinReader = ::Reader; +pub type SstPuffinWriter = ::Writer; +pub type SstPuffinBlob = ::Blob; +pub type SstPuffinDir = ::Dir; +pub type BlobReader = ::Reader; const STAGING_DIR: &str = "staging"; +/// Reuses a scope across managers built from the same backend instance. +/// Keeping the service alive prevents pointer reuse from aliasing a cached identity. +/// Entries live with the factory and grow with distinct backend instances it encounters. +#[derive(Default)] +struct BackendScopes { + entries: Mutex>, +} + +struct BackendScope { + service: Servicer, + location: ServiceInfo, + scope: Arc, +} + +impl BackendScopes { + fn get(&self, store: &ObjectStore) -> Arc { + let service = store.base_service(); + let location = store.service().info(); + let mut entries = self + .entries + .lock() + .unwrap_or_else(|error| error.into_inner()); + if let Some(entry) = entries + .iter() + .find(|entry| Arc::ptr_eq(&entry.service, service) && entry.location == location) + { + return entry.scope.clone(); + } + let scope = Arc::new(PuffinStorageScope::unique( + location.scheme().to_string(), + location.name().to_string(), + location.root().to_string(), + )); + entries.push(BackendScope { + service: service.clone(), + location, + scope: scope.clone(), + }); + scope + } +} + /// A factory for creating `SstPuffinManager` instances. #[derive(Clone)] pub struct PuffinManagerFactory { @@ -56,6 +99,7 @@ pub struct PuffinManagerFactory { /// The size of the write buffer used to create object store. write_buffer_size: Option, + backend_scopes: Arc, } impl PuffinManagerFactory { @@ -78,20 +122,50 @@ impl PuffinManagerFactory { Ok(Self { stager: Arc::new(stager), write_buffer_size, + backend_scopes: Arc::default(), }) } - pub(crate) fn build( + /// Overrides only this task's upload buffers, sharing the existing stager. + pub(crate) fn with_write_buffer_size(mut self, bytes: usize) -> Self { + self.write_buffer_size = Some(bytes); + self + } + + pub fn build( &self, store: ObjectStore, path_provider: impl FilePathProvider + 'static, ) -> SstPuffinManager { + let scope = self.backend_scopes.get(&store); let store = InstrumentedStore::new(store).with_write_buffer_size(self.write_buffer_size); let puffin_file_accessor = - ObjectStorePuffinFileAccessor::new(store, Arc::new(path_provider)); + ObjectStorePuffinFileAccessor::new(store, Arc::new(path_provider), scope); SstPuffinManager::new(self.stager.clone(), puffin_file_accessor) } + /// Builds a reader manager for an exact local replica of an origin file. + /// + /// `origin` must come from this factory or one of its clones so both managers + /// share the same stager. The replica must contain the origin's exact bytes. + /// Reads use the replica location; cache keys retain the origin's identity. + pub(crate) fn build_cached( + &self, + origin: &SstPuffinManager, + store: ObjectStore, + path_provider: impl FilePathProvider + 'static, + ) -> SstPuffinManager { + let origin = origin.file_accessor(); + let accessor = ObjectStorePuffinFileAccessor { + object_store: InstrumentedStore::new(store) + .with_write_buffer_size(self.write_buffer_size), + path_provider: Arc::new(path_provider), + cache_path_provider: origin.cache_path_provider.clone(), + cache_scope: origin.cache_scope.clone(), + }; + SstPuffinManager::new(self.stager.clone(), accessor) + } + pub(crate) async fn purge_stager(&self, file_id: RegionIndexId) -> Result<()> { self.stager .purge(&file_id) @@ -124,20 +198,28 @@ impl PuffinManagerFactory { /// A `PuffinFileAccessor` implementation that uses an object store as the underlying storage. #[derive(Clone)] -pub(crate) struct ObjectStorePuffinFileAccessor { +pub struct ObjectStorePuffinFileAccessor { object_store: InstrumentedStore, path_provider: Arc, + cache_path_provider: Arc, + cache_scope: Arc, } impl ObjectStorePuffinFileAccessor { - pub fn new(object_store: InstrumentedStore, path_provider: Arc) -> Self { + pub(crate) fn new( + object_store: InstrumentedStore, + path_provider: Arc, + cache_scope: Arc, + ) -> Self { Self { object_store, + cache_path_provider: path_provider.clone(), path_provider, + cache_scope, } } - pub fn store(&self) -> &InstrumentedStore { + pub(crate) fn store(&self) -> &InstrumentedStore { &self.object_store } } @@ -148,6 +230,15 @@ impl PuffinFileAccessor for ObjectStorePuffinFileAccessor { type Writer = InstrumentedAsyncWrite; type FileHandle = RegionIndexId; + fn file_key(&self, handle: &RegionIndexId) -> PuffinFileKey { + PuffinFileKey::new( + self.cache_scope.clone(), + self.cache_path_provider + .build_index_file_path_with_version(*handle), + *handle, + ) + } + async fn reader(&self, handle: &RegionIndexId) -> PuffinResult { let file_path = self .path_provider @@ -210,6 +301,157 @@ mod tests { } } + #[tokio::test] + async fn test_file_key_tracks_storage_path_and_version() { + let (_dir, factory) = PuffinManagerFactory::new_for_test_async("test_file_key_").await; + let store = ObjectStore::new(Memory::default()).unwrap(); + let index_id = RegionIndexId::new(RegionFileId::new(0.into(), FileId::random()), 0); + let manager = factory.build(store.clone(), TestFilePathProvider); + let rebuilt = factory.build(store, TestFilePathProvider); + assert_eq!(manager.file_key(&index_id), rebuilt.file_key(&index_id)); + // Even a path provider that omits the version cannot alias generations. + let next = RegionIndexId::new(index_id.file_id, 1); + assert_ne!(manager.file_key(&index_id), manager.file_key(&next)); + + let other_store = ObjectStore::new(Memory::default()).unwrap(); + let other = factory.build(other_store, TestFilePathProvider); + assert_ne!(manager.file_key(&index_id), other.file_key(&index_id)); + + struct PrefixedPath; + impl FilePathProvider for PrefixedPath { + fn build_index_file_path(&self, id: RegionFileId) -> String { + format!("other/{}", id.file_id()) + } + fn build_index_file_path_with_version(&self, id: RegionIndexId) -> String { + format!("other/{}", id.file_id()) + } + fn build_sst_file_path(&self, id: RegionFileId) -> String { + format!("other/{}", id.file_id()) + } + } + let same_store = manager.file_accessor().store().store().clone(); + let moved = factory.build(same_store, PrefixedPath); + assert_ne!(manager.file_key(&index_id), moved.file_key(&index_id)); + } + + #[tokio::test] + async fn test_cached_replica_reuses_origin_metadata_and_reads_local_bytes() { + use api::v1::index::InvertedIndexMetas; + use puffin::puffin_manager::cache::PuffinMetadataCache; + use store_api::region_request::PathType; + + use crate::access_layer::RegionFilePathFactory; + use crate::cache::index::inverted_index::InvertedIndexCache; + use crate::metrics::CACHE_BYTES; + + let (_dir, factory) = PuffinManagerFactory::new_for_test_async("test_replica_key_").await; + let remote_store = ObjectStore::new(Memory::default()).unwrap(); + let local_store = ObjectStore::new(Memory::default()).unwrap(); + let metadata_cache = Arc::new(PuffinMetadataCache::new(1024 * 1024, &CACHE_BYTES)); + let manager = factory + .build(remote_store.clone(), TestFilePathProvider) + .with_puffin_metadata_cache(Some(metadata_cache.clone())); + let replica = factory + .build_cached( + &manager, + local_store.clone(), + RegionFilePathFactory::new("cached/".into(), PathType::Bare), + ) + .with_puffin_metadata_cache(Some(metadata_cache)); + // Hold the local bytes and path fixed; only cache identity differs. + let isolated_replica = factory.build( + local_store.clone(), + RegionFilePathFactory::new("cached/".into(), PathType::Bare), + ); + let id = RegionIndexId::new(RegionFileId::new(0.into(), FileId::random()), 0); + assert_ne!(manager.file_key(&id), isolated_replica.file_key(&id)); + assert_eq!(manager.file_key(&id), replica.file_key(&id)); + assert_ne!( + manager.file_key(&id), + replica.file_key(&RegionIndexId::new(id.file_id, 1)) + ); + + let bytes = b"read these bytes from the local replica"; + let mut writer = manager.writer(&id).await.unwrap(); + writer + .put_blob( + "blob", + Cursor::new(bytes), + PutOptions::default(), + Default::default(), + ) + .await + .unwrap(); + writer.finish().await.unwrap(); + let remote_path = TestFilePathProvider.build_index_file_path_with_version(id); + let local_path = RegionFilePathFactory::new("cached/".into(), PathType::Bare) + .build_index_file_path_with_version(id); + assert_ne!(remote_path, local_path); + local_store + .write(&local_path, remote_store.read(&remote_path).await.unwrap()) + .await + .unwrap(); + + let metadata = manager.reader(&id).await.unwrap().metadata().await.unwrap(); + remote_store.delete(&remote_path).await.unwrap(); + let reader = replica.reader(&id).await.unwrap(); + assert!(Arc::ptr_eq(&metadata, &reader.metadata().await.unwrap())); + let blob = reader.blob("blob").await.unwrap().reader().await.unwrap(); + assert_eq!(&*blob.read(0..bytes.len() as u64).await.unwrap(), bytes); + + let index_cache = InvertedIndexCache::new(1024 * 1024, 1024 * 1024, 1024); + let index_metadata = Arc::new(InvertedIndexMetas::default()); + index_cache + .put_metadata(manager.file_key(&id), index_metadata.clone()) + .await; + assert!( + index_cache + .get_metadata(isolated_replica.file_key(&id)) + .await + .is_none() + ); + assert!(Arc::ptr_eq( + &index_metadata, + &index_cache + .get_metadata(replica.file_key(&id)) + .await + .unwrap() + )); + } + + #[tokio::test] + async fn test_file_key_isolates_s3_endpoints_without_io() { + let (_dir, factory) = PuffinManagerFactory::new_for_test_async("test_s3_scope_").await; + let build = |endpoint| { + ObjectStore::new( + object_store::services::S3::default() + .bucket("same-bucket") + .root("same-root") + .region("us-east-1") + .endpoint(endpoint), + ) + .unwrap() + }; + let first = build("http://127.0.0.1:19001"); + let second = build("http://127.0.0.1:19002"); + assert_eq!(first.info().scheme(), second.info().scheme()); + assert_eq!(first.info().name(), second.info().name()); + assert_eq!(first.info().root(), second.info().root()); + let index_id = RegionIndexId::new(RegionFileId::new(0.into(), FileId::random()), 0); + let manager = factory.build(first.clone(), TestFilePathProvider); + let reconstructed = factory.clone().build(first.clone(), TestFilePathProvider); + let other = factory.build(second, TestFilePathProvider); + assert_eq!( + manager.file_key(&index_id), + reconstructed.file_key(&index_id) + ); + assert_ne!(manager.file_key(&index_id), other.file_key(&index_id)); + let (_other_dir, other_factory) = + PuffinManagerFactory::new_for_test_async("test_other_scope_").await; + let independent = other_factory.build(first, TestFilePathProvider); + assert_ne!(manager.file_key(&index_id), independent.file_key(&index_id)); + } + #[tokio::test] async fn test_puffin_manager_factory() { let (_dir, factory) = diff --git a/src/mito2/src/sst/index/registry.rs b/src/mito2/src/sst/index/registry.rs new file mode 100644 index 00000000000..7f7c43f3671 --- /dev/null +++ b/src/mito2/src/sst/index/registry.rs @@ -0,0 +1,93 @@ +// 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. + +//! Ordered planning of built-in index implementations. + +use std::sync::Arc; + +use common_error::ext::BoxedError; +use common_telemetry::warn; + +use crate::config::{BloomFilterConfig, FulltextIndexConfig, InvertedIndexConfig}; +use crate::sst::index::handler::builtin::BuiltinIndexHandler; +use crate::sst::index::handler::{IndexKindHandler, PlanContext, PlannedIndex}; + +/// Shared registry installed by the engine. +pub(crate) type IndexRegistryRef = Arc; + +/// Built-in handlers in index creation order. +#[derive(Debug, Clone)] +pub(crate) struct IndexRegistry { + handlers: Vec>, +} + +impl IndexRegistry { + /// Registers the existing built-in creators in their established order. + pub(crate) fn new( + inverted: InvertedIndexConfig, + fulltext: FulltextIndexConfig, + bloom: BloomFilterConfig, + ) -> Self { + Self { + handlers: vec![ + Arc::new(BuiltinIndexHandler::Inverted(inverted)), + Arc::new(BuiltinIndexHandler::Fulltext(fulltext)), + Arc::new(BuiltinIndexHandler::Bloom(bloom)), + ], + } + } + + /// Prepares each handler once, retaining the existing test panic and + /// production log-and-skip policy for construction failures. + pub(crate) fn plan(&self, context: &PlanContext<'_>) -> IndexBuildPlan { + let mut planned = Vec::new(); + for handler in &self.handlers { + match handler.plan(context) { + Ok(Some(plan)) => planned.push(plan), + Ok(None) => {} + Err(err) => { + Self::record_planning_error(handler.as_ref(), context, err); + } + } + } + IndexBuildPlan { planned } + } + + fn record_planning_error( + handler: &dyn IndexKindHandler, + context: &PlanContext<'_>, + err: BoxedError, + ) { + if cfg!(any(test, feature = "test")) { + panic!( + "Failed to prepare built-in index, region_id: {}, err: {err}", + context.metadata.region_id + ); + } + warn!(err; "Failed to prepare index, region_id: {}, kind: {:?}", context.metadata.region_id, handler.kind()); + } +} + +/// Typed plans retained across output files of one operation. +#[derive(Debug, Clone, Default)] +pub(crate) struct IndexBuildPlan { + planned: Vec>, +} + +impl IndexBuildPlan { + /// Plans in index creation order. + pub(crate) fn planned(&self) -> &[Arc] { + &self.planned + } +} diff --git a/src/mito2/src/sst/index/sparse_test.rs b/src/mito2/src/sst/index/sparse_test.rs index c6031d50ad6..e12d77f7903 100644 --- a/src/mito2/src/sst/index/sparse_test.rs +++ b/src/mito2/src/sst/index/sparse_test.rs @@ -37,7 +37,7 @@ use store_api::storage::consts::ReservedColumnId; use super::{IndexBuildType, IndexerBuilder, IndexerBuilderImpl}; use crate::region::options::IndexOptions; -use crate::sst::file::{RegionFileId, RegionIndexId}; +use crate::sst::file::{IndexType, RegionFileId, RegionIndexId}; use crate::sst::index::bloom_filter::creator::tests::TestPathProvider; use crate::sst::index::intermediate::IntermediateManager; use crate::sst::index::puffin_manager::PuffinManagerFactory; @@ -138,9 +138,11 @@ async fn sparse_and_materialized_tags_produce_identical_indexes() { .await .unwrap(), index_options: options, - inverted_index_config: Default::default(), - fulltext_index_config: Default::default(), - bloom_filter_index_config: Default::default(), + registry: Arc::new(crate::sst::index::registry::IndexRegistry::new( + Default::default(), + Default::default(), + Default::default(), + )), }; let mut expected = None; for batch in [materialized, sparse, mixed] { @@ -150,15 +152,22 @@ async fn sparse_and_materialized_tags_produce_identical_indexes() { indexer.update_flat(&batch.slice(0, 2)).await; indexer.update_flat(&batch.slice(2, 9)).await; let output = indexer.finish().await; - assert_eq!(output.inverted_index.row_count, 11); - assert_eq!(output.bloom_filter.row_count, 11); - assert_eq!(output.inverted_index.columns.len(), 4); - assert_eq!(output.bloom_filter.columns.len(), 4); + for kind in [IndexType::InvertedIndex, IndexType::BloomFilterIndex] { + assert_eq!( + output + .entries + .iter() + .filter(|entry| entry.kind.index_type() == kind) + .count(), + 4 + ); + } let reader = puffin.reader(&RegionIndexId::new(file, 0)).await.unwrap(); let blob = reader.blob("greptime-inverted-index-v1").await.unwrap(); let inverted = InvertedIndexBlobReader::new(blob.reader().await.unwrap()); let metas = inverted.metadata(None).await.unwrap(); + assert_eq!(metas.total_row_count, 11); let mut index_bytes = BTreeMap::new(); // Columns can be emitted in a different order; compare each column's FST and bitmaps. for (name, meta) in &metas.metas { diff --git a/src/mito2/src/sst/index/statistics.rs b/src/mito2/src/sst/index/statistics.rs index 698ac29c94e..5d63a0e826b 100644 --- a/src/mito2/src/sst/index/statistics.rs +++ b/src/mito2/src/sst/index/statistics.rs @@ -16,22 +16,28 @@ use std::time::{Duration, Instant}; use crate::metrics::{INDEX_CREATE_BYTES_TOTAL, INDEX_CREATE_ELAPSED, INDEX_CREATE_ROWS_TOTAL}; -pub(crate) type ByteCount = u64; -pub(crate) type RowCount = usize; +pub type ByteCount = u64; +pub type RowCount = usize; /// Stage of the index creation process. enum Stage { Update, + #[cfg(feature = "enterprise")] + Merge, Finish, Cleanup, } /// Statistics for index creation. Flush metrics when dropped. -pub(crate) struct Statistics { +pub struct Statistics { /// Index type. index_type: &'static str, /// Accumulated elapsed time for the index update stage. update_elapsed: Duration, + /// Whether update and total elapsed time can be attributed to this index. + update_timing_available: bool, + /// Accumulated time spent merging existing index states. + merge_elapsed: Duration, /// Accumulated elapsed time for the index finish stage. finish_elapsed: Duration, /// Accumulated elapsed time for the cleanup stage. @@ -43,10 +49,13 @@ pub(crate) struct Statistics { } impl Statistics { + /// Creates index statistics whose accumulated metrics are published on drop. pub fn new(index_type: &'static str) -> Self { Self { index_type, update_elapsed: Duration::default(), + update_timing_available: true, + merge_elapsed: Duration::default(), finish_elapsed: Duration::default(), cleanup_eplased: Duration::default(), row_count: 0, @@ -54,12 +63,38 @@ impl Statistics { } } + /// Creates counters for interleaved work whose update time cannot be attributed + /// to this index. Update and total histograms remain absent until `record_update`. + #[cfg(feature = "enterprise")] + pub fn new_without_update_timing(index_type: &'static str) -> Self { + let mut stats = Self::new(index_type); + stats.update_timing_available = false; + stats + } + + /// Counts rows without taking a clock sample or claiming an update duration. + #[cfg(feature = "enterprise")] + pub fn inc_row_count(&mut self, rows: RowCount) { + self.row_count += rows; + } + /// Starts timing the update stage, returning a `TimerGuard` to automatically record duration. #[must_use] pub fn record_update(&mut self) -> TimerGuard<'_> { + self.update_timing_available = true; TimerGuard::new(self, Stage::Update) } + /// Starts timing merges of existing index states. + /// + /// Merged input rows are represented rows, not newly scanned output rows. Callers + /// count actual output rows separately through the update or finish guard. + #[must_use] + #[cfg(feature = "enterprise")] + pub fn record_merge(&mut self) -> TimerGuard<'_> { + TimerGuard::new(self, Stage::Merge) + } + /// Starts timing the finish stage, returning a `TimerGuard` to automatically record duration. #[must_use] pub fn record_finish(&mut self) -> TimerGuard<'_> { @@ -85,20 +120,33 @@ impl Statistics { impl Drop for Statistics { fn drop(&mut self) { - INDEX_CREATE_ELAPSED - .with_label_values(&["update", self.index_type]) - .observe(self.update_elapsed.as_secs_f64()); + if self.update_timing_available { + INDEX_CREATE_ELAPSED + .with_label_values(&["update", self.index_type]) + .observe(self.update_elapsed.as_secs_f64()); + } + if !self.merge_elapsed.is_zero() { + INDEX_CREATE_ELAPSED + .with_label_values(&["merge", self.index_type]) + .observe(self.merge_elapsed.as_secs_f64()); + } INDEX_CREATE_ELAPSED .with_label_values(&["finish", self.index_type]) .observe(self.finish_elapsed.as_secs_f64()); INDEX_CREATE_ELAPSED .with_label_values(&["cleanup", self.index_type]) .observe(self.cleanup_eplased.as_secs_f64()); - INDEX_CREATE_ELAPSED - .with_label_values(&["total", self.index_type]) - .observe( - (self.update_elapsed + self.finish_elapsed + self.cleanup_eplased).as_secs_f64(), - ); + if self.update_timing_available { + INDEX_CREATE_ELAPSED + .with_label_values(&["total", self.index_type]) + .observe( + (self.update_elapsed + + self.merge_elapsed + + self.finish_elapsed + + self.cleanup_eplased) + .as_secs_f64(), + ); + } INDEX_CREATE_ROWS_TOTAL .with_label_values(&[self.index_type]) @@ -111,7 +159,7 @@ impl Drop for Statistics { /// `TimerGuard` is a RAII struct that ensures elapsed time /// is recorded when it goes out of scope. -pub(crate) struct TimerGuard<'a> { +pub struct TimerGuard<'a> { stats: &'a mut Statistics, stage: Stage, timer: Instant, @@ -144,6 +192,10 @@ impl Drop for TimerGuard<'_> { Stage::Update => { self.stats.update_elapsed += self.timer.elapsed(); } + #[cfg(feature = "enterprise")] + Stage::Merge => { + self.stats.merge_elapsed += self.timer.elapsed(); + } Stage::Finish => { self.stats.finish_elapsed += self.timer.elapsed(); } @@ -158,6 +210,46 @@ impl Drop for TimerGuard<'_> { mod tests { use super::*; + #[cfg(feature = "enterprise")] + #[test] + fn test_unmeasured_updates_do_not_publish_zero_durations() { + let name = "test_sketch_fused_counter_only"; + let update = INDEX_CREATE_ELAPSED.with_label_values(&["update", name]); + let total = INDEX_CREATE_ELAPSED.with_label_values(&["total", name]); + let update_before = update.get_sample_count(); + let total_before = total.get_sample_count(); + let mut stats = Statistics::new_without_update_timing(name); + stats.inc_row_count(7); + assert_eq!(stats.row_count(), 7); + drop(stats); + assert_eq!(update.get_sample_count(), update_before); + assert_eq!(total.get_sample_count(), total_before); + let mut measured = Statistics::new_without_update_timing(name); + { + let _timer = measured.record_update(); + } + drop(measured); + assert_eq!(update.get_sample_count(), update_before + 1); + assert_eq!(total.get_sample_count(), total_before + 1); + } + + #[cfg(feature = "enterprise")] + #[test] + fn test_merge_does_not_count_input_rows_as_output_rows() { + let mut stats = Statistics::new("test_merge"); + { + let _guard = stats.record_merge(); + } + assert_eq!(stats.row_count(), 0); + { + let mut guard = stats.record_finish(); + guard.inc_row_count(7); + guard.inc_byte_count(32); + } + assert_eq!(stats.row_count(), 7); + assert_eq!(stats.byte_count(), 32); + } + #[test] fn test_statistics_basic() { let mut stats = Statistics::new("test"); diff --git a/src/mito2/src/sst/index/store.rs b/src/mito2/src/sst/index/store.rs index 0a99744986a..f33159de5c1 100644 --- a/src/mito2/src/sst/index/store.rs +++ b/src/mito2/src/sst/index/store.rs @@ -154,7 +154,7 @@ impl InstrumentedStore { /// A wrapper around [`AsyncRead`] that adds instrumentation for monitoring #[pin_project] -pub(crate) struct InstrumentedAsyncRead<'a, R> { +pub struct InstrumentedAsyncRead<'a, R> { #[pin] inner: R, read_byte_count: CounterGuard<'a>, @@ -210,7 +210,7 @@ impl AsyncSeek for InstrumentedAsyncRead<'_, R> { /// A wrapper around [`AsyncWrite`] that adds instrumentation for monitoring #[pin_project] -pub(crate) struct InstrumentedAsyncWrite<'a, W> { +pub struct InstrumentedAsyncWrite<'a, W> { #[pin] inner: W, write_byte_count: CounterGuard<'a>, @@ -266,7 +266,7 @@ impl AsyncWrite for InstrumentedAsyncWrite<'_, W> const FETCH_CONCURRENCY: usize = 8; /// Implements `RangeReader` for `ObjectStore` and record metrics. -pub(crate) struct InstrumentedRangeReader<'a> { +pub struct InstrumentedRangeReader<'a> { store: ObjectStore, path: String, read_byte_count: &'a IntCounter, diff --git a/src/mito2/src/sst/parquet.rs b/src/mito2/src/sst/parquet.rs index 381b1ba4647..b8a8395088b 100644 --- a/src/mito2/src/sst/parquet.rs +++ b/src/mito2/src/sst/parquet.rs @@ -1491,6 +1491,48 @@ mod tests { ); } + async fn assert_inverted_and_bloom_artifacts( + manager: &crate::sst::index::puffin_manager::SstPuffinManager, + region_id: RegionId, + info: &SstInfo, + ) { + use crate::sst::file::{IndexType, RegionFileId, RegionIndexId}; + use index::bloom_filter::reader::{BloomFilterReader, BloomFilterReaderImpl}; + use index::inverted_index::format::reader::{InvertedIndexBlobReader, InvertedIndexReader}; + use puffin::puffin_manager::{PuffinManager, PuffinReader}; + + let columns = |kind| { + info.index_metadata + .entries + .iter() + .filter(|entry| entry.kind.index_type() == kind) + .filter_map(|entry| entry.column_id) + .collect::>() + }; + assert_eq!(columns(IndexType::InvertedIndex), vec![0]); + assert_eq!(columns(IndexType::BloomFilterIndex), vec![1]); + let reader = manager + .reader(&RegionIndexId::new( + RegionFileId::new(region_id, info.file_id), + info.index_metadata.version, + )) + .await + .unwrap(); + let blob = reader.blob("greptime-inverted-index-v1").await.unwrap(); + assert!(blob.metadata().length > 0); + let inverted = InvertedIndexBlobReader::new(blob.reader().await.unwrap()); + let metadata = inverted.metadata(None).await.unwrap(); + assert_eq!(metadata.total_row_count, 200); + assert_eq!( + metadata.metas.keys().cloned().collect::>(), + vec!["0".to_string()] + ); + let blob = reader.blob("greptime-bloom-filter-v1-1").await.unwrap(); + assert!(blob.metadata().length > 0); + let bloom = BloomFilterReaderImpl::new(blob.reader().await.unwrap()); + assert_eq!(bloom.metadata(None).await.unwrap().row_count, 200); + } + #[tokio::test] async fn test_write_read_with_index() { let mut env = TestEnv::new().await; @@ -1529,9 +1571,11 @@ mod tests { ..Default::default() }, }, - inverted_index_config: Default::default(), - fulltext_index_config: Default::default(), - bloom_filter_index_config: Default::default(), + registry: Arc::new(crate::sst::index::registry::IndexRegistry::new( + Default::default(), + Default::default(), + Default::default(), + )), }; let mut metrics = Metrics::new(WriteType::Flush); @@ -1554,13 +1598,13 @@ mod tests { assert!(info.file_size > 0); assert!(info.index_metadata.file_size > 0); - assert!(info.index_metadata.inverted_index.index_size > 0); - assert_eq!(info.index_metadata.inverted_index.row_count, 200); - assert_eq!(info.index_metadata.inverted_index.columns, vec![0]); - - assert!(info.index_metadata.bloom_filter.index_size > 0); - assert_eq!(info.index_metadata.bloom_filter.row_count, 200); - assert_eq!(info.index_metadata.bloom_filter.columns, vec![1]); + assert_inverted_and_bloom_artifacts( + &env.get_puffin_manager() + .build(object_store.clone(), file_path.clone()), + metadata.region_id, + &info, + ) + .await; assert_eq!( ( @@ -1579,7 +1623,7 @@ mod tests { file_size: info.file_size, max_row_group_uncompressed_size: info.max_row_group_uncompressed_size, available_indexes: info.index_metadata.build_available_indexes(), - indexes: info.index_metadata.build_indexes(), + indexes: info.index_metadata.build_indexes().unwrap(), index_file_size: info.index_metadata.file_size, index_version: 0, num_row_groups: info.num_row_groups, @@ -2073,9 +2117,11 @@ mod tests { ..Default::default() }, }, - inverted_index_config: Default::default(), - fulltext_index_config: Default::default(), - bloom_filter_index_config: Default::default(), + registry: Arc::new(crate::sst::index::registry::IndexRegistry::new( + Default::default(), + Default::default(), + Default::default(), + )), } } @@ -2120,7 +2166,7 @@ mod tests { file_size: info.file_size, max_row_group_uncompressed_size: info.max_row_group_uncompressed_size, available_indexes: info.index_metadata.build_available_indexes(), - indexes: info.index_metadata.build_indexes(), + indexes: info.index_metadata.build_indexes().unwrap(), index_file_size: info.index_metadata.file_size, index_version: 0, num_row_groups: info.num_row_groups, @@ -2192,9 +2238,11 @@ mod tests { ..Default::default() }, }, - inverted_index_config: Default::default(), - fulltext_index_config: Default::default(), - bloom_filter_index_config: Default::default(), + registry: Arc::new(crate::sst::index::registry::IndexRegistry::new( + Default::default(), + Default::default(), + Default::default(), + )), }; let mut metrics = Metrics::new(WriteType::Flush); @@ -2217,13 +2265,13 @@ mod tests { assert!(info.file_size > 0); assert!(info.index_metadata.file_size > 0); - assert!(info.index_metadata.inverted_index.index_size > 0); - assert_eq!(info.index_metadata.inverted_index.row_count, 200); - assert_eq!(info.index_metadata.inverted_index.columns, vec![0]); - - assert!(info.index_metadata.bloom_filter.index_size > 0); - assert_eq!(info.index_metadata.bloom_filter.row_count, 200); - assert_eq!(info.index_metadata.bloom_filter.columns, vec![1]); + assert_inverted_and_bloom_artifacts( + &env.get_puffin_manager() + .build(object_store.clone(), file_path.clone()), + metadata.region_id, + &info, + ) + .await; assert_eq!( ( @@ -3154,7 +3202,7 @@ mod tests { metadata.clone(), ); - let mut info = write_flat_sst( + let info = write_flat_sst( object_store.clone(), metadata.clone(), indexer_builder, @@ -3167,12 +3215,49 @@ mod tests { assert!(info.file_size > 0); assert!(info.index_metadata.file_size > 0); - // Verify fulltext indexes were created - assert!(info.index_metadata.fulltext_index.index_size > 0); - assert_eq!(info.index_metadata.fulltext_index.row_count, 200); - // text_bloom (column_id 1) and text_tantivy (column_id 2) - info.index_metadata.fulltext_index.columns.sort_unstable(); - assert_eq!(info.index_metadata.fulltext_index.columns, vec![1, 2]); + // Verify both persisted backends, not just their output descriptors. + use crate::sst::file::{RegionFileId, RegionIndexId}; + use crate::sst::index::kind::IndexKind; + use index::bloom_filter::reader::{BloomFilterReader, BloomFilterReaderImpl}; + use puffin::puffin_manager::{PuffinManager, PuffinReader}; + let mut columns = info + .index_metadata + .entries + .iter() + .filter(|entry| entry.kind == IndexKind::Fulltext) + .filter_map(|entry| entry.column_id) + .collect::>(); + columns.sort_unstable(); + assert_eq!(columns, vec![1, 2]); + let manager = env + .get_puffin_manager() + .build(object_store.clone(), file_path.clone()); + let reader = manager + .reader(&RegionIndexId::new( + RegionFileId::new(metadata.region_id, info.file_id), + info.index_metadata.version, + )) + .await + .unwrap(); + let footer = reader.metadata().await.unwrap(); + for key in [ + "greptime-fulltext-index-bloom-v2-1", + "greptime-fulltext-index-v1-2", + ] { + assert!( + footer + .blobs + .iter() + .any(|blob| blob.blob_type == key && blob.length > 0) + ); + } + let blob = reader + .blob("greptime-fulltext-index-bloom-v2-1") + .await + .unwrap(); + let bloom = BloomFilterReaderImpl::new(blob.reader().await.unwrap()); + assert_eq!(bloom.metadata(None).await.unwrap().row_count, 200); + // The following query assertions exercise both backends against all 200 rows. assert_eq!( ( diff --git a/src/mito2/src/sst/parquet/json_align.rs b/src/mito2/src/sst/parquet/json_align.rs index aa891dcef27..19d88afa2d2 100644 --- a/src/mito2/src/sst/parquet/json_align.rs +++ b/src/mito2/src/sst/parquet/json_align.rs @@ -837,6 +837,7 @@ mod tests { data_type: ConcreteDataType::string_datatype(), inverted_index: false, skipping_index: None, + fulltext_index: None, }], Some(0), ) diff --git a/src/mito2/src/sst/parquet/reader.rs b/src/mito2/src/sst/parquet/reader.rs index 3f89d80bb91..e92ac60f93b 100644 --- a/src/mito2/src/sst/parquet/reader.rs +++ b/src/mito2/src/sst/parquet/reader.rs @@ -61,10 +61,7 @@ use crate::error::{ ParquetToArrowSchemaSnafu, ReadDataPartSnafu, Result, SerializePartitionExprSnafu, UnexpectedSnafu, }; -use crate::metrics::{ - PRECISE_FILTER_ROWS_TOTAL, READ_ROW_GROUPS_TOTAL, READ_ROWS_IN_ROW_GROUP_TOTAL, - READ_ROWS_TOTAL, READ_STAGE_ELAPSED, -}; +use crate::metrics::{READ_ROWS_TOTAL, READ_STAGE_ELAPSED}; use crate::read::flat_projection::CompactionProjectionMapper; use crate::read::prune::FlatPruneReader; use crate::read::read_columns::ReadColumns; @@ -977,6 +974,7 @@ impl ParquetReaderBuilder { let fulltext_filtered = self .prune_row_groups_by_fulltext_index( + read_format.metadata(), row_group_size, num_row_groups, &mut output, @@ -1016,6 +1014,7 @@ impl ParquetReaderBuilder { if !fulltext_filtered { self.prune_row_groups_by_fulltext_bloom( + read_format.metadata(), row_group_size, parquet_meta, &mut output, @@ -1030,6 +1029,7 @@ impl ParquetReaderBuilder { /// Prunes row groups by fulltext index. Returns `true` if the row groups are pruned. async fn prune_row_groups_by_fulltext_index( &self, + sst_metadata: &RegionMetadataRef, row_group_size: usize, num_row_groups: usize, output: &mut RowGroupSelection, @@ -1048,12 +1048,16 @@ impl ParquetReaderBuilder { &self.fulltext_index_appliers[..] }; for index_applier in appliers.iter().flatten() { - let predicate_key = index_applier.predicate_key(); + // Filter out index requests incompatible with this SST. + let Some(requests) = index_applier.compatible_requests_for_sst(sst_metadata) else { + continue; + }; + let predicate_key = PredicateKey::new_fulltext(requests.clone()); // Fast path: return early if the result is in the cache. let cached = self .cache_strategy .index_result_cache() - .and_then(|cache| cache.get(predicate_key, self.file_handle.file_id().file_id())); + .and_then(|cache| cache.get(&predicate_key, self.file_handle.file_id().file_id())); if let Some(result) = cached.as_ref() && all_required_row_groups_searched(output, result) { @@ -1070,6 +1074,7 @@ impl ParquetReaderBuilder { .apply_fine( self.file_handle.index_id(), Some(file_size_hint), + &requests, metrics.fulltext_index_apply_metrics.as_mut(), ) .await; @@ -1085,7 +1090,7 @@ impl ParquetReaderBuilder { }; self.apply_index_result_and_update_cache( - predicate_key, + &predicate_key, self.file_handle.file_id().file_id(), selection, output, @@ -1291,6 +1296,7 @@ impl ParquetReaderBuilder { async fn prune_row_groups_by_fulltext_bloom( &self, + sst_metadata: &RegionMetadataRef, row_group_size: usize, parquet_meta: &ParquetMetaData, output: &mut RowGroupSelection, @@ -1309,12 +1315,16 @@ impl ParquetReaderBuilder { &self.fulltext_index_appliers[..] }; for index_applier in appliers.iter().flatten() { - let predicate_key = index_applier.predicate_key(); + // Filter out index requests incompatible with this SST. + let Some(requests) = index_applier.compatible_requests_for_sst(sst_metadata) else { + continue; + }; + let predicate_key = PredicateKey::new_fulltext(requests.clone()); // Fast path: return early if the result is in the cache. let cached = self .cache_strategy .index_result_cache() - .and_then(|cache| cache.get(predicate_key, self.file_handle.file_id().file_id())); + .and_then(|cache| cache.get(&predicate_key, self.file_handle.file_id().file_id())); if let Some(result) = cached.as_ref() && all_required_row_groups_searched(output, result) { @@ -1343,6 +1353,7 @@ impl ParquetReaderBuilder { self.file_handle.index_id(), Some(file_size_hint), rgs, + &requests, metrics.fulltext_index_apply_metrics.as_mut(), ) .await; @@ -1363,7 +1374,7 @@ impl ParquetReaderBuilder { } self.apply_index_result_and_update_cache( - predicate_key, + &predicate_key, self.file_handle.file_id().file_id(), selection, output, @@ -1630,41 +1641,6 @@ impl ReaderFilterMetrics { } } - /// Reports metrics. - pub(crate) fn observe(&self) { - READ_ROW_GROUPS_TOTAL - .with_label_values(&["before_filtering"]) - .inc_by(self.rg_total as u64); - READ_ROW_GROUPS_TOTAL - .with_label_values(&["fulltext_index_filtered"]) - .inc_by(self.rg_fulltext_filtered as u64); - READ_ROW_GROUPS_TOTAL - .with_label_values(&["inverted_index_filtered"]) - .inc_by(self.rg_inverted_filtered as u64); - READ_ROW_GROUPS_TOTAL - .with_label_values(&["minmax_index_filtered"]) - .inc_by(self.rg_minmax_filtered as u64); - READ_ROW_GROUPS_TOTAL - .with_label_values(&["bloom_filter_index_filtered"]) - .inc_by(self.rg_bloom_filtered as u64); - - PRECISE_FILTER_ROWS_TOTAL - .with_label_values(&["parquet"]) - .inc_by(self.rows_precise_filtered as u64); - READ_ROWS_IN_ROW_GROUP_TOTAL - .with_label_values(&["before_filtering"]) - .inc_by(self.rows_total as u64); - READ_ROWS_IN_ROW_GROUP_TOTAL - .with_label_values(&["fulltext_index_filtered"]) - .inc_by(self.rows_fulltext_filtered as u64); - READ_ROWS_IN_ROW_GROUP_TOTAL - .with_label_values(&["inverted_index_filtered"]) - .inc_by(self.rows_inverted_filtered as u64); - READ_ROWS_IN_ROW_GROUP_TOTAL - .with_label_values(&["bloom_filter_index_filtered"]) - .inc_by(self.rows_bloom_filtered as u64); - } - fn update_index_metrics(&mut self, index_type: &str, row_group_count: usize, row_count: usize) { match index_type { INDEX_TYPE_FULLTEXT => { @@ -2453,6 +2429,20 @@ impl ParquetReader { pub fn parquet_metadata(&self) -> Arc { self.context.reader_builder().parquet_meta.clone() } + + #[cfg(feature = "enterprise")] + pub(crate) fn fetched_store_page_bytes(&self) -> Result { + self.fetch_metrics + .data + .lock() + .map(|metrics| metrics.page_size_to_fetch_store) + .map_err(|_| { + crate::error::UnexpectedSnafu { + reason: "Source fetch metrics lock poisoned", + } + .build() + }) + } } /// Reader to read a row group of a parquet file in flat format, returning RecordBatch. diff --git a/src/mito2/src/sst/parquet/writer.rs b/src/mito2/src/sst/parquet/writer.rs index d7656d8c354..3b4c02b3080 100644 --- a/src/mito2/src/sst/parquet/writer.rs +++ b/src/mito2/src/sst/parquet/writer.rs @@ -38,10 +38,10 @@ use object_store::{FuturesAsyncWriter, ObjectStore}; use parquet::arrow::AsyncArrowWriter; use parquet::arrow::async_writer::AsyncFileWriter; use parquet::basic::{Compression, Encoding, ZstdLevel}; -use parquet::file::metadata::{KeyValue, ParquetMetaData}; +use parquet::file::metadata::{FileMetaData, KeyValue, ParquetMetaData}; use parquet::file::properties::WriterProperties; use smallvec::smallvec; -use snafu::{OptionExt, ResultExt}; +use snafu::{OptionExt, ResultExt, ensure}; use store_api::metadata::RegionMetadataRef; use store_api::storage::{FileId, SequenceNumber}; use tokio::io::AsyncWrite; @@ -193,6 +193,39 @@ impl SstArrowWriter { } } +/// Optional limits used by multi-output compaction. A batch may temporarily +/// exceed the working threshold before its check; callers reserve that workspace. +#[derive(Clone, Copy)] +pub(crate) struct SstWriteLimits { + pub(crate) working_bytes: usize, + pub(crate) metadata_bytes: usize, +} + +/// Tracks retained footer memory across rolled files as well as the current file. +#[derive(Default)] +struct WriteMemory { + limits: Option, + completed: usize, + current: usize, + row_groups: usize, +} + +impl WriteMemory { + fn check(&self, bytes: usize) -> Result<()> { + if let Some(limits) = self.limits { + ensure!( + bytes <= limits.metadata_bytes, + crate::error::SstWriteMemoryExceededSnafu { + kind: "metadata", + bytes, + limit: limits.metadata_bytes, + } + ); + } + Ok(()) + } +} + /// Parquet SST writer. pub struct ParquetWriter<'a, F: WriterFactory, I: IndexerBuilder, P: FilePathProvider> { /// Path provider that creates SST and index file paths according to file id. @@ -214,6 +247,20 @@ pub struct ParquetWriter<'a, F: WriterFactory, I: IndexerBuilder, P: FilePathPro file_cleaner: Option, /// Write metrics metrics: &'a mut Metrics, + write_guard: Option>, + memory: WriteMemory, +} + +/// Registers durable ownership before either an SST or its index is published to storage. +#[async_trait::async_trait] +pub trait SstWriteGuard: Send + Sync { + async fn before_create(&self, file_id: RegionFileId) -> Result<()>; +} + +/// Protection and resource limits travel together for table-compaction output. +pub(crate) struct SstWriteContext { + pub(crate) guard: Arc, + pub(crate) limits: SstWriteLimits, } pub trait WriterFactory { @@ -227,6 +274,7 @@ pub trait WriterFactory { pub struct ObjectStoreWriterFactory { object_store: ObjectStore, + concurrency: usize, } impl WriterFactory for ObjectStoreWriterFactory { @@ -236,7 +284,7 @@ impl WriterFactory for ObjectStoreWriterFactory { self.object_store .writer_with(file_path) .chunk(write_buffer_size) - .concurrent(DEFAULT_WRITE_CONCURRENCY) + .concurrent(self.concurrency) .await .map(|v| v.into_futures_async_write().compat_write()) .context(OpenDalSnafu) @@ -248,6 +296,11 @@ where P: FilePathProvider, I: IndexerBuilder, { + pub(crate) fn with_write_concurrency(mut self, concurrency: usize) -> Self { + self.writer_factory.concurrency = concurrency; + self + } + pub async fn new_with_object_store( object_store: ObjectStore, metadata: RegionMetadataRef, @@ -257,7 +310,10 @@ where metrics: &'a mut Metrics, ) -> ParquetWriter<'a, ObjectStoreWriterFactory, I, P> { ParquetWriter::new( - ObjectStoreWriterFactory { object_store }, + ObjectStoreWriterFactory { + object_store, + concurrency: DEFAULT_WRITE_CONCURRENCY, + }, metadata, index_config, indexer_builder, @@ -289,9 +345,6 @@ where metrics: &'a mut Metrics, ) -> ParquetWriter<'a, F, I, P> { let init_file = FileId::random(); - let indexer = indexer_builder - .build(RegionFileId::new(metadata.region_id, init_file), 0, None) - .await; ParquetWriter { path_provider, @@ -301,13 +354,55 @@ where metadata, index_config, indexer_builder, - current_indexer: Some(indexer), + // Build lazily with the actual row-group size, after the write guard. + current_indexer: None, + memory: WriteMemory::default(), bytes_written: Arc::new(AtomicUsize::new(0)), file_cleaner: None, metrics, + write_guard: None, } } + pub(crate) fn with_write_guard(mut self, guard: Option>) -> Self { + self.write_guard = guard; + self + } + + pub(crate) fn with_memory_limits(mut self, limits: Option) -> Self { + self.memory.limits = limits; + self + } + + /// Checks encoding state without flushing a partial row group: readers and + /// index row IDs require uniform row-group lengths except for the final one. + /// Only new footer entries are measured, avoiding quadratic footer walks. + async fn check_memory(&mut self) -> Result<()> { + let Some(limits) = self.memory.limits else { + return Ok(()); + }; + if let Some(SstArrowWriter::Serial(writer)) = &mut self.writer { + ensure!( + writer.memory_size() <= limits.working_bytes, + crate::error::SstWriteMemoryExceededSnafu { + kind: "encoder", + bytes: writer.memory_size(), + limit: limits.working_bytes, + } + ); + for group in &writer.flushed_row_groups()[self.memory.row_groups..] { + let file = FileMetaData::new(1, 0, None, None, group.schema_descr_ptr(), None); + // Reuse Parquet's heap estimator; counting the schema per group + // is conservative, including variable-length min/max statistics. + let metadata = ParquetMetaData::new(file, vec![group.clone()]); + self.memory.current = self.memory.current.saturating_add(metadata.memory_size()); + } + self.memory.row_groups = writer.flushed_row_groups().len(); + } + self.memory + .check(self.memory.completed.saturating_add(self.memory.current)) + } + /// Finishes current SST file and index file. async fn finish_current_file( &mut self, @@ -345,6 +440,15 @@ where let parquet_metadata = current_writer.close().await.context(WriteParquetSnafu)?; let file_size = self.bytes_written.load(Ordering::Relaxed) as u64; + if self.memory.limits.is_some() { + self.memory.completed = self.memory.completed.saturating_add( + parquet_metadata.memory_size().saturating_mul(2) + + std::mem::size_of::(), + ); + self.memory.check(self.memory.completed)?; + self.memory.current = 0; + self.memory.row_groups = 0; + } // Safety: num rows > 0 so we must have min/max. let time_range = stats.time_range.unwrap(); @@ -542,6 +646,10 @@ where } .await; + let result = match result { + Ok(()) => self.check_memory().await, + Err(error) => Err(error), + }; if result.is_err() { self.abort_current_indexer().await; } @@ -601,6 +709,14 @@ where self.metadata.region_id, self.current_file, )); + if let Some(guard) = &self.write_guard { + guard + .before_create(RegionFileId::new( + self.metadata.region_id, + self.current_file, + )) + .await?; + } let writer = SizeAwareWriter::new( self.writer_factory .create(&sst_file_path, opts.write_buffer_size.as_bytes() as usize) @@ -608,7 +724,8 @@ where self.bytes_written.clone(), ); let schema = maybe_wrap_schema(schema)?; - let arrow_writer = if opts.encode_parallelism > 1 + let arrow_writer = if self.memory.limits.is_none() + && opts.encode_parallelism > 1 && ParallelArrowWriter::>::supports(&writer_props) { SstArrowWriter::Parallel( diff --git a/src/mito2/src/sst/version.rs b/src/mito2/src/sst/version.rs index 5351195eefb..0f040d3bb3f 100644 --- a/src/mito2/src/sst/version.rs +++ b/src/mito2/src/sst/version.rs @@ -21,7 +21,7 @@ use common_time::{TimeToLive, Timestamp}; use store_api::metadata::RegionMetadataRef; use store_api::storage::{FileId, RegionId}; -use crate::sst::file::{FileHandle, FileMeta, FileTimeRange, Level, MAX_LEVEL}; +use crate::sst::file::{self, FileHandle, FileMeta, FileTimeRange, Level}; use crate::sst::file_purger::FilePurgerRef; use crate::sst::primary_key::PrimaryKeyRangeMapper; @@ -73,7 +73,7 @@ impl SstVersion { /// it will be overwritten with the new file. /// /// # Panics - /// Panics if level of [FileMeta] is greater than [MAX_LEVEL]. + /// Panics if the level of [FileMeta] has no storage slot. pub(crate) fn add_files( &mut self, file_purger: FilePurgerRef, @@ -83,8 +83,18 @@ impl SstVersion { for file in files_to_add { let level = file.level; let new_index_version = file.index_version; + // A trusted L0 adoption changes classification, not the physical object. + // Detach the old handle without marking it deleted (old readers may hold it). + // Admission rejects an existing L1 reference; see `prepare_region_edit`. + if level == file::LEVEL_SHARED { + levels[0].files.remove(&file.file_id); + } + // Shared references use a sentinel wire level and live in their own slot. + let Some(slot) = file::level_slot(level) else { + panic!("Unsupported SST level {level}"); + }; // If the file already exists, then we should only replace the handle when the index is outdated. - levels[level as usize] + levels[slot] .files .entry(file.file_id) .and_modify(|f| { @@ -112,12 +122,14 @@ impl SstVersion { /// Remove files from the version. /// /// # Panics - /// Panics if level of [FileMeta] is greater than [MAX_LEVEL]. + /// Panics if the level of [FileMeta] has no storage slot. pub(crate) fn remove_files(&mut self, files_to_remove: impl Iterator) { let levels = Arc::make_mut(&mut self.levels); for file in files_to_remove { - let level = file.level; - if let Some(handle) = levels[level as usize].files.remove(&file.file_id) { + let Some(slot) = file::level_slot(file.level) else { + panic!("Unsupported SST level {}", file.level); + }; + if let Some(handle) = levels[slot].files.remove(&file.file_id) { handle.mark_deleted(); } } @@ -217,7 +229,7 @@ impl SstVersion { // We only has fixed number of level, so we use array to hold elements. This implementation // detail of LevelMetaArray should not be exposed to users of [LevelMetas]. -type LevelMetaArray = [LevelMeta; MAX_LEVEL as usize]; +type LevelMetaArray = [LevelMeta; file::LEVEL_SLOT_COUNT]; /// Metadata of files in the same SST level. #[derive(Clone)] @@ -271,11 +283,12 @@ impl fmt::Debug for LevelMeta { } fn new_level_meta_vec() -> LevelMetaArray { - (0u8..MAX_LEVEL) - .map(LevelMeta::new) - .collect::>() - .try_into() - .unwrap() // safety: LevelMetaArray is a fixed length array with length MAX_LEVEL + // Slot 2 keeps the sentinel wire level so level-based filters still see shared files. + [ + LevelMeta::new(0), + LevelMeta::new(1), + LevelMeta::new(file::LEVEL_SHARED), + ] } #[cfg(test)] diff --git a/src/mito2/src/test_util.rs b/src/mito2/src/test_util.rs index 1d742505df4..29718163528 100644 --- a/src/mito2/src/test_util.rs +++ b/src/mito2/src/test_util.rs @@ -63,6 +63,7 @@ use rskafka::client::partition::{Compression, UnknownTopicHandling}; use rskafka::client::{Client, ClientBuilder}; use rskafka::record::Record; use rstest_reuse::template; +use store_api::ManifestVersion; use store_api::logstore::LogStore; use store_api::metadata::{ColumnMetadata, RegionMetadataRef}; use store_api::region_engine::{RegionEngine, RegionRole}; @@ -79,8 +80,11 @@ use crate::engine::listener::EventListenerRef; use crate::engine::{MITO_ENGINE_NAME, MitoEngine}; use crate::error::Result; use crate::flush::{WriteBufferManager, WriteBufferManagerRef}; +use crate::manifest::action::{RegionEdit, RegionMetaAction, RegionMetaActionList}; use crate::manifest::manager::{RegionManifestManager, RegionManifestOptions}; -use crate::manifest::storage::{is_checkpoint_file, is_delta_file}; +use crate::manifest::storage::{ + LAST_CHECKPOINT_FILE, delta_file, is_checkpoint_file, is_delta_file, +}; use crate::read::{Batch, BatchBuilder}; use crate::region::opener::{PartitionExprFetcher, PartitionExprFetcherRef}; use crate::sst::FormatType; @@ -91,7 +95,20 @@ use crate::sst::index::puffin_manager::PuffinManagerFactory; use crate::time_provider::{StdTimeProvider, TimeProviderRef}; use crate::worker::WorkerGroup; -/// Controls a mock object-store layer that blocks a checkpoint task once. +/// Returns a manifest action list with one empty edit. +pub(crate) fn nop_action() -> RegionMetaActionList { + RegionMetaActionList::new(vec![RegionMetaAction::Edit(RegionEdit { + files_to_add: vec![], + files_to_remove: vec![], + timestamp_ms: None, + compaction_time_window: None, + flushed_entry_id: None, + flushed_sequence: None, + committed_sequence: None, + })]) +} + +/// Controls a mock object-store layer that blocks one manifest write or checkpoint cleanup. #[derive(Clone)] pub(crate) struct CheckpointTaskBlocker { entered: Arc, @@ -123,23 +140,12 @@ impl CheckpointTaskBlocker { /// Blocks publication of `_last_checkpoint` at writer close. pub(crate) fn block_last_checkpoint_write() -> (Self, MockLayer) { - let blocker = Self { - entered: Arc::new(Notify::new()), - release: Arc::new(Notify::new()), - armed: Arc::new(AtomicBool::new(true)), - }; - let factory_blocker = blocker.clone(); - let layer = MockLayerBuilder::default() - .writer_factory(Arc::new(move |path, _args, inner| { - Box::new(BlockingCheckpointWriter { - path: path.to_string(), - inner, - blocker: factory_blocker.clone(), - }) - })) - .build() - .unwrap(); - (blocker, layer) + Self::block_write(LAST_CHECKPOINT_FILE.to_string(), true) + } + + /// Blocks the first write of the delta of `version`, before any of its bytes reach storage. + pub(crate) fn block_delta_write(version: ManifestVersion) -> (Self, MockLayer) { + Self::block_write(delta_file(version), false) } pub(crate) async fn wait_until_blocked(&self) { @@ -154,6 +160,30 @@ impl CheckpointTaskBlocker { self.armed.store(true, Ordering::Release); } + fn block_write(file_name: String, at_close: bool) -> (Self, MockLayer) { + let blocker = Self { + entered: Arc::new(Notify::new()), + release: Arc::new(Notify::new()), + armed: Arc::new(AtomicBool::new(true)), + }; + let factory_blocker = blocker.clone(); + let layer = MockLayerBuilder::default() + .writer_factory(Arc::new(move |path, _args, inner| { + if path.contains(&file_name) { + Box::new(BlockingManifestWriter { + inner, + blocker: factory_blocker.clone(), + at_close, + }) + } else { + inner + } + })) + .build() + .unwrap(); + (blocker, layer) + } + async fn block_once(&self) { if self.armed.swap(false, Ordering::AcqRel) { self.entered.notify_one(); @@ -195,19 +225,22 @@ fn is_manifest_checkpoint_file(path: &str) -> bool { is_delta_file(file_name) || is_checkpoint_file(file_name) } -struct BlockingCheckpointWriter { - path: String, +struct BlockingManifestWriter { inner: Writer, blocker: CheckpointTaskBlocker, + at_close: bool, } -impl object_store::layers::mock::Write for BlockingCheckpointWriter { +impl object_store::layers::mock::Write for BlockingManifestWriter { async fn write(&mut self, bs: Buffer) -> MockResult<()> { + if !self.at_close { + self.blocker.block_once().await; + } self.inner.write(bs).await } async fn close(&mut self) -> MockResult { - if self.path.ends_with("_last_checkpoint") { + if self.at_close { self.blocker.block_once().await; } self.inner.close().await @@ -405,6 +438,12 @@ impl TestEnv { } } + /// Sets the node identity used by engines created in this environment. + pub fn with_node_id(mut self, node_id: u64) -> Self { + self.file_ref_manager = Arc::new(FileReferenceManager::new(Some(node_id))); + self + } + /// Overwrites the original `log_store_factory`. pub fn with_log_store_factory(mut self, log_store_factory: LogStoreFactory) -> TestEnv { self.log_store_factory = log_store_factory; @@ -833,6 +872,7 @@ impl TestEnv { checkpoint_distance, remove_file_options: Default::default(), manifest_cache: None, + conditional_publication: false, }; if let Some(metadata) = initial_metadata { diff --git a/src/mito2/src/test_util/scheduler_util.rs b/src/mito2/src/test_util/scheduler_util.rs index 3185a9895a3..3249104978a 100644 --- a/src/mito2/src/test_util/scheduler_util.rs +++ b/src/mito2/src/test_util/scheduler_util.rs @@ -28,8 +28,8 @@ use tokio::sync::mpsc::Sender; use crate::access_layer::{AccessLayer, AccessLayerRef}; use crate::cache::CacheManager; -use crate::compaction::CompactionScheduler; use crate::compaction::memory_manager::new_compaction_memory_manager; +use crate::compaction::{CompactionCoordinator, CompactionScheduler}; use crate::config::MitoConfig; use crate::error::Result; use crate::flush::FlushScheduler; @@ -101,10 +101,20 @@ impl SchedulerEnv { request_sender: Sender, config: MitoConfig, ) -> CompactionScheduler { - let scheduler = self.get_scheduler(); + // Admission capacity and runner count must agree; derive both from the + // configured compaction concurrency unless a test injects an executor. + let coordinator = match &self.scheduler { + Some(scheduler) => Arc::new(CompactionCoordinator::new( + scheduler.clone(), + config.max_background_compactions, + )), + None => Arc::new(CompactionCoordinator::new_local( + config.max_background_compactions, + )), + }; CompactionScheduler::new( - scheduler, + coordinator, request_sender, Arc::new(CacheManager::default()), Arc::new(config), @@ -145,6 +155,7 @@ impl SchedulerEnv { checkpoint_distance: 10, remove_file_options: Default::default(), manifest_cache: None, + conditional_publication: false, }, FormatType::PrimaryKey, false, @@ -154,6 +165,7 @@ impl SchedulerEnv { .unwrap(), RegionRoleState::Leader(RegionLeaderState::Writable), None, + Default::default(), )) } @@ -164,6 +176,12 @@ impl SchedulerEnv { } } +/// Collects scheduled jobs without polling or dropping them. +/// +/// It counts submissions for scheduling assertions only. A retained job is never +/// run or released, so any shutdown path that waits for admitted work to drain +/// cannot make progress; use a real [`LocalScheduler`] for drain and shutdown +/// coverage. #[derive(Default)] pub struct VecScheduler { jobs: Mutex>, diff --git a/src/mito2/src/worker.rs b/src/mito2/src/worker.rs index b93331d99dc..31a2aa0f515 100644 --- a/src/mito2/src/worker.rs +++ b/src/mito2/src/worker.rs @@ -61,14 +61,15 @@ use tokio::sync::{Mutex, Semaphore, mpsc, oneshot, watch}; use crate::access_layer::new_fs_cache_store; use crate::cache::write_cache::{WriteCache, WriteCacheRef}; use crate::cache::{CacheManager, CacheManagerRef, WriteCacheUploadStoreWrapperRef}; -use crate::compaction::CompactionScheduler; use crate::compaction::memory_manager::{CompactionMemoryManager, new_compaction_memory_manager}; +use crate::compaction::{CancelCompactionResult, CompactionCoordinator, CompactionScheduler}; use crate::config::MitoConfig; use crate::error::{self, CreateDirSnafu, JoinSnafu, Result, WorkerStoppedSnafu}; use crate::flush::{FlushScheduler, WriteBufferManagerImpl, WriteBufferManagerRef}; use crate::gc::{GcLimiter, GcLimiterRef}; use crate::lease::NodeLease; use crate::memtable::MemtableBuilderProvider; +use crate::memtable::bulk::CompactDispatcher; use crate::metrics::{REGION_COUNT, REQUEST_WAIT_TIME, WRITE_STALLING}; use crate::region::opener::PartitionExprFetcherRef; use crate::region::{ @@ -92,6 +93,7 @@ use crate::sst::index::puffin_manager::PuffinManagerFactory; use crate::temp_file_sweeper; use crate::time_provider::{StdTimeProvider, TimeProviderRef}; use crate::wal::Wal; +use crate::worker::handle_flush::StagingRegionsRef; use crate::worker::handle_manifest::RegionEditQueues; /// Identifier for a worker. @@ -147,7 +149,7 @@ pub(crate) struct WorkerGroup { /// Flush background job pool. flush_job_pool: SchedulerRef, /// Compaction background job pool. - compact_job_pool: SchedulerRef, + compact_job_pool: Arc, /// Scheduler for index build jobs. index_build_job_pool: SchedulerRef, /// Scheduler for file purgers. @@ -204,7 +206,11 @@ impl WorkerGroup { let series_index_store = series_index_store_from_config(&config, data_home).await?; let series_index_disk_usage = Arc::new(AtomicU64::new(0)); let flush_job_pool = Arc::new(LocalScheduler::new(config.max_background_flushes)); - let compact_job_pool = Arc::new(LocalScheduler::new(config.max_background_compactions)); + let compact_job_pool = Arc::new(CompactionCoordinator::new_local( + config.max_background_compactions, + )); + let memtable_compact_dispatcher = + Arc::new(CompactDispatcher::new(config.max_background_compactions)); let flush_semaphore = Arc::new(Semaphore::new(config.max_background_flushes)); // We use another scheduler to avoid purge jobs blocking other jobs. let purge_scheduler = Arc::new(LocalScheduler::new(config.max_background_purges)); @@ -253,6 +259,7 @@ impl WorkerGroup { let sweep_limiter = (config.gc.max_concurrent_gc_job > 0) .then(|| Arc::new(Semaphore::new(config.gc.max_concurrent_gc_job))); let node_lease = Arc::new(NodeLease::default()); + let staging_regions = StagingRegionsRef::default(); let workers = (0..config.num_workers) .map(|id| { @@ -268,6 +275,7 @@ impl WorkerGroup { flush_job_pool: flush_job_pool.clone(), compact_job_pool: compact_job_pool.clone(), purge_scheduler: purge_scheduler.clone(), + memtable_compact_dispatcher: memtable_compact_dispatcher.clone(), listener: WorkerListener::default(), cache_manager: cache_manager.clone(), compaction_memory_manager: compaction_memory_manager.clone(), @@ -284,6 +292,7 @@ impl WorkerGroup { #[cfg(feature = "hdfs-object-store")] sweep_limiter: sweep_limiter.clone(), node_lease: node_lease.clone(), + staging_regions: staging_regions.clone(), } .start() }) @@ -312,7 +321,7 @@ impl WorkerGroup { // TODO(yingwen): Do we need to stop gracefully? // Stops the scheduler gracefully. - self.compact_job_pool.stop(true).await?; + self.compact_job_pool.stop().await?; // Stops the scheduler gracefully. self.flush_job_pool.stop(true).await?; // Stops the purge scheduler gracefully. @@ -468,7 +477,11 @@ impl WorkerGroup { let series_index_store = series_index_store_from_config(&config, data_home).await?; let series_index_disk_usage = Arc::new(AtomicU64::new(0)); let flush_job_pool = Arc::new(LocalScheduler::new(config.max_background_flushes)); - let compact_job_pool = Arc::new(LocalScheduler::new(config.max_background_compactions)); + let memtable_compact_dispatcher = + Arc::new(CompactDispatcher::new(config.max_background_compactions)); + let compact_job_pool = Arc::new(CompactionCoordinator::new_local( + config.max_background_compactions, + )); let flush_semaphore = Arc::new(Semaphore::new(config.max_background_flushes)); let purge_scheduler = Arc::new(LocalScheduler::new(config.max_background_flushes)); let puffin_manager_factory = PuffinManagerFactory::new( @@ -519,6 +532,7 @@ impl WorkerGroup { let sweep_limiter = (config.gc.max_concurrent_gc_job > 0) .then(|| Arc::new(Semaphore::new(config.gc.max_concurrent_gc_job))); let node_lease = Arc::new(NodeLease::default()); + let staging_regions = StagingRegionsRef::default(); let workers = (0..config.num_workers) .map(|id| { WorkerStarter { @@ -533,6 +547,7 @@ impl WorkerGroup { flush_job_pool: flush_job_pool.clone(), compact_job_pool: compact_job_pool.clone(), purge_scheduler: purge_scheduler.clone(), + memtable_compact_dispatcher: memtable_compact_dispatcher.clone(), listener: WorkerListener::new(listener.clone()), cache_manager: cache_manager.clone(), compaction_memory_manager: compaction_memory_manager.clone(), @@ -549,6 +564,7 @@ impl WorkerGroup { #[cfg(feature = "hdfs-object-store")] sweep_limiter: sweep_limiter.clone(), node_lease: node_lease.clone(), + staging_regions: staging_regions.clone(), } .start() }) @@ -639,12 +655,13 @@ struct WorkerStarter { log_store: Arc, object_store_manager: ObjectStoreManagerRef, write_buffer_manager: WriteBufferManagerRef, - compact_job_pool: SchedulerRef, + compact_job_pool: Arc, index_build_job_pool: SchedulerRef, series_index_store: Option, series_index_disk_usage: Arc, flush_job_pool: SchedulerRef, purge_scheduler: SchedulerRef, + memtable_compact_dispatcher: Arc, listener: WorkerListener, cache_manager: CacheManagerRef, compaction_memory_manager: Arc, @@ -665,6 +682,7 @@ struct WorkerStarter { /// no concurrent GC job. sweep_limiter: Option>, node_lease: Arc, + staging_regions: StagingRegionsRef, } impl WorkerStarter { @@ -726,6 +744,7 @@ impl WorkerStarter { memtable_builder_provider: MemtableBuilderProvider::new( Some(self.write_buffer_manager.clone()), self.config.clone(), + self.memtable_compact_dispatcher.clone(), ), purge_scheduler: self.purge_scheduler.clone(), write_buffer_manager: self.write_buffer_manager, @@ -760,6 +779,7 @@ impl WorkerStarter { region_count: REGION_COUNT.with_label_values(&[&id_string]), request_wait_time: REQUEST_WAIT_TIME.with_label_values(&[&id_string]), region_edit_queues: RegionEditQueues::default(), + pending_alters: Default::default(), schema_metadata_manager: self.schema_metadata_manager, file_ref_manager: self.file_ref_manager.clone(), partition_expr_fetcher: self.partition_expr_fetcher, @@ -768,6 +788,7 @@ impl WorkerStarter { #[cfg(feature = "hdfs-object-store")] sweep_limiter: self.sweep_limiter, node_lease: self.node_lease, + staging_regions: self.staging_regions, }; let handle = common_runtime::spawn_global(async move { worker_thread.run().await; @@ -783,6 +804,8 @@ impl WorkerStarter { series_index_handle: Mutex::new(series_index_handle), series_index_task_state, running, + #[cfg(test)] + memtable_compact_dispatcher: self.memtable_compact_dispatcher.clone(), }) } } @@ -807,6 +830,10 @@ pub(crate) struct RegionWorker { series_index_task_state: Option>, /// Whether to run the worker thread. running: Arc, + #[cfg(test)] + /// Dispatcher for bulk memtable compactions, shared by all workers in the group. + /// Kept only so tests can check that every worker holds the same one. + memtable_compact_dispatcher: Arc, } impl RegionWorker { @@ -1085,6 +1112,8 @@ struct RegionWorkerLoop { request_wait_time: Histogram, /// Queues for region edit requests. region_edit_queues: RegionEditQueues, + /// ALTER requests waiting for the current edit or ALTER to finish. + pending_alters: handle_alter::PendingAlters, /// Database level metadata manager. schema_metadata_manager: SchemaMetadataManagerRef, /// Datanode level file references manager. @@ -1100,14 +1129,24 @@ struct RegionWorkerLoop { /// no concurrent GC job. sweep_limiter: Option>, node_lease: Arc, + /// Staging regions of this node that have received writes. + staging_regions: StagingRegionsRef, } impl RegionWorkerLoop { /// Publishes a loaded region together with its resident compaction state. fn register_region(&mut self, region: MitoRegionRef) { - self.compaction_scheduler - .register_region(®ion.version_control, ®ion.access_layer); - self.regions.insert_region(region); + if let Some(old) = self.regions.get_region(region.region_id) { + old.deactivate_region_manifest_size_metric(); + } + + self.compaction_scheduler.register_region( + ®ion.version_control, + ®ion.access_layer, + ®ion.compaction_state, + ); + self.regions.insert_region(region.clone()); + region.activate_region_manifest_size_metric(); } /// Starts the worker loop. @@ -1321,6 +1360,31 @@ impl RegionWorkerLoop { WorkerRequest::EditRegion(request) => { self.handle_region_edit(request); } + WorkerRequest::CancelCompaction { + region_id, + task_id, + sender, + } => { + let result = match self.compaction_scheduler.cancel_task(region_id, &task_id) { + CancelCompactionResult::CancelIssued + | CancelCompactionResult::AlreadyCancelling => Ok(1), + CancelCompactionResult::NotFound => Ok(0), + CancelCompactionResult::TooLateToCancel => error::InvalidRequestSnafu { + region_id, + reason: format!( + "Compaction task {task_id} has crossed its commit boundary" + ), + } + .fail(), + CancelCompactionResult::Unsupported => error::UnsupportedOperationSnafu { + err_msg: format!( + "Cancellation of remote compaction task {task_id} is unsupported" + ), + } + .fail(), + }; + sender.send(result); + } WorkerRequest::Stop => { debug_assert!(!self.running.load(Ordering::Relaxed)); } @@ -1565,6 +1629,7 @@ impl RegionWorkerLoop { // Closes remaining regions. let regions = self.regions.list_regions(); for region in regions { + region.deactivate_region_manifest_size_metric(); region.stop().await; } @@ -1878,4 +1943,26 @@ mod tests { .unwrap(); } } + + /// Checks that all workers in a group share one bulk memtable compaction dispatcher. + #[tokio::test] + async fn test_workers_share_memtable_compact_dispatcher() { + let env = TestEnv::with_prefix("share-dispatcher").await; + let group = env + .create_worker_group(MitoConfig { + num_workers: 4, + ..Default::default() + }) + .await; + let first = &group.workers[0].memtable_compact_dispatcher; + for (index, worker) in group.workers.iter().enumerate() { + let current = &worker.memtable_compact_dispatcher; + assert!( + Arc::ptr_eq(first, current), + "worker {index} has its own memtable compaction dispatcher" + ); + } + + group.stop().await.unwrap(); + } } diff --git a/src/mito2/src/worker/handle_alter.rs b/src/mito2/src/worker/handle_alter.rs index 580e55f1bed..935dbd39413 100644 --- a/src/mito2/src/worker/handle_alter.rs +++ b/src/mito2/src/worker/handle_alter.rs @@ -45,12 +45,47 @@ use crate::request::{DdlRequest, OptionOutputTx, SenderDdlRequest}; use crate::sst::FormatType; use crate::worker::RegionWorkerLoop; +pub(crate) type PendingAlters = std::collections::HashMap< + RegionId, + std::collections::VecDeque<(RegionAlterRequest, OptionOutputTx)>, +>; + impl RegionWorkerLoop { pub(crate) async fn handle_alter_request( &mut self, region_id: RegionId, request: RegionAlterRequest, sender: OptionOutputTx, + ) { + if self.flush_scheduler.has_pending_alter(region_id) + || self.pending_alters.contains_key(®ion_id) + || self.regions.get_region(region_id).is_some_and(|region| { + matches!( + region.state(), + crate::region::RegionRoleState::Leader( + crate::region::RegionLeaderState::Editing + | crate::region::RegionLeaderState::Altering + ) + ) + }) + { + let queue = self.pending_alters.entry(region_id).or_default(); + if queue.len() >= 128 { + sender.send(crate::error::RegionBusySnafu { region_id }.fail()); + } else { + queue.push_back((request, sender)); + } + self.dispatch_pending_region_requests(region_id).await; + return; + } + self.execute_alter_request(region_id, request, sender).await; + } + + pub(crate) async fn execute_alter_request( + &mut self, + region_id: RegionId, + request: RegionAlterRequest, + sender: OptionOutputTx, ) { let requested_skip_wal = skip_wal_value(&request.kind); let (region, follower_skip_wal) = match self.regions.writable_non_staging_region(region_id) diff --git a/src/mito2/src/worker/handle_apply_staging.rs b/src/mito2/src/worker/handle_apply_staging.rs index 4ac8a8990f0..2598640b9f2 100644 --- a/src/mito2/src/worker/handle_apply_staging.rs +++ b/src/mito2/src/worker/handle_apply_staging.rs @@ -14,15 +14,12 @@ use chrono::Utc; use common_telemetry::{debug, info}; -use snafu::ResultExt; use store_api::logstore::LogStore; use store_api::region_request::ApplyStagingManifestRequest; use store_api::storage::RegionId; use tokio::sync::oneshot; -use crate::error::{ - RegionStateSnafu, Result, SerdeJsonSnafu, StagingPartitionExprMismatchSnafu, UnexpectedSnafu, -}; +use crate::error::{RegionStateSnafu, Result, StagingPartitionExprMismatchSnafu, UnexpectedSnafu}; use crate::manifest::action::{RegionEdit, RegionManifest}; use crate::manifest::storage::manifest_dir; use crate::manifest::storage::staging::{StagingBlobStorage, staging_blob_path}; @@ -140,7 +137,8 @@ impl RegionWorkerLoop { region_id, edit, // we don't need to preload sst cache during repartition, as it may cause extra network overhead. false, tx, - ), + ) + .for_staging(request.partition_expr), ))) .await; @@ -193,6 +191,6 @@ impl RegionWorkerLoop { ); let staging_manifest = staging_blob_storage.get(manifest_path).await?; - serde_json::from_slice::(&staging_manifest).context(SerdeJsonSnafu) + RegionManifest::decode(&staging_manifest) } } diff --git a/src/mito2/src/worker/handle_catchup.rs b/src/mito2/src/worker/handle_catchup.rs index 0ca51b98a11..26229b66e93 100644 --- a/src/mito2/src/worker/handle_catchup.rs +++ b/src/mito2/src/worker/handle_catchup.rs @@ -135,6 +135,7 @@ impl RegionWorkerLoop { region_id, region.table_dir(), region.access_layer.path_type(), + self.node_lease.clone(), self.memtable_builder_provider.clone(), self.object_store_manager.clone(), self.purge_scheduler.clone(), diff --git a/src/mito2/src/worker/handle_close.rs b/src/mito2/src/worker/handle_close.rs index ede17511ad7..c10ac761f43 100644 --- a/src/mito2/src/worker/handle_close.rs +++ b/src/mito2/src/worker/handle_close.rs @@ -36,6 +36,16 @@ impl RegionWorkerLoop { info!("Try to close region {}, worker: {}", region_id, self.id); + if region.is_staging_or_staged_edit() { + // A staging region cannot flush, so it leaves staging before the close-time flush + // below. The manifest lock lets a successful end of staging in progress finish first, + // after which the region is already out of staging. + let _manager = region.manifest_ctx.manifest_manager.write().await; + region.abort_staging(); + // Edits queued behind a staged edit belong to the staging that has just ended. + self.reject_region_edit_queue_as_not_found(region_id); + } + // Memtables containing skip-WAL writes must be flushed before closing. // Followers cannot flush; explicit flush-on-close and region WAL options // retain their existing behavior. @@ -76,6 +86,7 @@ impl RegionWorkerLoop { let Some(region) = self.regions.remove_region(region_id) else { return; }; + region.deactivate_region_manifest_size_metric(); region.stop().await; self.fail_region_stalled_requests_as_not_found(®ion_id); self.reject_region_edit_queue_as_not_found(region_id); diff --git a/src/mito2/src/worker/handle_copy_region.rs b/src/mito2/src/worker/handle_copy_region.rs index 710bf694f13..2204cec8e1c 100644 --- a/src/mito2/src/worker/handle_copy_region.rs +++ b/src/mito2/src/worker/handle_copy_region.rs @@ -13,8 +13,9 @@ // limitations under the License. use common_telemetry::{debug, error, info}; -use snafu::OptionExt; +use snafu::{OptionExt, ResultExt, ensure}; use store_api::region_engine::MitoCopyRegionFromResponse; +use store_api::region_request::PathType; use store_api::storage::{FileId, RegionId}; use crate::error::{InvalidRequestSnafu, MissingManifestSnafu, Result}; @@ -25,7 +26,7 @@ use crate::region::{ use crate::request::{ BackgroundNotify, CopyRegionFromFinished, CopyRegionFromRequest, WorkerRequest, }; -use crate::sst::file::FileMeta; +use crate::sst::file::{self, FileMeta}; use crate::sst::location::region_dir_from_table_dir; use crate::worker::{RegionWorkerLoop, WorkerRequestWithTime}; @@ -64,8 +65,11 @@ impl RegionWorkerLoop { return; } - let region_metadata_loader = - RegionMetadataLoader::new(self.config.clone(), self.object_store_manager.clone()); + let region_metadata_loader = RegionMetadataLoader::new( + self.config.clone(), + self.object_store_manager.clone(), + self.node_lease.is_enabled(), + ); let worker_sender = self.sender.clone(); common_runtime::spawn_global(async move { @@ -86,6 +90,45 @@ impl RegionWorkerLoop { }; match region_edit { + Some(region_edit) + if region_edit + .files_to_add + .iter() + .any(|file| file.level == file::LEVEL_SHARED) => + { + // Shared references and their target admission sequence must enter + // the serialized edit lane, not the asynchronous physical-copy path. + // The response lists installed references, including shared SSTs + // whose objects stay in place; it is not a physical COPY count. + let copied_file_ids = region_edit + .files_to_add + .iter() + .map(|file| file.file_id) + .collect(); + let (tx, rx) = tokio::sync::oneshot::channel(); + if worker_sender + .send(WorkerRequestWithTime::new(WorkerRequest::EditRegion( + crate::request::RegionEditRequest::new( + region_id, + region_edit, + false, + tx, + ), + ))) + .await + .is_err() + { + let _ = sender.send(crate::error::RegionNotFoundSnafu { region_id }.fail()); + return; + } + let result = match rx.await { + Ok(result) => { + result.map(|_| MitoCopyRegionFromResponse { copied_file_ids }) + } + Err(error) => Err(error).context(crate::error::RecvSnafu), + }; + let _ = sender.send(result); + } Some(region_edit) => { if let Err(e) = worker_sender .send(WorkerRequestWithTime::new(WorkerRequest::Background { @@ -137,7 +180,7 @@ impl RegionWorkerLoop { let _ = sender.send(Ok(MitoCopyRegionFromResponse { copied_file_ids })); } - /// Returns the region edit and the file ids that were copied from the source region to the target region. + /// Returns the region edit and source file IDs, including shared logical references. /// /// If no need to copy files, returns (None, source_file_ids). async fn copy_region_from( @@ -154,11 +197,25 @@ impl RegionWorkerLoop { "Loading source region manifest from region dir: {region_dir}, target region: {target_region_id}" ); let source_region_manifest = region_metadata_loader - .load_manifest(®ion_dir, ®ion.version().options.storage) + .load_manifest(®ion_dir, ®ion.version().options) .await? .context(MissingManifestSnafu { region_id: source_region_id, })?; + // Metadata sync transforms copied rows and then removes these references. + // It cannot retire shared inputs through the ordinary edit API, so reject + // them before either physical copying or extending the target manifest. + ensure!( + path_type != PathType::Metadata + || source_region_manifest + .files + .values() + .all(|file| file.level != file::LEVEL_SHARED), + InvalidRequestSnafu { + region_id: target_region_id, + reason: "Shared SST references are not supported in metadata-region copies", + } + ); let mut new_file_metas = vec![]; let target_region_manifest = region.manifest_ctx.manifest().await; let source_file_ids = source_region_manifest @@ -172,7 +229,11 @@ impl RegionWorkerLoop { ); for (file_id, file_meta) in &source_region_manifest.files { if !target_region_manifest.files.contains_key(file_id) { - new_file_metas.push(remap_copied_file_meta(file_meta, target_region_id)); + new_file_metas.push(if file_meta.level == file::LEVEL_SHARED { + file_meta.clone() + } else { + remap_copied_file_meta(file_meta, target_region_id) + }); } } if new_file_metas.is_empty() { @@ -181,6 +242,7 @@ impl RegionWorkerLoop { let file_descriptors = new_file_metas .iter() + .filter(|file| file.level != file::LEVEL_SHARED) .flat_map(file_descriptors_for_meta) .collect(); debug!("File descriptors to copy: {:?}", file_descriptors); @@ -203,6 +265,13 @@ impl RegionWorkerLoop { flushed_sequence: None, committed_sequence: None, }; + if edit + .files_to_add + .iter() + .any(|file| file.level == file::LEVEL_SHARED) + { + return Ok((Some(edit), source_file_ids)); + } let action_list = RegionMetaActionList::with_action(RegionMetaAction::Edit(edit.clone())); info!( "Applying {:?} to region {target_region_id}, reason: CopyRegionFrom", diff --git a/src/mito2/src/worker/handle_create.rs b/src/mito2/src/worker/handle_create.rs index d2eab4a3f59..5c7da5779f3 100644 --- a/src/mito2/src/worker/handle_create.rs +++ b/src/mito2/src/worker/handle_create.rs @@ -61,6 +61,7 @@ impl RegionWorkerLoop { region_id, &request.table_dir, request.path_type, + self.node_lease.clone(), self.memtable_builder_provider.clone(), self.object_store_manager.clone(), self.purge_scheduler.clone(), diff --git a/src/mito2/src/worker/handle_drop.rs b/src/mito2/src/worker/handle_drop.rs index 192106110eb..e3950e0b264 100644 --- a/src/mito2/src/worker/handle_drop.rs +++ b/src/mito2/src/worker/handle_drop.rs @@ -114,6 +114,7 @@ where region.stop().await; // Removes this region from region map to prevent other requests from accessing this region self.regions.remove_region(region_id); + region.deactivate_region_manifest_size_metric(); self.dropping_regions.insert_region(region.clone()); // The region is no longer served once it leaves the map, so unregister its // runtime state before the fallible WAL cleanup below. Otherwise a WAL @@ -222,6 +223,9 @@ where /// Cleans runtime state for a region that is no longer available to serve requests. pub(crate) async fn cleanup_dropped_region_runtime_state(&mut self, region_id: RegionId) { + // A successful flush may hand off DROP before queued ALTERs and edits resume. + // Reject their waiters here because the removed region has no next turn. + self.reject_region_edit_queue_as_not_found(region_id); // Notifies flush scheduler. self.flush_scheduler.on_region_dropped(region_id); // Notifies compaction scheduler. diff --git a/src/mito2/src/worker/handle_flush.rs b/src/mito2/src/worker/handle_flush.rs index 657559e12f3..984b551d7bb 100644 --- a/src/mito2/src/worker/handle_flush.rs +++ b/src/mito2/src/worker/handle_flush.rs @@ -14,9 +14,9 @@ //! Handling flush related requests. -use std::collections::HashSet; -use std::sync::Arc; +use std::collections::{HashMap, HashSet}; use std::sync::atomic::Ordering; +use std::sync::{Arc, Mutex, Weak}; use common_base::readable_size::ReadableSize; use common_telemetry::{debug, error, info}; @@ -25,10 +25,10 @@ use store_api::region_request::{RegionFlushReason, RegionFlushRequest}; use store_api::storage::RegionId; use crate::config::{IndexBuildMode, MitoConfig}; -use crate::error::{RegionNotFoundSnafu, Result}; +use crate::error::{RegionBusySnafu, RegionNotFoundSnafu, Result}; use crate::flush::{FlushReason, RegionFlushTask}; -use crate::region::MitoRegionRef; use crate::region::version::VersionRef; +use crate::region::{MitoRegion, MitoRegionRef}; use crate::request::{BuildIndexRequest, FlushFailed, FlushFinished, OnFailure, OptionOutputTx}; use crate::sst::index::IndexBuildType; use crate::worker::RegionWorkerLoop; @@ -39,6 +39,33 @@ pub(crate) struct RegionWriteBufferPressure { pub(crate) rejected_region_ids: HashSet, } +/// Staging regions of a node that have received writes. +/// +/// Workers share it to bound the memtables that stay unflushed until staging ends. +#[derive(Debug, Default)] +pub(crate) struct StagingRegions { + regions: Mutex>>, +} + +pub(crate) type StagingRegionsRef = Arc; + +impl StagingRegions { + /// Records `region` and returns the memtable usage of the regions still in staging. + fn record_and_memtable_usage(&self, region: &MitoRegionRef) -> usize { + let mut regions = self.regions.lock().unwrap(); + regions.insert(region.region_id, Arc::downgrade(region)); + let mut usage = 0; + regions.retain(|_, region| match region.upgrade() { + Some(region) if region.is_staging_or_staged_edit() => { + usage += region_memtable_usage(®ion.version()); + true + } + _ => false, + }); + usage + } +} + #[derive(Debug, Default, PartialEq, Eq)] struct RegionWriteBufferStatus { should_flush: bool, @@ -74,6 +101,7 @@ impl RegionWorkerLoop { // Handle stalled requests. self.handle_stalled_requests().await; + self.dispatch_pending_region_requests(region_id).await; } /// Checks whether the engine reaches flush threshold. If so, finds regions in this @@ -99,8 +127,11 @@ impl RegionWorkerLoop { let mut pending_regions = vec![]; for region in ®ions { - if self.flush_scheduler.is_flush_requested(region.region_id) || !region.is_writable() { - // Already flushing or not writable. + if self.flush_scheduler.is_flush_requested(region.region_id) + || !region.is_writable() + || region.is_staging() + { + // Already flushing, not writable, or in staging, whose rows must stay in the WAL. continue; } @@ -192,6 +223,19 @@ impl RegionWorkerLoop { self.stalled_requests.estimated_size(®ion_id), ); + if region.is_staging() { + // Staging regions don't flush, so waiting would not release their memory. Writes + // are rejected at twice the region limit or at half of the engine's flush limit, + // which reserves memory headroom for other regions. + let staging_usage = self.staging_regions.record_and_memtable_usage(®ion); + if status.should_reject + || staging_usage >= self.write_buffer_manager.flush_limit() / 2 + { + pressure.rejected_region_ids.insert(region_id); + } + continue; + } + if status.should_flush && !self.flush_scheduler.is_flush_requested(region.region_id) { let task = self.new_flush_task( ®ion, @@ -241,8 +285,7 @@ impl RegionWorkerLoop { manifest_ctx: region.manifest_ctx.clone(), index_options: region.version().options.index_options.clone(), flush_semaphore: self.flush_semaphore.clone(), - is_staging: region.is_staging(), - partition_expr: region.maybe_staging_partition_expr_str(), + partition_expr: region.metadata().partition_expr.clone(), durability_barrier: self .wal .durability_barrier(region.region_id, ®ion.provider), @@ -326,6 +369,18 @@ impl RegionWorkerLoop { // when handling flush request instead of in `schedule_flush` or `flush_finished`. self.update_topic_latest_entry_id(®ion); + // A staging region must keep its WAL until staging ends, so it flushes nothing. + if region.is_staging() && !region.version().memtables.is_empty() { + sender.send(match request.reason { + // These only ask to advance the flushed position, which can wait. + Some(RegionFlushReason::RegionMigration | RegionFlushReason::RemoteWalPrune) => { + Ok(0) + } + _ => RegionBusySnafu { region_id }.fail(), + }); + return; + } + let reason = resolve_flush_reason(request.reason, region.is_downgrading()); let mut task = self.new_flush_task(®ion, reason, request.row_group_size, self.config.clone()); @@ -349,6 +404,12 @@ impl RegionWorkerLoop { continue; } self.update_topic_latest_entry_id(region); + // The rows of a staging region must stay in the WAL until staging ends, so a staging + // region with rows pins its topic's prune point: the update above only keeps the id + // fresh while the memtable is empty. + if region.is_staging() { + continue; + } let auto_flush_interval = region .version() @@ -398,28 +459,15 @@ impl RegionWorkerLoop { } }; - if request.is_staging { - // Skip the region metadata update. - info!( - "Skipping region metadata update for region {} in staging mode", - region_id - ); - region.version_control.apply_edit( - None, - &request.memtables_to_remove, - region.file_purger.clone(), - ); - } else { - region.version_control.apply_edit( - Some(request.edit.clone()), - &request.memtables_to_remove, - region.file_purger.clone(), - ); - } + region.version_control.apply_edit( + Some(request.edit.clone()), + &request.memtables_to_remove, + region.file_purger.clone(), + ); - // The flush has committed its manifest, including in staging mode. Count only - // its Parquet output, before WAL cleanup (which can fail after the commit). - let flushed_parquet_bytes = request + // The flush has committed its manifest. Count only its Parquet output, before + // WAL cleanup (which can fail after the commit). + let ingested_parquet_bytes = request .edit .files_to_add .iter() @@ -427,8 +475,8 @@ impl RegionWorkerLoop { .sum(); region .region_stats - .flushed_parquet_bytes - .fetch_add(flushed_parquet_bytes, Ordering::Relaxed); + .ingested_parquet_bytes + .fetch_add(ingested_parquet_bytes, Ordering::Relaxed); region.update_flush_millis(); // Update topic latest entry id as soon as possible after flush to make sure the prunable entry id is updated timely, @@ -483,7 +531,15 @@ impl RegionWorkerLoop { self.flush_scheduler.on_flush_success(region_id) { // Perform DDLs first because they require empty memtables. - self.handle_ddl_requests(&mut ddl_requests).await; + // These ALTERs already own the flush turn; bypass initial admission. + for ddl in ddl_requests.drain(..) { + if let crate::request::DdlRequest::Alter(request) = ddl.request { + self.execute_alter_request(ddl.region_id, request, ddl.sender) + .await; + } else { + self.handle_ddl_requests(&mut vec![ddl]).await; + } + } if self.flush_scheduler.is_flush_requested(region_id) { // The DDL may schedule another flush, e.g. a close-time flush after writes // arrived in the mutable memtable during the previous flush. Keep pending @@ -518,6 +574,7 @@ impl RegionWorkerLoop { // Schedules compaction. self.schedule_compaction(®ion).await; + self.dispatch_pending_region_requests(region_id).await; self.listener.on_flush_success(region_id); } diff --git a/src/mito2/src/worker/handle_manifest.rs b/src/mito2/src/worker/handle_manifest.rs index 9510b484d84..d8f4ecf8c16 100644 --- a/src/mito2/src/worker/handle_manifest.rs +++ b/src/mito2/src/worker/handle_manifest.rs @@ -22,7 +22,7 @@ use std::sync::Arc; use common_telemetry::{debug, info, warn}; use parquet::file::metadata::PageIndexPolicy; -use snafu::ResultExt; +use snafu::{OptionExt, ResultExt}; use store_api::logstore::LogStore; use store_api::metadata::RegionMetadataRef; use store_api::storage::{RegionId, SequenceNumber}; @@ -30,7 +30,9 @@ use store_api::storage::{RegionId, SequenceNumber}; use crate::cache::CacheManagerRef; use crate::cache::file_cache::{FileType, IndexKey}; use crate::config::IndexBuildMode; -use crate::error::{EditRegionSnafu, RegionBusySnafu, RegionNotFoundSnafu, Result}; +use crate::error::{ + EditRegionSnafu, RegionBusySnafu, RegionNotFoundSnafu, RegionStateSnafu, Result, +}; use crate::manifest::action::{ RegionChange, RegionEdit, RegionMetaAction, RegionMetaActionList, RegionTruncate, TruncateKind, }; @@ -46,13 +48,20 @@ use crate::request::{ WorkerRequest, WorkerRequestWithTime, }; use crate::sst::index::IndexBuildType; -use crate::sst::location; +use crate::sst::{file, location}; use crate::wal::EntryId; use crate::worker::{RegionWorkerLoop, WorkerListener}; pub(crate) type RegionEditQueues = HashMap; -/// A queue for region edit requests received while the region is already `Editing`. +/// Outcome of admitting a region edit, independent of subsequent region role changes. +pub(crate) enum RegionEditDispatch { + Started, + Queued, + Rejected, +} + +/// A queue for region edits waiting behind an active edit or ALTER. /// /// Normal writes and bulk inserts that arrive during `Editing` use the stalled-write queue instead. /// When an edit completes, those writes are handled before the next queued edit starts, preserving @@ -74,7 +83,7 @@ impl RegionEditQueue { } } - fn enqueue(&mut self, request: RegionEditRequest) { + fn enqueue(&mut self, request: RegionEditRequest) -> RegionEditDispatch { if self.requests.len() > Self::QUEUE_MAX_LEN { request.waiters.reply_with(|| { RegionBusySnafu { @@ -82,9 +91,10 @@ impl RegionEditQueue { } .fail() }); - return; + return RegionEditDispatch::Rejected; }; self.requests.push_back(request); + RegionEditDispatch::Queued } fn dequeue(&mut self) -> Option { @@ -149,8 +159,13 @@ impl RegionEditQueue { } impl RegionWorkerLoop { - /// Rejects queued region edit requests as region not found. + /// Rejects queued ALTER and region edit requests as region not found. pub(crate) fn reject_region_edit_queue_as_not_found(&mut self, region_id: RegionId) { + if let Some(queue) = self.pending_alters.remove(®ion_id) { + for (_, sender) in queue { + sender.send(RegionNotFoundSnafu { region_id }.fail()); + } + } if let Some(edit_queue) = self.region_edit_queues.remove(®ion_id) { edit_queue.reject_all_as_not_found(); } @@ -206,6 +221,8 @@ impl RegionWorkerLoop { // Handles the stalled requests. self.handle_region_stalled_requests(&change_result.region_id, true) .await; + self.dispatch_pending_region_requests(change_result.region_id) + .await; } /// Handles region sync request. @@ -285,19 +302,54 @@ impl RegionWorkerLoop { } impl RegionWorkerLoop { - /// Handles region edit request. - pub(crate) fn handle_region_edit(&mut self, request: RegionEditRequest) { + /// Admits an edit and reports whether it started, queued, or failed synchronously. + pub(crate) fn handle_region_edit(&mut self, request: RegionEditRequest) -> RegionEditDispatch { let region_id = request.region_id; let Some(region) = self.regions.get_region(region_id) else { request .waiters .reply_with(|| RegionNotFoundSnafu { region_id }.fail()); - return; + return RegionEditDispatch::Rejected; }; - if !region.is_writable() { - if region.state() == RegionRoleState::Leader(RegionLeaderState::Editing) { - self.region_edit_queues + // A close-time flush ends with the region removed. A close that left staging keeps the + // region writable until then, so an edit meant for staging would run as a normal edit. + if self.flush_scheduler.has_close_time_flush(region_id) { + request + .waiters + .reply_with(|| RegionBusySnafu { region_id }.fail()); + return RegionEditDispatch::Rejected; + } + + // A close may have abandoned the staging this edit belongs to, even if its flush failed. + if let Some(expected) = &request.staging_partition_expr + && region + .manifest_ctx + .staging_partition_info() + .as_ref() + .and_then(|info| info.partition_expr()) + != Some(expected.as_str()) + { + let state = region.state(); + request.waiters.reply_with(|| { + RegionStateSnafu { + region_id, + state, + expect: RegionRoleState::Leader(RegionLeaderState::Staging), + } + .fail() + }); + return RegionEditDispatch::Rejected; + } + + if !region.is_writable() || self.flush_scheduler.has_pending_alter(region_id) { + if matches!( + region.state(), + RegionRoleState::Leader(RegionLeaderState::Editing | RegionLeaderState::Altering) + ) || (region.is_writable() && self.flush_scheduler.has_pending_alter(region_id)) + { + return self + .region_edit_queues .entry(region_id) .or_insert_with(|| RegionEditQueue::new(region_id)) .enqueue(request); @@ -306,7 +358,7 @@ impl RegionWorkerLoop { .waiters .reply_with(|| RegionBusySnafu { region_id }.fail()); } - return; + return RegionEditDispatch::Rejected; } let RegionEditRequest { @@ -314,18 +366,12 @@ impl RegionWorkerLoop { mut edit, waiters, preload_sst_cache, + staging_partition_expr: _, } = request; - let file_sequence = region.version_control.current().last_sequence + 1; - edit.committed_sequence = Some(file_sequence); - - // Generic region edits (direct/import/staging) assign a new destination - // sequence domain but cannot prove or rewrite the physical per-row sequence - // column. The added files are therefore atomic/untrusted: clear the - // `preserve_row_sequence` marker so exact sequence-range scans fail closed - // until the scan reaches the assigned max sequence. - for file in &mut edit.files_to_add { - file.sequence = NonZeroU64::new(file_sequence); - file.preserve_row_sequence = false; + if let Err(error) = prepare_region_edit(®ion, &mut edit) { + let error = Arc::new(error); + waiters.reply_with(|| Err(error.clone()).context(EditRegionSnafu { region_id })); + return RegionEditDispatch::Rejected; } // Allow retrieving `is_staging` before spawn the edit region task. @@ -339,9 +385,11 @@ impl RegionWorkerLoop { if let Err(e) = region.set_editing(expect_state) { let e = Arc::new(e); waiters.reply_with(|| Err(e.clone()).context(EditRegionSnafu { region_id })); - return; + return RegionEditDispatch::Rejected; + } + if let Some(sequence) = edit.committed_sequence { + region.version_control.update_last_sequence(sequence); } - region.version_control.update_last_sequence(file_sequence); let request_sender = self.sender.clone(); let cache_manager = self.cache_manager.clone(); @@ -363,6 +411,7 @@ impl RegionWorkerLoop { region_id, notify: BackgroundNotify::RegionEdit(RegionEditResult { region_id, + origin: region, waiters, edit, result, @@ -383,6 +432,7 @@ impl RegionWorkerLoop { ); } }); + RegionEditDispatch::Started } /// Handles region edit result. @@ -405,8 +455,42 @@ impl RegionWorkerLoop { } }; + if !Arc::ptr_eq(®ion, &edit_result.origin) { + // The durable edit will be recovered by open. Never replay its old + // completion over newer files, or change the new incarnation's queues. + edit_result.waiters.reply_with(|| { + RegionNotFoundSnafu { + region_id: edit_result.region_id, + } + .fail() + }); + return; + } + let requires_reopen = edit_result.result.is_err() + && region + .manifest_ctx + .manifest_manager + .read() + .await + .is_stopped(); + if let Err(error) = &edit_result.result + && requires_reopen + { + // An uncertain manifest write requires replay before the old Version + // can become writable again. + self.remove_region(edit_result.region_id).await; + edit_result.waiters.reply_with(|| { + Err(error.clone()).context(EditRegionSnafu { + region_id: edit_result.region_id, + }) + }); + return; + } let need_compaction = if edit_result.is_staging { - if edit_result.update_region_state { + // A close may have abandoned this edit and left staging already. + if edit_result.update_region_state + && region.state() == RegionRoleState::Leader(RegionLeaderState::Editing) + { // For staging regions, edits are not applied immediately, // as they remain invisible until the region exits the staging state. region.switch_state_to_staging(RegionLeaderState::Editing); @@ -416,7 +500,11 @@ impl RegionWorkerLoop { } else { let need_compaction = self.config.schedule_compaction_after_edit && edit_result.result.is_ok() - && !edit_result.edit.files_to_add.is_empty(); + && edit_result + .edit + .files_to_add + .iter() + .any(|file| file.level < file::LEVEL_SHARED); // Only apply the edit if the result is ok and region is not in staging state. if edit_result.result.is_ok() { @@ -450,25 +538,68 @@ impl RegionWorkerLoop { .await; } - let next_request = - if let Some(edit_queue) = self.region_edit_queues.get_mut(&edit_result.region_id) { - let request = edit_queue.dequeue(); - if edit_queue.is_empty() { - self.region_edit_queues.remove(&edit_result.region_id); - } - request - } else { - None - }; - if let Some(request) = next_request { - self.handle_region_edit(request); - } + self.dispatch_pending_region_requests(edit_result.region_id) + .await; if need_compaction { self.schedule_compaction(®ion).await; } } + /// ALTER has priority over the edit backlog. Flush-pending DDLs and the + /// Altering state retain that priority until their terminal notification. + pub(crate) async fn dispatch_pending_region_requests(&mut self, region_id: RegionId) { + loop { + if self.flush_scheduler.has_pending_alter(region_id) { + return; + } + if self.regions.get_region(region_id).is_some_and(|region| { + matches!( + region.state(), + RegionRoleState::Leader( + RegionLeaderState::Editing | RegionLeaderState::Altering + ) + ) + }) { + return; + } + let next = self + .pending_alters + .get_mut(®ion_id) + .and_then(|q| q.pop_front()); + let Some((request, sender)) = next else { + break; + }; + self.execute_alter_request(region_id, request, sender).await; + } + self.pending_alters.remove(®ion_id); + loop { + let next_request = self + .region_edit_queues + .get_mut(®ion_id) + .and_then(|queue| queue.dequeue()); + if self + .region_edit_queues + .get(®ion_id) + .is_some_and(|queue| queue.is_empty()) + { + self.region_edit_queues.remove(®ion_id); + } + let Some(request) = next_request else { + return; + }; + // Start at most one edit batch per turn. Started and queued requests + // rely on a completion notification to resume dispatch. Only synchronous + // rejections continue: they produce no notification, so stopping would + // strand the remaining waiters. Use the admission outcome rather than + // rereading region state, which can race with a role change. + match self.handle_region_edit(request) { + RegionEditDispatch::Started | RegionEditDispatch::Queued => return, + RegionEditDispatch::Rejected => continue, + } + } + } + /// Writes truncate action to the manifest and then applies it to the region in background. pub(crate) fn handle_manifest_truncate_action( &self, @@ -672,6 +803,87 @@ impl RegionWorkerLoop { } } +fn prepare_region_edit(region: &MitoRegionRef, edit: &mut RegionEdit) -> Result<()> { + let region_id = region.region_id; + edit.validate_shared_reclassification(region_id)?; + let current = region.version_control.current(); + let shared = ¤t.version.ssts.levels()[file::SHARED_LEVEL_SLOT].files; + // Shared adoption is L0-only. The manifest is keyed by FileId and would + // replace an existing reference, but installing a shared handle detaches + // only the L0 handle, so an existing L1 reference would leave two live + // handles for one file and duplicate its rows until reopen. + let l1_files = ¤t.version.ssts.levels()[1].files; + snafu::ensure!( + edit.files_to_add + .iter() + .all(|file| file.level != file::LEVEL_SHARED || !l1_files.contains_key(&file.file_id)), + crate::error::InvalidRequestSnafu { + region_id, + reason: "Cannot adopt an existing L1 SST as shared; adoption is L0-only", + } + ); + snafu::ensure!( + edit.files_to_remove + .iter() + .all(|file| file.level < file::LEVEL_SHARED && !shared.contains_key(&file.file_id)) + && edit + .files_to_add + .iter() + .all(|file| file::is_supported_level(file.level) + && (file.level != file::LEVEL_SHARED + || file.region_id.table_id() == region_id.table_id())), + crate::error::InvalidRequestSnafu { + region_id, + reason: "Invalid shared SST import or removal" + } + ); + for file in &edit.files_to_add { + if let Some(existing) = shared.get(&file.file_id) { + let mut imported = file.clone(); + imported.sequence = existing.meta_ref().sequence; + imported.preserve_row_sequence = false; + snafu::ensure!( + &imported == existing.meta_ref(), + crate::error::InvalidRequestSnafu { + region_id, + reason: "Shared SST import conflicts with a visible reference", + } + ); + } + } + let existing_sequence = |file: &file::FileMeta| { + shared + .get(&file.file_id) + .and_then(|handle| handle.meta_ref().sequence) + }; + // A repeat of a still-visible shared import is not a new admission. Retired + // imports are not tracked: compaction retries must never re-import old inputs. + let same_import = !edit.files_to_add.is_empty() + && edit.files_to_remove.is_empty() + && edit + .files_to_add + .iter() + .all(|file| existing_sequence(file).is_some()); + let sequence = + if same_import { + None + } else { + let sequence = current.last_sequence.checked_add(1).context( + crate::error::InvalidRequestSnafu { + region_id, + reason: "Region sequence exhausted", + }, + )?; + edit.committed_sequence = Some(sequence); + NonZeroU64::new(sequence) + }; + for file in &mut edit.files_to_add { + file.sequence = existing_sequence(file).or(sequence); + file.preserve_row_sequence = false; + } + Ok(()) +} + /// Checks the edit, writes and applies it. async fn edit_region( region: &MitoRegionRef, @@ -694,7 +906,7 @@ async fn edit_region( let remote_path = location::sst_file_path(layer.table_dir(), file_meta.file_id(), layer.path_type()); - let is_index_exist = file_meta.exists_index(); + let has_downloadable_index = file_meta.has_downloadable_index(); let index_file_size = file_meta.index_file_size(); let index_file_index_key = IndexKey::new( @@ -728,12 +940,8 @@ async fn edit_region( PageIndexPolicy::Optional, ) .await; - - if matches!(parquet_cached, Ok(true)) { - listener.on_file_cache_filled(index_key.file_id); - } } - if is_index_exist { + if has_downloadable_index { // also download puffin file if let Err(err) = write_cache .download( @@ -751,6 +959,9 @@ async fn edit_region( } WRITE_CACHE_INFLIGHT_DOWNLOAD.sub(1); + if matches!(parquet_cached, Ok(true)) { + listener.on_file_cache_filled(index_key.file_id); + } }); } } @@ -761,9 +972,120 @@ async fn edit_region( ); let action_list = RegionMetaActionList::with_action(RegionMetaAction::Edit(edit)); - region + let result = region .manifest_ctx .update_manifest(RegionLeaderState::Editing, action_list, is_staging) + .await; + if let Err(error) = &result + && error.may_have_persisted_manifest_update() + { + // Recover the file list before accepting another edit after an uncertain write. + region + .manifest_ctx + .manifest_manager + .write() + .await + .stop() + .await; + } + result.map(|_| ()) +} + +#[cfg(test)] +mod tests { + use store_api::region_engine::RegionEngine; + use store_api::region_request::RegionRequest; + use store_api::storage::FileId; + + use super::*; + use crate::sst::file::{FileMeta, LEVEL_SHARED}; + use crate::test_util::{CreateRequestBuilder, TestEnv}; + + #[rstest::rstest] + #[case::shared_removal(false)] + #[case::unsupported_level(true)] + #[tokio::test] + async fn test_rejected_edit_does_not_stop_manifest(#[case] unsupported_level: bool) { + let mut env = TestEnv::new().await; + let engine = env.create_engine(Default::default()).await; + let region_id = RegionId::new(1, 1); + engine + .handle_request( + region_id, + RegionRequest::Create(CreateRequestBuilder::new().build()), + ) + .await + .unwrap(); + let region = engine.get_region(region_id).unwrap(); + let manifest_version = region.manifest_ctx.manifest_version().await; + let file = FileMeta { + region_id, + file_id: FileId::random(), + level: if unsupported_level { + // An ordinary-looking but unallocated level; rejected in every build. + 2 + } else { + LEVEL_SHARED + }, + ..Default::default() + }; + let edit = if unsupported_level { + RegionEdit { + files_to_add: vec![file], + ..Default::default() + } + } else { + RegionEdit { + files_to_remove: vec![file], + ..Default::default() + } + }; + region.set_editing(RegionLeaderState::Writable).unwrap(); + // Exercise persistence-side rejection, not the earlier worker admission guard. + let error = edit_region( + ®ion, + edit, + engine.cache_manager(), + WorkerListener::default(), + false, + false, + ) .await - .map(|_| ()) + .unwrap_err(); + assert!(matches!(error, crate::error::Error::InvalidRequest { .. })); + assert_eq!( + manifest_version, + region.manifest_ctx.manifest_version().await + ); + assert!( + !region + .manifest_ctx + .manifest_manager + .read() + .await + .is_stopped() + ); + assert!( + region + .version() + .ssts + .levels() + .iter() + .all(|level| level.files.is_empty()) + ); + // A rejected edit must not poison the manager for a subsequent valid update. + region + .manifest_ctx + .update_manifest( + RegionLeaderState::Editing, + RegionMetaActionList::with_action(RegionMetaAction::Edit(RegionEdit::default())), + false, + ) + .await + .unwrap(); + assert_eq!( + manifest_version + 1, + region.manifest_ctx.manifest_version().await + ); + } } diff --git a/src/mito2/src/worker/handle_open.rs b/src/mito2/src/worker/handle_open.rs index b734d7e9b86..28a612fad8d 100644 --- a/src/mito2/src/worker/handle_open.rs +++ b/src/mito2/src/worker/handle_open.rs @@ -185,6 +185,7 @@ impl RegionWorkerLoop { region_id, &request.table_dir, request.path_type, + self.node_lease.clone(), self.memtable_builder_provider.clone(), self.object_store_manager.clone(), self.purge_scheduler.clone(), diff --git a/src/mito2/src/worker/handle_rebuild_index.rs b/src/mito2/src/worker/handle_rebuild_index.rs index 927a5866a80..10f55c78943 100644 --- a/src/mito2/src/worker/handle_rebuild_index.rs +++ b/src/mito2/src/worker/handle_rebuild_index.rs @@ -33,7 +33,7 @@ use crate::metrics::INDEX_PUBLICATION_STALE_TOTAL; use crate::region::options::IndexOptions; use crate::region::{IndexBuildSource, MitoRegionRef, RegionLeaderState, RegionRoleState}; use crate::request::{BuildIndexRequest, IndexBuildFinished, IndexBuildStopped, OptionOutputTx}; -use crate::sst::file::{FileHandle, FileMeta, RegionFileId, RegionIndexId}; +use crate::sst::file::{self, FileHandle, FileMeta, RegionFileId, RegionIndexId}; use crate::sst::index::{ IndexBuildOutcome, IndexBuildTask, IndexBuildType, IndexerBuilderImpl, ResultMpscSender, cleanup_stale_index_caches, @@ -76,9 +76,11 @@ impl RegionWorkerLoop { let indexer_builder_ref = Arc::new(IndexerBuilderImpl { build_type: build_type.clone(), metadata: snapshot.metadata.clone(), - inverted_index_config: self.config.inverted_index.clone(), - fulltext_index_config: self.config.fulltext_index.clone(), - bloom_filter_index_config: self.config.bloom_filter_index.clone(), + registry: Arc::new(crate::sst::index::registry::IndexRegistry::new( + self.config.inverted_index.clone(), + self.config.fulltext_index.clone(), + self.config.bloom_filter_index.clone(), + )), index_options: snapshot.index_options.clone(), intermediate_manager, puffin_manager, @@ -192,7 +194,11 @@ impl RegionWorkerLoop { .levels() .iter() .flat_map(|level| level.files.iter()) - .filter(|(_, handle)| !handle.is_deleted() && !handle.compacting()) + .filter(|(_, handle)| { + !handle.is_deleted() + && !handle.compacting() + && handle.level() < file::LEVEL_SHARED + }) .map(|(id, handle)| (*id, handle.clone())) .collect(); let snapshot = IndexBuildSnapshot { diff --git a/src/mito2/src/worker/handle_remap.rs b/src/mito2/src/worker/handle_remap.rs index 639b9eef3e9..24480f0f490 100644 --- a/src/mito2/src/worker/handle_remap.rs +++ b/src/mito2/src/worker/handle_remap.rs @@ -58,8 +58,11 @@ impl RegionWorkerLoop { return; } - let region_metadata_loader = - RegionMetadataLoader::new(self.config.clone(), self.object_store_manager.clone()); + let region_metadata_loader = RegionMetadataLoader::new( + self.config.clone(), + self.object_store_manager.clone(), + self.node_lease.is_enabled(), + ); common_runtime::spawn_global(async move { let result = Self::fetch_and_remap_manifests( region, @@ -92,11 +95,11 @@ impl RegionWorkerLoop { let now = Instant::now(); for input_region in &input_regions { let region_dir = region_dir_from_table_dir(table_dir, *input_region, path_type); - let storage = region_options.storage.clone(); + let region_options = region_options.clone(); let moved_region_metadata_loader = region_metadata_loader.clone(); tasks.push(async move { moved_region_metadata_loader - .load_manifest(®ion_dir, &storage) + .load_manifest(®ion_dir, ®ion_options) .await }); } diff --git a/src/operator/src/expr_helper.rs b/src/operator/src/expr_helper.rs index 1fe7be2e51f..af6c960556c 100644 --- a/src/operator/src/expr_helper.rs +++ b/src/operator/src/expr_helper.rs @@ -20,17 +20,17 @@ use std::collections::{HashMap, HashSet}; use api::helper::ColumnDataTypeWrapper; use api::v1::alter_database_expr::Kind as AlterDatabaseKind; use api::v1::alter_table_expr::Kind as AlterTableKind; -use api::v1::column_def::{options_from_column_schema, try_as_column_schema}; +use api::v1::column_def::{self, options_from_column_schema, try_as_column_schema}; use api::v1::{ AddColumn, AddColumns, AlterDatabaseExpr, AlterTableExpr, Analyzer, ColumnDataType, ColumnDataTypeExtension, CreateFlowExpr, CreateTableExpr, CreateViewExpr, DropColumn, DropColumns, DropDefaults, ExpireAfter, FulltextBackend as PbFulltextBackend, - JsonSettings as PbJsonSettings, JsonTypeHint as PbJsonTypeHint, ModifyColumnType, - ModifyColumnTypes, RenameTable, SemanticType, SetDatabaseOptions, SetDefaults, SetFulltext, - SetIndex, SetIndexes, SetInverted, SetJsonSettings, SetSkipping, SetTableOptions, - SkippingIndexType as PbSkippingIndexType, TableName, UnsetDatabaseOptions, UnsetFulltext, - UnsetIndex, UnsetIndexes, UnsetInverted, UnsetSkipping, UnsetTableOptions, set_index, - unset_index, + JsonSettings as PbJsonSettings, JsonSkippingIndexOptions, JsonTypeHint as PbJsonTypeHint, + ModifyColumnType, ModifyColumnTypes, RenameTable, SemanticType, SetDatabaseOptions, + SetDefaults, SetFulltext, SetIndex, SetIndexes, SetInverted, SetJsonSettings, SetSkipping, + SetTableOptions, SkippingIndexType as PbSkippingIndexType, TableName, UnsetDatabaseOptions, + UnsetFulltext, UnsetIndex, UnsetIndexes, UnsetInverted, UnsetSkipping, UnsetTableOptions, + set_index, unset_index, }; use common_datasource::object_store::LocalFileAccess; use common_error::ext::BoxedError; @@ -806,16 +806,15 @@ fn json_settings_to_proto(settings: JsonSettings) -> Result { data_type: data_type as i32, datatype_extension, inverted_index: hint.inverted_index, - skipping_index: hint.skipping_index.map(|options| { - api::v1::JsonSkippingIndexOptions { - granularity: options.granularity, - index_type: match options.index_type { - SkippingIndexType::BloomFilter => { - PbSkippingIndexType::BloomFilter.into() - } - }, - false_positive_rate: options.false_positive_rate(), - } + fulltext_index: hint + .fulltext_index + .map(column_def::json_fulltext_options_to_proto), + skipping_index: hint.skipping_index.map(|options| JsonSkippingIndexOptions { + granularity: options.granularity, + index_type: match options.index_type { + SkippingIndexType::BloomFilter => PbSkippingIndexType::BloomFilter.into(), + }, + false_positive_rate: options.false_positive_rate(), }), }) }) @@ -1211,11 +1210,14 @@ mod tests { use api::v1::{SetDatabaseOptions, UnsetDatabaseOptions}; use datatypes::extension::json::is_json2_extension_type; + use datatypes::json::{JsonSettings, JsonTypeHint}; + use datatypes::schema::{FulltextOptions, SkippingIndexOptions}; use datatypes::value::Value; use session::context::{QueryContext, QueryContextBuilder}; use sql::dialect::GreptimeDbDialect; use sql::parser::{ParseOptions, ParserContext}; use sql::statements::statement::Statement; + use store_api::region_request::{AlterKind as RegionAlterKind, RegionAlterRequest}; use store_api::storage::ColumnDefaultConstraint; use super::*; @@ -1861,6 +1863,71 @@ SELECT max(c1), min(c2) FROM schema_2.table_2;"; assert!(modify_column_type.target_type_extension.is_none()); } + #[test] + fn test_json_settings_roundtrip() { + let mut cases = vec![JsonSettings::default(), JsonSettings::new_v2()]; + for backend in [FulltextBackend::Bloom, FulltextBackend::Tantivy] { + let options = + FulltextOptions::new(true, FulltextAnalyzer::Chinese, true, backend, 8, 0.05) + .unwrap(); + cases.push( + JsonSettings::try_new( + vec![ + JsonTypeHint { + path: vec!["nested".into(), "message".into()], + data_type: ConcreteDataType::string_datatype(), + inverted_index: true, + skipping_index: Some( + SkippingIndexOptions::new(8, 0.05, SkippingIndexType::BloomFilter) + .unwrap(), + ), + fulltext_index: Some(options), + }, + JsonTypeHint { + path: vec!["count".into()], + data_type: ConcreteDataType::int64_datatype(), + inverted_index: false, + skipping_index: None, + fulltext_index: None, + }, + ], + Some(0), + ) + .unwrap(), + ); + } + for settings in cases { + let wire = json_settings_to_proto(settings.clone()).unwrap(); + let set_settings = api::v1::SetJsonSettings { + column_name: "payload".into(), + settings: Some(wire), + }; + let expr = api::v1::AlterTableExpr { + kind: Some(AlterTableKind::SetJsonSettings(set_settings.clone())), + ..Default::default() + }; + let request = common_grpc_expr::alter_expr_to_request(1, expr, None).unwrap(); + let table::requests::AlterKind::SetJsonSettings { request } = request.alter_kind else { + panic!("expected JSON settings request"); + }; + assert_eq!(settings, request.settings); + let request = RegionAlterRequest::try_from(api::v1::region::AlterRequest { + kind: Some(api::v1::region::alter_request::Kind::SetJsonSettings( + set_settings, + )), + ..Default::default() + }) + .unwrap(); + let RegionAlterKind::SetJsonSettings { + settings: decoded, .. + } = request.kind + else { + panic!("expected JSON settings region request"); + }; + assert_eq!(settings, decoded); + } + } + #[test] fn test_to_alter_set_json_settings_expr() { let sql = "ALTER TABLE monitor MODIFY COLUMN payload JSON2 (service STRING INVERTED INDEX SKIPPING INDEX WITH (granularity='8'), message STRING);"; diff --git a/src/operator/src/request.rs b/src/operator/src/request.rs index ce3b3568651..88eac1a940a 100644 --- a/src/operator/src/request.rs +++ b/src/operator/src/request.rs @@ -17,8 +17,8 @@ use std::sync::Arc; use api::helper::to_pb_time_unit; use api::v1::region::region_request::Body as RegionRequestBody; use api::v1::region::{ - BuildIndexRequest, CompactRequest, CompactionTimeRange, FlushRequest, RegionRequestHeader, - TruncateRequest, Unflushed, build_index_request, truncate_request, + BuildIndexRequest, CancelCompactionRequest, CompactRequest, CompactionTimeRange, FlushRequest, + RegionRequestHeader, TruncateRequest, Unflushed, build_index_request, truncate_request, }; use catalog::CatalogManagerRef; use common_catalog::build_db_string; @@ -34,6 +34,7 @@ use partition::cache::PhysicalPartitionInfo; use partition::manager::PartitionRuleManagerRef; use session::context::QueryContextRef; use snafu::prelude::*; +use store_api::metric_engine_consts; use store_api::storage::RegionId; use table::requests::{BuildIndexTableRequest, CompactTableRequest, FlushTableRequest}; use table::table_name::TableName; @@ -236,6 +237,27 @@ impl Requester { self.do_request(vec![request], None, &ctx).await } + /// Cancels one identified compaction task through the region leader. + pub async fn handle_cancel_region_compaction( + &self, + region_id: RegionId, + task_id: String, + ctx: QueryContextRef, + ) -> Result { + ensure!( + region_id.region_group() != metric_engine_consts::METRIC_METADATA_REGION_GROUP, + NotSupportedSnafu { + feat: "cancelling compaction for an internal metric metadata region", + } + ); + + let request = RegionRequestBody::CancelCompaction(CancelCompactionRequest { + region_id: region_id.into(), + task_id, + }); + self.do_request(vec![request], None, &ctx).await + } + /// Discard all unflushed data from the region. pub async fn handle_discard_unflushed_data( &self, @@ -389,6 +411,7 @@ impl Requester { let region_id = match req { RegionRequestBody::Flush(req) => req.region_id, RegionRequestBody::Compact(req) => req.region_id, + RegionRequestBody::CancelCompaction(req) => req.region_id, RegionRequestBody::BuildIndex(req) => req.region_id, RegionRequestBody::Truncate(req) => req.region_id, _ => { @@ -451,11 +474,83 @@ fn ensure_discard_unflushed_supported(engine: &str, is_physical_table: bool) -> #[cfg(test)] mod tests { + use api::region::RegionResponse; use api::v1::TimeUnit; + use common_error::ext::ErrorExt; + use common_error::status_code::StatusCode; + use common_meta::ddl::test_util::datanode_handler::DatanodeWatcher; + use common_meta::test_util::MockDatanodeManager; use common_time::Timestamp; use common_time::range::TimestampRange; + use session::context::QueryContext; use super::*; + use crate::test_util; + + #[tokio::test] + async fn test_cancel_region_compaction_routes_to_region_leader() { + let backend = test_util::prepare_mocked_backend().await; + let partition_manager = test_util::create_partition_rule_manager(backend).await; + let (sender, mut requests) = tokio::sync::mpsc::channel(4); + let watcher = DatanodeWatcher::new(sender).with_handler(|_, request| { + let Some(RegionRequestBody::CancelCompaction(request)) = request.body else { + panic!("expected cancellation through Handle"); + }; + Ok(RegionResponse::new(usize::from( + request.task_id == "live-cycle", + ))) + }); + let requester = Requester::new( + catalog::memory::MemoryCatalogManager::new(), + partition_manager, + Arc::new(MockDatanodeManager::new(watcher)), + ); + let ctx = Arc::new(QueryContext::with("greptime", "cancel_test")); + for (region_number, task_id, affected_rows) in + [(1, "live-cycle", 1), (3, "absent-cycle", 0)] + { + let region_id = RegionId::new(1, region_number); + assert_eq!( + requester + .handle_cancel_region_compaction(region_id, task_id.into(), ctx.clone()) + .await + .unwrap(), + affected_rows + ); + let (peer, request) = requests.try_recv().unwrap(); + assert_eq!(peer.id, u64::from(region_number)); + assert_eq!(request.header.unwrap().dbname, ctx.get_db_string()); + assert_eq!( + request.body, + Some(RegionRequestBody::CancelCompaction( + CancelCompactionRequest { + region_id: region_id.as_u64(), + task_id: task_id.into(), + } + )) + ); + } + // Metadata regions are rejected before routing, even without a table route. + for table_id in [1, u32::MAX] { + let region_id = RegionId::with_group_and_seq( + table_id, + metric_engine_consts::METRIC_METADATA_REGION_GROUP, + 1, + ); + let error = requester + .handle_cancel_region_compaction(region_id, "live-cycle".into(), ctx.clone()) + .await + .unwrap_err(); + assert_eq!(error.status_code(), StatusCode::Unsupported); + assert!(matches!(error, crate::error::Error::NotSupported { .. })); + assert!( + error + .to_string() + .contains("internal metric metadata region") + ); + } + assert!(requests.try_recv().is_err()); + } #[test] fn test_build_series_index_requires_physical_metric_table() { diff --git a/src/operator/src/table.rs b/src/operator/src/table.rs index 117351280b9..69eb85062b5 100644 --- a/src/operator/src/table.rs +++ b/src/operator/src/table.rs @@ -134,6 +134,19 @@ impl TableMutationHandler for TableMutationOperator { .context(query_error::TableMutationSnafu) } + async fn cancel_region_compaction( + &self, + region_id: RegionId, + task_id: String, + ctx: QueryContextRef, + ) -> QueryResult { + self.requester + .handle_cancel_region_compaction(region_id, task_id, ctx) + .await + .map_err(BoxedError::new) + .context(query_error::TableMutationSnafu) + } + async fn discard_unflushed_data( &self, region_id: RegionId, diff --git a/src/pipeline/src/etl/transform.rs b/src/pipeline/src/etl/transform.rs index 09cb0a3aa0b..ffa805dae5e 100644 --- a/src/pipeline/src/etl/transform.rs +++ b/src/pipeline/src/etl/transform.rs @@ -539,6 +539,7 @@ fn parse_json2_type_hint(value: &yaml_rust::Yaml) -> Result { data_type, inverted_index, skipping_index: None, + fulltext_index: None, }) } diff --git a/src/pipeline/src/etl/transform/transformer/greptime.rs b/src/pipeline/src/etl/transform/transformer/greptime.rs index 87430cd1f98..5df641f444c 100644 --- a/src/pipeline/src/etl/transform/transformer/greptime.rs +++ b/src/pipeline/src/etl/transform/transformer/greptime.rs @@ -1191,6 +1191,7 @@ transform: data_type: ConcreteDataType::int64_datatype(), inverted_index: false, skipping_index: None, + fulltext_index: None, }], None, ) @@ -1207,6 +1208,7 @@ transform: data_type: ConcreteDataType::string_datatype(), inverted_index: false, skipping_index: None, + fulltext_index: None, }], None, ) diff --git a/src/pipeline/src/etl/transform/transformer/greptime/coerce.rs b/src/pipeline/src/etl/transform/transformer/greptime/coerce.rs index 2e350b3b9a8..6485eb2495e 100644 --- a/src/pipeline/src/etl/transform/transformer/greptime/coerce.rs +++ b/src/pipeline/src/etl/transform/transformer/greptime/coerce.rs @@ -775,6 +775,7 @@ mod tests { data_type: ConcreteDataType::int64_datatype(), inverted_index: false, skipping_index: None, + fulltext_index: None, }], None, ) diff --git a/src/pipeline/src/manager/pipeline_operator.rs b/src/pipeline/src/manager/pipeline_operator.rs index 7568fc088bd..c38fbffca34 100644 --- a/src/pipeline/src/manager/pipeline_operator.rs +++ b/src/pipeline/src/manager/pipeline_operator.rs @@ -283,6 +283,11 @@ impl PipelineOperator { .await } + /// Returns the server's pipeline options. + pub fn options(&self) -> &PipelineOptions { + &self.options + } + /// Compile a pipeline. pub fn build_pipeline(&self, pipeline: &str) -> Result { crate::parse_with_options(&crate::Content::Yaml(pipeline), &self.options) diff --git a/src/pipeline/src/options.rs b/src/pipeline/src/options.rs index ad1c72a430b..27bf153dede 100644 --- a/src/pipeline/src/options.rs +++ b/src/pipeline/src/options.rs @@ -28,6 +28,12 @@ pub struct PipelineOptions { /// local timezone, network, and logs. Enable only for trusted pipeline authors. /// Defaults to false. Changes require a restart. pub allow_vrl_host_access: bool, + /// 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`. + /// Defaults to false. Changes require a restart. + pub ignore_errors: bool, } impl Default for PipelineOptions { @@ -35,6 +41,7 @@ impl Default for PipelineOptions { Self { cache_ttl: Duration::from_secs(10), allow_vrl_host_access: false, + ignore_errors: false, } } } diff --git a/src/puffin/src/error.rs b/src/puffin/src/error.rs index 40d1eff9ada..37a73ac7ffa 100644 --- a/src/puffin/src/error.rs +++ b/src/puffin/src/error.rs @@ -191,6 +191,13 @@ pub enum Error { location: Location, }, + #[snafu(display("Multiple blobs have the same key: {blob}"))] + AmbiguousBlob { + blob: String, + #[snafu(implicit)] + location: Location, + }, + #[snafu(display("Blob not found: {blob}"))] BlobNotFound { blob: String, @@ -256,6 +263,7 @@ impl ErrorExt for Error { | UnexpectedPuffinFileSize { .. } | Lz4Compression { .. } | Lz4Decompression { .. } + | AmbiguousBlob { .. } | BlobNotFound { .. } | BlobIndexOutOfBound { .. } | FileKeyNotMatch { .. } diff --git a/src/puffin/src/puffin_manager.rs b/src/puffin/src/puffin_manager.rs index 060bd4237bf..af71430fb5f 100644 --- a/src/puffin/src/puffin_manager.rs +++ b/src/puffin/src/puffin_manager.rs @@ -14,6 +14,7 @@ pub mod cache; pub mod file_accessor; +pub mod file_key; pub mod fs_puffin_manager; pub mod stager; @@ -31,6 +32,7 @@ use futures::AsyncRead; use crate::blob_metadata::{BlobMetadata, CompressionCodec}; use crate::error::Result; use crate::file_metadata::FileMetadata; +use crate::puffin_manager::file_key::PuffinFileKey; /// Metrics returned by `PuffinReader::dir` operations. #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] @@ -48,6 +50,9 @@ pub trait PuffinManager { type Writer: PuffinWriter; type FileHandle: ToString + Clone + Send + Sync; + /// Returns a stable storage-scoped key without opening or reading the file. + fn file_key(&self, handle: &Self::FileHandle) -> PuffinFileKey; + /// Creates a `PuffinReader` for the specified `handle`. async fn reader(&self, handle: &Self::FileHandle) -> Result; @@ -107,6 +112,20 @@ pub trait PuffinReader { /// Returns the metadata of the Puffin file. async fn metadata(&self) -> Result>; + /// Returns metadata for a unique blob key without reading its payload. + /// + /// Missing keys return `None`; duplicate keys return an error. The length is + /// the stored byte length, before any decompression performed by [`Self::blob`]. + async fn blob_metadata(&self, key: &str) -> Result> { + let metadata = self.metadata().await?; + let mut matches = metadata.blobs.iter().filter(|blob| blob.blob_type == key); + let first = matches.next(); + if matches.next().is_some() { + return crate::error::AmbiguousBlobSnafu { blob: key }.fail(); + } + Ok(first.cloned()) + } + /// Reads a blob from the Puffin file. /// /// The returned `GuardWithMetadata` is used to access the blob data and its metadata. diff --git a/src/puffin/src/puffin_manager/cache.rs b/src/puffin/src/puffin_manager/cache.rs index bfc4269ef11..ee88bd38d61 100644 --- a/src/puffin/src/puffin_manager/cache.rs +++ b/src/puffin/src/puffin_manager/cache.rs @@ -23,6 +23,7 @@ use snafu::ResultExt; use crate::error::{CacheGetSnafu, Result}; use crate::file_metadata::FileMetadata; +use crate::puffin_manager::file_key::PuffinFileKey; /// Metrics for index metadata. const PUFFIN_METADATA_TYPE: &str = "puffin_metadata"; @@ -31,11 +32,11 @@ pub type PuffinMetadataCacheRef = Arc; /// A cache for storing the metadata of the index files. pub struct PuffinMetadataCache { - cache: Cache>, + cache: Cache, Arc>, } -fn puffin_metadata_weight(k: &str, v: &Arc) -> u32 { - (k.len() + v.memory_usage()) as u32 +fn puffin_metadata_weight(k: &PuffinFileKey, v: &Arc) -> u32 { + u32::try_from(k.estimated_size() + k.handle().capacity() + v.memory_usage()).unwrap_or(u32::MAX) } impl PuffinMetadataCache { @@ -45,7 +46,7 @@ impl PuffinMetadataCache { cache: Cache::new( "puffin_metadata", capacity, - |k: &String, v: &Arc| puffin_metadata_weight(k, v), + |k: &PuffinFileKey, v: &Arc| puffin_metadata_weight(k, v), |_, _, _| {}, ) .with_size_metric(cache_bytes.bind(&[PUFFIN_METADATA_TYPE])), @@ -59,13 +60,17 @@ impl PuffinMetadataCache { } /// Gets the metadata from the cache. - pub async fn get_metadata(&self, file_id: &str) -> Option> { + pub async fn get_metadata(&self, file_id: &PuffinFileKey) -> Option> { self.cache.get(file_id).await } /// Shares one metadata load among concurrent readers of the same file. #[tracing::instrument(name = "puffin_metadata_lookup", skip_all)] - pub async fn try_get_with(&self, file_id: &str, load: F) -> Result> + pub async fn try_get_with( + &self, + file_id: &PuffinFileKey, + load: F, + ) -> Result> where F: Future>>, { @@ -81,12 +86,20 @@ impl PuffinMetadataCache { } /// Puts the metadata into the cache. - pub async fn put_metadata(&self, file_id: String, metadata: Arc) { + pub async fn put_metadata(&self, file_id: PuffinFileKey, metadata: Arc) { self.cache.insert(file_id, metadata).await; } + /// Invalidates the versioned handle across storage scopes when the caller has no manager. + /// Pending loaders are not fenced; physical removal runs asynchronously. + pub fn invalidate_file(&self, file_id: &str) -> std::io::Result<()> { + let file_id = file_id.to_string(); + self.cache + .invalidate_if(move |key, _| key.handle() == &file_id) + } + /// Removes the metadata of the given file from the cache, if present. - pub async fn remove(&self, file_id: &str) { + pub async fn remove(&self, file_id: &PuffinFileKey) { self.cache.invalidate(file_id).await; } } @@ -101,10 +114,23 @@ mod tests { use super::*; use crate::error::InvalidPuffinFooterSnafu; + fn key() -> PuffinFileKey { + PuffinFileKey::new( + Arc::new(crate::puffin_manager::file_key::PuffinStorageScope::new( + "file".into(), + String::new(), + "/root/".into(), + )), + "file".into(), + "file".into(), + ) + } + fn new_cache() -> (PuffinMetadataCache, CacheSizeMetrics) { let metrics = CacheSizeMetrics::new(Opts::new("test_metadata_bytes", "test"), &["type"]).unwrap(); - (PuffinMetadataCache::new(1024 * 1024, &metrics), metrics) + let capacity = u64::from(puffin_metadata_weight(&key(), &metadata())) * 4; + (PuffinMetadataCache::new(capacity, &metrics), metrics) } fn sample_bytes(metrics: &CacheSizeMetrics) -> i64 { @@ -125,6 +151,7 @@ mod tests { // Hold both requests at the same cold-load boundary. Only coalescing differs. #[tokio::test] async fn compare_separate_lookup_with_coalesced_load() { + let key = key(); for _ in 0..3 { for coalesce in [false, true] { let (cache, _) = new_cache(); @@ -137,12 +164,12 @@ mod tests { Ok(metadata()) }; if coalesce { - cache.try_get_with("file", load).await - } else if let Some(value) = cache.get_metadata("file").await { + cache.try_get_with(&key, load).await + } else if let Some(value) = cache.get_metadata(&key).await { Ok(value) } else { let value = load.await?; - cache.put_metadata("file".to_string(), value.clone()).await; + cache.put_metadata(key.clone(), value.clone()).await; Ok(value) } }; @@ -160,6 +187,7 @@ mod tests { #[tokio::test] async fn concurrent_loads_share_result_and_accounting() { + let key = key(); let (cache, gauge) = new_cache(); let calls = AtomicUsize::new(0); let gate = tokio::sync::Notify::new(); @@ -168,8 +196,8 @@ mod tests { gate.notified().await; Ok(metadata()) }; - let mut first = Box::pin(cache.try_get_with("file", load())); - let mut second = Box::pin(cache.try_get_with("file", load())); + let mut first = Box::pin(cache.try_get_with(&key, load())); + let mut second = Box::pin(cache.try_get_with(&key, load())); assert!(futures::poll!(&mut first).is_pending()); assert!(futures::poll!(&mut second).is_pending()); assert_eq!(calls.load(Ordering::Relaxed), 1); @@ -180,21 +208,22 @@ mod tests { cache.cache.run_pending_tasks().await; assert_eq!( sample_bytes(&gauge), - i64::from(puffin_metadata_weight("file", &first)) + i64::from(puffin_metadata_weight(&key, &first)) ); let warm = cache - .try_get_with("file", async { panic!("warm read loaded") }) + .try_get_with(&key, async { panic!("warm read loaded") }) .await .unwrap(); assert!(Arc::ptr_eq(&first, &warm)); - cache.remove("file").await; + cache.remove(&key).await; cache.cache.run_pending_tasks().await; - assert!(cache.get_metadata("file").await.is_none()); + assert!(cache.get_metadata(&key).await.is_none()); assert_eq!(sample_bytes(&gauge), 0); } #[tokio::test] async fn shared_failure_can_retry() { + let key = key(); let (cache, gauge) = new_cache(); let calls = AtomicUsize::new(0); let gate = tokio::sync::Notify::new(); @@ -203,8 +232,8 @@ mod tests { gate.notified().await; InvalidPuffinFooterSnafu.fail() }; - let mut first = Box::pin(cache.try_get_with("file", load())); - let mut second = Box::pin(cache.try_get_with("file", load())); + let mut first = Box::pin(cache.try_get_with(&key, load())); + let mut second = Box::pin(cache.try_get_with(&key, load())); assert!(futures::poll!(&mut first).is_pending()); assert!(futures::poll!(&mut second).is_pending()); gate.notify_waiters(); @@ -215,7 +244,7 @@ mod tests { assert_eq!(sample_bytes(&gauge), 0); assert!( cache - .try_get_with("file", async { Ok(metadata()) }) + .try_get_with(&key, async { Ok(metadata()) }) .await .is_ok() ); @@ -223,10 +252,11 @@ mod tests { #[tokio::test] async fn cancelled_loader_allows_waiter_to_load() { + let key = key(); let (cache, _) = new_cache(); - let mut first = Box::pin(cache.try_get_with("file", std::future::pending())); + let mut first = Box::pin(cache.try_get_with(&key, std::future::pending())); assert!(futures::poll!(&mut first).is_pending()); - let mut second = Box::pin(cache.try_get_with("file", async { Ok(metadata()) })); + let mut second = Box::pin(cache.try_get_with(&key, async { Ok(metadata()) })); assert!(futures::poll!(&mut second).is_pending()); drop(first); tokio::time::timeout(std::time::Duration::from_secs(5), second) @@ -234,4 +264,40 @@ mod tests { .unwrap() .unwrap(); } + + #[tokio::test] + async fn same_handle_in_different_stores_does_not_share_footer() { + let (cache, _) = new_cache(); + let first = key(); + let second = PuffinFileKey::new( + Arc::new(crate::puffin_manager::file_key::PuffinStorageScope::new( + "file".into(), + String::new(), + "/other-root/".into(), + )), + "file".into(), + "file".into(), + ); + let first_metadata = metadata(); + cache + .put_metadata(first.clone(), first_metadata.clone()) + .await; + assert!(cache.get_metadata(&second).await.is_none()); + let second_metadata = cache + .try_get_with(&second, async { + Ok(Arc::new(FileMetadata { + blobs: Vec::new(), + properties: [("store".to_string(), "second".to_string())].into(), + })) + }) + .await + .unwrap(); + assert_ne!(first_metadata, second_metadata); + cache.remove(&first).await; + assert!(cache.get_metadata(&first).await.is_none()); + assert_eq!(Some(second_metadata), cache.get_metadata(&second).await); + cache.invalidate_file("file").unwrap(); + cache.cache.run_pending_tasks().await; + assert!(cache.get_metadata(&second).await.is_none()); + } } diff --git a/src/puffin/src/puffin_manager/file_accessor.rs b/src/puffin/src/puffin_manager/file_accessor.rs index cc4cca3171e..b8806bd2221 100644 --- a/src/puffin/src/puffin_manager/file_accessor.rs +++ b/src/puffin/src/puffin_manager/file_accessor.rs @@ -12,6 +12,8 @@ // See the License for the specific language governing permissions and // limitations under the License. +use std::sync::Arc; + use async_trait::async_trait; use common_base::range_read::{FileReader, SizeAwareRangeReader}; use common_test_util::temp_dir::{TempDir, create_temp_dir}; @@ -20,6 +22,7 @@ use tokio::fs::File; use tokio_util::compat::{Compat, TokioAsyncReadCompatExt}; use crate::error::Result; +use crate::puffin_manager::file_key::{PuffinFileKey, PuffinStorageScope}; /// `PuffinFileAccessor` is for opening readers and writers for puffin files. #[async_trait] @@ -29,6 +32,10 @@ pub trait PuffinFileAccessor: Send + Sync + 'static { type Writer: AsyncWrite + Unpin + Send; type FileHandle: ToString + Clone + Send + Sync; + /// Returns stable identity using the same resolved path as reader and writer. + /// Keys include the physical file version; this operation performs no I/O. + fn file_key(&self, handle: &Self::FileHandle) -> PuffinFileKey; + /// Opens a reader for the given puffin file handle. async fn reader(&self, handle: &Self::FileHandle) -> Result; @@ -38,12 +45,18 @@ pub trait PuffinFileAccessor: Send + Sync + 'static { pub struct MockFileAccessor { tempdir: TempDir, + scope: Arc, } impl MockFileAccessor { pub fn new(prefix: &str) -> Self { let tempdir = create_temp_dir(prefix); - Self { tempdir } + let scope = Arc::new(PuffinStorageScope::new( + "file".to_string(), + String::new(), + tempdir.path().to_string_lossy().into_owned(), + )); + Self { tempdir, scope } } } @@ -53,6 +66,10 @@ impl PuffinFileAccessor for MockFileAccessor { type Writer = Compat; type FileHandle = String; + fn file_key(&self, handle: &Self::FileHandle) -> PuffinFileKey { + PuffinFileKey::new(self.scope.clone(), handle.clone(), handle.clone()) + } + async fn reader(&self, handle: &String) -> Result { Ok(FileReader::new(self.tempdir.path().join(handle)) .await diff --git a/src/puffin/src/puffin_manager/file_key.rs b/src/puffin/src/puffin_manager/file_key.rs new file mode 100644 index 00000000000..78b5923c3e2 --- /dev/null +++ b/src/puffin/src/puffin_manager/file_key.rs @@ -0,0 +1,171 @@ +// 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 uuid::Uuid; + +/// Stable storage identity shared by file keys from one accessor. +/// Fields stay separate so separators in paths or store names cannot cause collisions. +/// Canonical names can use [`Self::new`]; backends whose metadata does not uniquely +/// identify their endpoint or configuration use [`Self::unique`] and share that scope. +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub struct PuffinStorageScope { + scheme: String, + name: String, + root: String, + instance_id: Uuid, +} + +impl PuffinStorageScope { + /// Identifies the object store backend, name and root. + /// Reconstructed accessors must use the same canonical values for the same storage. + /// The name must distinguish backends with different endpoints or configurations. + pub fn new(scheme: String, name: String, root: String) -> Self { + Self { + scheme, + name, + root, + instance_id: Uuid::nil(), + } + } + + /// Creates isolated identity when store metadata alone cannot distinguish backends. + /// Accessors for the same live backend share this scope rather than recreating it. + pub fn unique(scheme: String, name: String, root: String) -> Self { + Self { + scheme, + name, + root, + instance_id: Uuid::new_v4(), + } + } +} + +/// Immutable file identity for caches; the handle must include its physical version. +/// Equal storage scopes compare by value even when independently allocated. +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub struct PuffinFileKey { + scope: Arc, + path: Arc, + handle: H, +} + +impl PuffinFileKey { + /// Combines the accessor's resolved file path and versioned handle with its store scope. + pub fn new(scope: Arc, path: String, handle: H) -> Self { + Self { + scope, + path: path.into(), + handle, + } + } + + /// Converts the handle representation while preserving the same resolved storage location. + pub fn map_handle(self, map: impl FnOnce(H) -> T) -> PuffinFileKey { + PuffinFileKey { + scope: self.scope, + path: self.path, + handle: map(self.handle), + } + } + + /// Returns the versioned handle for cache invalidation and file bookkeeping. + pub fn handle(&self) -> &H { + &self.handle + } + + /// Conservative key size including the shared scope, but excluding any heap + /// allocations owned by the generic handle. Shared scope is charged per key. + pub fn estimated_size(&self) -> usize { + std::mem::size_of::() + + std::mem::size_of::() + + self.scope.scheme.capacity() + + self.scope.name.capacity() + + self.scope.root.capacity() + + self.path.len() + } +} + +#[cfg(test)] +mod tests { + use std::collections::HashSet; + + use super::*; + + fn scope(parts: [&str; 3]) -> Arc { + let [scheme, name, root] = parts.map(str::to_string); + Arc::new(PuffinStorageScope::new(scheme, name, root)) + } + + #[test] + fn test_reconstructed_keys_share_identity() { + let parts = ["s3", "bucket", "prefix/"]; + let original = PuffinFileKey::new(scope(parts), "table/file".into(), (17_u64, 2_u32)); + let reconstructed = PuffinFileKey::new(scope(parts), "table/file".into(), (17_u64, 2_u32)); + let keys = HashSet::from([original.clone()]); + assert!(keys.contains(&reconstructed)); + assert!(keys.contains(&original.clone())); + assert_eq!(&(17_u64, 2_u32), original.handle()); + assert!(!keys.contains(&PuffinFileKey::new( + scope(parts), + "table/file".into(), + (17_u64, 3_u32) + ))); + assert!(!keys.contains(&PuffinFileKey::new( + scope(parts), + "table/file".into(), + (18_u64, 2_u32) + ))); + } + + #[test] + fn test_unique_scopes_require_explicit_sharing() { + let first = Arc::new(PuffinStorageScope::unique( + "s3".into(), + "bucket".into(), + "/".into(), + )); + let second = Arc::new(PuffinStorageScope::unique( + "s3".into(), + "bucket".into(), + "/".into(), + )); + let key = PuffinFileKey::new(first.clone(), "file".into(), 1_u64); + assert_eq!(key, PuffinFileKey::new(first, "file".into(), 1_u64)); + assert_ne!(key, PuffinFileKey::new(second, "file".into(), 1_u64)); + } + + #[test] + fn test_storage_components_are_independent() { + let parts = ["s3", "bucket", "prefix/"]; + let original = PuffinFileKey::new(scope(parts), "table/file".into(), 17_u64); + for index in 0..parts.len() { + let mut changed = parts; + changed[index] = "different"; + assert_ne!( + original, + PuffinFileKey::new(scope(changed), "table/file".into(), 17_u64) + ); + } + assert_ne!( + original, + PuffinFileKey::new(scope(parts), "other/file".into(), 17_u64) + ); + assert_ne!( + PuffinFileKey::new(scope(["s3", "a:b", "c"]), "d".into(), 17_u64), + PuffinFileKey::new(scope(["s3", "a", "b:c"]), "d".into(), 17_u64), + ); + } +} diff --git a/src/puffin/src/puffin_manager/fs_puffin_manager.rs b/src/puffin/src/puffin_manager/fs_puffin_manager.rs index 8b4e6e64a7b..03d8030dfee 100644 --- a/src/puffin/src/puffin_manager/fs_puffin_manager.rs +++ b/src/puffin/src/puffin_manager/fs_puffin_manager.rs @@ -24,6 +24,7 @@ use crate::error::Result; use crate::puffin_manager::PuffinManager; use crate::puffin_manager::cache::PuffinMetadataCacheRef; use crate::puffin_manager::file_accessor::PuffinFileAccessor; +use crate::puffin_manager::file_key::PuffinFileKey; use crate::puffin_manager::stager::Stager; /// `FsPuffinManager` is a `PuffinManager` that provides readers and writers for puffin data in filesystem. @@ -72,6 +73,10 @@ where type Writer = FsPuffinWriter; type FileHandle = F::FileHandle; + fn file_key(&self, handle: &Self::FileHandle) -> PuffinFileKey { + self.puffin_file_accessor.file_key(handle) + } + async fn reader(&self, handle: &Self::FileHandle) -> Result { Ok(FsPuffinReader::new( handle.clone(), diff --git a/src/puffin/src/puffin_manager/fs_puffin_manager/reader.rs b/src/puffin/src/puffin_manager/fs_puffin_manager/reader.rs index 77834ca2671..a54a044d7c2 100644 --- a/src/puffin/src/puffin_manager/fs_puffin_manager/reader.rs +++ b/src/puffin/src/puffin_manager/fs_puffin_manager/reader.rs @@ -12,6 +12,9 @@ // See the License for the specific language governing permissions and // limitations under the License. +#[cfg(test)] +mod tests; + use std::io; use std::ops::Range; use std::sync::Arc; @@ -23,6 +26,7 @@ use common_base::range_read::{AsyncReadAdapter, Metadata, RangeReader, SizeAware use futures::io::BufReader; use futures::{AsyncRead, AsyncWrite}; use snafu::{OptionExt, ResultExt, ensure}; +use tokio::sync::OnceCell; use crate::blob_metadata::{BlobMetadata, CompressionCodec}; use crate::error::{ @@ -33,12 +37,15 @@ use crate::file_format::reader::{AsyncReader, PuffinFileReader}; use crate::file_metadata::FileMetadata; use crate::partial_reader::PartialReader; use crate::puffin_manager::file_accessor::PuffinFileAccessor; +use crate::puffin_manager::file_key::PuffinFileKey; use crate::puffin_manager::fs_puffin_manager::PuffinMetadataCacheRef; use crate::puffin_manager::fs_puffin_manager::dir_meta::DirMetadata; use crate::puffin_manager::stager::{BoxWriter, DirWriterProviderRef, Stager}; use crate::puffin_manager::{BlobGuard, DirMetrics, GuardWithMetadata, PuffinReader}; /// `FsPuffinReader` is a `PuffinReader` that provides fs readers for puffin files. +/// Metadata is retained for this immutable file identity until the reader is dropped. +/// Replacing file contents requires a new reader and invalidating shared caches. pub struct FsPuffinReader where S: Stager + 'static, @@ -58,6 +65,10 @@ where /// The puffin file metadata cache. puffin_file_metadata_cache: Option, + + /// Successful metadata retained for this immutable file handle. + /// Failures leave the cell empty so a later operation can retry. + metadata: OnceCell>, } impl FsPuffinReader @@ -65,6 +76,11 @@ where S: Stager + 'static, F: PuffinFileAccessor + Clone, { + /// Returns this reader's storage-scoped file identity without opening the file. + pub fn file_key(&self) -> PuffinFileKey { + self.puffin_file_accessor.file_key(&self.handle) + } + pub(crate) fn new( handle: F::FileHandle, stager: S, @@ -77,6 +93,7 @@ where stager, puffin_file_accessor, puffin_file_metadata_cache, + metadata: OnceCell::new(), } } } @@ -96,14 +113,16 @@ where } async fn metadata(&self) -> Result> { + if let Some(metadata) = self.metadata.get() { + return Ok(metadata.clone()); + } let mut file = self.puffin_reader().await?; self.get_puffin_file_metadata(&mut file).await } async fn blob(&self, key: &str) -> Result> { - let mut file = self.puffin_reader().await?; - let metadata = self.get_puffin_file_metadata(&mut file).await?; - let blob_metadata = Self::get_blob_metadata(key, &metadata)?; + let metadata = self.metadata().await?; + let blob_metadata = get_blob_metadata(&metadata, key)?; let blob = if blob_metadata.compression_codec.is_none() { // If the blob is not compressed, we can directly read it from the puffin file. Either::L(RandomReadBlob { @@ -113,6 +132,7 @@ where }) } else { // If the blob is compressed, we need to decompress it into staging space before reading. + let file = self.puffin_reader().await?; let blob_metadata = blob_metadata.clone(); let staged_blob = self .stager @@ -134,7 +154,7 @@ where async fn dir(&self, key: &str) -> Result<(GuardWithMetadata, DirMetrics)> { let mut file = self.puffin_reader().await?; let metadata = self.get_puffin_file_metadata(&mut file).await?; - let blob_metadata = Self::get_blob_metadata(key, &metadata)?; + let blob_metadata = get_blob_metadata(&metadata, key)?; let (dir, metrics) = self .stager .get_dir( @@ -169,26 +189,24 @@ where &self, reader: &mut PuffinFileReader, ) -> Result> { - if let Some(cache) = &self.puffin_file_metadata_cache { - cache - .try_get_with(&self.handle.to_string(), async { - reader.metadata().await.map(Arc::new) - }) - .await - } else { - reader.metadata().await.map(Arc::new) - } - } - - fn get_blob_metadata(key: &str, metadata: &FileMetadata) -> Result { - let blob_metadata = metadata - .blobs - .iter() - .find(|m| m.blob_type == key) - .context(BlobNotFoundSnafu { blob: key })? - .clone(); - - Ok(blob_metadata) + let cached = self + .metadata + .get_or_try_init(|| async { + let metadata = if let Some(cache) = &self.puffin_file_metadata_cache { + let key = self + .puffin_file_accessor + .file_key(&self.handle) + .map_handle(|handle| handle.to_string()); + cache + .try_get_with(&key, async { reader.metadata().await.map(Arc::new) }) + .await? + } else { + Arc::new(reader.metadata().await?) + }; + Ok::<_, crate::error::Error>(metadata) + }) + .await?; + Ok(cached.clone()) } async fn puffin_reader(&self) -> Result> { @@ -372,3 +390,13 @@ where } } } + +/// Looks up the first matching blob without allocating a per-reader key index. +fn get_blob_metadata(metadata: &FileMetadata, key: &str) -> Result { + metadata + .blobs + .iter() + .find(|blob| blob.blob_type == key) + .cloned() + .context(BlobNotFoundSnafu { blob: key }) +} diff --git a/src/puffin/src/puffin_manager/fs_puffin_manager/reader/tests.rs b/src/puffin/src/puffin_manager/fs_puffin_manager/reader/tests.rs new file mode 100644 index 00000000000..566f2257350 --- /dev/null +++ b/src/puffin/src/puffin_manager/fs_puffin_manager/reader/tests.rs @@ -0,0 +1,39 @@ +// 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 super::*; +use crate::blob_metadata::BlobMetadataBuilder; + +#[test] +fn test_blob_lookup_preserves_first_duplicate() { + let blob = |offset| { + BlobMetadataBuilder::default() + .blob_type("duplicate".to_string()) + .offset(offset) + .length(4) + .build() + .unwrap() + }; + let first = blob(4); + let metadata = FileMetadata { + blobs: vec![first.clone(), blob(8)], + properties: Default::default(), + }; + assert_eq!(first, get_blob_metadata(&metadata, "duplicate").unwrap()); + assert!( + get_blob_metadata(&metadata, "unknown") + .unwrap_err() + .is_blob_not_found() + ); +} diff --git a/src/puffin/src/puffin_manager/tests.rs b/src/puffin/src/puffin_manager/tests.rs index a09c5696b41..a5423635d93 100644 --- a/src/puffin/src/puffin_manager/tests.rs +++ b/src/puffin/src/puffin_manager/tests.rs @@ -437,7 +437,7 @@ async fn test_metadata_cache_shared_by_independent_readers() { assert_eq!(1, values[0].blobs.len()); assert_eq!("blob", values[0].blobs[0].blob_type); - cache.remove(&file).await; + cache.remove(&manager.file_key(&file)).await; let reloaded = manager .reader(&file) .await @@ -454,11 +454,13 @@ async fn test_metadata_cache_shared_by_independent_readers() { struct FooterGuardAccessor { inner: MockFileAccessor, blob_end: Arc, + reads: Arc, } struct FooterGuardReader { inner: common_base::range_read::FileReader, blob_end: Arc, + reads: Arc, } #[async_trait::async_trait] @@ -468,10 +470,18 @@ impl crate::puffin_manager::file_accessor::PuffinFileAccessor for FooterGuardAcc ::Writer; type FileHandle = String; + fn file_key( + &self, + handle: &Self::FileHandle, + ) -> crate::puffin_manager::file_key::PuffinFileKey { + self.inner.file_key(handle) + } + async fn reader(&self, handle: &String) -> crate::error::Result { Ok(FooterGuardReader { inner: self.inner.reader(handle).await?, blob_end: self.blob_end.clone(), + reads: self.reads.clone(), }) } @@ -487,6 +497,8 @@ impl RangeReader for FooterGuardReader { } async fn read(&self, range: std::ops::Range) -> std::io::Result { + self.reads + .fetch_add(1, std::sync::atomic::Ordering::Relaxed); if range.end > self.blob_end.load(std::sync::atomic::Ordering::Relaxed) { return Err(std::io::Error::other( "unexpected footer read after cache warmup", @@ -521,6 +533,7 @@ async fn test_cached_metadata_used_when_staging_directory() { let accessor = Arc::new(FooterGuardAccessor { inner: MockFileAccessor::new("cached_directory"), blob_end: blob_end.clone(), + reads: Arc::new(std::sync::atomic::AtomicUsize::new(0)), }); let manager = FsPuffinManager::new(stager.clone(), accessor).with_puffin_metadata_cache(Some(cache)); @@ -548,3 +561,190 @@ async fn test_cached_metadata_used_when_staging_directory() { let reader = manager.reader(&file).await.unwrap(); check_dir(&file, "dir", files, &stager, &reader).await; } + +#[tokio::test] +async fn test_cached_metadata_avoids_footer_reads_for_many_blobs() { + use std::sync::atomic::{AtomicU64, Ordering}; + + use prometheus::Opts; + + use crate::puffin_manager::cache::PuffinMetadataCache; + + let bytes = common_cache::metrics::CacheSizeMetrics::new( + Opts::new("many_blob_metadata_bytes", "test"), + &["type"], + ) + .unwrap(); + let cache = Arc::new(PuffinMetadataCache::new(1024 * 1024, &bytes)); + let (_dir, stager) = new_bounded_stager("cached_many_blobs", 1024 * 1024).await; + let blob_end = Arc::new(AtomicU64::new(u64::MAX)); + let accessor = Arc::new(FooterGuardAccessor { + inner: MockFileAccessor::new("cached_many_blobs"), + blob_end: blob_end.clone(), + reads: Arc::new(std::sync::atomic::AtomicUsize::new(0)), + }); + let manager = FsPuffinManager::new(stager.clone(), accessor.clone()) + .with_puffin_metadata_cache(Some(cache)); + let uncached_manager = FsPuffinManager::new(stager.clone(), accessor); + let file = "many_blobs".to_string(); + let payload = b"identical column sketch payload"; + let mut writer = manager.writer(&file).await.unwrap(); + for column in 0..64 { + put_blob(&format!("sketch.v1.{column}"), payload, None, &mut writer).await; + } + writer.finish().await.unwrap(); + let reader = manager.reader(&file).await.unwrap(); + let metadata = reader.metadata().await.unwrap(); + assert_eq!(64, metadata.blobs.len()); + blob_end.store( + metadata + .blobs + .iter() + .map(|blob| u64::try_from(blob.offset + blob.length).unwrap()) + .max() + .unwrap(), + Ordering::Relaxed, + ); + + // Any footer range read now fails, so all 64 lookups must reuse the cache. + for column in 0..64 { + check_blob( + &file, + &format!("sketch.v1.{column}"), + payload, + &stager, + &reader, + false, + ) + .await; + } + + // Same file and payload: removing only the cache must trip the footer guard. + let uncached_reader = uncached_manager.reader(&file).await.unwrap(); + let error = match uncached_reader.blob("sketch.v1.0").await { + Ok(_) => panic!("uncached lookup unexpectedly avoided the footer"), + Err(error) => error, + }; + assert!(format!("{error:?}").contains("unexpected footer read after cache warmup")); +} + +async fn check_reader_local_metadata_reuse_without_global_cache(blob_count: usize) { + use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering}; + + let (_dir, stager) = new_bounded_stager("reader_local_metadata", 1024 * 1024).await; + let reads = Arc::new(AtomicUsize::new(0)); + let accessor = Arc::new(FooterGuardAccessor { + inner: MockFileAccessor::new("reader_local_metadata"), + blob_end: Arc::new(AtomicU64::new(u64::MAX)), + reads: reads.clone(), + }); + let manager = FsPuffinManager::new(stager, accessor); + let file = "many_blobs".to_string(); + let mut writer = manager.writer(&file).await.unwrap(); + for column in 0..blob_count { + put_blob(&format!("column.{column}"), b"payload", None, &mut writer).await; + } + writer.finish().await.unwrap(); + + let reader = manager.reader(&file).await.unwrap(); + let metadata = futures::future::join_all((0..8).map(|_| reader.metadata())).await; + let first = metadata[0].as_ref().unwrap(); + for value in &metadata { + assert!(Arc::ptr_eq(first, value.as_ref().unwrap())); + } + let cold_reads = reads.swap(0, Ordering::Relaxed); + assert!(cold_reads > 0); + + // Metadata inspection and uncompressed lookup must reuse one footer. + for column in 0..blob_count { + let key = format!("column.{column}"); + let metadata = reader.blob_metadata(&key).await.unwrap().unwrap(); + assert_eq!(7, metadata.length); + assert_eq!(None, metadata.compression_codec); + reader.blob(&key).await.unwrap(); + } + assert!(reader.blob_metadata("missing").await.unwrap().is_none()); + assert_eq!(0, reads.swap(0, Ordering::Relaxed)); + + // Same file, keys and disabled global cache; change only reader reuse. + for column in 0..blob_count { + manager + .reader(&file) + .await + .unwrap() + .blob(&format!("column.{column}")) + .await + .unwrap(); + } + assert_eq!(blob_count * cold_reads, reads.load(Ordering::Relaxed)); +} + +#[tokio::test] +async fn test_reader_local_metadata_failure_is_retryable() { + use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering}; + + let (_dir, stager) = new_bounded_stager("reader_local_retry", 1024 * 1024).await; + let reads = Arc::new(AtomicUsize::new(0)); + let blob_end = Arc::new(AtomicU64::new(0)); + let accessor = Arc::new(FooterGuardAccessor { + inner: MockFileAccessor::new("reader_local_retry"), + blob_end: blob_end.clone(), + reads: reads.clone(), + }); + let manager = FsPuffinManager::new(stager, accessor); + let file = "retry".to_string(); + let mut writer = manager.writer(&file).await.unwrap(); + put_blob("key", b"payload", None, &mut writer).await; + writer.finish().await.unwrap(); + let reader = manager.reader(&file).await.unwrap(); + assert!(reader.metadata().await.is_err()); + blob_end.store(u64::MAX, Ordering::Relaxed); + let metadata = reader.metadata().await.unwrap(); + blob_end.store(0, Ordering::Relaxed); + reads.store(0, Ordering::Relaxed); + assert!(Arc::ptr_eq(&metadata, &reader.metadata().await.unwrap())); + reader.blob("key").await.unwrap(); + assert!(reader.blob("missing").await.is_err()); + assert_eq!(0, reads.load(Ordering::Relaxed)); +} + +#[tokio::test] +async fn test_reader_local_metadata_reuse_without_global_cache() { + for blob_count in [64, 1024] { + check_reader_local_metadata_reuse_without_global_cache(blob_count).await; + } +} + +#[tokio::test] +async fn test_blob_metadata_rejects_duplicate_keys() { + use crate::file_format::writer::{AsyncWriter, Blob, PuffinFileWriter}; + use crate::puffin_manager::file_accessor::PuffinFileAccessor; + + let (_dir, stager) = new_bounded_stager("duplicate_blob_metadata", 1024).await; + let accessor = Arc::new(MockFileAccessor::new("duplicate_blob_metadata")); + let file = "duplicates".to_string(); + // External files can contain duplicate keys, unlike FsPuffinWriter output. + let mut writer = PuffinFileWriter::new(accessor.writer(&file).await.unwrap()); + for payload in [b"first".as_slice(), b"second".as_slice()] { + writer + .add_blob(Blob { + blob_type: "duplicate".to_string(), + compressed_data: payload, + compression_codec: None, + properties: HashMap::from_iter([( + "test_key".to_string(), + "test_value".to_string(), + )]), + }) + .await + .unwrap(); + } + writer.finish().await.unwrap(); + drop(writer); + let manager = FsPuffinManager::new(stager.clone(), accessor); + let reader = manager.reader(&file).await.unwrap(); + let error = reader.blob_metadata("duplicate").await.unwrap_err(); + assert!(matches!(error, crate::error::Error::AmbiguousBlob { .. })); + assert!(reader.blob_metadata("missing").await.unwrap().is_none()); + check_blob(&file, "duplicate", b"first", &stager, &reader, false).await; +} diff --git a/src/query/Cargo.toml b/src/query/Cargo.toml index 1d95f7856d5..950f5da9e82 100644 --- a/src/query/Cargo.toml +++ b/src/query/Cargo.toml @@ -81,9 +81,11 @@ uuid.workspace = true [dev-dependencies] arrow.workspace = true +cache.workspace = true catalog = { workspace = true, features = ["testing"] } common-function.workspace = true common-macro.workspace = true +common-procedure.workspace = true common-query = { workspace = true, features = ["testing"] } fastrand = "2.0" moka = { workspace = true, features = ["future"] } diff --git a/src/query/src/datafusion.rs b/src/query/src/datafusion.rs index 874e3901498..e00ec1ebb1e 100644 --- a/src/query/src/datafusion.rs +++ b/src/query/src/datafusion.rs @@ -1748,6 +1748,15 @@ mod tests { unimplemented!("unexpected compact_region") } + async fn cancel_region_compaction( + &self, + _region_id: store_api::storage::RegionId, + _task_id: String, + _ctx: session::context::QueryContextRef, + ) -> common_query::error::Result { + unimplemented!("unexpected cancel_region_compaction") + } + async fn discard_unflushed_data( &self, _region_id: store_api::storage::RegionId, diff --git a/src/query/src/datafusion/json_expr_planner.rs b/src/query/src/datafusion/json_expr_planner.rs index 79af2405ff0..89ba57e3dbc 100644 --- a/src/query/src/datafusion/json_expr_planner.rs +++ b/src/query/src/datafusion/json_expr_planner.rs @@ -754,6 +754,7 @@ mod tests { data_type: ConcreteDataType::int64_datatype(), inverted_index: false, skipping_index: None, + fulltext_index: None, }], None, ) @@ -789,12 +790,14 @@ mod tests { data_type: ConcreteDataType::int64_datatype(), inverted_index: false, skipping_index: None, + fulltext_index: None, }, JsonTypeHint { path: vec!["payload.cpu".to_string()], data_type: ConcreteDataType::string_datatype(), inverted_index: false, skipping_index: None, + fulltext_index: None, }, ], None, diff --git a/src/query/src/optimizer.rs b/src/query/src/optimizer.rs index 1fc0730c4fd..62894a0862b 100644 --- a/src/query/src/optimizer.rs +++ b/src/query/src/optimizer.rs @@ -23,10 +23,12 @@ pub(crate) mod infer_aggregate_input_bounds; pub(crate) mod insert_assignment; pub(crate) mod json_schema_concretize; pub(crate) mod json_type_concretize; +pub(crate) mod merge_scan_projection; pub mod parallelize_scan; pub mod promql_tsid_narrow_join; pub mod remove_duplicate; pub mod scan_hint; +pub(crate) mod sst_manifest_aggregate; pub mod string_normalization; #[cfg(test)] pub(crate) mod test_util; diff --git a/src/query/src/optimizer/merge_scan_projection.rs b/src/query/src/optimizer/merge_scan_projection.rs new file mode 100644 index 00000000000..12a3a534df6 --- /dev/null +++ b/src/query/src/optimizer/merge_scan_projection.rs @@ -0,0 +1,141 @@ +// 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 datafusion_common::Result; +use datafusion_common::tree_node::Transformed; +use datafusion_expr::{Expr, LogicalPlan, LogicalPlanBuilder}; +use datafusion_optimizer::optimizer::ApplyOrder; +use datafusion_optimizer::{OptimizerConfig, OptimizerRule}; + +use crate::dist_plan::MergeScanLogicalPlan; + +#[derive(Debug)] +pub(crate) struct MergeScanProjection; + +impl OptimizerRule for MergeScanProjection { + fn name(&self) -> &str { + "merge_scan_projection" + } + + fn apply_order(&self) -> Option { + Some(ApplyOrder::BottomUp) + } + + fn rewrite( + &self, + plan: LogicalPlan, + _config: &dyn OptimizerConfig, + ) -> Result> { + let LogicalPlan::Projection(projection) = &plan else { + return Ok(Transformed::no(plan)); + }; + // Remote batches do not yet preserve the row count of empty projections. + if projection.expr.is_empty() + || !projection + .expr + .iter() + .all(|expr| matches!(expr, Expr::Column(_))) + { + return Ok(Transformed::no(plan)); + } + let LogicalPlan::Extension(extension) = projection.input.as_ref() else { + return Ok(Transformed::no(plan)); + }; + let Some(scan) = extension + .node + .as_any() + .downcast_ref::() + else { + return Ok(Transformed::no(plan)); + }; + if scan.is_placeholder() { + return Ok(Transformed::no(plan)); + } + // Project after the remote subtree, preserving its sort, limit, and aggregation scope. + let remote = LogicalPlanBuilder::from(scan.input().clone()) + .project(projection.expr.clone())? + .build()?; + let mut projected = + MergeScanLogicalPlan::new(remote, false).with_output_schema(projection.schema.clone()); + if let Some(id) = scan.remote_dyn_filter_producer_id() { + projected = projected.with_remote_dyn_filter_producer_id(id); + } + Ok(Transformed::yes(projected.into_logical_plan())) + } +} + +#[cfg(test)] +mod tests { + use datafusion_expr::{col, lit}; + use datafusion_optimizer::optimizer::OptimizerContext; + + use super::*; + + #[test] + fn projects_remote_columns_without_changing_limit_scope() { + let input = LogicalPlanBuilder::values(vec![vec![lit(1), lit(2)]]) + .unwrap() + .limit(0, Some(1)) + .unwrap() + .build() + .unwrap(); + let producer = crate::dist_plan::RemoteDynFilterProducerId::new(42); + let scan = MergeScanLogicalPlan::new(input.clone(), false) + .with_remote_dyn_filter_producer_id(producer); + let plan = LogicalPlanBuilder::from(scan.into_logical_plan()) + .project(vec![col("column2")]) + .unwrap() + .build() + .unwrap(); + let schema = plan.schema().clone(); + let result = MergeScanProjection + .rewrite(plan, &OptimizerContext::new()) + .unwrap(); + assert!(result.transformed); + assert_eq!(result.data.schema(), &schema); + let LogicalPlan::Extension(extension) = result.data else { + panic!("expected MergeScan") + }; + let scan = extension + .node + .as_any() + .downcast_ref::() + .unwrap(); + assert_eq!(scan.remote_dyn_filter_producer_id(), Some(producer)); + let LogicalPlan::Projection(projection) = scan.input() else { + panic!("expected remote projection") + }; + assert_eq!(projection.expr, vec![col("column2")]); + assert_eq!(*projection.input, input); + } + + #[test] + fn keeps_computed_expressions_local() { + let input = LogicalPlanBuilder::values(vec![vec![lit(1), lit(2)]]) + .unwrap() + .build() + .unwrap(); + let plan = + LogicalPlanBuilder::from(MergeScanLogicalPlan::new(input, false).into_logical_plan()) + .project(vec![col("column2") + lit(1)]) + .unwrap() + .build() + .unwrap(); + let result = MergeScanProjection + .rewrite(plan.clone(), &OptimizerContext::new()) + .unwrap(); + assert!(!result.transformed); + assert_eq!(result.data, plan); + } +} diff --git a/src/query/src/optimizer/sst_manifest_aggregate.rs b/src/query/src/optimizer/sst_manifest_aggregate.rs new file mode 100644 index 00000000000..e1d99ea0d3f --- /dev/null +++ b/src/query/src/optimizer/sst_manifest_aggregate.rs @@ -0,0 +1,296 @@ +// 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. + +//! Partial aggregation of the manifest inventory on each datanode. + +#[cfg(test)] +mod tests; + +use std::fmt; +use std::sync::Arc; + +use arrow_schema::DataType; +use catalog::information_schema::{InformationExtensionRef, SSTS_MANIFEST}; +use common_catalog::consts; +use common_function::aggrs::aggr_wrapper::{StateMergeHelper, get_aggr_func}; +use common_query::logical_plan::is_lossless_substrait_type; +use datafusion::catalog::Session; +use datafusion::datasource::DefaultTableSource; +use datafusion::functions_aggregate::{count::count_udaf, sum::sum_udaf}; +use datafusion::logical_expr::physical_planning_context::PhysicalPlanningContext; +use datafusion::physical_plan::ExecutionPlan; +use datafusion::physical_planner::{ExtensionPlanner, PhysicalPlanner}; +use datafusion_common::config::ConfigOptions; +use datafusion_common::tree_node::{Transformed, TreeNode, TreeNodeRecursion}; +use datafusion_common::{DFSchema, DFSchemaRef, DataFusionError, Result, ScalarValue}; +use datafusion_expr::{ + Expr, ExprSchemable, Extension, LogicalPlan, LogicalPlanBuilder, UserDefinedLogicalNode, + UserDefinedLogicalNodeCore, +}; +use datafusion_optimizer::AnalyzerRule; +use datatypes::schema::Schema; +use store_api::sst_entry::ManifestSstEntry; +use store_api::storage::ScanRequest; +use table::table::adapter::DfTableProviderAdapter; + +/// Splits supported ungrouped manifest aggregates before general distributed planning. +#[derive(Debug)] +pub(crate) struct SstManifestAggregateRule; + +impl AnalyzerRule for SstManifestAggregateRule { + fn name(&self) -> &str { + "sst_manifest_aggregate" + } + + fn analyze(&self, plan: LogicalPlan, _config: &ConfigOptions) -> Result { + Ok(plan + .transform_up_with_subqueries(|plan| { + let LogicalPlan::Aggregate(aggregate) = &plan else { + return Ok(Transformed::no(plan)); + }; + if !aggregate.group_expr.is_empty() + || aggregate.aggr_expr.is_empty() + || !aggregate + .aggr_expr + .iter() + .all(|expr| is_supported_aggregate(expr, aggregate.input.schema())) + || !is_supported_input(&aggregate.input) + { + return Ok(Transformed::no(plan)); + } + let split = StateMergeHelper::split_aggr_node(aggregate.clone())?; + // The frontend may compute types that cannot cross the inspection boundary. + if Schema::try_from(split.lower_state.schema().clone()).is_err() { + return Ok(Transformed::no(plan)); + } + let remote = split + .lower_state + .transform_up(|node| { + if let LogicalPlan::TableScan(scan) = node { + // An alias preserves the original qualified column bindings above the scan. + let reserved = ManifestSstEntry::build_plan(ScanRequest::default())?; + let replacement = LogicalPlanBuilder::from(reserved) + .alias(scan.table_name)? + .build()?; + Ok(Transformed::yes(replacement)) + } else { + Ok(Transformed::no(node)) + } + })? + .data; + let leaf = LogicalPlan::Extension(Extension { + node: Arc::new(SstManifestAggregate { remote }), + }); + let upper = split + .upper_merge + .with_new_exprs(split.upper_merge.expressions(), vec![leaf])?; + Ok(Transformed::yes(upper)) + })? + .data) + } +} + +/// Converts manifest state leaves into the catalog's distributed inspection plan. +pub(crate) struct SstManifestAggregatePlanner { + extension: InformationExtensionRef, +} + +impl SstManifestAggregatePlanner { + /// Uses the same capability-checked extension as the analyzer registration. + pub(crate) fn new(extension: InformationExtensionRef) -> Self { + Self { extension } + } +} + +#[async_trait::async_trait] +impl ExtensionPlanner for SstManifestAggregatePlanner { + async fn plan_extension( + &self, + _planner: &dyn PhysicalPlanner, + node: &dyn UserDefinedLogicalNode, + _logical_inputs: &[&LogicalPlan], + _physical_inputs: &[Arc], + _session: &dyn Session, + _planning_ctx: &PhysicalPlanningContext, + ) -> Result>> { + let Some(node) = node.as_any().downcast_ref::() else { + return Ok(None); + }; + self.extension + .inspect_datanode_query_plan(node.remote.clone()) + .map_err(|error| DataFusionError::External(Box::new(error)))? + .map(Some) + .ok_or_else(|| { + DataFusionError::Internal( + "Manifest aggregation requires inspect query support".into(), + ) + }) + } +} + +/// Carries remote aggregate states without exposing them to frontend optimizer rewrites. +#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Hash)] +struct SstManifestAggregate { + remote: LogicalPlan, +} + +impl UserDefinedLogicalNodeCore for SstManifestAggregate { + fn name(&self) -> &str { + "SstManifestAggregate" + } + fn inputs(&self) -> Vec<&LogicalPlan> { + vec![] + } + fn schema(&self) -> &DFSchemaRef { + self.remote.schema() + } + fn expressions(&self) -> Vec { + vec![] + } + fn fmt_for_explain(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "SstManifestAggregate: {}", self.remote.display_indent()) + } + fn with_exprs_and_inputs(&self, exprs: Vec, inputs: Vec) -> Result { + if !exprs.is_empty() || !inputs.is_empty() { + return Err(DataFusionError::Internal( + "SstManifestAggregate is a leaf".into(), + )); + } + Ok(self.clone()) + } +} + +fn is_supported_aggregate(expr: &Expr, schema: &DFSchema) -> bool { + let Some(function) = get_aggr_func(expr) else { + return false; + }; + let params = &function.params; + if params.distinct || !params.order_by.is_empty() || params.null_treatment.is_some() { + return false; + } + if params + .filter + .as_deref() + .is_some_and(|filter| !is_supported_predicate(filter, schema)) + { + return false; + } + if function.func == count_udaf() { + matches!( + params.args.as_slice(), + [Expr::Column(_)] + | [Expr::Literal( + ScalarValue::Int64(Some(1)) + | ScalarValue::UInt64(Some(1)) + | ScalarValue::Int32(Some(1)) + | ScalarValue::UInt8(Some(1)), + _ + )] + ) + } else if function.func == sum_udaf() { + matches!(params.args.as_slice(), [arg] if is_numeric_column(arg, schema)) + } else { + false + } +} + +// SUM coerces narrow numeric columns before this rule runs. Keep those casts in +// the remote plan while rejecting computed aggregate arguments. +fn is_numeric_column(expr: &Expr, schema: &DFSchema) -> bool { + match expr { + Expr::Column(_) => expr + .get_type(schema) + .is_ok_and(|data_type| data_type.is_numeric()), + Expr::Cast(cast) if cast.field.data_type().is_numeric() => { + is_numeric_column(&cast.expr, schema) + } + _ => false, + } +} + +fn is_supported_predicate(expr: &Expr, schema: &DFSchema) -> bool { + let mut supported = true; + let visited = expr.apply(|expr| { + // Aggregate state types do not cover intermediate predicate types. In particular, + // Substrait loses timestamp timezones even when encoding succeeds. + let Ok(data_type) = expr.get_type(schema) else { + supported = false; + return Ok(TreeNodeRecursion::Stop); + }; + if !is_lossless_substrait_type(&data_type) { + supported = false; + return Ok(TreeNodeRecursion::Stop); + } + // The SQL parser represents TIMESTAMP_NS literals as arrow_cast calls. + // Limit this exception to timezone-free timestamps and still check the arguments. + if let Expr::ScalarFunction(function) = expr + && function.func == datafusion::functions::core::arrow_cast() + && matches!(data_type, DataType::Timestamp(_, None)) + && function + .args + .iter() + .all(|arg| matches!(arg, Expr::Literal(_, _))) + { + return Ok(TreeNodeRecursion::Continue); + } + if !matches!( + expr, + Expr::Column(_) + | Expr::Literal(_, _) + | Expr::BinaryExpr(_) + | Expr::Cast(_) + | Expr::TryCast(_) + | Expr::Not(_) + | Expr::IsNull(_) + | Expr::IsNotNull(_) + | Expr::Between(_) + | Expr::InList(_) + ) { + supported = false; + return Ok(TreeNodeRecursion::Stop); + } + Ok(TreeNodeRecursion::Continue) + }); + visited.is_ok() && supported +} + +fn is_supported_input(plan: &LogicalPlan) -> bool { + match plan { + LogicalPlan::Filter(filter) => { + is_supported_predicate(&filter.predicate, filter.input.schema()) + && is_supported_input(&filter.input) + } + LogicalPlan::SubqueryAlias(alias) => is_supported_input(&alias.input), + LogicalPlan::TableScan(scan) => { + if scan.fetch.is_some() || scan.projection.is_some() || !scan.filters.is_empty() { + return false; + } + let Some(source) = scan.source.downcast_ref::() else { + return false; + }; + let Some(adapter) = source + .table_provider + .downcast_ref::() + else { + return false; + }; + let info = adapter.table().table_info(); + info.ident.table_id == consts::INFORMATION_SCHEMA_SSTS_MANIFEST_TABLE_ID + && info.schema_name == consts::INFORMATION_SCHEMA_NAME + && info.name == SSTS_MANIFEST + && info.meta.schema.as_ref() == ManifestSstEntry::schema().as_ref() + } + _ => false, + } +} diff --git a/src/query/src/optimizer/sst_manifest_aggregate/tests.rs b/src/query/src/optimizer/sst_manifest_aggregate/tests.rs new file mode 100644 index 00000000000..3ab2bdb598f --- /dev/null +++ b/src/query/src/optimizer/sst_manifest_aggregate/tests.rs @@ -0,0 +1,505 @@ +// 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 catalog::information_schema::{DatanodeInspectRequest, InformationExtension}; +use common_meta::cluster::NodeInfo; +use common_meta::datanode::RegionStat; +use common_meta::key::flow::flow_state::FlowStat; +use common_procedure::ProcedureInfo; +use common_query::logical_plan::SubstraitPlanDecoder; +use common_recordbatch::SendableRecordBatchStream; +use datafusion::arrow::record_batch::RecordBatch; +use datafusion::datasource::{MemTable, provider_as_source}; +use datafusion::execution::TaskContext; +use datafusion::physical_plan::SendableRecordBatchStream as DfStream; +use datafusion::physical_plan::stream::RecordBatchStreamAdapter; +use datafusion::physical_plan::streaming::{PartitionStream, StreamingTableExec}; +use datafusion::physical_planner::DefaultPhysicalPlanner; +use datafusion::prelude::SessionContext; +use datafusion_optimizer::Analyzer; +use session::context::QueryContext; +use store_api::data_source::DataSource; +use substrait::{DFLogicalSubstraitConvertor, SubstraitPlan}; +use table::metadata::{FilterPushDownType, TableInfoBuilder, TableMetaBuilder}; +use table::table::Table; + +use super::*; +use crate::query_engine::{DefaultPlanDecoder, DefaultSerializer}; + +struct PlanningOnlySource; + +impl DataSource for PlanningOnlySource { + fn get_stream( + &self, + _request: ScanRequest, + ) -> std::result::Result { + unreachable!("tests replace table sources before execution") + } +} + +fn table_provider(table_id: u32) -> Arc { + let schema = ManifestSstEntry::schema(); + let next_column_id = u32::try_from(schema.num_columns()).unwrap(); + let meta = TableMetaBuilder::new_external_table() + .schema(schema) + .next_column_id(next_column_id) + .build() + .unwrap(); + let info = TableInfoBuilder::new("ssts_manifest", meta) + .table_id(table_id) + .schema_name(consts::INFORMATION_SCHEMA_NAME) + .build() + .unwrap(); + Arc::new(DfTableProviderAdapter::new(Arc::new(Table::new( + Arc::new(info), + FilterPushDownType::Unsupported, + Arc::new(PlanningOnlySource), + )))) +} + +fn batch(sizes: Vec) -> RecordBatch { + let entries = sizes + .into_iter() + .enumerate() + .map(|(index, file_size)| ManifestSstEntry { + table_dir: "test/".into(), + region_id: 42.into(), + table_id: 0, + region_number: 42, + region_group: 0, + region_sequence: 42, + file_id: index.to_string(), + index_version: 0, + level: 0, + file_path: format!("test/{index}.parquet"), + file_size, + max_row_group_uncompressed_size: 0, + index_file_path: None, + index_file_size: (index % 2 == 0).then_some(file_size), + num_rows: 1, + num_row_groups: 1, + num_series: None, + min_ts: common_time::Timestamp::new_millisecond(index as i64), + max_ts: common_time::Timestamp::new_millisecond(index as i64), + sequence: None, + partition_expr: None, + origin_region_id: 42.into(), + node_id: None, + visible: true, + primary_key_min: None, + primary_key_max: None, + }) + .collect::>(); + ManifestSstEntry::to_record_batch(&entries).unwrap() +} + +fn replace_source(plan: LogicalPlan, batches: Vec) -> LogicalPlan { + let table = Arc::new( + MemTable::try_new( + ManifestSstEntry::schema().arrow_schema().clone(), + vec![batches], + ) + .unwrap(), + ); + plan.transform_up(|plan| { + if let LogicalPlan::TableScan(mut scan) = plan { + scan.source = provider_as_source(table.clone()); + Ok(Transformed::yes(LogicalPlan::TableScan(scan))) + } else { + Ok(Transformed::no(plan)) + } + }) + .unwrap() + .data +} + +#[derive(Debug, Clone)] +struct LocalNodes { + batches: Vec, + states: Arc, +} + +#[derive(Debug)] +struct StatePartition { + nodes: LocalNodes, + remote: LogicalPlan, + schema: datafusion::arrow::datatypes::SchemaRef, +} + +impl PartitionStream for StatePartition { + fn schema(&self) -> &datafusion::arrow::datatypes::SchemaRef { + &self.schema + } + + fn execute(&self, _ctx: Arc) -> DfStream { + let nodes = self.nodes.clone(); + let remote = self.remote.clone(); + Box::pin(RecordBatchStreamAdapter::new( + self.schema.clone(), + async_stream::try_stream! { + for batch in nodes.batches { + let ctx = SessionContext::new(); + let table = MemTable::try_new(batch.schema(), vec![vec![batch]])?; + ctx.register_table( + ManifestSstEntry::reserved_table_name_for_inspection(), + Arc::new(table), + )?; + // Exercise the same bytes and decoder as frontend -> datanode inspection. + let encoded = DFLogicalSubstraitConvertor + .encode(&remote, DefaultSerializer) + .map_err(|error| DataFusionError::External(Box::new(error)))?; + let decoder = DefaultPlanDecoder::new(ctx.state(), &QueryContext::arc()) + .map_err(|error| DataFusionError::External(Box::new(error)))?; + let plan = decoder + .decode(encoded, ctx.state().catalog_list().clone(), false) + .await + .map_err(|error| DataFusionError::External(Box::new(error)))?; + for state in datafusion::dataframe::DataFrame::new(ctx.state(), plan).collect().await? { + nodes.states.fetch_add(state.num_rows(), Ordering::SeqCst); + yield state; + } + } + }, + )) + } +} + +#[async_trait::async_trait] +impl InformationExtension for LocalNodes { + type Error = catalog::error::Error; + + async fn nodes(&self) -> std::result::Result, Self::Error> { + unimplemented!() + } + + async fn procedures(&self) -> std::result::Result, Self::Error> { + unimplemented!() + } + + async fn region_stats(&self) -> std::result::Result, Self::Error> { + unimplemented!() + } + + async fn flow_stats(&self) -> std::result::Result, Self::Error> { + unimplemented!() + } + + async fn inspect_datanode( + &self, + _request: DatanodeInspectRequest, + ) -> std::result::Result { + unimplemented!() + } + + fn supports_inspect_query_plan(&self) -> bool { + true + } + + fn inspect_datanode_query_plan( + &self, + remote: LogicalPlan, + ) -> std::result::Result>, Self::Error> { + let schema = Arc::new(remote.schema().as_arrow().clone()); + let partition = StatePartition { + nodes: self.clone(), + remote, + schema: schema.clone(), + }; + Ok(Some(Arc::new( + StreamingTableExec::try_new(schema, vec![Arc::new(partition)], None, None, false, None) + .unwrap(), + ))) + } +} + +async fn analyzed(sql: &str, table_id: u32) -> LogicalPlan { + let context = SessionContext::new(); + context + .register_table("ssts_manifest", table_provider(table_id)) + .unwrap(); + let plan = context.sql(sql).await.unwrap().into_unoptimized_plan(); + Analyzer::new() + .execute_and_check(plan, &ConfigOptions::default(), |_, _| {}) + .unwrap() +} + +fn has_remote(plan: &LogicalPlan) -> bool { + let mut found = false; + plan.apply(|plan| { + if let LogicalPlan::Extension(extension) = plan { + found |= extension.node.as_any().is::(); + } + Ok(TreeNodeRecursion::Continue) + }) + .unwrap(); + found +} + +#[tokio::test] +async fn test_manifest_aggregate_states_match_baseline() { + for sizes in [ + vec![vec![0, 2, 10], vec![3, 9], vec![]], + vec![vec![], vec![]], + vec![], + ] { + for sql in [ + "SELECT COUNT(*), COUNT(1), SUM(file_size) FROM ssts_manifest", + "SELECT SUM(CAST(file_size AS DOUBLE)), SUM(CAST(index_file_size AS DECIMAL(20, 0))) FROM ssts_manifest", + "SELECT COUNT(file_id), COUNT(index_file_size), COUNT(node_id), COUNT(visible), COUNT(min_ts), COUNT(primary_key_min), SUM(node_id), SUM(index_file_size), SUM(num_rows), SUM(level), SUM(table_id) FROM ssts_manifest", + "SELECT COUNT(file_id) FILTER (WHERE visible AND level = 0), SUM(num_rows) FILTER (WHERE min_ts >= CAST(1 AS TIMESTAMP)), SUM(index_file_size) FILTER (WHERE index_file_size IS NOT NULL), COUNT(*) FILTER (WHERE file_size % 2 = 0) FROM ssts_manifest", + "SELECT COUNT(*) FILTER (WHERE min_ts < arrow_cast('1970-01-02T00:00:00', 'Timestamp(Nanosecond, None)')), SUM(file_size) FILTER (WHERE TRY_CAST(file_size AS BIGINT) > 0) FROM ssts_manifest", + "SELECT COUNT(*) FROM ssts_manifest WHERE CAST(file_size AS DECIMAL(20, 0)) > CAST(0 AS DECIMAL(20, 0))", + "SELECT COUNT(*) AS files, SUM(m.file_size) AS bytes FROM ssts_manifest m WHERE m.file_size >= 2", + "SELECT COUNT(*), SUM(file_size), COUNT(*) FILTER (WHERE file_size < 5), SUM(file_size) FILTER (WHERE file_size < 5) FROM ssts_manifest", + "SELECT COUNT(*), SUM(file_size) FROM ssts_manifest WHERE file_size > 100", + "SELECT SUM(file_size) FILTER (WHERE file_size > 100) AS missing FROM ssts_manifest", + "SELECT COUNT(*) FILTER (WHERE file_size < 5), COUNT(*) FILTER (WHERE file_size < 10), SUM(file_size) FILTER (WHERE file_size < 5), SUM(file_size) FILTER (WHERE file_size < 10) FROM ssts_manifest", + ] { + let plan = analyzed(sql, consts::INFORMATION_SCHEMA_SSTS_MANIFEST_TABLE_ID).await; + let mut analyzer = Analyzer::new(); + analyzer.rules.push(Arc::new(SstManifestAggregateRule)); + analyzer + .rules + .push(Arc::new(crate::dist_plan::DistPlannerAnalyzer)); + analyzer.rules.push(Arc::new( + common_function::aggrs::aggr_wrapper::fix_order::FixStateUdafOrderingAnalyzer, + )); + let rewritten = analyzer + .execute_and_check(plan.clone(), &ConfigOptions::default(), |_, _| {}) + .unwrap(); + assert!( + has_remote(&rewritten), + "{sql}: {rewritten}; original: {plan:?}" + ); + assert_eq!(plan.schema(), rewritten.schema()); + let batches = sizes.iter().cloned().map(batch).collect::>(); + let expected_context = SessionContext::new(); + let expected = datafusion::dataframe::DataFrame::new( + expected_context.state(), + replace_source(plan, batches.clone()), + ) + .collect() + .await + .unwrap(); + let nodes = Arc::new(LocalNodes { + batches, + states: Arc::new(AtomicUsize::new(0)), + }); + let planner = DefaultPhysicalPlanner::with_extension_planners(vec![Arc::new( + SstManifestAggregatePlanner::new(nodes.clone()), + )]); + let context = SessionContext::new(); + let physical = planner + .create_physical_plan(&rewritten, &context.state()) + .await + .unwrap(); + let actual = datafusion::physical_plan::collect(physical, context.task_ctx()) + .await + .unwrap(); + assert_eq!(actual, expected, "{sql}, {sizes:?}"); + assert_eq!( + nodes.states.load(Ordering::SeqCst), + sizes.len(), + "one state row per node" + ); + } + } +} + +#[tokio::test] +async fn test_manifest_aggregate_fallbacks() { + for sql in [ + "SELECT COUNT(DISTINCT file_size) FROM ssts_manifest", + "SELECT AVG(file_size) FROM ssts_manifest", + "SELECT COUNT(*) FROM ssts_manifest WHERE file_path LIKE 'test/%'", + "SELECT CAST(SUM(CAST(file_size AS DECIMAL(39, 0))) AS DOUBLE) FROM ssts_manifest", + "SELECT COUNT(*), CAST(SUM(CAST(file_size AS DECIMAL(39, 0))) AS DOUBLE) FROM ssts_manifest", + "SELECT file_size, COUNT(*) FROM ssts_manifest GROUP BY file_size", + "SELECT SUM(file_size + 1) FROM ssts_manifest", + "SELECT SUM(CAST(min_ts AS BIGINT)) FROM ssts_manifest", + "SELECT COUNT(file_size + 1) FROM ssts_manifest", + "SELECT SUM(CAST(file_size + 1 AS DOUBLE)) FROM ssts_manifest", + "SELECT COUNT(*) FROM ssts_manifest WHERE length(file_path) > 0", + "SELECT COUNT(*) FROM (SELECT * FROM ssts_manifest LIMIT 1) m", + "SELECT SUM(file_size) FILTER (WHERE length(file_path) > 0) FROM ssts_manifest", + ] { + let plan = analyzed(sql, consts::INFORMATION_SCHEMA_SSTS_MANIFEST_TABLE_ID).await; + let rewritten = SstManifestAggregateRule + .analyze(plan.clone(), &ConfigOptions::default()) + .unwrap(); + assert_eq!(rewritten, plan, "{sql}"); + } + let plan = analyzed("SELECT COUNT(*) FROM ssts_manifest", 1000).await; + assert_eq!( + SstManifestAggregateRule + .analyze(plan.clone(), &ConfigOptions::default()) + .unwrap(), + plan + ); +} + +#[tokio::test] +async fn test_manifest_aggregate_real_catalog_timestamp_cast() { + use cache::{build_fundamental_cache_registry, with_default_composite_cache_registry}; + use common_meta::cache::{CacheRegistryBuilder, LayeredCacheRegistryBuilder}; + use common_meta::kv_backend::memory::MemoryKvBackend; + use session::context::QueryContext; + + let nodes = Arc::new(LocalNodes { + batches: vec![batch(vec![0, 2, 10]), batch(vec![3, 9])], + states: Arc::new(AtomicUsize::new(0)), + }); + let backend = Arc::new(MemoryKvBackend::default()); + let caches = LayeredCacheRegistryBuilder::default() + .add_cache_registry(CacheRegistryBuilder::default().build()) + .add_cache_registry(build_fundamental_cache_registry(backend.clone())); + let caches = Arc::new( + with_default_composite_cache_registry(caches) + .unwrap() + .build(), + ); + let catalog = + catalog::kvbackend::KvBackendCatalogManagerBuilder::new(nodes.clone(), backend, caches) + .build(); + let engine = crate::QueryEngineFactory::try_new( + catalog, + None, + None, + None, + None, + true, + Default::default(), + ) + .unwrap() + .query_engine(); + let query_ctx = QueryContext::arc(); + let sql = "SELECT COUNT(*) AS files, SUM(file_size) AS bytes, COUNT(*) FILTER (WHERE file_size >= 1) AS nonempty, SUM(file_size) FILTER (WHERE file_size = 0) AS zero_bytes FROM information_schema.ssts_manifest WHERE region_id > 0 AND min_ts >= '1970-01-01T00:00:00.001Z'::TIMESTAMP_NS AND max_ts < '1970-01-01T00:00:00.003Z'::TIMESTAMP_NS"; + let statement = crate::parser::QueryLanguageParser::parse_sql(sql, &query_ctx).unwrap(); + let original = engine + .planner() + .plan(&statement, query_ctx.clone()) + .await + .unwrap(); + let state = engine.engine_state().session_state(); + // Uses the real catalog identity, parser, registered analyzer ordering and planner. + let rewritten = state + .analyzer() + .execute_and_check(original.clone(), state.config_options(), |_, _| {}) + .unwrap(); + assert!(has_remote(&rewritten), "{rewritten}"); + let physical = state.create_physical_plan(&rewritten).await.unwrap(); + let actual = datafusion::physical_plan::collect(physical, state.task_ctx()) + .await + .unwrap(); + let context = SessionContext::new(); + let expected = datafusion::dataframe::DataFrame::new( + context.state(), + replace_source(original, nodes.batches.clone()), + ) + .collect() + .await + .unwrap(); + assert_eq!(actual, expected); + assert_eq!(nodes.states.load(Ordering::SeqCst), nodes.batches.len()); +} + +#[tokio::test] +async fn test_manifest_aggregate_predicate_transport_fallbacks() { + for predicate in [ + "min_ts < arrow_cast('1970-01-01T04:00:00', 'Timestamp(Nanosecond, Some(\"+08:00\"))')", + "arrow_cast(1, 'Decimal32(9, 0)') > arrow_cast(0, 'Decimal32(9, 0)')", + ] { + for sql in [ + format!( + "SELECT COUNT(*) FILTER (WHERE {predicate}), SUM(file_size) FILTER (WHERE {predicate}) FROM ssts_manifest" + ), + format!("SELECT COUNT(*), SUM(file_size) FROM ssts_manifest WHERE {predicate}"), + ] { + let plan = analyzed(&sql, consts::INFORMATION_SCHEMA_SSTS_MANIFEST_TABLE_ID).await; + let rewritten = SstManifestAggregateRule + .analyze(plan.clone(), &ConfigOptions::default()) + .unwrap(); + assert_eq!(rewritten, plan, "{sql}"); + let context = SessionContext::new(); + let actual = datafusion::dataframe::DataFrame::new( + context.state(), + replace_source(rewritten, vec![batch(vec![2, 3])]), + ) + .collect() + .await + .unwrap(); + assert_eq!(actual.len(), 1, "{sql}"); + assert_eq!(actual[0].num_rows(), 1, "{sql}"); + assert_eq!( + actual[0].columns(), + &[ + Arc::new(arrow::array::Int64Array::from(vec![2])) as arrow::array::ArrayRef, + Arc::new(arrow::array::UInt64Array::from(vec![5])) as arrow::array::ArrayRef, + ], + "{sql}" + ); + } + } +} + +#[test] +fn test_manifest_aggregate_predicate_intermediate_types() { + use arrow_schema::TimeUnit; + use datafusion_expr::expr::{Cast, TryCast}; + + let schema = DFSchema::empty(); + for (data_type, supported) in [ + (DataType::Timestamp(TimeUnit::Nanosecond, None), true), + (DataType::Decimal128(20, 0), true), + ( + DataType::Timestamp(TimeUnit::Nanosecond, Some("+08:00".into())), + false, + ), + ( + DataType::Timestamp(TimeUnit::Nanosecond, Some("UTC".into())), + false, + ), + (DataType::Decimal32(9, 0), false), + (DataType::Decimal64(18, 0), false), + (DataType::Decimal256(39, 0), false), + ] { + let literal = Expr::Literal(ScalarValue::try_from(&data_type).unwrap(), None); + if !supported { + let cast = datafusion::functions::core::arrow_cast().call(vec![ + literal.clone(), + datafusion_expr::lit("Timestamp(Nanosecond, None)"), + ]); + assert!(!is_supported_predicate( + &Expr::IsNull(Box::new(cast)), + &schema + )); + } + let input = Box::new(Expr::Literal(ScalarValue::Utf8(Some("0".into())), None)); + for expr in [ + literal, + Expr::Cast(Cast::new(input.clone(), data_type.clone())), + Expr::TryCast(TryCast::new(input, data_type.clone())), + ] { + // The outer predicate returns Boolean even when its child cannot cross the wire. + let predicate = Expr::IsNull(Box::new(expr)); + assert_eq!( + is_supported_predicate(&predicate, &schema), + supported, + "{predicate:?}" + ); + } + } +} diff --git a/src/query/src/plan.rs b/src/query/src/plan.rs index 26635a9d990..d69cda86da9 100644 --- a/src/query/src/plan.rs +++ b/src/query/src/plan.rs @@ -12,18 +12,25 @@ // See the License for the specific language governing permissions and // limitations under the License. -use std::collections::HashSet; +use std::collections::{HashMap, HashSet}; +use std::sync::Arc; -use datafusion::datasource::DefaultTableSource; +use catalog::CatalogManagerRef; +use datafusion::datasource::{DefaultTableSource, provider_as_source}; use datafusion_common::TableReference; -use datafusion_common::tree_node::{Transformed, TreeNodeRewriter}; +use datafusion_common::tree_node::{Transformed, TreeNodeRecursion, TreeNodeRewriter}; +use datafusion_expr::logical_plan::TableScan; use datafusion_expr::{Expr, LogicalPlan}; -use session::context::QueryContextRef; +use session::context::{QueryContext, QueryContextRef}; +use snafu::ResultExt; +use table::TableRef; +use table::dist_table::DistTable; pub use table::metadata::TableType; +use table::table::PartitionRules; use table::table::adapter::DfTableProviderAdapter; use table::table_name::TableName; -use crate::error::Result; +use crate::error::{CatalogSnafu, Result}; struct TableNamesExtractAndRewriter { pub(crate) table_names: HashSet, @@ -40,13 +47,8 @@ impl TreeNodeRewriter for TableNamesExtractAndRewriter { ) -> datafusion::error::Result> { match node { LogicalPlan::TableScan(mut scan) => { - if let Some(source) = scan.source.downcast_ref::() - && let Some(provider) = source - .table_provider - .downcast_ref::() - && provider.table().table_type() == TableType::Base - { - let info = provider.table().table_info(); + if let Some(table) = scanned_base_table(&scan) { + let info = table.table_info(); self.table_names.insert(TableName::new( info.catalog_name.clone(), info.schema_name.clone(), @@ -119,6 +121,128 @@ pub fn extract_and_rewrite_full_table_names( Ok((extractor.table_names, plan.data)) } +/// Updates the scans in `plan` whose table changed its partition columns after the plan was built. +/// +/// Distributed planning reads the partition columns from the table a scan holds, and the regions +/// from the current route. A plan kept across executions, such as a prepared statement's, must +/// therefore report the current partition columns, or a query that needs merging on the frontend +/// runs entirely on each region. +/// +/// Returns `plan` as it is when no scanned table changed its partition columns. +pub async fn refresh_partition_columns( + plan: LogicalPlan, + catalog_manager: &CatalogManagerRef, + query_ctx: &QueryContext, +) -> Result { + let mut scanned = HashMap::new(); + plan.apply_with_subqueries(|node| { + if let LogicalPlan::TableScan(scan) = node + && let Some(table) = scanned_base_table(scan) + { + scanned.insert(table.table_info().table_id(), table); + } + Ok(TreeNodeRecursion::Continue) + })?; + + let mut refreshed = HashMap::new(); + for (table_id, table) in scanned { + // Looks up by id to follow a rename and to not bind a table that replaced the scanned one. + let Some(info) = catalog_manager + .table_info_by_id(table_id) + .await + .context(CatalogSnafu)? + else { + continue; + }; + let current = catalog_manager + .table( + &info.catalog_name, + &info.schema_name, + &info.name, + Some(query_ctx), + ) + .await + .context(CatalogSnafu)?; + let Some(current) = current.filter(|t| t.table_info().table_id() == table_id) else { + continue; + }; + if has_same_partition_columns(&table, ¤t) { + continue; + } + let table = if table.schema() == current.schema() { + current + } else { + with_unmapped_partition_columns(&table, ¤t) + }; + refreshed.insert(table_id, table); + } + if refreshed.is_empty() { + return Ok(plan); + } + + let plan = plan.transform_with_subqueries(|node| { + let LogicalPlan::TableScan(mut scan) = node else { + return Ok(Transformed::no(node)); + }; + let Some(table) = scanned_base_table(&scan) + .and_then(|table| refreshed.get(&table.table_info().table_id())) + else { + return Ok(Transformed::no(LogicalPlan::TableScan(scan))); + }; + scan.source = provider_as_source(Arc::new(DfTableProviderAdapter::new(table.clone()))); + Ok(Transformed::yes(LogicalPlan::TableScan(scan))) + })?; + Ok(plan.data) +} + +fn scanned_base_table(scan: &TableScan) -> Option { + let source = scan.source.downcast_ref::()?; + let provider = source + .table_provider + .downcast_ref::()?; + let table = provider.table(); + (table.table_type() == TableType::Base).then_some(table) +} + +fn has_same_partition_columns(left: &TableRef, right: &TableRef) -> bool { + left.table_info() + .meta + .partition_column_names() + .eq(right.table_info().meta.partition_column_names()) + && extra_partition_columns(left) == extra_partition_columns(right) +} + +fn extra_partition_columns(table: &TableRef) -> &[String] { + table + .partition_rules() + .map(|rules| rules.extra_phy_cols_not_in_logical_table.as_slice()) + .unwrap_or_default() +} + +/// Builds a table that keeps the schema of `table` and reports the partition columns of `current` +/// as absent from that schema. +/// +/// A scan's projection holds indices into the schema it was built on, and Substrait sends that +/// schema with those indices, so a plan cannot move to a changed schema. Reporting the columns as +/// absent keeps distributed planning from relying on any of them. +fn with_unmapped_partition_columns(table: &TableRef, current: &TableRef) -> TableRef { + let mut info = (*table.table_info()).clone(); + info.meta.partition_key_indices.clear(); + let current_info = current.table_info(); + let extra_phy_cols_not_in_logical_table = current_info + .meta + .partition_column_names() + .chain(extra_partition_columns(current)) + .cloned() + .collect(); + DistTable::table_partitioned( + Arc::new(info), + Some(PartitionRules { + extra_phy_cols_not_in_logical_table, + }), + ) +} + /// A trait to extract expressions from a logical plan. pub trait ExtractExpr { /// Gets expressions from a logical plan. @@ -139,13 +263,20 @@ pub(crate) mod tests { use std::sync::Arc; use arrow::datatypes::{DataType, Field, Schema, SchemaRef, TimeUnit}; - use common_catalog::consts::DEFAULT_CATALOG_NAME; + use catalog::RegisterTableRequest; + use catalog::memory::MemoryCatalogManager; + use common_catalog::consts::{DEFAULT_CATALOG_NAME, DEFAULT_SCHEMA_NAME}; use datafusion::logical_expr::builder::LogicalTableSource; use datafusion::logical_expr::{LogicalPlan, LogicalPlanBuilder, col, lit, scalar_subquery}; + use datatypes::prelude::ConcreteDataType; + use datatypes::schema::{ColumnSchema, Schema as TableSchema}; use session::context::QueryContextBuilder; + use table::test_util::table_info::test_table_info; use super::*; + const TABLE_ID: u32 = 1024; + fn mock_table_source() -> Arc { let schema = Schema::new(vec![ Field::new("id", DataType::Int32, true), @@ -307,4 +438,107 @@ pub(crate) mod tests { TableReference::full("qp031_external_catalog", "qp031_external_schema", "lookup"), ); } + + fn partitioned_table( + columns: &[&str], + partition_key_indices: Vec, + extras: &[&str], + ) -> TableRef { + let columns = columns + .iter() + .map(|name| ColumnSchema::new(*name, ConcreteDataType::string_datatype(), true)) + .collect(); + let mut info = test_table_info( + TABLE_ID, + "t", + DEFAULT_SCHEMA_NAME, + DEFAULT_CATALOG_NAME, + Arc::new(TableSchema::new(columns)), + ); + info.meta.partition_key_indices = partition_key_indices; + let rules = PartitionRules { + extra_phy_cols_not_in_logical_table: extras.iter().map(ToString::to_string).collect(), + }; + DistTable::table_partitioned(Arc::new(info), Some(rules)) + } + + /// Returns the plan that [refresh_partition_columns] builds for a scan of `captured` when + /// the catalog holds `current`. + async fn refresh_scan(captured: TableRef, current: TableRef) -> (TableScan, TableScan) { + let source = provider_as_source(Arc::new(DfTableProviderAdapter::new(captured))); + let filters = vec![col("a").gt(lit("x"))]; + let plan = LogicalPlanBuilder::scan_with_filters_fetch( + "t", + source, + Some(vec![1]), + filters, + Some(5), + ) + .unwrap() + .build() + .unwrap(); + let catalog_manager = MemoryCatalogManager::with_default_setup(); + catalog_manager + .register_table_sync(RegisterTableRequest { + catalog: DEFAULT_CATALOG_NAME.to_string(), + schema: DEFAULT_SCHEMA_NAME.to_string(), + table_name: "t".to_string(), + table_id: TABLE_ID, + table: current, + }) + .unwrap(); + let catalog_manager: CatalogManagerRef = catalog_manager; + let refreshed = + refresh_partition_columns(plan.clone(), &catalog_manager, &QueryContext::arc()) + .await + .unwrap(); + let (LogicalPlan::TableScan(original), LogicalPlan::TableScan(refreshed)) = + (plan, refreshed) + else { + panic!("expected table scans"); + }; + (original, refreshed) + } + + #[tokio::test] + async fn test_refresh_partition_columns_compares_names() { + let captured = partitioned_table(&["a", "b"], vec![1], &[]); + let current = partitioned_table(&["b", "a", "c"], vec![0], &[]); + + let (original, refreshed) = refresh_scan(captured, current).await; + + assert!(Arc::ptr_eq(&original.source, &refreshed.source)); + } + + #[tokio::test] + async fn test_refresh_partition_columns_with_equal_schema() { + let captured = partitioned_table(&["a", "b"], vec![], &[]); + let current = partitioned_table(&["a", "b"], vec![1], &[]); + + let (original, refreshed) = refresh_scan(captured, current.clone()).await; + + let table = scanned_base_table(&refreshed).unwrap(); + assert!(Arc::ptr_eq(&table, ¤t)); + assert_eq!(original.projection, refreshed.projection); + assert_eq!(original.projected_schema, refreshed.projected_schema); + assert_eq!(original.filters, refreshed.filters); + assert_eq!(original.fetch, refreshed.fetch); + } + + #[tokio::test] + async fn test_refresh_partition_columns_with_changed_schema() { + let captured = partitioned_table(&["a", "b"], vec![1], &[]); + let current = partitioned_table(&["a", "b", "c"], vec![2], &["d"]); + + let (original, refreshed) = refresh_scan(captured.clone(), current).await; + + let table = scanned_base_table(&refreshed).unwrap(); + assert_eq!(table.schema(), captured.schema()); + assert!(table.table_info().meta.partition_key_indices.is_empty()); + assert_eq!(extra_partition_columns(&table), ["c", "d"]); + assert_eq!(original.projection, refreshed.projection); + assert_eq!(original.projected_schema, refreshed.projected_schema); + assert_eq!(original.filters, refreshed.filters); + assert_eq!(original.fetch, refreshed.fetch); + } } diff --git a/src/query/src/promql/label_values.rs b/src/query/src/promql/label_values.rs index cae53c64853..4b73340164d 100644 --- a/src/query/src/promql/label_values.rs +++ b/src/query/src/promql/label_values.rs @@ -41,7 +41,7 @@ fn millis_since_epoch(time: SystemTime) -> Result { /// /// Sub-millisecond parts round down, also before the epoch, like Prometheus' /// `timestamp.FromTime`. -pub(crate) fn signed_millis_since_epoch(time: SystemTime) -> Result { +pub fn signed_millis_since_epoch(time: SystemTime) -> Result { let (millis, before_epoch) = match time.duration_since(UNIX_EPOCH) { Ok(duration) => (duration.as_millis(), false), Err(earlier) => (earlier.duration().as_nanos().div_ceil(1_000_000), true), diff --git a/src/query/src/promql/planner.rs b/src/query/src/promql/planner.rs index 6cb0d671196..dcb4e8fe4e4 100644 --- a/src/query/src/promql/planner.rs +++ b/src/query/src/promql/planner.rs @@ -3021,6 +3021,14 @@ impl PromPlanner { let (_, upper) = bounds(end); return Ok(filter(lower, upper)); } + // Overlapping or touching windows form one continuous range. Use the last + // evaluation point, since the requested end need not lie on the step grid. + if window >= self.ctx.interval { + let (lower, _) = bounds(start); + let last = i128::from(start) + num_points * i128::from(self.ctx.interval); + let upper = last - i128::from(offset_duration); + return Ok(filter(lower, upper)); + } let mut filters = Vec::new(); for timestamp in (start..=end).step_by(self.ctx.interval as usize) { let (lower, upper) = bounds(timestamp); @@ -3031,7 +3039,20 @@ impl PromPlanner { }; filters.push(filter); } - Ok(filters.into_iter().reduce(DfExpr::or)) + // Pair adjacent windows to keep generated expression depth logarithmic. + // A left fold can exceed the expression-depth guard for ordinary queries. + while filters.len() > 1 { + let mut next = Vec::with_capacity(filters.len().div_ceil(2)); + let mut iter = filters.into_iter(); + while let Some(left) = iter.next() { + next.push(match iter.next() { + Some(right) => left.or(right), + None => left, + }); + } + filters = next; + } + Ok(filters.pop()) } /// Create a table scan plan and a filter plan with given filter. diff --git a/src/query/src/promql/planner/test.rs b/src/query/src/promql/planner/test.rs index be3140a6a52..7588390dc9e 100644 --- a/src/query/src/promql/planner/test.rs +++ b/src/query/src/promql/planner/test.rs @@ -6414,6 +6414,29 @@ async fn only_equals_is_supported_for_special_matcher() { } } +#[tokio::test] +async fn scatter_time_filter_many_evaluation_points() { + for function in ["increase", "sum_over_time"] { + for window in ["1h", "2h", "3h"] { + let query = format!("sum({function}(some_metric[{window}]))"); + let eval_stmt = EvalStmt { + expr: parser::parse(&query).unwrap(), + start: UNIX_EPOCH, + end: UNIX_EPOCH + Duration::from_secs(30 * 24 * 3600 + 1800), + interval: Duration::from_secs(2 * 3600), + lookback_delta: Duration::from_secs(300), + }; + let provider = build_test_table_provider( + &[(DEFAULT_SCHEMA_NAME.to_string(), "some_metric".to_string())], + 1, + 1, + ) + .await; + build_optimized_promql_plan(provider, &eval_stmt).await; + } + } +} + #[tokio::test] async fn native_scan_bounds_preserve_zero_lookback_and_overflow() { let table_provider = build_test_table_provider( diff --git a/src/query/src/query_engine/state.rs b/src/query/src/query_engine/state.rs index 9598656b1c9..62a8e73d1eb 100644 --- a/src/query/src/query_engine/state.rs +++ b/src/query/src/query_engine/state.rs @@ -19,6 +19,7 @@ use std::sync::{Arc, RwLock}; use async_trait::async_trait; use catalog::CatalogManagerRef; +use catalog::information_schema::InformationExtensionRef; use common_base::Plugins; use common_function::aggrs::aggr_wrapper::fix_order::FixStateUdafOrderingAnalyzer; use common_function::function_factory::ScalarFunctionFactory; @@ -73,10 +74,14 @@ use crate::optimizer::global_limit::EnsureGlobalLimitForFetch; use crate::optimizer::infer_aggregate_input_bounds::InferAggregateInputBoundsRule; use crate::optimizer::json_schema_concretize::JsonSchemaConcretizeRule; use crate::optimizer::json_type_concretize::JsonTypeConcretizeRule; +use crate::optimizer::merge_scan_projection::MergeScanProjection; use crate::optimizer::parallelize_scan::ParallelizeScan; use crate::optimizer::promql_tsid_narrow_join::PromqlTsidNarrowJoin; use crate::optimizer::remove_duplicate::RemoveDuplicate; use crate::optimizer::scan_hint::ScanHintRule; +use crate::optimizer::sst_manifest_aggregate::{ + SstManifestAggregatePlanner, SstManifestAggregateRule, +}; use crate::optimizer::string_normalization::StringNormalizationRule; use crate::optimizer::transcribe_atat::TranscribeAtatRule; use crate::optimizer::type_conversion::TypeConversionRule; @@ -215,6 +220,9 @@ impl QueryEngineState { FUNCTION_REGISTRY.function_rewrites(), )), ); + if inspect_query_extension(&catalog_list).is_some() { + analyzer.rules.push(Arc::new(SstManifestAggregateRule)); + } if with_dist_planner { analyzer.rules.push(Arc::new(DistPlannerAnalyzer)); analyzer.rules.push(Arc::new(JsonSchemaConcretizeRule)); @@ -244,6 +252,9 @@ impl QueryEngineState { filter_pushdown_index, Arc::new(InferAggregateInputBoundsRule), ); + if with_dist_planner { + optimizer.rules.push(Arc::new(MergeScanProjection)); + } optimizer.rules.push(Arc::new(ScanHintRule)); optimizer.rules.push(Arc::new(JsonTypeConcretizeRule)); @@ -666,6 +677,14 @@ fn register_pg_catalog_compat(ctx: &SessionContext) { ); } +fn inspect_query_extension(catalog_manager: &CatalogManagerRef) -> Option { + catalog_manager + .as_any() + .downcast_ref::() + .map(|catalog| catalog.information_extension()) + .filter(|extension| extension.supports_inspect_query_plan()) +} + impl DfQueryPlanner { fn new( catalog_manager: CatalogManagerRef, @@ -678,6 +697,9 @@ impl DfQueryPlanner { Arc::new(RangeSelectPlanner), Arc::new(RemoteDynFilterReceiverExtensionPlanner), ]; + if let Some(extension) = inspect_query_extension(&catalog_manager) { + planners.push(Arc::new(SstManifestAggregatePlanner::new(extension))); + } if let (Some(region_query_handler), Some(partition_rule_manager)) = (region_query_handler, partition_rule_manager) { diff --git a/src/servers/AGENTS.md b/src/servers/AGENTS.md index 9556c1a9909..7bbdcf21861 100644 --- a/src/servers/AGENTS.md +++ b/src/servers/AGENTS.md @@ -16,6 +16,7 @@ provided through handler traits, mostly implemented by `frontend`. | HTTP | `src/servers/src/http.rs`, `src/servers/src/http/` | Routes, middleware, protocol endpoints, output formats | | SQL protocols | `src/servers/src/mysql.rs`, `src/servers/src/mysql/`, `src/servers/src/postgres.rs`, `src/servers/src/postgres/` | MySQL/PostgreSQL servers and type conversion | | Observability protocols | `src/servers/src/prom_remote_write/`, `src/servers/src/prometheus.rs`, `src/servers/src/otlp/`, `src/servers/src/otel_arrow.rs` | Prometheus and OpenTelemetry conversion | +| Exemplars | `src/servers/src/exemplar/`, `src/servers/src/exemplar.rs`, `src/servers/src/http/prom_store/exemplar.rs` | Shared row contract, millisecond query API, completion-aware metric/exemplar writes | | Resources / TLS | `src/servers/src/request_memory_limiter.rs`, `src/servers/src/tls.rs`, `src/servers/src/addrs.rs` | Memory admission, TLS, listener addresses | ## Change coupling diff --git a/src/servers/Cargo.toml b/src/servers/Cargo.toml index 4383896e1f8..684697687ec 100644 --- a/src/servers/Cargo.toml +++ b/src/servers/Cargo.toml @@ -98,7 +98,7 @@ otel-arrow-rust.workspace = true parking_lot.workspace = true partition.workspace = true pg_interval = "0.6" -pgwire = { version = "0.42.1", default-features = false, features = [ +pgwire = { version = "0.42.2", default-features = false, features = [ "server-api-aws-lc-rs", "pg-ext-types", ] } diff --git a/src/servers/dashboard/VERSION b/src/servers/dashboard/VERSION index b0d2e474f72..574be600071 100644 --- a/src/servers/dashboard/VERSION +++ b/src/servers/dashboard/VERSION @@ -1 +1 @@ -v0.14.2 +v0.14.5 diff --git a/src/servers/src/exemplar.rs b/src/servers/src/exemplar.rs index cd20b796739..986c7212181 100644 --- a/src/servers/src/exemplar.rs +++ b/src/servers/src/exemplar.rs @@ -14,6 +14,8 @@ //! Normalized metric exemplars shared by Remote Write and OTLP conversion. +pub mod query; + use std::collections::{BTreeMap, BTreeSet}; use std::sync::Arc; diff --git a/src/servers/src/exemplar/query.rs b/src/servers/src/exemplar/query.rs new file mode 100644 index 00000000000..64cf609bd9d --- /dev/null +++ b/src/servers/src/exemplar/query.rs @@ -0,0 +1,289 @@ +// 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. + +//! Prometheus exemplar selectors and millisecond API timestamps. + +use std::collections::BTreeMap; + +use promql_parser::label::{METRIC_NAME, MatchOp, Matcher}; +use promql_parser::parser::{Expr, VectorSelector}; +use promql_parser::util::{ExprVisitor, walk_expr}; +use query::parser::QueryLanguageParser; +use query::promql::label_values::signed_millis_since_epoch; +use serde::{Deserialize, Serialize}; +use snafu::OptionExt; + +use crate::error::{InvalidQuerySnafu, Result}; +use crate::prom_store::{FIELD_NAME_LABEL, is_database_selection_label}; +use crate::prometheus_handler::resolve_schema_from_matchers; + +#[derive(Debug, Clone)] +pub struct Selector { + pub schema: String, + pub matchers: Vec, +} + +#[derive(Debug)] +pub struct Query { + pub expression: String, + pub selectors: Vec, + /// Inclusive nanosecond scan bounds covering the requested milliseconds. + pub bounds: (i64, i64), +} + +impl Query { + pub fn parse(expression: String, start: &str, end: &str, schema: &str) -> Result { + let parse = |input| { + let time = QueryLanguageParser::parse_promql_timestamp(input).map_err(|error| { + InvalidQuerySnafu { + reason: error.to_string(), + } + .build() + })?; + let millis = signed_millis_since_epoch(time).map_err(|error| { + InvalidQuerySnafu { + reason: error.to_string(), + } + .build() + })?; + millis.checked_mul(1_000_000).context(InvalidQuerySnafu { + reason: "timestamp exceeds signed nanosecond range", + }) + }; + let start = parse(start)?; + let end = parse(end)?; + if start > end { + return invalid("start must not exceed end"); + } + let expr = promql_parser::parser::parse(&expression) + .map_err(|reason| InvalidQuerySnafu { reason }.build())?; + struct Collector<'a> { + schema: &'a str, + selectors: Vec, + } + impl ExprVisitor for Collector<'_> { + type Error = crate::error::Error; + fn pre_visit(&mut self, expr: &Expr) -> Result { + let selector = match expr { + Expr::VectorSelector(vs) => vs, + Expr::MatrixSelector(ms) => &ms.vs, + Expr::Aggregate(aggregate) => { + // promql-parser 0.10's walker omits aggregation parameters. + if let Some(param) = &aggregate.param { + walk_expr(self, param)?; + } + return Ok(true); + } + _ => return Ok(true), + }; + self.selectors.extend(resolve(selector, self.schema)?); + Ok(true) + } + } + let mut collector = Collector { + schema, + selectors: Vec::new(), + }; + walk_expr(&mut collector, &expr)?; + Ok(Self { + expression, + selectors: collector.selectors, + // Include the whole final millisecond without casting the scanned column. + bounds: (start, end.saturating_add(999_999)), + }) + } +} + +fn resolve(selector: &VectorSelector, default_schema: &str) -> Result> { + let branches = if selector.matchers.or_matchers.is_empty() { + vec![&selector.matchers.matchers] + } else { + selector.matchers.or_matchers.iter().collect() + }; + branches + .into_iter() + .map(|branch| { + if branch + .iter() + .any(|matcher| matcher.name == FIELD_NAME_LABEL) + { + return invalid("__field__ is not supported in exemplar queries"); + } + let schema = + resolve_schema_from_matchers(branch)?.unwrap_or_else(|| default_schema.to_string()); + let mut matchers = branch + .iter() + .filter(|matcher| !is_database_selection_label(&matcher.name)) + .cloned() + .collect::>(); + if let Some(name) = &selector.name { + matchers.push(Matcher::new(MatchOp::Equal, METRIC_NAME, name)); + } + Ok(Selector { schema, matchers }) + }) + .collect() +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct Series { + #[serde(rename = "seriesLabels")] + pub series_labels: BTreeMap, + pub exemplars: Vec, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct Observation { + pub labels: BTreeMap, + pub value: String, + /// Unix seconds at millisecond precision. + pub timestamp: f64, +} + +fn invalid(reason: &str) -> Result { + InvalidQuerySnafu { reason }.fail() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn query_bounds_use_prometheus_milliseconds() { + for (input, millis) in [ + ("1.234567891", 1235), + ("1.234e0", 1234), + ("1720000000.123456789", 1720000000123), + ("-0.0006", -1), + ("-0.0004", 0), + ("-1.0005", -1000), + ("1970-01-01T00:00:00.0019Z", 1), + ("1969-12-31T23:59:59.999999999Z", -1), + ("1970-01-01T01:00:00.0019+01:00", 1), + ] { + assert_eq!( + Query::parse("up".into(), input, input, "public") + .unwrap() + .bounds, + (millis * 1_000_000, millis * 1_000_000 + 999_999), + "{input}", + ); + } + assert_eq!( + Query::parse("up".into(), "0.0012", "0.0011", "public") + .unwrap() + .bounds, + (1_000_000, 1_999_999), + ); + assert_eq!( + Query::parse( + "up".into(), + "2262-04-11T23:47:16.854Z", + "2262-04-11T23:47:16.854Z", + "public" + ) + .unwrap() + .bounds, + (9_223_372_036_854_000_000, i64::MAX), + ); + assert!(Query::parse("up".into(), "0.002", "0.001", "public").is_err()); + for input in [ + "NaN", + "inf", + "", + "1e100", + "9223372036.855", + "-9223372036.855", + ] { + assert!( + Query::parse("up".into(), input, input, "public").is_err(), + "{input}" + ); + } + assert!( + Query::parse("1".into(), "0", "1", "public") + .unwrap() + .selectors + .is_empty() + ); + } + + #[test] + fn aggregation_parameter_selectors() { + for (expression, expected) in [ + ( + "topk(scalar(limit_metric), requests)", + vec!["limit_metric", "requests"], + ), + ( + "bottomk(scalar(limit_metric), requests)", + vec!["limit_metric", "requests"], + ), + ( + "quantile(scalar(limit_metric), requests)", + vec!["limit_metric", "requests"], + ), + ( + "topk(scalar(topk(scalar(inner_limit), limit_metric)), requests)", + vec!["inner_limit", "limit_metric", "requests"], + ), + ("topk(2, requests)", vec!["requests"]), + ("count_values(\"kind\", requests)", vec!["requests"]), + ( + "topk(scalar(requests), requests)", + vec!["requests", "requests"], + ), + ] { + let query = Query::parse(expression.into(), "0", "1", "public").unwrap(); + let mut names = query + .selectors + .iter() + .flat_map(|selector| &selector.matchers) + .filter(|matcher| matcher.name == METRIC_NAME) + .map(|matcher| matcher.value.as_str()) + .collect::>(); + names.sort_unstable(); + assert_eq!(names, expected, "{expression}"); + } + } + + #[test] + fn range_vectors_and_routing_controls() { + let query = Query::parse( + "topk(scalar(sum(rate(requests{__schema__=\"a\"}[5m]))), errors{__database__=\"b\"})" + .into(), + "0", + "1", + "public", + ) + .unwrap(); + assert_eq!( + query + .selectors + .iter() + .map(|s| s.schema.as_str()) + .collect::>(), + ["a", "b"] + ); + for query in [ + "up{__schema__=\"\"}", + "up{__schema__!=\"a\"}", + "up{__field__=\"x\"}", + "topk(scalar(up{__schema__=\"\"}), requests)", + "topk(scalar(up{__schema__!=\"a\"}), requests)", + "topk(scalar(up{__field__=\"x\"}), requests)", + ] { + assert!(Query::parse(query.into(), "0", "1", "public").is_err()); + } + } +} diff --git a/src/servers/src/grpc/greptime_handler.rs b/src/servers/src/grpc/greptime_handler.rs index 81dd4d9adf2..c103e38e231 100644 --- a/src/servers/src/grpc/greptime_handler.rs +++ b/src/servers/src/grpc/greptime_handler.rs @@ -22,7 +22,8 @@ use std::time::Instant; use api::helper::request_type; use api::v1::greptime_request::Request as QueryRequest; -use api::v1::{GreptimeRequest, RequestHeader}; +use api::v1::query_request::Query; +use api::v1::{GreptimeRequest, QueryRequest as ApiQueryRequest, RequestHeader}; use auth::UserProviderRef; use common_catalog::consts::{DEFAULT_CATALOG_NAME, DEFAULT_SCHEMA_NAME}; use common_catalog::parse_catalog_and_schema_from_db_string; @@ -42,6 +43,7 @@ use session::hints::{INSERT_SKIP_WAL_HINT, READ_PREFERENCE_HINT, is_reserved_ext use snafu::{OptionExt, ResultExt}; use tokio::sync::mpsc; use tokio::sync::mpsc::error::TrySendError; +use tokio_util::task::AbortOnDropHandle; use tonic::Status; use crate::error::{InvalidQuerySnafu, JoinTaskSnafu, Result, UnknownHintSnafu}; @@ -108,6 +110,13 @@ impl GreptimeRequestHandler { ) -> impl Future> + Send + 'static { let handler = self.handler.clone(); let runtime = self.runtime.clone(); + // SQL can contain writes or DDL; only explicit read-query variants are cancellable. + let cancel_on_drop = matches!( + &query, + QueryRequest::Query(ApiQueryRequest { + query: Some(Query::LogicalPlan(_) | Query::PromRangeQuery(_)), + }) + ); let request_type = request_type(&query).to_string(); let db = query_ctx.get_db_string(); let timer = RequestTimer::new(db.clone(), request_type); @@ -135,20 +144,17 @@ impl GreptimeRequestHandler { match runtime { Some(runtime) => { - // Executes requests in another runtime to - // 1. prevent the execution from being cancelled unexpected by Tonic runtime; - // - Refer to our blog for the rational behind it: - // https://www.greptime.com/blogs/2023-01-12-hidden-control-flow.html - // - Obtaining a `JoinHandle` to get the panic message (if there's any). - // From its docs, `JoinHandle` is cancel safe. The task keeps running even it's handle been dropped. - // 2. avoid the handler blocks the gRPC runtime incidentally. - runtime - .spawn(result_future) - .await - .context(JoinTaskSnafu) - .inspect_err(|e| { - timer.record(e.status_code()); - })? + let task = runtime.spawn(result_future); + let result = if cancel_on_drop { + AbortOnDropHandle::new(task).await + } else { + // Writes must outlive the RPC to avoid cancellation between state updates. + // https://www.greptime.com/blogs/2023-01-12-hidden-control-flow.html + task.await + }; + result.context(JoinTaskSnafu).inspect_err(|e| { + timer.record(e.status_code()); + })? } None => result_future.await, } @@ -317,20 +323,150 @@ impl Drop for RequestTimer { #[cfg(test)] mod tests { + use std::error::Error as StdError; + use std::result::Result as StdResult; + use std::time::Duration; + + use async_trait::async_trait; use chrono::FixedOffset; use common_error::ext::BoxedError; use common_error::{GREPTIME_DB_HEADER_ERROR_CODE, GREPTIME_DB_HEADER_ERROR_RETRY_HINT}; use common_time::Timezone; + use futures::stream::{self, BoxStream}; use query::options::FLOW_SCHEDULED_TIME_MILLIS; + use session::context::QueryContext; use session::hints::{ INITIAL_REMOTE_DYN_FILTER_REGISTRATIONS_EXTENSION_KEY, READ_PREFERENCE_EXTENSION_KEY, REMOTE_QUERY_ID_EXTENSION_KEY, }; use snafu::ResultExt; + use tokio::sync::Notify; + use tokio::time::timeout; use tonic::Code; use super::*; use crate::error::{ExecuteGrpcRequestSnafu, InvalidParameterSnafu}; + use crate::query_handler::grpc::GrpcQueryHandler; + + struct BlockingQueryHandler { + started: Arc, + finished: Arc, + resume: Arc, + completed: Arc, + } + + struct QueryFinished(Arc); + + impl Drop for QueryFinished { + fn drop(&mut self) { + self.0.notify_one(); + } + } + + #[async_trait] + impl GrpcQueryHandler for BlockingQueryHandler { + async fn do_query(&self, _: QueryRequest, _: QueryContextRef) -> Result { + let _finished = QueryFinished(self.finished.clone()); + self.started.notify_one(); + self.resume.notified().await; + self.completed.notify_one(); + Ok(Output::new_with_affected_rows(1)) + } + + fn handle_put_record_batch_stream( + &self, + _: PutRecordBatchRequestStream, + _: QueryContextRef, + ) -> BoxStream<'static, Result> { + Box::pin(stream::empty()) + } + } + + async fn check_request_cancellation( + request: QueryRequest, + runtime: Option, + cancels: bool, + ) -> StdResult<(), Box> { + let started = Arc::new(Notify::new()); + let finished = Arc::new(Notify::new()); + let resume = Arc::new(Notify::new()); + let completed = Arc::new(Notify::new()); + let handler = GreptimeRequestHandler::new( + Arc::new(BlockingQueryHandler { + started: started.clone(), + finished: finished.clone(), + resume: resume.clone(), + completed: completed.clone(), + }), + None, + runtime, + FlightCompression::default(), + ); + let task = AbortOnDropHandle::new(tokio::spawn( + handler.handle_request_with_query_ctx(request, QueryContext::arc()), + )); + timeout(Duration::from_secs(5), started.notified()).await?; + task.abort(); + assert!(task.await.is_err_and(|error| error.is_cancelled())); + if !cancels { + // Resuming after the caller is gone proves execution can still finish normally. + resume.notify_one(); + timeout(Duration::from_secs(5), completed.notified()).await?; + } + timeout(Duration::from_secs(5), finished.notified()).await?; + Ok(()) + } + + #[tokio::test] + async fn test_drop_read_request_cancels_execution() + -> StdResult<(), Box> { + // Payloads are opaque here; cancellation is tested before do_query returns Output. + for query in [ + Query::LogicalPlan(Vec::new()), + Query::PromRangeQuery(Default::default()), + ] { + let request = QueryRequest::Query(ApiQueryRequest { query: Some(query) }); + for runtime in [None, Some(common_runtime::query_runtime())] { + check_request_cancellation(request.clone(), runtime, true).await?; + } + } + Ok(()) + } + + #[tokio::test] + async fn test_drop_other_request_preserves_spawned_execution() + -> StdResult<(), Box> { + let requests = [ + QueryRequest::Inserts(Default::default()), + QueryRequest::RowInserts(Default::default()), + QueryRequest::Deletes(Default::default()), + QueryRequest::RowDeletes(Default::default()), + QueryRequest::Ddl(Default::default()), + QueryRequest::Query(ApiQueryRequest { + query: Some(Query::InsertIntoPlan(Default::default())), + }), + QueryRequest::Query(ApiQueryRequest { query: None }), + QueryRequest::Query(ApiQueryRequest { + query: Some(Query::Sql("SELECT * FROM numbers".into())), + }), + QueryRequest::Query(ApiQueryRequest { + query: Some(Query::Sql("INSERT INTO t VALUES (1)".into())), + }), + QueryRequest::Query(ApiQueryRequest { + query: Some(Query::Sql( + "CREATE TABLE t (ts TIMESTAMP TIME INDEX)".into(), + )), + }), + ]; + for request in requests { + for runtime in [None, Some(common_runtime::query_runtime())] { + // Without a separate runtime, preserve the existing inline cancellation behavior. + let cancels = runtime.is_none(); + check_request_cancellation(request.clone(), runtime, cancels).await?; + } + } + Ok(()) + } #[test] fn test_create_query_context_typed_skip_wal() { diff --git a/src/servers/src/grpc/region_server.rs b/src/servers/src/grpc/region_server.rs index aa2bdf3a74b..d18dbe9f9d5 100644 --- a/src/servers/src/grpc/region_server.rs +++ b/src/servers/src/grpc/region_server.rs @@ -117,3 +117,110 @@ impl RegionServer for RegionServerRequestHandler { cancellation::with_cancellation_handler(request_future, cancellation_future).await } } + +#[cfg(test)] +mod tests { + use std::sync::Mutex; + use std::time::Duration; + + use api::v1::region::region_client::RegionClient; + use api::v1::region::region_server::RegionServer as RegionService; + use api::v1::region::{CancelCompactionRequest, RegionRequestHeader}; + use api::v1::{ResponseHeader, Status as ResponseStatus}; + use common_error::status_code::StatusCode; + use tokio::net::TcpListener; + use tokio_stream::wrappers::TcpListenerStream; + + use super::*; + + #[derive(Default)] + struct RecordingHandler { + requests: Mutex>, + } + + #[async_trait] + impl RegionServerHandler for RecordingHandler { + async fn handle(&self, request: region_request::Body) -> Result { + self.requests.lock().unwrap().push(request); + Ok(RegionResponse { + header: Some(ResponseHeader { + status: Some(ResponseStatus { + status_code: StatusCode::Success as u32, + ..Default::default() + }), + }), + affected_rows: 1, + ..Default::default() + }) + } + } + + #[tokio::test] + async fn test_cancel_compaction_forwards_through_region_handler() { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + let handler = Arc::new(RecordingHandler::default()); + let bridge = + RegionServerRequestHandler::new(handler.clone(), common_runtime::global_runtime()); + let (shutdown, stopped) = tokio::sync::oneshot::channel(); + let server = tokio::spawn(async move { + tonic::transport::Server::builder() + .add_service(RegionService::new(bridge)) + .serve_with_incoming_shutdown(TcpListenerStream::new(listener), async { + let _ = stopped.await; + }) + .await + .unwrap(); + }); + tokio::time::timeout(Duration::from_secs(10), async { + let mut client = RegionClient::connect(format!("http://{addr}")) + .await + .unwrap(); + let error = client + .handle(RegionRequest { + header: None, + body: Some(region_request::Body::CancelCompaction( + CancelCompactionRequest { + region_id: 42, + task_id: "cycle-id".into(), + }, + )), + }) + .await + .unwrap_err(); + assert_eq!(error.code(), tonic::Code::InvalidArgument); + assert!(handler.requests.lock().unwrap().is_empty()); + + let request = RegionRequest { + header: Some(RegionRequestHeader { + dbname: "greptime-public".into(), + tracing_context: TracingContext::from_current_span().to_w3c(), + ..Default::default() + }), + body: Some(region_request::Body::CancelCompaction( + CancelCompactionRequest { + region_id: 42, + task_id: "cycle-id".into(), + }, + )), + }; + let response = client.handle(request.clone()).await.unwrap().into_inner(); + assert_eq!(response.affected_rows, 1); + assert_eq!( + response.header.unwrap().status.unwrap().status_code, + StatusCode::Success as u32 + ); + assert_eq!( + *handler.requests.lock().unwrap(), + vec![request.body.unwrap()] + ); + }) + .await + .expect("cancellation RPC did not complete"); + shutdown.send(()).unwrap(); + tokio::time::timeout(Duration::from_secs(10), server) + .await + .unwrap() + .unwrap(); + } +} diff --git a/src/servers/src/http.rs b/src/servers/src/http.rs index 01b13e72087..13be8b03b2a 100644 --- a/src/servers/src/http.rs +++ b/src/servers/src/http.rs @@ -64,7 +64,7 @@ use crate::http::otlp::OtlpState; use crate::http::prom_store::PromStoreState; use crate::http::prometheus::{ build_info_query, format_query, instant_query, label_values_query, labels_query, - metadata_query, parse_query, range_query, series_query, + metadata_query, parse_query, query_exemplars, range_query, series_query, }; use crate::http::result::arrow_result::ArrowResponse; use crate::http::result::csv_result::CsvResponse; @@ -1458,6 +1458,10 @@ impl HttpServer { .route("/status/buildinfo", routing::get(build_info_query)) .route("/query", routing::post(instant_query).get(instant_query)) .route("/query_range", routing::post(range_query).get(range_query)) + .route( + "/query_exemplars", + routing::post(query_exemplars).get(query_exemplars), + ) .route("/labels", routing::post(labels_query).get(labels_query)) .route("/metadata", routing::get(metadata_query)) .route("/series", routing::post(series_query).get(series_query)) diff --git a/src/servers/src/http/event.rs b/src/servers/src/http/event.rs index 651621dcdea..2470080c1b4 100644 --- a/src/servers/src/http/event.rs +++ b/src/servers/src/http/event.rs @@ -12,6 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. +use std::borrow::Cow; use std::collections::BTreeMap; use std::fmt::Display; use std::io::BufRead; @@ -67,7 +68,7 @@ use crate::http::result::greptime_result_v1::GreptimedbV1Response; use crate::interceptor::{LogIngestInterceptor, LogIngestInterceptorRef}; use crate::metrics::{ METRIC_FAILURE_VALUE, METRIC_HTTP_LOGS_INGESTION_COUNTER, METRIC_HTTP_LOGS_INGESTION_ELAPSED, - METRIC_SUCCESS_VALUE, + METRIC_HTTP_LOGS_UTF8_RETRIES_TOTAL, METRIC_SUCCESS_VALUE, }; use crate::pipeline::run_pipeline; use crate::query_handler::PipelineHandlerRef; @@ -103,7 +104,8 @@ pub struct LogIngesterQueryParams { pub pipeline_name: Option, /// The version of the pipeline to be used for log ingestion. pub version: Option, - /// Whether to ignore errors during log ingestion. + /// Whether to ignore payload parsing and custom timestamp errors during log ingestion. + /// Defaults to the server's `pipeline.ignore_errors` setting when omitted. pub ignore_errors: Option, /// The source of the log data. pub source: Option, @@ -122,7 +124,7 @@ pub struct LogIngesterQueryParams { /// Whether to skip errors during log ingestion. /// If set to true, the ingestion will continue even if there are errors in the data. /// If set to false, the ingestion will stop at the first error. - /// This is different from `ignore_errors`, which is used to ignore errors during the pipeline execution. + /// This controls pipeline execution errors, separately from `ignore_errors`. /// The priority of query params is lower than that headers of x-greptime-pipeline-params. pub skip_error: Option, } @@ -591,9 +593,13 @@ fn add_step_info_for_pipeline_dryrun_error(step_msg: &str, e: Error) -> Response /// Parse the data with given content type /// If the content type is invalid, return error /// content type is one of application/json, text/plain, application/x-ndjson -fn parse_dryrun_data(data_type: String, data: String) -> Result> { +fn parse_dryrun_data( + data_type: String, + data: String, + ignore_errors: bool, +) -> Result> { if let Ok(content_type) = ContentType::from_str(&data_type) { - extract_pipeline_value_by_content_type(content_type, Bytes::from(data), false) + extract_pipeline_value_by_content_type(content_type, Bytes::from(data), ignore_errors) } else { InvalidParameterSnafu { reason: format!( @@ -620,11 +626,16 @@ pub async fn pipeline_dryrun( let query_ctx = Arc::new(query_ctx); handler.check_pipeline_query_permission(&query_ctx)?; + let ignore_errors = query_params + .ignore_errors + .unwrap_or(handler.pipeline_options().ignore_errors); + match check_pipeline_dryrun_params_valid(&payload) { Some(params) => { let data = parse_dryrun_data( params.data_type.unwrap_or("application/json".to_string()), params.data, + ignore_errors, )?; check_data_valid(data.len())?; @@ -675,8 +686,6 @@ pub async fn pipeline_dryrun( let version = to_pipeline_version(query_params.version.as_deref()).context(PipelineSnafu)?; - let ignore_errors = query_params.ignore_errors.unwrap_or(false); - let value = extract_pipeline_value_by_content_type(content_type, payload, ignore_errors)?; @@ -749,7 +758,9 @@ pub async fn log_ingester( reason: "table is required", })?; - let ignore_errors = query_params.ignore_errors.unwrap_or(false); + let ignore_errors = query_params + .ignore_errors + .unwrap_or(handler.pipeline_options().ignore_errors); // A pipeline name supplied via header takes precedence over the query parameter, // consistent with how other pipeline options (e.g. `x-greptime-pipeline-params`) @@ -875,40 +886,92 @@ impl<'a> TryFrom<&'a ContentType> for EventPayloadResolver<'a> { } impl EventPayloadResolver<'_> { - fn parse_payload(&self, payload: Bytes, ignore_errors: bool) -> Result> { + fn parse_payload( + &self, + payload: Bytes, + ignore_errors: bool, + utf8_retries: &IntCounterVec, + ) -> Result> { match self.inner { EventPayloadResolverInner::Json | EventPayloadResolverInner::JsonStream => { - transform_ndjson_array_factory( - Deserializer::from_slice(&payload).into_iter(), + // Detect UTF-8 failures even when ignore_errors would discard them. + let mut saw_invalid_utf8 = false; + let result = transform_ndjson_array_factory( + Deserializer::from_slice(&payload) + .into_iter() + .inspect(|item| { + // serde_json keeps its error codes private. + saw_invalid_utf8 |= item.as_ref().is_err_and(|error| { + error.is_syntax() + && error + .to_string() + .starts_with("invalid unicode code point at line ") + }); + }), ignore_errors, - ) + ); + if saw_invalid_utf8 && let Cow::Owned(text) = String::from_utf8_lossy(&payload) { + // Release partially parsed records before retrying the entire payload. + drop(result); + let format = if matches!(self.inner, EventPayloadResolverInner::Json) { + "json" + } else { + "json_stream" + }; + utf8_retries.with_label_values(&[format]).inc(); + return transform_ndjson_array_factory( + Deserializer::from_str(&text).into_iter(), + ignore_errors, + ); + } + result } EventPayloadResolverInner::Ndjson => { let mut result = Vec::with_capacity(1000); let mut buffer = Buffers::new(1000); - for (index, line) in payload.lines().enumerate() { - let mut line = match line { - Ok(line) if !line.is_empty() => line, - Ok(_) => continue, // Skip empty lines - Err(_) if ignore_errors => continue, - Err(e) => { - warn!(e; "invalid string at index: {}", index); - return InvalidParameterSnafu { - reason: format!("invalid line at index: {}", index), - } - .fail(); - } - }; + let mut remaining = payload.as_ref(); + let mut line_bytes = Vec::new(); + // read_until keeps the optimized newline search without validating UTF-8. + for index in 0usize.. { + let original = remaining; + line_bytes.clear(); + let read = remaining.read_until(b'\n', &mut line_bytes)?; + if read == 0 { + break; + } - // simd_json, according to description, only de-escapes string at character level, - // like any other json parser. So it should be safe here. - if let Ok(v) = simd_json::serde::from_slice_with_buffers( - unsafe { line.as_bytes_mut() }, - &mut buffer, - ) { + let line = &original[..read]; + let line = if let Some(line) = line.strip_suffix(b"\n") { + line.strip_suffix(b"\r").unwrap_or(line) + } else { + line + }; + if line.is_empty() { + continue; + } + + line_bytes.truncate(line.len()); + let mut parsed = + simd_json::serde::from_slice_with_buffers(&mut line_bytes, &mut buffer); + // Retry from the original line because SIMD parsing can rewrite its input. + if parsed.as_ref().is_err_and(|error| { + matches!(error.error(), simd_json::ErrorType::InvalidUtf8) + }) && let Cow::Owned(text) = String::from_utf8_lossy(line) + { + line_bytes = text.into_bytes(); + utf8_retries.with_label_values(&["ndjson"]).inc(); + parsed = + simd_json::serde::from_slice_with_buffers(&mut line_bytes, &mut buffer); + } + + if let Ok(v) = parsed { result.push(v); } else if !ignore_errors { - warn!("invalid JSON at index: {}, content: {:?}", index, line); + warn!( + "invalid JSON at index: {}, content: {:?}", + index, + String::from_utf8_lossy(line) + ); return InvalidParameterSnafu { reason: format!("invalid JSON at index: {}", index), } @@ -943,7 +1006,7 @@ fn extract_pipeline_value_by_content_type( ) -> Result> { EventPayloadResolver::try_from(&content_type).and_then(|resolver| { resolver - .parse_payload(payload, ignore_errors) + .parse_payload(payload, ignore_errors, &METRIC_HTTP_LOGS_UTF8_RETRIES_TOTAL) .map_err(|e| match &e { Error::InvalidParameter { reason, .. } if content_type == *JSON_CONTENT_TYPE => { if reason.contains("invalid item:") { @@ -1057,6 +1120,8 @@ pub struct LogState { #[cfg(test)] mod tests { + use prometheus::Opts; + use super::*; #[test] @@ -1133,6 +1198,322 @@ mod tests { assert_eq!(via_stream.len(), 2); } + #[test] + fn test_json_parser_invalid_utf8_errors() { + for payload in [ + b"{\"message\":\"bad\xff\"}".as_slice(), + b"{\"message\":\"bad\xc1\x89\xc8\"}".as_slice(), + b"{\"message\":\"bad\xe2\x82\"}".as_slice(), + b"{\"message\":\"line\\nbad\xff\"}".as_slice(), + b"{\"bad\xff\":1}".as_slice(), + ] { + let error = Deserializer::from_slice(payload) + .into_iter::() + .next() + .unwrap() + .unwrap_err(); + assert!(error.is_syntax(), "{error:?}"); + assert!( + error + .to_string() + .starts_with("invalid unicode code point at line "), + "{error:?}" + ); + + let mut line = payload.to_vec(); + let error = simd_json::serde::from_slice_with_buffers::( + &mut line, + &mut Buffers::new(payload.len()), + ) + .unwrap_err(); + assert_eq!(error.error(), &simd_json::ErrorType::InvalidUtf8); + } + } + + #[test] + fn test_json_does_not_retry_other_errors() { + for payload in [ + b"{\"message\":\"bad\xff\\q\"}".as_slice(), + b"{\"message\":\"bad\xff".as_slice(), + ] { + let original_error = Deserializer::from_slice(payload) + .into_iter::() + .next() + .unwrap() + .unwrap_err(); + assert!( + !original_error + .to_string() + .starts_with("invalid unicode code point at line ") + ); + + for content_type in [ContentType::json(), JSON_STREAM_CONTENT_TYPE.clone()] { + let error = extract_pipeline_value_by_content_type( + content_type, + Bytes::from_static(payload), + false, + ) + .unwrap_err(); + let Error::ParseJson { error: source, .. } = error else { + panic!("expected a JSON parse error, got {error}"); + }; + assert_eq!(source.to_string(), original_error.to_string()); + } + } + } + + #[test] + fn test_utf8_retry_counter() { + // Keep exact retry counts independent of other parser tests. + let utf8_retries = IntCounterVec::new( + Opts::new("test_utf8_retries", "UTF-8 retry attempts"), + &["format"], + ) + .unwrap(); + for (content_type, format, multi_record_retries) in [ + (ContentType::json(), "json", 1), + (JSON_STREAM_CONTENT_TYPE.clone(), "json_stream", 1), + (NDJSON_CONTENT_TYPE.clone(), "ndjson", 2), + ] { + let resolver = EventPayloadResolver::try_from(&content_type).unwrap(); + let counter = utf8_retries.with_label_values(&[format]); + for ignore_errors in [false, true] { + for (payload, retries, valid_after_retry) in [ + (br#"{"message":"ok"}"#.as_slice(), 0, true), + ( + b"{\"message\":\"bad\xff\"}\n{\"message\":\"bad\xfe\"}".as_slice(), + multi_record_retries, + true, + ), + (br#"{"broken":}"#.as_slice(), 0, false), + (br#"{"message":"\uDC00"}"#.as_slice(), 0, false), + ( + b"{\"message\":\"bad\xff\",\"broken\":}".as_slice(), + 1, + false, + ), + // SIMD validates UTF-8 before decoding the invalid escape. + ( + b"{\"message\":\"bad\xff\\q\"}".as_slice(), + u64::from(format == "ndjson"), + false, + ), + ] { + let before = counter.get(); + let result = resolver.parse_payload( + Bytes::from_static(payload), + ignore_errors, + &utf8_retries, + ); + assert_eq!(result.is_ok(), valid_after_retry || ignore_errors); + assert_eq!( + counter.get() - before, + retries, + "format={format}, ignore_errors={ignore_errors}, payload={payload:?}" + ); + } + } + } + } + + #[test] + fn test_json_invalid_utf8_retry() { + let expected = vec![ + json!({"message": "before"}).into(), + json!({"message": "bad\u{fffd}\u{fffd}\u{fffd}\u{7f}\u{7f}"}).into(), + json!({"message": "after"}).into(), + ]; + + for payload in [ + b"[{\"message\":\"before\"},{\"message\":\"bad\xc1\x89\xc8\x7f\x7f\"},{\"message\":\"after\"}]".as_slice(), + b"{\"message\":\"before\"}\n{\"message\":\"bad\xc1\x89\xc8\x7f\x7f\"}\n{\"message\":\"after\"}".as_slice(), + ] { + for content_type in [ContentType::json(), JSON_STREAM_CONTENT_TYPE.clone()] { + for ignore_errors in [false, true] { + let actual = extract_pipeline_value_by_content_type( + content_type.clone(), + Bytes::from_static(payload), + ignore_errors, + ) + .unwrap(); + assert_eq!(actual, expected); + } + } + } + } + + #[test] + fn test_json_invalid_utf8_retry_preserves_parse_errors() { + let cases = [ + ( + br#"{"message":"before"}{"message":"\uD800"}{"message":"after"}"#.as_slice(), + vec![json!({"message": "before"}).into()], + ), + ( + b"{\"message\":\"before\"}{\"message\":\"bad\xff\"}{\"broken\":}".as_slice(), + vec![ + json!({"message": "before"}).into(), + json!({"message": "bad\u{fffd}"}).into(), + ], + ), + ]; + + for (payload, expected) in cases { + for content_type in [ContentType::json(), JSON_STREAM_CONTENT_TYPE.clone()] { + for ignore_errors in [false, true] { + let result = extract_pipeline_value_by_content_type( + content_type.clone(), + Bytes::from_static(payload), + ignore_errors, + ); + if ignore_errors { + assert_eq!(result.unwrap(), expected); + } else { + assert!(matches!(result, Err(Error::ParseJson { .. }))); + } + } + } + } + } + + #[test] + fn test_json_invalid_utf8_retry_preserves_ignored_items() { + let payload = Bytes::from_static(b"0{\"message\":\"bad\xff\"}false{\"message\":\"after\"}"); + for content_type in [ContentType::json(), JSON_STREAM_CONTENT_TYPE.clone()] { + let result = extract_pipeline_value_by_content_type( + content_type.clone(), + payload.clone(), + false, + ); + assert!(matches!(result, Err(Error::InvalidParameter { .. }))); + + let actual = + extract_pipeline_value_by_content_type(content_type, payload.clone(), true) + .unwrap(); + assert_eq!( + actual, + vec![ + json!({"message": "bad\u{fffd}"}).into(), + json!({"message": "after"}).into(), + ], + ); + } + } + + #[test] + fn test_ndjson_invalid_utf8_retry() { + for invalid_bytes in [1, 8192] { + let mut payload = b"\n{\"message\":\"before\"}\r\n\r\n{\"escaped\":\"line\\nquote\\\"slash\\\\\",\"message\":\"bad".to_vec(); + payload.extend(std::iter::repeat_n(0xff, invalid_bytes)); + payload.extend_from_slice(b"\"}\r\n{\"message\":\"after\"}"); + let payload = Bytes::from(payload); + let expected = vec![ + json!({"message": "before"}).into(), + json!({ + "escaped": "line\nquote\"slash\\", + "message": format!("bad{}", "\u{fffd}".repeat(invalid_bytes)), + }) + .into(), + json!({"message": "after"}).into(), + ]; + + for ignore_errors in [false, true] { + let actual = extract_pipeline_value_by_content_type( + NDJSON_CONTENT_TYPE.clone(), + payload.clone(), + ignore_errors, + ) + .unwrap(); + assert_eq!(actual, expected); + } + } + } + + #[test] + fn test_ndjson_invalid_utf8_retry_preserves_parse_errors() { + let too_deep = format!("{}0{}", "[".repeat(1025), "]".repeat(1025)); + for bad_line in [ + br#"{"escaped":"line\n","broken":}"#.as_slice(), + b"{\"escaped\":\"line\\n\",\"message\":\"bad\xff\",\"broken\":}".as_slice(), + br#"{"escaped":"line\n","message":"\uDC00"}"#.as_slice(), + br#"{"message":"\uD800"}"#.as_slice(), + br#"{"value":1e4294967296}"#.as_slice(), + b"{\"value\":123\0}".as_slice(), + b"{\"message\":\"bad\xe2\x82".as_slice(), + too_deep.as_bytes(), + ] { + let mut payload = b"{\"message\":\"before\"}\n".to_vec(); + payload.extend_from_slice(bad_line); + payload.extend_from_slice(b"\n{\"message\":\"after\"}\n"); + let payload = Bytes::from(payload); + + for ignore_errors in [false, true] { + let result = extract_pipeline_value_by_content_type( + NDJSON_CONTENT_TYPE.clone(), + payload.clone(), + ignore_errors, + ); + if ignore_errors { + assert_eq!( + result.unwrap(), + vec![ + json!({"message": "before"}).into(), + json!({"message": "after"}).into(), + ], + ); + } else { + assert!(matches!( + result, + Err(Error::InvalidParameter { reason, .. }) + if reason.ends_with("at index: 1") + )); + } + } + } + } + + #[test] + fn test_ndjson_large_exponents() { + let payload = Bytes::from_static(br#"{"zero":0e99999999999,"underflow":1e-4294967295}"#); + for ignore_errors in [false, true] { + let actual = extract_pipeline_value_by_content_type( + NDJSON_CONTENT_TYPE.clone(), + payload.clone(), + ignore_errors, + ) + .unwrap(); + assert_eq!(actual, vec![json!({"zero": 0.0, "underflow": 0.0}).into()]); + } + } + + #[test] + fn test_ndjson_empty_and_whitespace_lines() { + for ignore_errors in [false, true] { + for payload in [b"".as_slice(), b"\n\r\n".as_slice()] { + let actual = extract_pipeline_value_by_content_type( + NDJSON_CONTENT_TYPE.clone(), + Bytes::from_static(payload), + ignore_errors, + ) + .unwrap(); + assert!(actual.is_empty()); + } + + for payload in [b"\r".as_slice(), b" \n".as_slice(), b"\r\r\n".as_slice()] { + let result = extract_pipeline_value_by_content_type( + NDJSON_CONTENT_TYPE.clone(), + Bytes::from_static(payload), + ignore_errors, + ); + if ignore_errors { + assert!(result.unwrap().is_empty()); + } else { + assert!(matches!(result, Err(Error::InvalidParameter { .. }))); + } + } + } + } + #[test] fn test_extract_by_content() { let payload = r#" diff --git a/src/servers/src/http/prom_store.rs b/src/servers/src/http/prom_store.rs index 7ccaffd641d..b4f182a5a41 100644 --- a/src/servers/src/http/prom_store.rs +++ b/src/servers/src/http/prom_store.rs @@ -26,6 +26,8 @@ use axum::http::{Extensions, HeaderMap, HeaderValue, StatusCode, header}; use axum::response::IntoResponse; use axum_extra::TypedHeader; use common_catalog::consts::DEFAULT_SCHEMA_NAME; +use common_error::ext::BoxedError; +use common_memory_manager::OnExhaustedPolicy; use common_query::prelude::GREPTIME_PHYSICAL_TABLE; use common_telemetry::tracing; use mime_guess::mime; @@ -246,12 +248,27 @@ async fn remote_write_v1( ) })?; memory_limiter.check_request_fits(bytes, body_reserved_bytes)?; - let reservation = Arc::new( + // Holding body permits while waiting for expansion can stall concurrent requests. + let reservation = Arc::new(if body_reserved_bytes > 0 { + memory_limiter.try_acquire(bytes).ok_or_else(|| { + let source = common_memory_manager::Error::MemoryLimitExceeded { + requested_bytes: bytes, + limit_bytes: memory_limiter.limit_bytes(), + }; + // Wait-policy contention must remain retryable by Remote Write senders. + match memory_limiter.policy() { + OnExhaustedPolicy::Wait { .. } => { + error::OtherSnafu.into_error(BoxedError::new(source)) + } + OnExhaustedPolicy::Fail => error::MemoryLimitExceededSnafu.into_error(source), + } + })? + } else { memory_limiter .acquire(bytes) .await - .map_err(prom_remote_write::map_memory_acquire_timeout)?, - ); + .map_err(prom_remote_write::map_memory_acquire_timeout)? + }); let mut ctx = query_ctx.fork(); ctx.set_write_progress(Arc::new( session::write_progress::WriteProgress::with_reservation(reservation), @@ -542,7 +559,7 @@ async fn preflight_prometheus_rows( } operator::insert::admit_row_insert_batches(batches) .await - .map_err(common_error::ext::BoxedError::new) + .map_err(BoxedError::new) .context(error::ExecuteGrpcQuerySnafu)?; Ok(()) } @@ -971,7 +988,6 @@ mod tests { use axum::body::Body; use axum::http::Request; use axum::{Router, middleware, routing}; - use common_memory_manager::OnExhaustedPolicy; use common_query::Output; use pipeline::GreptimePipelineParams; use session::context::{QueryContext, QueryContextRef}; @@ -1460,6 +1476,110 @@ mod tests { } } + #[tokio::test(start_paused = true)] + async fn test_exemplar_v1_concurrent_body_reservations() { + use api::prom_store::remote; + + use crate::http::{HttpOptions, HttpServerBuilder}; + + let wire = remote::WriteRequest { + timeseries: vec![remote::TimeSeries { + labels: vec![ + remote::Label { + name: "__name__".into(), + value: "metric".into(), + }, + remote::Label { + name: "job".into(), + value: "api".into(), + }, + ], + exemplars: vec![remote::Exemplar::default()], + ..Default::default() + }], + ..Default::default() + } + .encode_to_vec(); + let body = Bytes::from(crate::prom_store::snappy_compress(&wire).unwrap()); + let body_length = body.len(); + let request = |body: Body| { + Request::post("/v1/prometheus/write") + .header(header::CONTENT_TYPE, "application/x-protobuf") + .header(header::CONTENT_ENCODING, DEFAULT_ENCODING) + .header(header::CONTENT_LENGTH, body_length) + .body(body) + .unwrap() + }; + + for policy in [OnExhaustedPolicy::default(), OnExhaustedPolicy::Fail] { + // Each request fits alone: 1 KiB for its body and 5 KiB for exemplar rows. + let limiter = ServerMemoryLimiter::new(6 * 1024, policy); + let handler = Arc::new(ExemplarMemoryHandler { + limiter: limiter.clone(), + progress: Mutex::new(None), + }); + let server = HttpServerBuilder::new(HttpOptions::default()) + .with_memory_limiter(limiter.clone()) + .with_prom_handler( + handler.clone(), + None, + true, + PromValidationMode::Strict, + None, + ) + .build(); + let app = server.build(server.make_app()).unwrap(); + let single = app + .clone() + .oneshot(request(Body::from(body.clone()))) + .await + .unwrap(); + assert_eq!(single.status(), StatusCode::NO_CONTENT); + drop(handler.progress.lock().unwrap().take()); + assert_eq!(limiter.used_bytes(), 0); + + let (send_body, receive_body) = tokio::sync::oneshot::channel(); + let delayed_body = body.clone(); + let mut second = Box::pin(app.clone().oneshot(request(Body::from_stream( + futures::stream::once(async move { + receive_body.await.unwrap(); + Ok::<_, std::io::Error>(delayed_body) + }), + )))); + assert!(futures::poll!(second.as_mut()).is_pending()); + assert_eq!(limiter.used_bytes(), 1024); + + let started = tokio::time::Instant::now(); + let mut first = Box::pin(app.clone().oneshot(request(Body::from(body.clone())))); + let first_poll = futures::poll!(first.as_mut()); + assert!(handler.progress.lock().unwrap().is_none()); + send_body.send(()).unwrap(); + let (first, second) = match first_poll { + std::task::Poll::Ready(first) => (first, second.await), + std::task::Poll::Pending => futures::join!(first, second), + }; + assert_eq!( + first.unwrap().status(), + match policy { + OnExhaustedPolicy::Wait { .. } => StatusCode::INTERNAL_SERVER_ERROR, + OnExhaustedPolicy::Fail => StatusCode::TOO_MANY_REQUESTS, + } + ); + assert_eq!(second.unwrap().status(), StatusCode::NO_CONTENT); + assert_eq!(started.elapsed(), Duration::ZERO); + assert!(handler.progress.lock().unwrap().take().is_some()); + assert_eq!(limiter.used_bytes(), 0); + + let retry = app + .oneshot(request(Body::from(body.clone()))) + .await + .unwrap(); + assert_eq!(retry.status(), StatusCode::NO_CONTENT); + assert!(handler.progress.lock().unwrap().take().is_some()); + assert_eq!(limiter.used_bytes(), 0); + } + } + #[tokio::test(start_paused = true)] async fn test_exemplar_row_memory_is_charged_and_retained() { use api::greptime_proto::io::prometheus::write::v2; @@ -1467,7 +1587,7 @@ mod tests { use crate::http::{HttpOptions, HttpServerBuilder}; - for version in [1, 2] { + for (version, holds_body) in [(1, false), (1, true), (2, true)] { for policy in [OnExhaustedPolicy::Fail, OnExhaustedPolicy::default()] { for (distinct_tags, contended, expire) in [ (true, false, false), @@ -1543,7 +1663,15 @@ mod tests { None, ) .build(); - let response = server.build(server.make_app()).unwrap().oneshot( + let app = if holds_body { + server.build(server.make_app()).unwrap() + } else { + // Exercise waiting without transport-owned permits. + server + .make_app() + .layer(Extension(QueryContext::with("greptime", "public"))) + }; + let response = app.oneshot( Request::post("/v1/prometheus/write") .header(header::CONTENT_TYPE, content_type) .header(header::CONTENT_ENCODING, DEFAULT_ENCODING) @@ -1554,27 +1682,33 @@ mod tests { ); let started = tokio::time::Instant::now(); tokio::pin!(response); - if contended && matches!(policy, OnExhaustedPolicy::Wait { .. }) { + let fail_fast = version == 1 + && holds_body + && contended + && matches!(policy, OnExhaustedPolicy::Wait { .. }); + if contended && matches!(policy, OnExhaustedPolicy::Wait { .. }) && !fail_fast { assert!(futures::poll!(response.as_mut()).is_pending()); if !expire { drop(occupied.take()); } } let response = response.await.unwrap(); - let timed_out = expire && matches!(policy, OnExhaustedPolicy::Wait { .. }); + let timed_out = + expire && matches!(policy, OnExhaustedPolicy::Wait { .. }) && !fail_fast; let rejected = distinct_tags || timed_out + || fail_fast || (contended && matches!(policy, OnExhaustedPolicy::Fail)); assert_eq!( response.status(), - if timed_out { + if timed_out || fail_fast { StatusCode::INTERNAL_SERVER_ERROR } else if rejected { StatusCode::TOO_MANY_REQUESTS } else { StatusCode::NO_CONTENT }, - "version={version}, distinct={distinct_tags}, contended={contended}, expire={expire}, policy={policy:?}" + "version={version}, holds_body={holds_body}, distinct={distinct_tags}, contended={contended}, expire={expire}, policy={policy:?}" ); if let OnExhaustedPolicy::Wait { timeout } = policy && timed_out diff --git a/src/servers/src/http/prometheus.rs b/src/servers/src/http/prometheus.rs index 82bbc665202..0773b337889 100644 --- a/src/servers/src/http/prometheus.rs +++ b/src/servers/src/http/prometheus.rs @@ -59,7 +59,7 @@ use query::parser::{DEFAULT_LOOKBACK_STRING, PromQuery, QueryLanguageParser, Que use serde::de::{self, MapAccess, Visitor}; use serde::{Deserialize, Serialize}; use serde_json::Value; -use session::context::{QueryContext, QueryContextRef}; +use session::context::{Channel, QueryContext, QueryContextRef}; use snafu::{Location, OptionExt, ResultExt, ensure}; use store_api::metric_engine_consts::{ DATA_SCHEMA_TABLE_ID_COLUMN_NAME, DATA_SCHEMA_TSID_COLUMN_NAME, LOGICAL_TABLE_METADATA_KEY, @@ -175,6 +175,7 @@ pub enum PrometheusResponse { BuildInfo(OwnedBuildInfo), #[serde(skip_deserializing)] ParseResult(promql_parser::parser::Expr), + Exemplars(Vec), #[default] None, } @@ -221,6 +222,84 @@ impl PrometheusResponse { } } +#[derive(Debug, Default, Deserialize)] +pub struct ExemplarQuery { + query: Option, + start: Option, + end: Option, + db: Option, + timeout: Option, +} + +#[axum_macros::debug_handler] +#[tracing::instrument( + skip_all, + fields(protocol = "prometheus", request_type = "query_exemplars") +)] +pub async fn query_exemplars( + State(handler): State, + Query(params): Query, + Extension(mut ctx): Extension, + Form(form): Form, +) -> PrometheusJsonResponse { + if let Some(db) = params.db.or(form.db) { + let (catalog, schema) = parse_catalog_and_schema_from_db_string(&db); + try_update_catalog_schema(&mut ctx, &catalog, &schema); + } + ctx.set_channel(Channel::Prometheus); + let ctx = Arc::new(ctx); + let _timer = crate::metrics::METRIC_HTTP_PROMETHEUS_PROMQL_ELAPSED + .with_label_values(&[ctx.get_db_string().as_str(), "query_exemplars"]) + .start_timer(); + let query = match crate::exemplar::query::Query::parse( + params.query.or(form.query).unwrap_or_default(), + ¶ms.start.or(form.start).unwrap_or_default(), + ¶ms.end.or(form.end).unwrap_or_default(), + &ctx.current_schema(), + ) { + Ok(query) => query, + Err(error) => { + return PrometheusJsonResponse::error(error.status_code(), error.output_msg()); + } + }; + let timeout = if let Some(timeout) = params.timeout.or(form.timeout) { + match humantime::parse_duration(&timeout) { + Ok(timeout) => Some(timeout), + Err(error) => { + return PrometheusJsonResponse::error( + StatusCode::InvalidArguments, + error.to_string(), + ); + } + } + } else { + ctx.query_timeout() + }; + let future = handler.query_exemplars(query, ctx.clone()); + let result = if let Some(timeout) = timeout.filter(|timeout| !timeout.is_zero()) { + match tokio::time::timeout(timeout, future).await { + Ok(result) => result, + Err(_) => { + return PrometheusJsonResponse::error( + StatusCode::Cancelled, + "exemplar query timed out".to_string(), + ); + } + } + } else { + future.await + }; + match result { + Ok(series) => { + let mut response = + PrometheusJsonResponse::success(PrometheusResponse::Exemplars(series)); + response.warnings = ctx.warning().map(|warning| vec![warning]); + response + } + Err(error) => PrometheusJsonResponse::error(error.status_code(), error.output_msg()), + } +} + #[derive(Debug, Default, Serialize, Deserialize)] pub struct FormatQuery { query: Option, @@ -2630,6 +2709,22 @@ mod tests { #[async_trait::async_trait] impl PrometheusHandler for TestPrometheusHandler { + async fn query_exemplars( + &self, + _: crate::exemplar::query::Query, + _: QueryContextRef, + ) -> Result> { + struct Scan<'a>(&'a Mutex>); + impl Drop for Scan<'_> { + fn drop(&mut self) { + self.0.lock().unwrap().push("cancelled".into()); + } + } + let _scan = Scan(&self.queries); + self.queries.lock().unwrap().push("started".into()); + futures::future::pending().await + } + async fn do_query(&self, _: &PromQuery, _: QueryContextRef) -> Result { unreachable!("HTTP handlers should execute the parsed query") } @@ -2780,6 +2875,41 @@ mod tests { ); } + #[tokio::test] + async fn test_exemplar_timeout_cancels_scan() { + for explicit in [false, true] { + let handler = Arc::new(TestPrometheusHandler { + catalog_manager: MemoryCatalogManager::new(), + deny_operation: false, + denied_table: None, + metric_names: Vec::new(), + label_metric_names: Vec::new(), + label_lookups: Mutex::new(Vec::new()), + queries: Mutex::new(Vec::new()), + ordered_outputs: Mutex::new(Vec::new()), + }); + let ctx = QueryContext::with(DEFAULT_CATALOG_NAME, DEFAULT_SCHEMA_NAME); + if !explicit { + ctx.set_query_timeout(std::time::Duration::from_millis(1)); + } + let response = query_exemplars( + State(handler.clone()), + Query(ExemplarQuery { + query: Some("requests".into()), + start: Some("0".into()), + end: Some("1".into()), + timeout: explicit.then(|| "1ms".into()), + ..Default::default() + }), + Extension(ctx), + Form(ExemplarQuery::default()), + ) + .await; + assert_eq!(response.status_code, Some(StatusCode::Cancelled)); + assert_eq!(*handler.queries.lock().unwrap(), ["started", "cancelled"]); + } + } + #[tokio::test] async fn range_query_does_not_require_execution_output_ordering() { let handler = Arc::new(TestPrometheusHandler { diff --git a/src/servers/src/interceptor.rs b/src/servers/src/interceptor.rs index 30bc5a2aa07..6de898a919c 100644 --- a/src/servers/src/interceptor.rs +++ b/src/servers/src/interceptor.rs @@ -28,8 +28,11 @@ use query::parser::PromQuery; use session::context::QueryContextRef; use sql::statements::statement::Statement; use table::TableRef; +use table::table_reference::TableReference; use vrl::value::Value; +use crate::exemplar::query::Query as ExemplarQuery; + /// SqlQueryInterceptor can track life cycle of a sql query and customize or /// abort its execution at given point. pub trait SqlQueryInterceptor { @@ -232,6 +235,17 @@ pub trait PromQueryInterceptor { Ok(()) } + /// Called after authorization, before each resolved exemplar table is scanned. + /// Returning an error aborts the query. `query_ctx` uses the table's schema. + fn pre_execute_exemplars( + &self, + _query: &ExemplarQuery, + _table: TableReference<'_>, + _query_ctx: QueryContextRef, + ) -> Result<(), Self::Error> { + Ok(()) + } + /// Called after execution finished. The implementation can modify the /// output if needed. fn post_execute( @@ -277,6 +291,19 @@ where Ok(output) } } + + fn pre_execute_exemplars( + &self, + query: &ExemplarQuery, + table: TableReference<'_>, + query_ctx: QueryContextRef, + ) -> Result<(), Self::Error> { + if let Some(this) = self { + this.pre_execute_exemplars(query, table, query_ctx) + } else { + Ok(()) + } + } } impl PromQueryInterceptor for Option<&PromQueryInterceptorRef> @@ -310,6 +337,19 @@ where Ok(output) } } + + fn pre_execute_exemplars( + &self, + query: &ExemplarQuery, + table: TableReference<'_>, + query_ctx: QueryContextRef, + ) -> Result<(), Self::Error> { + if let Some(this) = self { + this.pre_execute_exemplars(query, table, query_ctx) + } else { + Ok(()) + } + } } /// LineProtocolInterceptor can track life cycle of a line protocol request diff --git a/src/servers/src/metrics.rs b/src/servers/src/metrics.rs index cd254559e0f..615bc8b67ba 100644 --- a/src/servers/src/metrics.rs +++ b/src/servers/src/metrics.rs @@ -257,6 +257,12 @@ lazy_static! { &[METRIC_DB_LABEL, METRIC_RESULT_LABEL] ) .unwrap(); + pub static ref METRIC_HTTP_LOGS_UTF8_RETRIES_TOTAL: IntCounterVec = register_int_counter_vec!( + "greptime_servers_http_logs_utf8_retries_total", + "UTF-8 parse retry attempts for HTTP logs and pipeline dry-runs, per JSON/JSON stream payload or NDJSON line, regardless of outcome", + &["format"] + ) + .unwrap(); /// Count of logs ingested into Loki. pub static ref METRIC_LOKI_LOGS_INGESTION_COUNTER: IntCounterVec = register_int_counter_vec!( diff --git a/src/servers/src/otlp/logs.rs b/src/servers/src/otlp/logs.rs index 53a2189044d..7f20e7cc39a 100644 --- a/src/servers/src/otlp/logs.rs +++ b/src/servers/src/otlp/logs.rs @@ -17,16 +17,18 @@ use std::collections::BTreeMap; use ahash::{HashMap, HashMapExt}; use api::helper::{ColumnDataTypeWrapper, timestamp_unit}; use api::v1::column_data_type_extension::TypeExt; -use api::v1::column_def::options_from_column_schema; +use api::v1::column_def::{options_from_column_schema, options_from_skipping}; use api::v1::value::ValueData; use api::v1::{ ColumnDataType, ColumnDataTypeExtension, ColumnOptions, ColumnSchema, JsonTypeExtension, Row, RowInsertRequest, Rows, SemanticType, Value as GreptimeValue, }; use bytes::Bytes; +use common_catalog::consts::SERVICE_NAME_COLUMN; use common_telemetry::warn; use common_time::Timestamp; use common_time::timestamp::TimeUnit; +use datatypes::schema::SkippingIndexOptions; use jsonb::{Number as JsonbNumber, Value as JsonbValue}; use opentelemetry_proto::tonic::collector::logs::v1::ExportLogsServiceRequest; use opentelemetry_proto::tonic::common::v1::{AnyValue, InstrumentationScope, KeyValue, any_value}; @@ -36,6 +38,7 @@ use pipeline::{ }; use session::context::QueryContextRef; use snafu::ensure; +use table::requests::TABLE_DATA_MODEL_LOG_V1; use vrl::prelude::NotNan; use vrl::value::{KeyString, Value as VrlValue}; @@ -46,11 +49,13 @@ use crate::error::{ use crate::http::event::PipelineIngestRequest; use crate::otlp::coerce::{coerce_value_data, is_supported_signed_to_unsigned_coercion}; use crate::otlp::trace::attributes::OtlpAnyValue; -use crate::otlp::utils::{bytes_to_hex_string, key_value_to_jsonb}; +use crate::otlp::utils::{bytes_to_hex_string, key_value_to_jsonb, resource_service_name}; use crate::pipeline::run_pipeline; use crate::query_handler::PipelineHandlerRef; pub const LOG_TABLE_NAME: &str = "opentelemetry_logs"; +const EVENT_NAME_COLUMN: &str = "event_name"; +const OBSERVED_TIMESTAMP_COLUMN: &str = "observed_timestamp"; /// Convert OpenTelemetry metrics to GreptimeDB insert requests /// @@ -73,6 +78,11 @@ pub async fn to_grpc_insert_requests( .get_table(&table_name, query_ctx) .await .map_err(Error::from)?; + // New tables get the v1 schema. Existing tables without the v1 marker keep + // the legacy schema, so upgrading never alters their columns or keys. + let v1_schema = table.as_deref().is_none_or(|table| { + table.table_info().meta.options.data_model() == Some(TABLE_DATA_MODEL_LOG_V1) + }); let existing_schema = table .as_deref() .map(ExistingLogSchema::try_from_table) @@ -80,6 +90,7 @@ pub async fn to_grpc_insert_requests( let rows = parse_export_logs_service_request_to_rows( request, select_info, + v1_schema, existing_schema.as_ref(), &table_name, )?; @@ -197,8 +208,17 @@ fn log_to_pipeline_value( VrlValue::Object(map) } -fn build_otlp_logs_identity_schema() -> Vec { - [ +/// Built-in columns of a direct OTLP log row, in row order. +/// +/// The v1 schema puts `service_name` before `scope_name` because auto-create +/// orders the primary key by column order. +fn build_otlp_logs_identity_schema(v1_schema: bool) -> Result> { + let trace_id_options = if v1_schema { + options_from_skipping(&SkippingIndexOptions::default())? + } else { + None + }; + let mut columns = vec![ ( "timestamp", ColumnDataType::TimestampNanosecond, @@ -211,7 +231,7 @@ fn build_otlp_logs_identity_schema() -> Vec { ColumnDataType::String, SemanticType::Field, None, - None, + trace_id_options, ), ( "span_id", @@ -262,6 +282,17 @@ fn build_otlp_logs_identity_schema() -> Vec { None, None, ), + ]; + if v1_schema { + columns.push(( + SERVICE_NAME_COLUMN, + ColumnDataType::String, + SemanticType::Tag, + None, + None, + )); + } + columns.extend([ ( "scope_name", ColumnDataType::String, @@ -308,18 +339,38 @@ fn build_otlp_logs_identity_schema() -> Vec { None, None, ), - ] - .into_iter() - .map( - |(field_name, column_type, semantic_type, datatype_extension, options)| ColumnSchema { - column_name: field_name.to_string(), - datatype: column_type as i32, - semantic_type: semantic_type as i32, - datatype_extension, - options, - }, - ) - .collect::>() + ]); + if v1_schema { + columns.extend([ + ( + EVENT_NAME_COLUMN, + ColumnDataType::String, + SemanticType::Field, + None, + None, + ), + ( + OBSERVED_TIMESTAMP_COLUMN, + ColumnDataType::TimestampNanosecond, + SemanticType::Field, + None, + None, + ), + ]); + } + + Ok(columns + .into_iter() + .map( + |(field_name, column_type, semantic_type, datatype_extension, options)| ColumnSchema { + column_name: field_name.to_string(), + datatype: column_type as i32, + semantic_type: semantic_type as i32, + datatype_extension, + options, + }, + ) + .collect()) } #[derive(Clone)] @@ -405,16 +456,17 @@ impl ExistingLogSchema { fn build_otlp_build_in_row( log: LogRecord, - parse_ctx: &mut ParseContext, -) -> (Row, JsonbValue<'static>) { - let log_attr = key_value_to_jsonb(log.attributes); + log_attr: &JsonbValue, + service_name: Option, + parse_ctx: &ParseContext, +) -> Row { let ts = if log.time_unix_nano != 0 { log.time_unix_nano } else { log.observed_time_unix_nano }; - let row = vec![ + let mut row = vec![ GreptimeValue { value_data: Some(ValueData::TimestampNanosecondValue(ts as i64)), }, @@ -442,6 +494,13 @@ fn build_otlp_build_in_row( GreptimeValue { value_data: Some(ValueData::I32Value(log.flags as i32)), }, + ]; + if parse_ctx.v1_schema { + row.push(GreptimeValue { + value_data: service_name.map(ValueData::StringValue), + }); + } + row.extend([ GreptimeValue { value_data: parse_ctx.scope_name.clone().map(ValueData::StringValue), }, @@ -460,8 +519,41 @@ fn build_otlp_build_in_row( GreptimeValue { value_data: Some(ValueData::StringValue(parse_ctx.resource_url.clone())), }, - ]; - (Row { values: row }, log_attr) + ]); + if parse_ctx.v1_schema { + row.extend([ + GreptimeValue { + value_data: (!log.event_name.is_empty()) + .then_some(ValueData::StringValue(log.event_name)), + }, + GreptimeValue { + value_data: (log.observed_time_unix_nano != 0).then_some( + ValueData::TimestampNanosecondValue(log.observed_time_unix_nano as i64), + ), + }, + ]); + } + Row { values: row } +} + +/// Reads a `service_name` value the request asked to extract from `attrs`, with +/// the same key matching and type rules as other extract keys. +fn extracted_service_name(attrs: &JsonbValue) -> Result> { + attrs + .get_by_name_ignore_case(SERVICE_NAME_COLUMN) + .cloned() + .map(|value| scalar_attr_to_string(SERVICE_NAME_COLUMN, value)) + .transpose() + .map(Option::flatten) +} + +fn scalar_attr_to_string(name: &str, value: JsonbValue) -> Result> { + Ok(jsonb_value_to_log_value_data(name, value, true)? + .and_then(|(value_data, _)| stringify_scalar_value(value_data)) + .and_then(|value_data| match value_data { + ValueData::StringValue(value) => Some(value), + _ => None, + })) } fn extract_field_from_attr_and_combine_schema( @@ -900,13 +992,37 @@ fn is_timestamp_type(datatype: ColumnDataType) -> bool { fn parse_export_logs_service_request_to_rows( request: ExportLogsServiceRequest, - select_info: Box, + mut select_info: Box, + v1_schema: bool, existing_schema: Option<&ExistingLogSchema>, table_name: &str, ) -> Result { - let mut schemas = build_otlp_logs_identity_schema(); + let mut schemas = build_otlp_logs_identity_schema(v1_schema)?; - let mut parse_ctx = ParseContext::new(select_info, existing_schema, table_name); + // Extract keys named after v1 built-in columns would add duplicate columns. A + // `service_name` key fills the built-in column; `event_name` and + // `observed_timestamp` keep the LogRecord values, and the attribute stays in + // `log_attributes`. + let extract_service_name = v1_schema + && select_info + .keys + .iter() + .any(|key| key == SERVICE_NAME_COLUMN); + if v1_schema { + select_info.keys.retain(|key| { + !matches!( + key.as_str(), + SERVICE_NAME_COLUMN | EVENT_NAME_COLUMN | OBSERVED_TIMESTAMP_COLUMN + ) + }); + } + let mut parse_ctx = ParseContext::new( + select_info, + v1_schema, + extract_service_name, + existing_schema, + table_name, + ); let mut rows = parse_resource(&mut parse_ctx, request.resource_logs)?; schemas.extend(parse_ctx.select_schema.column_schemas()?); @@ -935,12 +1051,26 @@ fn parse_resource( let mut results = Vec::with_capacity(total_len); for r in resource_logs_vec { - parse_ctx.resource_attr = r - .resource - .map(|resource| key_value_to_jsonb(resource.attributes)) - .unwrap_or(JsonbValue::Null); + let mut resource_service = None; + parse_ctx.resource_attr = match r.resource { + Some(resource) => { + if parse_ctx.v1_schema { + resource_service = resource_service_name(&resource.attributes); + } + key_value_to_jsonb(resource.attributes) + } + None => JsonbValue::Null, + }; parse_ctx.resource_url = r.schema_url; + if parse_ctx.v1_schema { + let extracted = if parse_ctx.extract_service_name { + extracted_service_name(&parse_ctx.resource_attr)? + } else { + None + }; + parse_ctx.resource_service_name = extracted.or(resource_service); + } parse_ctx.resource_uplift_values = extract_field_from_attr_and_combine_schema( &parse_ctx.select_info, @@ -959,6 +1089,8 @@ fn parse_resource( struct ParseContext<'a> { // input selected keys select_info: Box, + v1_schema: bool, + extract_service_name: bool, existing_schema: Option<&'a ExistingLogSchema>, table_name: &'a str, // schema infos for selected keys from resource/scope/log for current request @@ -976,17 +1108,25 @@ struct ParseContext<'a> { scope_version: Option, scope_url: String, scope_attrs: JsonbValue<'a>, + // `service_name` values resolved at the resource and scope levels; a log + // record falls back to them when its own attributes don't carry one + resource_service_name: Option, + scope_service_name: Option, } impl<'a> ParseContext<'a> { pub fn new( select_info: Box, + v1_schema: bool, + extract_service_name: bool, existing_schema: Option<&'a ExistingLogSchema>, table_name: &'a str, ) -> ParseContext<'a> { let len = select_info.keys.len(); ParseContext { select_info, + v1_schema, + extract_service_name, existing_schema, table_name, select_schema: SchemaInfo::with_capacity(len), @@ -998,6 +1138,8 @@ impl<'a> ParseContext<'a> { scope_version: None, scope_url: String::new(), scope_attrs: JsonbValue::Null, + resource_service_name: None, + scope_service_name: None, } } } @@ -1012,6 +1154,11 @@ fn parse_scope(scopes_log_vec: Vec, parse_ctx: &mut ParseContext) -> parse_ctx.scope_version = scope_version; parse_ctx.scope_url = scope_logs.schema_url; parse_ctx.scope_attrs = scope_attrs; + parse_ctx.scope_service_name = if parse_ctx.extract_service_name { + extracted_service_name(&parse_ctx.scope_attrs)? + } else { + None + }; parse_ctx.scope_uplift_values = extract_field_from_attr_and_combine_schema( &parse_ctx.select_info, @@ -1030,8 +1177,21 @@ fn parse_scope(scopes_log_vec: Vec, parse_ctx: &mut ParseContext) -> fn parse_log(log_records: Vec, parse_ctx: &mut ParseContext) -> Result> { let mut result = Vec::with_capacity(log_records.len()); - for log in log_records { - let (mut row, log_attr) = build_otlp_build_in_row(log, parse_ctx); + for mut log in log_records { + let log_attr = key_value_to_jsonb(std::mem::take(&mut log.attributes)); + let service_name = if parse_ctx.v1_schema { + let extracted = if parse_ctx.extract_service_name { + extracted_service_name(&log_attr)? + } else { + None + }; + extracted + .or_else(|| parse_ctx.scope_service_name.clone()) + .or_else(|| parse_ctx.resource_service_name.clone()) + } else { + None + }; + let mut row = build_otlp_build_in_row(log, &log_attr, service_name, parse_ctx); let log_values = extract_field_from_attr_and_combine_schema( &parse_ctx.select_info, @@ -1161,6 +1321,7 @@ mod tests { use opentelemetry_proto::tonic::common::v1::any_value::Value as OtlpValue; use super::*; + use crate::otlp::trace::KEY_SERVICE_NAME; fn time_column(datatype: ConcreteDataType) -> DatatypesColumnSchema { DatatypesColumnSchema::new("timestamp", datatype, false).with_time_index(true) @@ -1225,9 +1386,12 @@ mod tests { select: &str, existing_schema: Option<&ExistingLogSchema>, ) -> Result { + // Mirrors production: only new tables get the v1 schema, and the existing + // schemas built here carry no v1 marker. parse_export_logs_service_request_to_rows( request, Box::new(SelectInfo::from(select.to_string())), + existing_schema.is_none(), existing_schema, "test_logs", ) @@ -1257,6 +1421,165 @@ mod tests { ); } + fn request_with_resource_and_logs( + resource_attrs: Vec, + log_records: Vec, + ) -> ExportLogsServiceRequest { + ExportLogsServiceRequest { + resource_logs: vec![ResourceLogs { + resource: Some(opentelemetry_proto::tonic::resource::v1::Resource { + attributes: resource_attrs, + ..Default::default() + }), + scope_logs: vec![ScopeLogs { + scope: Some(InstrumentationScope { + name: "com.example.Checkout".to_string(), + ..Default::default() + }), + log_records, + ..Default::default() + }], + ..Default::default() + }], + } + } + + fn value_at(rows: &Rows, row: usize, column: &str) -> Option { + rows.rows[row].values[column_index(rows, column)] + .value_data + .clone() + } + + #[test] + fn test_new_table_uses_v1_schema() { + let request = request_with_resource_and_logs( + vec![kv( + KEY_SERVICE_NAME, + OtlpValue::StringValue("checkout".to_string()), + )], + vec![ + LogRecord { + time_unix_nano: 1_000, + observed_time_unix_nano: 2_000, + event_name: "gen_ai.choice".to_string(), + ..Default::default() + }, + LogRecord { + time_unix_nano: 3_000, + ..Default::default() + }, + ], + ); + let rows = parse_with_select(request, "", None).unwrap(); + + // Auto-create orders the primary key by column order. + let tags: Vec<_> = rows + .schema + .iter() + .filter(|schema| schema.semantic_type == SemanticType::Tag as i32) + .map(|schema| schema.column_name.as_str()) + .collect(); + assert_eq!(tags, [SERVICE_NAME_COLUMN, "scope_name"]); + let trace_id = &rows.schema[column_index(&rows, "trace_id")]; + assert!( + trace_id + .options + .as_ref() + .is_some_and(|options| options.options.contains_key("skipping_index")) + ); + + assert_eq!( + value_at(&rows, 0, SERVICE_NAME_COLUMN), + Some(ValueData::StringValue("checkout".to_string())) + ); + assert_eq!( + value_at(&rows, 0, EVENT_NAME_COLUMN), + Some(ValueData::StringValue("gen_ai.choice".to_string())) + ); + assert_eq!( + value_at(&rows, 0, OBSERVED_TIMESTAMP_COLUMN), + Some(ValueData::TimestampNanosecondValue(2_000)) + ); + // Empty event name and zero observed time mean "absent" in OTLP. + assert_eq!(value_at(&rows, 1, EVENT_NAME_COLUMN), None); + assert_eq!(value_at(&rows, 1, OBSERVED_TIMESTAMP_COLUMN), None); + } + + #[test] + fn test_extracted_service_name_overrides_resource_service_name() { + let mut request = request_with_resource_and_logs( + vec![kv( + KEY_SERVICE_NAME, + OtlpValue::StringValue("from-resource".to_string()), + )], + vec![ + LogRecord { + attributes: vec![ + kv( + SERVICE_NAME_COLUMN, + OtlpValue::StringValue("from-log".to_string()), + ), + kv( + EVENT_NAME_COLUMN, + OtlpValue::StringValue("from-attr".to_string()), + ), + ], + event_name: "from-record".to_string(), + ..Default::default() + }, + LogRecord::default(), + ], + ); + let mut scope_logs = request.resource_logs[0].scope_logs[0].clone(); + scope_logs.scope.as_mut().unwrap().attributes = vec![kv( + SERVICE_NAME_COLUMN, + OtlpValue::StringValue("from-scope".to_string()), + )]; + scope_logs.log_records = vec![LogRecord::default()]; + request.resource_logs[0].scope_logs.push(scope_logs); + let rows = parse_with_select(request, "service_name,event_name,host", None).unwrap(); + + for column in [SERVICE_NAME_COLUMN, EVENT_NAME_COLUMN] { + assert_eq!( + rows.schema + .iter() + .filter(|schema| schema.column_name == column) + .count(), + 1 + ); + } + assert_eq!( + value_at(&rows, 0, SERVICE_NAME_COLUMN), + Some(ValueData::StringValue("from-log".to_string())) + ); + assert_eq!( + value_at(&rows, 0, EVENT_NAME_COLUMN), + Some(ValueData::StringValue("from-record".to_string())) + ); + assert_eq!( + value_at(&rows, 1, SERVICE_NAME_COLUMN), + Some(ValueData::StringValue("from-resource".to_string())) + ); + assert_eq!( + value_at(&rows, 2, SERVICE_NAME_COLUMN), + Some(ValueData::StringValue("from-scope".to_string())) + ); + } + + #[test] + fn test_non_scalar_resource_service_name_is_not_an_error() { + let request = request_with_resource_and_logs( + vec![kv( + KEY_SERVICE_NAME, + OtlpValue::ArrayValue(Default::default()), + )], + vec![LogRecord::default()], + ); + let rows = parse_with_select(request, "", None).unwrap(); + + assert_eq!(value_at(&rows, 0, SERVICE_NAME_COLUMN), None); + } + #[test] fn test_fresh_table_trace_flags_is_int32() { // Phase 1 of the unsigned -> signed transition: a fresh log table now @@ -1508,6 +1831,18 @@ mod tests { rows.schema[scope_name_idx].semantic_type, SemanticType::Field as i32 ); + // Unmarked existing tables keep the legacy columns. + for column in [ + SERVICE_NAME_COLUMN, + EVENT_NAME_COLUMN, + OBSERVED_TIMESTAMP_COLUMN, + ] { + assert!( + rows.schema + .iter() + .all(|schema| schema.column_name != column) + ); + } } #[test] diff --git a/src/servers/src/otlp/trace/span.rs b/src/servers/src/otlp/trace/span.rs index a8a51705ffe..14734d78fa0 100644 --- a/src/servers/src/otlp/trace/span.rs +++ b/src/servers/src/otlp/trace/span.rs @@ -17,14 +17,13 @@ use std::fmt::Display; use common_time::timestamp::Timestamp; use itertools::Itertools; use opentelemetry_proto::tonic::collector::trace::v1::ExportTraceServiceRequest; -use opentelemetry_proto::tonic::common::v1::{InstrumentationScope, any_value}; +use opentelemetry_proto::tonic::common::v1::InstrumentationScope; use opentelemetry_proto::tonic::trace::v1::span::{Event, Link}; use opentelemetry_proto::tonic::trace::v1::{Span, Status}; use serde::Serialize; -use crate::otlp::trace::KEY_SERVICE_NAME; use crate::otlp::trace::attributes::{Attributes, SharedAttributes}; -use crate::otlp::utils::bytes_to_hex_string; +use crate::otlp::utils::{bytes_to_hex_string, resource_service_name}; #[derive(Debug, Clone)] pub struct TraceSpan { @@ -268,21 +267,7 @@ pub fn parse(request: ExportTraceServiceRequest) -> TraceSpanGroups { .map(|r| r.attributes) .unwrap_or_default(); - // "service.name" is required; SDKs MUST provide a fallback when it is unset. - // This is in the specification: - // https://opentelemetry.io/docs/specs/semconv/resource/service/ - // Tolerate missing names from senders without using unrelated attributes as names. - let service_name = resource_attrs - .iter() - .find(|kv| kv.key == KEY_SERVICE_NAME) - .and_then(|kv| kv.value.clone()) - .and_then(|v| match v.value { - Some(any_value::Value::StringValue(s)) => Some(s), - Some(any_value::Value::BytesValue(b)) => { - Some(String::from_utf8_lossy(&b).to_string()) - } - _ => None, - }); + let service_name = resource_service_name(&resource_attrs); let resource_attrs = SharedAttributes::from(Attributes::from(resource_attrs)); for scope_spans in resource_spans.scope_spans { diff --git a/src/servers/src/otlp/utils.rs b/src/servers/src/otlp/utils.rs index 5ae5fe6ef50..96ba02fe4d0 100644 --- a/src/servers/src/otlp/utils.rs +++ b/src/servers/src/otlp/utils.rs @@ -18,6 +18,23 @@ use common_telemetry::warn; use jsonb::{Number as JsonbNumber, Value as JsonbValue}; use opentelemetry_proto::tonic::common::v1::{KeyValue, any_value}; +use crate::otlp::trace::KEY_SERVICE_NAME; + +/// Reads the resource `service.name`. It is required by the semantic conventions, +/// but senders may omit it; unrelated attributes are never used as a fallback. +/// +pub(crate) fn resource_service_name(resource_attrs: &[KeyValue]) -> Option { + resource_attrs + .iter() + .find(|kv| kv.key == KEY_SERVICE_NAME) + .and_then(|kv| kv.value.as_ref()?.value.as_ref()) + .and_then(|value| match value { + any_value::Value::StringValue(s) => Some(s.clone()), + any_value::Value::BytesValue(b) => Some(String::from_utf8_lossy(b).to_string()), + _ => None, + }) +} + pub fn bytes_to_hex_string(bs: &[u8]) -> String { hex::encode(bs) } diff --git a/src/servers/src/prom_store.rs b/src/servers/src/prom_store.rs index cc83b35e6fc..7b7fc9d7eba 100644 --- a/src/servers/src/prom_store.rs +++ b/src/servers/src/prom_store.rs @@ -172,8 +172,7 @@ pub fn query_to_plan( q: &Query, timestamp_column_name: &str, ) -> Result { - let start_timestamp_ms = q.start_timestamp_ms; - let end_timestamp_ms = q.end_timestamp_ms; + let (start_timestamp_ms, end_timestamp_ms) = remote_read_time_range(q); let label_matches = &q.matchers; @@ -266,6 +265,22 @@ pub fn query_to_plan( Ok(dataframe.into_parts().1) } +/// Uses selector time hints without expanding the client's remote-storage range. +/// Nonpositive or reversed hints retain the outer range: proto3 scalar defaults +/// cannot distinguish missing endpoints from explicit zero timestamps. Valid +/// disjoint ranges produce contradictory time predicates and therefore no rows. +fn remote_read_time_range(query: &Query) -> (i64, i64) { + let outer = (query.start_timestamp_ms, query.end_timestamp_ms); + let Some(hints) = &query.hints else { + return outer; + }; + if hints.start_ms <= 0 || hints.end_ms <= 0 || hints.start_ms > hints.end_ms { + return outer; + } + + (outer.0.max(hints.start_ms), outer.1.min(hints.end_ms)) +} + /// Prometheus's NewFastRegexMatcher also wraps patterns in ^(?s:...)$: /// https://github.com/prometheus/prometheus/blob/main/model/labels/regexp.go fn anchored_label_regex(value: &str) -> String { @@ -1233,6 +1248,81 @@ mod tests { assert_eq!(expected, display_string); } + #[tokio::test] + async fn test_remote_read_time_hints() { + use api::prom_store::remote::ReadHints; + + let ctx = SessionContext::new(); + let timestamps = vec![-1, 0, 999, 1000, 1500, 2000, 2001, 3000]; + let batch = DfRecordBatch::try_from_iter(vec![( + greptime_timestamp(), + Arc::new(TimestampMillisecondArray::from(timestamps)) as ArrayRef, + )]) + .unwrap(); + ctx.register_batch("metrics", batch).unwrap(); + + for (outer, hinted, expected) in [ + ((1000, 2000), None, vec![1000, 1500, 2000]), + ((1000, 2000), Some((0, 0)), vec![1000, 1500, 2000]), + ((1000, 2000), Some((0, 1500)), vec![1000, 1500, 2000]), + ((1000, 2000), Some((1500, 0)), vec![1000, 1500, 2000]), + ((1000, 2000), Some((-1, 1500)), vec![1000, 1500, 2000]), + ((1000, 2000), Some((1500, -1)), vec![1000, 1500, 2000]), + ((1000, 2000), Some((2000, 1000)), vec![1000, 1500, 2000]), + ((1000, 2000), Some((1000, 2000)), vec![1000, 1500, 2000]), + ((1000, 2000), Some((1, 3000)), vec![1000, 1500, 2000]), + ((1000, 2000), Some((1001, 1999)), vec![1500]), + ((1000, 2000), Some((1500, 3000)), vec![1500, 2000]), + ((1000, 2000), Some((1, 1500)), vec![1000, 1500]), + ((1000, 2000), Some((1500, 1500)), vec![1500]), + ((1000, 2000), Some((2000, 3000)), vec![2000]), + ((1000, 2000), Some((2001, 3000)), vec![]), + ((1000, 2000), Some((1, 999)), vec![]), + ((2000, 1000), Some((1, 3000)), vec![]), + ((-1, 1000), Some((0, 1000)), vec![-1, 0, 999, 1000]), + ] { + let query = Query { + start_timestamp_ms: outer.0, + end_timestamp_ms: outer.1, + hints: hinted.map(|(start_ms, end_ms)| ReadHints { + start_ms, + end_ms, + // These describe evaluation, not sampling or aggregation instructions. + step_ms: 10000, + range_ms: 300000, + func: "rate".into(), + grouping: vec!["job".into()], + by: true, + }), + ..Default::default() + }; + let plan = query_to_plan( + ctx.table("metrics").await.unwrap(), + &query, + greptime_timestamp(), + ) + .unwrap(); + let batches = ctx + .execute_logical_plan(plan) + .await + .unwrap() + .collect() + .await + .unwrap(); + let actual: Vec = batches + .iter() + .flat_map(|batch| { + batch + .column(0) + .as_primitive::() + .values() + .to_vec() + }) + .collect(); + assert_eq!(expected, actual, "outer={outer:?}, hints={hinted:?}"); + } + } + #[tokio::test] async fn test_remote_read_label_matcher_semantics() { let ctx = SessionContext::new(); diff --git a/src/servers/src/prometheus_handler.rs b/src/servers/src/prometheus_handler.rs index 2c7aec1fb61..3f4f8509700 100644 --- a/src/servers/src/prometheus_handler.rs +++ b/src/servers/src/prometheus_handler.rs @@ -128,6 +128,17 @@ pub fn resolve_schema_from_matchers(matchers: &[Matcher]) -> Result Result> { + crate::error::NotSupportedSnafu { + feat: "query_exemplars", + } + .fail() + } + async fn do_query(&self, query: &PromQuery, query_ctx: QueryContextRef) -> Result; /// Executes a query whose statement has already been parsed. diff --git a/src/servers/src/query_handler.rs b/src/servers/src/query_handler.rs index 62aad96c873..9ddc46d4db9 100644 --- a/src/servers/src/query_handler.rs +++ b/src/servers/src/query_handler.rs @@ -41,7 +41,9 @@ use opentelemetry_proto::tonic::collector::logs::v1::ExportLogsServiceRequest; use opentelemetry_proto::tonic::collector::trace::v1::ExportTraceServiceRequest; use operator::insert::PreparedMetricInserts; use otel_arrow_rust::proto::opentelemetry::collector::metrics::v1::ExportMetricsServiceRequest; -use pipeline::{GreptimePipelineParams, Pipeline, PipelineInfo, PipelineVersion, PipelineWay}; +use pipeline::{ + GreptimePipelineParams, Pipeline, PipelineInfo, PipelineOptions, PipelineVersion, PipelineWay, +}; use serde_json::Value; use session::context::{QueryContext, QueryContextRef}; use table::metadata::TableInfoRef; @@ -285,6 +287,9 @@ pub trait PipelineHandler { query_ctx: &QueryContext, ) -> std::result::Result>, catalog::error::Error>; + /// Returns the server's pipeline options. + fn pipeline_options(&self) -> &PipelineOptions; + //// Build a pipeline from a string. fn build_pipeline(&self, pipeline: &str) -> Result; diff --git a/src/servers/tests/interceptor.rs b/src/servers/tests/interceptor.rs index fd516a0dfe5..69759fe0f03 100644 --- a/src/servers/tests/interceptor.rs +++ b/src/servers/tests/interceptor.rs @@ -13,6 +13,7 @@ // limitations under the License. use std::borrow::Cow; +use std::sync::Arc; use api::v1::greptime_request::Request; use api::v1::{InsertRequest, InsertRequests}; @@ -21,9 +22,13 @@ use common_query::Output; use datafusion_expr::LogicalPlan; use query::parser::PromQuery; use servers::error::{self, InternalSnafu, NotSupportedSnafu, Result}; -use servers::interceptor::{GrpcQueryInterceptor, PromQueryInterceptor, SqlQueryInterceptor}; +use servers::exemplar::query::Query as ExemplarQuery; +use servers::interceptor::{ + GrpcQueryInterceptor, PromQueryInterceptor, PromQueryInterceptorRef, SqlQueryInterceptor, +}; use session::context::{QueryContext, QueryContextRef}; use snafu::ensure; +use table::table_reference::TableReference; pub struct NoopInterceptor; @@ -110,6 +115,49 @@ impl PromQueryInterceptor for NoopInterceptor { _ => Ok(output), } } + + fn pre_execute_exemplars( + &self, + query: &ExemplarQuery, + _table: TableReference<'_>, + _query_ctx: QueryContextRef, + ) -> Result<()> { + match query.expression.as_str() { + "up" => InternalSnafu { err_msg: "test" }.fail(), + _ => Ok(()), + } + } +} + +#[test] +fn test_exemplar_interceptor_wrappers() { + let interceptor: Option> = + Some(Arc::new(NoopInterceptor)); + let table = TableReference::bare("greptime_metrics_exemplars"); + for expression in ["up", "down"] { + let query = ExemplarQuery::parse(expression.into(), "0", "1", "public").unwrap(); + assert_eq!( + interceptor + .pre_execute_exemplars(&query, table, QueryContext::arc()) + .is_err(), + expression == "up", + ); + assert_eq!( + interceptor + .as_ref() + .pre_execute_exemplars(&query, table, QueryContext::arc()) + .is_err(), + expression == "up", + ); + let absent: Option> = None; + absent + .pre_execute_exemplars(&query, table, QueryContext::arc()) + .unwrap(); + absent + .as_ref() + .pre_execute_exemplars(&query, table, QueryContext::arc()) + .unwrap(); + } } #[test] diff --git a/src/sql/src/parsers/create_parser/json.rs b/src/sql/src/parsers/create_parser/json.rs index d13ea0fa53f..e75bbef8911 100644 --- a/src/sql/src/parsers/create_parser/json.rs +++ b/src/sql/src/parsers/create_parser/json.rs @@ -14,6 +14,7 @@ use datatypes::extension::json::JSON2_REMAINDER_FIELD_NAME; use datatypes::json::JSON2_MAX_STRUCTURED_DEPTH; +use datatypes::schema::FulltextOptions; use snafu::{ResultExt, ensure}; use sqlparser::ast::{DataType, ExactNumberInfo, ObjectName}; use sqlparser::dialect::keywords::Keyword; @@ -24,6 +25,7 @@ use crate::ast::Ident; use crate::dialect::GreptimeDbDialect; use crate::error::{InvalidSqlSnafu, Result, SyntaxSnafu}; use crate::parsers::create_parser::{INVERTED, SKIPPING}; +use crate::statements::OptionMap; use crate::statements::create::{Json2Options, JsonTypeHint}; const JSON2_TYPE_NAME: &str = "JSON2"; @@ -158,6 +160,7 @@ fn parse_json2_type_hint(parser: &mut Parser<'_>) -> Result { let mut inverted_index = false; let mut skipping_index = None; + let mut fulltext_index = None; loop { if parser.parse_keywords(&[Keyword::NOT, Keyword::NULL]) @@ -238,10 +241,47 @@ fn parse_json2_type_hint(parser: &mut Parser<'_>) -> Result { } skipping_index = Some( datatypes::schema::SkippingIndexOptions::try_from( - crate::statements::OptionMap::new(options).into_map(), + OptionMap::new(options).into_map(), ) .context(crate::error::SetSkippingIndexOptionSnafu)?, ); + } else if parser.parse_keyword(Keyword::FULLTEXT) { + ensure!( + matches!(data_type, DataType::String(None)), + InvalidSqlSnafu { + msg: "JSON2 FULLTEXT index only supports string type hints", + } + ); + ensure!( + parser.parse_keyword(Keyword::INDEX), + InvalidSqlSnafu { + msg: "expect INDEX after FULLTEXT keyword", + } + ); + ensure!( + fulltext_index.is_none(), + InvalidSqlSnafu { + msg: "duplicated FULLTEXT INDEX option for JSON2 type hint", + } + ); + let options = parser + .parse_options(Keyword::WITH) + .context(SyntaxSnafu)? + .into_iter() + .map(crate::util::parse_option_string) + .collect::>>()?; + for (key, _) in &options { + ensure!( + crate::parsers::utils::validate_column_fulltext_create_option(key), + InvalidSqlSnafu { + msg: format!("invalid FULLTEXT INDEX option: {key}") + } + ); + } + fulltext_index = Some( + FulltextOptions::try_from(OptionMap::new(options).into_map()) + .context(crate::error::SetFulltextOptionSnafu)?, + ); } else if matches!(parser.peek_token().token, Token::Comma | Token::RParen) { break; } else { @@ -256,6 +296,7 @@ fn parse_json2_type_hint(parser: &mut Parser<'_>) -> Result { data_type, inverted_index, skipping_index, + fulltext_index, }) } @@ -341,6 +382,64 @@ mod tests { create_table.columns.remove(0) } + #[test] + fn test_json2_fulltext_index() { + use datatypes::schema::FulltextBackend; + for (options, backend) in [ + ("", FulltextBackend::Bloom), + ( + "WITH (backend='tantivy', analyzer='Chinese', case_sensitive='true')", + FulltextBackend::Tantivy, + ), + ( + "WITH (backend='bloom', granularity='8', false_positive_rate='0.05')", + FulltextBackend::Bloom, + ), + ] { + let sql = format!( + "CREATE TABLE logs (attrs JSON2 (message STRING FULLTEXT INDEX {options} SKIPPING INDEX INVERTED INDEX), ts TIMESTAMP TIME INDEX)" + ); + let column = parse_json2_column(&sql); + let options = column.extensions.json2_options.unwrap(); + let settings = options.build_json_settings().unwrap(); + let hint = &settings.type_hints()[0]; + assert_eq!(hint.fulltext_index.as_ref().unwrap().backend, backend); + assert!(hint.fulltext_index.as_ref().unwrap().enable); + assert!(hint.inverted_index); + assert!(hint.skipping_index.is_some()); + let rebuilt = parse_json2_column(&format!( + "CREATE TABLE logs (attrs JSON2 {options}, ts TIMESTAMP TIME INDEX)" + )); + assert_eq!( + settings, + rebuilt + .extensions + .json2_options + .unwrap() + .build_json_settings() + .unwrap() + ); + } + for hint in [ + "message BIGINT FULLTEXT INDEX", + "message STRING FULLTEXT INDEX FULLTEXT INDEX", + "message STRING FULLTEXT", + "message STRING FULLTEXT INDEX WITH (analyzer='unknown')", + "message STRING FULLTEXT INDEX WITH (backend='unknown')", + "message STRING FULLTEXT INDEX WITH (granularity='0')", + "message STRING FULLTEXT INDEX WITH (false_positive_rate='0')", + "message STRING FULLTEXT INDEX WITH (unknown='1')", + ] { + let sql = format!("CREATE TABLE logs (attrs JSON2 ({hint}), ts TIMESTAMP TIME INDEX)"); + let parsed = ParserContext::create_with_dialect( + &sql, + &GreptimeDbDialect {}, + ParseOptions::default(), + ); + assert!(parsed.is_err(), "{sql}"); + } + } + #[test] fn test_json2_skipping_index() { let column = parse_json2_column( diff --git a/src/sql/src/statements.rs b/src/sql/src/statements.rs index ffb00eba313..67233cce671 100644 --- a/src/sql/src/statements.rs +++ b/src/sql/src/statements.rs @@ -734,6 +734,7 @@ mod tests { data_type: ConcreteDataType::string_datatype(), inverted_index: false, skipping_index: None, + fulltext_index: None, }], None, )?)?; diff --git a/src/sql/src/statements/create.rs b/src/sql/src/statements/create.rs index d01ac85a5de..e0130613c01 100644 --- a/src/sql/src/statements/create.rs +++ b/src/sql/src/statements/create.rs @@ -210,6 +210,24 @@ impl Display for Json2Options { options.index_type )?; } + if let Some(options) = &hint.fulltext_index + && options.enable + { + write!( + f, + " FULLTEXT INDEX WITH (analyzer = '{}', case_sensitive = '{}', backend = '{}'", + options.analyzer, options.case_sensitive, options.backend + )?; + if options.backend == datatypes::schema::FulltextBackend::Bloom { + write!( + f, + ", granularity = '{}', false_positive_rate = '{}'", + options.granularity, + options.false_positive_rate() + )?; + } + f.write_char(')')?; + } if hint.inverted_index { f.write_str(" INVERTED INDEX")?; } @@ -229,6 +247,7 @@ impl Json2Options { data_type: sql_data_type_to_concrete_data_type(&hint.data_type)?, inverted_index: hint.inverted_index, skipping_index: hint.skipping_index.clone(), + fulltext_index: hint.fulltext_index.clone(), }) }) .collect::>>()?; @@ -246,6 +265,8 @@ pub struct JsonTypeHint { pub inverted_index: bool, /// Skipping index options for this hinted path. pub skipping_index: Option, + /// Fulltext index options for a string hinted path. + pub fulltext_index: Option, } impl Column { @@ -367,6 +388,7 @@ impl ColumnExtensions { data_type, inverted_index: hint.inverted_index, skipping_index: hint.skipping_index, + fulltext_index: hint.fulltext_index, }) }) .collect::>>()?; @@ -832,6 +854,7 @@ mod tests { data_type: DataType::Text, inverted_index: true, skipping_index: None, + fulltext_index: None, }], }); assert!(!create.consume_sql_size_budget(&mut 4096)); @@ -853,6 +876,7 @@ mod tests { data_type: DataType::Text, inverted_index: false, skipping_index: None, + fulltext_index: None, }], }; assert_eq!( @@ -1179,30 +1203,35 @@ ENGINE=mito data_type: ConcreteDataType::int64_datatype(), inverted_index: false, skipping_index: None, + fulltext_index: None, }, DatatypeJsonTypeHint { path: vec!["f".to_string()], data_type: ConcreteDataType::float64_datatype(), inverted_index: false, skipping_index: None, + fulltext_index: None, }, DatatypeJsonTypeHint { path: vec!["u".to_string()], data_type: ConcreteDataType::uint64_datatype(), inverted_index: false, skipping_index: None, + fulltext_index: None, }, DatatypeJsonTypeHint { path: vec!["s".to_string()], data_type: ConcreteDataType::string_datatype(), inverted_index: false, skipping_index: None, + fulltext_index: None, }, DatatypeJsonTypeHint { path: vec!["b".to_string()], data_type: ConcreteDataType::boolean_datatype(), inverted_index: false, skipping_index: None, + fulltext_index: None, }, ], None, @@ -1230,6 +1259,7 @@ ENGINE=mito data_type: ConcreteDataType::date_datatype(), inverted_index: false, skipping_index: None, + fulltext_index: None, }], None, ) diff --git a/src/standalone/src/information_extension.rs b/src/standalone/src/information_extension.rs index 44fc266c5be..083fabadeb8 100644 --- a/src/standalone/src/information_extension.rs +++ b/src/standalone/src/information_extension.rs @@ -138,7 +138,7 @@ impl InformationExtension for StandaloneInformationExtension { data_topic_latest_entry_id: region_stat.data_topic_latest_entry_id, metadata_topic_latest_entry_id: region_stat.metadata_topic_latest_entry_id, 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, min_timestamp: region_stat.min_timestamp, diff --git a/src/standalone/src/options.rs b/src/standalone/src/options.rs index 4bc10b61cf2..fe7d91371d0 100644 --- a/src/standalone/src/options.rs +++ b/src/standalone/src/options.rs @@ -328,13 +328,17 @@ concurrent_query_limiter_timeout = "250ms""#, } #[test] - fn test_pipeline_host_access_config_forwarding() { + fn test_pipeline_config_forwarding() { let defaults: StandaloneOptions = toml::from_str("").unwrap(); assert!(!defaults.pipeline.allow_vrl_host_access); assert!(!defaults.frontend_options().pipeline.allow_vrl_host_access); + assert!(!defaults.pipeline.ignore_errors); + assert!(!defaults.frontend_options().pipeline.ignore_errors); let options: StandaloneOptions = - 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.frontend_options().pipeline.allow_vrl_host_access); + assert!(options.frontend_options().pipeline.ignore_errors); let serialized = toml::to_string(&options).unwrap(); let restored: StandaloneOptions = toml::from_str(&serialized).unwrap(); assert_eq!(options.pipeline, restored.pipeline); diff --git a/src/store-api/src/compaction_task.rs b/src/store-api/src/compaction_task.rs new file mode 100644 index 00000000000..6dffb34d6aa --- /dev/null +++ b/src/store-api/src/compaction_task.rs @@ -0,0 +1,625 @@ +// 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 common_recordbatch::DfRecordBatch; +use common_recordbatch::filter::MetadataFilter; +use common_time::Timestamp; +use common_time::timestamp::TimeUnit; +use datafusion_common::{DataFusionError, ScalarValue}; +use datafusion_expr::LogicalPlan; +use datatypes::arrow::array::{ + ArrayRef, StringArray, TimestampMillisecondArray, TimestampNanosecondArray, UInt32Array, + UInt64Array, +}; +use datatypes::arrow::datatypes::SchemaRef as ArrowSchemaRef; +use datatypes::arrow::error::ArrowError; +use datatypes::schema::{ColumnSchema, Schema, SchemaRef}; + +use crate::inspect::{self, ProjectedBatchBuilder}; +use crate::storage::{RegionId, ScanRequest, TableId}; + +// Compaction task column names. +pub const TASK_ID: &str = "task_id"; +pub const REGION_ID: &str = "region_id"; +pub const TABLE_ID: &str = "table_id"; +pub const NODE_ID: &str = "node_id"; +pub const TRIGGER_TYPE: &str = "trigger_type"; +pub const STATE: &str = "state"; +pub const PHASE: &str = "phase"; +pub const SUBMITTED_AT: &str = "submitted_at"; +pub const ELAPSED_MILLIS: &str = "elapsed_millis"; +pub const INPUT_FILES: &str = "input_files"; +pub const INPUT_BYTES: &str = "input_bytes"; +pub const TOTAL_UNITS: &str = "total_units"; +pub const COMPLETED_UNITS: &str = "completed_units"; +pub const REQUEST_OPTIONS: &str = "request_options"; +pub const EFFECTIVE_OPTIONS: &str = "effective_options"; +pub const INPUT_TIME_START: &str = "input_time_start"; +pub const INPUT_TIME_END: &str = "input_time_end"; +pub const OUTPUT_TIME_START: &str = "output_time_start"; +pub const OUTPUT_TIME_END: &str = "output_time_end"; + +/// Queued compaction cycle. +pub const STATE_QUEUED: &str = "queued"; +/// Running compaction cycle. +pub const STATE_RUNNING: &str = "running"; +/// Compaction cycle with cancellation requested. +pub const STATE_CANCELLING: &str = "cancelling"; +/// Cycle waiting for execution. +pub const PHASE_WAITING: &str = "waiting"; +/// Cycle selecting a compaction plan. +pub const PHASE_PLANNING: &str = "planning"; +/// Cycle executing local compaction units. +pub const PHASE_EXECUTING: &str = "executing"; +/// Cycle committing compaction output. +pub const PHASE_COMMITTING: &str = "committing"; +/// Cycle executing through a remote compactor. +pub const PHASE_REMOTE: &str = "remote"; +/// Compaction requested manually. +pub const TRIGGER_TYPE_MANUAL: &str = "manual"; +/// Compaction triggered automatically. +pub const TRIGGER_TYPE_AUTOMATIC: &str = "automatic"; + +/// A live region-level compaction cycle. Completed cycles are not retained. +/// +/// String fields are shared so cloning a snapshot does not copy parameter payloads. +/// Time ranges are envelopes and may contain holes. SQL endpoints are NULL when +/// unknown, unbounded, or outside the representable nanosecond timestamp range. +#[derive(Debug, Clone)] +pub struct CompactionTaskEntry { + /// UUID retained from acceptance until this cycle leaves the scheduler. + pub task_id: Arc, + /// Physical region whose scheduler owns this cycle. + pub region_id: RegionId, + /// Physical table ID derived from the region ID. + pub table_id: TableId, + /// Reporting datanode ID (0 in standalone), not the remote executor ID. + pub node_id: Option, + /// Whether this cycle was triggered automatically or manually. + pub trigger_type: Arc, + /// Queued, running, or cancelling, aggregated across the cycle. + pub state: Arc, + /// Phase label: `waiting`, `planning`, `executing`, `committing`, or `remote`. + pub phase: Arc, + /// Acceptance time in milliseconds since the Unix epoch. + pub submitted_at: i64, + /// Monotonic elapsed time since acceptance, including waiting. + pub elapsed_millis: u64, + /// Distinct plan input files, including expired SSTs; unknown before plan acceptance. + pub input_files: Option, + /// Total size of plan inputs, including expired SSTs; not bytes processed. + pub input_bytes: Option, + /// Number of local atomic units; unavailable for remote execution. + pub total_units: Option, + /// Local units with a terminal result, including failures. + pub completed_units: Option, + /// JSON snapshot of request arguments, including requested parallelism. + pub request_options: Arc, + /// JSON snapshot of resolved settings and picker output, if available. + pub effective_options: Option>, + /// Inclusive earliest timestamp in plan input SSTs, including expired SSTs. + pub input_time_start: Option, + /// Inclusive latest timestamp in plan input SSTs, including expired SSTs. + pub input_time_end: Option, + /// Inclusive start of the planned output envelope, not actual output SST bounds. + pub output_time_start: Option, + /// Exclusive end of the planned output envelope, not actual output SST bounds. + pub output_time_end: Option, +} + +impl CompactionTaskEntry { + /// Returns the public inspection schema. + pub fn schema() -> SchemaRef { + use datatypes::prelude::ConcreteDataType as Ty; + Arc::new(Schema::new(vec![ + ColumnSchema::new(TASK_ID, Ty::string_datatype(), false), + ColumnSchema::new(REGION_ID, Ty::uint64_datatype(), false), + ColumnSchema::new(TABLE_ID, Ty::uint32_datatype(), false), + ColumnSchema::new(NODE_ID, Ty::uint64_datatype(), true), + ColumnSchema::new(TRIGGER_TYPE, Ty::string_datatype(), false), + ColumnSchema::new(STATE, Ty::string_datatype(), false), + ColumnSchema::new(PHASE, Ty::string_datatype(), false), + ColumnSchema::new(SUBMITTED_AT, Ty::timestamp_millisecond_datatype(), false), + ColumnSchema::new(ELAPSED_MILLIS, Ty::uint64_datatype(), false), + ColumnSchema::new(INPUT_FILES, Ty::uint64_datatype(), true), + ColumnSchema::new(INPUT_BYTES, Ty::uint64_datatype(), true), + ColumnSchema::new(TOTAL_UNITS, Ty::uint64_datatype(), true), + ColumnSchema::new(COMPLETED_UNITS, Ty::uint64_datatype(), true), + ColumnSchema::new(REQUEST_OPTIONS, Ty::string_datatype(), false), + ColumnSchema::new(EFFECTIVE_OPTIONS, Ty::string_datatype(), true), + ColumnSchema::new(INPUT_TIME_START, Ty::timestamp_nanosecond_datatype(), true), + ColumnSchema::new(INPUT_TIME_END, Ty::timestamp_nanosecond_datatype(), true), + ColumnSchema::new(OUTPUT_TIME_START, Ty::timestamp_nanosecond_datatype(), true), + ColumnSchema::new(OUTPUT_TIME_END, Ty::timestamp_nanosecond_datatype(), true), + ])) + } + + /// Prunes using known values, leaving unsupported predicates to DataFusion. + pub fn matches(&self, filters: &MetadataFilter) -> bool { + filters.matches(|name| { + Some(match name { + TASK_ID => ScalarValue::Utf8(Some(self.task_id.to_string())), + REGION_ID => ScalarValue::UInt64(Some(self.region_id.as_u64())), + TABLE_ID => ScalarValue::UInt32(Some(self.table_id)), + NODE_ID => ScalarValue::UInt64(self.node_id), + TRIGGER_TYPE => ScalarValue::Utf8(Some(self.trigger_type.to_string())), + STATE => ScalarValue::Utf8(Some(self.state.to_string())), + PHASE => ScalarValue::Utf8(Some(self.phase.to_string())), + SUBMITTED_AT => ScalarValue::TimestampMillisecond(Some(self.submitted_at), None), + ELAPSED_MILLIS => ScalarValue::UInt64(Some(self.elapsed_millis)), + INPUT_FILES => ScalarValue::UInt64(self.input_files), + INPUT_BYTES => ScalarValue::UInt64(self.input_bytes), + TOTAL_UNITS => ScalarValue::UInt64(self.total_units), + COMPLETED_UNITS => ScalarValue::UInt64(self.completed_units), + REQUEST_OPTIONS => ScalarValue::Utf8(Some(self.request_options.to_string())), + EFFECTIVE_OPTIONS => { + ScalarValue::Utf8(self.effective_options.as_deref().map(str::to_string)) + } + INPUT_TIME_START => { + ScalarValue::TimestampNanosecond(timestamp_nanos(self.input_time_start), None) + } + INPUT_TIME_END => { + ScalarValue::TimestampNanosecond(timestamp_nanos(self.input_time_end), None) + } + OUTPUT_TIME_START => { + ScalarValue::TimestampNanosecond(timestamp_nanos(self.output_time_start), None) + } + OUTPUT_TIME_END => { + ScalarValue::TimestampNanosecond(timestamp_nanos(self.output_time_end), None) + } + _ => return None, + }) + }) + } + + /// Converts compaction task entries to a record batch. + pub fn to_record_batch(entries: &[Self]) -> Result { + Self::to_projected_record_batch(entries, None) + } + + /// Builds only the requested columns, including empty and repeated projections. + fn to_projected_record_batch( + entries: &[Self], + projection: Option<&[usize]>, + ) -> Result { + let schema = Self::schema().arrow_schema().clone(); + let schema = match projection { + Some(projection) => Arc::new(schema.project(projection)?), + None => schema, + }; + CompactionTaskBatchBuilder::new(schema).build(entries) + } + + /// Internal name, inaccessible through user table resolution. + pub fn reserved_table_name_for_inspection() -> &'static str { + "__inspect/__mito/__compaction_tasks" + } + + /// Builds a remote scan with filtering before projection and limit. + pub fn build_plan(request: ScanRequest) -> Result { + inspect::build_plan( + request, + Self::reserved_table_name_for_inspection(), + Self::schema(), + ) + } +} + +/// Converts compaction task batches using a schema prepared once per scan. +/// Repeated projected columns share the same Arrow array. +pub struct CompactionTaskBatchBuilder { + projected: ProjectedBatchBuilder, +} + +impl CompactionTaskBatchBuilder { + /// Creates a builder for a projected compaction task schema. + pub fn new(schema: ArrowSchemaRef) -> Self { + Self { + projected: ProjectedBatchBuilder::new(schema), + } + } + + /// Builds the projected columns, copying string contents only into Arrow buffers. + pub fn build(&self, entries: &[CompactionTaskEntry]) -> Result { + self.projected.build(entries.len(), |name| { + let array: ArrayRef = match name { + TASK_ID => Arc::new(StringArray::from_iter_values( + entries.iter().map(|e| e.task_id.as_ref()), + )), + REGION_ID => Arc::new(UInt64Array::from_iter_values( + entries.iter().map(|e| e.region_id.as_u64()), + )), + TABLE_ID => Arc::new(UInt32Array::from_iter_values( + entries.iter().map(|e| e.table_id), + )), + NODE_ID => Arc::new(UInt64Array::from_iter(entries.iter().map(|e| e.node_id))), + TRIGGER_TYPE => Arc::new(StringArray::from_iter_values( + entries.iter().map(|e| e.trigger_type.as_ref()), + )), + STATE => Arc::new(StringArray::from_iter_values( + entries.iter().map(|e| e.state.as_ref()), + )), + PHASE => Arc::new(StringArray::from_iter_values( + entries.iter().map(|e| e.phase.as_ref()), + )), + SUBMITTED_AT => Arc::new(TimestampMillisecondArray::from_iter_values( + entries.iter().map(|e| e.submitted_at), + )), + ELAPSED_MILLIS => Arc::new(UInt64Array::from_iter_values( + entries.iter().map(|e| e.elapsed_millis), + )), + INPUT_FILES => Arc::new(UInt64Array::from_iter( + entries.iter().map(|e| e.input_files), + )), + INPUT_BYTES => Arc::new(UInt64Array::from_iter( + entries.iter().map(|e| e.input_bytes), + )), + TOTAL_UNITS => Arc::new(UInt64Array::from_iter( + entries.iter().map(|e| e.total_units), + )), + COMPLETED_UNITS => Arc::new(UInt64Array::from_iter( + entries.iter().map(|e| e.completed_units), + )), + REQUEST_OPTIONS => Arc::new(StringArray::from_iter_values( + entries.iter().map(|e| e.request_options.as_ref()), + )), + EFFECTIVE_OPTIONS => Arc::new(StringArray::from_iter( + entries.iter().map(|e| e.effective_options.as_deref()), + )), + INPUT_TIME_START => Arc::new(TimestampNanosecondArray::from_iter( + entries.iter().map(|e| timestamp_nanos(e.input_time_start)), + )), + INPUT_TIME_END => Arc::new(TimestampNanosecondArray::from_iter( + entries.iter().map(|e| timestamp_nanos(e.input_time_end)), + )), + OUTPUT_TIME_START => Arc::new(TimestampNanosecondArray::from_iter( + entries.iter().map(|e| timestamp_nanos(e.output_time_start)), + )), + OUTPUT_TIME_END => Arc::new(TimestampNanosecondArray::from_iter( + entries.iter().map(|e| timestamp_nanos(e.output_time_end)), + )), + _ => { + return Err(ArrowError::SchemaError(format!( + "Unknown compaction task column: {name}" + ))); + } + }; + Ok(array) + }) + } +} + +/// Converts endpoints identically for predicate pruning and Arrow output. +fn timestamp_nanos(timestamp: Option) -> Option { + timestamp + .and_then(|ts| ts.convert_to(TimeUnit::Nanosecond)) + .map(|ts| ts.value()) +} + +#[cfg(test)] +mod tests { + use datafusion_expr::{col, lit}; + use datatypes::arrow::datatypes::DataType; + + use super::*; + + fn entry() -> CompactionTaskEntry { + CompactionTaskEntry { + task_id: "task-1".into(), + region_id: RegionId::new(1, 42), + table_id: 1, + node_id: Some(7), + trigger_type: "manual".into(), + state: "queued".into(), + phase: "waiting".into(), + submitted_at: 123, + elapsed_millis: 10, + input_files: Some(3), + input_bytes: Some(4096), + total_units: Some(5), + completed_units: Some(2), + request_options: "{\"request\":1}".into(), + effective_options: Some("{\"effective\":2}".into()), + input_time_start: Some(Timestamp::new_nanosecond(11)), + input_time_end: Some(Timestamp::new_nanosecond(22)), + output_time_start: Some(Timestamp::new_nanosecond(33)), + output_time_end: Some(Timestamp::new_nanosecond(44)), + } + } + + #[test] + fn test_compaction_task_clone_shares_strings() { + let entry = entry(); + let cloned = entry.clone(); + for (original, cloned) in [ + (&entry.task_id, &cloned.task_id), + (&entry.trigger_type, &cloned.trigger_type), + (&entry.state, &cloned.state), + (&entry.phase, &cloned.phase), + (&entry.request_options, &cloned.request_options), + ( + entry.effective_options.as_ref().unwrap(), + cloned.effective_options.as_ref().unwrap(), + ), + ] { + assert!(Arc::ptr_eq(original, cloned)); + } + assert_eq!( + CompactionTaskEntry::to_record_batch(&[entry]).unwrap(), + CompactionTaskEntry::to_record_batch(&[cloned]).unwrap() + ); + } + + #[test] + fn test_compaction_task_column_values_and_predicates() { + let entry = entry(); + let batch = CompactionTaskEntry::to_record_batch(std::slice::from_ref(&entry)).unwrap(); + // Independent SQL contract values distinguish every same-typed field. + let expected = [ + ("task_id", ScalarValue::Utf8(Some("task-1".into()))), + ("region_id", ScalarValue::UInt64(Some(4_294_967_338))), + ("table_id", ScalarValue::UInt32(Some(1))), + ("node_id", ScalarValue::UInt64(Some(7))), + ("trigger_type", ScalarValue::Utf8(Some("manual".into()))), + ("state", ScalarValue::Utf8(Some("queued".into()))), + ("phase", ScalarValue::Utf8(Some("waiting".into()))), + ( + "submitted_at", + ScalarValue::TimestampMillisecond(Some(123), None), + ), + ("elapsed_millis", ScalarValue::UInt64(Some(10))), + ("input_files", ScalarValue::UInt64(Some(3))), + ("input_bytes", ScalarValue::UInt64(Some(4096))), + ("total_units", ScalarValue::UInt64(Some(5))), + ("completed_units", ScalarValue::UInt64(Some(2))), + ( + "request_options", + ScalarValue::Utf8(Some("{\"request\":1}".into())), + ), + ( + "effective_options", + ScalarValue::Utf8(Some("{\"effective\":2}".into())), + ), + ( + "input_time_start", + ScalarValue::TimestampNanosecond(Some(11), None), + ), + ( + "input_time_end", + ScalarValue::TimestampNanosecond(Some(22), None), + ), + ( + "output_time_start", + ScalarValue::TimestampNanosecond(Some(33), None), + ), + ( + "output_time_end", + ScalarValue::TimestampNanosecond(Some(44), None), + ), + ]; + assert_eq!(batch.num_columns(), expected.len()); + for (index, (name, value)) in expected.into_iter().enumerate() { + assert_eq!(batch.schema().field(index).name(), name); + assert_eq!( + ScalarValue::try_from_array(batch.column(index), 0).unwrap(), + value, + "{name}" + ); + assert!( + entry.matches(&MetadataFilter::new(&[col(name).eq(lit(value.clone()))])), + "{name}" + ); + let different = match &value { + ScalarValue::Utf8(Some(value)) => ScalarValue::Utf8(Some(format!("{value}-other"))), + ScalarValue::UInt32(Some(value)) => ScalarValue::UInt32(Some(value + 1)), + ScalarValue::UInt64(Some(value)) => ScalarValue::UInt64(Some(value + 1)), + ScalarValue::TimestampMillisecond(Some(value), timezone) => { + ScalarValue::TimestampMillisecond(Some(value + 1), timezone.clone()) + } + ScalarValue::TimestampNanosecond(Some(value), timezone) => { + ScalarValue::TimestampNanosecond(Some(value + 1), timezone.clone()) + } + unexpected => panic!("unexpected contract value for {name}: {unexpected:?}"), + }; + assert!( + !entry.matches(&MetadataFilter::new(&[col(name).eq(lit(different))])), + "{name}" + ); + assert!( + !entry.matches(&MetadataFilter::new(&[col(name).not_eq(lit(value))])), + "{name}" + ); + } + } + + #[test] + fn test_compaction_task_schema_and_projection() { + let entries = [entry()]; + let full = CompactionTaskEntry::to_record_batch(&entries).unwrap(); + let fields: Vec<_> = full + .schema() + .fields() + .iter() + .map(|f| (f.name().clone(), f.data_type().clone(), f.is_nullable())) + .collect(); + let expected = [ + ("task_id", DataType::Utf8, false), + ("region_id", DataType::UInt64, false), + ("table_id", DataType::UInt32, false), + ("node_id", DataType::UInt64, true), + ("trigger_type", DataType::Utf8, false), + ("state", DataType::Utf8, false), + ("phase", DataType::Utf8, false), + ( + "submitted_at", + DataType::Timestamp(datatypes::arrow::datatypes::TimeUnit::Millisecond, None), + false, + ), + ("elapsed_millis", DataType::UInt64, false), + ("input_files", DataType::UInt64, true), + ("input_bytes", DataType::UInt64, true), + ("total_units", DataType::UInt64, true), + ("completed_units", DataType::UInt64, true), + ("request_options", DataType::Utf8, false), + ("effective_options", DataType::Utf8, true), + ( + "input_time_start", + DataType::Timestamp(datatypes::arrow::datatypes::TimeUnit::Nanosecond, None), + true, + ), + ( + "input_time_end", + DataType::Timestamp(datatypes::arrow::datatypes::TimeUnit::Nanosecond, None), + true, + ), + ( + "output_time_start", + DataType::Timestamp(datatypes::arrow::datatypes::TimeUnit::Nanosecond, None), + true, + ), + ( + "output_time_end", + DataType::Timestamp(datatypes::arrow::datatypes::TimeUnit::Nanosecond, None), + true, + ), + ] + .map(|(name, ty, nullable)| (name.to_string(), ty, nullable)); + assert_eq!(fields, expected); + for projection in [ + vec![], + vec![5, 0, 5], + vec![14, 3, 8], + vec![18, 15, 17, 16, 15], + ] { + let actual = + CompactionTaskEntry::to_projected_record_batch(&entries, Some(&projection)) + .unwrap(); + assert_eq!(actual, full.project(&projection).unwrap()); + assert_eq!(actual.num_rows(), 1); + } + assert!(CompactionTaskEntry::to_projected_record_batch(&entries, Some(&[99])).is_err()); + let projected_schema = Arc::new(full.schema().project(&[0, 9, 0, 18, 9]).unwrap()); + let builder = CompactionTaskBatchBuilder::new(projected_schema.clone()); + for rows in [entries.as_slice(), &entries[..0]] { + let projected = builder.build(rows).unwrap(); + assert_eq!( + projected, + CompactionTaskEntry::to_record_batch(rows) + .unwrap() + .project(&[0, 9, 0, 18, 9]) + .unwrap() + ); + assert!(Arc::ptr_eq(&projected.schema(), &projected_schema)); + assert!(Arc::ptr_eq(projected.column(0), projected.column(2))); + assert!(Arc::ptr_eq(projected.column(1), projected.column(4))); + } + } + + #[test] + fn test_compaction_task_time_ranges_precision_and_nulls() { + let precise = CompactionTaskEntry { + input_time_start: Some(Timestamp::new(-2, TimeUnit::Second)), + input_time_end: Some(Timestamp::new(3, TimeUnit::Millisecond)), + output_time_start: Some(Timestamp::new(-4, TimeUnit::Microsecond)), + output_time_end: Some(Timestamp::new(5, TimeUnit::Nanosecond)), + ..entry() + }; + let overflow = CompactionTaskEntry { + input_time_start: Some(Timestamp::new(i64::MIN, TimeUnit::Second)), + input_time_end: Some(Timestamp::new(i64::MAX, TimeUnit::Second)), + output_time_start: Some(Timestamp::new(i64::MIN, TimeUnit::Millisecond)), + output_time_end: Some(Timestamp::new(i64::MAX, TimeUnit::Microsecond)), + ..entry() + }; + let unknown = CompactionTaskEntry { + input_time_start: None, + input_time_end: None, + output_time_start: None, + output_time_end: None, + ..entry() + }; + let entries = [precise, overflow, unknown]; + let batch = + CompactionTaskEntry::to_projected_record_batch(&entries, Some(&[15, 16, 17, 18])) + .unwrap(); + for (index, (name, nanos)) in [ + ("input_time_start", -2_000_000_000), + ("input_time_end", 3_000_000), + ("output_time_start", -4_000), + ("output_time_end", 5), + ] + .into_iter() + .enumerate() + { + let values = batch + .column(index) + .as_any() + .downcast_ref::() + .unwrap(); + assert_eq!( + values, + &TimestampNanosecondArray::from(vec![Some(nanos), None, None]) + ); + let equal = col(name).eq(lit(ScalarValue::TimestampNanosecond(Some(nanos), None))); + let different = + col(name).eq(lit(ScalarValue::TimestampNanosecond(Some(nanos + 1), None))); + assert!(entries[0].matches(&MetadataFilter::new(std::slice::from_ref(&equal)))); + assert!(!entries[0].matches(&MetadataFilter::new(&[different]))); + assert!(!entries[0].matches(&MetadataFilter::new(&[col(name).is_null()]))); + for entry in &entries[1..] { + assert!(entry.matches(&MetadataFilter::new(&[col(name).is_null()]))); + assert!(!entry.matches(&MetadataFilter::new(&[col(name).is_not_null()]))); + assert!(!entry.matches(&MetadataFilter::new(std::slice::from_ref(&equal)))); + } + } + let full = CompactionTaskEntry::to_record_batch(&entries).unwrap(); + let projection = [18, 16, 15, 18, 17]; + assert_eq!( + CompactionTaskEntry::to_projected_record_batch(&entries, Some(&projection)).unwrap(), + full.project(&projection).unwrap() + ); + } + + #[test] + fn test_compaction_task_predicates_and_plan() { + let entry = entry(); + for (expr, expected) in [ + (col("task_id").eq(lit("task-1")), true), + (col("table_id").eq(lit(2u32)), false), + (col("state").eq(lit("running")), false), + (col("node_id").is_null(), false), + ( + col("state") + .eq(lit("running")) + .or(col("unknown").eq(lit(1))), + true, + ), + ] { + assert_eq!(entry.matches(&MetadataFilter::new(&[expr])), expected); + } + let plan = CompactionTaskEntry::build_plan(ScanRequest { + projection: Some(vec![0]), + filters: vec![col("state").eq(lit("running"))], + limit: Some(1), + ..Default::default() + }) + .unwrap(); + assert_eq!(plan.schema().fields().len(), 1); + let plan = plan.display_indent().to_string(); + assert!(plan.contains("Filter:"), "{plan}"); + assert!(plan.contains("Limit:"), "{plan}"); + } +} diff --git a/src/store-api/src/inspect.rs b/src/store-api/src/inspect.rs new file mode 100644 index 00000000000..d68283a89de --- /dev/null +++ b/src/store-api/src/inspect.rs @@ -0,0 +1,104 @@ +// 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 common_recordbatch::DfRecordBatch; +use datafusion_common::DataFusionError; +use datafusion_expr::{LogicalPlan, LogicalPlanBuilder, LogicalTableSource}; +use datatypes::arrow::array::ArrayRef; +use datatypes::arrow::datatypes::SchemaRef as ArrowSchemaRef; +use datatypes::arrow::error::ArrowError; +use datatypes::arrow::record_batch::RecordBatchOptions; +use datatypes::schema::SchemaRef; + +use crate::storage::ScanRequest; + +/// Builds projected inspection batches while sharing arrays for repeated columns. +pub(crate) struct ProjectedBatchBuilder { + schema: ArrowSchemaRef, + duplicates: Vec>, +} + +impl ProjectedBatchBuilder { + /// Prepares duplicate-column mappings once per scan. + pub(crate) fn new(schema: ArrowSchemaRef) -> Self { + let duplicates = schema + .fields() + .iter() + .enumerate() + .map(|(index, field)| { + schema.fields()[..index] + .iter() + .position(|previous| previous == field) + }) + .collect(); + Self { schema, duplicates } + } + + /// Builds each distinct projected column once and preserves empty-projection row counts. + pub(crate) fn build( + &self, + row_count: usize, + mut build_column: impl FnMut(&str) -> Result, + ) -> Result { + let mut columns: Vec = Vec::with_capacity(self.schema.fields().len()); + for (index, field) in self.schema.fields().iter().enumerate() { + let array = match self.duplicates[index] { + Some(previous) => columns[previous].clone(), + None => build_column(field.name())?, + }; + columns.push(array); + } + DfRecordBatch::try_new_with_options( + self.schema.clone(), + columns, + &RecordBatchOptions::new().with_row_count(Some(row_count)), + ) + } +} + +/// Builds an inspection scan with filtering before projection and limit. +pub(crate) fn build_plan( + scan_request: ScanRequest, + table_name: &str, + schema: SchemaRef, +) -> Result { + let table_source = LogicalTableSource::new(schema.arrow_schema().clone()); + + // Filters may reference columns omitted from the requested output. Apply + // them to the full schema and let the optimizer push the minimal projection. + let projection = scan_request.projection; + let mut builder = LogicalPlanBuilder::scan(table_name, Arc::new(table_source), None)?; + + for filter in scan_request.filters { + builder = builder.filter(filter)?; + } + + if let Some(projection) = projection { + let projected = schema.arrow_schema().project(&projection)?; + builder = builder.project( + projected + .fields() + .iter() + .map(|field| datafusion_expr::col(field.name())), + )?; + } + + if let Some(limit) = scan_request.limit { + builder = builder.limit(0, Some(limit))?; + } + + builder.build() +} diff --git a/src/store-api/src/lib.rs b/src/store-api/src/lib.rs index 30c9ec50f16..7d156388e98 100644 --- a/src/store-api/src/lib.rs +++ b/src/store-api/src/lib.rs @@ -15,7 +15,9 @@ //! Storage related APIs pub mod codec; +pub mod compaction_task; pub mod data_source; +mod inspect; pub mod logstore; pub mod metadata; pub mod metric_engine_consts; diff --git a/src/store-api/src/region_engine.rs b/src/store-api/src/region_engine.rs index 5d7af812685..a2e47640d42 100644 --- a/src/store-api/src/region_engine.rs +++ b/src/store-api/src/region_engine.rs @@ -50,7 +50,7 @@ pub enum SettableRegionRoleState { DowngradingLeader, /// Exit staging mode and return to normal leader state. Only allowed from staging state. Leader, - /// Enter staging mode. Region remains writable but disables checkpoint and compaction. Only allowed from normal leader state. + /// Enter staging mode. Region remains writable but disables checkpoint, compaction and flush. Only allowed from normal leader state. StagingLeader, } @@ -579,7 +579,10 @@ pub struct RegionStatistic { pub memtable_size: u64, /// The size of WAL in bytes. pub wal_size: u64, - /// The size of manifest in bytes. + /// Stored bytes of the latest observed manifest checkpoint and subsequent deltas, + /// compressed when enabled. Excludes staging manifests, `_last_checkpoint`, and + /// superseded files still present on disk. This is a logical recovery-size estimate, + /// not the physical directory usage; observation failures can leave it incomplete. pub manifest_size: u64, /// The size of SST data files owned by this region in bytes. /// @@ -600,12 +603,14 @@ pub struct RegionStatistic { #[serde(default)] /// 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. /// - /// Includes staging flushes, but excludes index files, compaction and imported SSTs. + /// Excludes index files, compaction and imported SSTs. /// Resets when the region instance is recreated; manifest replay does not increment it. - #[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. @@ -801,24 +806,39 @@ mod tests { "written_bytes": 11 }"#; let mut statistic = RegionStatistic::deserialize_from_slice(legacy_bytes).unwrap(); - assert_eq!(statistic.flushed_parquet_bytes, 0); - statistic.flushed_parquet_bytes = 1234; + assert_eq!(statistic.ingested_parquet_bytes, 0); + statistic.ingested_parquet_bytes = 1234; let encoded = statistic.serialize_to_vec().unwrap(); let decoded = RegionStatistic::deserialize_from_slice(&encoded).unwrap(); - assert_eq!(decoded.flushed_parquet_bytes, 1234); + assert_eq!(decoded.ingested_parquet_bytes, 1234); let legacy: serde_json::Value = serde_json::from_slice(legacy_bytes).unwrap(); let mut current: serde_json::Value = serde_json::from_slice(&encoded).unwrap(); + assert_eq!(current["ingested_parquet_bytes"], 1234); + assert!(current.get("flushed_parquet_bytes").is_none()); + let mut old_wire = current.clone(); + let bytes = old_wire + .as_object_mut() + .unwrap() + .remove("ingested_parquet_bytes") + .unwrap(); + old_wire["flushed_parquet_bytes"] = bytes; + assert_eq!( + serde_json::from_value::(old_wire) + .unwrap() + .ingested_parquet_bytes, + 1234 + ); for (key, value) in legacy.as_object().unwrap() { assert_eq!(¤t[key], value); } current .as_object_mut() .unwrap() - .remove("flushed_parquet_bytes"); + .remove("ingested_parquet_bytes"); assert_eq!( serde_json::from_value::(current) .unwrap() - .flushed_parquet_bytes, + .ingested_parquet_bytes, 0 ); } @@ -989,7 +1009,10 @@ pub struct MitoCopyRegionFromRequest { #[derive(Debug, Clone)] pub struct MitoCopyRegionFromResponse { - /// The file ids that were copied from the source region to the target region. + /// Source SST IDs installed in the target by this copy. Shared references may + /// be installed without copying their physical objects. If no new references + /// need installation, returns the source IDs already present in the target. + /// This is not a count or inventory of physical object transfers. pub copied_file_ids: Vec, } diff --git a/src/store-api/src/region_request.rs b/src/store-api/src/region_request.rs index cf98ead1857..f86184fd9f4 100644 --- a/src/store-api/src/region_request.rs +++ b/src/store-api/src/region_request.rs @@ -23,7 +23,7 @@ use api::v1::column_def::{ }; use api::v1::region::bulk_insert_request::Body; use api::v1::region::{ - AlterRequest, AlterRequests, BuildIndexRequest, BulkInsertRequest, + AlterRequest, AlterRequests, BuildIndexRequest, BulkInsertRequest, CancelCompactionRequest, CleanUpRequest as PbCleanUpRequest, CloseRequest, CompactRequest, CreateRequest, CreateRequests, DeleteRequests, DropRequest, DropRequests, FlushRequest, InsertRequests, OpenRequest, TruncateRequest, alter_request, build_index_request, compact_request, @@ -161,6 +161,7 @@ pub enum RegionRequest { Alter(RegionAlterRequest), Flush(RegionFlushRequest), Compact(RegionCompactRequest), + CancelCompaction(RegionCancelCompactionRequest), BuildIndex(RegionBuildIndexRequest), Truncate(RegionTruncateRequest), Catchup(RegionCatchupRequest), @@ -184,6 +185,7 @@ impl RegionRequest { region_request::Body::Alter(alter) => make_region_alter(alter), region_request::Body::Flush(flush) => make_region_flush(flush), region_request::Body::Compact(compact) => make_region_compact(compact), + region_request::Body::CancelCompaction(cancel) => make_region_cancel_compaction(cancel), region_request::Body::BuildIndex(index) => make_region_build_index(index), region_request::Body::Truncate(truncate) => make_region_truncate(truncate), region_request::Body::Creates(creates) => make_region_creates(creates), @@ -448,6 +450,25 @@ fn make_region_compact(compact: CompactRequest) -> Result Result> { + let region_id = cancel.region_id.into(); + ensure!( + !cancel.task_id.trim().is_empty(), + InvalidRegionRequestSnafu { + region_id, + err: "compaction task_id must not be empty".to_string(), + } + ); + Ok(vec![( + region_id, + RegionRequest::CancelCompaction(RegionCancelCompactionRequest { + task_id: cancel.task_id, + }), + )]) +} + fn make_region_build_index(index: BuildIndexRequest) -> Result> { let region_id = index.region_id.into(); Ok(vec![( @@ -1571,6 +1592,16 @@ fn json_settings_from_proto(settings: v1::JsonSettings) -> Result path: hint.path, data_type, inverted_index: hint.inverted_index, + fulltext_index: hint + .fulltext_index + .map(api::v1::column_def::json_fulltext_options_from_proto) + .transpose() + .map_err(|err| { + InvalidRawRegionRequestSnafu { + err: err.to_string(), + } + .build() + })?, skipping_index: hint .skipping_index .map(api::v1::column_def::json_skipping_options_from_proto) @@ -1912,6 +1943,12 @@ pub struct RegionFlushRequest { pub reason: Option, } +/// Cancels one exact live compaction identity without pausing future compactions. +#[derive(Debug)] +pub struct RegionCancelCompactionRequest { + pub task_id: String, +} + #[derive(Debug)] pub struct RegionCompactRequest { pub options: compact_request::Options, @@ -1940,6 +1977,9 @@ pub struct RegionBuildIndexRequest { #[derive(Debug)] pub enum RegionTruncateRequest { /// Truncate all data in the region. + /// + /// Mito2 also retires this region's shared SST references. Other regions and + /// existing readers may still retain the physical objects. All, /// Discard all unflushed data while preserving persisted SST files. /// @@ -1951,6 +1991,8 @@ pub enum RegionTruncateRequest { /// WAL is obsoleted last. Retrying is safe: a request against a region with nothing /// left to discard only re-attempts the WAL obsoletion. Unflushed, + /// Retires fully contained SST references, including shared SSTs in Mito2. + /// Physical reclamation still waits for other references and readers. ByTimeRanges { /// Time ranges to truncate. Both bound are inclusive. /// only files that are fully contained in the time range will be truncated. @@ -2073,6 +2115,7 @@ impl fmt::Display for RegionRequest { RegionRequest::Alter(_) => write!(f, "Alter"), RegionRequest::Flush(_) => write!(f, "Flush"), RegionRequest::Compact(_) => write!(f, "Compact"), + RegionRequest::CancelCompaction(_) => write!(f, "CancelCompaction"), RegionRequest::BuildIndex(_) => write!(f, "BuildIndex"), RegionRequest::Truncate(_) => write!(f, "Truncate"), RegionRequest::Catchup(_) => write!(f, "Catchup"), @@ -2098,6 +2141,35 @@ mod tests { use super::*; use crate::metadata::RegionMetadataBuilder; + #[test] + fn test_cancel_compaction_request_conversion() { + let region_id = RegionId::new(7, 3); + let requests = RegionRequest::try_from_request_body( + region_request::Body::CancelCompaction(CancelCompactionRequest { + region_id: region_id.as_u64(), + task_id: "task-1".to_string(), + }), + ) + .unwrap(); + assert_eq!(requests.len(), 1); + assert_eq!(requests[0].0, region_id); + let RegionRequest::CancelCompaction(request) = &requests[0].1 else { + panic!("expected cancellation") + }; + assert_eq!(request.task_id, "task-1"); + for task_id in ["", " ", "\t\n"] { + assert!( + RegionRequest::try_from_request_body(region_request::Body::CancelCompaction( + CancelCompactionRequest { + region_id: region_id.as_u64(), + task_id: task_id.to_string() + } + )) + .is_err() + ); + } + } + #[test] fn test_build_index_options_round_trip() { use prost::Message; @@ -2532,6 +2604,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), @@ -2617,6 +2690,7 @@ mod tests { data_type: ColumnDataType::String as i32, datatype_extension: None, inverted_index: true, + fulltext_index: None, skipping_index: Some(v1::JsonSkippingIndexOptions { granularity: 8, index_type: 0, diff --git a/src/store-api/src/sst_entry.rs b/src/store-api/src/sst_entry.rs index 6017f26bed3..45f90b80a70 100644 --- a/src/store-api/src/sst_entry.rs +++ b/src/store-api/src/sst_entry.rs @@ -19,7 +19,7 @@ use common_recordbatch::DfRecordBatch; use common_time::Timestamp; use common_time::timestamp::TimeUnit; use datafusion_common::DataFusionError; -use datafusion_expr::{LogicalPlan, LogicalPlanBuilder, LogicalTableSource}; +use datafusion_expr::LogicalPlan; use datatypes::arrow::array::{ ArrayRef, BinaryArray, BooleanArray, TimestampMillisecondArray, TimestampNanosecondArray, UInt8Array, UInt32Array, UInt64Array, @@ -30,6 +30,7 @@ use datatypes::arrow_array::StringArray; use datatypes::schema::{ColumnSchema, Schema, SchemaRef}; use serde::{Deserialize, Serialize}; +use crate::inspect::{self, ProjectedBatchBuilder}; use crate::storage::{RegionGroup, RegionId, RegionNumber, RegionSeq, ScanRequest, TableId}; // Manifest SST column names. @@ -193,7 +194,7 @@ impl ManifestSstEntry { /// Builds a logical plan for scanning the manifest sst entries. pub fn build_plan(scan_request: ScanRequest) -> Result { - build_plan_helper( + inspect::build_plan( scan_request, Self::reserved_table_name_for_inspection(), Self::schema(), @@ -204,24 +205,15 @@ impl ManifestSstEntry { /// Converts manifest SST batches using a schema prepared once per scan. /// Repeated projected columns share the same Arrow array. pub struct ManifestSstBatchBuilder { - schema: ArrowSchemaRef, - duplicates: Vec>, + projected: ProjectedBatchBuilder, } impl ManifestSstBatchBuilder { /// Creates a builder for a projected manifest SST schema. pub fn new(schema: ArrowSchemaRef) -> Self { - let duplicates = schema - .fields() - .iter() - .enumerate() - .map(|(index, field)| { - schema.fields()[..index] - .iter() - .position(|previous| previous == field) - }) - .collect(); - Self { schema, duplicates } + Self { + projected: ProjectedBatchBuilder::new(schema), + } } /// Builds the projected columns, copying string contents only into Arrow buffers. @@ -229,13 +221,8 @@ impl ManifestSstBatchBuilder { &self, entries: &[ManifestSstEntry], ) -> std::result::Result { - let mut columns: Vec = Vec::with_capacity(self.schema.fields().len()); - for (index, field) in self.schema.fields().iter().enumerate() { - if let Some(previous) = self.duplicates[index] { - columns.push(columns[previous].clone()); - continue; - } - let array: ArrayRef = match field.name().as_str() { + self.projected.build(entries.len(), |name| { + let array: ArrayRef = match name { TABLE_DIR => Arc::new(StringArray::from_iter_values( entries.iter().map(|e| e.table_dir.as_str()), )), @@ -324,14 +311,8 @@ impl ManifestSstBatchBuilder { ))); } }; - columns.push(array); - } - DfRecordBatch::try_new_with_options( - self.schema.clone(), - columns, - &datatypes::arrow::record_batch::RecordBatchOptions::new() - .with_row_count(Some(entries.len())), - ) + Ok(array) + }) } } @@ -396,7 +377,7 @@ impl StorageSstEntry { /// Builds a logical plan for scanning the storage sst entries. pub fn build_plan(scan_request: ScanRequest) -> Result { - build_plan_helper( + inspect::build_plan( scan_request, Self::reserved_table_name_for_inspection(), Self::schema(), @@ -514,7 +495,7 @@ impl PuffinIndexMetaEntry { /// Builds a logical plan for scanning puffin index metadata entries. pub fn build_plan(scan_request: ScanRequest) -> Result { - build_plan_helper( + inspect::build_plan( scan_request, Self::reserved_table_name_for_inspection(), Self::schema(), @@ -522,39 +503,6 @@ impl PuffinIndexMetaEntry { } } -fn build_plan_helper( - scan_request: ScanRequest, - table_name: &str, - schema: SchemaRef, -) -> Result { - let table_source = LogicalTableSource::new(schema.arrow_schema().clone()); - - // Filters may reference columns omitted from the requested output. Apply - // them to the full schema and let the optimizer push the minimal projection. - let projection = scan_request.projection; - let mut builder = LogicalPlanBuilder::scan(table_name, Arc::new(table_source), None)?; - - for filter in scan_request.filters { - builder = builder.filter(filter)?; - } - - if let Some(projection) = projection { - let projected = schema.arrow_schema().project(&projection)?; - builder = builder.project( - projected - .fields() - .iter() - .map(|field| datafusion_expr::col(field.name())), - )?; - } - - if let Some(limit) = scan_request.limit { - builder = builder.limit(0, Some(limit))?; - } - - builder.build() -} - #[cfg(test)] mod tests { use datafusion_common::TableReference; diff --git a/src/table/src/requests.rs b/src/table/src/requests.rs index 4cfded64fb5..f83af641323 100644 --- a/src/table/src/requests.rs +++ b/src/table/src/requests.rs @@ -75,6 +75,9 @@ pub const TABLE_DATA_MODEL: &str = "table_data_model"; pub const TABLE_DATA_MODEL_TRACE_V1: &str = "greptime_trace_v1"; /// Table data model used by the JSON2-based OTLP trace pipeline. pub const TABLE_DATA_MODEL_TRACE_V2: &str = "greptime_trace_v2"; +/// Table data model of OTLP log tables auto-created with the v1 built-in schema. +/// Log tables without this marker keep the legacy built-in schema. +pub const TABLE_DATA_MODEL_LOG_V1: &str = "greptime_log_v1"; /// Returns true for the Trace V1 and V2 data models supported /// by semantic graph derivation. diff --git a/src/table/src/table.rs b/src/table/src/table.rs index cdc06a50be2..7b126b3fdfb 100644 --- a/src/table/src/table.rs +++ b/src/table/src/table.rs @@ -56,10 +56,10 @@ lazy_static! { /// Defines partition rules for a table. /// TODO(discord9): add the entire partition exprs rules here later pub struct PartitionRules { - /// The physical partition columns that are not in the logical table. - /// only used in kvbackend manager to store the physical partition columns that are not in the logical table. - /// This is used to avoid the partition columns in the physical table that are not in the logical table - /// to prevent certain optimizations, if table is not a logical table, this should be empty + /// The partition columns that are not in this table's schema: physical partition columns + /// missing from a logical table, or the current partition columns of a table that a plan + /// keeps with an older schema. They prevent optimizations that rely on knowing the partition + /// columns. pub extra_phy_cols_not_in_logical_table: Vec, } diff --git a/tests-integration/src/cluster.rs b/tests-integration/src/cluster.rs index ba4814763c6..fe6ee9d9fe9 100644 --- a/tests-integration/src/cluster.rs +++ b/tests-integration/src/cluster.rs @@ -57,6 +57,7 @@ use frontend::frontend::{Frontend, FrontendOptions}; use frontend::instance::Instance as FeInstance; use frontend::instance::builder::FrontendBuilder; use frontend::server::Services; +use frontend::service_config::BatcherOptions; use futures::TryStreamExt; use hyper_util::rt::TokioIo; use meta_client::client::MetaClientBuilder; @@ -202,6 +203,7 @@ pub struct GreptimeDbClusterBuilder { datanode_gc_config: GcConfig, metasrv_gc_config: GcSchedulerOptions, frontend_auto_create_table: bool, + table_batcher: BatcherOptions, shared_home_dir: Option>, meta_selector: Option, plugins: Plugins, @@ -240,6 +242,7 @@ impl GreptimeDbClusterBuilder { datanode_gc_config: GcConfig::default(), metasrv_gc_config: GcSchedulerOptions::default(), frontend_auto_create_table: true, + table_batcher: BatcherOptions::default(), shared_home_dir: None, meta_selector: None, plugins: Plugins::default(), @@ -306,6 +309,13 @@ impl GreptimeDbClusterBuilder { self } + /// Configures ordinary-table batching for the frontend. + #[must_use] + pub fn with_table_batcher(mut self, options: BatcherOptions) -> Self { + self.table_batcher = options; + self + } + #[must_use] pub fn with_shared_home_dir(mut self, shared_home_dir: Arc) -> Self { self.shared_home_dir = Some(shared_home_dir); @@ -667,6 +677,7 @@ impl GreptimeDbClusterBuilder { event_recorder: self.event_recorder_options.clone(), ..Default::default() }; + fe_opts.pending_rows_batcher.table = self.table_batcher.clone(); // Choose a random unused port between [14000, 24000] for local test to avoid conflicts. let port_range = 14000..=24000; diff --git a/tests-integration/src/instance.rs b/tests-integration/src/instance.rs index 955e9780517..dd9509b3958 100644 --- a/tests-integration/src/instance.rs +++ b/tests-integration/src/instance.rs @@ -336,6 +336,7 @@ mod tests { "SELECT compact_table('admin_fn_demo')", "SELECT flush_region(0)", "SELECT compact_region(0)", + "SELECT cancel_region_compaction(0, 'x')", "SELECT migrate_region(1, 2, 3)", "SELECT gc_regions(0)", "SELECT gc_table('admin_fn_demo')", @@ -668,6 +669,173 @@ mod tests { } } + #[tokio::test(flavor = "multi_thread")] + async fn test_exemplar_authorization_and_interception() { + use common_catalog::consts::METRICS_EXEMPLARS_TABLE; + use servers::exemplar::query::Query; + use servers::interceptor::{PromQueryInterceptor, PromQueryInterceptorRef}; + use servers::prometheus_handler::PrometheusHandler; + use std::sync::Mutex; + use std::sync::atomic::{AtomicBool, Ordering}; + use table::table_reference::TableReference; + + #[derive(Default)] + struct Hook { + tables: Mutex>, + reject: AtomicBool, + } + impl PromQueryInterceptor for Hook { + type Error = servers::error::Error; + + fn pre_execute_exemplars( + &self, + query: &Query, + table: TableReference<'_>, + ctx: QueryContextRef, + ) -> servers::error::Result<()> { + assert_eq!(query.bounds, (0, 1_000_999_999)); + assert!(query.expression.starts_with("metric")); + assert_eq!(table.catalog, ctx.current_catalog()); + assert_eq!(table.schema, ctx.current_schema()); + assert_eq!(table.table, METRICS_EXEMPLARS_TABLE); + self.tables.lock().unwrap().push(table.to_string()); + if self.reject.load(Ordering::Relaxed) { + return servers::error::NotSupportedSnafu { + feat: "intercepted exemplar query", + } + .fail(); + } + Ok(()) + } + } + + struct Checker(Mutex>); + impl auth::PermissionChecker for Checker { + fn check_permission( + &self, + _: auth::UserInfoRef, + _: auth::PermissionReq, + ) -> auth::error::Result { + Ok(auth::PermissionResp::Allow) + } + fn check_permission_with_table_targets( + &self, + _: auth::UserInfoRef, + req: auth::PermissionReq, + targets: auth::PermissionTableTargets, + ) -> auth::error::Result { + if !matches!(req, auth::PermissionReq::Action(auth::PROMQL_QUERY)) { + return Ok(auth::PermissionResp::Allow); + } + self.0.lock().unwrap().push(targets.clone()); + let denied = match targets { + auth::PermissionTableTargets::Unresolved => true, + auth::PermissionTableTargets::Resolved(targets) => targets.iter().any(|t| { + t.schema == "secret" && t.table == "metric" + || t.schema == "shared_denied" && t.table == METRICS_EXEMPLARS_TABLE + }), + }; + Ok(if denied { + auth::PermissionResp::Reject + } else { + auth::PermissionResp::Allow + }) + } + } + let checker = Arc::new(Checker(Mutex::new(Vec::new()))); + let hook = Arc::new(Hook::default()); + let plugins = Plugins::new(); + plugins.insert::(checker.clone()); + plugins.insert::>(hook.clone()); + let standalone = GreptimeDbStandaloneBuilder::new("exemplar_query_auth") + .with_plugin(plugins) + .build() + .await; + let instance = standalone.fe_instance(); + query(instance, "CREATE DATABASE other").await; + for schema in ["public", "other"] { + create_table(instance, &format!("CREATE TABLE {schema}.{METRICS_EXEMPLARS_TABLE} (__table_id INT UNSIGNED NOT NULL, __tsid BIGINT UNSIGNED NOT NULL, greptime_timestamp TIMESTAMP(9) TIME INDEX, greptime_metric STRING, greptime_value DOUBLE, exemplar_labels JSON2, PRIMARY KEY (__table_id, __tsid, greptime_metric)) WITH ('append_mode'='true', 'primary_key_encoding'='sparse')")).await; + } + for expression in [ + "rate(metric{__schema__=\"public\"}[5m]) + metric{__database__=\"secret\"}", + "metric{__schema__=\"public\" or __schema__=\"secret\"}", + "metric{__database__=\"shared_denied\"}", + "{__name__=~\"metric.*\",__schema__=\"secret\"}", + "topk(scalar(metric{__schema__=\"secret\"}), metric)", + ] { + checker.0.lock().unwrap().clear(); + let query = Query::parse(expression.into(), "0", "1", "public").unwrap(); + let error = instance + .query_exemplars(query, QueryContext::arc()) + .await + .unwrap_err(); + assert_eq!( + error.status_code(), + StatusCode::PermissionDenied, + "{expression}: {error:?}" + ); + assert!(!checker.0.lock().unwrap().is_empty()); + assert!(hook.tables.lock().unwrap().is_empty()); + } + let query = Query::parse( + "metric{__schema__=\"public\" or __database__=\"other\"}".into(), + "0", + "1", + "public", + ) + .unwrap(); + checker.0.lock().unwrap().clear(); + assert!( + instance + .query_exemplars(query, QueryContext::arc()) + .await + .unwrap() + .is_empty() + ); + let checks = checker.0.lock().unwrap().clone(); + for schema in ["public", "other"] { + for table in ["metric", METRICS_EXEMPLARS_TABLE] { + assert!(checks.iter().any(|c| matches!(c, auth::PermissionTableTargets::Resolved(t) if t.iter().any(|t| t.schema == schema && t.table == table)))); + } + } + assert_eq!( + *hook.tables.lock().unwrap(), + [ + format!("greptime.other.{METRICS_EXEMPLARS_TABLE}"), + format!("greptime.public.{METRICS_EXEMPLARS_TABLE}"), + ], + ); + hook.tables.lock().unwrap().clear(); + hook.reject.store(true, Ordering::Relaxed); + let error = instance + .query_exemplars( + Query::parse("metric".into(), "0", "1", "public").unwrap(), + QueryContext::arc(), + ) + .await + .unwrap_err(); + assert!(matches!( + error, + servers::error::Error::NotSupported { feat, .. } + if feat == "intercepted exemplar query" + )); + assert_eq!(hook.tables.lock().unwrap().len(), 1); + + hook.tables.lock().unwrap().clear(); + assert!( + instance + .query_exemplars( + Query::parse("metric{__schema__=\"missing\"}".into(), "0", "1", "public") + .unwrap(), + QueryContext::arc(), + ) + .await + .unwrap() + .is_empty() + ); + assert!(hook.tables.lock().unwrap().is_empty()); + } + /// The entity-graph derivation must run as the caller: a source table the /// caller cannot read contributes neither entities nor edges. #[tokio::test(flavor = "multi_thread")] diff --git a/tests-integration/src/prom_store.rs b/tests-integration/src/prom_store.rs index 0608ff88f9c..8e78b32cdee 100644 --- a/tests-integration/src/prom_store.rs +++ b/tests-integration/src/prom_store.rs @@ -892,12 +892,27 @@ mod tests { let mut empty = query.clone(); empty.start_timestamp_ms = 5000; empty.end_timestamp_ms = 6000; + let mut hinted = query.clone(); + hinted.end_timestamp_ms = 3000; + hinted.hints = Some(api::prom_store::remote::ReadHints { + start_ms: 2000, + end_ms: 5000, + ..Default::default() + }); + let mut disjoint = query.clone(); + disjoint.hints = Some(api::prom_store::remote::ReadHints { + start_ms: 5000, + end_ms: 6000, + ..Default::default() + }); let request = ReadRequest { queries: vec![ remote_query("metric1"), query, remote_query("missing_metric"), empty, + hinted, + disjoint, ], accepted_response_types, }; @@ -911,7 +926,7 @@ mod tests { assert_eq!(response.headers()["content-encoding"], "snappy"); let body = prom_store::snappy_decompress(&response.bytes().await).unwrap(); let response = ReadResponse::decode(body.as_slice()).unwrap(); - assert_eq!(response.results.len(), 4); + assert_eq!(response.results.len(), 6); assert!(!response.results[0].timeseries[0].samples.is_empty()); assert!(response.results[2].timeseries.is_empty()); assert!(response.results[3].timeseries.is_empty()); @@ -947,6 +962,10 @@ mod tests { Some(api::prom_store::remote::histogram::Count::CountFloat(6.0)) ); assert_eq!(series.histograms[3].sum.to_bits(), 0x7ff0_0000_0000_0002); + let hinted_series = &response.results[4].timeseries[0]; + assert_eq!(hinted_series.labels, series.labels); + assert_eq!(hinted_series.histograms, series.histograms[1..3]); + assert!(response.results[5].timeseries.is_empty()); } } let response = client diff --git a/tests-integration/src/standalone.rs b/tests-integration/src/standalone.rs index 5bd0d970de5..142ef72b000 100644 --- a/tests-integration/src/standalone.rs +++ b/tests-integration/src/standalone.rs @@ -19,7 +19,6 @@ use cache::{ build_datanode_layered_cache_registry, build_fundamental_cache_registry, with_default_composite_cache_registry, }; -use catalog::information_schema::NoopInformationExtension; use catalog::kvbackend::KvBackendCatalogManagerBuilder; use catalog::process_manager::ProcessManager; use common_base::Plugins; @@ -55,7 +54,10 @@ use frontend::service_config::{BatcherOptions, PendingRowsBatcherOptions}; use meta_srv::metasrv::{FLOW_ID_SEQ, TABLE_ID_SEQ}; use servers::grpc::GrpcOptions; use standalone::options::StandaloneOptions; -use standalone::{StandaloneDatanodeManager, StandaloneRepartitionProcedureFactory}; +use standalone::{ + StandaloneDatanodeManager, StandaloneInformationExtension, + StandaloneRepartitionProcedureFactory, +}; use crate::test_util::{self, StorageType, TestGuard, create_tmp_dir_and_datanode_opts}; @@ -234,8 +236,12 @@ impl GreptimeDbStandaloneBuilder { .build(), ); + let information_extension = Arc::new(StandaloneInformationExtension::new( + datanode.region_server(), + procedure_manager.clone(), + )); let catalog_manager = KvBackendCatalogManagerBuilder::new( - Arc::new(NoopInformationExtension), + information_extension.clone(), kv_backend.clone(), cache_registry.clone(), ) @@ -253,6 +259,9 @@ impl GreptimeDbStandaloneBuilder { Arc::new(frontend_client), ); let flownode = Arc::new(flow_builder.build().await.unwrap()); + information_extension + .set_flow_engine(flownode.flow_engine()) + .await; let node_manager = Arc::new(StandaloneDatanodeManager { region_server: datanode.region_server(), diff --git a/tests-integration/src/test_util.rs b/tests-integration/src/test_util.rs index 6da25d659b6..caccd4d4eca 100644 --- a/tests-integration/src/test_util.rs +++ b/tests-integration/src/test_util.rs @@ -12,9 +12,9 @@ // See the License for the specific language governing permissions and // limitations under the License. -use std::collections::BTreeMap; #[cfg(test)] use std::collections::HashMap; +use std::collections::{BTreeMap, HashSet}; use std::env; use std::fmt::Display; use std::net::SocketAddr; @@ -31,7 +31,7 @@ use client::{Client, Database}; use common_base::Plugins; use common_catalog::consts::MIN_USER_TABLE_ID; use common_config::Configurable; -use common_event_recorder::EventRecorderOptions; +use common_event_recorder::{EventRecorderOptions, EventTypeFilter}; #[cfg(test)] use common_meta::DatanodeId; use common_meta::key::TableMetadataManager; @@ -172,7 +172,8 @@ impl MockInstanceImpl { } } - /// Creates a standalone instance or a three-datanode cluster using local storage. + /// Creates a standalone instance or a three-datanode cluster using local + /// storage, with the event recorder disabled. pub async fn new(name: &str, distributed: bool) -> Self { let name = format!( "{name}_{}", @@ -188,12 +189,18 @@ impl MockInstanceImpl { Self::Distributed( GreptimeDbClusterBuilder::new(&name) .await + .with_event_recorder_options(disabled_event_recorder_options()) .with_datanodes(3) .build(false) .await, ) } else { - Self::Standalone(GreptimeDbStandaloneBuilder::new(&name).build().await) + Self::Standalone( + GreptimeDbStandaloneBuilder::new(&name) + .with_event_recorder_options(disabled_event_recorder_options()) + .build() + .await, + ) } } @@ -341,6 +348,14 @@ pub fn test_event_recorder_options() -> EventRecorderOptions { } } +/// Event recorder options that record no events, for tests that count WAL writes. +pub fn disabled_event_recorder_options() -> EventRecorderOptions { + EventRecorderOptions { + event_types: Arc::new(EventTypeFilter::Only(HashSet::new())), + ..Default::default() + } +} + fn s3_test_config() -> S3Config { S3Config { connection: S3Connection { @@ -1133,7 +1148,18 @@ pub async fn setup_mysql_server_with_user_provider( } let instance = setup_standalone_instance_with_plugins(name, store_type, plugins).await; + let mysql_server = + setup_mysql_server_for_frontend_instance(instance.fe_instance().clone(), user_provider) + .await; + (instance.guard, Arc::new(mysql_server)) +} + +/// Builds and starts a MySQL server on an existing frontend instance. +pub async fn setup_mysql_server_for_frontend_instance( + fe_instance_ref: Arc, + user_provider: Option, +) -> Box { let runtime = RuntimeBuilder::default() .worker_threads(2) .thread_name("mysql-runtime") @@ -1142,7 +1168,6 @@ pub async fn setup_mysql_server_with_user_provider( let fe_mysql_addr = format!("127.0.0.1:{}", ports::get_port()); - let fe_instance_ref = instance.fe_instance().clone(); let opts = MysqlOptions { addr: fe_mysql_addr.clone(), ..Default::default() @@ -1168,7 +1193,7 @@ pub async fn setup_mysql_server_with_user_provider( .await .unwrap(); - (instance.guard, Arc::new(mysql_server)) + mysql_server } pub async fn setup_pg_server( @@ -1234,7 +1259,17 @@ pub async fn setup_pg_server_with_user_provider( user_provider: Option, ) -> (TestGuard, Arc>) { let instance = setup_standalone_instance(name, store_type).await; + let pg_server = + setup_pg_server_for_frontend_instance(instance.fe_instance().clone(), user_provider).await; + (instance.guard, Arc::new(pg_server)) +} + +/// Builds and starts a Postgres server on an existing frontend instance. +pub async fn setup_pg_server_for_frontend_instance( + fe_instance_ref: Arc, + user_provider: Option, +) -> Box { let runtime = RuntimeBuilder::default() .worker_threads(2) .thread_name("pg-runtime") @@ -1243,7 +1278,6 @@ pub async fn setup_pg_server_with_user_provider( let fe_pg_addr = format!("127.0.0.1:{}", ports::get_port()); - let fe_instance_ref = instance.fe_instance().clone(); let opts = PostgresOptions { addr: fe_pg_addr.clone(), ..Default::default() @@ -1273,7 +1307,7 @@ pub async fn setup_pg_server_with_user_provider( .await .unwrap(); - (instance.guard, Arc::new(pg_server)) + pg_server } /// Sets up a standalone instance with both a Prometheus remote-write HTTP app diff --git a/tests-integration/src/tests/instance_test.rs b/tests-integration/src/tests/instance_test.rs index 0615b684f6b..2d8034b1510 100644 --- a/tests-integration/src/tests/instance_test.rs +++ b/tests-integration/src/tests/instance_test.rs @@ -22,6 +22,7 @@ use common_error::status_code::StatusCode; use common_query::Output; use common_recordbatch::util; use common_test_util::recordbatch::check_output_stream; +use datanode::region_server::RegionServer; use datatypes::arrow::array::{ ArrayRef, AsArray, StringArray, TimestampMillisecondArray, UInt64Array, }; @@ -4979,3 +4980,1228 @@ async fn test_exemplar_source_identity_policy() { .collect::>(); assert_eq!(ids, vec![source.table_id(), replacement.table_id()]); } + +#[rstest] +#[case::completed(false)] +#[case::cancelled(true)] +#[tokio::test] +async fn test_compaction_tasks_sql_lifecycle(#[case] cancel: bool) { + use crate::standalone::GreptimeDbStandaloneBuilder; + + let instance = GreptimeDbStandaloneBuilder::new("compaction_tasks_sql_lifecycle") + .build() + .await; + check_compaction_tasks_sql_lifecycle( + instance.fe_instance(), + instance.datanode.region_server(), + 0, + None, + cancel, + ) + .await; +} + +#[rstest] +#[case::completed(false)] +#[case::cancelled(true)] +#[tokio::test] +async fn test_compaction_tasks_distributed_sql_lifecycle(#[case] cancel: bool) { + use common_meta::peer::Peer; + use meta_srv::error::Result as MetaResult; + use meta_srv::metasrv::SelectorContext; + use meta_srv::selector::{Selector, SelectorOptions}; + + use crate::cluster::GreptimeDbClusterBuilder; + use crate::test_util::PEER_PLACEHOLDER_ADDR; + + struct CompactionNodeSelector; + + #[async_trait::async_trait] + impl Selector for CompactionNodeSelector { + type Context = SelectorContext; + type Output = Vec; + + async fn select( + &self, + _ctx: &Self::Context, + _opts: SelectorOptions<'_>, + ) -> MetaResult { + Ok(vec![Peer { + id: 1, + addr: PEER_PLACEHOLDER_ADDR.to_string(), + }]) + } + } + + let cluster = GreptimeDbClusterBuilder::new("compaction_tasks_distributed_sql_lifecycle") + .await + .with_datanodes(2) + // Only node 1 gets the gated engine; place the table there deterministically. + .with_meta_selector(Arc::new(CompactionNodeSelector)) + .build(false) + .await; + assert_eq!(cluster.datanode_instances.len(), 2); + check_compaction_tasks_sql_lifecycle( + cluster.fe_instance(), + cluster.datanode_instances[&1].region_server(), + 1, + Some(2), + cancel, + ) + .await; +} + +/// Exercises SQL -> catalog -> datanode inspection -> live scheduler state. +async fn check_compaction_tasks_sql_lifecycle( + frontend: &Arc, + mut region_server: RegionServer, + node_id: u64, + other_node_id: Option, + cancel: bool, +) { + use std::time::Duration; + + use common_recordbatch::RecordBatches; + use mito2::config::MitoConfig; + use mito2::engine::listener::CompactionListener; + use mito2::test_util::TestEnv; + + struct Release(Arc); + + impl Drop for Release { + fn drop(&mut self) { + self.0.wake(); + } + } + + async fn rows(frontend: &Arc, sql: &str) -> RecordBatches { + let output = execute_sql(frontend, sql).await; + match output.data { + OutputData::Stream(stream) => RecordBatches::try_collect(stream).await.unwrap(), + OutputData::RecordBatches(batches) => batches, + _ => panic!("expected query output"), + } + } + + let listener = Arc::new(CompactionListener::default()); + let release = Release(listener.clone()); + let mut env = TestEnv::new().await.with_node_id(node_id); + let engine = env + .create_engine_with( + MitoConfig { + min_compaction_interval: Duration::from_secs(3600), + ..Default::default() + }, + None, + Some(listener.clone()), + None, + ) + .await; + // Install a real engine with a deterministic merge gate before creating any user table. + region_server.register_engine(Arc::new(engine.clone())); + execute_sql(frontend, "CREATE TABLE compact_inspect (host STRING PRIMARY KEY, ts TIMESTAMP TIME INDEX, val DOUBLE) WITH ('compaction.type' = 'twcs', 'compaction.twcs.trigger_file_num' = '100')").await; + for value in [1, 2] { + execute_sql( + frontend, + &format!("INSERT INTO compact_inspect VALUES ('a', 0, {value}), ('a', 1000, {value})"), + ) + .await; + execute_sql(frontend, "ADMIN FLUSH_TABLE('compact_inspect')").await; + } + let before = rows(frontend, "SELECT * FROM compact_inspect ORDER BY ts") + .await + .pretty_print() + .unwrap(); + let compact = { + let frontend = frontend.clone(); + tokio::spawn(async move { + frontend + .do_query( + "ADMIN COMPACT_TABLE('compact_inspect', 'strict_window', 'window=3600')", + QueryContext::arc(), + ) + .await + .remove(0) + }) + }; + tokio::time::timeout(Duration::from_secs(20), listener.wait_handle_finished()) + .await + .unwrap(); + let live_tasks = engine.inspect_compaction_tasks(&[]).await.unwrap(); + assert_eq!(live_tasks.len(), 1); + assert_eq!(live_tasks[0].state.as_ref(), "running"); + assert_eq!(live_tasks[0].node_id, Some(node_id)); + // Input SST bounds are inclusive; strict-window output bounds are [start, end). + let ranges = rows(frontend, &format!("SELECT input_time_start, input_time_end, output_time_start, output_time_end FROM information_schema.compaction_tasks WHERE node_id = {node_id} AND input_time_end = CAST('1970-01-01T00:00:01Z' AS TIMESTAMP(9))")).await; + assert_eq!( + ranges.iter().map(|batch| batch.num_rows()).sum::(), + 1 + ); + let range_batch = ranges.iter().find(|batch| batch.num_rows() > 0).unwrap(); + for (index, expected) in [0, 1_000_000_000, 0, 3_600_000_000_000i64] + .into_iter() + .enumerate() + { + let values = range_batch + .column(index) + .as_any() + .downcast_ref::() + .unwrap(); + assert_eq!(values.iter().collect::>(), vec![Some(expected)]); + } + let snapshot = rows(frontend, &format!("SELECT task_id, trigger_type, state, input_files, request_options, effective_options, node_id FROM information_schema.compaction_tasks WHERE trigger_type = 'manual' AND node_id = {node_id} LIMIT 1")).await; + assert_eq!(snapshot.iter().map(|b| b.num_rows()).sum::(), 1); + let snapshot = snapshot.iter().find(|batch| batch.num_rows() > 0).unwrap(); + assert_eq!( + snapshot.column(0).as_string::().value(0), + live_tasks[0].task_id.as_ref() + ); + assert_eq!(snapshot.column(1).as_string::().value(0), "manual"); + assert_eq!(snapshot.column(2).as_string::().value(0), "running"); + assert_eq!( + snapshot + .column(3) + .as_any() + .downcast_ref::() + .unwrap() + .value(0), + 2 + ); + let request: serde_json::Value = + serde_json::from_str(snapshot.column(4).as_string::().value(0)).unwrap(); + assert_eq!(request["type"], "strict_window"); + assert_eq!(request["window_seconds"], 3600); + let effective: serde_json::Value = + serde_json::from_str(snapshot.column(5).as_string::().value(0)).unwrap(); + assert_eq!(effective["time_window_seconds"], 3600); + assert_eq!( + snapshot + .column(6) + .as_any() + .downcast_ref::() + .unwrap() + .value(0), + node_id + ); + assert_eq!( + rows( + frontend, + "SELECT task_id FROM information_schema.compaction_tasks WHERE node_id IS NULL" + ) + .await + .iter() + .map(|batch| batch.num_rows()) + .sum::(), + 0 + ); + let nodes = rows( + frontend, + "SELECT node_id FROM information_schema.compaction_tasks", + ) + .await; + assert_eq!(nodes.iter().map(|batch| batch.num_rows()).sum::(), 1); + assert_eq!( + nodes + .iter() + .find(|batch| batch.num_rows() > 0) + .unwrap() + .column(0) + .as_any() + .downcast_ref::() + .unwrap() + .value(0), + node_id + ); + if let Some(other_node_id) = other_node_id { + let count = rows(frontend, &format!( + "SELECT count(*) FROM information_schema.compaction_tasks WHERE node_id = {other_node_id}" + )).await.pretty_print().unwrap(); + assert_eq!( + count, + "+----------+\n| count(*) |\n+----------+\n| 0 |\n+----------+" + ); + } + for sql in [ + "SELECT count(*) FROM information_schema.compaction_tasks", + "SELECT count(*) FROM information_schema.compaction_tasks WHERE state = 'running'", + ] { + let count = rows(frontend, sql).await.pretty_print().unwrap(); + assert_eq!( + count, + "+----------+\n| count(*) |\n+----------+\n| 1 |\n+----------+" + ); + } + assert_eq!(rows(frontend, "SELECT task_id FROM information_schema.compaction_tasks WHERE node_id = 18446744073709551615").await.iter().map(|b| b.num_rows()).sum::(), 0); + let task_id = snapshot.column(0).as_string::().value(0); + let region_id = live_tasks[0].region_id.as_u64(); + let cancel_sql = format!("ADMIN cancel_region_compaction({region_id}, '{task_id}')"); + if cancel { + for (sql, expected) in [ + ( + format!("ADMIN cancel_region_compaction({region_id}, 'stale-task-id')"), + 0, + ), + (cancel_sql.clone(), 1), + (cancel_sql.clone(), 1), + ] { + let result = tokio::time::timeout(Duration::from_secs(10), rows(frontend, &sql)) + .await + .expect("SQL compaction cancellation did not return"); + assert_eq!( + result.iter().map(|batch| batch.num_rows()).sum::(), + 1 + ); + let batch = result.iter().find(|batch| batch.num_rows() > 0).unwrap(); + assert_eq!( + batch + .column(0) + .as_primitive::() + .value(0), + expected + ); + } + assert_eq!( + engine.inspect_compaction_tasks(&[]).await.unwrap()[0] + .state + .as_ref(), + "cancelling" + ); + } + drop(release); + let result = tokio::time::timeout(Duration::from_secs(20), compact) + .await + .unwrap() + .unwrap(); + assert_eq!( + result.is_err(), + cancel, + "unexpected COMPACT_TABLE outcome: {result:?}" + ); + 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!( + rows( + frontend, + "SELECT task_id FROM information_schema.compaction_tasks" + ) + .await + .iter() + .map(|b| b.num_rows()) + .sum::(), + 0 + ); + if cancel { + let result = tokio::time::timeout(Duration::from_secs(10), rows(frontend, &cancel_sql)) + .await + .expect("completed task cancellation did not return"); + assert_eq!( + result.iter().map(|batch| batch.num_rows()).sum::(), + 1 + ); + let batch = result.iter().find(|batch| batch.num_rows() > 0).unwrap(); + assert_eq!( + batch + .column(0) + .as_primitive::() + .value(0), + 0 + ); + } + assert_eq!( + before, + rows(frontend, "SELECT * FROM compact_inspect ORDER BY ts") + .await + .pretty_print() + .unwrap() + ); + execute_sql(frontend, "DROP TABLE compact_inspect").await; +} + +#[apply(both_instances_cases)] +async fn test_compaction_tasks_empty_and_node_pruning(instance: Arc) { + let frontend = instance.frontend(); + for sql in [ + "SELECT task_id FROM information_schema.compaction_tasks", + "SELECT task_id FROM information_schema.compaction_tasks WHERE node_id = 18446744073709551615 LIMIT 1", + "SELECT task_id FROM information_schema.compaction_tasks WHERE state = 'running' AND region_id = 0", + ] { + let output = execute_sql(&frontend, sql).await; + let batches = match output.data { + OutputData::Stream(stream) => common_recordbatch::RecordBatches::try_collect(stream) + .await + .unwrap(), + OutputData::RecordBatches(batches) => batches, + _ => panic!("expected query output"), + }; + assert_eq!( + batches.iter().map(|b| b.num_rows()).sum::(), + 0, + "{sql}" + ); + } +} + +async fn create_exemplar_source(frontend: &Arc, schema: &str, name: &str) { + execute_sql(frontend, &format!( + "CREATE TABLE IF NOT EXISTS {schema}.exemplar_sources (greptime_timestamp TIMESTAMP(9) TIME INDEX, greptime_value DOUBLE) ENGINE=metric WITH ('physical_metric_table'='')" + )).await; + execute_sql(frontend, &format!( + "CREATE TABLE {schema}.{name} (greptime_timestamp TIMESTAMP(9) TIME INDEX, greptime_value DOUBLE) ENGINE=metric WITH ('on_physical_table'='exemplar_sources')" + )).await; +} + +#[rstest] +#[case::standalone(false, false, false, false)] +#[case::standalone_batched(false, true, false, false)] +#[case::distributed_batched(true, true, false, false)] +#[case::precreated_json_settings(false, true, true, false)] +#[case::standalone_batched_sync(false, true, false, true)] +#[case::distributed_batched_sync(true, true, false, true)] +#[test] +fn test_exemplar_protocol_storage_lifecycle( + #[case] distributed: bool, + #[case] batching: bool, + #[case] precreated: bool, + #[case] sync: bool, +) { + temp_env::with_var( + "PENDING_ROWS_BATCH_SYNC", + Some(if sync { "true" } else { "false" }), + || { + tokio::runtime::Builder::new_multi_thread() + .enable_all() + .build() + .unwrap() + .block_on(exemplar_protocol_storage_lifecycle( + distributed, + batching, + precreated, + )); + }, + ); +} + +async fn exemplar_protocol_storage_lifecycle(distributed: bool, batching: bool, precreated: bool) { + use api::prom_store::remote::{Exemplar, Label, Sample, TimeSeries, WriteRequest}; + use axum::body::{Body, to_bytes}; + use frontend::service_config::BatcherOptions; + use http::Request; + use prost::Message; + use servers::batcher::BatchingProtocol; + use servers::http::{HttpOptions, HttpServerBuilder}; + use servers::prom_remote_write::v2::test_util as v2; + use servers::prom_remote_write::validation::PromValidationMode; + use servers::prom_store::snappy_compress; + use tower::ServiceExt; + + use crate::cluster::GreptimeDbClusterBuilder; + use crate::standalone::GreptimeDbStandaloneBuilder; + use crate::test_util::build_test_prom_server; + use crate::tests::test_util::{MockInstanceBuilder, RebuildableMockInstance, TestContext}; + + let name = format!("exemplar_lifecycle_{distributed}_{batching}_{precreated}"); + let protocols = if batching { + vec![BatchingProtocol::Prom, BatchingProtocol::Otlp] + } else { + Vec::new() + }; + let table_batcher = BatcherOptions { + protocols: protocols.clone(), + pending_rows_flush_interval: std::time::Duration::from_millis(20), + ..Default::default() + }; + let builder = if distributed { + MockInstanceBuilder::Distributed( + GreptimeDbClusterBuilder::new(&name) + .await + .with_datanodes(3) + .with_table_batcher(table_batcher), + ) + } else { + MockInstanceBuilder::Standalone( + GreptimeDbStandaloneBuilder::new(&name).with_table_batcher(table_batcher), + ) + }; + let mut context = TestContext::new(builder).await; + if precreated { + execute_sql( + &context.frontend(), + &format!( + "CREATE TABLE {METRICS_EXEMPLARS_TABLE} ( + __table_id INT UNSIGNED NOT NULL, + __tsid BIGINT UNSIGNED NOT NULL, + greptime_timestamp TIMESTAMP(6) TIME INDEX, + greptime_metric STRING, + greptime_value DOUBLE, + exemplar_labels JSON2(max_auto_expanded_paths = 0, trace_id STRING), + PRIMARY KEY (__table_id, __tsid, greptime_metric) + ) WITH ('append_mode'='true', 'primary_key_encoding'='sparse', 'sst_format'='primary_key')" + ), + ) + .await; + } + let router = |frontend: Arc| { + let builder = if batching { + build_test_prom_server(frontend.clone(), true, None) + } else { + HttpServerBuilder::new(HttpOptions::default()) + .with_prometheus_handler(frontend.clone()) + .with_prom_handler( + frontend.clone(), + None, + true, + PromValidationMode::Strict, + None, + ) + }; + let server = builder + .with_batching_protocols(protocols.clone()) + .with_otlp_handler(frontend, true) + .build(); + server.build(server.make_app()).unwrap() + }; + let mut app = router(context.frontend()); + let request = WriteRequest { + timeseries: vec![TimeSeries { + labels: vec![ + Label { + name: "__name__".into(), + value: "exemplar_metric".into(), + }, + Label { + name: "job".into(), + value: "api".into(), + }, + ], + samples: vec![Sample { + timestamp: 1720000000123, + value: 1.0, + }], + exemplars: vec![ + Exemplar { + timestamp: i64::MAX, + ..Default::default() + }, + Exemplar { + timestamp: 1720000000123, + value: 0.32, + labels: vec![Label { + name: "trace_id".into(), + value: "abc".into(), + }], + }, + ], + ..Default::default() + }], + ..Default::default() + }; + for _ in 0..2 { + let response = app + .clone() + .oneshot( + Request::post("/v1/prometheus/write") + .header("Content-Encoding", "snappy") + .header("Content-Type", "application/x-protobuf") + .body(Body::from( + snappy_compress(&request.encode_to_vec()).unwrap(), + )) + .unwrap(), + ) + .await + .unwrap(); + let status = response.status(); + assert_eq!( + status, + 204, + "{:?}", + to_bytes(response.into_body(), usize::MAX).await.unwrap() + ); + } + // Exemplar-only series require an existing source and must not register a sample kind. + create_exemplar_source(&context.frontend(), "public", "retained_exemplar").await; + let mut request = v2::request_with_labels_and_samples( + vec![("__name__", "retained_exemplar"), ("zone", "east")], + vec![], + ); + request.timeseries[0].exemplars.push( + api::greptime_proto::io::prometheus::write::v2::Exemplar { + timestamp: i64::MAX, + ..Default::default() + }, + ); + request.timeseries[0].exemplars.push( + api::greptime_proto::io::prometheus::write::v2::Exemplar { + timestamp: 1720000000124, + value: 2.0, + ..Default::default() + }, + ); + let response = app + .clone() + .oneshot( + Request::post("/v1/prometheus/write") + .header("Content-Encoding", "snappy") + .header( + "Content-Type", + "application/x-protobuf;proto=io.prometheus.write.v2.Request", + ) + .body(Body::from( + snappy_compress(&request.encode_to_vec()).unwrap(), + )) + .unwrap(), + ) + .await + .unwrap(); + let status = response.status(); + assert_eq!( + response + .headers() + .get("x-prometheus-remote-write-exemplars-written") + .unwrap(), + "1" + ); + assert_eq!( + response + .headers() + .get("x-prometheus-remote-write-samples-written") + .unwrap(), + "0" + ); + assert_eq!( + status, + 204, + "{:?}", + to_bytes(response.into_body(), usize::MAX).await.unwrap() + ); + let output = execute_sql( + &context.frontend(), + "SELECT COUNT(*) FROM retained_exemplar", + ) + .await; + check_output_stream( + output.data, + "+----------+\n| count(*) |\n+----------+\n| 0 |\n+----------+", + ) + .await; + + use otel_arrow_rust::proto::opentelemetry::collector::metrics::v1::ExportMetricsServiceRequest; + use otel_arrow_rust::proto::opentelemetry::metrics::v1 as otlp; + let request = ExportMetricsServiceRequest { + resource_metrics: vec![otlp::ResourceMetrics { + scope_metrics: vec![otlp::ScopeMetrics { + metrics: vec![otlp::Metric { + name: "otlp_exemplar".into(), + data: Some(otlp::metric::Data::Gauge(otlp::Gauge { + data_points: vec![otlp::NumberDataPoint { + time_unix_nano: 1720000000999999999, + value: Some(otlp::number_data_point::Value::AsDouble(10.0)), + exemplars: vec![ + otlp::Exemplar::default(), + otlp::Exemplar { + time_unix_nano: 1720000000123456789, + value: Some(otlp::exemplar::Value::AsDouble(0.5)), + trace_id: vec![0xab; 16], + ..Default::default() + }, + ], + ..Default::default() + }], + })), + ..Default::default() + }], + ..Default::default() + }], + ..Default::default() + }], + }; + let response = app + .clone() + .oneshot( + Request::post("/v1/otlp/v1/metrics") + .header("Content-Type", "application/x-protobuf") + .body(Body::from(request.encode_to_vec())) + .unwrap(), + ) + .await + .unwrap(); + assert_eq!( + response.status(), + 200, + "{:?}", + to_bytes(response.into_body(), usize::MAX).await.unwrap() + ); + + let expression = urlencoding::encode( + "topk(scalar(retained_exemplar), rate(exemplar_metric{job=\"api\"}[5m])) + otlp_exemplar", + ); + let path = format!( + "/v1/prometheus/api/v1/query_exemplars?query={expression}&start=1720000000.123&end=1720000000.124" + ); + let mut baseline = None; + for phase in ["memory", "wal", "sst", "compaction", "reopen"] { + match phase { + "wal" | "reopen" => { + drop(app); + context.rebuild().await; + app = router(context.frontend()); + } + "sst" => { + execute_sql( + &context.frontend(), + &format!("admin flush_table('{METRICS_EXEMPLARS_TABLE}')"), + ) + .await; + } + "compaction" => { + execute_sql( + &context.frontend(), + &format!("admin compact_table('{METRICS_EXEMPLARS_TABLE}', 'strict_window', 'window=3600')"), + ) + .await; + } + _ => {} + } + let response = app + .clone() + .oneshot(Request::get(&path).body(Body::empty()).unwrap()) + .await + .unwrap(); + let status = response.status(); + let bytes = to_bytes(response.into_body(), usize::MAX).await.unwrap(); + assert_eq!(status, 200, "{phase}: {}", String::from_utf8_lossy(&bytes)); + let value: serde_json::Value = serde_json::from_slice(&bytes).unwrap(); + assert_eq!(value["status"], "success", "{phase}: {value}"); + for series in value["data"].as_array().unwrap() { + assert!(series["seriesLabels"].get("__table_id").is_none()); + assert!(series["seriesLabels"].get("__tsid").is_none()); + } + assert_eq!( + value["data"].as_array().unwrap().len(), + 3, + "{phase}: {value}" + ); + let otlp = value["data"] + .as_array() + .unwrap() + .iter() + .find(|series| series["seriesLabels"]["__name__"] == "otlp_exemplar") + .unwrap(); + assert_eq!( + otlp["exemplars"][0]["timestamp"], 1720000000.123, + "{phase}: {value}" + ); + let stored_timestamp = if precreated { + 1720000000123456i64 + } else { + 1720000000123456789i64 + }; + let output = execute_sql( + &context.frontend(), + &format!("SELECT COUNT(*) FROM {METRICS_EXEMPLARS_TABLE} WHERE greptime_metric = 'otlp_exemplar' AND CAST(greptime_timestamp AS BIGINT) = {stored_timestamp}"), + ).await; + check_output_stream( + output.data, + "+----------+\n| count(*) |\n+----------+\n| 1 |\n+----------+", + ) + .await; + assert_eq!( + value["data"][0]["exemplars"].as_array().unwrap().len(), + 1, + "exact duplicates: {value}" + ); + assert_eq!( + value["data"][0]["exemplars"][0]["labels"]["trace_id"], + "abc" + ); + if let Some(baseline) = &baseline { + assert_eq!(&value, baseline, "{phase}"); + } else { + baseline = Some(value); + } + } + execute_sql(&context.frontend(), "DROP TABLE exemplar_metric").await; + // Storage columns are absent labels; ordinary null tags have empty-label semantics. + for (expression, count) in [ + ("exemplar_metric{zone=\"\"}", 1), + ("exemplar_metric{zone!~\".+\"}", 1), + ("exemplar_metric{greptime_value=\"\"}", 1), + ("exemplar_metric{greptime_metric=\"\"}", 1), + ("exemplar_metric{__table_id=\"\"}", 1), + ("exemplar_metric{__tsid=\"\"}", 1), + ("exemplar_metric{__table_id!=\"\"}", 0), + ("exemplar_metric{__tsid=~\".+\"}", 0), + ] { + let form = format!( + "query={}&start=1720000000.123&end=1720000000.123", + urlencoding::encode(expression) + ); + let response = app + .clone() + .oneshot( + Request::post("/v1/prometheus/api/v1/query_exemplars") + .header("Content-Type", "application/x-www-form-urlencoded") + .body(Body::from(form)) + .unwrap(), + ) + .await + .unwrap(); + let value: serde_json::Value = + serde_json::from_slice(&to_bytes(response.into_body(), usize::MAX).await.unwrap()) + .unwrap(); + assert_eq!( + value["data"].as_array().unwrap().len(), + count, + "{expression}: {value}" + ); + } +} + +#[rstest] +#[tokio::test(flavor = "multi_thread")] +async fn test_exemplar_query_bounds_and_malformed_rows( + #[values(http::Method::GET, http::Method::POST)] method: http::Method, +) { + use std::sync::atomic::{AtomicUsize, Ordering}; + + use axum::body::{Body, to_bytes}; + use common_base::Plugins; + use http::Request; + use servers::exemplar::query::Query; + use servers::http::{HttpOptions, HttpServerBuilder}; + use servers::interceptor::{PromQueryInterceptor, PromQueryInterceptorRef}; + use session::context::Channel; + use table::table_reference::TableReference; + use tower::ServiceExt; + + use crate::standalone::GreptimeDbStandaloneBuilder; + + struct Hook(AtomicUsize); + + impl PromQueryInterceptor for Hook { + type Error = server_error::Error; + + fn pre_execute_exemplars( + &self, + _query: &Query, + _table: TableReference<'_>, + ctx: QueryContextRef, + ) -> server_error::Result<()> { + assert_eq!(ctx.channel(), Channel::Prometheus); + self.0.fetch_add(1, Ordering::Relaxed); + Ok(()) + } + } + + let hook = Arc::new(Hook(AtomicUsize::new(0))); + let plugins = Plugins::new(); + plugins.insert::>(hook.clone()); + let instance = GreptimeDbStandaloneBuilder::new("exemplar_malformed_rows") + .with_plugin(plugins) + .build() + .await; + let frontend = instance.fe_instance(); + execute_sql(frontend, &format!("CREATE TABLE {METRICS_EXEMPLARS_TABLE} (__table_id INT UNSIGNED NOT NULL, __tsid BIGINT UNSIGNED NOT NULL, greptime_timestamp TIMESTAMP(9) TIME INDEX, greptime_metric STRING, job STRING, greptime_value DOUBLE, exemplar_labels JSON2, PRIMARY KEY (__table_id, __tsid, greptime_metric, job)) WITH ('append_mode'='true', 'primary_key_encoding'='sparse')")).await; + execute_sql( + frontend, + &format!( + r#"INSERT INTO {METRICS_EXEMPLARS_TABLE} VALUES + (42, 7, 1000000, 'metric', 'api', 1, '{{"trace_id":"good"}}'), + (42, 7, 1000000, 'metric', 'api', 1, '{{"trace_id":"good"}}'), + (42, 7, 1999999, 'metric', 'api', 1, '{{"trace_id":"good"}}'), + (42, 7, -1000000, 'metric', 'api', 1, '{{"trace_id":"good"}}'), + (42, 7, -1, 'metric', 'api', 1, '{{"trace_id":"good"}}'), + (42, 7, 2000000, 'metric', 'api', 2, '{{"trace_id":42}}'), + (42, 7, 3000000, 'metric', 'api', NULL, '{{}}'), + (42, 7, 4000000, 'metric', 'api', 4, NULL), + (42, 7, 5000000, NULL, 'api', 5, '{{}}'), + (42, 7, 6000000, 'bad_only', 'api', NULL, '{{}}')"# + ), + ) + .await; + let server = HttpServerBuilder::new(HttpOptions::default()) + .with_prometheus_handler(frontend.clone()) + .build(); + let app = server.build(server.make_app()).unwrap(); + for (query, start, end, skipped, series) in [ + ("metric", "0", "1", 3, 1), + ("%7Bjob%3D%22api%22%7D", "0", "1", 5, 1), + ("metric", "0", "0.001", 0, 1), + ("metric", "0", "0", 0, 0), + ("metric", "0.002", "0.002", 1, 0), + ("metric", "-0.001", "-0.001", 0, 1), + ("metric", "0.0011", "0.0012", 0, 1), + ("metric", "0.0012", "0.0011", 0, 1), + ( + "metric", + "1970-01-01T00:00:00.0011Z", + "1970-01-01T00:00:00.0012Z", + 0, + 1, + ), + ("missing", "0", "1", 0, 0), + ("bad_only", "0", "1", 1, 0), + ] { + let params = format!("query={query}&start={start}&end={end}"); + let request = if method == http::Method::GET { + Request::get(format!("/v1/prometheus/api/v1/query_exemplars?{params}")) + .body(Body::empty()) + } else { + Request::post("/v1/prometheus/api/v1/query_exemplars") + .header("Content-Type", "application/x-www-form-urlencoded") + .body(Body::from(params)) + } + .unwrap(); + let response = app.clone().oneshot(request).await.unwrap(); + assert_eq!(response.status(), http::StatusCode::OK); + assert_eq!(hook.0.swap(0, Ordering::Relaxed), 1); + let body = to_bytes(response.into_body(), usize::MAX).await.unwrap(); + let response: serde_json::Value = serde_json::from_slice(&body).unwrap(); + assert_eq!( + response["data"].as_array().unwrap().len(), + series, + "{response}" + ); + if skipped > 0 { + assert_eq!( + response["warnings"], + serde_json::json!([format!("Skipped {skipped} malformed stored exemplars")]) + ); + } else { + assert!(response.get("warnings").is_none(), "{response}"); + } + if series > 0 { + assert_eq!( + response["data"][0]["exemplars"].as_array().unwrap().len(), + 2, + "deduplicate stored timestamps before rounding: {response}" + ); + let timestamp = if start == "-0.001" { -0.001 } else { 0.001 }; + for exemplar in response["data"][0]["exemplars"].as_array().unwrap() { + assert_eq!(exemplar["timestamp"], timestamp, "{response}"); + } + assert_eq!( + response["data"][0]["exemplars"][0]["labels"]["trace_id"], + "good" + ); + } + } +} + +#[tokio::test(flavor = "multi_thread")] +async fn test_exemplar_concurrent_ddl_and_precreated_contract() { + use std::collections::BTreeMap; + + use servers::exemplar::query::Query; + use servers::exemplar::{Exemplar, into_rows}; + use servers::prometheus_handler::PrometheusHandler; + use servers::query_handler::PromStoreProtocolHandler; + + use crate::standalone::GreptimeDbStandaloneBuilder; + + let instance = GreptimeDbStandaloneBuilder::new("exemplar_concurrent_ddl") + .build() + .await; + let frontend = instance.fe_instance(); + create_exemplar_source(frontend, "public", "concurrent").await; + let request = |tag: String, timestamp: i64| { + into_rows(vec![Exemplar { + metric: "concurrent".into(), + series_labels: BTreeMap::from([(tag, "present".into())]).into(), + timestamp, + value: 1.0, + labels: BTreeMap::from([("trace_id".into(), "abc".into())]), + }]) + .unwrap() + .0 + }; + // Disjoint first creators and repeated additions must converge on one schema. + for repeated in [false, true] { + let barrier = Arc::new(tokio::sync::Barrier::new(8)); + let writes = (0..8).map(|i| { + let barrier = barrier.clone(); + let request = request( + if repeated { + "shared".into() + } else { + format!("tag_{i}") + }, + i, + ); + async move { + barrier.wait().await; + frontend + .write_exemplars_prepared( + request, + Arc::new(QueryContext::arc().with_confirmed_writes()), + ) + .await + .unwrap() + .write_progress() + .await + .into_result() + .unwrap() + } + }); + assert_eq!(futures::future::join_all(writes).await, vec![1; 8]); + } + let info = frontend + .catalog_manager() + .table("greptime", "public", METRICS_EXEMPLARS_TABLE, None) + .await + .unwrap() + .unwrap() + .table_info(); + assert_eq!(info.meta.primary_key_indices.len(), 12); + operator::insert::validate_exemplar_table(&info).unwrap(); + let response = frontend + .query_exemplars( + Query::parse("concurrent".into(), "0", "1", "public").unwrap(), + QueryContext::arc(), + ) + .await + .unwrap(); + assert_eq!( + response.iter().map(|s| s.exemplars.len()).sum::(), + 16 + ); + + // Incompatible pre-created tables must be rejected before adding inherited tags. + let definition = format!( + "CREATE TABLE {METRICS_EXEMPLARS_TABLE} (__table_id INT UNSIGNED NOT NULL, __tsid BIGINT UNSIGNED NOT NULL, greptime_timestamp TIMESTAMP(6) TIME INDEX, greptime_metric STRING, greptime_value DOUBLE, exemplar_labels JSON2(max_auto_expanded_paths=0, trace_id STRING), PRIMARY KEY (__table_id, __tsid, greptime_metric)) WITH ('append_mode'='true', 'primary_key_encoding'='sparse')" + ); + for definition in [ + definition.replace("greptime_value DOUBLE", "greptime_value BIGINT"), + definition.replace("__tsid, greptime_metric)", "__tsid)"), + definition.replace("JSON2(max_auto_expanded_paths=0, trace_id STRING)", "JSON"), + definition.replace("trace_id STRING", "trace_id BIGINT"), + ] { + execute_sql(frontend, &format!("DROP TABLE {METRICS_EXEMPLARS_TABLE}")).await; + execute_sql(frontend, &definition).await; + let before = frontend + .catalog_manager() + .table("greptime", "public", METRICS_EXEMPLARS_TABLE, None) + .await + .unwrap() + .unwrap() + .table_info(); + assert!( + frontend + .write_exemplars_prepared(request("must_not_add".into(), 0), QueryContext::arc()) + .await + .is_err(), + "{definition}" + ); + let after = frontend + .catalog_manager() + .table("greptime", "public", METRICS_EXEMPLARS_TABLE, None) + .await + .unwrap() + .unwrap() + .table_info(); + assert_eq!(before, after, "incompatible table must not be altered"); + } + + let disabled = GreptimeDbStandaloneBuilder::new("exemplar_disabled_ddl") + .with_auto_create_table(false) + .build() + .await; + let frontend = disabled.fe_instance(); + create_exemplar_source(frontend, "public", "concurrent").await; + assert!( + frontend + .write_exemplars_prepared(request("tag".into(), 0), QueryContext::arc()) + .await + .is_err() + ); + assert!( + frontend + .catalog_manager() + .table("greptime", "public", METRICS_EXEMPLARS_TABLE, None) + .await + .unwrap() + .is_none() + ); +} + +#[rstest] +#[case::auto_create(true, false, false)] +#[case::auto_create_disabled(false, false, false)] +#[case::hint_disabled(true, true, false)] +#[case::batched(true, false, true)] +#[case::batched_auto_create_disabled(false, false, true)] +#[case::batched_hint_disabled(true, true, true)] +#[tokio::test(flavor = "multi_thread")] +async fn test_exemplar_precreated_precision_and_label_defaults( + #[case] auto_create: bool, + #[case] hint_disabled: bool, + #[case] batching: bool, +) { + use std::collections::BTreeMap; + + use frontend::service_config::BatcherOptions; + use servers::batcher::BatchingProtocol; + use servers::exemplar::query::Query; + use servers::exemplar::{Exemplar, into_rows}; + use servers::prometheus_handler::PrometheusHandler; + use servers::query_handler::PromStoreProtocolHandler; + use table::requests::AUTO_CREATE_TABLE_KEY; + + use crate::standalone::GreptimeDbStandaloneBuilder; + + let mut builder = GreptimeDbStandaloneBuilder::new("exemplar_precreated_contract") + .with_auto_create_table(auto_create); + if batching { + builder = builder.with_table_batcher(BatcherOptions { + protocols: vec![BatchingProtocol::Otlp], + pending_rows_flush_interval: std::time::Duration::from_millis(10), + ..Default::default() + }); + } + let instance = builder.build().await; + let frontend = instance.fe_instance(); + create_exemplar_source(frontend, "public", "metric").await; + let mut ctx = QueryContext::arc().with_confirmed_writes(); + ctx.set_batching_enabled(batching); + if hint_disabled { + ctx.set_extension(AUTO_CREATE_TABLE_KEY, "false"); + } + let ctx = Arc::new(ctx); + for default in ["", "DEFAULT NULL", "DEFAULT 'east'"] { + execute_sql( + frontend, + &format!( + "CREATE TABLE {METRICS_EXEMPLARS_TABLE} ( + __table_id INT UNSIGNED NOT NULL, + __tsid BIGINT UNSIGNED NOT NULL, + greptime_timestamp TIMESTAMP(6) TIME INDEX, + greptime_metric STRING, site STRING {default}, + greptime_value DOUBLE, exemplar_labels JSON2, + PRIMARY KEY (__table_id, __tsid, greptime_metric, site) + ) WITH ('append_mode'='true', 'primary_key_encoding'='sparse')" + ), + ) + .await; + let request = into_rows(vec![Exemplar { + metric: "metric".into(), + series_labels: BTreeMap::new().into(), + timestamp: -1, + value: 1.0, + labels: BTreeMap::new(), + }]) + .unwrap() + .0; + let result = frontend + .write_exemplars_prepared(request, ctx.clone()) + .await; + if default == "DEFAULT 'east'" { + let error = result.unwrap_err(); + assert!( + error.output_msg().contains("non-NULL defaults"), + "{error:?}" + ); + } else { + assert_eq!( + result + .unwrap() + .write_progress() + .await + .into_result() + .unwrap(), + 1 + ); + let series = frontend + .query_exemplars( + Query::parse("metric{site=\"\"}".into(), "-0.001", "0", "public").unwrap(), + QueryContext::arc(), + ) + .await + .unwrap(); + assert_eq!(series.len(), 1); + assert!(!series[0].series_labels.contains_key("site")); + assert_eq!(series[0].exemplars[0].timestamp, -0.001); + } + execute_sql(frontend, &format!("DROP TABLE {METRICS_EXEMPLARS_TABLE}")).await; + } +} + +#[tokio::test(flavor = "multi_thread")] +async fn test_exemplar_cross_schema_exact_identity() { + use std::collections::BTreeMap; + + use servers::exemplar::query::Query; + use servers::exemplar::{Exemplar, into_rows}; + use servers::prometheus_handler::PrometheusHandler; + use servers::query_handler::PromStoreProtocolHandler; + + use crate::standalone::GreptimeDbStandaloneBuilder; + + let instance = GreptimeDbStandaloneBuilder::new("exemplar_cross_schema_identity") + .build() + .await; + let frontend = instance.fe_instance(); + execute_sql(frontend, "CREATE DATABASE exemplar_other").await; + let values = [ + 0.0, + -0.0, + f64::from_bits(0x7ff8_0000_0000_0001), + f64::from_bits(0x7ff8_0000_0000_0002), + f64::INFINITY, + f64::NEG_INFINITY, + ]; + for schema in ["public", "exemplar_other"] { + create_exemplar_source(frontend, schema, "identity").await; + let observations = values + .into_iter() + .flat_map(|value| { + (0..2).map(move |_| Exemplar { + metric: "identity".into(), + series_labels: BTreeMap::new().into(), + timestamp: -1, + value, + labels: BTreeMap::from([ + ("z".into(), "last".into()), + ("a".into(), "first".into()), + ]), + }) + }) + .collect(); + let requests = into_rows(observations).unwrap().0; + let ctx = Arc::new(QueryContext::with("greptime", schema)); + frontend + .write_exemplars_prepared(requests, ctx) + .await + .unwrap() + .write_progress() + .await + .into_result() + .unwrap(); + } + let query = Query::parse("identity{__schema__=\"public\" or __database__=\"exemplar_other\" or __schema__=\"missing\"}".into(), "-0.001", "-0.001", "public").unwrap(); + let response = frontend + .query_exemplars(query, QueryContext::arc()) + .await + .unwrap(); + assert_eq!(response.len(), 1); + assert_eq!(response[0].exemplars.len(), values.len()); + let encoded = serde_json::to_string(&response).unwrap(); + for value in ["0", "-0", "NaN", "+Inf", "-Inf"] { + assert!( + response[0].exemplars.iter().any(|e| e.value == value), + "{encoded}" + ); + } + assert!(encoded.contains("\"timestamp\":-0.001"), "{encoded}"); +} diff --git a/tests-integration/src/tests/test_util.rs b/tests-integration/src/tests/test_util.rs index 7c99e89ee08..64a4e98c5e2 100644 --- a/tests-integration/src/tests/test_util.rs +++ b/tests-integration/src/tests/test_util.rs @@ -111,17 +111,31 @@ impl MockInstanceBuilder { async fn rebuild(&self, instance: MockInstanceImpl) -> MockInstanceImpl { match self { MockInstanceBuilder::Standalone(builder) => { - let MockInstanceImpl::Standalone(instance) = instance else { + let MockInstanceImpl::Standalone(mut instance) = instance else { unreachable!() }; + instance.datanode.shutdown().await.unwrap(); + instance.procedure_manager.stop().await.unwrap(); let GreptimeDbStandalone { opts, guard, kv_backend, procedure_manager, event_recorder_handle, - .. + frontend, + datanode, + mito_engine, } = instance; + // Procedure loaders retain the old datanode, including its WAL lock. + drop(( + frontend, + datanode, + mito_engine, + procedure_manager, + event_recorder_handle, + )); + let (procedure_manager, event_recorder_handle) = + standalone::build_procedure_manager(kv_backend.clone(), opts.procedure); MockInstanceImpl::Standalone( builder .build_with( @@ -130,7 +144,7 @@ impl MockInstanceBuilder { opts, procedure_manager, event_recorder_handle, - false, + true, ) .await, ) diff --git a/tests-integration/tests/grpc.rs b/tests-integration/tests/grpc.rs index 82feb3f1fec..e134a5e808c 100644 --- a/tests-integration/tests/grpc.rs +++ b/tests-integration/tests/grpc.rs @@ -2909,3 +2909,76 @@ pub async fn test_grpc_memory_limit(store_type: StorageType) { let _ = fe_grpc_server.shutdown().await; } + +#[apply(both_deployment_cases)] +async fn test_exemplar_otel_arrow_skips_non_metric_source(distributed: bool) { + use datatypes::arrow::array::BinaryArray; + use servers::query_handler::sql::SqlQueryHandler; + use session::context::QueryContext; + + let env = MockInstanceImpl::new("exemplar_otel_arrow", distributed).await; + let frontend = env.frontend(); + let server = setup_grpc_server_for_frontend_instance(frontend.clone(), None).await; + let mut client = + ArrowMetricsServiceClient::connect(format!("http://{}", server.bind_addr().unwrap())) + .await + .unwrap(); + let exemplars = ArrowRecordBatch::try_from_iter(vec![ + ( + arrow_consts::PARENT_ID, + Arc::new(UInt32Array::from(vec![0])) as ArrayRef, + ), + ( + arrow_consts::TIME_UNIX_NANO, + Arc::new(TimestampNanosecondArray::from(vec![1_123_456_789])) as ArrayRef, + ), + ( + arrow_consts::DOUBLE_VALUE, + Arc::new(Float64Array::from(vec![0.25])) as ArrayRef, + ), + ( + arrow_consts::TRACE_ID, + Arc::new(BinaryArray::from(vec![&[0xab; 16][..]])) as ArrayRef, + ), + ( + arrow_consts::SPAN_ID, + Arc::new(BinaryArray::from(vec![&[0xcd; 8][..]])) as ArrayRef, + ), + ]) + .unwrap(); + let mut batch = gauge_arrow_batch(1, false); + batch.arrow_payloads.push(ArrowPayload { + schema_id: "exemplars-1".into(), + r#type: ArrowPayloadType::NumberDpExemplars as i32, + record: serialize_arrow_record_batch(&exemplars), + }); + let mut response = client + .arrow_metrics(Request::new(futures::stream::iter([batch]))) + .await + .unwrap() + .into_inner(); + let status = response.message().await.unwrap().unwrap(); + assert_eq!(status.status_code, ArrowStatusCode::Ok as i32); + assert!(status.status_message.is_empty()); + assert!(response.message().await.unwrap().is_none()); + // Arrow currently selects ordinary-engine ingestion; only exemplars are skipped. + let output = frontend + .do_query("SELECT COUNT(*) FROM otel_arrow_gauge", QueryContext::arc()) + .await + .remove(0) + .unwrap(); + common_test_util::recordbatch::check_output_stream( + output.data, + "+----------+\n| count(*) |\n+----------+\n| 1 |\n+----------+", + ) + .await; + assert!( + frontend + .catalog_manager() + .table("greptime", "public", METRICS_EXEMPLARS_TABLE, None) + .await + .unwrap() + .is_none() + ); + server.shutdown().await.unwrap(); +} diff --git a/tests-integration/tests/http.rs b/tests-integration/tests/http.rs index c7ba62a473f..a7879d3a779 100644 --- a/tests-integration/tests/http.rs +++ b/tests-integration/tests/http.rs @@ -203,6 +203,7 @@ macro_rules! http_tests { test_pipeline_context, test_pipeline_with_vrl, test_pipeline_vrl_host_access, + test_pipeline_ignore_errors_config, test_pipeline_with_hint_vrl, test_pipeline_one_to_many_vrl, test_pipeline_2, @@ -3657,6 +3658,7 @@ enable_heap_profiling = true [pipeline] cache_ttl = "10s" allow_vrl_host_access = false +ignore_errors = false [event_recorder] ttl = "2months 29days 2h 52m 48s" @@ -7265,6 +7267,7 @@ transform: // Force named dry-runs to reload and compile the stored definition. cache_ttl: Duration::ZERO, allow_vrl_host_access, + ..Default::default() }) .build() .await; @@ -7310,6 +7313,132 @@ transform: } } +pub async fn test_pipeline_ignore_errors_config(storage_type: StorageType) { + let pipeline = "transform:\n - field: value\n type: int32\n"; + let data = "{\"value\":1}\ninvalid JSON\n{\"value\":2}\n"; + + for ignore_errors in [false, true] { + let mut instance = tests_integration::standalone::GreptimeDbStandaloneBuilder::new( + "test_pipeline_ignore_errors_config", + ) + .with_default_store_type(storage_type) + .with_pipeline_options(pipeline::PipelineOptions { + ignore_errors, + ..Default::default() + }) + .build() + .await; + let server = HttpServerBuilder::new(HttpOptions::default()) + .with_log_ingest_handler(instance.fe_instance().clone(), None, None) + .build(); + let client = TestClient::new(server.build(server.make_app()).unwrap()).await; + let response = client + .post("/v1/pipelines/ignore_errors") + .header("Content-Type", "application/x-yaml") + .body(pipeline) + .send() + .await; + assert_eq!(response.status(), StatusCode::OK); + + for request_override in [None, Some(false), Some(true)] { + let effective = request_override.unwrap_or(ignore_errors); + let query = request_override + .map(|value| format!("&ignore_errors={value}")) + .unwrap_or_default(); + let expected_status = if effective { + StatusCode::OK + } else { + StatusCode::BAD_REQUEST + }; + + for path in ["/v1/ingest", "/v1/events/logs"] { + let response = client + .post(&format!( + "{path}?table=logs&pipeline_name=ignore_errors{query}" + )) + .header("Content-Type", "application/x-ndjson") + .body(data) + .send() + .await; + assert_eq!(response.status(), expected_status); + if effective { + let body: Value = response.json().await; + assert_eq!(body["output"][0]["affectedrows"], 2); + } + } + + for (content_type, body) in [ + ("application/x-ndjson", data.to_string()), + ( + "application/json", + json!({ + "pipeline_name": "ignore_errors", + "data_type": "application/x-ndjson", + "data": data, + }) + .to_string(), + ), + ( + "application/json", + json!({ + "pipeline": pipeline, + "data_type": "application/x-ndjson", + "data": data, + }) + .to_string(), + ), + ] { + let response = client + .post(&format!( + "/v1/pipelines/_dryrun?pipeline_name=ignore_errors{query}" + )) + .header("Content-Type", content_type) + .body(body) + .send() + .await; + assert_eq!(response.status(), expected_status); + if effective { + let body: Value = response.json().await; + assert_eq!(body[0]["rows"].as_array().unwrap().len(), 2); + } + } + + let response = client + .post(&format!( + "/v1/ingest?table=timestamps&pipeline_name=greptime_identity\ + &custom_time_index=ts;epoch;s{query}" + )) + .header("Content-Type", "application/json") + .body(r#"{"ts":"invalid","value":1}"#) + .send() + .await; + assert_eq!( + response.status(), + if effective { + StatusCode::OK + } else { + StatusCode::INTERNAL_SERVER_ERROR + } + ); + if effective { + let body: Value = response.json().await; + assert_eq!(body["output"][0]["affectedrows"], 1); + } + } + + // Parsing tolerance does not enable skipping pipeline execution errors. + let response = client + .post("/v1/ingest?table=logs&pipeline_name=ignore_errors&ignore_errors=true") + .header("Content-Type", "application/json") + .body(r#"{"value":"not an integer"}"#) + .send() + .await; + assert!(!response.status().is_success()); + + instance.guard.remove_all().await; + } +} + pub async fn test_pipeline_with_vrl(storage_type: StorageType) { common_telemetry::init_default_ut_logging(); let (app, mut guard) = @@ -11151,7 +11280,7 @@ pub async fn test_otlp_logs(store_type: StorageType) { ) .await; assert_eq!(StatusCode::OK, res.status()); - let expected = "[[1736413568497632000,\"f665100a612542b69cc362fe2ae9d3bf\",\"e58f01c4c69f4488\",\"Info\",9,\"the message line one\",{\"app\":\"server1\"},0,\"\",\"\",{\"instance_num\":\"10\"},\"\",{},\"https://opentelemetry.io/schemas/1.4.0\"],[1736413568538897000,\"f665100a612542b69cc362fe2ae9d3bf\",\"e58f01c4c69f4488\",\"Info\",9,\"the message line two\",{\"app\":\"server2\"},0,\"\",\"\",{},\"\",{},\"https://opentelemetry.io/schemas/1.4.0\"]]"; + let expected = "[[1736413568497632000,\"f665100a612542b69cc362fe2ae9d3bf\",\"e58f01c4c69f4488\",\"Info\",9,\"the message line one\",{\"app\":\"server1\"},0,null,\"\",\"\",{\"instance_num\":\"10\"},\"\",{},\"https://opentelemetry.io/schemas/1.4.0\",null,null],[1736413568538897000,\"f665100a612542b69cc362fe2ae9d3bf\",\"e58f01c4c69f4488\",\"Info\",9,\"the message line two\",{\"app\":\"server2\"},0,null,\"\",\"\",{},\"\",{},\"https://opentelemetry.io/schemas/1.4.0\",null,null]]"; validate_data( "otlp_logs", &client, @@ -11177,10 +11306,28 @@ pub async fn test_otlp_logs(store_type: StorageType) { &client, "select count(*) from information_schema.tables where table_name = 'opentelemetry_logs' \ and create_options like '%greptime.semantic.signal_type=log%' \ - and create_options like '%greptime.semantic.source=opentelemetry%';", + and create_options like '%greptime.semantic.source=opentelemetry%' \ + and create_options like '%table_data_model=greptime_log_v1%' \ + and create_options like '%greptime.semantic.pipeline=greptime_log_v1%';", "[[1]]", ) .await; + validate_data( + "otlp_logs_v1_keys_and_indexes", + &client, + "select column_name, constraint_name, ordinal_position from information_schema.key_column_usage \ + where table_name = 'opentelemetry_logs' order by constraint_name, ordinal_position, column_name;", + r#"[["service_name","PRIMARY",1],["scope_name","PRIMARY",2],["timestamp","TIME INDEX",1]]"#, + ) + .await; + validate_data( + "otlp_logs_v1_column_indexes", + &client, + "select index_name, column_name from information_schema.statistics \ + where table_name = 'opentelemetry_logs' and index_name like '%INDEX_%' order by index_name;", + r#"[["FULLTEXT_INDEX_body","body"],["SKIPPING_INDEX_trace_id","trace_id"]]"#, + ) + .await; // Write another batch after the table exists. This verifies existing-schema // alignment accepts the built-in JSONB columns in direct OTLP logs. @@ -11230,7 +11377,7 @@ pub async fn test_otlp_logs(store_type: StorageType) { .await; assert_eq!(StatusCode::OK, res.status()); - let expected = "[[1736413568538897000,\"f665100a612542b69cc362fe2ae9d3bf\",\"e58f01c4c69f4488\",\"Info\",9,\"the message line two\",{\"app\":\"server2\"},0,\"\",\"\",{},\"\",{},\"https://opentelemetry.io/schemas/1.4.0\",null,\"server2\"],[1736413568497632000,\"f665100a612542b69cc362fe2ae9d3bf\",\"e58f01c4c69f4488\",\"Info\",9,\"the message line one\",{\"app\":\"server1\"},0,\"\",\"\",{\"instance_num\":\"10\"},\"\",{},\"https://opentelemetry.io/schemas/1.4.0\",\"10\",\"server1\"]]"; + let expected = "[[1736413568538897000,\"f665100a612542b69cc362fe2ae9d3bf\",\"e58f01c4c69f4488\",\"Info\",9,\"the message line two\",{\"app\":\"server2\"},0,null,\"\",\"\",{},\"\",{},\"https://opentelemetry.io/schemas/1.4.0\",null,null,null,\"server2\"],[1736413568497632000,\"f665100a612542b69cc362fe2ae9d3bf\",\"e58f01c4c69f4488\",\"Info\",9,\"the message line one\",{\"app\":\"server1\"},0,null,\"\",\"\",{\"instance_num\":\"10\"},\"\",{},\"https://opentelemetry.io/schemas/1.4.0\",null,null,\"10\",\"server1\"]]"; validate_data( "otlp_logs_with_selector", &client, @@ -11270,7 +11417,7 @@ pub async fn test_otlp_logs(store_type: StorageType) { .await; assert_eq!(StatusCode::OK, res.status()); - let expected = "[[1736413568497632000,\"f665100a612542b69cc362fe2ae9d3bf\",\"e58f01c4c69f4488\",\"Info\",9,\"the message line one\",{\"app\":\"server\",\"fromwhere\":\"log_attr\"},0,\"\",\"\",{\"fromwhere\":\"scope\"},\"\",{\"fromwhere\":\"resource\"},\"https://opentelemetry.io/schemas/1.4.0\",\"log_attr\"]]"; + let expected = "[[1736413568497632000,\"f665100a612542b69cc362fe2ae9d3bf\",\"e58f01c4c69f4488\",\"Info\",9,\"the message line one\",{\"app\":\"server\",\"fromwhere\":\"log_attr\"},0,null,\"\",\"\",{\"fromwhere\":\"scope\"},\"\",{\"fromwhere\":\"resource\"},\"https://opentelemetry.io/schemas/1.4.0\",null,null,\"log_attr\"]]"; validate_data( "otlp_logs_with_selector_overlapping", &client, @@ -11280,6 +11427,51 @@ pub async fn test_otlp_logs(store_type: StorageType) { .await; } + { + // The built-in `service_name` comes from the resource `service.name`, and log + // tables declare no entity. + let table_name = "otlp_logs_semantic"; + let now_nanos = common_time::util::current_time_millis() * 1_000_000; + let mut record = make_log_record( + "00000000000000000000000000000005", + "0000000000000005", + now_nanos, + "semantic layer", + vec![], + ); + record["eventName"] = json!("checkout.completed"); + record["observedTimeUnixNano"] = json!((now_nanos + 1).to_string()); + let mut req = make_log_request(vec![record]); + req.resource_logs[0].resource.as_mut().unwrap().attributes = + serde_json::from_value(json!([ + {"key": "service.name", "value": {"stringValue": "checkout"}} + ])) + .unwrap(); + // The first write creates the v1 table; the second reads its marker back. + for _ in 0..2 { + let res = send_log_req(&client, table_name, None, req.clone(), false).await; + assert_eq!(res.status(), StatusCode::OK, "{:?}", res.text().await); + } + + validate_data( + "otlp_logs_semantic_table_semantics", + &client, + &format!( + "select signal_type, source, pipeline, entity_declarations from information_schema.table_semantics where table_name = '{table_name}';" + ), + r#"[["log","opentelemetry","greptime_log_v1",null]]"#, + ) + .await; + let row = format!(r#"["checkout","checkout.completed",{}]"#, now_nanos + 1); + validate_data( + "otlp_logs_semantic_v1_columns", + &client, + &format!("select service_name, event_name, observed_timestamp from {table_name};"), + &format!("[{row},{row}]"), + ) + .await; + } + { let existing_table_name = "otlp_logs_existing_schema"; let res = execute_sql( @@ -11317,6 +11509,14 @@ pub async fn test_otlp_logs(store_type: StorageType) { r#"[["host","TAG"],["scope_name","FIELD"],["timestamp","TIMESTAMP"],["trace_id","TAG"]]"#, ) .await; + // Tables without the v1 marker keep the legacy built-in columns. + validate_data( + "otlp_logs_existing_schema_no_v1_columns", + &client, + "select count(*) from information_schema.columns where table_name = 'otlp_logs_existing_schema' and column_name in ('service_name', 'event_name', 'observed_timestamp');", + "[[0]]", + ) + .await; } { diff --git a/tests-integration/tests/object_store_wal.rs b/tests-integration/tests/object_store_wal.rs index 0aef1e145b0..f0915fd8d3a 100644 --- a/tests-integration/tests/object_store_wal.rs +++ b/tests-integration/tests/object_store_wal.rs @@ -26,7 +26,7 @@ use object_store::services::{Fs, S3}; use servers::query_handler::sql::SqlQueryHandler; use session::context::QueryContext; use tests_integration::standalone::{GreptimeDbStandalone, GreptimeDbStandaloneBuilder}; -use tests_integration::test_util::StorageType; +use tests_integration::test_util::{StorageType, disabled_event_recorder_options}; /// The root the store derives its node prefix from. const WAL_ROOT: &str = "cluster-a/wal"; @@ -126,7 +126,8 @@ async fn run_restarts_on_object_store_wal(store_type: StorageType) { }; let builder = GreptimeDbStandaloneBuilder::new("object_store_wal") .with_default_store_type(store_type) - .with_datanode_wal_config(DatanodeWalConfig::ObjectStore(wal_config)); + .with_datanode_wal_config(DatanodeWalConfig::ObjectStore(wal_config)) + .with_event_recorder_options(disabled_event_recorder_options()); let standalone = builder.build().await; execute_sql( diff --git a/tests-integration/tests/repartition.rs b/tests-integration/tests/repartition.rs index 880bd715c57..c4f56162a6b 100644 --- a/tests-integration/tests/repartition.rs +++ b/tests-integration/tests/repartition.rs @@ -35,10 +35,14 @@ use servers::error::Result as ServerResult; use servers::query_handler::sql::SqlQueryHandler; use session::Session; use session::context::{Channel, QueryContext, QueryContextRef}; +use sqlx::Row; use store_api::codec::PrimaryKeyEncoding; use store_api::storage::{RegionId, TableId}; use tests_integration::cluster::{GreptimeDbCluster, GreptimeDbClusterBuilder}; -use tests_integration::test_util::{StorageType, get_test_store_config}; +use tests_integration::test_util::{ + StorageType, get_test_store_config, setup_mysql_server_for_frontend_instance, + setup_pg_server_for_frontend_instance, +}; use tokio::sync::oneshot; #[macro_export] @@ -471,6 +475,81 @@ async fn assert_append_count( ); } +#[tokio::test(flavor = "multi_thread")] +async fn test_exemplar_sparse_repartition_compaction() { + let (cluster, _home_guard) = repartition_cluster("exemplar_sparse_repartition").await; + let instance = cluster.fe_instance(); + let ctx = QueryContext::arc(); + for sql in [ + "CREATE TABLE exemplar_sparse_repartition ( + __table_id INT UNSIGNED NOT NULL, __tsid BIGINT UNSIGNED NOT NULL, + host STRING, ts TIMESTAMP TIME INDEX, val DOUBLE, PRIMARY KEY (__table_id, __tsid, host) + ) PARTITION ON COLUMNS(host) (host < 'm', host >= 'm') + WITH ('primary_key_encoding'='sparse', 'append_mode'='true')", + "INSERT INTO exemplar_sparse_repartition VALUES (42, 7, 'a', 1, 1), (42, 7, 'h', 1, 2), (43, 7, 'z', 1, 3)", + "ADMIN FLUSH_TABLE('exemplar_sparse_repartition')", + "INSERT INTO exemplar_sparse_repartition VALUES (42, 7, 'a', 1, 4), (42, 7, 'h', 1, 5), (43, 7, 'z', 1, 6)", + "ADMIN FLUSH_TABLE('exemplar_sparse_repartition')", + "ALTER TABLE exemplar_sparse_repartition SPLIT PARTITION (host < 'm') + INTO (host < 'g', host >= 'g' AND host < 'm')", + ] { + run_sql(instance, sql, ctx.clone()).await.unwrap(); + } + // Refresh routes synchronously instead of depending on heartbeat timing. + instance.cache_invalidator().invalidate_all().unwrap(); + let mut inherited_ssts = 0; + for datanode in cluster.datanode_instances.values() { + inherited_ssts += datanode + .region_server() + .mito_engine() + .unwrap() + .all_ssts_from_manifest() + .await + .into_iter() + .filter(|entry| entry.origin_region_id != entry.region_id) + .count(); + } + assert!(inherited_ssts > 0); + run_sql( + instance, + "ADMIN COMPACT_TABLE('exemplar_sparse_repartition', 'swcs', '3600')", + ctx.clone(), + ) + .await + .unwrap(); + let output = run_sql( + instance, + "SELECT host, COUNT(*) AS n, SUM(val) AS total + FROM exemplar_sparse_repartition GROUP BY host ORDER BY host", + ctx.clone(), + ) + .await + .unwrap(); + check_output_stream( + output.data, + "+------+---+-------+\n\ + | host | n | total |\n\ + +------+---+-------+\n\ + | a | 2 | 5.0 |\n\ + | h | 2 | 7.0 |\n\ + | z | 2 | 9.0 |\n\ + +------+---+-------+", + ) + .await; + let output = run_sql( + instance, + "SELECT COUNT(*) FROM exemplar_sparse_repartition WHERE __table_id=42 AND __tsid=7", + ctx, + ) + .await + .unwrap(); + check_output_stream( + output.data, + "+----------+\n| count(*) |\n+----------+\n| 4 |\n+----------+", + ) + .await; +} + #[tokio::test(flavor = "multi_thread")] async fn test_repartition_multi_hop_fulltext_index_gc_file() { if StorageType::File.test_on() { @@ -682,6 +761,300 @@ async fn test_repartition_multi_hop_fulltext_index_gc() { ); } +const DEVICES: &str = "CREATE TABLE {t} (ts TIMESTAMP TIME INDEX, city STRING, device_id BIGINT, \ + PRIMARY KEY(city, device_id))"; +const DEVICES_ON_DEVICE_ID: &str = "CREATE TABLE {t} (ts TIMESTAMP TIME INDEX, city STRING, device_id BIGINT, \ + PRIMARY KEY(city, device_id)) PARTITION ON COLUMNS (device_id) (device_id < 10, device_id >= 10)"; +const DEVICE_ROWS: &str = "INSERT INTO {t} VALUES (1000, 'Aachen', 1), (1000, 'Zurich', 1), \ + (1000, 'Paris', 2), (1000, 'Aachen', 10), (1000, 'Zurich', 10), (1000, 'Beijing', 20)"; +const PARTITION_DEVICES: &str = "ALTER TABLE {t} PARTITION ON COLUMNS (device_id) \ + (device_id < 10, device_id >= 10 AND device_id < 20, device_id >= 20)"; +const METRIC_PHYSICAL: &str = r#"CREATE TABLE {t}_phy (ts TIMESTAMP TIME INDEX, val DOUBLE, host STRING PRIMARY KEY) ENGINE = metric WITH ("physical_metric_table" = "true")"#; +const METRIC_LOGICAL: &str = r#"CREATE TABLE {t} (ts TIMESTAMP TIME INDEX, val DOUBLE, host STRING PRIMARY KEY) ENGINE = metric WITH ("on_physical_table" = "{t}_phy")"#; +const METRIC_LOGICAL_NO_HOST: &str = r#"CREATE TABLE {t}_job (ts TIMESTAMP TIME INDEX, val DOUBLE, job STRING PRIMARY KEY) ENGINE = metric WITH ("on_physical_table" = "{t}_phy")"#; +const METRIC_ROWS: &str = "INSERT INTO {t} (host, ts, val) VALUES ('a_host', 1000, 1), \ + ('b_host', 1000, 2), ('n_host', 1000, 2), ('z_host', 1000, 2)"; +const METRIC_NO_HOST_ROWS: &str = + "INSERT INTO {t}_job (job, ts, val) VALUES ('a', 1000, 1), ('b', 1000, 2)"; +const PARTITION_METRIC_PHYSICAL: &str = "ALTER TABLE {t}_phy PARTITION ON COLUMNS (host) \ + (host < 'g', host >= 'g' AND host < 'p', host >= 'p')"; +const COUNT: &str = "SELECT COUNT(1) FROM {t}"; +const COUNT_BY_CITY: &str = "SELECT COUNT(1) FROM {t} GROUP BY city ORDER BY city"; +const COUNT_BY_DEVICE: &str = "SELECT COUNT(1) FROM {t} GROUP BY device_id ORDER BY device_id"; +const COUNT_BY_VAL: &str = "SELECT COUNT(1) FROM {t} GROUP BY val ORDER BY val"; +const FIRST_DEVICES: &str = "SELECT device_id FROM {t} ORDER BY device_id LIMIT 2"; +const FIRST_DEVICES_ALL_COLUMNS: &str = "SELECT * FROM {t} ORDER BY device_id LIMIT 2"; + +/// What a statement prepared before a case's DDL returns after it. +enum Expected { + /// The same as the same text prepared on a new connection. + NewStatement, + /// These values of the last column. + Rows(&'static [i64]), + Error, +} + +/// `{t}` in the statements stands for a table name unique to the case. +struct PreparedStatementCase { + name: &'static str, + setup: &'static [&'static str], + queries: &'static [(&'static str, Expected)], + ddl: &'static [&'static str], +} + +const PREPARED_STATEMENT_CASES: &[PreparedStatementCase] = &[ + PreparedStatementCase { + name: "first partitioning", + setup: &[ + DEVICES, + DEVICE_ROWS, + "CREATE VIEW {t}_view AS SELECT city, COUNT(1) AS c FROM {t} GROUP BY city", + "CREATE TABLE {t}_sink (city STRING PRIMARY KEY, c BIGINT, ts TIMESTAMP TIME INDEX)", + ], + queries: &[ + (COUNT, Expected::NewStatement), + (COUNT_BY_CITY, Expected::NewStatement), + (FIRST_DEVICES, Expected::NewStatement), + ( + "SELECT COUNT(1) FROM {t} WHERE device_id >= ?", + Expected::NewStatement, + ), + ("SELECT (SELECT COUNT(1) FROM {t})", Expected::NewStatement), + ( + "SELECT c FROM {t}_view ORDER BY city", + Expected::NewStatement, + ), + ( + "INSERT INTO {t}_sink SELECT city, COUNT(1), MAX(ts) FROM {t} GROUP BY city", + Expected::NewStatement, + ), + ( + "SELECT c FROM {t}_sink ORDER BY city", + Expected::Rows(&[2, 1, 1, 2]), + ), + ], + ddl: &[PARTITION_DEVICES], + }, + PreparedStatementCase { + name: "split adding a partition column", + setup: &[DEVICES_ON_DEVICE_ID, DEVICE_ROWS], + queries: &[(COUNT_BY_DEVICE, Expected::NewStatement)], + ddl: &[ + "ALTER TABLE {t} SPLIT PARTITION (device_id >= 10) ON COLUMNS (device_id, city) \ + INTO (device_id >= 10 AND city < 'M', device_id >= 10 AND city >= 'M')", + ], + }, + PreparedStatementCase { + name: "repartition replacing the partition column", + setup: &[DEVICES_ON_DEVICE_ID, DEVICE_ROWS], + queries: &[(COUNT_BY_DEVICE, Expected::NewStatement)], + ddl: &[ + "ALTER TABLE {t} REPARTITION (device_id < 10, device_id >= 10) ON COLUMNS (city) \ + INTO (city < 'M', city >= 'M')", + ], + }, + PreparedStatementCase { + name: "metric logical tables with and without the physical partition column", + setup: &[ + METRIC_PHYSICAL, + METRIC_LOGICAL, + METRIC_LOGICAL_NO_HOST, + METRIC_ROWS, + METRIC_NO_HOST_ROWS, + ], + queries: &[ + (COUNT, Expected::NewStatement), + (COUNT_BY_VAL, Expected::NewStatement), + ("TQL EVAL (0, 10, '5s') sum({t})", Expected::NewStatement), + ("SELECT COUNT(1) FROM {t}_job", Expected::NewStatement), + ], + ddl: &[PARTITION_METRIC_PHYSICAL], + }, + PreparedStatementCase { + name: "metric logical table gains the physical partition column", + setup: &[ + METRIC_PHYSICAL, + METRIC_LOGICAL_NO_HOST, + METRIC_NO_HOST_ROWS, + PARTITION_METRIC_PHYSICAL, + ], + queries: &[("SELECT COUNT(1) FROM {t}_job", Expected::NewStatement)], + ddl: &["ALTER TABLE {t}_job ADD COLUMN host STRING PRIMARY KEY"], + }, + PreparedStatementCase { + name: "schema and partition columns change", + setup: &[DEVICES, DEVICE_ROWS], + queries: &[ + (COUNT, Expected::NewStatement), + (COUNT_BY_CITY, Expected::NewStatement), + (FIRST_DEVICES, Expected::NewStatement), + (FIRST_DEVICES_ALL_COLUMNS, Expected::Rows(&[1, 1])), + ], + ddl: &["ALTER TABLE {t} ADD COLUMN zone STRING", PARTITION_DEVICES], + }, + PreparedStatementCase { + name: "metric logical table schema and physical partition columns change", + setup: &[METRIC_PHYSICAL, METRIC_LOGICAL, METRIC_ROWS], + queries: &[ + (COUNT, Expected::NewStatement), + (COUNT_BY_VAL, Expected::NewStatement), + ], + ddl: &[ + "ALTER TABLE {t} ADD COLUMN job STRING PRIMARY KEY", + PARTITION_METRIC_PHYSICAL, + ], + }, + PreparedStatementCase { + name: "column comment and partition columns change", + setup: &[DEVICES, DEVICE_ROWS], + queries: &[ + (COUNT, Expected::NewStatement), + (COUNT_BY_CITY, Expected::NewStatement), + ], + ddl: &["COMMENT ON COLUMN {t}.city IS 'x'", PARTITION_DEVICES], + }, + PreparedStatementCase { + name: "rename and partition columns change", + setup: &[DEVICES, DEVICE_ROWS], + queries: &[(COUNT, Expected::Rows(&[6]))], + ddl: &[ + "ALTER TABLE {t} RENAME {t}_renamed", + "ALTER TABLE {t}_renamed PARTITION ON COLUMNS (device_id) \ + (device_id < 10, device_id >= 10 AND device_id < 20, device_id >= 20)", + ], + }, + PreparedStatementCase { + name: "schema change alone", + setup: &[DEVICES_ON_DEVICE_ID, DEVICE_ROWS], + queries: &[ + (COUNT, Expected::NewStatement), + (FIRST_DEVICES_ALL_COLUMNS, Expected::Rows(&[1, 1])), + ], + ddl: &["ALTER TABLE {t} ADD COLUMN zone STRING"], + }, + PreparedStatementCase { + name: "dropped and recreated", + setup: &[DEVICES, DEVICE_ROWS], + queries: &[(COUNT, Expected::Error)], + ddl: &["DROP TABLE {t}", DEVICES], + }, +]; + +macro_rules! fetch_last_column { + ($pool:expr, $sql:expr, $param:expr) => {{ + let mut query = sqlx::query(sqlx::AssertSqlSafe($sql)); + if let Some(param) = $param { + query = query.bind(param); + } + let rows = query.fetch_all($pool).await.map_err(|e| e.to_string())?; + rows.iter() + .map(|row| { + let last = row.len() - 1; + row.try_get::(last) + .or_else(|_| row.try_get::(last).map(|v| v as i64)) + .map_err(|e| e.to_string()) + }) + .collect() + }}; +} + +/// A connection that keeps the statements it prepares. +enum PreparedClient { + Mysql(sqlx::MySqlPool), + Postgres(sqlx::PgPool), +} + +impl PreparedClient { + async fn connect_each(mysql_addr: &str, pg_addr: &str) -> [Self; 2] { + [ + Self::Mysql( + sqlx::mysql::MySqlPoolOptions::new() + .max_connections(1) + .connect(&format!("mysql://{mysql_addr}/public")) + .await + .unwrap(), + ), + Self::Postgres( + sqlx::postgres::PgPoolOptions::new() + .max_connections(1) + .connect(&format!("postgres://{pg_addr}/public")) + .await + .unwrap(), + ), + ] + } + + fn protocol(&self) -> &'static str { + match self { + Self::Mysql(_) => "mysql", + Self::Postgres(_) => "postgres", + } + } + + /// Returns the last column of each row, binding 2 to a `?` in `sql`. + async fn fetch(&self, sql: &str) -> Result, String> { + let param = sql.contains('?').then_some(2i64); + match self { + Self::Mysql(pool) => fetch_last_column!(pool, sql, param), + Self::Postgres(pool) => fetch_last_column!(pool, sql.replace('?', "$1"), param), + } + } +} + +#[tokio::test(flavor = "multi_thread")] +async fn test_prepared_statement_across_partition_column_change() { + let (cluster, _home_guard) = repartition_cluster("prepared_statement_partition").await; + let instance = cluster.fe_instance(); + let mysql = setup_mysql_server_for_frontend_instance(instance.clone(), None).await; + let pg = setup_pg_server_for_frontend_instance(instance.clone(), None).await; + let mysql_addr = mysql.bind_addr().unwrap().to_string(); + let pg_addr = pg.bind_addr().unwrap().to_string(); + + let mut failures = Vec::new(); + for (index, case) in PREPARED_STATEMENT_CASES.iter().enumerate() { + let table = format!("prepared_{index}"); + let sql = |template: &str| template.replace("{t}", &table); + for setup in case.setup { + run_sql(instance, &sql(setup), QueryContext::arc()) + .await + .unwrap(); + } + let held = PreparedClient::connect_each(&mysql_addr, &pg_addr).await; + for client in &held { + for (query, _) in case.queries { + client.fetch(&sql(query)).await.unwrap(); + } + } + for ddl in case.ddl { + run_sql(instance, &sql(ddl), QueryContext::arc()) + .await + .unwrap(); + } + + let new = PreparedClient::connect_each(&mysql_addr, &pg_addr).await; + for (held, new) in held.iter().zip(&new) { + for (query, expected) in case.queries { + let query = sql(query); + let expected = match expected { + // Runs first, so that the held statement of an `INSERT` writes last. + Expected::NewStatement => Some(new.fetch(&query).await.unwrap()), + Expected::Rows(rows) => Some(rows.to_vec()), + Expected::Error => None, + }; + let actual = held.fetch(&query).await; + if actual.as_ref().ok() != expected.as_ref() { + failures.push(format!( + "{}, {}, {query}: got {actual:?}, expected {expected:?}", + case.name, + held.protocol(), + )); + } + } + } + } + assert!(failures.is_empty(), "{failures:#?}"); +} + pub async fn test_partition_unpartitioned_mito(store_type: StorageType) { info!( "test_partition_unpartitioned_mito: store_type: {:?}", diff --git a/tests/cases/distributed/explain/step_aggr_advance.result b/tests/cases/distributed/explain/step_aggr_advance.result index 4186cb18c3a..95f71de8ae1 100644 --- a/tests/cases/distributed/explain/step_aggr_advance.result +++ b/tests/cases/distributed/explain/step_aggr_advance.result @@ -1084,9 +1084,9 @@ EXPLAIN SELECT COUNT(DISTINCT val_col_1) FROM step_aggr_extended; | logical_plan_| Projection: count(alias1) AS count(DISTINCT step_aggr_extended.val_col_1)_| |_|_Aggregate: groupBy=[[]], aggr=[[count(alias1)]]_| |_|_Aggregate: groupBy=[[step_aggr_extended.val_col_1 AS alias1]], aggr=[[]]_| -|_|_Projection: step_aggr_extended.val_col_1_| |_|_MergeScan [is_placeholder=false, remote_input=[_| -|_| TableScan: step_aggr_extended_| +|_| Projection: step_aggr_extended.val_col_1_| +|_|_TableScan: step_aggr_extended_| |_| ]]_| | physical_plan | ProjectionExec: expr=[count(alias1)@0 as count(DISTINCT step_aggr_extended.val_col_1)]_| |_|_AggregateExec: mode=Final, gby=[], aggr=[count(alias1)]_| @@ -1096,7 +1096,6 @@ EXPLAIN SELECT COUNT(DISTINCT val_col_1) FROM step_aggr_extended; |_|_RepartitionExec: partitioning=REDACTED |_|_AggregateExec: mode=Partial, gby=[val_col_1@0 as alias1], aggr=[]_| |_|_RepartitionExec: partitioning=REDACTED -|_|_ProjectionExec: expr=[val_col_1@2 as val_col_1]_| |_|_MergeScanExec: REDACTED |_|_| +-+-+ diff --git a/tests/cases/distributed/explain/subqueries.result b/tests/cases/distributed/explain/subqueries.result index 3d3f24777db..657b7cb3e30 100644 --- a/tests/cases/distributed/explain/subqueries.result +++ b/tests/cases/distributed/explain/subqueries.result @@ -89,9 +89,9 @@ order by t.i desc; | logical_plan_| Sort: t.i DESC NULLS FIRST_| |_|_SubqueryAlias: t_| |_|_Cross Join:_| -|_|_Projection: integers.i_| |_|_MergeScan [is_placeholder=false, remote_input=[_| -|_| Filter: integers.i IS NOT NULL_| +|_| Projection: integers.i_| +|_|_Filter: integers.i IS NOT NULL_| |_|_TableScan: integers, partial_filters=[integers.i IS NOT NULL, Boolean(true)] | |_| ]]_| |_|_Projection:_| @@ -101,7 +101,6 @@ order by t.i desc; | physical_plan | SortPreservingMergeExec: [i@0 DESC]_| |_|_SortExec: expr=[i@0 DESC], preserve_partitioning=[true]_| |_|_CrossJoinExec_| -|_|_ProjectionExec: expr=[i@0 as i]_| |_|_MergeScanExec: REDACTED |_|_RepartitionExec: partitioning=REDACTED |_|_ProjectionExec: expr=[]_| @@ -129,9 +128,9 @@ EXPLAIN INSERT INTO other SELECT i, 2 FROM integers WHERE i=(SELECT MAX(i) FROM | | Aggregate: groupBy=[[]], aggr=[[max(integers.i)]] | | | TableScan: integers | | | ]] | -| | Projection: integers.i | -| | MergeScan [is_placeholder=false, remote_input=[ | -| | TableScan: integers | +| | MergeScan [is_placeholder=false, remote_input=[ | +| | Projection: integers.i | +| | TableScan: integers | | | ]] | | physical_plan_error | This feature is not implemented: Insert into not implemented for this table | +---------------------+-----------------------------------------------------------------------------+ @@ -203,9 +202,9 @@ EXPLAIN SELECT * FROM integers i1 WHERE EXISTS(SELECT count(i) FROM integers WHE |_|_Filter: integers.i IS NOT NULL_| |_|_TableScan: integers, partial_filters=[integers.i IS NOT NULL]_| |_| ]]_| -|_|_Projection: __correlated_sq_1.i_| |_|_MergeScan [is_placeholder=false, remote_input=[_| -|_| SubqueryAlias: __correlated_sq_1_| +|_| Projection: __correlated_sq_1.i_| +|_|_SubqueryAlias: __correlated_sq_1_| |_|_Projection: count(integers.i), integers.i_| |_|_Aggregate: groupBy=[[integers.i]], aggr=[[count(integers.i)]]_| |_|_Filter: integers.i IS NOT NULL_| @@ -217,7 +216,6 @@ EXPLAIN SELECT * FROM integers i1 WHERE EXISTS(SELECT count(i) FROM integers WHE |_|_RepartitionExec: partitioning=REDACTED |_|_MergeScanExec: REDACTED |_|_RepartitionExec: partitioning=REDACTED -|_|_ProjectionExec: expr=[i@1 as i]_| |_|_MergeScanExec: REDACTED |_|_| +-+-+ @@ -773,9 +771,9 @@ EXPLAIN SELECT (SELECT SUM(v) FROM nested_scalar_part WHERE v > (SELECT AVG(v) F |_| Aggregate: groupBy=[[]], aggr=[[__avg_state(CAST(nested_scalar_part.v AS Float64))]]_| |_|_TableScan: nested_scalar_part_| |_| ]]_| -|_|_Projection: nested_scalar_part.v_| |_|_MergeScan [is_placeholder=false, remote_input=[_| -|_| TableScan: nested_scalar_part_| +|_| Projection: nested_scalar_part.v_| +|_|_TableScan: nested_scalar_part_| |_| ]]_| |_|_Projection:_| |_|_Limit: skip=0, fetch=1_| @@ -795,7 +793,6 @@ EXPLAIN SELECT (SELECT SUM(v) FROM nested_scalar_part WHERE v > (SELECT AVG(v) F |_|_AggregateExec: mode=Partial, gby=[], aggr=[sum(nested_scalar_part.v)]_| |_|_FilterExec: CAST(v@0 AS Float64) > scalar_subquery()_| |_|_RepartitionExec: partitioning=REDACTED -|_|_ProjectionExec: expr=[v@1 as v]_| |_|_MergeScanExec: REDACTED |_|_AggregateExec: mode=Final, gby=[], aggr=[__avg_merge(__avg_state(nested_scalar_part.v)) as avg(nested_scalar_part.v)]_| |_|_CoalescePartitionsExec_| diff --git a/tests/cases/distributed/information_schema/ssts_limit.result b/tests/cases/distributed/information_schema/ssts_limit.result index 67c6abf3cb1..a853efc1304 100644 --- a/tests/cases/distributed/information_schema/ssts_limit.result +++ b/tests/cases/distributed/information_schema/ssts_limit.result @@ -148,6 +148,330 @@ LIMIT 1 OFFSET 1; | 1970-01-01T00:00:00.002 | +-------------------------+ +-- Each datanode contributes aggregate states; the frontend merges them. +-- SQLNESS REPLACE (RepartitionExec:.*) RepartitionExec: REDACTED +EXPLAIN SELECT COUNT(*) AS files, COUNT(1) AS files_one, SUM(file_size) AS bytes, + COUNT(*) FILTER (WHERE file_size >= 1) AS nonempty_files, + SUM(file_size) FILTER (WHERE file_size = 0) AS zero_bytes +FROM information_schema.ssts_manifest +WHERE table_id > 0 AND region_id > 0 + AND min_ts >= '1970-01-01T00:00:00.002Z'::TIMESTAMP_NS + AND max_ts < '1970-01-01T00:00:00.004Z'::TIMESTAMP_NS; + ++---------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| plan_type | plan | ++---------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| logical_plan | Projection: count(Int64(1)) AS count(*) AS files, count(Int64(1)) AS files_one, sum(information_schema.ssts_manifest.file_size) AS bytes, count(Int64(1)) FILTER (WHERE information_schema.ssts_manifest.file_size >= Int64(1)) AS count(*) FILTER (WHERE information_schema.ssts_manifest.file_size >= Int64(1)) AS nonempty_files, sum(information_schema.ssts_manifest.file_size) FILTER (WHERE information_schema.ssts_manifest.file_size = Int64(0)) AS zero_bytes | +| | Aggregate: groupBy=[[]], aggr=[[__count_merge(__count_state(Int64(1))) AS count(Int64(1)), __sum_merge(__sum_state(information_schema.ssts_manifest.file_size)) AS sum(information_schema.ssts_manifest.file_size), __count_merge(__count_state(Int64(1)) FILTER (WHERE CAST(information_schema.ssts_manifest.file_size AS Decimal128(20, 0)) >= CAST(Int64(1) AS Decimal128(20, 0)))) AS count(Int64(1)) FILTER (WHERE information_schema.ssts_manifest.file_size >= Int64(1)), __sum_merge(__sum_state(information_schema.ssts_manifest.file_size) FILTER (WHERE CAST(information_schema.ssts_manifest.file_size AS Decimal128(20, 0)) = CAST(Int64(0) AS Decimal128(20, 0)))) AS sum(information_schema.ssts_manifest.file_size) FILTER (WHERE information_schema.ssts_manifest.file_size = Int64(0))]] | +| | SstManifestAggregate: Aggregate: groupBy=[[]], aggr=[[__count_state(Int64(1)), __sum_state(information_schema.ssts_manifest.file_size), __count_state(Int64(1)) FILTER (WHERE CAST(information_schema.ssts_manifest.file_size AS Decimal128(20, 0)) >= CAST(Int64(1) AS Decimal128(20, 0))), __sum_state(information_schema.ssts_manifest.file_size) FILTER (WHERE CAST(information_schema.ssts_manifest.file_size AS Decimal128(20, 0)) = CAST(Int64(0) AS Decimal128(20, 0)))]] | +| | Filter: information_schema.ssts_manifest.table_id > UInt32(0) AND CAST(information_schema.ssts_manifest.region_id AS Decimal128(20, 0)) > CAST(Int64(0) AS Decimal128(20, 0)) AND information_schema.ssts_manifest.min_ts >= arrow_cast(Utf8("1970-01-01T00:00:00.002Z"), Utf8("Timestamp(ns)")) AND information_schema.ssts_manifest.max_ts < arrow_cast(Utf8("1970-01-01T00:00:00.004Z"), Utf8("Timestamp(ns)")) | +| | SubqueryAlias: information_schema.ssts_manifest | +| | TableScan: __inspect/__mito/__sst_manifest | +| physical_plan | ProjectionExec: expr=[count(Int64(1))@0 as files, count(Int64(1))@0 as files_one, sum(information_schema.ssts_manifest.file_size)@1 as bytes, count(Int64(1)) FILTER (WHERE information_schema.ssts_manifest.file_size >= Int64(1))@2 as nonempty_files, sum(information_schema.ssts_manifest.file_size) FILTER (WHERE information_schema.ssts_manifest.file_size = Int64(0))@3 as zero_bytes] | +| | AggregateExec: mode=Final, gby=[], aggr=[__count_merge(__count_state(Int64(1))) as count(Int64(1)), __sum_merge(__sum_state(information_schema.ssts_manifest.file_size)) as sum(information_schema.ssts_manifest.file_size), __count_merge(__count_state(Int64(1)) FILTER (WHERE CAST(information_schema.ssts_manifest.file_size AS Decimal128(20, 0)) >= CAST(Int64(1) AS Decimal128(20, 0)))) as count(Int64(1)) FILTER (WHERE information_schema.ssts_manifest.file_size >= Int64(1)), __sum_merge(__sum_state(information_schema.ssts_manifest.file_size) FILTER (WHERE CAST(information_schema.ssts_manifest.file_size AS Decimal128(20, 0)) = CAST(Int64(0) AS Decimal128(20, 0)))) as sum(information_schema.ssts_manifest.file_size) FILTER (WHERE information_schema.ssts_manifest.file_size = Int64(0))] | +| | CoalescePartitionsExec | +| | AggregateExec: mode=Partial, gby=[], aggr=[__count_merge(__count_state(Int64(1))) as count(Int64(1)), __sum_merge(__sum_state(information_schema.ssts_manifest.file_size)) as sum(information_schema.ssts_manifest.file_size), __count_merge(__count_state(Int64(1)) FILTER (WHERE CAST(information_schema.ssts_manifest.file_size AS Decimal128(20, 0)) >= CAST(Int64(1) AS Decimal128(20, 0)))) as count(Int64(1)) FILTER (WHERE information_schema.ssts_manifest.file_size >= Int64(1)), __sum_merge(__sum_state(information_schema.ssts_manifest.file_size) FILTER (WHERE CAST(information_schema.ssts_manifest.file_size AS Decimal128(20, 0)) = CAST(Int64(0) AS Decimal128(20, 0)))) as sum(information_schema.ssts_manifest.file_size) FILTER (WHERE information_schema.ssts_manifest.file_size = Int64(0))] | +| | RepartitionExec: REDACTED +| | DistributedInspectExec: query=Aggregate: groupBy=[[]], aggr=[[__count_state(Int64(1)), __sum_state(information_schema.ssts_manifest.file_size), __count_state(Int64(1)) FILTER (WHERE CAST(information_schema.ssts_manifest.file_size AS Decimal128(20, 0)) >= CAST(Int64(1) AS Decimal128(20, 0))), __sum_state(information_schema.ssts_manifest.file_size) FILTER (WHERE CAST(information_schema.ssts_manifest.file_size AS Decimal128(20, 0)) = CAST(Int64(0) AS Decimal128(20, 0)))]] | +| | Filter: information_schema.ssts_manifest.table_id > UInt32(0) AND CAST(information_schema.ssts_manifest.region_id AS Decimal128(20, 0)) > CAST(Int64(0) AS Decimal128(20, 0)) AND information_schema.ssts_manifest.min_ts >= arrow_cast(Utf8("1970-01-01T00:00:00.002Z"), Utf8("Timestamp(ns)")) AND information_schema.ssts_manifest.max_ts < arrow_cast(Utf8("1970-01-01T00:00:00.004Z"), Utf8("Timestamp(ns)")) | +| | SubqueryAlias: information_schema.ssts_manifest | +| | TableScan: __inspect/__mito/__sst_manifest, schema=Schema { fields: [Field { name: "__count_state(Int64(1))", data_type: Struct([Field { name: "count[count]", data_type: Int64, nullable: true }]) }, Field { name: "__sum_state(information_schema.ssts_manifest.file_size)", data_type: Struct([Field { name: "sum[sum]", data_type: UInt64, nullable: true }]), nullable: true }, Field { name: "__count_state(Int64(1)) FILTER (WHERE CAST(information_schema.ssts_manifest.file_size AS Decimal128(20, 0)) >= CAST(Int64(1) AS Decimal128(20, 0)))", data_type: Struct([Field { name: "count[count]", data_type: Int64, nullable: true }]) }, Field { name: "__sum_state(information_schema.ssts_manifest.file_size) FILTER (WHERE CAST(information_schema.ssts_manifest.file_size AS Decimal128(20, 0)) = CAST(Int64(0) AS Decimal128(20, 0)))", data_type: Struct([Field { name: "sum[sum]", data_type: UInt64, nullable: true }]), nullable: true }], metadata: {"greptime:version": "0"} } | +| | | ++---------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ + +-- Compare exact byte totals with a limited-input query that must not push +-- aggregation through its global limit. The limit exceeds this fixture's size. +WITH pushed AS ( + SELECT COUNT(*) AS files, COUNT(1) AS files_one, SUM(file_size) AS bytes, + COUNT(*) FILTER (WHERE file_size >= 1) AS nonempty_files, + SUM(file_size) FILTER (WHERE file_size >= 1) AS nonempty_bytes, + COUNT(*) FILTER (WHERE file_size = 0) AS zero_files, + SUM(file_size) FILTER (WHERE file_size = 0) AS zero_bytes + FROM information_schema.ssts_manifest + WHERE table_id > 0 AND region_id > 0 + AND min_ts >= '1970-01-01T00:00:00.002Z'::TIMESTAMP_NS + AND max_ts < '1970-01-01T00:00:00.004Z'::TIMESTAMP_NS +), fallback AS ( + SELECT COUNT(*) AS files, SUM(file_size) AS bytes + FROM ( + SELECT file_size FROM information_schema.ssts_manifest + WHERE table_id > 0 AND region_id > 0 + AND min_ts >= '1970-01-01T00:00:00.002Z'::TIMESTAMP_NS + AND max_ts < '1970-01-01T00:00:00.004Z'::TIMESTAMP_NS + LIMIT 1000 + ) +) +SELECT pushed.files, pushed.files_one, pushed.nonempty_files, pushed.zero_files, + pushed.files = fallback.files AS same_count, + pushed.bytes = fallback.bytes AS same_bytes, + pushed.nonempty_bytes = fallback.bytes AS same_filtered_bytes, + pushed.zero_bytes IS NULL AS empty_filtered_sum +FROM pushed CROSS JOIN fallback; + ++-------+-----------+----------------+------------+------------+------------+---------------------+--------------------+ +| files | files_one | nonempty_files | zero_files | same_count | same_bytes | same_filtered_bytes | empty_filtered_sum | ++-------+-----------+----------------+------------+------------+------------+---------------------+--------------------+ +| 2 | 2 | 2 | 0 | true | true | true | true | ++-------+-----------+----------------+------------+------------+------------+---------------------+--------------------+ + +-- All nodes have empty input: COUNT returns zero, while SUM remains NULL. +SELECT COUNT(*) AS files, COUNT(1) AS files_one, SUM(file_size) AS bytes, + COUNT(*) FILTER (WHERE file_size >= 1) AS nonempty_files, + SUM(file_size) FILTER (WHERE file_size >= 1) AS nonempty_bytes +FROM information_schema.ssts_manifest WHERE region_id = 0; + ++-------+-----------+-------+----------------+----------------+ +| files | files_one | bytes | nonempty_files | nonempty_bytes | ++-------+-----------+-------+----------------+----------------+ +| 0 | 0 | | 0 | | ++-------+-----------+-------+----------------+----------------+ + +-- SQLNESS REPLACE (RepartitionExec:.*) RepartitionExec: REDACTED +EXPLAIN SELECT COUNT(*), SUM(file_size) +FROM (SELECT file_size FROM information_schema.ssts_manifest LIMIT 1); + ++---------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| plan_type | plan | ++---------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| logical_plan | MergeScan [is_placeholder=false, remote_input=[ | +| | Projection: count(Int64(1)) AS count(*), sum(information_schema.ssts_manifest.file_size) | +| | Aggregate: groupBy=[[]], aggr=[[count(Int64(1)), sum(information_schema.ssts_manifest.file_size)]] | +| | Limit: skip=0, fetch=1 | +| | Projection: information_schema.ssts_manifest.file_size | +| | TableScan: information_schema.ssts_manifest | +| | ]] | +| physical_plan | ProjectionExec: expr=[count(Int64(1))@0 as count(*), sum(information_schema.ssts_manifest.file_size)@1 as sum(information_schema.ssts_manifest.file_size)] | +| | AggregateExec: mode=Final, gby=[], aggr=[count(Int64(1)), sum(information_schema.ssts_manifest.file_size)] | +| | CoalescePartitionsExec | +| | AggregateExec: mode=Partial, gby=[], aggr=[count(Int64(1)), sum(information_schema.ssts_manifest.file_size)] | +| | RepartitionExec: REDACTED +| | GlobalLimitExec: skip=0, fetch=1 | +| | DistributedInspectExec: kind=SstManifest, scan=ScanRequest { projection: [10], limit: 1 }, schema=Schema { fields: [Field { name: "file_size", data_type: UInt64 }], metadata: {"greptime:version": "0"} } | +| | | ++---------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ + +SELECT COUNT(*) AS files, SUM(file_size) > 0 AS has_bytes +FROM (SELECT file_size FROM information_schema.ssts_manifest LIMIT 1); + ++-------+-----------+ +| files | has_bytes | ++-------+-----------+ +| 1 | true | ++-------+-----------+ + +-- Other aggregate shapes retain ordinary query execution. +SELECT level, COUNT(*) AS files, SUM(file_size) > 0 AS has_bytes +FROM information_schema.ssts_manifest GROUP BY level ORDER BY level; + ++-------+-------+-----------+ +| level | files | has_bytes | ++-------+-------+-----------+ +| 0 | 3 | true | ++-------+-------+-----------+ + +SELECT COUNT(DISTINCT region_id) AS distinct_regions, + SUM(file_size + 1) = SUM(file_size) + COUNT(*) AS complex_input_matches +FROM information_schema.ssts_manifest; + ++------------------+-----------------------+ +| distinct_regions | complex_input_matches | ++------------------+-----------------------+ +| 3 | true | ++------------------+-----------------------+ + +-- Non-file-size columns and general aggregate filters use the same state merge. +-- SQLNESS REPLACE (RepartitionExec:.*) RepartitionExec: REDACTED +EXPLAIN SELECT COUNT(file_id), SUM(num_rows), SUM(level), SUM(table_id), + SUM(CAST(num_row_groups AS DOUBLE)), SUM(CAST(max_row_group_uncompressed_size AS DECIMAL(20, 0))), + COUNT(index_file_size), SUM(index_file_size), + COUNT(*) FILTER (WHERE visible AND level = 0) +FROM information_schema.ssts_manifest WHERE region_id > 0; + ++---------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| plan_type | plan | ++---------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| logical_plan | Projection: count(information_schema.ssts_manifest.file_id), sum(information_schema.ssts_manifest.num_rows), sum(information_schema.ssts_manifest.level), sum(information_schema.ssts_manifest.table_id), sum(information_schema.ssts_manifest.num_row_groups), sum(information_schema.ssts_manifest.max_row_group_uncompressed_size), count(information_schema.ssts_manifest.index_file_size), sum(information_schema.ssts_manifest.index_file_size), count(Int64(1)) FILTER (WHERE information_schema.ssts_manifest.visible AND information_schema.ssts_manifest.level = Int64(0)) AS count(*) FILTER (WHERE information_schema.ssts_manifest.visible AND information_schema.ssts_manifest.level = Int64(0)) | +| | Aggregate: groupBy=[[]], aggr=[[__count_merge(__count_state(information_schema.ssts_manifest.file_id)) AS count(information_schema.ssts_manifest.file_id), __sum_merge(__sum_state(information_schema.ssts_manifest.num_rows)) AS sum(information_schema.ssts_manifest.num_rows), __sum_merge(__sum_state(information_schema.ssts_manifest.level)) AS sum(information_schema.ssts_manifest.level), __sum_merge(__sum_state(information_schema.ssts_manifest.table_id)) AS sum(information_schema.ssts_manifest.table_id), __sum_merge(__sum_state(information_schema.ssts_manifest.num_row_groups)) AS sum(information_schema.ssts_manifest.num_row_groups), __sum_merge(__sum_state(information_schema.ssts_manifest.max_row_group_uncompressed_size)) AS sum(information_schema.ssts_manifest.max_row_group_uncompressed_size), __count_merge(__count_state(information_schema.ssts_manifest.index_file_size)) AS count(information_schema.ssts_manifest.index_file_size), __sum_merge(__sum_state(information_schema.ssts_manifest.index_file_size)) AS sum(information_schema.ssts_manifest.index_file_size), __count_merge(__count_state(Int64(1)) FILTER (WHERE information_schema.ssts_manifest.visible AND CAST(information_schema.ssts_manifest.level AS Int64) = Int64(0))) AS count(Int64(1)) FILTER (WHERE information_schema.ssts_manifest.visible AND information_schema.ssts_manifest.level = Int64(0))]] | +| | SstManifestAggregate: Aggregate: groupBy=[[]], aggr=[[__count_state(information_schema.ssts_manifest.file_id), __sum_state(information_schema.ssts_manifest.num_rows), __sum_state(CAST(information_schema.ssts_manifest.level AS UInt64)), __sum_state(CAST(information_schema.ssts_manifest.table_id AS UInt64)), __sum_state(CAST(information_schema.ssts_manifest.num_row_groups AS Float64)), __sum_state(CAST(information_schema.ssts_manifest.max_row_group_uncompressed_size AS Decimal128(20, 0))), __count_state(information_schema.ssts_manifest.index_file_size), __sum_state(information_schema.ssts_manifest.index_file_size), __count_state(Int64(1)) FILTER (WHERE information_schema.ssts_manifest.visible AND CAST(information_schema.ssts_manifest.level AS Int64) = Int64(0))]] | +| | Filter: CAST(information_schema.ssts_manifest.region_id AS Decimal128(20, 0)) > CAST(Int64(0) AS Decimal128(20, 0)) | +| | SubqueryAlias: information_schema.ssts_manifest | +| | TableScan: __inspect/__mito/__sst_manifest | +| physical_plan | ProjectionExec: expr=[count(information_schema.ssts_manifest.file_id)@0 as count(information_schema.ssts_manifest.file_id), sum(information_schema.ssts_manifest.num_rows)@1 as sum(information_schema.ssts_manifest.num_rows), sum(information_schema.ssts_manifest.level)@2 as sum(information_schema.ssts_manifest.level), sum(information_schema.ssts_manifest.table_id)@3 as sum(information_schema.ssts_manifest.table_id), sum(information_schema.ssts_manifest.num_row_groups)@4 as sum(information_schema.ssts_manifest.num_row_groups), sum(information_schema.ssts_manifest.max_row_group_uncompressed_size)@5 as sum(information_schema.ssts_manifest.max_row_group_uncompressed_size), count(information_schema.ssts_manifest.index_file_size)@6 as count(information_schema.ssts_manifest.index_file_size), sum(information_schema.ssts_manifest.index_file_size)@7 as sum(information_schema.ssts_manifest.index_file_size), count(Int64(1)) FILTER (WHERE information_schema.ssts_manifest.visible AND information_schema.ssts_manifest.level = Int64(0))@8 as count(*) FILTER (WHERE information_schema.ssts_manifest.visible AND information_schema.ssts_manifest.level = Int64(0))] | +| | AggregateExec: mode=Final, gby=[], aggr=[__count_merge(__count_state(information_schema.ssts_manifest.file_id)) as count(information_schema.ssts_manifest.file_id), __sum_merge(__sum_state(information_schema.ssts_manifest.num_rows)) as sum(information_schema.ssts_manifest.num_rows), __sum_merge(__sum_state(information_schema.ssts_manifest.level)) as sum(information_schema.ssts_manifest.level), __sum_merge(__sum_state(information_schema.ssts_manifest.table_id)) as sum(information_schema.ssts_manifest.table_id), __sum_merge(__sum_state(information_schema.ssts_manifest.num_row_groups)) as sum(information_schema.ssts_manifest.num_row_groups), __sum_merge(__sum_state(information_schema.ssts_manifest.max_row_group_uncompressed_size)) as sum(information_schema.ssts_manifest.max_row_group_uncompressed_size), __count_merge(__count_state(information_schema.ssts_manifest.index_file_size)) as count(information_schema.ssts_manifest.index_file_size), __sum_merge(__sum_state(information_schema.ssts_manifest.index_file_size)) as sum(information_schema.ssts_manifest.index_file_size), __count_merge(__count_state(Int64(1)) FILTER (WHERE information_schema.ssts_manifest.visible AND CAST(information_schema.ssts_manifest.level AS Int64) = Int64(0))) as count(Int64(1)) FILTER (WHERE information_schema.ssts_manifest.visible AND information_schema.ssts_manifest.level = Int64(0))] | +| | CoalescePartitionsExec | +| | AggregateExec: mode=Partial, gby=[], aggr=[__count_merge(__count_state(information_schema.ssts_manifest.file_id)) as count(information_schema.ssts_manifest.file_id), __sum_merge(__sum_state(information_schema.ssts_manifest.num_rows)) as sum(information_schema.ssts_manifest.num_rows), __sum_merge(__sum_state(information_schema.ssts_manifest.level)) as sum(information_schema.ssts_manifest.level), __sum_merge(__sum_state(information_schema.ssts_manifest.table_id)) as sum(information_schema.ssts_manifest.table_id), __sum_merge(__sum_state(information_schema.ssts_manifest.num_row_groups)) as sum(information_schema.ssts_manifest.num_row_groups), __sum_merge(__sum_state(information_schema.ssts_manifest.max_row_group_uncompressed_size)) as sum(information_schema.ssts_manifest.max_row_group_uncompressed_size), __count_merge(__count_state(information_schema.ssts_manifest.index_file_size)) as count(information_schema.ssts_manifest.index_file_size), __sum_merge(__sum_state(information_schema.ssts_manifest.index_file_size)) as sum(information_schema.ssts_manifest.index_file_size), __count_merge(__count_state(Int64(1)) FILTER (WHERE information_schema.ssts_manifest.visible AND CAST(information_schema.ssts_manifest.level AS Int64) = Int64(0))) as count(Int64(1)) FILTER (WHERE information_schema.ssts_manifest.visible AND information_schema.ssts_manifest.level = Int64(0))] | +| | RepartitionExec: REDACTED +| | DistributedInspectExec: query=Aggregate: groupBy=[[]], aggr=[[__count_state(information_schema.ssts_manifest.file_id), __sum_state(information_schema.ssts_manifest.num_rows), __sum_state(CAST(information_schema.ssts_manifest.level AS UInt64)), __sum_state(CAST(information_schema.ssts_manifest.table_id AS UInt64)), __sum_state(CAST(information_schema.ssts_manifest.num_row_groups AS Float64)), __sum_state(CAST(information_schema.ssts_manifest.max_row_group_uncompressed_size AS Decimal128(20, 0))), __count_state(information_schema.ssts_manifest.index_file_size), __sum_state(information_schema.ssts_manifest.index_file_size), __count_state(Int64(1)) FILTER (WHERE information_schema.ssts_manifest.visible AND CAST(information_schema.ssts_manifest.level AS Int64) = Int64(0))]] | +| | Filter: CAST(information_schema.ssts_manifest.region_id AS Decimal128(20, 0)) > CAST(Int64(0) AS Decimal128(20, 0)) | +| | SubqueryAlias: information_schema.ssts_manifest | +| | TableScan: __inspect/__mito/__sst_manifest, schema=Schema { fields: [Field { name: "__count_state(information_schema.ssts_manifest.file_id)", data_type: Struct([Field { name: "count[count]", data_type: Int64, nullable: true }]) }, Field { name: "__sum_state(information_schema.ssts_manifest.num_rows)", data_type: Struct([Field { name: "sum[sum]", data_type: UInt64, nullable: true }]), nullable: true }, Field { name: "__sum_state(information_schema.ssts_manifest.level)", data_type: Struct([Field { name: "sum[sum]", data_type: UInt64, nullable: true }]), nullable: true }, Field { name: "__sum_state(information_schema.ssts_manifest.table_id)", data_type: Struct([Field { name: "sum[sum]", data_type: UInt64, nullable: true }]), nullable: true }, Field { name: "__sum_state(information_schema.ssts_manifest.num_row_groups)", data_type: Struct([Field { name: "sum[sum]", data_type: Float64, nullable: true }]), nullable: true }, Field { name: "__sum_state(information_schema.ssts_manifest.max_row_group_uncompressed_size)", data_type: Struct([Field { name: "sum[sum]", data_type: Decimal128(30, 0), nullable: true }]), nullable: true }, Field { name: "__count_state(information_schema.ssts_manifest.index_file_size)", data_type: Struct([Field { name: "count[count]", data_type: Int64, nullable: true }]) }, Field { name: "__sum_state(information_schema.ssts_manifest.index_file_size)", data_type: Struct([Field { name: "sum[sum]", data_type: UInt64, nullable: true }]), nullable: true }, Field { name: "__count_state(Int64(1)) FILTER (WHERE information_schema.ssts_manifest.visible AND CAST(information_schema.ssts_manifest.level AS Int64) = Int64(0))", data_type: Struct([Field { name: "count[count]", data_type: Int64, nullable: true }]) }], metadata: {"greptime:version": "0"} } | +| | | ++---------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ + +WITH pushed AS ( + SELECT COUNT(file_id) AS files, COUNT(index_file_size) AS indexes, + SUM(num_rows) AS rows, SUM(level) AS levels, SUM(table_id) AS tables, + SUM(index_file_size) AS index_bytes, + SUM(CAST(num_row_groups AS DOUBLE)) AS float_groups, + SUM(CAST(max_row_group_uncompressed_size AS DECIMAL(20, 0))) AS decimal_bytes, + COUNT(*) FILTER (WHERE visible AND level = 0) AS visible_files, + SUM(num_rows) FILTER (WHERE min_ts >= '1970-01-01T00:00:00.002Z'::TIMESTAMP_NS) AS recent_rows + FROM information_schema.ssts_manifest WHERE region_id > 0 +), fallback AS ( + SELECT COUNT(file_id) AS files, COUNT(index_file_size) AS indexes, + SUM(num_rows) AS rows, SUM(level) AS levels, SUM(table_id) AS tables, + SUM(index_file_size) AS index_bytes, + SUM(CAST(num_row_groups AS DOUBLE)) AS float_groups, + SUM(CAST(max_row_group_uncompressed_size AS DECIMAL(20, 0))) AS decimal_bytes, + COUNT(*) FILTER (WHERE visible AND level = 0) AS visible_files, + SUM(num_rows) FILTER (WHERE min_ts >= '1970-01-01T00:00:00.002Z'::TIMESTAMP_NS) AS recent_rows + FROM (SELECT * FROM information_schema.ssts_manifest WHERE region_id > 0 LIMIT 1000) +) +SELECT pushed.files = fallback.files AS same_count, + pushed.indexes = fallback.indexes AS same_nullable_count, + pushed.rows = fallback.rows AS same_rows, + pushed.float_groups = fallback.float_groups AS same_float_groups, + pushed.decimal_bytes = fallback.decimal_bytes AS same_decimal_bytes, + pushed.levels = fallback.levels AS same_levels, + pushed.tables = fallback.tables AS same_tables, + pushed.index_bytes IS NOT DISTINCT FROM fallback.index_bytes AS same_index_bytes, + pushed.visible_files = fallback.visible_files AS same_visible_count, + pushed.recent_rows IS NOT DISTINCT FROM fallback.recent_rows AS same_recent_rows +FROM pushed CROSS JOIN fallback; + ++------------+---------------------+-----------+-------------------+--------------------+-------------+-------------+------------------+--------------------+------------------+ +| same_count | same_nullable_count | same_rows | same_float_groups | same_decimal_bytes | same_levels | same_tables | same_index_bytes | same_visible_count | same_recent_rows | ++------------+---------------------+-----------+-------------------+--------------------+-------------+-------------+------------------+--------------------+------------------+ +| true | true | true | true | true | true | true | true | true | true | ++------------+---------------------+-----------+-------------------+--------------------+-------------+-------------+------------------+--------------------+------------------+ + +-- Unsupported aggregate state types stay on the frontend, including mixed aggregates. +-- SQLNESS REPLACE (RepartitionExec:.*) RepartitionExec: REDACTED +EXPLAIN SELECT COUNT(*), CAST(SUM(CAST(file_size AS DECIMAL(39, 0))) AS DOUBLE) +FROM information_schema.ssts_manifest; + ++---------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| plan_type | plan | ++---------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| logical_plan | MergeScan [is_placeholder=false, remote_input=[ | +| | Projection: count(Int64(1)) AS count(*), CAST(sum(information_schema.ssts_manifest.file_size) AS Float64) | +| | Aggregate: groupBy=[[]], aggr=[[count(Int64(1)), sum(CAST(information_schema.ssts_manifest.file_size AS Decimal256(39, 0)))]] | +| | TableScan: information_schema.ssts_manifest | +| | ]] | +| physical_plan | ProjectionExec: expr=[count(Int64(1))@0 as count(*), CAST(sum(information_schema.ssts_manifest.file_size)@1 AS Float64) as sum(information_schema.ssts_manifest.file_size)] | +| | AggregateExec: mode=Final, gby=[], aggr=[count(Int64(1)), sum(information_schema.ssts_manifest.file_size)] | +| | CoalescePartitionsExec | +| | AggregateExec: mode=Partial, gby=[], aggr=[count(Int64(1)), sum(information_schema.ssts_manifest.file_size)] | +| | RepartitionExec: REDACTED +| | DistributedInspectExec: kind=SstManifest, scan=ScanRequest { projection: [10] }, schema=Schema { fields: [Field { name: "file_size", data_type: UInt64 }], metadata: {"greptime:version": "0"} } | +| | | ++---------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ + +WITH candidate AS ( + SELECT COUNT(*) AS files, + CAST(SUM(CAST(file_size AS DECIMAL(39, 0))) AS DOUBLE) AS bytes + FROM information_schema.ssts_manifest +), baseline AS ( + SELECT COUNT(*) AS files, + CAST(SUM(CAST(file_size AS DECIMAL(39, 0))) AS DOUBLE) AS bytes + FROM (SELECT file_size FROM information_schema.ssts_manifest LIMIT 1000) +) +SELECT candidate.files = baseline.files AS same_count, + candidate.bytes = baseline.bytes AS same_bytes +FROM candidate CROSS JOIN baseline; + ++------------+------------+ +| same_count | same_bytes | ++------------+------------+ +| true | true | ++------------+------------+ + +-- Timezone-bearing implicit casts must remain on the frontend. +-- The inner LIMIT blocks aggregate pushdown without truncating the fixture. +WITH candidate AS ( + SELECT COUNT(*) FILTER (WHERE min_ts < arrow_cast('1970-01-01T04:00:00', 'Timestamp(Nanosecond, Some("+08:00"))')) AS files, + SUM(file_size) FILTER (WHERE min_ts < arrow_cast('1970-01-01T04:00:00', 'Timestamp(Nanosecond, Some("+08:00"))')) AS bytes + FROM information_schema.ssts_manifest +), fallback AS ( + SELECT COUNT(*) FILTER (WHERE min_ts < arrow_cast('1970-01-01T04:00:00', 'Timestamp(Nanosecond, Some("+08:00"))')) AS files, + SUM(file_size) FILTER (WHERE min_ts < arrow_cast('1970-01-01T04:00:00', 'Timestamp(Nanosecond, Some("+08:00"))')) AS bytes + FROM (SELECT * FROM information_schema.ssts_manifest LIMIT 1000) +) +SELECT candidate.files, fallback.files AS expected_files, + candidate.files = fallback.files AS same_count, + candidate.bytes = fallback.bytes AS same_bytes +FROM candidate CROSS JOIN fallback; + ++-------+----------------+------------+------------+ +| files | expected_files | same_count | same_bytes | ++-------+----------------+------------+------------+ +| 3 | 3 | true | true | ++-------+----------------+------------+------------+ + +-- Apply the same transport boundary to a WHERE predicate below the aggregate. +WITH candidate AS ( + SELECT COUNT(*) AS files, SUM(file_size) AS bytes + FROM information_schema.ssts_manifest + WHERE min_ts < arrow_cast('1970-01-01T04:00:00', 'Timestamp(Nanosecond, Some("+08:00"))') +), fallback AS ( + SELECT COUNT(*) AS files, SUM(file_size) AS bytes + FROM (SELECT * FROM information_schema.ssts_manifest LIMIT 1000) + WHERE min_ts < arrow_cast('1970-01-01T04:00:00', 'Timestamp(Nanosecond, Some("+08:00"))') +) +SELECT candidate.files, fallback.files AS expected_files, + candidate.files = fallback.files AS same_count, + candidate.bytes = fallback.bytes AS same_bytes +FROM candidate CROSS JOIN fallback; + ++-------+----------------+------------+------------+ +| files | expected_files | same_count | same_bytes | ++-------+----------------+------------+------------+ +| 3 | 3 | true | true | ++-------+----------------+------------+------------+ + +-- Unsupported intermediate types must not enter the remote plan. +-- The inner LIMIT blocks aggregate pushdown without truncating the fixture. +WITH candidate AS ( + SELECT COUNT(*) FILTER (WHERE arrow_cast(1, 'Decimal32(9, 0)') > arrow_cast(0, 'Decimal32(9, 0)')) AS files, + SUM(file_size) FILTER (WHERE arrow_cast(1, 'Decimal32(9, 0)') > arrow_cast(0, 'Decimal32(9, 0)')) AS bytes + FROM information_schema.ssts_manifest +), fallback AS ( + SELECT COUNT(*) FILTER (WHERE arrow_cast(1, 'Decimal32(9, 0)') > arrow_cast(0, 'Decimal32(9, 0)')) AS files, + SUM(file_size) FILTER (WHERE arrow_cast(1, 'Decimal32(9, 0)') > arrow_cast(0, 'Decimal32(9, 0)')) AS bytes + FROM (SELECT * FROM information_schema.ssts_manifest LIMIT 1000) +) +SELECT candidate.files, fallback.files AS expected_files, + candidate.files = fallback.files AS same_count, + candidate.bytes = fallback.bytes AS same_bytes +FROM candidate CROSS JOIN fallback; + ++-------+----------------+------------+------------+ +| files | expected_files | same_count | same_bytes | ++-------+----------------+------------+------------+ +| 3 | 3 | true | true | ++-------+----------------+------------+------------+ + +-- Apply the same transport boundary to a WHERE predicate below the aggregate. +WITH candidate AS ( + SELECT COUNT(*) AS files, SUM(file_size) AS bytes + FROM information_schema.ssts_manifest + WHERE arrow_cast(1, 'Decimal32(9, 0)') > arrow_cast(0, 'Decimal32(9, 0)') +), fallback AS ( + SELECT COUNT(*) AS files, SUM(file_size) AS bytes + FROM (SELECT * FROM information_schema.ssts_manifest LIMIT 1000) + WHERE arrow_cast(1, 'Decimal32(9, 0)') > arrow_cast(0, 'Decimal32(9, 0)') +) +SELECT candidate.files, fallback.files AS expected_files, + candidate.files = fallback.files AS same_count, + candidate.bytes = fallback.bytes AS same_bytes +FROM candidate CROSS JOIN fallback; + ++-------+----------------+------------+------------+ +| files | expected_files | same_count | same_bytes | ++-------+----------------+------------+------------+ +| 3 | 3 | true | true | ++-------+----------------+------------+------------+ + DROP TABLE ssts_limit_case; Affected Rows: 0 diff --git a/tests/cases/distributed/information_schema/ssts_limit.sql b/tests/cases/distributed/information_schema/ssts_limit.sql index e634f7a2378..a63c9252189 100644 --- a/tests/cases/distributed/information_schema/ssts_limit.sql +++ b/tests/cases/distributed/information_schema/ssts_limit.sql @@ -66,4 +66,183 @@ WHERE region_id > 0 AND min_ts >= '1970-01-01T00:00:00.002Z'::TIMESTAMP_NS ORDER BY min_ts DESC LIMIT 1 OFFSET 1; +-- Each datanode contributes aggregate states; the frontend merges them. +-- SQLNESS REPLACE (RepartitionExec:.*) RepartitionExec: REDACTED +EXPLAIN SELECT COUNT(*) AS files, COUNT(1) AS files_one, SUM(file_size) AS bytes, + COUNT(*) FILTER (WHERE file_size >= 1) AS nonempty_files, + SUM(file_size) FILTER (WHERE file_size = 0) AS zero_bytes +FROM information_schema.ssts_manifest +WHERE table_id > 0 AND region_id > 0 + AND min_ts >= '1970-01-01T00:00:00.002Z'::TIMESTAMP_NS + AND max_ts < '1970-01-01T00:00:00.004Z'::TIMESTAMP_NS; + +-- Compare exact byte totals with a limited-input query that must not push +-- aggregation through its global limit. The limit exceeds this fixture's size. +WITH pushed AS ( + SELECT COUNT(*) AS files, COUNT(1) AS files_one, SUM(file_size) AS bytes, + COUNT(*) FILTER (WHERE file_size >= 1) AS nonempty_files, + SUM(file_size) FILTER (WHERE file_size >= 1) AS nonempty_bytes, + COUNT(*) FILTER (WHERE file_size = 0) AS zero_files, + SUM(file_size) FILTER (WHERE file_size = 0) AS zero_bytes + FROM information_schema.ssts_manifest + WHERE table_id > 0 AND region_id > 0 + AND min_ts >= '1970-01-01T00:00:00.002Z'::TIMESTAMP_NS + AND max_ts < '1970-01-01T00:00:00.004Z'::TIMESTAMP_NS +), fallback AS ( + SELECT COUNT(*) AS files, SUM(file_size) AS bytes + FROM ( + SELECT file_size FROM information_schema.ssts_manifest + WHERE table_id > 0 AND region_id > 0 + AND min_ts >= '1970-01-01T00:00:00.002Z'::TIMESTAMP_NS + AND max_ts < '1970-01-01T00:00:00.004Z'::TIMESTAMP_NS + LIMIT 1000 + ) +) +SELECT pushed.files, pushed.files_one, pushed.nonempty_files, pushed.zero_files, + pushed.files = fallback.files AS same_count, + pushed.bytes = fallback.bytes AS same_bytes, + pushed.nonempty_bytes = fallback.bytes AS same_filtered_bytes, + pushed.zero_bytes IS NULL AS empty_filtered_sum +FROM pushed CROSS JOIN fallback; + +-- All nodes have empty input: COUNT returns zero, while SUM remains NULL. +SELECT COUNT(*) AS files, COUNT(1) AS files_one, SUM(file_size) AS bytes, + COUNT(*) FILTER (WHERE file_size >= 1) AS nonempty_files, + SUM(file_size) FILTER (WHERE file_size >= 1) AS nonempty_bytes +FROM information_schema.ssts_manifest WHERE region_id = 0; + +-- SQLNESS REPLACE (RepartitionExec:.*) RepartitionExec: REDACTED +EXPLAIN SELECT COUNT(*), SUM(file_size) +FROM (SELECT file_size FROM information_schema.ssts_manifest LIMIT 1); + +SELECT COUNT(*) AS files, SUM(file_size) > 0 AS has_bytes +FROM (SELECT file_size FROM information_schema.ssts_manifest LIMIT 1); + +-- Other aggregate shapes retain ordinary query execution. +SELECT level, COUNT(*) AS files, SUM(file_size) > 0 AS has_bytes +FROM information_schema.ssts_manifest GROUP BY level ORDER BY level; + +SELECT COUNT(DISTINCT region_id) AS distinct_regions, + SUM(file_size + 1) = SUM(file_size) + COUNT(*) AS complex_input_matches +FROM information_schema.ssts_manifest; + +-- Non-file-size columns and general aggregate filters use the same state merge. +-- SQLNESS REPLACE (RepartitionExec:.*) RepartitionExec: REDACTED +EXPLAIN SELECT COUNT(file_id), SUM(num_rows), SUM(level), SUM(table_id), + SUM(CAST(num_row_groups AS DOUBLE)), SUM(CAST(max_row_group_uncompressed_size AS DECIMAL(20, 0))), + COUNT(index_file_size), SUM(index_file_size), + COUNT(*) FILTER (WHERE visible AND level = 0) +FROM information_schema.ssts_manifest WHERE region_id > 0; + +WITH pushed AS ( + SELECT COUNT(file_id) AS files, COUNT(index_file_size) AS indexes, + SUM(num_rows) AS rows, SUM(level) AS levels, SUM(table_id) AS tables, + SUM(index_file_size) AS index_bytes, + SUM(CAST(num_row_groups AS DOUBLE)) AS float_groups, + SUM(CAST(max_row_group_uncompressed_size AS DECIMAL(20, 0))) AS decimal_bytes, + COUNT(*) FILTER (WHERE visible AND level = 0) AS visible_files, + SUM(num_rows) FILTER (WHERE min_ts >= '1970-01-01T00:00:00.002Z'::TIMESTAMP_NS) AS recent_rows + FROM information_schema.ssts_manifest WHERE region_id > 0 +), fallback AS ( + SELECT COUNT(file_id) AS files, COUNT(index_file_size) AS indexes, + SUM(num_rows) AS rows, SUM(level) AS levels, SUM(table_id) AS tables, + SUM(index_file_size) AS index_bytes, + SUM(CAST(num_row_groups AS DOUBLE)) AS float_groups, + SUM(CAST(max_row_group_uncompressed_size AS DECIMAL(20, 0))) AS decimal_bytes, + COUNT(*) FILTER (WHERE visible AND level = 0) AS visible_files, + SUM(num_rows) FILTER (WHERE min_ts >= '1970-01-01T00:00:00.002Z'::TIMESTAMP_NS) AS recent_rows + FROM (SELECT * FROM information_schema.ssts_manifest WHERE region_id > 0 LIMIT 1000) +) +SELECT pushed.files = fallback.files AS same_count, + pushed.indexes = fallback.indexes AS same_nullable_count, + pushed.rows = fallback.rows AS same_rows, + pushed.float_groups = fallback.float_groups AS same_float_groups, + pushed.decimal_bytes = fallback.decimal_bytes AS same_decimal_bytes, + pushed.levels = fallback.levels AS same_levels, + pushed.tables = fallback.tables AS same_tables, + pushed.index_bytes IS NOT DISTINCT FROM fallback.index_bytes AS same_index_bytes, + pushed.visible_files = fallback.visible_files AS same_visible_count, + pushed.recent_rows IS NOT DISTINCT FROM fallback.recent_rows AS same_recent_rows +FROM pushed CROSS JOIN fallback; + +-- Unsupported aggregate state types stay on the frontend, including mixed aggregates. +-- SQLNESS REPLACE (RepartitionExec:.*) RepartitionExec: REDACTED +EXPLAIN SELECT COUNT(*), CAST(SUM(CAST(file_size AS DECIMAL(39, 0))) AS DOUBLE) +FROM information_schema.ssts_manifest; + +WITH candidate AS ( + SELECT COUNT(*) AS files, + CAST(SUM(CAST(file_size AS DECIMAL(39, 0))) AS DOUBLE) AS bytes + FROM information_schema.ssts_manifest +), baseline AS ( + SELECT COUNT(*) AS files, + CAST(SUM(CAST(file_size AS DECIMAL(39, 0))) AS DOUBLE) AS bytes + FROM (SELECT file_size FROM information_schema.ssts_manifest LIMIT 1000) +) +SELECT candidate.files = baseline.files AS same_count, + candidate.bytes = baseline.bytes AS same_bytes +FROM candidate CROSS JOIN baseline; + +-- Timezone-bearing implicit casts must remain on the frontend. +-- The inner LIMIT blocks aggregate pushdown without truncating the fixture. +WITH candidate AS ( + SELECT COUNT(*) FILTER (WHERE min_ts < arrow_cast('1970-01-01T04:00:00', 'Timestamp(Nanosecond, Some("+08:00"))')) AS files, + SUM(file_size) FILTER (WHERE min_ts < arrow_cast('1970-01-01T04:00:00', 'Timestamp(Nanosecond, Some("+08:00"))')) AS bytes + FROM information_schema.ssts_manifest +), fallback AS ( + SELECT COUNT(*) FILTER (WHERE min_ts < arrow_cast('1970-01-01T04:00:00', 'Timestamp(Nanosecond, Some("+08:00"))')) AS files, + SUM(file_size) FILTER (WHERE min_ts < arrow_cast('1970-01-01T04:00:00', 'Timestamp(Nanosecond, Some("+08:00"))')) AS bytes + FROM (SELECT * FROM information_schema.ssts_manifest LIMIT 1000) +) +SELECT candidate.files, fallback.files AS expected_files, + candidate.files = fallback.files AS same_count, + candidate.bytes = fallback.bytes AS same_bytes +FROM candidate CROSS JOIN fallback; + +-- Apply the same transport boundary to a WHERE predicate below the aggregate. +WITH candidate AS ( + SELECT COUNT(*) AS files, SUM(file_size) AS bytes + FROM information_schema.ssts_manifest + WHERE min_ts < arrow_cast('1970-01-01T04:00:00', 'Timestamp(Nanosecond, Some("+08:00"))') +), fallback AS ( + SELECT COUNT(*) AS files, SUM(file_size) AS bytes + FROM (SELECT * FROM information_schema.ssts_manifest LIMIT 1000) + WHERE min_ts < arrow_cast('1970-01-01T04:00:00', 'Timestamp(Nanosecond, Some("+08:00"))') +) +SELECT candidate.files, fallback.files AS expected_files, + candidate.files = fallback.files AS same_count, + candidate.bytes = fallback.bytes AS same_bytes +FROM candidate CROSS JOIN fallback; + +-- Unsupported intermediate types must not enter the remote plan. +-- The inner LIMIT blocks aggregate pushdown without truncating the fixture. +WITH candidate AS ( + SELECT COUNT(*) FILTER (WHERE arrow_cast(1, 'Decimal32(9, 0)') > arrow_cast(0, 'Decimal32(9, 0)')) AS files, + SUM(file_size) FILTER (WHERE arrow_cast(1, 'Decimal32(9, 0)') > arrow_cast(0, 'Decimal32(9, 0)')) AS bytes + FROM information_schema.ssts_manifest +), fallback AS ( + SELECT COUNT(*) FILTER (WHERE arrow_cast(1, 'Decimal32(9, 0)') > arrow_cast(0, 'Decimal32(9, 0)')) AS files, + SUM(file_size) FILTER (WHERE arrow_cast(1, 'Decimal32(9, 0)') > arrow_cast(0, 'Decimal32(9, 0)')) AS bytes + FROM (SELECT * FROM information_schema.ssts_manifest LIMIT 1000) +) +SELECT candidate.files, fallback.files AS expected_files, + candidate.files = fallback.files AS same_count, + candidate.bytes = fallback.bytes AS same_bytes +FROM candidate CROSS JOIN fallback; + +-- Apply the same transport boundary to a WHERE predicate below the aggregate. +WITH candidate AS ( + SELECT COUNT(*) AS files, SUM(file_size) AS bytes + FROM information_schema.ssts_manifest + WHERE arrow_cast(1, 'Decimal32(9, 0)') > arrow_cast(0, 'Decimal32(9, 0)') +), fallback AS ( + SELECT COUNT(*) AS files, SUM(file_size) AS bytes + FROM (SELECT * FROM information_schema.ssts_manifest LIMIT 1000) + WHERE arrow_cast(1, 'Decimal32(9, 0)') > arrow_cast(0, 'Decimal32(9, 0)') +) +SELECT candidate.files, fallback.files AS expected_files, + candidate.files = fallback.files AS same_count, + candidate.bytes = fallback.bytes AS same_bytes +FROM candidate CROSS JOIN fallback; + DROP TABLE ssts_limit_case; diff --git a/tests/cases/distributed/optimizer/pass_distribution_partition_subset_join.result b/tests/cases/distributed/optimizer/pass_distribution_partition_subset_join.result index 91c0e3e851d..7b2552b70e7 100644 --- a/tests/cases/distributed/optimizer/pass_distribution_partition_subset_join.result +++ b/tests/cases/distributed/optimizer/pass_distribution_partition_subset_join.result @@ -71,27 +71,25 @@ ORDER BY l.area, r.area; | logical_plan | Sort: l.area ASC NULLS LAST, r.area ASC NULLS LAST | | | Projection: l.area, r.area | | | Inner Join: l.device_id = r.device_id | -| | Projection: l.device_id, l.area | -| | MergeScan [is_placeholder=false, remote_input=[ | -| | SubqueryAlias: l | -| | Filter: pd_sub_l.device_id IS NOT NULL | -| | TableScan: pd_sub_l, partial_filters=[pd_sub_l.device_id IS NOT NULL] | +| | MergeScan [is_placeholder=false, remote_input=[ | +| | Projection: l.device_id, l.area | +| | SubqueryAlias: l | +| | Filter: pd_sub_l.device_id IS NOT NULL | +| | TableScan: pd_sub_l, partial_filters=[pd_sub_l.device_id IS NOT NULL] | | | ]] | -| | Projection: r.device_id, r.area | -| | MergeScan [is_placeholder=false, remote_input=[ | -| | SubqueryAlias: r | -| | Filter: pd_sub_r.device_id IS NOT NULL | -| | TableScan: pd_sub_r, partial_filters=[pd_sub_r.device_id IS NOT NULL] | +| | MergeScan [is_placeholder=false, remote_input=[ | +| | Projection: r.device_id, r.area | +| | SubqueryAlias: r | +| | Filter: pd_sub_r.device_id IS NOT NULL | +| | TableScan: pd_sub_r, partial_filters=[pd_sub_r.device_id IS NOT NULL] | | | ]] | | physical_plan | SortPreservingMergeExec: [area@0 ASC NULLS LAST, area@1 ASC NULLS LAST] | | | SortExec: expr=[area@0 ASC NULLS LAST, area@1 ASC NULLS LAST], preserve_partitioning=[true] | | | HashJoinExec: mode=Partitioned, join_type=Inner, on=[(device_id@0, device_id@0)], projection=[area@1, area@3] | | | RepartitionExec: partitioning=Hash([device_id@0],REDACTED_PARTITIONS), input_partitions=REDACTED| -| | ProjectionExec: expr=[device_id@1 as device_id, area@2 as area] | -| | MergeScanExec: peers=[REDACTED_REGION, REDACTED_REGION, REDACTED_REGION, ] | +| | MergeScanExec: peers=[REDACTED_REGION, REDACTED_REGION, REDACTED_REGION, ] | | | RepartitionExec: partitioning=Hash([device_id@0],REDACTED_PARTITIONS), input_partitions=REDACTED| -| | ProjectionExec: expr=[device_id@1 as device_id, area@2 as area] | -| | MergeScanExec: peers=[REDACTED_REGION, REDACTED_REGION, REDACTED_REGION, ] | +| | MergeScanExec: peers=[REDACTED_REGION, REDACTED_REGION, REDACTED_REGION, ] | | | | +---------------+-------------------------------------------------------------------------------------------------------------------+ diff --git a/tests/cases/distributed/optimizer/time_index_filter_pushdown.result b/tests/cases/distributed/optimizer/time_index_filter_pushdown.result index 5530edbcead..0da80725d67 100644 --- a/tests/cases/distributed/optimizer/time_index_filter_pushdown.result +++ b/tests/cases/distributed/optimizer/time_index_filter_pushdown.result @@ -122,13 +122,12 @@ WHERE |_|_Projection: cpu.greptime_timestamp_| |_|_TableScan: cpu_| |_| ]]_| -|_|_Projection: cpu.rack, cpu.os, cpu.greptime_timestamp_| |_|_MergeScan [is_placeholder=false, remote_input=[_| -|_| TableScan: cpu_| +|_| Projection: cpu.rack, cpu.os, cpu.greptime_timestamp_| +|_|_TableScan: cpu_| |_| ]]_| | physical_plan | ScalarSubqueryExec: subqueries=1_| |_|_FilterExec: greptime_timestamp@2 = scalar_subquery()_| -|_|_ProjectionExec: expr=[rack@0 as rack, os@1 as os, greptime_timestamp@3 as greptime_timestamp]_| |_|_CooperativeExec_| |_|_MergeScanExec: REDACTED |_|_MergeSortExec: [greptime_timestamp@0 DESC], fetch=1_| @@ -198,26 +197,25 @@ WHERE +-+-+-+ | 0_| 0_|_ScalarSubqueryExec REDACTED |_|_|_FilterExec: greptime_timestamp@2 = scalar_subquery(1686535800000000000) REDACTED -|_|_|_ProjectionExec: expr=[rack@0 as rack, os@1 as os, greptime_timestamp@3 as greptime_timestamp] REDACTED |_|_|_CooperativeExec REDACTED |_|_|_MergeScanExec: REDACTED |_|_|_MergeSortExec: [greptime_timestamp@0 DESC], fetch=1 REDACTED |_|_|_MergeScanExec: REDACTED |_|_|_| | 1_| 0_|_CooperativeExec REDACTED -|_|_|_UnorderedScan: REDACTED, "dyn_filters": ["DynamicFilter [ greptime_timestamp@3 = 1686535800000000000 ]"] +|_|_|_UnorderedScan: REDACTED, "dyn_filters": ["DynamicFilter [ greptime_timestamp@2 = 1686535800000000000 ]"] |_|_|_| | 1_| 1_|_CooperativeExec REDACTED -|_|_|_UnorderedScan: REDACTED, "dyn_filters": ["DynamicFilter [ greptime_timestamp@3 = 1686535800000000000 ]"] +|_|_|_UnorderedScan: REDACTED, "dyn_filters": ["DynamicFilter [ greptime_timestamp@2 = 1686535800000000000 ]"] |_|_|_| | 1_| 2_|_CooperativeExec REDACTED -|_|_|_UnorderedScan: REDACTED, "dyn_filters": ["DynamicFilter [ greptime_timestamp@3 = 1686535800000000000 ]"] +|_|_|_UnorderedScan: REDACTED, "dyn_filters": ["DynamicFilter [ greptime_timestamp@2 = 1686535800000000000 ]"] |_|_|_| | 1_| 3_|_CooperativeExec REDACTED -|_|_|_UnorderedScan: REDACTED, "dyn_filters": ["DynamicFilter [ greptime_timestamp@3 = 1686535800000000000 ]"] +|_|_|_UnorderedScan: REDACTED, "dyn_filters": ["DynamicFilter [ greptime_timestamp@2 = 1686535800000000000 ]"] |_|_|_| | 1_| 4_|_CooperativeExec REDACTED -|_|_|_UnorderedScan: REDACTED, "dyn_filters": ["DynamicFilter [ greptime_timestamp@3 = 1686535800000000000 ]"] +|_|_|_UnorderedScan: REDACTED, "dyn_filters": ["DynamicFilter [ greptime_timestamp@2 = 1686535800000000000 ]"] |_|_|_| | 1_| 0_|_FilterExec: DynamicFilter [ REDACTED ] REDACTED |_|_|_SortPreservingMergeExec: [greptime_timestamp@0 DESC], fetch=1 REDACTED diff --git a/tests/cases/standalone/common/cte/cte_join_build_side.result b/tests/cases/standalone/common/cte/cte_join_build_side.result index d549b21c241..f697d85999a 100644 --- a/tests/cases/standalone/common/cte/cte_join_build_side.result +++ b/tests/cases/standalone/common/cte/cte_join_build_side.result @@ -53,44 +53,42 @@ FROM cte_join_logs AS t JOIN top_dbs td ON t."db" = td."db" GROUP BY t."db" ORDER BY c DESC, t."db"; -+---------------+----------------------------------------------------------------------------------------------------------+ -| plan_type | plan | -+---------------+----------------------------------------------------------------------------------------------------------+ -| logical_plan | Sort: c DESC NULLS FIRST, t.db ASC NULLS LAST | -| | Projection: t.db, count(Int64(1)) AS count(*) AS c | -| | Aggregate: groupBy=[[t.db]], aggr=[[count(Int64(1))]] | -| | LeftSemi Join: t.db = td.db | -| | Projection: t.db | -| | MergeScan [is_placeholder=false, remote_input=[ | -| | SubqueryAlias: t | -| | Filter: cte_join_logs.db IS NOT NULL | -| | TableScan: cte_join_logs, partial_filters=[cte_join_logs.db IS NOT NULL] | -| | ]] | -| | Projection: td.db | -| | MergeScan [is_placeholder=false, remote_input=[ | -| | SubqueryAlias: td | -| | SubqueryAlias: top_dbs | -| | Filter: cte_join_logs.db IS NOT NULL | -| | Limit: skip=0, fetch=5 | -| | Sort: cnt DESC NULLS FIRST | -| | Projection: cte_join_logs.db, count(Int64(1)) AS count(*) AS cnt | -| | Aggregate: groupBy=[[cte_join_logs.db]], aggr=[[count(cte_join_logs.ts) AS count(Int64(1))]] | -| | TableScan: cte_join_logs | -| | ]] | -| physical_plan | ProjectionExec: expr=[db@0 as db, count(Int64(1))@1 as c] | -| | SortPreservingMergeExec: [count(Int64(1))@1 DESC, db@0 ASC NULLS LAST] | ++---------------+------------------------------------------------------------------------------------------------------------+ +| plan_type | plan | ++---------------+------------------------------------------------------------------------------------------------------------+ +| logical_plan | Sort: c DESC NULLS FIRST, t.db ASC NULLS LAST | +| | Projection: t.db, count(Int64(1)) AS count(*) AS c | +| | Aggregate: groupBy=[[t.db]], aggr=[[count(Int64(1))]] | +| | LeftSemi Join: t.db = td.db | +| | MergeScan [is_placeholder=false, remote_input=[ | +| | Projection: t.db | +| | SubqueryAlias: t | +| | Filter: cte_join_logs.db IS NOT NULL | +| | TableScan: cte_join_logs, partial_filters=[cte_join_logs.db IS NOT NULL] | +| | ]] | +| | MergeScan [is_placeholder=false, remote_input=[ | +| | Projection: td.db | +| | SubqueryAlias: td | +| | SubqueryAlias: top_dbs | +| | Filter: cte_join_logs.db IS NOT NULL | +| | Limit: skip=0, fetch=5 | +| | Sort: cnt DESC NULLS FIRST | +| | Projection: cte_join_logs.db, count(Int64(1)) AS count(*) AS cnt | +| | Aggregate: groupBy=[[cte_join_logs.db]], aggr=[[count(cte_join_logs.ts) AS count(Int64(1))]] | +| | TableScan: cte_join_logs | +| | ]] | +| physical_plan | ProjectionExec: expr=[db@0 as db, count(Int64(1))@1 as c] | +| | SortPreservingMergeExec: [count(Int64(1))@1 DESC, db@0 ASC NULLS LAST] | | | SortExec: expr=[count(Int64(1))@1 DESC, db@0 ASC NULLS LAST], preserve_REDACTED -| | AggregateExec: mode=FinalPartitioned, gby=[db@0 as db], aggr=[count(Int64(1))] | +| | AggregateExec: mode=FinalPartitioned, gby=[db@0 as db], aggr=[count(Int64(1))] | | | RepartitionExec: REDACTED -| | AggregateExec: mode=Partial, gby=[db@0 as db], aggr=[count(Int64(1))] | -| | HashJoinExec: mode=CollectLeft, join_type=RightSemi, on=[(db@0, db@0)] | -| | ProjectionExec: expr=[db@0 as db] | -| | MergeScanExec: REDACTED +| | AggregateExec: mode=Partial, gby=[db@0 as db], aggr=[count(Int64(1))] | +| | HashJoinExec: mode=CollectLeft, join_type=RightSemi, on=[(db@0, db@0)] | +| | MergeScanExec: REDACTED | | RepartitionExec: REDACTED -| | ProjectionExec: expr=[db@1 as db] | -| | MergeScanExec: REDACTED -| | | -+---------------+----------------------------------------------------------------------------------------------------------+ +| | MergeScanExec: REDACTED +| | | ++---------------+------------------------------------------------------------------------------------------------------------+ WITH top_dbs AS ( SELECT "db", count(*) AS cnt FROM cte_join_logs diff --git a/tests/cases/standalone/common/filter/hash_join_dyn_filter.result b/tests/cases/standalone/common/filter/hash_join_dyn_filter.result index e534f55791c..266a5e11bfe 100644 --- a/tests/cases/standalone/common/filter/hash_join_dyn_filter.result +++ b/tests/cases/standalone/common/filter/hash_join_dyn_filter.result @@ -39,25 +39,23 @@ WHERE c.tier = 'gold'; +---------------+-----------------------------------------------------------------------------------------------------------------------------------+ | logical_plan | Projection: o.id, o.amount, c.name, c.tier | | | Inner Join: o.customer_id = c.customer_id | -| | Projection: o.id, o.customer_id, o.amount | -| | MergeScan [is_placeholder=false, remote_input=[ | -| | SubqueryAlias: o | -| | Filter: orders.customer_id IS NOT NULL | -| | TableScan: orders, partial_filters=[orders.customer_id IS NOT NULL] | +| | MergeScan [is_placeholder=false, remote_input=[ | +| | Projection: o.id, o.customer_id, o.amount | +| | SubqueryAlias: o | +| | Filter: orders.customer_id IS NOT NULL | +| | TableScan: orders, partial_filters=[orders.customer_id IS NOT NULL] | | | ]] | -| | Projection: c.customer_id, c.name, c.tier | -| | MergeScan [is_placeholder=false, remote_input=[ | -| | SubqueryAlias: c | -| | Filter: customers.customer_id IS NOT NULL AND customers.tier = Utf8("gold") | -| | TableScan: customers, partial_filters=[customers.customer_id IS NOT NULL, customers.tier = Utf8("gold")] | +| | MergeScan [is_placeholder=false, remote_input=[ | +| | Projection: c.customer_id, c.name, c.tier | +| | SubqueryAlias: c | +| | Filter: customers.customer_id IS NOT NULL AND customers.tier = Utf8("gold") | +| | TableScan: customers, partial_filters=[customers.customer_id IS NOT NULL, customers.tier = Utf8("gold")] | | | ]] | | physical_plan | HashJoinExec: mode=Partitioned, join_type=Inner, on=[(customer_id@1, customer_id@0)], projection=[id@0, amount@2, name@4, tier@5] | | | RepartitionExec: REDACTED -| | ProjectionExec: expr=[id@0 as id, customer_id@1 as customer_id, amount@2 as amount] | -| | MergeScanExec: REDACTED +| | MergeScanExec: REDACTED | | RepartitionExec: REDACTED -| | ProjectionExec: expr=[customer_id@0 as customer_id, name@1 as name, tier@2 as tier] | -| | MergeScanExec: REDACTED +| | MergeScanExec: REDACTED | | | +---------------+-----------------------------------------------------------------------------------------------------------------------------------+ @@ -89,19 +87,17 @@ WHERE c.tier = 'gold'; +-+-+-+ | 0_| 0_|_HashJoinExec: mode=Partitioned, join_type=Inner, on=[(customer_id@1, customer_id@0)], projection=[id@0, amount@2, name@4, tier@5] metrics=REDACTED_| |_|_|_RepartitionExec: partitioning=REDACTED -|_|_|_ProjectionExec: expr=[id@0 as id, customer_id@1 as customer_id, amount@2 as amount] metrics=REDACTED_| |_|_|_MergeScanExec: REDACTED |_|_|_RepartitionExec: partitioning=REDACTED -|_|_|_ProjectionExec: expr=[customer_id@0 as customer_id, name@1 as name, tier@2 as tier] metrics=REDACTED_| |_|_|_MergeScanExec: REDACTED |_|_|_| | 1_| 0_|_FilterExec: customer_id@1 IS NOT NULL metrics=REDACTED_| |_|_|_CooperativeExec metrics=REDACTED_| -|_|_|_SeqScan: region=REDACTED, {"partition_count":REDACTED, "projection": ["id", "customer_id", "amount", "ts"], "filters": ["customer_id IS NOT NULL"], "time_range":REDACTED +|_|_|_SeqScan: region=REDACTED, {"partition_count":REDACTED, "projection": ["id", "customer_id", "amount"], "filters": ["customer_id IS NOT NULL"], "time_range":REDACTED |_|_|_| | 1_| 0_|_FilterExec: customer_id@0 IS NOT NULL AND tier@2 = gold metrics=REDACTED_| |_|_|_CooperativeExec metrics=REDACTED_| -|_|_|_SeqScan: region=REDACTED, {"partition_count":REDACTED, "projection": ["customer_id", "name", "tier", "ts"], "filters": ["customer_id IS NOT NULL", "tier = Utf8(\"gold\")"], "dyn_filters":REDACTED +|_|_|_SeqScan: region=REDACTED, {"partition_count":REDACTED, "projection": ["customer_id", "name", "tier"], "filters": ["customer_id IS NOT NULL", "tier = Utf8(\"gold\")"], "dyn_filters":REDACTED |_|_|_| |_|_| Total rows: REDACTED_| +-+-+-+ @@ -162,33 +158,31 @@ FROM (SELECT "id", customer_id as cid, amount, ts FROM orders) o JOIN customers c ON o.cid = c.customer_id WHERE c.tier IN ('gold', 'silver'); -+---------------+-------------------------------------------------------------------------------------------------------------------------------------------------+ -| plan_type | plan | -+---------------+-------------------------------------------------------------------------------------------------------------------------------------------------+ -| logical_plan | Projection: o.id, o.amount, c.name, c.tier | -| | Inner Join: o.cid = c.customer_id | -| | Projection: o.id, o.cid, o.amount | -| | MergeScan [is_placeholder=false, remote_input=[ | -| | SubqueryAlias: o | -| | Projection: orders.id, orders.customer_id AS cid, orders.amount, orders.ts | -| | Filter: orders.customer_id IS NOT NULL | -| | TableScan: orders, partial_filters=[orders.customer_id IS NOT NULL] | -| | ]] | -| | Projection: c.customer_id, c.name, c.tier | -| | MergeScan [is_placeholder=false, remote_input=[ | -| | SubqueryAlias: c | -| | Filter: customers.customer_id IS NOT NULL AND (customers.tier = Utf8("gold") OR customers.tier = Utf8("silver")) | -| | TableScan: customers, partial_filters=[customers.customer_id IS NOT NULL, customers.tier = Utf8("gold") OR customers.tier = Utf8("silver")] | -| | ]] | -| physical_plan | HashJoinExec: mode=Partitioned, join_type=Inner, on=[(cid@1, customer_id@0)], projection=[id@0, amount@2, name@4, tier@5] | ++---------------+---------------------------------------------------------------------------------------------------------------------------------------------------+ +| plan_type | plan | ++---------------+---------------------------------------------------------------------------------------------------------------------------------------------------+ +| logical_plan | Projection: o.id, o.amount, c.name, c.tier | +| | Inner Join: o.cid = c.customer_id | +| | MergeScan [is_placeholder=false, remote_input=[ | +| | Projection: o.id, o.cid, o.amount | +| | SubqueryAlias: o | +| | Projection: orders.id, orders.customer_id AS cid, orders.amount, orders.ts | +| | Filter: orders.customer_id IS NOT NULL | +| | TableScan: orders, partial_filters=[orders.customer_id IS NOT NULL] | +| | ]] | +| | MergeScan [is_placeholder=false, remote_input=[ | +| | Projection: c.customer_id, c.name, c.tier | +| | SubqueryAlias: c | +| | Filter: customers.customer_id IS NOT NULL AND (customers.tier = Utf8("gold") OR customers.tier = Utf8("silver")) | +| | TableScan: customers, partial_filters=[customers.customer_id IS NOT NULL, customers.tier = Utf8("gold") OR customers.tier = Utf8("silver")] | +| | ]] | +| physical_plan | HashJoinExec: mode=Partitioned, join_type=Inner, on=[(cid@1, customer_id@0)], projection=[id@0, amount@2, name@4, tier@5] | | | RepartitionExec: REDACTED -| | ProjectionExec: expr=[id@0 as id, cid@1 as cid, amount@2 as amount] | -| | MergeScanExec: REDACTED +| | MergeScanExec: REDACTED | | RepartitionExec: REDACTED -| | ProjectionExec: expr=[customer_id@0 as customer_id, name@1 as name, tier@2 as tier] | -| | MergeScanExec: REDACTED -| | | -+---------------+-------------------------------------------------------------------------------------------------------------------------------------------------+ +| | MergeScanExec: REDACTED +| | | ++---------------+---------------------------------------------------------------------------------------------------------------------------------------------------+ -- SQLNESS REPLACE ("metrics_per_partition":\s*.*metrics=) "metrics_per_partition": REDACTED metrics= -- SQLNESS REPLACE (metrics=\{.*\}) metrics=REDACTED @@ -218,20 +212,18 @@ WHERE c.tier IN ('gold', 'silver'); +-+-+-+ | 0_| 0_|_HashJoinExec: mode=Partitioned, join_type=Inner, on=[(cid@1, customer_id@0)], projection=[id@0, amount@2, name@4, tier@5] metrics=REDACTED_| |_|_|_RepartitionExec: partitioning=REDACTED -|_|_|_ProjectionExec: expr=[id@0 as id, cid@1 as cid, amount@2 as amount] metrics=REDACTED_| |_|_|_MergeScanExec: REDACTED |_|_|_RepartitionExec: partitioning=REDACTED -|_|_|_ProjectionExec: expr=[customer_id@0 as customer_id, name@1 as name, tier@2 as tier] metrics=REDACTED_| |_|_|_MergeScanExec: REDACTED |_|_|_| -| 1_| 0_|_ProjectionExec: expr=[id@0 as id, customer_id@1 as cid, amount@2 as amount, ts@3 as ts] metrics=REDACTED_| +| 1_| 0_|_ProjectionExec: expr=[id@0 as id, customer_id@1 as cid, amount@2 as amount] metrics=REDACTED_| |_|_|_FilterExec: customer_id@1 IS NOT NULL metrics=REDACTED_| |_|_|_CooperativeExec metrics=REDACTED_| -|_|_|_SeqScan: region=REDACTED, {"partition_count":REDACTED, "projection": ["id", "customer_id", "amount", "ts"], "filters": ["customer_id IS NOT NULL"], "time_range":REDACTED +|_|_|_SeqScan: region=REDACTED, {"partition_count":REDACTED, "projection": ["id", "customer_id", "amount"], "filters": ["customer_id IS NOT NULL"], "time_range":REDACTED |_|_|_| | 1_| 0_|_FilterExec: customer_id@0 IS NOT NULL AND (tier@2 = gold OR tier@2 = silver) metrics=REDACTED_| |_|_|_CooperativeExec metrics=REDACTED_| -|_|_|_SeqScan: region=REDACTED, {"partition_count":REDACTED, "projection": ["customer_id", "name", "tier", "ts"], "filters": ["customer_id IS NOT NULL", "tier = Utf8(\"gold\") OR tier = Utf8(\"silver\")"], "dyn_filters":REDACTED +|_|_|_SeqScan: region=REDACTED, {"partition_count":REDACTED, "projection": ["customer_id", "name", "tier"], "filters": ["customer_id IS NOT NULL", "tier = Utf8(\"gold\") OR tier = Utf8(\"silver\")"], "dyn_filters":REDACTED |_|_|_| |_|_| Total rows: REDACTED_| +-+-+-+ diff --git a/tests/cases/standalone/common/filter/hash_join_topk_dyn_filter.result b/tests/cases/standalone/common/filter/hash_join_topk_dyn_filter.result index 1c2d05bbcbb..a218c5b2c31 100644 --- a/tests/cases/standalone/common/filter/hash_join_topk_dyn_filter.result +++ b/tests/cases/standalone/common/filter/hash_join_topk_dyn_filter.result @@ -47,35 +47,33 @@ FROM ( JOIN customers c ON top_orders.customer_id = c.customer_id WHERE c.tier IN ('gold', 'bronze'); -+---------------+-------------------------------------------------------------------------------------------------------------------------------------------------+ -| plan_type | plan | -+---------------+-------------------------------------------------------------------------------------------------------------------------------------------------+ -| logical_plan | Projection: top_orders.id, top_orders.amount, c.name, c.tier | -| | Inner Join: top_orders.customer_id = c.customer_id | -| | Projection: top_orders.id, top_orders.customer_id, top_orders.amount | -| | MergeScan [is_placeholder=false, remote_input=[ | -| | SubqueryAlias: top_orders | -| | Filter: orders.customer_id IS NOT NULL | -| | Limit: skip=0, fetch=5 | -| | Sort: orders.amount DESC NULLS FIRST | -| | Projection: orders.id, orders.customer_id, orders.amount, orders.ts | -| | TableScan: orders | -| | ]] | -| | Projection: c.customer_id, c.name, c.tier | -| | MergeScan [is_placeholder=false, remote_input=[ | -| | SubqueryAlias: c | -| | Filter: customers.customer_id IS NOT NULL AND (customers.tier = Utf8("gold") OR customers.tier = Utf8("bronze")) | -| | TableScan: customers, partial_filters=[customers.customer_id IS NOT NULL, customers.tier = Utf8("gold") OR customers.tier = Utf8("bronze")] | -| | ]] | -| physical_plan | HashJoinExec: mode=CollectLeft, join_type=Inner, on=[(customer_id@1, customer_id@0)], projection=[id@0, amount@2, name@4, tier@5] | -| | ProjectionExec: expr=[id@0 as id, customer_id@1 as customer_id, amount@2 as amount] | -| | CooperativeExec | -| | MergeScanExec: REDACTED -| | RepartitionExec: partitioning=RoundRobinBatch(4), input_partitions=1 | -| | ProjectionExec: expr=[customer_id@0 as customer_id, name@1 as name, tier@2 as tier] | -| | MergeScanExec: REDACTED -| | | -+---------------+-------------------------------------------------------------------------------------------------------------------------------------------------+ ++---------------+---------------------------------------------------------------------------------------------------------------------------------------------------+ +| plan_type | plan | ++---------------+---------------------------------------------------------------------------------------------------------------------------------------------------+ +| logical_plan | Projection: top_orders.id, top_orders.amount, c.name, c.tier | +| | Inner Join: top_orders.customer_id = c.customer_id | +| | MergeScan [is_placeholder=false, remote_input=[ | +| | Projection: top_orders.id, top_orders.customer_id, top_orders.amount | +| | SubqueryAlias: top_orders | +| | Filter: orders.customer_id IS NOT NULL | +| | Limit: skip=0, fetch=5 | +| | Sort: orders.amount DESC NULLS FIRST | +| | Projection: orders.id, orders.customer_id, orders.amount, orders.ts | +| | TableScan: orders | +| | ]] | +| | MergeScan [is_placeholder=false, remote_input=[ | +| | Projection: c.customer_id, c.name, c.tier | +| | SubqueryAlias: c | +| | Filter: customers.customer_id IS NOT NULL AND (customers.tier = Utf8("gold") OR customers.tier = Utf8("bronze")) | +| | TableScan: customers, partial_filters=[customers.customer_id IS NOT NULL, customers.tier = Utf8("gold") OR customers.tier = Utf8("bronze")] | +| | ]] | +| physical_plan | HashJoinExec: mode=CollectLeft, join_type=Inner, on=[(customer_id@1, customer_id@0)], projection=[id@0, amount@2, name@4, tier@5] | +| | CooperativeExec | +| | MergeScanExec: REDACTED +| | RepartitionExec: partitioning=RoundRobinBatch(4), input_partitions=1 | +| | MergeScanExec: REDACTED +| | | ++---------------+---------------------------------------------------------------------------------------------------------------------------------------------------+ -- SQLNESS REPLACE ("metrics_per_partition":\s*.*metrics=) "metrics_per_partition": REDACTED metrics= -- SQLNESS REPLACE (metrics=\{.*\}) metrics=REDACTED @@ -109,22 +107,20 @@ WHERE c.tier IN ('gold', 'bronze'); | stage | node | plan_| +-+-+-+ | 0_| 0_|_HashJoinExec: mode=CollectLeft, join_type=Inner, on=[(customer_id@1, customer_id@0)], projection=[id@0, amount@2, name@4, tier@5] metrics=REDACTED_| -|_|_|_ProjectionExec: expr=[id@0 as id, customer_id@1 as customer_id, amount@2 as amount] metrics=REDACTED_| |_|_|_CooperativeExec metrics=REDACTED_| |_|_|_MergeScanExec: REDACTED |_|_|_RepartitionExec: partitioning=REDACTED -|_|_|_ProjectionExec: expr=[customer_id@0 as customer_id, name@1 as name, tier@2 as tier] metrics=REDACTED_| |_|_|_MergeScanExec: REDACTED |_|_|_| | 1_| 0_|_FilterExec: customer_id@1 IS NOT NULL metrics=REDACTED_| |_|_|_RepartitionExec: partitioning=REDACTED |_|_|_SortPreservingMergeExec: [amount@2 DESC], fetch=5 metrics=REDACTED_| |_|_|_SortExec: TopK(fetch=5), expr=[amount@2 DESC], preserve_partitioning=[true] metrics=REDACTED_| -|_|_|_SeqScan: region=REDACTED, {"partition_count":REDACTED, "projection": ["id", "customer_id", "amount", "ts"], "dyn_filters":REDACTED +|_|_|_SeqScan: region=REDACTED, {"partition_count":REDACTED, "projection": ["id", "customer_id", "amount"], "dyn_filters":REDACTED |_|_|_| | 1_| 0_|_FilterExec: customer_id@0 IS NOT NULL AND (tier@2 = gold OR tier@2 = bronze) metrics=REDACTED_| |_|_|_CooperativeExec metrics=REDACTED_| -|_|_|_SeqScan: region=REDACTED, {"partition_count":REDACTED, "projection": ["customer_id", "name", "tier", "ts"], "filters": ["customer_id IS NOT NULL", "tier = Utf8(\"gold\") OR tier = Utf8(\"bronze\")"], "dyn_filters":REDACTED +|_|_|_SeqScan: region=REDACTED, {"partition_count":REDACTED, "projection": ["customer_id", "name", "tier"], "filters": ["customer_id IS NOT NULL", "tier = Utf8(\"gold\") OR tier = Utf8(\"bronze\")"], "dyn_filters":REDACTED |_|_|_| |_|_| Total rows: REDACTED_| +-+-+-+ @@ -211,27 +207,25 @@ LIMIT 4; | logical_plan | Sort: o.amount DESC NULLS FIRST, fetch=4 | | | Projection: o.id, o.customer_id, c.name, c.tier, o.amount | | | Inner Join: o.customer_id = c.customer_id | -| | Projection: o.id, o.customer_id, o.amount | -| | MergeScan [is_placeholder=false, remote_input=[ | -| | SubqueryAlias: o | -| | Filter: orders.customer_id IS NOT NULL | -| | TableScan: orders, partial_filters=[orders.customer_id IS NOT NULL] | +| | MergeScan [is_placeholder=false, remote_input=[ | +| | Projection: o.id, o.customer_id, o.amount | +| | SubqueryAlias: o | +| | Filter: orders.customer_id IS NOT NULL | +| | TableScan: orders, partial_filters=[orders.customer_id IS NOT NULL] | | | ]] | -| | Projection: c.customer_id, c.name, c.tier | -| | MergeScan [is_placeholder=false, remote_input=[ | -| | SubqueryAlias: c | -| | Filter: customers.customer_id IS NOT NULL AND (customers.tier = Utf8("gold") OR customers.tier = Utf8("silver")) | -| | TableScan: customers, partial_filters=[customers.customer_id IS NOT NULL, customers.tier = Utf8("gold") OR customers.tier = Utf8("silver")] | +| | MergeScan [is_placeholder=false, remote_input=[ | +| | Projection: c.customer_id, c.name, c.tier | +| | SubqueryAlias: c | +| | Filter: customers.customer_id IS NOT NULL AND (customers.tier = Utf8("gold") OR customers.tier = Utf8("silver")) | +| | TableScan: customers, partial_filters=[customers.customer_id IS NOT NULL, customers.tier = Utf8("gold") OR customers.tier = Utf8("silver")] | | | ]] | | physical_plan | SortPreservingMergeExec: [amount@4 DESC], fetch=4 | | | SortExec: TopK(fetch=4), expr=[amount@4 DESC], preserve_partitioning=[true] | | | HashJoinExec: mode=Partitioned, join_type=Inner, on=[(customer_id@1, customer_id@0)], projection=[id@0, customer_id@1, name@4, tier@5, amount@2] | | | RepartitionExec: partitioning=REDACTED -| | ProjectionExec: expr=[id@0 as id, customer_id@1 as customer_id, amount@2 as amount] | -| | MergeScanExec: REDACTED +| | MergeScanExec: REDACTED | | RepartitionExec: partitioning=REDACTED -| | ProjectionExec: expr=[customer_id@0 as customer_id, name@1 as name, tier@2 as tier] | -| | MergeScanExec: REDACTED +| | MergeScanExec: REDACTED | | | +---------------+------------------------------------------------------------------------------------------------------------------------------------------------------+ @@ -270,19 +264,17 @@ LIMIT 4; |_|_|_SortExec: TopK(fetch=4), expr=[amount@4 DESC], preserve_partitioning=[true] metrics=REDACTED_| |_|_|_HashJoinExec: mode=Partitioned, join_type=Inner, on=[(customer_id@1, customer_id@0)], projection=[id@0, customer_id@1, name@4, tier@5, amount@2] metrics=REDACTED_| |_|_|_RepartitionExec: partitioning=REDACTED -|_|_|_ProjectionExec: expr=[id@0 as id, customer_id@1 as customer_id, amount@2 as amount] metrics=REDACTED_| |_|_|_MergeScanExec: REDACTED |_|_|_RepartitionExec: partitioning=REDACTED -|_|_|_ProjectionExec: expr=[customer_id@0 as customer_id, name@1 as name, tier@2 as tier] metrics=REDACTED_| |_|_|_MergeScanExec: REDACTED |_|_|_| | 1_| 0_|_FilterExec: customer_id@1 IS NOT NULL metrics=REDACTED_| |_|_|_CooperativeExec metrics=REDACTED_| -|_|_|_SeqScan: region=REDACTED, {"partition_count":REDACTED, "projection": ["id", "customer_id", "amount", "ts"], "filters": ["customer_id IS NOT NULL"], "dyn_filters":REDACTED +|_|_|_SeqScan: region=REDACTED, {"partition_count":REDACTED, "projection": ["id", "customer_id", "amount"], "filters": ["customer_id IS NOT NULL"], "dyn_filters":REDACTED |_|_|_| | 1_| 0_|_FilterExec: customer_id@0 IS NOT NULL AND (tier@2 = gold OR tier@2 = silver) metrics=REDACTED_| |_|_|_CooperativeExec metrics=REDACTED_| -|_|_|_SeqScan: region=REDACTED, {"partition_count":REDACTED, "projection": ["customer_id", "name", "tier", "ts"], "filters": ["customer_id IS NOT NULL", "tier = Utf8(\"gold\") OR tier = Utf8(\"silver\")"], "dyn_filters":REDACTED +|_|_|_SeqScan: region=REDACTED, {"partition_count":REDACTED, "projection": ["customer_id", "name", "tier"], "filters": ["customer_id IS NOT NULL", "tier = Utf8(\"gold\") OR tier = Utf8(\"silver\")"], "dyn_filters":REDACTED |_|_|_| |_|_| Total rows: REDACTED_| +-+-+-+ @@ -377,37 +369,34 @@ WHERE c.tier IN ('gold', 'silver') | | Inner Join: o.product_id = p.product_id | | | Projection: o.id, o.product_id, o.amount, c.name, c.tier | | | Inner Join: o.customer_id = c.customer_id | -| | Projection: o.id, o.customer_id, o.product_id, o.amount | -| | MergeScan [is_placeholder=false, remote_input=[ | -| | SubqueryAlias: o | -| | Filter: orders.customer_id IS NOT NULL AND orders.product_id IS NOT NULL | -| | TableScan: orders, partial_filters=[orders.customer_id IS NOT NULL, orders.product_id IS NOT NULL] | +| | MergeScan [is_placeholder=false, remote_input=[ | +| | Projection: o.id, o.customer_id, o.product_id, o.amount | +| | SubqueryAlias: o | +| | Filter: orders.customer_id IS NOT NULL AND orders.product_id IS NOT NULL | +| | TableScan: orders, partial_filters=[orders.customer_id IS NOT NULL, orders.product_id IS NOT NULL] | | | ]] | -| | Projection: c.customer_id, c.name, c.tier | -| | MergeScan [is_placeholder=false, remote_input=[ | -| | SubqueryAlias: c | -| | Filter: customers.customer_id IS NOT NULL AND (customers.tier = Utf8("gold") OR customers.tier = Utf8("silver")) | -| | TableScan: customers, partial_filters=[customers.customer_id IS NOT NULL, customers.tier = Utf8("gold") OR customers.tier = Utf8("silver")] | +| | MergeScan [is_placeholder=false, remote_input=[ | +| | Projection: c.customer_id, c.name, c.tier | +| | SubqueryAlias: c | +| | Filter: customers.customer_id IS NOT NULL AND (customers.tier = Utf8("gold") OR customers.tier = Utf8("silver")) | +| | TableScan: customers, partial_filters=[customers.customer_id IS NOT NULL, customers.tier = Utf8("gold") OR customers.tier = Utf8("silver")] | | | ]] | -| | Projection: p.product_id, p.name, p.category | -| | MergeScan [is_placeholder=false, remote_input=[ | -| | SubqueryAlias: p | -| | Filter: products.product_id IS NOT NULL AND products.category = Utf8("electronics") | -| | TableScan: products, partial_filters=[products.product_id IS NOT NULL, products.category = Utf8("electronics")] | +| | MergeScan [is_placeholder=false, remote_input=[ | +| | Projection: p.product_id, p.name, p.category | +| | SubqueryAlias: p | +| | Filter: products.product_id IS NOT NULL AND products.category = Utf8("electronics") | +| | TableScan: products, partial_filters=[products.product_id IS NOT NULL, products.category = Utf8("electronics")] | | | ]] | | physical_plan | ProjectionExec: expr=[id@0 as id, amount@1 as amount, name@2 as name, tier@3 as tier, name@4 as product_name, category@5 as category] | | | HashJoinExec: mode=Partitioned, join_type=Inner, on=[(product_id@1, product_id@0)], projection=[id@0, amount@2, name@3, tier@4, name@6, category@7] | | | RepartitionExec: partitioning=REDACTED | | HashJoinExec: mode=Partitioned, join_type=Inner, on=[(customer_id@1, customer_id@0)], projection=[id@0, product_id@2, amount@3, name@5, tier@6] | | | RepartitionExec: partitioning=REDACTED -| | ProjectionExec: expr=[id@0 as id, customer_id@1 as customer_id, product_id@2 as product_id, amount@3 as amount] | -| | MergeScanExec: REDACTED +| | MergeScanExec: REDACTED | | RepartitionExec: partitioning=REDACTED -| | ProjectionExec: expr=[customer_id@0 as customer_id, name@1 as name, tier@2 as tier] | -| | MergeScanExec: REDACTED +| | MergeScanExec: REDACTED | | RepartitionExec: partitioning=REDACTED -| | ProjectionExec: expr=[product_id@0 as product_id, name@1 as name, category@2 as category] | -| | MergeScanExec: REDACTED +| | MergeScanExec: REDACTED | | | +---------------+-------------------------------------------------------------------------------------------------------------------------------------------------------+ @@ -444,26 +433,23 @@ WHERE c.tier IN ('gold', 'silver') |_|_|_RepartitionExec: partitioning=REDACTED |_|_|_HashJoinExec: mode=Partitioned, join_type=Inner, on=[(customer_id@1, customer_id@0)], projection=[id@0, product_id@2, amount@3, name@5, tier@6] metrics=REDACTED_| |_|_|_RepartitionExec: partitioning=REDACTED -|_|_|_ProjectionExec: expr=[id@0 as id, customer_id@1 as customer_id, product_id@2 as product_id, amount@3 as amount] metrics=REDACTED_| |_|_|_MergeScanExec: REDACTED |_|_|_RepartitionExec: partitioning=REDACTED -|_|_|_ProjectionExec: expr=[customer_id@0 as customer_id, name@1 as name, tier@2 as tier] metrics=REDACTED_| |_|_|_MergeScanExec: REDACTED |_|_|_RepartitionExec: partitioning=REDACTED -|_|_|_ProjectionExec: expr=[product_id@0 as product_id, name@1 as name, category@2 as category] metrics=REDACTED_| |_|_|_MergeScanExec: REDACTED |_|_|_| | 1_| 0_|_FilterExec: customer_id@1 IS NOT NULL AND product_id@2 IS NOT NULL metrics=REDACTED_| |_|_|_CooperativeExec metrics=REDACTED_| -|_|_|_SeqScan: region=REDACTED, {"partition_count":REDACTED, "projection": ["id", "customer_id", "product_id", "amount", "ts"], "filters": ["customer_id IS NOT NULL", "product_id IS NOT NULL"], "time_range":REDACTED +|_|_|_SeqScan: region=REDACTED, {"partition_count":REDACTED, "projection": ["id", "customer_id", "product_id", "amount"], "filters": ["customer_id IS NOT NULL", "product_id IS NOT NULL"], "time_range":REDACTED |_|_|_| | 1_| 0_|_FilterExec: customer_id@0 IS NOT NULL AND (tier@2 = gold OR tier@2 = silver) metrics=REDACTED_| |_|_|_CooperativeExec metrics=REDACTED_| -|_|_|_SeqScan: region=REDACTED, {"partition_count":REDACTED, "projection": ["customer_id", "name", "tier", "ts"], "filters": ["customer_id IS NOT NULL", "tier = Utf8(\"gold\") OR tier = Utf8(\"silver\")"], "dyn_filters":REDACTED +|_|_|_SeqScan: region=REDACTED, {"partition_count":REDACTED, "projection": ["customer_id", "name", "tier"], "filters": ["customer_id IS NOT NULL", "tier = Utf8(\"gold\") OR tier = Utf8(\"silver\")"], "dyn_filters":REDACTED |_|_|_| | 1_| 0_|_FilterExec: product_id@0 IS NOT NULL AND category@2 = electronics metrics=REDACTED_| |_|_|_CooperativeExec metrics=REDACTED_| -|_|_|_SeqScan: region=REDACTED, {"partition_count":REDACTED, "projection": ["product_id", "name", "category", "ts"], "filters": ["product_id IS NOT NULL", "category = Utf8(\"electronics\")"], "dyn_filters":REDACTED +|_|_|_SeqScan: region=REDACTED, {"partition_count":REDACTED, "projection": ["product_id", "name", "category"], "filters": ["product_id IS NOT NULL", "category = Utf8(\"electronics\")"], "dyn_filters":REDACTED |_|_|_| |_|_| Total rows: REDACTED_| +-+-+-+ diff --git a/tests/cases/standalone/common/information_schema/compaction_tasks.result b/tests/cases/standalone/common/information_schema/compaction_tasks.result new file mode 100644 index 00000000000..778b15dc997 --- /dev/null +++ b/tests/cases/standalone/common/information_schema/compaction_tasks.result @@ -0,0 +1,49 @@ +DESC TABLE information_schema.compaction_tasks; + ++-------------------+----------------------+-----+------+---------+---------------+ +| Column | Type | Key | Null | Default | Semantic Type | ++-------------------+----------------------+-----+------+---------+---------------+ +| task_id | String | | NO | | FIELD | +| region_id | UInt64 | | NO | | FIELD | +| table_id | UInt32 | | NO | | FIELD | +| node_id | UInt64 | | YES | | FIELD | +| trigger_type | String | | NO | | FIELD | +| state | String | | NO | | FIELD | +| phase | String | | NO | | FIELD | +| submitted_at | TimestampMillisecond | | NO | | FIELD | +| elapsed_millis | UInt64 | | NO | | FIELD | +| input_files | UInt64 | | YES | | FIELD | +| input_bytes | UInt64 | | YES | | FIELD | +| total_units | UInt64 | | YES | | FIELD | +| completed_units | UInt64 | | YES | | FIELD | +| request_options | String | | NO | | FIELD | +| effective_options | String | | YES | | FIELD | +| input_time_start | TimestampNanosecond | | YES | | FIELD | +| input_time_end | TimestampNanosecond | | YES | | FIELD | +| output_time_start | TimestampNanosecond | | YES | | FIELD | +| output_time_end | TimestampNanosecond | | YES | | FIELD | ++-------------------+----------------------+-----+------+---------+---------------+ + +SELECT * FROM information_schema.compaction_tasks WHERE node_id = 18446744073709551615; + ++---------+-----------+----------+---------+--------------+-------+-------+--------------+----------------+-------------+-------------+-------------+-----------------+-----------------+-------------------+------------------+----------------+-------------------+-----------------+ +| task_id | region_id | table_id | node_id | trigger_type | state | phase | submitted_at | elapsed_millis | input_files | input_bytes | total_units | completed_units | request_options | effective_options | input_time_start | input_time_end | output_time_start | output_time_end | ++---------+-----------+----------+---------+--------------+-------+-------+--------------+----------------+-------------+-------------+-------------+-----------------+-----------------+-------------------+------------------+----------------+-------------------+-----------------+ ++---------+-----------+----------+---------+--------------+-------+-------+--------------+----------------+-------------+-------------+-------------+-----------------+-----------------+-------------------+------------------+----------------+-------------------+-----------------+ + +-- Constant projections and aggregates must preserve the empty row count. +SELECT 1 FROM information_schema.compaction_tasks WHERE node_id = 18446744073709551615; + ++----------+ +| Int64(1) | ++----------+ ++----------+ + +SELECT count(*) FROM information_schema.compaction_tasks WHERE node_id = 18446744073709551615; + ++----------+ +| count(*) | ++----------+ +| 0 | ++----------+ + diff --git a/tests/cases/standalone/common/information_schema/compaction_tasks.sql b/tests/cases/standalone/common/information_schema/compaction_tasks.sql new file mode 100644 index 00000000000..854f9c02772 --- /dev/null +++ b/tests/cases/standalone/common/information_schema/compaction_tasks.sql @@ -0,0 +1,8 @@ +DESC TABLE information_schema.compaction_tasks; + +SELECT * FROM information_schema.compaction_tasks WHERE node_id = 18446744073709551615; + +-- Constant projections and aggregates must preserve the empty row count. +SELECT 1 FROM information_schema.compaction_tasks WHERE node_id = 18446744073709551615; + +SELECT count(*) FROM information_schema.compaction_tasks WHERE node_id = 18446744073709551615; diff --git a/tests/cases/standalone/common/information_schema/ssts.result b/tests/cases/standalone/common/information_schema/ssts.result index d8149d27769..029df0e0b7f 100644 --- a/tests/cases/standalone/common/information_schema/ssts.result +++ b/tests/cases/standalone/common/information_schema/ssts.result @@ -321,6 +321,90 @@ ORDER BY min_ts LIMIT 0; +--------+ +--------+ +-- COUNT-only output still applies predicates on columns absent from the output. +SELECT COUNT(*) AS files +FROM information_schema.ssts_manifest +WHERE table_id > 0 + AND min_ts >= '1970-01-01T00:00:00.002Z'::TIMESTAMP_NS + AND max_ts < '1970-01-01T00:00:00.004Z'::TIMESTAMP_NS; + ++-------+ +| files | ++-------+ +| 2 | ++-------+ + +-- Standalone executes these aggregates normally; distributed mode may merge +-- remote states. Both preserve COUNT/SUM and FILTER semantics. +SELECT COUNT(*) AS files, COUNT(1) AS files_one, + SUM(file_size) > 0 AS has_bytes, + COUNT(*) FILTER (WHERE file_size >= 1) AS nonempty_files, + COUNT(*) FILTER (WHERE file_size = 0) AS zero_files, + SUM(file_size) FILTER (WHERE file_size = 0) AS zero_bytes +FROM information_schema.ssts_manifest +WHERE table_id > 0 AND region_id > 0 + AND min_ts >= '1970-01-01T00:00:00.002Z'::TIMESTAMP_NS + AND max_ts < '1970-01-01T00:00:00.004Z'::TIMESTAMP_NS; + ++-------+-----------+-----------+----------------+------------+------------+ +| files | files_one | has_bytes | nonempty_files | zero_files | zero_bytes | ++-------+-----------+-----------+----------------+------------+------------+ +| 2 | 2 | true | 2 | 0 | | ++-------+-----------+-----------+----------------+------------+------------+ + +SELECT COUNT(*) AS files, COUNT(1) AS files_one, SUM(file_size) AS bytes +FROM information_schema.ssts_manifest WHERE region_id = 0; + ++-------+-----------+-------+ +| files | files_one | bytes | ++-------+-----------+-------+ +| 0 | 0 | | ++-------+-----------+-------+ + +-- Generic column aggregates retain the same semantics in both deployment modes. +SELECT COUNT(file_id) = COUNT(*) AS same_file_count, + COUNT(index_file_size) <= COUNT(*) AS nullable_count, + SUM(num_rows) > 0 AS has_rows, + SUM(CAST(num_row_groups AS DOUBLE)) > 0 AS has_float_groups, + SUM(CAST(max_row_group_uncompressed_size AS DECIMAL(20, 0))) >= 0 AS has_decimal_bytes, + COUNT(*) FILTER (WHERE visible AND level = 0) <= COUNT(*) AS visible_count +FROM information_schema.ssts_manifest WHERE region_id > 0; + ++-----------------+----------------+----------+------------------+-------------------+---------------+ +| same_file_count | nullable_count | has_rows | has_float_groups | has_decimal_bytes | visible_count | ++-----------------+----------------+----------+------------------+-------------------+---------------+ +| true | true | true | true | true | true | ++-----------------+----------------+----------+------------------+-------------------+---------------+ + +SELECT COUNT(index_file_size), SUM(num_rows), SUM(level), SUM(index_file_size) +FROM information_schema.ssts_manifest WHERE region_id = 0; + ++---------------------------------------------------------+------------------------------------------------+---------------------------------------------+-------------------------------------------------------+ +| count(information_schema.ssts_manifest.index_file_size) | sum(information_schema.ssts_manifest.num_rows) | sum(information_schema.ssts_manifest.level) | sum(information_schema.ssts_manifest.index_file_size) | ++---------------------------------------------------------+------------------------------------------------+---------------------------------------------+-------------------------------------------------------+ +| 0 | | | | ++---------------------------------------------------------+------------------------------------------------+---------------------------------------------+-------------------------------------------------------+ + +-- Decimal256 can remain internal when only the final DOUBLE result crosses the boundary. +SELECT CAST(SUM(CAST(num_rows AS DECIMAL(39, 0))) AS DOUBLE) > 0 AS has_rows +FROM information_schema.ssts_manifest; + ++----------+ +| has_rows | ++----------+ +| true | ++----------+ + +SELECT COUNT(*) AS files, + CAST(SUM(CAST(file_size AS DECIMAL(39, 0))) AS DOUBLE) AS bytes +FROM information_schema.ssts_manifest WHERE region_id = 0; + ++-------+-------+ +| files | bytes | ++-------+-------+ +| 0 | | ++-------+-------+ + DROP TABLE sst_case; Affected Rows: 0 diff --git a/tests/cases/standalone/common/information_schema/ssts.sql b/tests/cases/standalone/common/information_schema/ssts.sql index e630ab9a0ba..e16a73213b7 100644 --- a/tests/cases/standalone/common/information_schema/ssts.sql +++ b/tests/cases/standalone/common/information_schema/ssts.sql @@ -115,4 +115,46 @@ WHERE region_id = 0 ORDER BY min_ts LIMIT 1; SELECT min_ts FROM information_schema.ssts_manifest ORDER BY min_ts LIMIT 0; +-- COUNT-only output still applies predicates on columns absent from the output. +SELECT COUNT(*) AS files +FROM information_schema.ssts_manifest +WHERE table_id > 0 + AND min_ts >= '1970-01-01T00:00:00.002Z'::TIMESTAMP_NS + AND max_ts < '1970-01-01T00:00:00.004Z'::TIMESTAMP_NS; + +-- Standalone executes these aggregates normally; distributed mode may merge +-- remote states. Both preserve COUNT/SUM and FILTER semantics. +SELECT COUNT(*) AS files, COUNT(1) AS files_one, + SUM(file_size) > 0 AS has_bytes, + COUNT(*) FILTER (WHERE file_size >= 1) AS nonempty_files, + COUNT(*) FILTER (WHERE file_size = 0) AS zero_files, + SUM(file_size) FILTER (WHERE file_size = 0) AS zero_bytes +FROM information_schema.ssts_manifest +WHERE table_id > 0 AND region_id > 0 + AND min_ts >= '1970-01-01T00:00:00.002Z'::TIMESTAMP_NS + AND max_ts < '1970-01-01T00:00:00.004Z'::TIMESTAMP_NS; + +SELECT COUNT(*) AS files, COUNT(1) AS files_one, SUM(file_size) AS bytes +FROM information_schema.ssts_manifest WHERE region_id = 0; + +-- Generic column aggregates retain the same semantics in both deployment modes. +SELECT COUNT(file_id) = COUNT(*) AS same_file_count, + COUNT(index_file_size) <= COUNT(*) AS nullable_count, + SUM(num_rows) > 0 AS has_rows, + SUM(CAST(num_row_groups AS DOUBLE)) > 0 AS has_float_groups, + SUM(CAST(max_row_group_uncompressed_size AS DECIMAL(20, 0))) >= 0 AS has_decimal_bytes, + COUNT(*) FILTER (WHERE visible AND level = 0) <= COUNT(*) AS visible_count +FROM information_schema.ssts_manifest WHERE region_id > 0; + +SELECT COUNT(index_file_size), SUM(num_rows), SUM(level), SUM(index_file_size) +FROM information_schema.ssts_manifest WHERE region_id = 0; + +-- Decimal256 can remain internal when only the final DOUBLE result crosses the boundary. +SELECT CAST(SUM(CAST(num_rows AS DECIMAL(39, 0))) AS DOUBLE) > 0 AS has_rows +FROM information_schema.ssts_manifest; + +SELECT COUNT(*) AS files, + CAST(SUM(CAST(file_size AS DECIMAL(39, 0))) AS DOUBLE) AS bytes +FROM information_schema.ssts_manifest WHERE region_id = 0; + DROP TABLE sst_case; diff --git a/tests/cases/standalone/common/join/merge_scan_projection.result b/tests/cases/standalone/common/join/merge_scan_projection.result new file mode 100644 index 00000000000..2607a776d93 --- /dev/null +++ b/tests/cases/standalone/common/join/merge_scan_projection.result @@ -0,0 +1,103 @@ +CREATE TABLE projection_spans ( + trace_id STRING, + span_id STRING, + parent_span_id STRING, + service_name STRING, + payload STRING, + ts TIMESTAMP TIME INDEX, + PRIMARY KEY (service_name) +) +PARTITION ON COLUMNS (service_name) ( + service_name < 'storage', service_name >= 'storage' +) +WITH (append_mode = 'true'); + +Affected Rows: 0 + +INSERT INTO projection_spans VALUES + ('trace-a', 'root', NULL, 'front', 'root payload', 0), + ('trace-a', 'child', 'root', 'storage', 'child payload', 1), + ('trace-a', 'same', 'root', 'front', 'same service', 2), + ('trace-b', 'child', 'root', 'storage', 'unmatched trace', 3); + +Affected Rows: 4 + +ADMIN FLUSH_TABLE('projection_spans'); + ++---------------------------------------+ +| ADMIN FLUSH_TABLE('projection_spans') | ++---------------------------------------+ +| 0 | ++---------------------------------------+ + +-- Each remote scan supplies the three join columns without a local projection. +-- SQLNESS REPLACE (peers.*) peers=REDACTED +EXPLAIN SELECT p.service_name AS parent_service, + c.service_name AS child_service, COUNT(*) AS call_count +FROM projection_spans c JOIN projection_spans p + ON c.trace_id = p.trace_id AND c.parent_span_id = p.span_id +WHERE c.service_name <> p.service_name +GROUP BY p.service_name, c.service_name +ORDER BY p.service_name, c.service_name; + ++---------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| plan_type | plan | ++---------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| logical_plan | Sort: parent_service ASC NULLS LAST, child_service ASC NULLS LAST | +| | Projection: p.service_name AS parent_service, c.service_name AS child_service, count(Int64(1)) AS count(*) AS call_count | +| | Aggregate: groupBy=[[p.service_name, c.service_name]], aggr=[[count(Int64(1))]] | +| | Projection: c.service_name, p.service_name | +| | Inner Join: c.trace_id = p.trace_id, c.parent_span_id = p.span_id Filter: p.service_name != c.service_name | +| | MergeScan [is_placeholder=false, remote_input=[ | +| | Projection: c.trace_id, c.parent_span_id, c.service_name | +| | SubqueryAlias: c | +| | Filter: projection_spans.trace_id IS NOT NULL AND projection_spans.parent_span_id IS NOT NULL | +| | TableScan: projection_spans, partial_filters=[projection_spans.trace_id IS NOT NULL, projection_spans.parent_span_id IS NOT NULL] | +| | ]] | +| | MergeScan [is_placeholder=false, remote_input=[ | +| | Projection: p.trace_id, p.span_id, p.service_name | +| | SubqueryAlias: p | +| | Filter: projection_spans.trace_id IS NOT NULL AND projection_spans.span_id IS NOT NULL | +| | TableScan: projection_spans, partial_filters=[projection_spans.trace_id IS NOT NULL, projection_spans.span_id IS NOT NULL] | +| | ]] | +| physical_plan | SortPreservingMergeExec: [parent_service@0 ASC NULLS LAST, child_service@1 ASC NULLS LAST] | +| | ProjectionExec: expr=[service_name@0 as parent_service, service_name@1 as child_service, count(Int64(1))@2 as call_count] | +| | SortExec: expr=[service_name@0 ASC NULLS LAST, service_name@1 ASC NULLS LAST], preserve_partitioning=[true] | +| | AggregateExec: mode=FinalPartitioned, gby=[service_name@0 as service_name, service_name@1 as service_name], aggr=[count(Int64(1))] | +| | RepartitionExec: partitioning=Hash([service_name@0, service_name@1], 4), input_partitions=4 | +| | AggregateExec: mode=Partial, gby=[service_name@1 as service_name, service_name@0 as service_name], aggr=[count(Int64(1))] | +| | HashJoinExec: mode=Partitioned, join_type=Inner, on=[(trace_id@0, trace_id@0), (parent_span_id@1, span_id@1)], filter=service_name@1 != service_name@0, projection=[service_name@2, service_name@5] | +| | RepartitionExec: partitioning=Hash([trace_id@0, parent_span_id@1], 4), input_partitions=2 | +| | MergeScanExec: peers=REDACTED +| | RepartitionExec: partitioning=Hash([trace_id@0, span_id@1], 4), input_partitions=2 | +| | MergeScanExec: peers=REDACTED +| | | ++---------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ + +SELECT p.service_name AS parent_service, + c.service_name AS child_service, COUNT(*) AS call_count +FROM projection_spans c JOIN projection_spans p + ON c.trace_id = p.trace_id AND c.parent_span_id = p.span_id +WHERE c.service_name <> p.service_name +GROUP BY p.service_name, c.service_name +ORDER BY p.service_name, c.service_name; + ++----------------+---------------+------------+ +| parent_service | child_service | call_count | ++----------------+---------------+------------+ +| front | storage | 1 | ++----------------+---------------+------------+ + +SELECT COUNT(*) AS cross_rows +FROM projection_spans a CROSS JOIN projection_spans b; + ++------------+ +| cross_rows | ++------------+ +| 16 | ++------------+ + +DROP TABLE projection_spans; + +Affected Rows: 0 + diff --git a/tests/cases/standalone/common/join/merge_scan_projection.sql b/tests/cases/standalone/common/join/merge_scan_projection.sql new file mode 100644 index 00000000000..a9297d028b2 --- /dev/null +++ b/tests/cases/standalone/common/join/merge_scan_projection.sql @@ -0,0 +1,44 @@ +CREATE TABLE projection_spans ( + trace_id STRING, + span_id STRING, + parent_span_id STRING, + service_name STRING, + payload STRING, + ts TIMESTAMP TIME INDEX, + PRIMARY KEY (service_name) +) +PARTITION ON COLUMNS (service_name) ( + service_name < 'storage', service_name >= 'storage' +) +WITH (append_mode = 'true'); + +INSERT INTO projection_spans VALUES + ('trace-a', 'root', NULL, 'front', 'root payload', 0), + ('trace-a', 'child', 'root', 'storage', 'child payload', 1), + ('trace-a', 'same', 'root', 'front', 'same service', 2), + ('trace-b', 'child', 'root', 'storage', 'unmatched trace', 3); + +ADMIN FLUSH_TABLE('projection_spans'); + +-- Each remote scan supplies the three join columns without a local projection. +-- SQLNESS REPLACE (peers.*) peers=REDACTED +EXPLAIN SELECT p.service_name AS parent_service, + c.service_name AS child_service, COUNT(*) AS call_count +FROM projection_spans c JOIN projection_spans p + ON c.trace_id = p.trace_id AND c.parent_span_id = p.span_id +WHERE c.service_name <> p.service_name +GROUP BY p.service_name, c.service_name +ORDER BY p.service_name, c.service_name; + +SELECT p.service_name AS parent_service, + c.service_name AS child_service, COUNT(*) AS call_count +FROM projection_spans c JOIN projection_spans p + ON c.trace_id = p.trace_id AND c.parent_span_id = p.span_id +WHERE c.service_name <> p.service_name +GROUP BY p.service_name, c.service_name +ORDER BY p.service_name, c.service_name; + +SELECT COUNT(*) AS cross_rows +FROM projection_spans a CROSS JOIN projection_spans b; + +DROP TABLE projection_spans; diff --git a/tests/cases/standalone/common/join/merge_scan_semi_join.result b/tests/cases/standalone/common/join/merge_scan_semi_join.result index 598e2099662..d56fd6a6877 100644 --- a/tests/cases/standalone/common/join/merge_scan_semi_join.result +++ b/tests/cases/standalone/common/join/merge_scan_semi_join.result @@ -42,36 +42,35 @@ WHERE key_id IN ( ) GROUP BY key_id ORDER BY key_id; -+---------------+---------------------------------------------------------------------------------------------------------------------------------------+ -| plan_type | plan | -+---------------+---------------------------------------------------------------------------------------------------------------------------------------+ -| logical_plan | Sort: merge_semi_data.key_id ASC NULLS LAST | -| | Projection: merge_semi_data.key_id, min(merge_semi_data.ts) AS first_ts | -| | Aggregate: groupBy=[[merge_semi_data.key_id]], aggr=[[min(merge_semi_data.ts)]] | -| | LeftSemi Join: merge_semi_data.key_id = __correlated_sq_1.key_id | -| | Projection: merge_semi_data.ts, merge_semi_data.key_id | -| | MergeScan [is_placeholder=false, remote_input=[ | -| | Filter: merge_semi_data.key_id IS NOT NULL | -| | TableScan: merge_semi_data, partial_filters=[merge_semi_data.key_id IS NOT NULL] | -| | ]] | -| | MergeScan [is_placeholder=false, remote_input=[ | -| | SubqueryAlias: __correlated_sq_1 | -| | Projection: merge_semi_data.key_id | -| | Filter: merge_semi_data.is_match AND merge_semi_data.key_id IS NOT NULL | -| | TableScan: merge_semi_data, partial_filters=[merge_semi_data.is_match, merge_semi_data.key_id IS NOT NULL] | -| | ]] | -| physical_plan | SortPreservingMergeExec: [key_id@0 ASC NULLS LAST] | -| | ProjectionExec: expr=[key_id@0 as key_id, min(merge_semi_data.ts)@1 as first_ts] | -| | SortExec: expr=[key_id@0 ASC NULLS LAST], preserve_partitioning=[true] | -| | AggregateExec: mode=SinglePartitioned, gby=[key_id@1 as key_id], aggr=[min(merge_semi_data.ts)] | -| | HashJoinExec: mode=Partitioned, join_type=LeftSemi, on=[(key_id@1, key_id@0)] | -| | RepartitionExec: partitioning=Hash([key_id@1], 4), input_partitions=4 | -| | ProjectionExec: expr=[ts@0 as ts, key_id@1 as key_id] | -| | MergeScanExec: peers=REDACTED -| | RepartitionExec: partitioning=Hash([key_id@0], 4), input_partitions=4 | ++---------------+-------------------------------------------------------------------------------------------------------------------------------------+ +| plan_type | plan | ++---------------+-------------------------------------------------------------------------------------------------------------------------------------+ +| logical_plan | Sort: merge_semi_data.key_id ASC NULLS LAST | +| | Projection: merge_semi_data.key_id, min(merge_semi_data.ts) AS first_ts | +| | Aggregate: groupBy=[[merge_semi_data.key_id]], aggr=[[min(merge_semi_data.ts)]] | +| | LeftSemi Join: merge_semi_data.key_id = __correlated_sq_1.key_id | +| | MergeScan [is_placeholder=false, remote_input=[ | +| | Projection: merge_semi_data.ts, merge_semi_data.key_id | +| | Filter: merge_semi_data.key_id IS NOT NULL | +| | TableScan: merge_semi_data, partial_filters=[merge_semi_data.key_id IS NOT NULL] | +| | ]] | +| | MergeScan [is_placeholder=false, remote_input=[ | +| | SubqueryAlias: __correlated_sq_1 | +| | Projection: merge_semi_data.key_id | +| | Filter: merge_semi_data.is_match AND merge_semi_data.key_id IS NOT NULL | +| | TableScan: merge_semi_data, partial_filters=[merge_semi_data.is_match, merge_semi_data.key_id IS NOT NULL] | +| | ]] | +| physical_plan | SortPreservingMergeExec: [key_id@0 ASC NULLS LAST] | +| | ProjectionExec: expr=[key_id@0 as key_id, min(merge_semi_data.ts)@1 as first_ts] | +| | SortExec: expr=[key_id@0 ASC NULLS LAST], preserve_partitioning=[true] | +| | AggregateExec: mode=SinglePartitioned, gby=[key_id@1 as key_id], aggr=[min(merge_semi_data.ts)] | +| | HashJoinExec: mode=Partitioned, join_type=LeftSemi, on=[(key_id@1, key_id@0)] | +| | RepartitionExec: partitioning=Hash([key_id@1], 4), input_partitions=4 | | | MergeScanExec: peers=REDACTED -| | | -+---------------+---------------------------------------------------------------------------------------------------------------------------------------+ +| | RepartitionExec: partitioning=Hash([key_id@0], 4), input_partitions=4 | +| | MergeScanExec: peers=REDACTED +| | | ++---------------+-------------------------------------------------------------------------------------------------------------------------------------+ -- Every key matches and reports its earliest (false-row) timestamp. SELECT key_id, MIN(ts) AS first_ts @@ -131,36 +130,35 @@ WHERE key_id IN ( ) GROUP BY key_id ORDER BY key_id; -+---------------+---------------------------------------------------------------------------------------------------------------------------------------+ -| plan_type | plan | -+---------------+---------------------------------------------------------------------------------------------------------------------------------------+ -| logical_plan | Sort: merge_semi_data.key_id ASC NULLS LAST | -| | Projection: merge_semi_data.key_id, min(merge_semi_data.ts) AS first_ts | -| | Aggregate: groupBy=[[merge_semi_data.key_id]], aggr=[[min(merge_semi_data.ts)]] | -| | LeftSemi Join: merge_semi_data.key_id = __correlated_sq_1.key_id | -| | Projection: merge_semi_data.ts, merge_semi_data.key_id | -| | MergeScan [is_placeholder=false, remote_input=[ | -| | Filter: merge_semi_data.key_id IS NOT NULL | -| | TableScan: merge_semi_data, partial_filters=[merge_semi_data.key_id IS NOT NULL] | -| | ]] | -| | MergeScan [is_placeholder=false, remote_input=[ | -| | SubqueryAlias: __correlated_sq_1 | -| | Projection: merge_semi_data.key_id | -| | Filter: merge_semi_data.is_match AND merge_semi_data.key_id IS NOT NULL | -| | TableScan: merge_semi_data, partial_filters=[merge_semi_data.is_match, merge_semi_data.key_id IS NOT NULL] | -| | ]] | -| physical_plan | SortPreservingMergeExec: [key_id@0 ASC NULLS LAST] | -| | ProjectionExec: expr=[key_id@0 as key_id, min(merge_semi_data.ts)@1 as first_ts] | -| | SortExec: expr=[key_id@0 ASC NULLS LAST], preserve_partitioning=[true] | -| | AggregateExec: mode=SinglePartitioned, gby=[key_id@1 as key_id], aggr=[min(merge_semi_data.ts)] | -| | HashJoinExec: mode=Partitioned, join_type=LeftSemi, on=[(key_id@1, key_id@0)] | -| | RepartitionExec: partitioning=Hash([key_id@1], 2), input_partitions=2 | -| | ProjectionExec: expr=[ts@0 as ts, key_id@1 as key_id] | -| | MergeScanExec: peers=REDACTED -| | RepartitionExec: partitioning=Hash([key_id@0], 2), input_partitions=2 | ++---------------+-------------------------------------------------------------------------------------------------------------------------------------+ +| plan_type | plan | ++---------------+-------------------------------------------------------------------------------------------------------------------------------------+ +| logical_plan | Sort: merge_semi_data.key_id ASC NULLS LAST | +| | Projection: merge_semi_data.key_id, min(merge_semi_data.ts) AS first_ts | +| | Aggregate: groupBy=[[merge_semi_data.key_id]], aggr=[[min(merge_semi_data.ts)]] | +| | LeftSemi Join: merge_semi_data.key_id = __correlated_sq_1.key_id | +| | MergeScan [is_placeholder=false, remote_input=[ | +| | Projection: merge_semi_data.ts, merge_semi_data.key_id | +| | Filter: merge_semi_data.key_id IS NOT NULL | +| | TableScan: merge_semi_data, partial_filters=[merge_semi_data.key_id IS NOT NULL] | +| | ]] | +| | MergeScan [is_placeholder=false, remote_input=[ | +| | SubqueryAlias: __correlated_sq_1 | +| | Projection: merge_semi_data.key_id | +| | Filter: merge_semi_data.is_match AND merge_semi_data.key_id IS NOT NULL | +| | TableScan: merge_semi_data, partial_filters=[merge_semi_data.is_match, merge_semi_data.key_id IS NOT NULL] | +| | ]] | +| physical_plan | SortPreservingMergeExec: [key_id@0 ASC NULLS LAST] | +| | ProjectionExec: expr=[key_id@0 as key_id, min(merge_semi_data.ts)@1 as first_ts] | +| | SortExec: expr=[key_id@0 ASC NULLS LAST], preserve_partitioning=[true] | +| | AggregateExec: mode=SinglePartitioned, gby=[key_id@1 as key_id], aggr=[min(merge_semi_data.ts)] | +| | HashJoinExec: mode=Partitioned, join_type=LeftSemi, on=[(key_id@1, key_id@0)] | +| | RepartitionExec: partitioning=Hash([key_id@1], 2), input_partitions=2 | | | MergeScanExec: peers=REDACTED -| | | -+---------------+---------------------------------------------------------------------------------------------------------------------------------------+ +| | RepartitionExec: partitioning=Hash([key_id@0], 2), input_partitions=2 | +| | MergeScanExec: peers=REDACTED +| | | ++---------------+-------------------------------------------------------------------------------------------------------------------------------------+ -- SQLNESS PROTOCOL MYSQL SELECT key_id, MIN(ts) AS first_ts @@ -220,35 +218,34 @@ WHERE key_id IN ( ) GROUP BY key_id ORDER BY key_id; -+---------------+-------------------------------------------------------------------------------------------------------------------------------------+ -| plan_type | plan | -+---------------+-------------------------------------------------------------------------------------------------------------------------------------+ -| logical_plan | Sort: merge_semi_data.key_id ASC NULLS LAST | -| | Projection: merge_semi_data.key_id, min(merge_semi_data.ts) AS first_ts | -| | Aggregate: groupBy=[[merge_semi_data.key_id]], aggr=[[min(merge_semi_data.ts)]] | -| | LeftSemi Join: merge_semi_data.key_id = __correlated_sq_1.key_id | -| | Projection: merge_semi_data.ts, merge_semi_data.key_id | -| | MergeScan [is_placeholder=false, remote_input=[ | -| | Filter: merge_semi_data.key_id IS NOT NULL | -| | TableScan: merge_semi_data, partial_filters=[merge_semi_data.key_id IS NOT NULL] | -| | ]] | -| | MergeScan [is_placeholder=false, remote_input=[ | -| | SubqueryAlias: __correlated_sq_1 | -| | Projection: merge_semi_data.key_id | -| | Filter: merge_semi_data.is_match AND merge_semi_data.key_id IS NOT NULL | -| | TableScan: merge_semi_data, partial_filters=[merge_semi_data.is_match, merge_semi_data.key_id IS NOT NULL] | -| | ]] | -| physical_plan | ProjectionExec: expr=[key_id@0 as key_id, min(merge_semi_data.ts)@1 as first_ts] | -| | SortExec: expr=[key_id@0 ASC NULLS LAST], preserve_partitioning=[false] | -| | AggregateExec: mode=Single, gby=[key_id@1 as key_id], aggr=[min(merge_semi_data.ts)] | -| | HashJoinExec: mode=CollectLeft, join_type=LeftSemi, on=[(key_id@1, key_id@0)] | -| | ProjectionExec: expr=[ts@0 as ts, key_id@1 as key_id] | -| | CooperativeExec | -| | MergeScanExec: peers=REDACTED -| | CooperativeExec | ++---------------+-----------------------------------------------------------------------------------------------------------------------------------+ +| plan_type | plan | ++---------------+-----------------------------------------------------------------------------------------------------------------------------------+ +| logical_plan | Sort: merge_semi_data.key_id ASC NULLS LAST | +| | Projection: merge_semi_data.key_id, min(merge_semi_data.ts) AS first_ts | +| | Aggregate: groupBy=[[merge_semi_data.key_id]], aggr=[[min(merge_semi_data.ts)]] | +| | LeftSemi Join: merge_semi_data.key_id = __correlated_sq_1.key_id | +| | MergeScan [is_placeholder=false, remote_input=[ | +| | Projection: merge_semi_data.ts, merge_semi_data.key_id | +| | Filter: merge_semi_data.key_id IS NOT NULL | +| | TableScan: merge_semi_data, partial_filters=[merge_semi_data.key_id IS NOT NULL] | +| | ]] | +| | MergeScan [is_placeholder=false, remote_input=[ | +| | SubqueryAlias: __correlated_sq_1 | +| | Projection: merge_semi_data.key_id | +| | Filter: merge_semi_data.is_match AND merge_semi_data.key_id IS NOT NULL | +| | TableScan: merge_semi_data, partial_filters=[merge_semi_data.is_match, merge_semi_data.key_id IS NOT NULL] | +| | ]] | +| physical_plan | ProjectionExec: expr=[key_id@0 as key_id, min(merge_semi_data.ts)@1 as first_ts] | +| | SortExec: expr=[key_id@0 ASC NULLS LAST], preserve_partitioning=[false] | +| | AggregateExec: mode=Single, gby=[key_id@1 as key_id], aggr=[min(merge_semi_data.ts)] | +| | HashJoinExec: mode=CollectLeft, join_type=LeftSemi, on=[(key_id@1, key_id@0)] | +| | CooperativeExec | | | MergeScanExec: peers=REDACTED -| | | -+---------------+-------------------------------------------------------------------------------------------------------------------------------------+ +| | CooperativeExec | +| | MergeScanExec: peers=REDACTED +| | | ++---------------+-----------------------------------------------------------------------------------------------------------------------------------+ -- SQLNESS PROTOCOL MYSQL SELECT key_id, MIN(ts) AS first_ts @@ -313,36 +310,35 @@ WHERE key_id IN ( ) GROUP BY key_id ORDER BY key_id; -+---------------+---------------------------------------------------------------------------------------------------------------------------------------+ -| plan_type | plan | -+---------------+---------------------------------------------------------------------------------------------------------------------------------------+ -| logical_plan | Sort: merge_semi_data.key_id ASC NULLS LAST | -| | Projection: merge_semi_data.key_id, min(merge_semi_data.ts) AS first_ts | -| | Aggregate: groupBy=[[merge_semi_data.key_id]], aggr=[[min(merge_semi_data.ts)]] | -| | LeftSemi Join: merge_semi_data.key_id = __correlated_sq_1.key_id | -| | Projection: merge_semi_data.ts, merge_semi_data.key_id | -| | MergeScan [is_placeholder=false, remote_input=[ | -| | Filter: merge_semi_data.key_id IS NOT NULL | -| | TableScan: merge_semi_data, partial_filters=[merge_semi_data.key_id IS NOT NULL] | -| | ]] | -| | MergeScan [is_placeholder=false, remote_input=[ | -| | SubqueryAlias: __correlated_sq_1 | -| | Projection: merge_semi_data.key_id | -| | Filter: merge_semi_data.is_match AND merge_semi_data.key_id IS NOT NULL | -| | TableScan: merge_semi_data, partial_filters=[merge_semi_data.is_match, merge_semi_data.key_id IS NOT NULL] | -| | ]] | -| physical_plan | SortPreservingMergeExec: [key_id@0 ASC NULLS LAST] | -| | ProjectionExec: expr=[key_id@0 as key_id, min(merge_semi_data.ts)@1 as first_ts] | -| | SortExec: expr=[key_id@0 ASC NULLS LAST], preserve_partitioning=[true] | -| | AggregateExec: mode=SinglePartitioned, gby=[key_id@1 as key_id], aggr=[min(merge_semi_data.ts)] | -| | HashJoinExec: mode=Partitioned, join_type=LeftSemi, on=[(key_id@1, key_id@0)] | -| | RepartitionExec: partitioning=Hash([key_id@1], 2), input_partitions=2 | -| | ProjectionExec: expr=[ts@0 as ts, key_id@1 as key_id] | -| | MergeScanExec: peers=REDACTED -| | RepartitionExec: partitioning=Hash([key_id@0], 2), input_partitions=2 | ++---------------+-------------------------------------------------------------------------------------------------------------------------------------+ +| plan_type | plan | ++---------------+-------------------------------------------------------------------------------------------------------------------------------------+ +| logical_plan | Sort: merge_semi_data.key_id ASC NULLS LAST | +| | Projection: merge_semi_data.key_id, min(merge_semi_data.ts) AS first_ts | +| | Aggregate: groupBy=[[merge_semi_data.key_id]], aggr=[[min(merge_semi_data.ts)]] | +| | LeftSemi Join: merge_semi_data.key_id = __correlated_sq_1.key_id | +| | MergeScan [is_placeholder=false, remote_input=[ | +| | Projection: merge_semi_data.ts, merge_semi_data.key_id | +| | Filter: merge_semi_data.key_id IS NOT NULL | +| | TableScan: merge_semi_data, partial_filters=[merge_semi_data.key_id IS NOT NULL] | +| | ]] | +| | MergeScan [is_placeholder=false, remote_input=[ | +| | SubqueryAlias: __correlated_sq_1 | +| | Projection: merge_semi_data.key_id | +| | Filter: merge_semi_data.is_match AND merge_semi_data.key_id IS NOT NULL | +| | TableScan: merge_semi_data, partial_filters=[merge_semi_data.is_match, merge_semi_data.key_id IS NOT NULL] | +| | ]] | +| physical_plan | SortPreservingMergeExec: [key_id@0 ASC NULLS LAST] | +| | ProjectionExec: expr=[key_id@0 as key_id, min(merge_semi_data.ts)@1 as first_ts] | +| | SortExec: expr=[key_id@0 ASC NULLS LAST], preserve_partitioning=[true] | +| | AggregateExec: mode=SinglePartitioned, gby=[key_id@1 as key_id], aggr=[min(merge_semi_data.ts)] | +| | HashJoinExec: mode=Partitioned, join_type=LeftSemi, on=[(key_id@1, key_id@0)] | +| | RepartitionExec: partitioning=Hash([key_id@1], 2), input_partitions=2 | | | MergeScanExec: peers=REDACTED -| | | -+---------------+---------------------------------------------------------------------------------------------------------------------------------------+ +| | RepartitionExec: partitioning=Hash([key_id@0], 2), input_partitions=2 | +| | MergeScanExec: peers=REDACTED +| | | ++---------------+-------------------------------------------------------------------------------------------------------------------------------------+ -- SQLNESS PROTOCOL MYSQL SELECT key_id, MIN(ts) AS first_ts @@ -398,36 +394,35 @@ WHERE key_id IN ( ) GROUP BY key_id ORDER BY key_id; -+---------------+---------------------------------------------------------------------------------------------------------------------------------------+ -| plan_type | plan | -+---------------+---------------------------------------------------------------------------------------------------------------------------------------+ -| logical_plan | Sort: merge_semi_data.key_id ASC NULLS LAST | -| | Projection: merge_semi_data.key_id, min(merge_semi_data.ts) AS first_ts | -| | Aggregate: groupBy=[[merge_semi_data.key_id]], aggr=[[min(merge_semi_data.ts)]] | -| | LeftSemi Join: merge_semi_data.key_id = __correlated_sq_1.key_id | -| | Projection: merge_semi_data.ts, merge_semi_data.key_id | -| | MergeScan [is_placeholder=false, remote_input=[ | -| | Filter: merge_semi_data.key_id IS NOT NULL | -| | TableScan: merge_semi_data, partial_filters=[merge_semi_data.key_id IS NOT NULL] | -| | ]] | -| | MergeScan [is_placeholder=false, remote_input=[ | -| | SubqueryAlias: __correlated_sq_1 | -| | Projection: merge_semi_data.key_id | -| | Filter: merge_semi_data.is_match AND merge_semi_data.key_id IS NOT NULL | -| | TableScan: merge_semi_data, partial_filters=[merge_semi_data.is_match, merge_semi_data.key_id IS NOT NULL] | -| | ]] | -| physical_plan | SortPreservingMergeExec: [key_id@0 ASC NULLS LAST] | -| | ProjectionExec: expr=[key_id@0 as key_id, min(merge_semi_data.ts)@1 as first_ts] | -| | SortExec: expr=[key_id@0 ASC NULLS LAST], preserve_partitioning=[true] | -| | AggregateExec: mode=SinglePartitioned, gby=[key_id@1 as key_id], aggr=[min(merge_semi_data.ts)] | -| | HashJoinExec: mode=Partitioned, join_type=LeftSemi, on=[(key_id@1, key_id@0)] | -| | RepartitionExec: partitioning=Hash([key_id@1], 4), input_partitions=4 | -| | ProjectionExec: expr=[ts@0 as ts, key_id@1 as key_id] | -| | MergeScanExec: peers=REDACTED -| | RepartitionExec: partitioning=Hash([key_id@0], 4), input_partitions=4 | ++---------------+-------------------------------------------------------------------------------------------------------------------------------------+ +| plan_type | plan | ++---------------+-------------------------------------------------------------------------------------------------------------------------------------+ +| logical_plan | Sort: merge_semi_data.key_id ASC NULLS LAST | +| | Projection: merge_semi_data.key_id, min(merge_semi_data.ts) AS first_ts | +| | Aggregate: groupBy=[[merge_semi_data.key_id]], aggr=[[min(merge_semi_data.ts)]] | +| | LeftSemi Join: merge_semi_data.key_id = __correlated_sq_1.key_id | +| | MergeScan [is_placeholder=false, remote_input=[ | +| | Projection: merge_semi_data.ts, merge_semi_data.key_id | +| | Filter: merge_semi_data.key_id IS NOT NULL | +| | TableScan: merge_semi_data, partial_filters=[merge_semi_data.key_id IS NOT NULL] | +| | ]] | +| | MergeScan [is_placeholder=false, remote_input=[ | +| | SubqueryAlias: __correlated_sq_1 | +| | Projection: merge_semi_data.key_id | +| | Filter: merge_semi_data.is_match AND merge_semi_data.key_id IS NOT NULL | +| | TableScan: merge_semi_data, partial_filters=[merge_semi_data.is_match, merge_semi_data.key_id IS NOT NULL] | +| | ]] | +| physical_plan | SortPreservingMergeExec: [key_id@0 ASC NULLS LAST] | +| | ProjectionExec: expr=[key_id@0 as key_id, min(merge_semi_data.ts)@1 as first_ts] | +| | SortExec: expr=[key_id@0 ASC NULLS LAST], preserve_partitioning=[true] | +| | AggregateExec: mode=SinglePartitioned, gby=[key_id@1 as key_id], aggr=[min(merge_semi_data.ts)] | +| | HashJoinExec: mode=Partitioned, join_type=LeftSemi, on=[(key_id@1, key_id@0)] | +| | RepartitionExec: partitioning=Hash([key_id@1], 4), input_partitions=4 | | | MergeScanExec: peers=REDACTED -| | | -+---------------+---------------------------------------------------------------------------------------------------------------------------------------+ +| | RepartitionExec: partitioning=Hash([key_id@0], 4), input_partitions=4 | +| | MergeScanExec: peers=REDACTED +| | | ++---------------+-------------------------------------------------------------------------------------------------------------------------------------+ DROP TABLE merge_semi_data; diff --git a/tests/cases/standalone/common/promql/scatter_time_filter.result b/tests/cases/standalone/common/promql/scatter_time_filter.result new file mode 100644 index 00000000000..82242fe7ae2 --- /dev/null +++ b/tests/cases/standalone/common/promql/scatter_time_filter.result @@ -0,0 +1,57 @@ +-- More than 128 evaluation points must survive the expression-depth guard. +-- Sparse samples exercise excluded lower bounds, included upper bounds and gaps. +CREATE TABLE scatter_time_filter ( + ts TIMESTAMP TIME INDEX, + val DOUBLE +); + +Affected Rows: 0 + +INSERT INTO scatter_time_filter VALUES + (3600000, 1), (3600001, 2), (7199999, 3), (7200000, 4), + (7200001, 5), (10800000, 6), (2592000000, 7), + (2592000001, 8); + +Affected Rows: 8 + +TQL EVAL (0, 2593800, '2h') sum(sum_over_time(scatter_time_filter[1h])); + ++---------------------+---------------------------------------+ +| ts | sum(prom_sum_over_time(ts_range,val)) | ++---------------------+---------------------------------------+ +| 1970-01-01T02:00:00 | 9.0 | +| 1970-01-31T00:00:00 | 7.0 | ++---------------------+---------------------------------------+ + +TQL EVAL (0, 2593800, '2h') sum(increase(scatter_time_filter[1h])); + ++---------------------+----------------------------------------------------+ +| ts | sum(prom_increase(ts_range,val,ts,Int64(3600000))) | ++---------------------+----------------------------------------------------+ +| 1970-01-01T02:00:00 | 2.00000055555571 | ++---------------------+----------------------------------------------------+ + +TQL EVAL (0, 2593800, '2h') sum(sum_over_time(scatter_time_filter[2h])); + ++---------------------+---------------------------------------+ +| ts | sum(prom_sum_over_time(ts_range,val)) | ++---------------------+---------------------------------------+ +| 1970-01-01T02:00:00 | 10.0 | +| 1970-01-01T04:00:00 | 11.0 | +| 1970-01-31T00:00:00 | 7.0 | ++---------------------+---------------------------------------+ + +TQL EVAL (0, 2593800, '2h') sum(sum_over_time(scatter_time_filter[3h])); + ++---------------------+---------------------------------------+ +| ts | sum(prom_sum_over_time(ts_range,val)) | ++---------------------+---------------------------------------+ +| 1970-01-01T02:00:00 | 10.0 | +| 1970-01-01T04:00:00 | 20.0 | +| 1970-01-31T00:00:00 | 7.0 | ++---------------------+---------------------------------------+ + +DROP TABLE scatter_time_filter; + +Affected Rows: 0 + diff --git a/tests/cases/standalone/common/promql/scatter_time_filter.sql b/tests/cases/standalone/common/promql/scatter_time_filter.sql new file mode 100644 index 00000000000..56fedc44210 --- /dev/null +++ b/tests/cases/standalone/common/promql/scatter_time_filter.sql @@ -0,0 +1,18 @@ +-- More than 128 evaluation points must survive the expression-depth guard. +-- Sparse samples exercise excluded lower bounds, included upper bounds and gaps. +CREATE TABLE scatter_time_filter ( + ts TIMESTAMP TIME INDEX, + val DOUBLE +); + +INSERT INTO scatter_time_filter VALUES + (3600000, 1), (3600001, 2), (7199999, 3), (7200000, 4), + (7200001, 5), (10800000, 6), (2592000000, 7), + (2592000001, 8); + +TQL EVAL (0, 2593800, '2h') sum(sum_over_time(scatter_time_filter[1h])); +TQL EVAL (0, 2593800, '2h') sum(increase(scatter_time_filter[1h])); +TQL EVAL (0, 2593800, '2h') sum(sum_over_time(scatter_time_filter[2h])); +TQL EVAL (0, 2593800, '2h') sum(sum_over_time(scatter_time_filter[3h])); + +DROP TABLE scatter_time_filter; diff --git a/tests/cases/standalone/common/promql/tsid_binary_join_regression.result b/tests/cases/standalone/common/promql/tsid_binary_join_regression.result index 144f9defc35..4219b3a4787 100644 --- a/tests/cases/standalone/common/promql/tsid_binary_join_regression.result +++ b/tests/cases/standalone/common/promql/tsid_binary_join_regression.result @@ -119,7 +119,6 @@ TQL ANALYZE (0, 5, '5s') tsid_binary_join_left / tsid_binary_join_right; +-+-+-+ | 0_| 0_|_ProjectionExec: expr=[host@0 as host, job@1 as job, ts@2 as ts, __tsid@3 as __tsid, greptime_value@4 / greptime_value@5 as tsid_binary_join_left.greptime_value / tsid_binary_join_right.greptime_value] REDACTED |_|_|_HashJoinExec: mode=CollectLeft, join_type=Inner, on=[(__tsid@1, __tsid@3), (ts@2, ts@4)], projection=[host@4, job@5, ts@7, __tsid@6, greptime_value@0, greptime_value@3], NullsEqual: true REDACTED -|_|_|_ProjectionExec: expr=[greptime_value@0 as greptime_value, __tsid@3 as __tsid, ts@4 as ts] REDACTED |_|_|_CooperativeExec REDACTED |_|_|_MergeScanExec: REDACTED |_|_|_RepartitionExec: partitioning=REDACTED @@ -127,9 +126,9 @@ TQL ANALYZE (0, 5, '5s') tsid_binary_join_left / tsid_binary_join_right; |_|_|_| | 1_| 0_|_PromInstantManipulateExec: range=[0..5000], lookback=[300000], interval=[5000], time index=[ts] REDACTED |_|_|_PromSeriesDivideExec: tags=["__tsid"] REDACTED -|_|_|_ProjectionExec: expr=[greptime_value@1 as greptime_value, host@3 as host, job@4 as job, __tsid@2 as __tsid, ts@0 as ts] REDACTED +|_|_|_ProjectionExec: expr=[greptime_value@1 as greptime_value, __tsid@2 as __tsid, ts@0 as ts] REDACTED |_|_|_CooperativeExec REDACTED -|_|_|_SeriesScan: region=REDACTED, "partition_count":REDACTED, "distribution":"PerSeries", "projection": ["ts", "greptime_value", "__tsid", "host", "job"], "filters": ["__table_id=UInt32(REDACTED)", "ts >= TimestampMillisecond(-299999, None)", "ts <= TimestampMillisecond(5000, None)"], "time_range":REDACTED +|_|_|_SeriesScan: region=REDACTED, "partition_count":REDACTED, "distribution":"PerSeries", "projection": ["ts", "greptime_value", "__tsid"], "filters": ["__table_id=UInt32(REDACTED)", "ts >= TimestampMillisecond(-299999, None)", "ts <= TimestampMillisecond(5000, None)"], "time_range":REDACTED |_|_|_| | 1_| 0_|_PromInstantManipulateExec: range=[0..5000], lookback=[300000], interval=[5000], time index=[ts] REDACTED |_|_|_PromSeriesDivideExec: tags=["__tsid"] REDACTED @@ -164,7 +163,6 @@ TQL ANALYZE (0, 5, '5s') (tsid_binary_join_left + tsid_binary_join_right) / tsid |_|_|_RepartitionExec: partitioning=Hash([__tsid@3, ts@4],REDACTED |_|_|_MergeScanExec: REDACTED |_|_|_RepartitionExec: partitioning=Hash([__tsid@1, ts@2],REDACTED -|_|_|_ProjectionExec: expr=[greptime_value@0 as greptime_value, __tsid@3 as __tsid, ts@4 as ts] REDACTED |_|_|_MergeScanExec: REDACTED |_|_|_| | 1_| 0_|_PromInstantManipulateExec: range=[0..5000], lookback=[300000], interval=[5000], time index=[ts] REDACTED @@ -175,9 +173,9 @@ TQL ANALYZE (0, 5, '5s') (tsid_binary_join_left + tsid_binary_join_right) / tsid |_|_|_| | 1_| 0_|_PromInstantManipulateExec: range=[0..5000], lookback=[300000], interval=[5000], time index=[ts] REDACTED |_|_|_PromSeriesDivideExec: tags=["__tsid"] REDACTED -|_|_|_ProjectionExec: expr=[greptime_value@1 as greptime_value, host@3 as host, job@4 as job, __tsid@2 as __tsid, ts@0 as ts] REDACTED +|_|_|_ProjectionExec: expr=[greptime_value@1 as greptime_value, __tsid@2 as __tsid, ts@0 as ts] REDACTED |_|_|_CooperativeExec REDACTED -|_|_|_SeriesScan: region=REDACTED, "partition_count":REDACTED, "distribution":"PerSeries", "projection": ["ts", "greptime_value", "__tsid", "host", "job"], "filters": ["__table_id=UInt32(REDACTED)", "ts >= TimestampMillisecond(-299999, None)", "ts <= TimestampMillisecond(5000, None)"], "time_range":REDACTED +|_|_|_SeriesScan: region=REDACTED, "partition_count":REDACTED, "distribution":"PerSeries", "projection": ["ts", "greptime_value", "__tsid"], "filters": ["__table_id=UInt32(REDACTED)", "ts >= TimestampMillisecond(-299999, None)", "ts <= TimestampMillisecond(5000, None)"], "time_range":REDACTED |_|_|_| |_|_| Total rows: 4_| +-+-+-+ @@ -206,10 +204,8 @@ TQL ANALYZE (0, 5, '5s') ((tsid_binary_join_left + tsid_binary_join_right) * (ts |_|_|_RepartitionExec: partitioning=Hash([REDACTED |_|_|_MergeScanExec: REDACTED |_|_|_RepartitionExec: partitioning=Hash([REDACTED -|_|_|_ProjectionExec: expr=[greptime_value@0 as greptime_value, __tsid@3 as __tsid, ts@4 as ts] REDACTED |_|_|_MergeScanExec: REDACTED |_|_|_RepartitionExec: partitioning=Hash([REDACTED -|_|_|_ProjectionExec: expr=[greptime_value@0 as greptime_value, __tsid@3 as __tsid, ts@4 as ts] REDACTED |_|_|_MergeScanExec: REDACTED |_|_|_| | 1_| 0_|_PromInstantManipulateExec: range=[0..5000], lookback=[300000], interval=[5000], time index=[ts] REDACTED @@ -220,15 +216,15 @@ TQL ANALYZE (0, 5, '5s') ((tsid_binary_join_left + tsid_binary_join_right) * (ts |_|_|_| | 1_| 0_|_PromInstantManipulateExec: range=[0..5000], lookback=[300000], interval=[5000], time index=[ts] REDACTED |_|_|_PromSeriesDivideExec: tags=["__tsid"] REDACTED -|_|_|_ProjectionExec: expr=[greptime_value@1 as greptime_value, host@3 as host, job@4 as job, __tsid@2 as __tsid, ts@0 as ts] REDACTED +|_|_|_ProjectionExec: expr=[greptime_value@1 as greptime_value, __tsid@2 as __tsid, ts@0 as ts] REDACTED |_|_|_CooperativeExec REDACTED -|_|_|_SeriesScan: region=REDACTED, "partition_count":REDACTED, "distribution":"PerSeries", "projection": ["ts", "greptime_value", "__tsid", "host", "job"], "filters": ["__table_id=UInt32(REDACTED)", "ts >= TimestampMillisecond(-299999, None)", "ts <= TimestampMillisecond(5000, None)"], "time_range":REDACTED +|_|_|_SeriesScan: region=REDACTED, "partition_count":REDACTED, "distribution":"PerSeries", "projection": ["ts", "greptime_value", "__tsid"], "filters": ["__table_id=UInt32(REDACTED)", "ts >= TimestampMillisecond(-299999, None)", "ts <= TimestampMillisecond(5000, None)"], "time_range":REDACTED |_|_|_| | 1_| 0_|_PromInstantManipulateExec: range=[0..5000], lookback=[300000], interval=[5000], time index=[ts] REDACTED |_|_|_PromSeriesDivideExec: tags=["__tsid"] REDACTED -|_|_|_ProjectionExec: expr=[greptime_value@1 as greptime_value, host@3 as host, job@4 as job, __tsid@2 as __tsid, ts@0 as ts] REDACTED +|_|_|_ProjectionExec: expr=[greptime_value@1 as greptime_value, __tsid@2 as __tsid, ts@0 as ts] REDACTED |_|_|_CooperativeExec REDACTED -|_|_|_SeriesScan: region=REDACTED, "partition_count":REDACTED, "distribution":"PerSeries", "projection": ["ts", "greptime_value", "__tsid", "host", "job"], "filters": ["__table_id=UInt32(REDACTED)", "ts >= TimestampMillisecond(-299999, None)", "ts <= TimestampMillisecond(5000, None)"], "time_range":REDACTED +|_|_|_SeriesScan: region=REDACTED, "partition_count":REDACTED, "distribution":"PerSeries", "projection": ["ts", "greptime_value", "__tsid"], "filters": ["__table_id=UInt32(REDACTED)", "ts >= TimestampMillisecond(-299999, None)", "ts <= TimestampMillisecond(5000, None)"], "time_range":REDACTED |_|_|_| |_|_| Total rows: 4_| +-+-+-+ @@ -257,26 +253,26 @@ TQL ANALYZE (0, 5, '5s') tsid_binary_join_left / ignoring(host) tsid_binary_join |_|_|_WindowAggExec: wdw=[__promql_match_group_count: Ok(Field { name: "__promql_match_group_count", data_type: Int64 }), frame: WindowFrame { units: Rows, start_bound: Preceding(UInt64(NULL)), end_bound: Following(UInt64(NULL)), is_causal: false }] REDACTED |_|_|_HashJoinExec: mode=Partitioned, join_type=Inner, on=[(job@1, job@1), (ts@2, ts@2)], projection=[greptime_value@0, job@1, ts@2, greptime_value@3, ts@5], NullsEqual: true REDACTED |_|_|_RepartitionExec: partitioning=Hash([job@1, ts@2],REDACTED -|_|_|_ProjectionExec: expr=[greptime_value@0 as greptime_value, job@2 as job, ts@4 as ts] REDACTED |_|_|_MergeScanExec: REDACTED |_|_|_FilterExec: prom_assert_unique_match_group(__promql_match_group_count@3, job@1), projection=[greptime_value@0, job@1, ts@2] REDACTED |_|_|_WindowAggExec: wdw=[__promql_match_group_count: Ok(Field { name: "__promql_match_group_count", data_type: Int64 }), frame: WindowFrame { units: Rows, start_bound: Preceding(UInt64(NULL)), end_bound: Following(UInt64(NULL)), is_causal: false }] REDACTED |_|_|_SortExec: expr=[job@1 ASC NULLS LAST, ts@2 ASC NULLS LAST], preserve_partitioning=[true] REDACTED |_|_|_RepartitionExec: partitioning=Hash([job@1, ts@2],REDACTED -|_|_|_ProjectionExec: expr=[greptime_value@0 as greptime_value, job@2 as job, ts@4 as ts] REDACTED |_|_|_MergeScanExec: REDACTED |_|_|_| -| 1_| 0_|_PromInstantManipulateExec: range=[0..5000], lookback=[300000], interval=[5000], time index=[ts] REDACTED +| 1_| 0_|_ProjectionExec: expr=[greptime_value@0 as greptime_value, job@1 as job, ts@3 as ts] REDACTED +|_|_|_PromInstantManipulateExec: range=[0..5000], lookback=[300000], interval=[5000], time index=[ts] REDACTED |_|_|_PromSeriesDivideExec: tags=["__tsid"] REDACTED -|_|_|_ProjectionExec: expr=[greptime_value@1 as greptime_value, host@3 as host, job@4 as job, __tsid@2 as __tsid, ts@0 as ts] REDACTED +|_|_|_ProjectionExec: expr=[greptime_value@1 as greptime_value, job@3 as job, __tsid@2 as __tsid, ts@0 as ts] REDACTED |_|_|_CooperativeExec REDACTED -|_|_|_SeriesScan: region=REDACTED, "partition_count":REDACTED, "distribution":"PerSeries", "projection": ["ts", "greptime_value", "__tsid", "host", "job"], "filters": ["__table_id=UInt32(REDACTED)", "ts >= TimestampMillisecond(-299999, None)", "ts <= TimestampMillisecond(5000, None)"], "time_range":REDACTED +|_|_|_SeriesScan: region=REDACTED, "partition_count":REDACTED, "distribution":"PerSeries", "projection": ["ts", "greptime_value", "__tsid", "job"], "filters": ["__table_id=UInt32(REDACTED)", "ts >= TimestampMillisecond(-299999, None)", "ts <= TimestampMillisecond(5000, None)"], "time_range":REDACTED |_|_|_| -| 1_| 0_|_PromInstantManipulateExec: range=[0..5000], lookback=[300000], interval=[5000], time index=[ts] REDACTED +| 1_| 0_|_ProjectionExec: expr=[greptime_value@0 as greptime_value, job@1 as job, ts@3 as ts] REDACTED +|_|_|_PromInstantManipulateExec: range=[0..5000], lookback=[300000], interval=[5000], time index=[ts] REDACTED |_|_|_PromSeriesDivideExec: tags=["__tsid"] REDACTED -|_|_|_ProjectionExec: expr=[greptime_value@1 as greptime_value, host@3 as host, job@4 as job, __tsid@2 as __tsid, ts@0 as ts] REDACTED +|_|_|_ProjectionExec: expr=[greptime_value@1 as greptime_value, job@3 as job, __tsid@2 as __tsid, ts@0 as ts] REDACTED |_|_|_CooperativeExec REDACTED -|_|_|_SeriesScan: region=REDACTED, "partition_count":REDACTED, "distribution":"PerSeries", "projection": ["ts", "greptime_value", "__tsid", "host", "job"], "filters": ["__table_id=UInt32(REDACTED)", "ts >= TimestampMillisecond(-299999, None)", "ts <= TimestampMillisecond(5000, None)"], "time_range":REDACTED +|_|_|_SeriesScan: region=REDACTED, "partition_count":REDACTED, "distribution":"PerSeries", "projection": ["ts", "greptime_value", "__tsid", "job"], "filters": ["__table_id=UInt32(REDACTED)", "ts >= TimestampMillisecond(-299999, None)", "ts <= TimestampMillisecond(5000, None)"], "time_range":REDACTED |_|_|_| |_|_| Total rows: 4_| +-+-+-+ @@ -308,19 +304,19 @@ TQL ANALYZE (0, 5, '5s') tsid_binary_join_left / on(job) tsid_binary_join_right_ |_|_|_CoalescePartitionsExec REDACTED |_|_|_HashJoinExec: mode=Partitioned, join_type=Inner, on=[(job@1, job@1), (ts@2, ts@2)], projection=[greptime_value@0, job@1, ts@2, greptime_value@3, ts@5], NullsEqual: true REDACTED |_|_|_RepartitionExec: partitioning=Hash([job@1, ts@2],REDACTED -|_|_|_ProjectionExec: expr=[greptime_value@0 as greptime_value, job@2 as job, ts@4 as ts] REDACTED |_|_|_MergeScanExec: REDACTED |_|_|_RepartitionExec: partitioning=Hash([job@1, ts@2],REDACTED -|_|_|_ProjectionExec: expr=[greptime_value@0 as greptime_value, job@1 as job, ts@3 as ts] REDACTED |_|_|_MergeScanExec: REDACTED |_|_|_| -| 1_| 0_|_PromInstantManipulateExec: range=[0..5000], lookback=[300000], interval=[5000], time index=[ts] REDACTED +| 1_| 0_|_ProjectionExec: expr=[greptime_value@0 as greptime_value, job@1 as job, ts@3 as ts] REDACTED +|_|_|_PromInstantManipulateExec: range=[0..5000], lookback=[300000], interval=[5000], time index=[ts] REDACTED |_|_|_PromSeriesDivideExec: tags=["__tsid"] REDACTED -|_|_|_ProjectionExec: expr=[greptime_value@1 as greptime_value, host@3 as host, job@4 as job, __tsid@2 as __tsid, ts@0 as ts] REDACTED +|_|_|_ProjectionExec: expr=[greptime_value@1 as greptime_value, job@3 as job, __tsid@2 as __tsid, ts@0 as ts] REDACTED |_|_|_CooperativeExec REDACTED -|_|_|_SeriesScan: region=REDACTED, "partition_count":REDACTED, "distribution":"PerSeries", "projection": ["ts", "greptime_value", "__tsid", "host", "job"], "filters": ["__table_id=UInt32(REDACTED)", "ts >= TimestampMillisecond(-299999, None)", "ts <= TimestampMillisecond(5000, None)"], "time_range":REDACTED +|_|_|_SeriesScan: region=REDACTED, "partition_count":REDACTED, "distribution":"PerSeries", "projection": ["ts", "greptime_value", "__tsid", "job"], "filters": ["__table_id=UInt32(REDACTED)", "ts >= TimestampMillisecond(-299999, None)", "ts <= TimestampMillisecond(5000, None)"], "time_range":REDACTED |_|_|_| -| 1_| 0_|_PromInstantManipulateExec: range=[0..5000], lookback=[300000], interval=[5000], time index=[ts] REDACTED +| 1_| 0_|_ProjectionExec: expr=[greptime_value@0 as greptime_value, job@1 as job, ts@3 as ts] REDACTED +|_|_|_PromInstantManipulateExec: range=[0..5000], lookback=[300000], interval=[5000], time index=[ts] REDACTED |_|_|_PromSeriesDivideExec: tags=["__tsid"] REDACTED |_|_|_ProjectionExec: expr=[greptime_value@1 as greptime_value, job@3 as job, __tsid@2 as __tsid, ts@0 as ts] REDACTED |_|_|_CooperativeExec REDACTED @@ -352,7 +348,6 @@ TQL ANALYZE (0, 5, '5s') tsid_binary_join_left > tsid_binary_join_right; |_|_|_RepartitionExec: partitioning=Hash([__tsid@3, ts@4],REDACTED |_|_|_MergeScanExec: REDACTED |_|_|_RepartitionExec: partitioning=Hash([__tsid@1, ts@2],REDACTED -|_|_|_ProjectionExec: expr=[greptime_value@0 as greptime_value, __tsid@3 as __tsid, ts@4 as ts] REDACTED |_|_|_MergeScanExec: REDACTED |_|_|_| | 1_| 0_|_PromInstantManipulateExec: range=[0..5000], lookback=[300000], interval=[5000], time index=[ts] REDACTED @@ -363,9 +358,9 @@ TQL ANALYZE (0, 5, '5s') tsid_binary_join_left > tsid_binary_join_right; |_|_|_| | 1_| 0_|_PromInstantManipulateExec: range=[0..5000], lookback=[300000], interval=[5000], time index=[ts] REDACTED |_|_|_PromSeriesDivideExec: tags=["__tsid"] REDACTED -|_|_|_ProjectionExec: expr=[greptime_value@1 as greptime_value, host@3 as host, job@4 as job, __tsid@2 as __tsid, ts@0 as ts] REDACTED +|_|_|_ProjectionExec: expr=[greptime_value@1 as greptime_value, __tsid@2 as __tsid, ts@0 as ts] REDACTED |_|_|_CooperativeExec REDACTED -|_|_|_SeriesScan: region=REDACTED, "partition_count":REDACTED, "distribution":"PerSeries", "projection": ["ts", "greptime_value", "__tsid", "host", "job"], "filters": ["__table_id=UInt32(REDACTED)", "ts >= TimestampMillisecond(-299999, None)", "ts <= TimestampMillisecond(5000, None)"], "time_range":REDACTED +|_|_|_SeriesScan: region=REDACTED, "partition_count":REDACTED, "distribution":"PerSeries", "projection": ["ts", "greptime_value", "__tsid"], "filters": ["__table_id=UInt32(REDACTED)", "ts >= TimestampMillisecond(-299999, None)", "ts <= TimestampMillisecond(5000, None)"], "time_range":REDACTED |_|_|_| |_|_| Total rows: 4_| +-+-+-+ @@ -390,7 +385,6 @@ TQL ANALYZE (0, 5, '5s') tsid_binary_join_left > bool tsid_binary_join_right; +-+-+-+ | 0_| 0_|_ProjectionExec: expr=[host@0 as host, job@1 as job, ts@2 as ts, __tsid@3 as __tsid, CAST(prom_gt(greptime_value@4, greptime_value@5) AS Float64) as tsid_binary_join_left.greptime_value > tsid_binary_join_right.greptime_value] REDACTED |_|_|_HashJoinExec: mode=CollectLeft, join_type=Inner, on=[(__tsid@1, __tsid@3), (ts@2, ts@4)], projection=[host@4, job@5, ts@7, __tsid@6, greptime_value@0, greptime_value@3], NullsEqual: true REDACTED -|_|_|_ProjectionExec: expr=[greptime_value@0 as greptime_value, __tsid@3 as __tsid, ts@4 as ts] REDACTED |_|_|_CooperativeExec REDACTED |_|_|_MergeScanExec: REDACTED |_|_|_RepartitionExec: partitioning=REDACTED @@ -398,9 +392,9 @@ TQL ANALYZE (0, 5, '5s') tsid_binary_join_left > bool tsid_binary_join_right; |_|_|_| | 1_| 0_|_PromInstantManipulateExec: range=[0..5000], lookback=[300000], interval=[5000], time index=[ts] REDACTED |_|_|_PromSeriesDivideExec: tags=["__tsid"] REDACTED -|_|_|_ProjectionExec: expr=[greptime_value@1 as greptime_value, host@3 as host, job@4 as job, __tsid@2 as __tsid, ts@0 as ts] REDACTED +|_|_|_ProjectionExec: expr=[greptime_value@1 as greptime_value, __tsid@2 as __tsid, ts@0 as ts] REDACTED |_|_|_CooperativeExec REDACTED -|_|_|_SeriesScan: region=REDACTED, "partition_count":REDACTED, "distribution":"PerSeries", "projection": ["ts", "greptime_value", "__tsid", "host", "job"], "filters": ["__table_id=UInt32(REDACTED)", "ts >= TimestampMillisecond(-299999, None)", "ts <= TimestampMillisecond(5000, None)"], "time_range":REDACTED +|_|_|_SeriesScan: region=REDACTED, "partition_count":REDACTED, "distribution":"PerSeries", "projection": ["ts", "greptime_value", "__tsid"], "filters": ["__table_id=UInt32(REDACTED)", "ts >= TimestampMillisecond(-299999, None)", "ts <= TimestampMillisecond(5000, None)"], "time_range":REDACTED |_|_|_| | 1_| 0_|_PromInstantManipulateExec: range=[0..5000], lookback=[300000], interval=[5000], time index=[ts] REDACTED |_|_|_PromSeriesDivideExec: tags=["__tsid"] REDACTED @@ -434,25 +428,23 @@ TQL ANALYZE (0, 5, '5s') ((tsid_binary_join_left > tsid_binary_join_right) / tsi |_|_|_CoalescePartitionsExec REDACTED |_|_|_HashJoinExec: mode=Partitioned, join_type=Inner, on=[(__tsid@1, __tsid@1), (ts@2, ts@2)], filter=prom_gt(greptime_value@0, greptime_value@1), projection=[ts@2, greptime_value@0, __tsid@1], NullsEqual: true REDACTED |_|_|_RepartitionExec: partitioning=Hash([REDACTED -|_|_|_ProjectionExec: expr=[greptime_value@0 as greptime_value, __tsid@3 as __tsid, ts@4 as ts] REDACTED |_|_|_MergeScanExec: REDACTED |_|_|_RepartitionExec: partitioning=Hash([REDACTED -|_|_|_ProjectionExec: expr=[greptime_value@0 as greptime_value, __tsid@3 as __tsid, ts@4 as ts] REDACTED |_|_|_MergeScanExec: REDACTED |_|_|_RepartitionExec: partitioning=REDACTED |_|_|_MergeScanExec: REDACTED |_|_|_| | 1_| 0_|_PromInstantManipulateExec: range=[0..5000], lookback=[300000], interval=[5000], time index=[ts] REDACTED |_|_|_PromSeriesDivideExec: tags=["__tsid"] REDACTED -|_|_|_ProjectionExec: expr=[greptime_value@1 as greptime_value, host@3 as host, job@4 as job, __tsid@2 as __tsid, ts@0 as ts] REDACTED +|_|_|_ProjectionExec: expr=[greptime_value@1 as greptime_value, __tsid@2 as __tsid, ts@0 as ts] REDACTED |_|_|_CooperativeExec REDACTED -|_|_|_SeriesScan: region=REDACTED, "partition_count":REDACTED, "distribution":"PerSeries", "projection": ["ts", "greptime_value", "__tsid", "host", "job"], "filters": ["__table_id=UInt32(REDACTED)", "ts >= TimestampMillisecond(-299999, None)", "ts <= TimestampMillisecond(5000, None)"], "time_range":REDACTED +|_|_|_SeriesScan: region=REDACTED, "partition_count":REDACTED, "distribution":"PerSeries", "projection": ["ts", "greptime_value", "__tsid"], "filters": ["__table_id=UInt32(REDACTED)", "ts >= TimestampMillisecond(-299999, None)", "ts <= TimestampMillisecond(5000, None)"], "time_range":REDACTED |_|_|_| | 1_| 0_|_PromInstantManipulateExec: range=[0..5000], lookback=[300000], interval=[5000], time index=[ts] REDACTED |_|_|_PromSeriesDivideExec: tags=["__tsid"] REDACTED -|_|_|_ProjectionExec: expr=[greptime_value@1 as greptime_value, host@3 as host, job@4 as job, __tsid@2 as __tsid, ts@0 as ts] REDACTED +|_|_|_ProjectionExec: expr=[greptime_value@1 as greptime_value, __tsid@2 as __tsid, ts@0 as ts] REDACTED |_|_|_CooperativeExec REDACTED -|_|_|_SeriesScan: region=REDACTED, "partition_count":REDACTED, "distribution":"PerSeries", "projection": ["ts", "greptime_value", "__tsid", "host", "job"], "filters": ["__table_id=UInt32(REDACTED)", "ts >= TimestampMillisecond(-299999, None)", "ts <= TimestampMillisecond(5000, None)"], "time_range":REDACTED +|_|_|_SeriesScan: region=REDACTED, "partition_count":REDACTED, "distribution":"PerSeries", "projection": ["ts", "greptime_value", "__tsid"], "filters": ["__table_id=UInt32(REDACTED)", "ts >= TimestampMillisecond(-299999, None)", "ts <= TimestampMillisecond(5000, None)"], "time_range":REDACTED |_|_|_| | 1_| 0_|_PromInstantManipulateExec: range=[0..5000], lookback=[300000], interval=[5000], time index=[ts] REDACTED |_|_|_PromSeriesDivideExec: tags=["__tsid"] REDACTED @@ -488,34 +480,31 @@ TQL ANALYZE (0, 5, '5s') ((tsid_binary_join_left > bool tsid_binary_join_right) |_|_|_ProjectionExec: expr=[ts@0 as ts, __tsid@1 as __tsid, CAST(prom_gt(greptime_value@2, greptime_value@3) AS Float64) as tsid_binary_join_left.greptime_value > tsid_binary_join_right.greptime_value] REDACTED |_|_|_HashJoinExec: mode=Partitioned, join_type=Inner, on=[(__tsid@1, __tsid@1), (ts@2, ts@2)], projection=[ts@5, __tsid@4, greptime_value@0, greptime_value@3], NullsEqual: true REDACTED |_|_|_RepartitionExec: partitioning=Hash([REDACTED -|_|_|_ProjectionExec: expr=[greptime_value@0 as greptime_value, __tsid@3 as __tsid, ts@4 as ts] REDACTED |_|_|_MergeScanExec: REDACTED |_|_|_RepartitionExec: partitioning=Hash([REDACTED -|_|_|_ProjectionExec: expr=[greptime_value@0 as greptime_value, __tsid@3 as __tsid, ts@4 as ts] REDACTED |_|_|_MergeScanExec: REDACTED |_|_|_RepartitionExec: partitioning=Hash([REDACTED -|_|_|_ProjectionExec: expr=[greptime_value@0 as greptime_value, __tsid@3 as __tsid, ts@4 as ts] REDACTED |_|_|_MergeScanExec: REDACTED |_|_|_RepartitionExec: partitioning=REDACTED |_|_|_MergeScanExec: REDACTED |_|_|_| | 1_| 0_|_PromInstantManipulateExec: range=[0..5000], lookback=[300000], interval=[5000], time index=[ts] REDACTED |_|_|_PromSeriesDivideExec: tags=["__tsid"] REDACTED -|_|_|_ProjectionExec: expr=[greptime_value@1 as greptime_value, host@3 as host, job@4 as job, __tsid@2 as __tsid, ts@0 as ts] REDACTED +|_|_|_ProjectionExec: expr=[greptime_value@1 as greptime_value, __tsid@2 as __tsid, ts@0 as ts] REDACTED |_|_|_CooperativeExec REDACTED -|_|_|_SeriesScan: region=REDACTED, "partition_count":REDACTED, "distribution":"PerSeries", "projection": ["ts", "greptime_value", "__tsid", "host", "job"], "filters": ["__table_id=UInt32(REDACTED)", "ts >= TimestampMillisecond(-299999, None)", "ts <= TimestampMillisecond(5000, None)"], "time_range":REDACTED +|_|_|_SeriesScan: region=REDACTED, "partition_count":REDACTED, "distribution":"PerSeries", "projection": ["ts", "greptime_value", "__tsid"], "filters": ["__table_id=UInt32(REDACTED)", "ts >= TimestampMillisecond(-299999, None)", "ts <= TimestampMillisecond(5000, None)"], "time_range":REDACTED |_|_|_| | 1_| 0_|_PromInstantManipulateExec: range=[0..5000], lookback=[300000], interval=[5000], time index=[ts] REDACTED |_|_|_PromSeriesDivideExec: tags=["__tsid"] REDACTED -|_|_|_ProjectionExec: expr=[greptime_value@1 as greptime_value, host@3 as host, job@4 as job, __tsid@2 as __tsid, ts@0 as ts] REDACTED +|_|_|_ProjectionExec: expr=[greptime_value@1 as greptime_value, __tsid@2 as __tsid, ts@0 as ts] REDACTED |_|_|_CooperativeExec REDACTED -|_|_|_SeriesScan: region=REDACTED, "partition_count":REDACTED, "distribution":"PerSeries", "projection": ["ts", "greptime_value", "__tsid", "host", "job"], "filters": ["__table_id=UInt32(REDACTED)", "ts >= TimestampMillisecond(-299999, None)", "ts <= TimestampMillisecond(5000, None)"], "time_range":REDACTED +|_|_|_SeriesScan: region=REDACTED, "partition_count":REDACTED, "distribution":"PerSeries", "projection": ["ts", "greptime_value", "__tsid"], "filters": ["__table_id=UInt32(REDACTED)", "ts >= TimestampMillisecond(-299999, None)", "ts <= TimestampMillisecond(5000, None)"], "time_range":REDACTED |_|_|_| | 1_| 0_|_PromInstantManipulateExec: range=[0..5000], lookback=[300000], interval=[5000], time index=[ts] REDACTED |_|_|_PromSeriesDivideExec: tags=["__tsid"] REDACTED -|_|_|_ProjectionExec: expr=[greptime_value@1 as greptime_value, host@3 as host, job@4 as job, __tsid@2 as __tsid, ts@0 as ts] REDACTED +|_|_|_ProjectionExec: expr=[greptime_value@1 as greptime_value, __tsid@2 as __tsid, ts@0 as ts] REDACTED |_|_|_CooperativeExec REDACTED -|_|_|_SeriesScan: region=REDACTED, "partition_count":REDACTED, "distribution":"PerSeries", "projection": ["ts", "greptime_value", "__tsid", "host", "job"], "filters": ["__table_id=UInt32(REDACTED)", "ts >= TimestampMillisecond(-299999, None)", "ts <= TimestampMillisecond(5000, None)"], "time_range":REDACTED +|_|_|_SeriesScan: region=REDACTED, "partition_count":REDACTED, "distribution":"PerSeries", "projection": ["ts", "greptime_value", "__tsid"], "filters": ["__table_id=UInt32(REDACTED)", "ts >= TimestampMillisecond(-299999, None)", "ts <= TimestampMillisecond(5000, None)"], "time_range":REDACTED |_|_|_| | 1_| 0_|_PromInstantManipulateExec: range=[0..5000], lookback=[300000], interval=[5000], time index=[ts] REDACTED |_|_|_PromSeriesDivideExec: tags=["__tsid"] REDACTED @@ -604,28 +593,27 @@ TQL ANALYZE (0, 5, '5s') (tsid_binary_join_left / ignoring(host) group_left tsid |_|_|_ProjectionExec: expr=[ts@0 as ts, __tsid@1 as __tsid, greptime_value@2 / greptime_value@3 as tsid_binary_join_left.greptime_value / tsid_binary_join_right.greptime_value] REDACTED |_|_|_HashJoinExec: mode=Partitioned, join_type=Inner, on=[(job@1, job@1), (ts@3, ts@2)], projection=[ts@6, __tsid@2, greptime_value@0, greptime_value@4], NullsEqual: true REDACTED |_|_|_RepartitionExec: partitioning=Hash([REDACTED -|_|_|_ProjectionExec: expr=[greptime_value@0 as greptime_value, job@2 as job, __tsid@3 as __tsid, ts@4 as ts] REDACTED |_|_|_MergeScanExec: REDACTED |_|_|_FilterExec: prom_assert_unique_match_group(__promql_match_group_count@3, job@1), projection=[greptime_value@0, job@1, ts@2] REDACTED |_|_|_WindowAggExec: wdw=[__promql_match_group_count: Ok(Field { name: "__promql_match_group_count", data_type: Int64 }), frame: WindowFrame { units: Rows, start_bound: Preceding(UInt64(NULL)), end_bound: Following(UInt64(NULL)), is_causal: false }] REDACTED |_|_|_SortExec: expr=[job@1 ASC NULLS LAST, ts@2 ASC NULLS LAST], preserve_partitioning=[true] REDACTED |_|_|_RepartitionExec: partitioning=Hash([REDACTED -|_|_|_ProjectionExec: expr=[greptime_value@0 as greptime_value, job@2 as job, ts@4 as ts] REDACTED |_|_|_MergeScanExec: REDACTED |_|_|_RepartitionExec: partitioning=REDACTED |_|_|_MergeScanExec: REDACTED |_|_|_| | 1_| 0_|_PromInstantManipulateExec: range=[0..5000], lookback=[300000], interval=[5000], time index=[ts] REDACTED |_|_|_PromSeriesDivideExec: tags=["__tsid"] REDACTED -|_|_|_ProjectionExec: expr=[greptime_value@1 as greptime_value, host@3 as host, job@4 as job, __tsid@2 as __tsid, ts@0 as ts] REDACTED +|_|_|_ProjectionExec: expr=[greptime_value@1 as greptime_value, job@3 as job, __tsid@2 as __tsid, ts@0 as ts] REDACTED |_|_|_CooperativeExec REDACTED -|_|_|_SeriesScan: region=REDACTED, "partition_count":REDACTED, "distribution":"PerSeries", "projection": ["ts", "greptime_value", "__tsid", "host", "job"], "filters": ["__table_id=UInt32(REDACTED)", "ts >= TimestampMillisecond(-299999, None)", "ts <= TimestampMillisecond(5000, None)"], "time_range":REDACTED +|_|_|_SeriesScan: region=REDACTED, "partition_count":REDACTED, "distribution":"PerSeries", "projection": ["ts", "greptime_value", "__tsid", "job"], "filters": ["__table_id=UInt32(REDACTED)", "ts >= TimestampMillisecond(-299999, None)", "ts <= TimestampMillisecond(5000, None)"], "time_range":REDACTED |_|_|_| -| 1_| 0_|_PromInstantManipulateExec: range=[0..5000], lookback=[300000], interval=[5000], time index=[ts] REDACTED +| 1_| 0_|_ProjectionExec: expr=[greptime_value@0 as greptime_value, job@1 as job, ts@3 as ts] REDACTED +|_|_|_PromInstantManipulateExec: range=[0..5000], lookback=[300000], interval=[5000], time index=[ts] REDACTED |_|_|_PromSeriesDivideExec: tags=["__tsid"] REDACTED -|_|_|_ProjectionExec: expr=[greptime_value@1 as greptime_value, host@3 as host, job@4 as job, __tsid@2 as __tsid, ts@0 as ts] REDACTED +|_|_|_ProjectionExec: expr=[greptime_value@1 as greptime_value, job@3 as job, __tsid@2 as __tsid, ts@0 as ts] REDACTED |_|_|_CooperativeExec REDACTED -|_|_|_SeriesScan: region=REDACTED, "partition_count":REDACTED, "distribution":"PerSeries", "projection": ["ts", "greptime_value", "__tsid", "host", "job"], "filters": ["__table_id=UInt32(REDACTED)", "ts >= TimestampMillisecond(-299999, None)", "ts <= TimestampMillisecond(5000, None)"], "time_range":REDACTED +|_|_|_SeriesScan: region=REDACTED, "partition_count":REDACTED, "distribution":"PerSeries", "projection": ["ts", "greptime_value", "__tsid", "job"], "filters": ["__table_id=UInt32(REDACTED)", "ts >= TimestampMillisecond(-299999, None)", "ts <= TimestampMillisecond(5000, None)"], "time_range":REDACTED |_|_|_| | 1_| 0_|_PromInstantManipulateExec: range=[0..5000], lookback=[300000], interval=[5000], time index=[ts] REDACTED |_|_|_PromSeriesDivideExec: tags=["__tsid"] REDACTED diff --git a/tests/cases/standalone/common/show/show_databases_tables.result b/tests/cases/standalone/common/show/show_databases_tables.result index d9eaaaa3cfe..05481af85af 100644 --- a/tests/cases/standalone/common/show/show_databases_tables.result +++ b/tests/cases/standalone/common/show/show_databases_tables.result @@ -36,6 +36,7 @@ SHOW TABLES; | column_privileges | | column_statistics | | columns | +| compaction_tasks | | engines | | events | | files | @@ -93,6 +94,7 @@ SHOW FULL TABLES; | column_privileges | LOCAL TEMPORARY | | column_statistics | LOCAL TEMPORARY | | columns | LOCAL TEMPORARY | +| compaction_tasks | LOCAL TEMPORARY | | engines | LOCAL TEMPORARY | | events | LOCAL TEMPORARY | | files | LOCAL TEMPORARY | @@ -144,6 +146,7 @@ SHOW TABLE STATUS; |column_privileges||11|Fixed|0|0|0|0|0|0|0|DATETIME|DATETIME||utf8_bin|0|greptime.semantic.table_scope=global|| |column_statistics||11|Fixed|0|0|0|0|0|0|0|DATETIME|DATETIME||utf8_bin|0|greptime.semantic.table_scope=global|| |columns||11|Fixed|0|0|0|0|0|0|0|DATETIME|DATETIME||utf8_bin|0|greptime.semantic.table_scope=catalog|| +|compaction_tasks||11|Fixed|0|0|0|0|0|0|0|DATETIME|DATETIME||utf8_bin|0|greptime.semantic.table_scope=global|| |engines||11|Fixed|0|0|0|0|0|0|0|DATETIME|DATETIME||utf8_bin|0|greptime.semantic.table_scope=public_global|| |events||11|Fixed|0|0|0|0|0|0|0|DATETIME|DATETIME||utf8_bin|0|greptime.semantic.table_scope=global|| |files||11|Fixed|0|0|0|0|0|0|0|DATETIME|DATETIME||utf8_bin|0|greptime.semantic.table_scope=global|| diff --git a/tests/cases/standalone/common/system/information_schema.result b/tests/cases/standalone/common/system/information_schema.result index 8fb02828fea..f39b4d53cbd 100644 --- a/tests/cases/standalone/common/system/information_schema.result +++ b/tests/cases/standalone/common/system/information_schema.result @@ -24,6 +24,7 @@ order by table_schema, table_name; |greptime|information_schema|column_privileges|LOCALTEMPORARY|6|0|0|0|0|0||11|Fixed|0|0|0|DATETIME|DATETIME||utf8_bin|0|greptime.semantic.table_scope=global||Y| |greptime|information_schema|column_statistics|LOCALTEMPORARY|7|0|0|0|0|0||11|Fixed|0|0|0|DATETIME|DATETIME||utf8_bin|0|greptime.semantic.table_scope=global||Y| |greptime|information_schema|columns|LOCALTEMPORARY|4|0|0|0|0|0||11|Fixed|0|0|0|DATETIME|DATETIME||utf8_bin|0|greptime.semantic.table_scope=catalog||Y| +|greptime|information_schema|compaction_tasks|LOCALTEMPORARY|50|0|0|0|0|0||11|Fixed|0|0|0|DATETIME|DATETIME||utf8_bin|0|greptime.semantic.table_scope=global||Y| |greptime|information_schema|engines|LOCALTEMPORARY|5|0|0|0|0|0||11|Fixed|0|0|0|DATETIME|DATETIME||utf8_bin|0|greptime.semantic.table_scope=public_global||Y| |greptime|information_schema|events|LOCALTEMPORARY|13|0|0|0|0|0||11|Fixed|0|0|0|DATETIME|DATETIME||utf8_bin|0|greptime.semantic.table_scope=global||Y| |greptime|information_schema|files|LOCALTEMPORARY|14|0|0|0|0|0||11|Fixed|0|0|0|DATETIME|DATETIME||utf8_bin|0|greptime.semantic.table_scope=global||Y| @@ -138,6 +139,25 @@ order by table_schema, table_name, column_name; | greptime | information_schema | columns | table_catalog | 1 | 2147483647 | 2147483647 | | | | utf8 | utf8_bin | | | select,insert | | String | string | FIELD | | NO | string | | | | greptime | information_schema | columns | table_name | 3 | 2147483647 | 2147483647 | | | | utf8 | utf8_bin | | | select,insert | | String | string | FIELD | | NO | string | | | | greptime | information_schema | columns | table_schema | 2 | 2147483647 | 2147483647 | | | | utf8 | utf8_bin | | | select,insert | | String | string | FIELD | | NO | string | | | +| greptime | information_schema | compaction_tasks | completed_units | 13 | | | 20 | 0 | | | | | | select,insert | | UInt64 | bigint unsigned | FIELD | | YES | bigint unsigned | | | +| greptime | information_schema | compaction_tasks | effective_options | 15 | 2147483647 | 2147483647 | | | | utf8 | utf8_bin | | | select,insert | | String | string | FIELD | | YES | string | | | +| greptime | information_schema | compaction_tasks | elapsed_millis | 9 | | | 20 | 0 | | | | | | select,insert | | UInt64 | bigint unsigned | FIELD | | NO | bigint unsigned | | | +| greptime | information_schema | compaction_tasks | input_bytes | 11 | | | 20 | 0 | | | | | | select,insert | | UInt64 | bigint unsigned | FIELD | | YES | bigint unsigned | | | +| greptime | information_schema | compaction_tasks | input_files | 10 | | | 20 | 0 | | | | | | select,insert | | UInt64 | bigint unsigned | FIELD | | YES | bigint unsigned | | | +| greptime | information_schema | compaction_tasks | input_time_end | 17 | | | | | 9 | | | | | select,insert | | TimestampNanosecond | timestamp(9) | FIELD | | YES | timestamp(9) | | | +| greptime | information_schema | compaction_tasks | input_time_start | 16 | | | | | 9 | | | | | select,insert | | TimestampNanosecond | timestamp(9) | FIELD | | YES | timestamp(9) | | | +| greptime | information_schema | compaction_tasks | node_id | 4 | | | 20 | 0 | | | | | | select,insert | | UInt64 | bigint unsigned | FIELD | | YES | bigint unsigned | | | +| greptime | information_schema | compaction_tasks | output_time_end | 19 | | | | | 9 | | | | | select,insert | | TimestampNanosecond | timestamp(9) | FIELD | | YES | timestamp(9) | | | +| greptime | information_schema | compaction_tasks | output_time_start | 18 | | | | | 9 | | | | | select,insert | | TimestampNanosecond | timestamp(9) | FIELD | | YES | timestamp(9) | | | +| greptime | information_schema | compaction_tasks | phase | 7 | 2147483647 | 2147483647 | | | | utf8 | utf8_bin | | | select,insert | | String | string | FIELD | | NO | string | | | +| greptime | information_schema | compaction_tasks | region_id | 2 | | | 20 | 0 | | | | | | select,insert | | UInt64 | bigint unsigned | FIELD | | NO | bigint unsigned | | | +| greptime | information_schema | compaction_tasks | request_options | 14 | 2147483647 | 2147483647 | | | | utf8 | utf8_bin | | | select,insert | | String | string | FIELD | | NO | string | | | +| greptime | information_schema | compaction_tasks | state | 6 | 2147483647 | 2147483647 | | | | utf8 | utf8_bin | | | select,insert | | String | string | FIELD | | NO | string | | | +| greptime | information_schema | compaction_tasks | submitted_at | 8 | | | | | 3 | | | | | select,insert | | TimestampMillisecond | timestamp(3) | FIELD | | NO | timestamp(3) | | | +| greptime | information_schema | compaction_tasks | table_id | 3 | | | 10 | 0 | | | | | | select,insert | | UInt32 | int unsigned | FIELD | | NO | int unsigned | | | +| greptime | information_schema | compaction_tasks | task_id | 1 | 2147483647 | 2147483647 | | | | utf8 | utf8_bin | | | select,insert | | String | string | FIELD | | NO | string | | | +| greptime | information_schema | compaction_tasks | total_units | 12 | | | 20 | 0 | | | | | | select,insert | | UInt64 | bigint unsigned | FIELD | | YES | bigint unsigned | | | +| greptime | information_schema | compaction_tasks | trigger_type | 5 | 2147483647 | 2147483647 | | | | utf8 | utf8_bin | | | select,insert | | String | string | FIELD | | NO | string | | | | greptime | information_schema | engines | comment | 3 | 2147483647 | 2147483647 | | | | utf8 | utf8_bin | | | select,insert | | String | string | FIELD | | NO | string | | | | greptime | information_schema | engines | engine | 1 | 2147483647 | 2147483647 | | | | utf8 | utf8_bin | | | select,insert | | String | string | FIELD | | NO | string | | | | greptime | information_schema | engines | savepoints | 6 | 2147483647 | 2147483647 | | | | utf8 | utf8_bin | | | select,insert | | String | string | FIELD | | NO | string | | | diff --git a/tests/cases/standalone/common/tql-explain-analyze/explain.result b/tests/cases/standalone/common/tql-explain-analyze/explain.result index 3184bb261cc..77870e8f062 100644 --- a/tests/cases/standalone/common/tql-explain-analyze/explain.result +++ b/tests/cases/standalone/common/tql-explain-analyze/explain.result @@ -69,6 +69,8 @@ TQL EXPLAIN ('1970-01-01T00:00:00'::timestamp, '1970-01-01T00:00:00'::timestamp +---------------+---------------------------------------------------------------------------------------------------------------------------------------+ -- explain verbose at 0s, 5s and 10s. No point at 0s. +-- The distributed-only SST analyzer is a no-op for TQL; omit its unchanged-plan row. +-- SQLNESS REPLACE (?m)^\|\s*logical_plan\s+after\s+sst_manifest_aggregate\s*\|\s*SAME\s+TEXT\s+AS\s+ABOVE\s*\|\n -- SQLNESS REPLACE (-+) - -- SQLNESS REPLACE (\s\s+) _ -- SQLNESS REPLACE (elapsed_compute.*) REDACTED @@ -136,6 +138,7 @@ TQL EXPLAIN VERBOSE (0, 10, '5s') test; |_|_Filter: test.j >= TimestampMillisecond(-299999, None) AND test.j <= TimestampMillisecond(10000, None)_| |_|_TableScan: test, partial_filters=[test.j >= TimestampMillisecond(-299999, None), test.j <= TimestampMillisecond(10000, None)] | |_| ]]_| +| logical_plan after merge_scan_projection_| SAME TEXT AS ABOVE_| | logical_plan after ScanHintRule_| SAME TEXT AS ABOVE_| | logical_plan after JsonTypeConcretizeRule_| SAME TEXT AS ABOVE_| | logical_plan after rewrite_set_comparison_| SAME TEXT AS ABOVE_| @@ -164,6 +167,7 @@ TQL EXPLAIN VERBOSE (0, 10, '5s') test; | logical_plan after extract_leaf_expressions_| SAME TEXT AS ABOVE_| | logical_plan after push_down_leaf_projections_| SAME TEXT AS ABOVE_| | logical_plan after optimize_projections_| SAME TEXT AS ABOVE_| +| logical_plan after merge_scan_projection_| SAME TEXT AS ABOVE_| | logical_plan after ScanHintRule_| SAME TEXT AS ABOVE_| | logical_plan after JsonTypeConcretizeRule_| SAME TEXT AS ABOVE_| | logical_plan_| MergeScan [is_placeholder=false, remote_input=[_| @@ -224,6 +228,7 @@ TQL EXPLAIN VERBOSE (0, 10, '5s') test; +-+-+ -- explain verbose at 0s, 5s and 10s. No point at 0s. +-- SQLNESS REPLACE (?m)^\|\s*logical_plan\s+after\s+sst_manifest_aggregate\s*\|\s*SAME\s+TEXT\s+AS\s+ABOVE\s*\|\n -- SQLNESS REPLACE (-+) - -- SQLNESS REPLACE (\s\s+) _ -- SQLNESS REPLACE (elapsed_compute.*) REDACTED @@ -294,6 +299,7 @@ TQL EXPLAIN VERBOSE (0, 10, '5s') test AS series; |_|_Filter: test.j >= TimestampMillisecond(-299999, None) AND test.j <= TimestampMillisecond(10000, None)_| |_|_TableScan: test, partial_filters=[test.j >= TimestampMillisecond(-299999, None), test.j <= TimestampMillisecond(10000, None)] | |_| ]]_| +| logical_plan after merge_scan_projection_| SAME TEXT AS ABOVE_| | logical_plan after ScanHintRule_| SAME TEXT AS ABOVE_| | logical_plan after JsonTypeConcretizeRule_| SAME TEXT AS ABOVE_| | logical_plan after rewrite_set_comparison_| SAME TEXT AS ABOVE_| @@ -322,6 +328,7 @@ TQL EXPLAIN VERBOSE (0, 10, '5s') test AS series; | logical_plan after extract_leaf_expressions_| SAME TEXT AS ABOVE_| | logical_plan after push_down_leaf_projections_| SAME TEXT AS ABOVE_| | logical_plan after optimize_projections_| SAME TEXT AS ABOVE_| +| logical_plan after merge_scan_projection_| SAME TEXT AS ABOVE_| | logical_plan after ScanHintRule_| SAME TEXT AS ABOVE_| | logical_plan after JsonTypeConcretizeRule_| SAME TEXT AS ABOVE_| | logical_plan_| MergeScan [is_placeholder=false, remote_input=[_| @@ -413,6 +420,7 @@ TQL EXPLAIN (0, 10, '5s') test_nano; +---------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------+ -- explain verbose at 0s, 5s and 10s for a nanosecond time index. +-- SQLNESS REPLACE (?m)^\|\s*logical_plan\s+after\s+sst_manifest_aggregate\s*\|\s*SAME\s+TEXT\s+AS\s+ABOVE\s*\|\n -- SQLNESS REPLACE (-+) - -- SQLNESS REPLACE (\s\s+) _ -- SQLNESS REPLACE (elapsed_compute.*) REDACTED @@ -483,6 +491,7 @@ TQL EXPLAIN VERBOSE (0, 10, '5s') test_nano; |_|_Filter: test_nano.j > TimestampNanosecond(-300000000000, None) AND test_nano.j <= TimestampNanosecond(10000000000, None)_| |_|_TableScan: test_nano, partial_filters=[test_nano.j > TimestampNanosecond(-300000000000, None), test_nano.j <= TimestampNanosecond(10000000000, None)] | |_| ]]_| +| logical_plan after merge_scan_projection_| SAME TEXT AS ABOVE_| | logical_plan after ScanHintRule_| SAME TEXT AS ABOVE_| | logical_plan after JsonTypeConcretizeRule_| SAME TEXT AS ABOVE_| | logical_plan after rewrite_set_comparison_| SAME TEXT AS ABOVE_| @@ -511,6 +520,7 @@ TQL EXPLAIN VERBOSE (0, 10, '5s') test_nano; | logical_plan after extract_leaf_expressions_| SAME TEXT AS ABOVE_| | logical_plan after push_down_leaf_projections_| SAME TEXT AS ABOVE_| | logical_plan after optimize_projections_| SAME TEXT AS ABOVE_| +| logical_plan after merge_scan_projection_| SAME TEXT AS ABOVE_| | logical_plan after ScanHintRule_| SAME TEXT AS ABOVE_| | logical_plan after JsonTypeConcretizeRule_| SAME TEXT AS ABOVE_| | logical_plan_| MergeScan [is_placeholder=false, remote_input=[_| diff --git a/tests/cases/standalone/common/tql-explain-analyze/explain.sql b/tests/cases/standalone/common/tql-explain-analyze/explain.sql index 62685b0952e..3748d3302ba 100644 --- a/tests/cases/standalone/common/tql-explain-analyze/explain.sql +++ b/tests/cases/standalone/common/tql-explain-analyze/explain.sql @@ -20,6 +20,8 @@ TQL EXPLAIN (0, 10, '1s', '2s') test; TQL EXPLAIN ('1970-01-01T00:00:00'::timestamp, '1970-01-01T00:00:00'::timestamp + '10 seconds'::interval, '5s') test; -- explain verbose at 0s, 5s and 10s. No point at 0s. +-- The distributed-only SST analyzer is a no-op for TQL; omit its unchanged-plan row. +-- SQLNESS REPLACE (?m)^\|\s*logical_plan\s+after\s+sst_manifest_aggregate\s*\|\s*SAME\s+TEXT\s+AS\s+ABOVE\s*\|\n -- SQLNESS REPLACE (-+) - -- SQLNESS REPLACE (\s\s+) _ -- SQLNESS REPLACE (elapsed_compute.*) REDACTED @@ -29,6 +31,7 @@ TQL EXPLAIN ('1970-01-01T00:00:00'::timestamp, '1970-01-01T00:00:00'::timestamp TQL EXPLAIN VERBOSE (0, 10, '5s') test; -- explain verbose at 0s, 5s and 10s. No point at 0s. +-- SQLNESS REPLACE (?m)^\|\s*logical_plan\s+after\s+sst_manifest_aggregate\s*\|\s*SAME\s+TEXT\s+AS\s+ABOVE\s*\|\n -- SQLNESS REPLACE (-+) - -- SQLNESS REPLACE (\s\s+) _ -- SQLNESS REPLACE (elapsed_compute.*) REDACTED @@ -48,6 +51,7 @@ INSERT INTO test_nano VALUES (1, 1000000, "a"), (1, 1000000, "b"), (2, 2000000, TQL EXPLAIN (0, 10, '5s') test_nano; -- explain verbose at 0s, 5s and 10s for a nanosecond time index. +-- SQLNESS REPLACE (?m)^\|\s*logical_plan\s+after\s+sst_manifest_aggregate\s*\|\s*SAME\s+TEXT\s+AS\s+ABOVE\s*\|\n -- SQLNESS REPLACE (-+) - -- SQLNESS REPLACE (\s\s+) _ -- SQLNESS REPLACE (elapsed_compute.*) REDACTED diff --git a/tests/cases/standalone/common/tql/tql-cte.result b/tests/cases/standalone/common/tql/tql-cte.result index c2bc149e66c..cb8ba2c1eff 100644 --- a/tests/cases/standalone/common/tql/tql-cte.result +++ b/tests/cases/standalone/common/tql/tql-cte.result @@ -360,44 +360,43 @@ WHERE m.ts = l.ts ORDER BY m.ts LIMIT 3; -+---------------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ -| plan_type | plan | -+---------------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ -| logical_plan | Projection: metric_val, label_val | -| | Sort: m.ts ASC NULLS LAST, fetch=3 | -| | Projection: m.val AS metric_val, l.cpu AS label_val, m.ts | -| | Inner Join: m.ts = l.ts | -| | MergeScan [is_placeholder=false, remote_input=[ | -| | SubqueryAlias: m | -| | SubqueryAlias: metric_data | -| | Projection: metric.ts AS ts, metric.val AS val | -| | PromInstantManipulate: range=[0..40000], lookback=[300000], interval=[10000], time index=[ts] | -| | PromSeriesDivide: tags=[] | -| | Filter: metric.ts >= TimestampMillisecond(-299999, None) AND metric.ts <= TimestampMillisecond(40000, None) | -| | TableScan: metric, partial_filters=[metric.ts >= TimestampMillisecond(-299999, None), metric.ts <= TimestampMillisecond(40000, None)] | -| | ]] | -| | Projection: l.ts, l.cpu | -| | MergeScan [is_placeholder=false, remote_input=[ | -| | SubqueryAlias: l | -| | SubqueryAlias: label_data | -| | Projection: labels.ts AS ts, labels.host AS host, labels.cpu AS cpu | -| | PromInstantManipulate: range=[0..40000], lookback=[300000], interval=[10000], time index=[ts] | -| | PromSeriesDivide: tags=["host"] | -| | Filter: labels.host = Utf8("host2") AND labels.ts >= TimestampMillisecond(-299999, None) AND labels.ts <= TimestampMillisecond(40000, None) | -| | TableScan: labels, partial_filters=[labels.host = Utf8("host2"), labels.ts >= TimestampMillisecond(-299999, None), labels.ts <= TimestampMillisecond(40000, None)] | -| | ]] | -| physical_plan | ProjectionExec: expr=[metric_val@0 as metric_val, label_val@1 as label_val] | -| | SortPreservingMergeExec: [ts@2 ASC NULLS LAST], fetch=3 | ++---------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| plan_type | plan | ++---------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| logical_plan | Projection: metric_val, label_val | +| | Sort: m.ts ASC NULLS LAST, fetch=3 | +| | Projection: m.val AS metric_val, l.cpu AS label_val, m.ts | +| | Inner Join: m.ts = l.ts | +| | MergeScan [is_placeholder=false, remote_input=[ | +| | SubqueryAlias: m | +| | SubqueryAlias: metric_data | +| | Projection: metric.ts AS ts, metric.val AS val | +| | PromInstantManipulate: range=[0..40000], lookback=[300000], interval=[10000], time index=[ts] | +| | PromSeriesDivide: tags=[] | +| | Filter: metric.ts >= TimestampMillisecond(-299999, None) AND metric.ts <= TimestampMillisecond(40000, None) | +| | TableScan: metric, partial_filters=[metric.ts >= TimestampMillisecond(-299999, None), metric.ts <= TimestampMillisecond(40000, None)] | +| | ]] | +| | MergeScan [is_placeholder=false, remote_input=[ | +| | Projection: l.ts, l.cpu | +| | SubqueryAlias: l | +| | SubqueryAlias: label_data | +| | Projection: labels.ts AS ts, labels.host AS host, labels.cpu AS cpu | +| | PromInstantManipulate: range=[0..40000], lookback=[300000], interval=[10000], time index=[ts] | +| | PromSeriesDivide: tags=["host"] | +| | Filter: labels.host = Utf8("host2") AND labels.ts >= TimestampMillisecond(-299999, None) AND labels.ts <= TimestampMillisecond(40000, None) | +| | TableScan: labels, partial_filters=[labels.host = Utf8("host2"), labels.ts >= TimestampMillisecond(-299999, None), labels.ts <= TimestampMillisecond(40000, None)] | +| | ]] | +| physical_plan | ProjectionExec: expr=[metric_val@0 as metric_val, label_val@1 as label_val] | +| | SortPreservingMergeExec: [ts@2 ASC NULLS LAST], fetch=3 | | | SortExec: TopK(fetch=3), expr=[ts@2 ASC NULLS LAST], preserve_REDACTED -| | ProjectionExec: expr=[val@0 as metric_val, cpu@1 as label_val, ts@2 as ts] | -| | HashJoinExec: mode=Partitioned, join_type=Inner, on=[(ts@0, ts@0)], projection=[val@1, cpu@3, ts@0] | +| | ProjectionExec: expr=[val@0 as metric_val, cpu@1 as label_val, ts@2 as ts] | +| | HashJoinExec: mode=Partitioned, join_type=Inner, on=[(ts@0, ts@0)], projection=[val@1, cpu@3, ts@0] | | | RepartitionExec: REDACTED | | MergeScanExec: REDACTED | | RepartitionExec: REDACTED -| | ProjectionExec: expr=[ts@0 as ts, cpu@2 as cpu] | -| | MergeScanExec: REDACTED -| | | -+---------------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| | MergeScanExec: REDACTED +| | | ++---------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ -- TQL CTE with mathematical operations WITH computed(ts, val) AS ( @@ -743,24 +742,24 @@ LIMIT 5; | logical_plan | Sort: t.ts ASC NULLS LAST, l.host ASC NULLS LAST, avg_value ASC NULLS LAST, fetch=5 | | | Projection: t.ts, t.cpu AS avg_value, l.host | | | Inner Join: date_trunc(Utf8("second"), t.ts) = date_trunc(Utf8("second"), l.ts) | -| | Projection: t.ts, t.cpu | -| | MergeScan [is_placeholder=false, remote_input=[ | -| | SubqueryAlias: t | -| | SubqueryAlias: tql_summary | -| | Projection: labels.ts AS ts, prom_avg_over_time(ts_range,cpu) AS host, labels.host AS cpu | -| | Filter: prom_avg_over_time(ts_range,cpu) IS NOT NULL | -| | Projection: labels.ts, prom_avg_over_time(ts_range, cpu) AS prom_avg_over_time(ts_range,cpu), labels.host | -| | PromRangeManipulate: req range=[0..40000], interval=[10000], eval range=[30000], time index=[ts], values=["cpu"] | -| | PromSeriesNormalize: offset=[0], time index=[ts], filter NaN: [true] | -| | PromSeriesDivide: tags=["host"] | -| | Filter: labels.ts >= TimestampMillisecond(-29999, None) AND labels.ts <= TimestampMillisecond(40000, None) | -| | TableScan: labels, partial_filters=[labels.ts >= TimestampMillisecond(-29999, None), labels.ts <= TimestampMillisecond(40000, None)] | +| | MergeScan [is_placeholder=false, remote_input=[ | +| | Projection: t.ts, t.cpu | +| | SubqueryAlias: t | +| | SubqueryAlias: tql_summary | +| | Projection: labels.ts AS ts, prom_avg_over_time(ts_range,cpu) AS host, labels.host AS cpu | +| | Filter: prom_avg_over_time(ts_range,cpu) IS NOT NULL | +| | Projection: labels.ts, prom_avg_over_time(ts_range, cpu) AS prom_avg_over_time(ts_range,cpu), labels.host | +| | PromRangeManipulate: req range=[0..40000], interval=[10000], eval range=[30000], time index=[ts], values=["cpu"] | +| | PromSeriesNormalize: offset=[0], time index=[ts], filter NaN: [true] | +| | PromSeriesDivide: tags=["host"] | +| | Filter: labels.ts >= TimestampMillisecond(-29999, None) AND labels.ts <= TimestampMillisecond(40000, None) | +| | TableScan: labels, partial_filters=[labels.ts >= TimestampMillisecond(-29999, None), labels.ts <= TimestampMillisecond(40000, None)] | | | ]] | -| | Projection: l.ts, l.host | -| | MergeScan [is_placeholder=false, remote_input=[ | -| | SubqueryAlias: l | -| | Filter: labels.host = Utf8("host1") | -| | TableScan: labels, partial_filters=[labels.host = Utf8("host1")] | +| | MergeScan [is_placeholder=false, remote_input=[ | +| | Projection: l.ts, l.host | +| | SubqueryAlias: l | +| | Filter: labels.host = Utf8("host1") | +| | TableScan: labels, partial_filters=[labels.host = Utf8("host1")] | | | ]] | | physical_plan | SortPreservingMergeExec: [ts@0 ASC NULLS LAST, host@2 ASC NULLS LAST, avg_value@1 ASC NULLS LAST], fetch=5 | | | SortExec: TopK(fetch=5), expr=[ts@0 ASC NULLS LAST, host@2 ASC NULLS LAST, avg_value@1 ASC NULLS LAST], preserve_REDACTED @@ -769,13 +768,11 @@ LIMIT 5; | | RepartitionExec: REDACTED | | ProjectionExec: expr=[ts@0 as ts, cpu@1 as cpu, date_trunc(second, ts@0) as date_trunc(Utf8("second"),t.ts)] | | | RepartitionExec: REDACTED -| | ProjectionExec: expr=[ts@0 as ts, cpu@2 as cpu] | -| | MergeScanExec: REDACTED +| | MergeScanExec: REDACTED | | RepartitionExec: REDACTED | | ProjectionExec: expr=[ts@0 as ts, host@1 as host, date_trunc(second, ts@0) as date_trunc(Utf8("second"),l.ts)] | | | RepartitionExec: REDACTED -| | ProjectionExec: expr=[ts@0 as ts, host@1 as host] | -| | MergeScanExec: REDACTED +| | MergeScanExec: REDACTED | | | +---------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------+ @@ -825,24 +822,24 @@ LIMIT 5; | logical_plan | Sort: t.ts ASC NULLS LAST, l.host ASC NULLS LAST, avg_value ASC NULLS LAST, fetch=5 | | | Projection: t.ts, t.cpu AS avg_value, l.host | | | Inner Join: date_trunc(Utf8("second"), t.ts) = date_trunc(Utf8("second"), l.ts) | -| | Projection: t.cpu, t.ts | -| | MergeScan [is_placeholder=false, remote_input=[ | -| | SubqueryAlias: t | -| | SubqueryAlias: tql_summary | -| | Projection: prom_avg_over_time(ts_range,cpu) AS cpu, labels.host, labels.ts | -| | Filter: prom_avg_over_time(ts_range,cpu) IS NOT NULL | -| | Projection: labels.ts, prom_avg_over_time(ts_range, cpu) AS prom_avg_over_time(ts_range,cpu), labels.host | -| | PromRangeManipulate: req range=[0..40000], interval=[10000], eval range=[30000], time index=[ts], values=["cpu"] | -| | PromSeriesNormalize: offset=[0], time index=[ts], filter NaN: [true] | -| | PromSeriesDivide: tags=["host"] | -| | Filter: labels.ts >= TimestampMillisecond(-29999, None) AND labels.ts <= TimestampMillisecond(40000, None) | -| | TableScan: labels, partial_filters=[labels.ts >= TimestampMillisecond(-29999, None), labels.ts <= TimestampMillisecond(40000, None)] | +| | MergeScan [is_placeholder=false, remote_input=[ | +| | Projection: t.cpu, t.ts | +| | SubqueryAlias: t | +| | SubqueryAlias: tql_summary | +| | Projection: prom_avg_over_time(ts_range,cpu) AS cpu, labels.host, labels.ts | +| | Filter: prom_avg_over_time(ts_range,cpu) IS NOT NULL | +| | Projection: labels.ts, prom_avg_over_time(ts_range, cpu) AS prom_avg_over_time(ts_range,cpu), labels.host | +| | PromRangeManipulate: req range=[0..40000], interval=[10000], eval range=[30000], time index=[ts], values=["cpu"] | +| | PromSeriesNormalize: offset=[0], time index=[ts], filter NaN: [true] | +| | PromSeriesDivide: tags=["host"] | +| | Filter: labels.ts >= TimestampMillisecond(-29999, None) AND labels.ts <= TimestampMillisecond(40000, None) | +| | TableScan: labels, partial_filters=[labels.ts >= TimestampMillisecond(-29999, None), labels.ts <= TimestampMillisecond(40000, None)] | | | ]] | -| | Projection: l.ts, l.host | -| | MergeScan [is_placeholder=false, remote_input=[ | -| | SubqueryAlias: l | -| | Filter: labels.host = Utf8("host1") | -| | TableScan: labels, partial_filters=[labels.host = Utf8("host1")] | +| | MergeScan [is_placeholder=false, remote_input=[ | +| | Projection: l.ts, l.host | +| | SubqueryAlias: l | +| | Filter: labels.host = Utf8("host1") | +| | TableScan: labels, partial_filters=[labels.host = Utf8("host1")] | | | ]] | | physical_plan | SortPreservingMergeExec: [ts@0 ASC NULLS LAST, host@2 ASC NULLS LAST, avg_value@1 ASC NULLS LAST], fetch=5 | | | SortExec: TopK(fetch=5), expr=[ts@0 ASC NULLS LAST, host@2 ASC NULLS LAST, avg_value@1 ASC NULLS LAST], preserve_REDACTED @@ -851,13 +848,11 @@ LIMIT 5; | | RepartitionExec: REDACTED | | ProjectionExec: expr=[cpu@0 as cpu, ts@1 as ts, date_trunc(second, ts@1) as date_trunc(Utf8("second"),t.ts)] | | | RepartitionExec: REDACTED -| | ProjectionExec: expr=[cpu@0 as cpu, ts@2 as ts] | -| | MergeScanExec: REDACTED +| | MergeScanExec: REDACTED | | RepartitionExec: REDACTED | | ProjectionExec: expr=[ts@0 as ts, host@1 as host, date_trunc(second, ts@0) as date_trunc(Utf8("second"),l.ts)] | | | RepartitionExec: REDACTED -| | ProjectionExec: expr=[ts@0 as ts, host@1 as host] | -| | MergeScanExec: REDACTED +| | MergeScanExec: REDACTED | | | +---------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------+ diff --git a/tests/cases/standalone/common/types/json/json.result b/tests/cases/standalone/common/types/json/json.result index 541606a3ed6..ae2587a745a 100644 --- a/tests/cases/standalone/common/types/json/json.result +++ b/tests/cases/standalone/common/types/json/json.result @@ -99,7 +99,7 @@ SELECT json_to_string(j), t FROM jsons; | {"a":null,"foo":"bar"} | 1970-01-01T00:00:00.009 | | [-1] | 1970-01-01T00:00:00.010 | | {"entities":{"description":{"urls":[{"display_url":"pixiv.net/member.php?id=…","expanded_url":"http://www.pixiv.net/member.php?id=4776","indices":[58,80],"url":"http://t.co/QMLJeFmfMT"},{"display_url":"ask.fm/KATANA77","expanded_url":"http://ask.fm/KATANA77","indices":[95,117],"url":"http://t.co/LU8T7vmU3h"}]}}} | 1970-01-01T00:00:00.011 | -| {"a":"abc\u2028tom"} | 1970-01-01T00:00:00.012 | +| {"a":"abc
tom"} | 1970-01-01T00:00:00.012 | | [null] | 1970-01-01T00:00:01 | | [true] | 1970-01-01T00:00:01.001 | | [false] | 1970-01-01T00:00:01.002 | @@ -113,7 +113,7 @@ SELECT json_to_string(j), t FROM jsons; | [-1] | 1970-01-01T00:00:01.010 | | [-2147483648] | 1970-01-01T00:00:01.011 | | {"entities":{"description":{"urls":[{"display_url":"pixiv.net/member.php?id=…","expanded_url":"http://www.pixiv.net/member.php?id=4776","indices":[58,80],"url":"http://t.co/QMLJeFmfMT"},{"display_url":"ask.fm/KATANA77","expanded_url":"http://ask.fm/KATANA77","indices":[95,117],"url":"http://t.co/LU8T7vmU3h"}]}}} | 1970-01-01T00:00:01.012 | -| {"a":"abc\u2028tom"} | 1970-01-01T00:00:01.013 | +| {"a":"abc
tom"} | 1970-01-01T00:00:01.013 | +---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------------------------+ --Insert invalid json strings-- diff --git a/tests/cases/standalone/common/types/json/json2_fulltext_index.result b/tests/cases/standalone/common/types/json/json2_fulltext_index.result new file mode 100644 index 00000000000..2efc271f9a3 --- /dev/null +++ b/tests/cases/standalone/common/types/json/json2_fulltext_index.result @@ -0,0 +1,814 @@ +-- Compare JSON paths with an ordinary column using the same fulltext backend. +CREATE TABLE json2_fulltext_bloom ( + ts TIMESTAMP TIME INDEX, + attrs JSON2 (max_auto_expanded_paths=0, + nested.message STRING FULLTEXT INDEX WITH (backend='bloom', analyzer='English', case_sensitive='false', granularity='1') SKIPPING INDEX INVERTED INDEX, + "nested.message" STRING FULLTEXT INDEX WITH (backend='bloom', analyzer='English', case_sensitive='false', granularity='1')), + ordinary STRING FULLTEXT INDEX WITH (backend='bloom', analyzer='English', case_sensitive='false', granularity='1') +) WITH ('append_mode'='true', 'sst_format'='flat'); + +Affected Rows: 0 + +SHOW CREATE TABLE json2_fulltext_bloom; + ++----------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| Table | Create Table | ++----------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| json2_fulltext_bloom | CREATE TABLE IF NOT EXISTS "json2_fulltext_bloom" ( | +| | "ts" TIMESTAMP(3) NOT NULL, | +| | "attrs" JSON2( | +| | max_auto_expanded_paths = 0, | +| | "nested"."message" STRING SKIPPING INDEX WITH (granularity = '10240', false_positive_rate = '0.01', type = 'BLOOM') FULLTEXT INDEX WITH (analyzer = 'English', case_sensitive = 'false', backend = 'bloom', granularity = '1', false_positive_rate = '0.01') INVERTED INDEX, | +| | "nested.message" STRING FULLTEXT INDEX WITH (analyzer = 'English', case_sensitive = 'false', backend = 'bloom', granularity = '1', false_positive_rate = '0.01') | +| | ) NULL, | +| | "ordinary" STRING NULL FULLTEXT INDEX WITH(analyzer = 'English', backend = 'bloom', case_sensitive = 'false', false_positive_rate = '0.01', granularity = '1'), | +| | TIME INDEX ("ts") | +| | ) | +| | | +| | ENGINE=mito | +| | WITH( | +| | append_mode = 'true', | +| | sst_format = 'flat' | +| | ) | ++----------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ + +INSERT INTO json2_fulltext_bloom VALUES + (1, '{"nested":{"message":"error timeout"},"nested.message":"healthy"}', 'error timeout'), + (2, '{"nested":{"message":"healthy"},"nested.message":"error timeout"}', 'healthy'), + (3, '{"nested":{"message":"ERROR retry"}}', 'ERROR retry'), + (4, '{}', NULL), (5, NULL, NULL), + (6, '{"nested":{"message":""}}', ''); + +Affected Rows: 6 + +ADMIN FLUSH_TABLE('json2_fulltext_bloom'); + ++-------------------------------------------+ +| ADMIN FLUSH_TABLE('json2_fulltext_bloom') | ++-------------------------------------------+ +| 0 | ++-------------------------------------------+ + +SELECT ts FROM json2_fulltext_bloom WHERE matches_term(attrs.nested.message, 'error') ORDER BY ts; + ++-------------------------+ +| ts | ++-------------------------+ +| 1970-01-01T00:00:00.001 | ++-------------------------+ + +SELECT ts FROM json2_fulltext_bloom WHERE matches_term(ordinary, 'error') ORDER BY ts; + ++-------------------------+ +| ts | ++-------------------------+ +| 1970-01-01T00:00:00.001 | ++-------------------------+ + +-- Combine fulltext predicates with inverted/skipping equality predicates. +SELECT ts FROM json2_fulltext_bloom WHERE matches_term(attrs.nested.message, 'error') AND attrs.nested.message = 'error timeout' ORDER BY ts; + ++-------------------------+ +| ts | ++-------------------------+ +| 1970-01-01T00:00:00.001 | ++-------------------------+ + +SELECT ts FROM json2_fulltext_bloom WHERE matches_term(json_get(attrs, '$."nested.message"'), 'error') AND attrs.nested.message = 'healthy' ORDER BY ts; + ++-------------------------+ +| ts | ++-------------------------+ +| 1970-01-01T00:00:00.002 | ++-------------------------+ + +SELECT ts FROM json2_fulltext_bloom WHERE matches_term(json_get(attrs, '$."nested.message"'), 'error') ORDER BY ts; + ++-------------------------+ +| ts | ++-------------------------+ +| 1970-01-01T00:00:00.002 | ++-------------------------+ + +SELECT ts FROM json2_fulltext_bloom WHERE attrs.nested.message IS NULL ORDER BY ts; + ++-------------------------+ +| ts | ++-------------------------+ +| 1970-01-01T00:00:00.004 | +| 1970-01-01T00:00:00.005 | ++-------------------------+ + +SELECT ts FROM json2_fulltext_bloom WHERE matches_term(attrs.nested.message, 'error') OR matches_term(json_get(attrs, '$."nested.message"'), 'error') ORDER BY ts; + ++-------------------------+ +| ts | ++-------------------------+ +| 1970-01-01T00:00:00.001 | +| 1970-01-01T00:00:00.002 | ++-------------------------+ + +SELECT ts FROM json2_fulltext_bloom WHERE matches_term(lower(attrs.nested.message), 'error') ORDER BY ts; + ++-------------------------+ +| ts | ++-------------------------+ +| 1970-01-01T00:00:00.001 | +| 1970-01-01T00:00:00.003 | ++-------------------------+ + +SELECT ts FROM json2_fulltext_bloom WHERE attrs.nested.message LIKE '%error timeout%' ORDER BY ts; + ++-------------------------+ +| ts | ++-------------------------+ +| 1970-01-01T00:00:00.001 | ++-------------------------+ + +SELECT ts FROM json2_fulltext_bloom WHERE ordinary LIKE '%error timeout%' ORDER BY ts; + ++-------------------------+ +| ts | ++-------------------------+ +| 1970-01-01T00:00:00.001 | ++-------------------------+ + +-- SQLNESS REPLACE "metrics_per_partition":.*("rows_fulltext_filtered":\d+).*metrics= "metrics_per_partition":{$1} metrics= +-- SQLNESS REPLACE "metrics_per_partition":\s*\[.*metrics= "metrics_per_partition":REDACTED metrics= +-- SQLNESS REPLACE (metrics=\{.*\}) metrics=REDACTED +-- SQLNESS REPLACE (metrics=\[[^\]]*\]) metrics=REDACTED +-- SQLNESS REPLACE (RoundRobinBatch.*) REDACTED +-- SQLNESS REPLACE (-+) - +-- SQLNESS REPLACE (\s\s+) _ +-- SQLNESS REPLACE "(file_id|time_range_start|time_range_end)":"[^"]+" "$1":"REDACTED" +-- SQLNESS REPLACE ("[a-z_]+":"[0-9\.]+(ns|us|µs|ms|s)") "DURATION": REDACTED +-- SQLNESS REPLACE "(size|flat_format)":\s*(\d+|true|false) "$1":REDACTED +-- SQLNESS REPLACE ,\s*filter=.*?metrics= metrics= +-- SQLNESS REPLACE Total\s+rows:\s+\d+ Total rows: REDACTED +-- SQLNESS REPLACE (peers.*) REDACTED +-- SQLNESS REPLACE region=\d+\(\d+,\s+\d+\) region=REDACTED +-- SQLNESS REPLACE ,\s"dyn_filters":\s\[.* REDACTED +-- SQLNESS REPLACE "index_size":\d+ "index_size":REDACTED +-- SQLNESS REPLACE "max_part_range":\s*\{[^}]*\} "max_part_range":REDACTED +EXPLAIN ANALYZE VERBOSE SELECT ts FROM json2_fulltext_bloom WHERE matches_term(attrs.nested.message, 'absenttoken'); + ++-+-+-+ +| stage | node | plan_| ++-+-+-+ +| 0_| 0_|_CooperativeExec metrics=REDACTED_| +|_|_|_MergeScanExec: REDACTED +|_|_|_| +| 1_| 0_|_FilterExec: matches_term(json_get(attrs@1, $.nested.message, NULL), absenttoken), projection=[ts@0] metrics=REDACTED_| +|_|_|_CooperativeExec metrics=REDACTED_| +|_|_|_UnorderedScan: region=REDACTED, {"partition_count":{"count":1, "mem_ranges":0, "files":1, "file_ranges":1}, "projection": ["ts", "attrs"], "filters": ["matches_term(json_get(attrs, Utf8(\"$.nested.message\"), Utf8View(NULL)), Utf8View(\"absenttoken\"))"], "time_range": "TimestampRange{{[#,#)}}", "file_summary": {"files":1,"rows":6,"row_groups":1,"size":REDACTED,"index_size":REDACTED}, "max_part_range":REDACTED, "files": [{"file_id":"REDACTED","time_range_start":"REDACTED","time_range_end":"REDACTED","rows":6,"size":REDACTED,"index_size":REDACTED}], "flat_format":REDACTED, "metrics_per_partition":{"rows_fulltext_filtered":6} metrics=REDACTED | +|_|_|_| +|_|_| Total rows: REDACTED_| ++-+-+-+ + +-- SQLNESS REPLACE "metrics_per_partition":.*("rows_fulltext_filtered":\d+).*metrics= "metrics_per_partition":{$1} metrics= +-- SQLNESS REPLACE "metrics_per_partition":\s*\[.*metrics= "metrics_per_partition":REDACTED metrics= +-- SQLNESS REPLACE (metrics=\{.*\}) metrics=REDACTED +-- SQLNESS REPLACE (metrics=\[[^\]]*\]) metrics=REDACTED +-- SQLNESS REPLACE (RoundRobinBatch.*) REDACTED +-- SQLNESS REPLACE (-+) - +-- SQLNESS REPLACE (\s\s+) _ +-- SQLNESS REPLACE "(file_id|time_range_start|time_range_end)":"[^"]+" "$1":"REDACTED" +-- SQLNESS REPLACE ("[a-z_]+":"[0-9\.]+(ns|us|µs|ms|s)") "DURATION": REDACTED +-- SQLNESS REPLACE "(size|flat_format)":\s*(\d+|true|false) "$1":REDACTED +-- SQLNESS REPLACE ,\s*filter=.*?metrics= metrics= +-- SQLNESS REPLACE Total\s+rows:\s+\d+ Total rows: REDACTED +-- SQLNESS REPLACE (peers.*) REDACTED +-- SQLNESS REPLACE region=\d+\(\d+,\s+\d+\) region=REDACTED +-- SQLNESS REPLACE ,\s"dyn_filters":\s\[.* REDACTED +-- SQLNESS REPLACE "index_size":\d+ "index_size":REDACTED +-- SQLNESS REPLACE "max_part_range":\s*\{[^}]*\} "max_part_range":REDACTED +EXPLAIN ANALYZE VERBOSE SELECT ts FROM json2_fulltext_bloom WHERE matches_term(attrs.nested.message, 'absenttoken'); + ++-+-+-+ +| stage | node | plan_| ++-+-+-+ +| 0_| 0_|_CooperativeExec metrics=REDACTED_| +|_|_|_MergeScanExec: REDACTED +|_|_|_| +| 1_| 0_|_FilterExec: matches_term(json_get(attrs@1, $.nested.message, NULL), absenttoken), projection=[ts@0] metrics=REDACTED_| +|_|_|_CooperativeExec metrics=REDACTED_| +|_|_|_UnorderedScan: region=REDACTED, {"partition_count":{"count":1, "mem_ranges":0, "files":1, "file_ranges":1}, "projection": ["ts", "attrs"], "filters": ["matches_term(json_get(attrs, Utf8(\"$.nested.message\"), Utf8View(NULL)), Utf8View(\"absenttoken\"))"], "time_range": "TimestampRange{{[#,#)}}", "file_summary": {"files":1,"rows":6,"row_groups":1,"size":REDACTED,"index_size":REDACTED}, "max_part_range":REDACTED, "files": [{"file_id":"REDACTED","time_range_start":"REDACTED","time_range_end":"REDACTED","rows":6,"size":REDACTED,"index_size":REDACTED}], "flat_format":REDACTED, "metrics_per_partition":{"rows_fulltext_filtered":6} metrics=REDACTED | +|_|_|_| +|_|_| Total rows: REDACTED_| ++-+-+-+ + +INSERT INTO json2_fulltext_bloom VALUES (7, '{"nested":{"message":"error extra"}}', 'error extra'); + +Affected Rows: 1 + +ADMIN FLUSH_TABLE('json2_fulltext_bloom'); + ++-------------------------------------------+ +| ADMIN FLUSH_TABLE('json2_fulltext_bloom') | ++-------------------------------------------+ +| 0 | ++-------------------------------------------+ + +ADMIN COMPACT_TABLE('json2_fulltext_bloom', 'swcs', '86400'); + ++--------------------------------------------------------------+ +| ADMIN COMPACT_TABLE('json2_fulltext_bloom', 'swcs', '86400') | ++--------------------------------------------------------------+ +| 0 | ++--------------------------------------------------------------+ + +SELECT ts FROM json2_fulltext_bloom WHERE matches_term(attrs.nested.message, 'error') ORDER BY ts; + ++-------------------------+ +| ts | ++-------------------------+ +| 1970-01-01T00:00:00.001 | +| 1970-01-01T00:00:00.007 | ++-------------------------+ + +-- SQLNESS REPLACE "metrics_per_partition":.*("rows_fulltext_filtered":\d+).*metrics= "metrics_per_partition":{$1} metrics= +-- SQLNESS REPLACE "metrics_per_partition":\s*\[.*metrics= "metrics_per_partition":REDACTED metrics= +-- SQLNESS REPLACE (metrics=\{.*\}) metrics=REDACTED +-- SQLNESS REPLACE (metrics=\[[^\]]*\]) metrics=REDACTED +-- SQLNESS REPLACE (RoundRobinBatch.*) REDACTED +-- SQLNESS REPLACE (-+) - +-- SQLNESS REPLACE (\s\s+) _ +-- SQLNESS REPLACE "(file_id|time_range_start|time_range_end)":"[^"]+" "$1":"REDACTED" +-- SQLNESS REPLACE ("[a-z_]+":"[0-9\.]+(ns|us|µs|ms|s)") "DURATION": REDACTED +-- SQLNESS REPLACE "(size|flat_format)":\s*(\d+|true|false) "$1":REDACTED +-- SQLNESS REPLACE ,\s*filter=.*?metrics= metrics= +-- SQLNESS REPLACE Total\s+rows:\s+\d+ Total rows: REDACTED +-- SQLNESS REPLACE (peers.*) REDACTED +-- SQLNESS REPLACE region=\d+\(\d+,\s+\d+\) region=REDACTED +-- SQLNESS REPLACE ,\s"dyn_filters":\s\[.* REDACTED +-- SQLNESS REPLACE "index_size":\d+ "index_size":REDACTED +-- SQLNESS REPLACE "max_part_range":\s*\{[^}]*\} "max_part_range":REDACTED +EXPLAIN ANALYZE VERBOSE SELECT ts FROM json2_fulltext_bloom WHERE matches_term(attrs.nested.message, 'absenttoken'); + ++-+-+-+ +| stage | node | plan_| ++-+-+-+ +| 0_| 0_|_CooperativeExec metrics=REDACTED_| +|_|_|_MergeScanExec: REDACTED +|_|_|_| +| 1_| 0_|_FilterExec: matches_term(json_get(attrs@1, $.nested.message, NULL), absenttoken), projection=[ts@0] metrics=REDACTED_| +|_|_|_CooperativeExec metrics=REDACTED_| +|_|_|_UnorderedScan: region=REDACTED, {"partition_count":{"count":1, "mem_ranges":0, "files":1, "file_ranges":1}, "projection": ["ts", "attrs"], "filters": ["matches_term(json_get(attrs, Utf8(\"$.nested.message\"), Utf8View(NULL)), Utf8View(\"absenttoken\"))"], "time_range": "TimestampRange{{[#,#)}}", "file_summary": {"files":1,"rows":7,"row_groups":1,"size":REDACTED,"index_size":REDACTED}, "max_part_range":REDACTED, "files": [{"file_id":"REDACTED","time_range_start":"REDACTED","time_range_end":"REDACTED","rows":7,"size":REDACTED,"index_size":REDACTED}], "flat_format":REDACTED, "metrics_per_partition":{"rows_fulltext_filtered":7} metrics=REDACTED | +|_|_|_| +|_|_| Total rows: REDACTED_| ++-+-+-+ + +ALTER TABLE json2_fulltext_bloom MODIFY COLUMN attrs JSON2(max_auto_expanded_paths=0, nested.message STRING, "nested.message" STRING); + +Affected Rows: 0 + +SELECT ts FROM json2_fulltext_bloom WHERE matches_term(attrs.nested.message, 'error') ORDER BY ts; + ++-------------------------+ +| ts | ++-------------------------+ +| 1970-01-01T00:00:00.001 | +| 1970-01-01T00:00:00.007 | ++-------------------------+ + +DROP TABLE json2_fulltext_bloom; + +Affected Rows: 0 + +-- Compare JSON paths with an ordinary column using the same fulltext backend. +CREATE TABLE json2_fulltext_tantivy ( + ts TIMESTAMP TIME INDEX, + attrs JSON2 (max_auto_expanded_paths=0, + nested.message STRING FULLTEXT INDEX WITH (backend='tantivy', analyzer='English', case_sensitive='false') SKIPPING INDEX INVERTED INDEX, + "nested.message" STRING FULLTEXT INDEX WITH (backend='tantivy', analyzer='English', case_sensitive='false')), + ordinary STRING FULLTEXT INDEX WITH (backend='tantivy', analyzer='English', case_sensitive='false') +) WITH ('append_mode'='true', 'sst_format'='flat'); + +Affected Rows: 0 + +SHOW CREATE TABLE json2_fulltext_tantivy; + ++------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| Table | Create Table | ++------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| json2_fulltext_tantivy | CREATE TABLE IF NOT EXISTS "json2_fulltext_tantivy" ( | +| | "ts" TIMESTAMP(3) NOT NULL, | +| | "attrs" JSON2( | +| | max_auto_expanded_paths = 0, | +| | "nested"."message" STRING SKIPPING INDEX WITH (granularity = '10240', false_positive_rate = '0.01', type = 'BLOOM') FULLTEXT INDEX WITH (analyzer = 'English', case_sensitive = 'false', backend = 'tantivy') INVERTED INDEX, | +| | "nested.message" STRING FULLTEXT INDEX WITH (analyzer = 'English', case_sensitive = 'false', backend = 'tantivy') | +| | ) NULL, | +| | "ordinary" STRING NULL FULLTEXT INDEX WITH(analyzer = 'English', backend = 'tantivy', case_sensitive = 'false'), | +| | TIME INDEX ("ts") | +| | ) | +| | | +| | ENGINE=mito | +| | WITH( | +| | append_mode = 'true', | +| | sst_format = 'flat' | +| | ) | ++------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ + +INSERT INTO json2_fulltext_tantivy VALUES + (1, '{"nested":{"message":"error timeout"},"nested.message":"healthy"}', 'error timeout'), + (2, '{"nested":{"message":"healthy"},"nested.message":"error timeout"}', 'healthy'), + (3, '{"nested":{"message":"ERROR retry"}}', 'ERROR retry'), + (4, '{}', NULL), (5, NULL, NULL), + (6, '{"nested":{"message":""}}', ''); + +Affected Rows: 6 + +ADMIN FLUSH_TABLE('json2_fulltext_tantivy'); + ++---------------------------------------------+ +| ADMIN FLUSH_TABLE('json2_fulltext_tantivy') | ++---------------------------------------------+ +| 0 | ++---------------------------------------------+ + +SELECT ts FROM json2_fulltext_tantivy WHERE matches(attrs.nested.message, 'error') ORDER BY ts; + ++-------------------------+ +| ts | ++-------------------------+ +| 1970-01-01T00:00:00.001 | ++-------------------------+ + +SELECT ts FROM json2_fulltext_tantivy WHERE matches(ordinary, 'error') ORDER BY ts; + ++-------------------------+ +| ts | ++-------------------------+ +| 1970-01-01T00:00:00.001 | ++-------------------------+ + +-- Combine fulltext predicates with inverted/skipping equality predicates. +SELECT ts FROM json2_fulltext_tantivy WHERE matches(attrs.nested.message, 'error') AND attrs.nested.message = 'error timeout' ORDER BY ts; + ++-------------------------+ +| ts | ++-------------------------+ +| 1970-01-01T00:00:00.001 | ++-------------------------+ + +SELECT ts FROM json2_fulltext_tantivy WHERE matches(json_get(attrs, '$."nested.message"'), 'error') AND attrs.nested.message = 'healthy' ORDER BY ts; + ++-------------------------+ +| ts | ++-------------------------+ +| 1970-01-01T00:00:00.002 | ++-------------------------+ + +SELECT ts FROM json2_fulltext_tantivy WHERE matches(json_get(attrs, '$."nested.message"'), 'error') ORDER BY ts; + ++-------------------------+ +| ts | ++-------------------------+ +| 1970-01-01T00:00:00.002 | ++-------------------------+ + +SELECT ts FROM json2_fulltext_tantivy WHERE attrs.nested.message IS NULL ORDER BY ts; + ++-------------------------+ +| ts | ++-------------------------+ +| 1970-01-01T00:00:00.004 | +| 1970-01-01T00:00:00.005 | ++-------------------------+ + +SELECT ts FROM json2_fulltext_tantivy WHERE matches(attrs.nested.message, 'error') OR matches(json_get(attrs, '$."nested.message"'), 'error') ORDER BY ts; + ++-------------------------+ +| ts | ++-------------------------+ +| 1970-01-01T00:00:00.001 | +| 1970-01-01T00:00:00.002 | ++-------------------------+ + +-- SQLNESS REPLACE "metrics_per_partition":.*("rows_fulltext_filtered":\d+).*metrics= "metrics_per_partition":{$1} metrics= +-- SQLNESS REPLACE "metrics_per_partition":\s*\[.*metrics= "metrics_per_partition":REDACTED metrics= +-- SQLNESS REPLACE (metrics=\{.*\}) metrics=REDACTED +-- SQLNESS REPLACE (metrics=\[[^\]]*\]) metrics=REDACTED +-- SQLNESS REPLACE (RoundRobinBatch.*) REDACTED +-- SQLNESS REPLACE (-+) - +-- SQLNESS REPLACE (\s\s+) _ +-- SQLNESS REPLACE "(file_id|time_range_start|time_range_end)":"[^"]+" "$1":"REDACTED" +-- SQLNESS REPLACE ("[a-z_]+":"[0-9\.]+(ns|us|µs|ms|s)") "DURATION": REDACTED +-- SQLNESS REPLACE "(size|flat_format)":\s*(\d+|true|false) "$1":REDACTED +-- SQLNESS REPLACE ,\s*filter=.*?metrics= metrics= +-- SQLNESS REPLACE Total\s+rows:\s+\d+ Total rows: REDACTED +-- SQLNESS REPLACE (peers.*) REDACTED +-- SQLNESS REPLACE region=\d+\(\d+,\s+\d+\) region=REDACTED +-- SQLNESS REPLACE ,\s"dyn_filters":\s\[.* REDACTED +-- SQLNESS REPLACE "index_size":\d+ "index_size":REDACTED +-- SQLNESS REPLACE "max_part_range":\s*\{[^}]*\} "max_part_range":REDACTED +EXPLAIN ANALYZE VERBOSE SELECT ts FROM json2_fulltext_tantivy WHERE matches(attrs.nested.message, 'absenttoken'); + ++-+-+-+ +| stage | node | plan_| ++-+-+-+ +| 0_| 0_|_CooperativeExec metrics=REDACTED_| +|_|_|_MergeScanExec: REDACTED +|_|_|_| +| 1_| 0_|_FilterExec: matches(json_get(attrs@1, $.nested.message, NULL), absenttoken), projection=[ts@0] metrics=REDACTED_| +|_|_|_CooperativeExec metrics=REDACTED_| +|_|_|_UnorderedScan: region=REDACTED, {"partition_count":{"count":1, "mem_ranges":0, "files":1, "file_ranges":1}, "projection": ["ts", "attrs"], "filters": ["matches(json_get(attrs, Utf8(\"$.nested.message\"), Utf8View(NULL)), Utf8View(\"absenttoken\"))"], "time_range": "TimestampRange{{[#,#)}}", "file_summary": {"files":1,"rows":6,"row_groups":1,"size":REDACTED,"index_size":REDACTED}, "max_part_range":REDACTED, "files": [{"file_id":"REDACTED","time_range_start":"REDACTED","time_range_end":"REDACTED","rows":6,"size":REDACTED,"index_size":REDACTED}], "flat_format":REDACTED, "metrics_per_partition":{"rows_fulltext_filtered":6} metrics=REDACTED | +|_|_|_| +|_|_| Total rows: REDACTED_| ++-+-+-+ + +-- SQLNESS REPLACE "metrics_per_partition":.*("rows_fulltext_filtered":\d+).*metrics= "metrics_per_partition":{$1} metrics= +-- SQLNESS REPLACE "metrics_per_partition":\s*\[.*metrics= "metrics_per_partition":REDACTED metrics= +-- SQLNESS REPLACE (metrics=\{.*\}) metrics=REDACTED +-- SQLNESS REPLACE (metrics=\[[^\]]*\]) metrics=REDACTED +-- SQLNESS REPLACE (RoundRobinBatch.*) REDACTED +-- SQLNESS REPLACE (-+) - +-- SQLNESS REPLACE (\s\s+) _ +-- SQLNESS REPLACE "(file_id|time_range_start|time_range_end)":"[^"]+" "$1":"REDACTED" +-- SQLNESS REPLACE ("[a-z_]+":"[0-9\.]+(ns|us|µs|ms|s)") "DURATION": REDACTED +-- SQLNESS REPLACE "(size|flat_format)":\s*(\d+|true|false) "$1":REDACTED +-- SQLNESS REPLACE ,\s*filter=.*?metrics= metrics= +-- SQLNESS REPLACE Total\s+rows:\s+\d+ Total rows: REDACTED +-- SQLNESS REPLACE (peers.*) REDACTED +-- SQLNESS REPLACE region=\d+\(\d+,\s+\d+\) region=REDACTED +-- SQLNESS REPLACE ,\s"dyn_filters":\s\[.* REDACTED +-- SQLNESS REPLACE "index_size":\d+ "index_size":REDACTED +-- SQLNESS REPLACE "max_part_range":\s*\{[^}]*\} "max_part_range":REDACTED +EXPLAIN ANALYZE VERBOSE SELECT ts FROM json2_fulltext_tantivy WHERE matches(attrs.nested.message, 'absenttoken'); + ++-+-+-+ +| stage | node | plan_| ++-+-+-+ +| 0_| 0_|_CooperativeExec metrics=REDACTED_| +|_|_|_MergeScanExec: REDACTED +|_|_|_| +| 1_| 0_|_FilterExec: matches(json_get(attrs@1, $.nested.message, NULL), absenttoken), projection=[ts@0] metrics=REDACTED_| +|_|_|_CooperativeExec metrics=REDACTED_| +|_|_|_UnorderedScan: region=REDACTED, {"partition_count":{"count":1, "mem_ranges":0, "files":1, "file_ranges":1}, "projection": ["ts", "attrs"], "filters": ["matches(json_get(attrs, Utf8(\"$.nested.message\"), Utf8View(NULL)), Utf8View(\"absenttoken\"))"], "time_range": "TimestampRange{{[#,#)}}", "file_summary": {"files":1,"rows":6,"row_groups":1,"size":REDACTED,"index_size":REDACTED}, "max_part_range":REDACTED, "files": [{"file_id":"REDACTED","time_range_start":"REDACTED","time_range_end":"REDACTED","rows":6,"size":REDACTED,"index_size":REDACTED}], "flat_format":REDACTED, "metrics_per_partition":{"rows_fulltext_filtered":6} metrics=REDACTED | +|_|_|_| +|_|_| Total rows: REDACTED_| ++-+-+-+ + +INSERT INTO json2_fulltext_tantivy VALUES (7, '{"nested":{"message":"error extra"}}', 'error extra'); + +Affected Rows: 1 + +ADMIN FLUSH_TABLE('json2_fulltext_tantivy'); + ++---------------------------------------------+ +| ADMIN FLUSH_TABLE('json2_fulltext_tantivy') | ++---------------------------------------------+ +| 0 | ++---------------------------------------------+ + +ADMIN COMPACT_TABLE('json2_fulltext_tantivy', 'swcs', '86400'); + ++----------------------------------------------------------------+ +| ADMIN COMPACT_TABLE('json2_fulltext_tantivy', 'swcs', '86400') | ++----------------------------------------------------------------+ +| 0 | ++----------------------------------------------------------------+ + +SELECT ts FROM json2_fulltext_tantivy WHERE matches(attrs.nested.message, 'error') ORDER BY ts; + ++-------------------------+ +| ts | ++-------------------------+ +| 1970-01-01T00:00:00.001 | +| 1970-01-01T00:00:00.007 | ++-------------------------+ + +-- SQLNESS REPLACE "metrics_per_partition":.*("rows_fulltext_filtered":\d+).*metrics= "metrics_per_partition":{$1} metrics= +-- SQLNESS REPLACE "metrics_per_partition":\s*\[.*metrics= "metrics_per_partition":REDACTED metrics= +-- SQLNESS REPLACE (metrics=\{.*\}) metrics=REDACTED +-- SQLNESS REPLACE (metrics=\[[^\]]*\]) metrics=REDACTED +-- SQLNESS REPLACE (RoundRobinBatch.*) REDACTED +-- SQLNESS REPLACE (-+) - +-- SQLNESS REPLACE (\s\s+) _ +-- SQLNESS REPLACE "(file_id|time_range_start|time_range_end)":"[^"]+" "$1":"REDACTED" +-- SQLNESS REPLACE ("[a-z_]+":"[0-9\.]+(ns|us|µs|ms|s)") "DURATION": REDACTED +-- SQLNESS REPLACE "(size|flat_format)":\s*(\d+|true|false) "$1":REDACTED +-- SQLNESS REPLACE ,\s*filter=.*?metrics= metrics= +-- SQLNESS REPLACE Total\s+rows:\s+\d+ Total rows: REDACTED +-- SQLNESS REPLACE (peers.*) REDACTED +-- SQLNESS REPLACE region=\d+\(\d+,\s+\d+\) region=REDACTED +-- SQLNESS REPLACE ,\s"dyn_filters":\s\[.* REDACTED +-- SQLNESS REPLACE "index_size":\d+ "index_size":REDACTED +-- SQLNESS REPLACE "max_part_range":\s*\{[^}]*\} "max_part_range":REDACTED +EXPLAIN ANALYZE VERBOSE SELECT ts FROM json2_fulltext_tantivy WHERE matches(attrs.nested.message, 'absenttoken'); + ++-+-+-+ +| stage | node | plan_| ++-+-+-+ +| 0_| 0_|_CooperativeExec metrics=REDACTED_| +|_|_|_MergeScanExec: REDACTED +|_|_|_| +| 1_| 0_|_FilterExec: matches(json_get(attrs@1, $.nested.message, NULL), absenttoken), projection=[ts@0] metrics=REDACTED_| +|_|_|_CooperativeExec metrics=REDACTED_| +|_|_|_UnorderedScan: region=REDACTED, {"partition_count":{"count":1, "mem_ranges":0, "files":1, "file_ranges":1}, "projection": ["ts", "attrs"], "filters": ["matches(json_get(attrs, Utf8(\"$.nested.message\"), Utf8View(NULL)), Utf8View(\"absenttoken\"))"], "time_range": "TimestampRange{{[#,#)}}", "file_summary": {"files":1,"rows":7,"row_groups":1,"size":REDACTED,"index_size":REDACTED}, "max_part_range":REDACTED, "files": [{"file_id":"REDACTED","time_range_start":"REDACTED","time_range_end":"REDACTED","rows":7,"size":REDACTED,"index_size":REDACTED}], "flat_format":REDACTED, "metrics_per_partition":{"rows_fulltext_filtered":7} metrics=REDACTED | +|_|_|_| +|_|_| Total rows: REDACTED_| ++-+-+-+ + +ALTER TABLE json2_fulltext_tantivy MODIFY COLUMN attrs JSON2(max_auto_expanded_paths=0, nested.message STRING, "nested.message" STRING); + +Affected Rows: 0 + +SELECT ts FROM json2_fulltext_tantivy WHERE matches(attrs.nested.message, 'error') ORDER BY ts; + ++-------------------------+ +| ts | ++-------------------------+ +| 1970-01-01T00:00:00.001 | +| 1970-01-01T00:00:00.007 | ++-------------------------+ + +DROP TABLE json2_fulltext_tantivy; + +Affected Rows: 0 + +CREATE TABLE json2_fulltext_chinese_bloom ( + ts TIMESTAMP TIME INDEX, + j JSON2(text STRING FULLTEXT INDEX WITH (backend='bloom', analyzer='Chinese', case_sensitive='true', granularity='1')), + ordinary STRING FULLTEXT INDEX WITH (backend='bloom', analyzer='Chinese', case_sensitive='true', granularity='1') +) WITH ('append_mode'='true'); + +Affected Rows: 0 + +INSERT INTO json2_fulltext_chinese_bloom VALUES + (1, '{"text":"错误 日志 ERROR"}', '错误 日志 ERROR'), + (2, '{"text":"正常 日志 error"}', '正常 日志 error'); + +Affected Rows: 2 + +ADMIN FLUSH_TABLE('json2_fulltext_chinese_bloom'); + ++---------------------------------------------------+ +| ADMIN FLUSH_TABLE('json2_fulltext_chinese_bloom') | ++---------------------------------------------------+ +| 0 | ++---------------------------------------------------+ + +SELECT ts FROM json2_fulltext_chinese_bloom WHERE matches_term(j.text, '错误') ORDER BY ts; + ++-------------------------+ +| ts | ++-------------------------+ +| 1970-01-01T00:00:00.001 | ++-------------------------+ + +SELECT ts FROM json2_fulltext_chinese_bloom WHERE matches_term(ordinary, '错误') ORDER BY ts; + ++-------------------------+ +| ts | ++-------------------------+ +| 1970-01-01T00:00:00.001 | ++-------------------------+ + +SELECT ts FROM json2_fulltext_chinese_bloom WHERE matches_term(j.text, 'ERROR') ORDER BY ts; + ++-------------------------+ +| ts | ++-------------------------+ +| 1970-01-01T00:00:00.001 | ++-------------------------+ + +SELECT ts FROM json2_fulltext_chinese_bloom WHERE matches_term(ordinary, 'ERROR') ORDER BY ts; + ++-------------------------+ +| ts | ++-------------------------+ +| 1970-01-01T00:00:00.001 | ++-------------------------+ + +SELECT ts FROM json2_fulltext_chinese_bloom WHERE matches_term(lower(j.text), 'error') ORDER BY ts; + ++-------------------------+ +| ts | ++-------------------------+ +| 1970-01-01T00:00:00.001 | +| 1970-01-01T00:00:00.002 | ++-------------------------+ + +SELECT ts FROM json2_fulltext_chinese_bloom WHERE matches_term(lower(ordinary), 'error') ORDER BY ts; + ++-------------------------+ +| ts | ++-------------------------+ +| 1970-01-01T00:00:00.001 | +| 1970-01-01T00:00:00.002 | ++-------------------------+ + +DROP TABLE json2_fulltext_chinese_bloom; + +Affected Rows: 0 + +CREATE TABLE json2_fulltext_chinese_tantivy ( + ts TIMESTAMP TIME INDEX, + j JSON2(text STRING FULLTEXT INDEX WITH (backend='tantivy', analyzer='Chinese', case_sensitive='true')), + ordinary STRING FULLTEXT INDEX WITH (backend='tantivy', analyzer='Chinese', case_sensitive='true') +) WITH ('append_mode'='true'); + +Affected Rows: 0 + +INSERT INTO json2_fulltext_chinese_tantivy VALUES + (1, '{"text":"错误 日志 ERROR"}', '错误 日志 ERROR'), + (2, '{"text":"正常 日志 error"}', '正常 日志 error'); + +Affected Rows: 2 + +ADMIN FLUSH_TABLE('json2_fulltext_chinese_tantivy'); + ++-----------------------------------------------------+ +| ADMIN FLUSH_TABLE('json2_fulltext_chinese_tantivy') | ++-----------------------------------------------------+ +| 0 | ++-----------------------------------------------------+ + +SELECT ts FROM json2_fulltext_chinese_tantivy WHERE matches(j.text, '错误') ORDER BY ts; + ++-------------------------+ +| ts | ++-------------------------+ +| 1970-01-01T00:00:00.001 | ++-------------------------+ + +SELECT ts FROM json2_fulltext_chinese_tantivy WHERE matches(ordinary, '错误') ORDER BY ts; + ++-------------------------+ +| ts | ++-------------------------+ +| 1970-01-01T00:00:00.001 | ++-------------------------+ + +SELECT ts FROM json2_fulltext_chinese_tantivy WHERE matches(j.text, 'ERROR') ORDER BY ts; + ++-------------------------+ +| ts | ++-------------------------+ +| 1970-01-01T00:00:00.001 | ++-------------------------+ + +SELECT ts FROM json2_fulltext_chinese_tantivy WHERE matches(ordinary, 'ERROR') ORDER BY ts; + ++-------------------------+ +| ts | ++-------------------------+ +| 1970-01-01T00:00:00.001 | ++-------------------------+ + +SELECT ts FROM json2_fulltext_chinese_tantivy WHERE matches_term(lower(j.text), 'error') ORDER BY ts; + ++-------------------------+ +| ts | ++-------------------------+ +| 1970-01-01T00:00:00.001 | +| 1970-01-01T00:00:00.002 | ++-------------------------+ + +SELECT ts FROM json2_fulltext_chinese_tantivy WHERE matches_term(lower(ordinary), 'error') ORDER BY ts; + ++-------------------------+ +| ts | ++-------------------------+ +| 1970-01-01T00:00:00.001 | +| 1970-01-01T00:00:00.002 | ++-------------------------+ + +DROP TABLE json2_fulltext_chinese_tantivy; + +Affected Rows: 0 + +-- Old SSTs, hint changes, restart, and backend changes. +CREATE TABLE json2_fulltext_evolution (ts TIMESTAMP TIME INDEX, j JSON2(max_auto_expanded_paths=0)) WITH ('append_mode'='true'); + +Affected Rows: 0 + +INSERT INTO json2_fulltext_evolution VALUES (1, '{"message":"error old"}'); + +Affected Rows: 1 + +ADMIN FLUSH_TABLE('json2_fulltext_evolution'); + ++-----------------------------------------------+ +| ADMIN FLUSH_TABLE('json2_fulltext_evolution') | ++-----------------------------------------------+ +| 0 | ++-----------------------------------------------+ + +ALTER TABLE json2_fulltext_evolution MODIFY COLUMN j JSON2(max_auto_expanded_paths=0, message STRING FULLTEXT INDEX WITH (granularity='1')); + +Affected Rows: 0 + +INSERT INTO json2_fulltext_evolution VALUES (2, '{"message":"error new"}'); + +Affected Rows: 1 + +ADMIN FLUSH_TABLE('json2_fulltext_evolution'); + ++-----------------------------------------------+ +| ADMIN FLUSH_TABLE('json2_fulltext_evolution') | ++-----------------------------------------------+ +| 0 | ++-----------------------------------------------+ + +SELECT ts FROM json2_fulltext_evolution WHERE matches_term(j.message, 'error') ORDER BY ts; + ++-------------------------+ +| ts | ++-------------------------+ +| 1970-01-01T00:00:00.001 | +| 1970-01-01T00:00:00.002 | ++-------------------------+ + +ALTER TABLE json2_fulltext_evolution MODIFY COLUMN j JSON2(max_auto_expanded_paths=0, message STRING FULLTEXT INDEX WITH (backend='tantivy', analyzer='Chinese', case_sensitive='true')); + +Affected Rows: 0 + +INSERT INTO json2_fulltext_evolution VALUES (3, '{"message":"错误 日志 error"}'); + +Affected Rows: 1 + +ADMIN FLUSH_TABLE('json2_fulltext_evolution'); + ++-----------------------------------------------+ +| ADMIN FLUSH_TABLE('json2_fulltext_evolution') | ++-----------------------------------------------+ +| 0 | ++-----------------------------------------------+ + +SELECT ts FROM json2_fulltext_evolution WHERE matches_term(j.message, 'error') ORDER BY ts; + ++-------------------------+ +| ts | ++-------------------------+ +| 1970-01-01T00:00:00.001 | +| 1970-01-01T00:00:00.002 | +| 1970-01-01T00:00:00.003 | ++-------------------------+ + +-- SQLNESS ARG restart=true +SHOW CREATE TABLE json2_fulltext_evolution; + ++--------------------------+---------------------------------------------------------------------------------------------------------------+ +| Table | Create Table | ++--------------------------+---------------------------------------------------------------------------------------------------------------+ +| json2_fulltext_evolution | CREATE TABLE IF NOT EXISTS "json2_fulltext_evolution" ( | +| | "ts" TIMESTAMP(3) NOT NULL, | +| | "j" JSON2( | +| | max_auto_expanded_paths = 0, | +| | "message" STRING FULLTEXT INDEX WITH (analyzer = 'Chinese', case_sensitive = 'true', backend = 'tantivy') | +| | ) NULL, | +| | TIME INDEX ("ts") | +| | ) | +| | | +| | ENGINE=mito | +| | WITH( | +| | append_mode = 'true' | +| | ) | ++--------------------------+---------------------------------------------------------------------------------------------------------------+ + +SELECT ts FROM json2_fulltext_evolution WHERE matches_term(j.message, 'error') ORDER BY ts; + ++-------------------------+ +| ts | ++-------------------------+ +| 1970-01-01T00:00:00.001 | +| 1970-01-01T00:00:00.002 | +| 1970-01-01T00:00:00.003 | ++-------------------------+ + +ADMIN COMPACT_TABLE('json2_fulltext_evolution', 'swcs', '86400'); + ++------------------------------------------------------------------+ +| ADMIN COMPACT_TABLE('json2_fulltext_evolution', 'swcs', '86400') | ++------------------------------------------------------------------+ +| 0 | ++------------------------------------------------------------------+ + +SELECT ts FROM json2_fulltext_evolution WHERE matches_term(j.message, 'error') ORDER BY ts; + ++-------------------------+ +| ts | ++-------------------------+ +| 1970-01-01T00:00:00.001 | +| 1970-01-01T00:00:00.002 | +| 1970-01-01T00:00:00.003 | ++-------------------------+ + +ALTER TABLE json2_fulltext_evolution MODIFY COLUMN j JSON2(max_auto_expanded_paths=0, message BIGINT); + +Affected Rows: 0 + +SELECT COUNT(*) FROM json2_fulltext_evolution; + ++----------+ +| count(*) | ++----------+ +| 3 | ++----------+ + +DROP TABLE json2_fulltext_evolution; + +Affected Rows: 0 + diff --git a/tests/cases/standalone/common/types/json/json2_fulltext_index.sql b/tests/cases/standalone/common/types/json/json2_fulltext_index.sql new file mode 100644 index 00000000000..a896d76b735 --- /dev/null +++ b/tests/cases/standalone/common/types/json/json2_fulltext_index.sql @@ -0,0 +1,233 @@ +-- Compare JSON paths with an ordinary column using the same fulltext backend. +CREATE TABLE json2_fulltext_bloom ( + ts TIMESTAMP TIME INDEX, + attrs JSON2 (max_auto_expanded_paths=0, + nested.message STRING FULLTEXT INDEX WITH (backend='bloom', analyzer='English', case_sensitive='false', granularity='1') SKIPPING INDEX INVERTED INDEX, + "nested.message" STRING FULLTEXT INDEX WITH (backend='bloom', analyzer='English', case_sensitive='false', granularity='1')), + ordinary STRING FULLTEXT INDEX WITH (backend='bloom', analyzer='English', case_sensitive='false', granularity='1') +) WITH ('append_mode'='true', 'sst_format'='flat'); +SHOW CREATE TABLE json2_fulltext_bloom; +INSERT INTO json2_fulltext_bloom VALUES + (1, '{"nested":{"message":"error timeout"},"nested.message":"healthy"}', 'error timeout'), + (2, '{"nested":{"message":"healthy"},"nested.message":"error timeout"}', 'healthy'), + (3, '{"nested":{"message":"ERROR retry"}}', 'ERROR retry'), + (4, '{}', NULL), (5, NULL, NULL), + (6, '{"nested":{"message":""}}', ''); +ADMIN FLUSH_TABLE('json2_fulltext_bloom'); +SELECT ts FROM json2_fulltext_bloom WHERE matches_term(attrs.nested.message, 'error') ORDER BY ts; +SELECT ts FROM json2_fulltext_bloom WHERE matches_term(ordinary, 'error') ORDER BY ts; +-- Combine fulltext predicates with inverted/skipping equality predicates. +SELECT ts FROM json2_fulltext_bloom WHERE matches_term(attrs.nested.message, 'error') AND attrs.nested.message = 'error timeout' ORDER BY ts; +SELECT ts FROM json2_fulltext_bloom WHERE matches_term(json_get(attrs, '$."nested.message"'), 'error') AND attrs.nested.message = 'healthy' ORDER BY ts; +SELECT ts FROM json2_fulltext_bloom WHERE matches_term(json_get(attrs, '$."nested.message"'), 'error') ORDER BY ts; +SELECT ts FROM json2_fulltext_bloom WHERE attrs.nested.message IS NULL ORDER BY ts; +SELECT ts FROM json2_fulltext_bloom WHERE matches_term(attrs.nested.message, 'error') OR matches_term(json_get(attrs, '$."nested.message"'), 'error') ORDER BY ts; +SELECT ts FROM json2_fulltext_bloom WHERE matches_term(lower(attrs.nested.message), 'error') ORDER BY ts; +SELECT ts FROM json2_fulltext_bloom WHERE attrs.nested.message LIKE '%error timeout%' ORDER BY ts; +SELECT ts FROM json2_fulltext_bloom WHERE ordinary LIKE '%error timeout%' ORDER BY ts; + +-- SQLNESS REPLACE "metrics_per_partition":.*("rows_fulltext_filtered":\d+).*metrics= "metrics_per_partition":{$1} metrics= +-- SQLNESS REPLACE "metrics_per_partition":\s*\[.*metrics= "metrics_per_partition":REDACTED metrics= +-- SQLNESS REPLACE (metrics=\{.*\}) metrics=REDACTED +-- SQLNESS REPLACE (metrics=\[[^\]]*\]) metrics=REDACTED +-- SQLNESS REPLACE (RoundRobinBatch.*) REDACTED +-- SQLNESS REPLACE (-+) - +-- SQLNESS REPLACE (\s\s+) _ +-- SQLNESS REPLACE "(file_id|time_range_start|time_range_end)":"[^"]+" "$1":"REDACTED" +-- SQLNESS REPLACE ("[a-z_]+":"[0-9\.]+(ns|us|µs|ms|s)") "DURATION": REDACTED +-- SQLNESS REPLACE "(size|flat_format)":\s*(\d+|true|false) "$1":REDACTED +-- SQLNESS REPLACE ,\s*filter=.*?metrics= metrics= +-- SQLNESS REPLACE Total\s+rows:\s+\d+ Total rows: REDACTED +-- SQLNESS REPLACE (peers.*) REDACTED +-- SQLNESS REPLACE region=\d+\(\d+,\s+\d+\) region=REDACTED +-- SQLNESS REPLACE ,\s"dyn_filters":\s\[.* REDACTED +-- SQLNESS REPLACE "index_size":\d+ "index_size":REDACTED +-- SQLNESS REPLACE "max_part_range":\s*\{[^}]*\} "max_part_range":REDACTED +EXPLAIN ANALYZE VERBOSE SELECT ts FROM json2_fulltext_bloom WHERE matches_term(attrs.nested.message, 'absenttoken'); + +-- SQLNESS REPLACE "metrics_per_partition":.*("rows_fulltext_filtered":\d+).*metrics= "metrics_per_partition":{$1} metrics= +-- SQLNESS REPLACE "metrics_per_partition":\s*\[.*metrics= "metrics_per_partition":REDACTED metrics= +-- SQLNESS REPLACE (metrics=\{.*\}) metrics=REDACTED +-- SQLNESS REPLACE (metrics=\[[^\]]*\]) metrics=REDACTED +-- SQLNESS REPLACE (RoundRobinBatch.*) REDACTED +-- SQLNESS REPLACE (-+) - +-- SQLNESS REPLACE (\s\s+) _ +-- SQLNESS REPLACE "(file_id|time_range_start|time_range_end)":"[^"]+" "$1":"REDACTED" +-- SQLNESS REPLACE ("[a-z_]+":"[0-9\.]+(ns|us|µs|ms|s)") "DURATION": REDACTED +-- SQLNESS REPLACE "(size|flat_format)":\s*(\d+|true|false) "$1":REDACTED +-- SQLNESS REPLACE ,\s*filter=.*?metrics= metrics= +-- SQLNESS REPLACE Total\s+rows:\s+\d+ Total rows: REDACTED +-- SQLNESS REPLACE (peers.*) REDACTED +-- SQLNESS REPLACE region=\d+\(\d+,\s+\d+\) region=REDACTED +-- SQLNESS REPLACE ,\s"dyn_filters":\s\[.* REDACTED +-- SQLNESS REPLACE "index_size":\d+ "index_size":REDACTED +-- SQLNESS REPLACE "max_part_range":\s*\{[^}]*\} "max_part_range":REDACTED +EXPLAIN ANALYZE VERBOSE SELECT ts FROM json2_fulltext_bloom WHERE matches_term(attrs.nested.message, 'absenttoken'); +INSERT INTO json2_fulltext_bloom VALUES (7, '{"nested":{"message":"error extra"}}', 'error extra'); +ADMIN FLUSH_TABLE('json2_fulltext_bloom'); +ADMIN COMPACT_TABLE('json2_fulltext_bloom', 'swcs', '86400'); +SELECT ts FROM json2_fulltext_bloom WHERE matches_term(attrs.nested.message, 'error') ORDER BY ts; +-- SQLNESS REPLACE "metrics_per_partition":.*("rows_fulltext_filtered":\d+).*metrics= "metrics_per_partition":{$1} metrics= +-- SQLNESS REPLACE "metrics_per_partition":\s*\[.*metrics= "metrics_per_partition":REDACTED metrics= +-- SQLNESS REPLACE (metrics=\{.*\}) metrics=REDACTED +-- SQLNESS REPLACE (metrics=\[[^\]]*\]) metrics=REDACTED +-- SQLNESS REPLACE (RoundRobinBatch.*) REDACTED +-- SQLNESS REPLACE (-+) - +-- SQLNESS REPLACE (\s\s+) _ +-- SQLNESS REPLACE "(file_id|time_range_start|time_range_end)":"[^"]+" "$1":"REDACTED" +-- SQLNESS REPLACE ("[a-z_]+":"[0-9\.]+(ns|us|µs|ms|s)") "DURATION": REDACTED +-- SQLNESS REPLACE "(size|flat_format)":\s*(\d+|true|false) "$1":REDACTED +-- SQLNESS REPLACE ,\s*filter=.*?metrics= metrics= +-- SQLNESS REPLACE Total\s+rows:\s+\d+ Total rows: REDACTED +-- SQLNESS REPLACE (peers.*) REDACTED +-- SQLNESS REPLACE region=\d+\(\d+,\s+\d+\) region=REDACTED +-- SQLNESS REPLACE ,\s"dyn_filters":\s\[.* REDACTED +-- SQLNESS REPLACE "index_size":\d+ "index_size":REDACTED +-- SQLNESS REPLACE "max_part_range":\s*\{[^}]*\} "max_part_range":REDACTED +EXPLAIN ANALYZE VERBOSE SELECT ts FROM json2_fulltext_bloom WHERE matches_term(attrs.nested.message, 'absenttoken'); +ALTER TABLE json2_fulltext_bloom MODIFY COLUMN attrs JSON2(max_auto_expanded_paths=0, nested.message STRING, "nested.message" STRING); +SELECT ts FROM json2_fulltext_bloom WHERE matches_term(attrs.nested.message, 'error') ORDER BY ts; +DROP TABLE json2_fulltext_bloom; + +-- Compare JSON paths with an ordinary column using the same fulltext backend. +CREATE TABLE json2_fulltext_tantivy ( + ts TIMESTAMP TIME INDEX, + attrs JSON2 (max_auto_expanded_paths=0, + nested.message STRING FULLTEXT INDEX WITH (backend='tantivy', analyzer='English', case_sensitive='false') SKIPPING INDEX INVERTED INDEX, + "nested.message" STRING FULLTEXT INDEX WITH (backend='tantivy', analyzer='English', case_sensitive='false')), + ordinary STRING FULLTEXT INDEX WITH (backend='tantivy', analyzer='English', case_sensitive='false') +) WITH ('append_mode'='true', 'sst_format'='flat'); +SHOW CREATE TABLE json2_fulltext_tantivy; +INSERT INTO json2_fulltext_tantivy VALUES + (1, '{"nested":{"message":"error timeout"},"nested.message":"healthy"}', 'error timeout'), + (2, '{"nested":{"message":"healthy"},"nested.message":"error timeout"}', 'healthy'), + (3, '{"nested":{"message":"ERROR retry"}}', 'ERROR retry'), + (4, '{}', NULL), (5, NULL, NULL), + (6, '{"nested":{"message":""}}', ''); +ADMIN FLUSH_TABLE('json2_fulltext_tantivy'); +SELECT ts FROM json2_fulltext_tantivy WHERE matches(attrs.nested.message, 'error') ORDER BY ts; +SELECT ts FROM json2_fulltext_tantivy WHERE matches(ordinary, 'error') ORDER BY ts; +-- Combine fulltext predicates with inverted/skipping equality predicates. +SELECT ts FROM json2_fulltext_tantivy WHERE matches(attrs.nested.message, 'error') AND attrs.nested.message = 'error timeout' ORDER BY ts; +SELECT ts FROM json2_fulltext_tantivy WHERE matches(json_get(attrs, '$."nested.message"'), 'error') AND attrs.nested.message = 'healthy' ORDER BY ts; +SELECT ts FROM json2_fulltext_tantivy WHERE matches(json_get(attrs, '$."nested.message"'), 'error') ORDER BY ts; +SELECT ts FROM json2_fulltext_tantivy WHERE attrs.nested.message IS NULL ORDER BY ts; +SELECT ts FROM json2_fulltext_tantivy WHERE matches(attrs.nested.message, 'error') OR matches(json_get(attrs, '$."nested.message"'), 'error') ORDER BY ts; + +-- SQLNESS REPLACE "metrics_per_partition":.*("rows_fulltext_filtered":\d+).*metrics= "metrics_per_partition":{$1} metrics= +-- SQLNESS REPLACE "metrics_per_partition":\s*\[.*metrics= "metrics_per_partition":REDACTED metrics= +-- SQLNESS REPLACE (metrics=\{.*\}) metrics=REDACTED +-- SQLNESS REPLACE (metrics=\[[^\]]*\]) metrics=REDACTED +-- SQLNESS REPLACE (RoundRobinBatch.*) REDACTED +-- SQLNESS REPLACE (-+) - +-- SQLNESS REPLACE (\s\s+) _ +-- SQLNESS REPLACE "(file_id|time_range_start|time_range_end)":"[^"]+" "$1":"REDACTED" +-- SQLNESS REPLACE ("[a-z_]+":"[0-9\.]+(ns|us|µs|ms|s)") "DURATION": REDACTED +-- SQLNESS REPLACE "(size|flat_format)":\s*(\d+|true|false) "$1":REDACTED +-- SQLNESS REPLACE ,\s*filter=.*?metrics= metrics= +-- SQLNESS REPLACE Total\s+rows:\s+\d+ Total rows: REDACTED +-- SQLNESS REPLACE (peers.*) REDACTED +-- SQLNESS REPLACE region=\d+\(\d+,\s+\d+\) region=REDACTED +-- SQLNESS REPLACE ,\s"dyn_filters":\s\[.* REDACTED +-- SQLNESS REPLACE "index_size":\d+ "index_size":REDACTED +-- SQLNESS REPLACE "max_part_range":\s*\{[^}]*\} "max_part_range":REDACTED +EXPLAIN ANALYZE VERBOSE SELECT ts FROM json2_fulltext_tantivy WHERE matches(attrs.nested.message, 'absenttoken'); + +-- SQLNESS REPLACE "metrics_per_partition":.*("rows_fulltext_filtered":\d+).*metrics= "metrics_per_partition":{$1} metrics= +-- SQLNESS REPLACE "metrics_per_partition":\s*\[.*metrics= "metrics_per_partition":REDACTED metrics= +-- SQLNESS REPLACE (metrics=\{.*\}) metrics=REDACTED +-- SQLNESS REPLACE (metrics=\[[^\]]*\]) metrics=REDACTED +-- SQLNESS REPLACE (RoundRobinBatch.*) REDACTED +-- SQLNESS REPLACE (-+) - +-- SQLNESS REPLACE (\s\s+) _ +-- SQLNESS REPLACE "(file_id|time_range_start|time_range_end)":"[^"]+" "$1":"REDACTED" +-- SQLNESS REPLACE ("[a-z_]+":"[0-9\.]+(ns|us|µs|ms|s)") "DURATION": REDACTED +-- SQLNESS REPLACE "(size|flat_format)":\s*(\d+|true|false) "$1":REDACTED +-- SQLNESS REPLACE ,\s*filter=.*?metrics= metrics= +-- SQLNESS REPLACE Total\s+rows:\s+\d+ Total rows: REDACTED +-- SQLNESS REPLACE (peers.*) REDACTED +-- SQLNESS REPLACE region=\d+\(\d+,\s+\d+\) region=REDACTED +-- SQLNESS REPLACE ,\s"dyn_filters":\s\[.* REDACTED +-- SQLNESS REPLACE "index_size":\d+ "index_size":REDACTED +-- SQLNESS REPLACE "max_part_range":\s*\{[^}]*\} "max_part_range":REDACTED +EXPLAIN ANALYZE VERBOSE SELECT ts FROM json2_fulltext_tantivy WHERE matches(attrs.nested.message, 'absenttoken'); +INSERT INTO json2_fulltext_tantivy VALUES (7, '{"nested":{"message":"error extra"}}', 'error extra'); +ADMIN FLUSH_TABLE('json2_fulltext_tantivy'); +ADMIN COMPACT_TABLE('json2_fulltext_tantivy', 'swcs', '86400'); +SELECT ts FROM json2_fulltext_tantivy WHERE matches(attrs.nested.message, 'error') ORDER BY ts; +-- SQLNESS REPLACE "metrics_per_partition":.*("rows_fulltext_filtered":\d+).*metrics= "metrics_per_partition":{$1} metrics= +-- SQLNESS REPLACE "metrics_per_partition":\s*\[.*metrics= "metrics_per_partition":REDACTED metrics= +-- SQLNESS REPLACE (metrics=\{.*\}) metrics=REDACTED +-- SQLNESS REPLACE (metrics=\[[^\]]*\]) metrics=REDACTED +-- SQLNESS REPLACE (RoundRobinBatch.*) REDACTED +-- SQLNESS REPLACE (-+) - +-- SQLNESS REPLACE (\s\s+) _ +-- SQLNESS REPLACE "(file_id|time_range_start|time_range_end)":"[^"]+" "$1":"REDACTED" +-- SQLNESS REPLACE ("[a-z_]+":"[0-9\.]+(ns|us|µs|ms|s)") "DURATION": REDACTED +-- SQLNESS REPLACE "(size|flat_format)":\s*(\d+|true|false) "$1":REDACTED +-- SQLNESS REPLACE ,\s*filter=.*?metrics= metrics= +-- SQLNESS REPLACE Total\s+rows:\s+\d+ Total rows: REDACTED +-- SQLNESS REPLACE (peers.*) REDACTED +-- SQLNESS REPLACE region=\d+\(\d+,\s+\d+\) region=REDACTED +-- SQLNESS REPLACE ,\s"dyn_filters":\s\[.* REDACTED +-- SQLNESS REPLACE "index_size":\d+ "index_size":REDACTED +-- SQLNESS REPLACE "max_part_range":\s*\{[^}]*\} "max_part_range":REDACTED +EXPLAIN ANALYZE VERBOSE SELECT ts FROM json2_fulltext_tantivy WHERE matches(attrs.nested.message, 'absenttoken'); +ALTER TABLE json2_fulltext_tantivy MODIFY COLUMN attrs JSON2(max_auto_expanded_paths=0, nested.message STRING, "nested.message" STRING); +SELECT ts FROM json2_fulltext_tantivy WHERE matches(attrs.nested.message, 'error') ORDER BY ts; +DROP TABLE json2_fulltext_tantivy; + +CREATE TABLE json2_fulltext_chinese_bloom ( + ts TIMESTAMP TIME INDEX, + j JSON2(text STRING FULLTEXT INDEX WITH (backend='bloom', analyzer='Chinese', case_sensitive='true', granularity='1')), + ordinary STRING FULLTEXT INDEX WITH (backend='bloom', analyzer='Chinese', case_sensitive='true', granularity='1') +) WITH ('append_mode'='true'); +INSERT INTO json2_fulltext_chinese_bloom VALUES + (1, '{"text":"错误 日志 ERROR"}', '错误 日志 ERROR'), + (2, '{"text":"正常 日志 error"}', '正常 日志 error'); +ADMIN FLUSH_TABLE('json2_fulltext_chinese_bloom'); +SELECT ts FROM json2_fulltext_chinese_bloom WHERE matches_term(j.text, '错误') ORDER BY ts; +SELECT ts FROM json2_fulltext_chinese_bloom WHERE matches_term(ordinary, '错误') ORDER BY ts; +SELECT ts FROM json2_fulltext_chinese_bloom WHERE matches_term(j.text, 'ERROR') ORDER BY ts; +SELECT ts FROM json2_fulltext_chinese_bloom WHERE matches_term(ordinary, 'ERROR') ORDER BY ts; +SELECT ts FROM json2_fulltext_chinese_bloom WHERE matches_term(lower(j.text), 'error') ORDER BY ts; +SELECT ts FROM json2_fulltext_chinese_bloom WHERE matches_term(lower(ordinary), 'error') ORDER BY ts; +DROP TABLE json2_fulltext_chinese_bloom; + +CREATE TABLE json2_fulltext_chinese_tantivy ( + ts TIMESTAMP TIME INDEX, + j JSON2(text STRING FULLTEXT INDEX WITH (backend='tantivy', analyzer='Chinese', case_sensitive='true')), + ordinary STRING FULLTEXT INDEX WITH (backend='tantivy', analyzer='Chinese', case_sensitive='true') +) WITH ('append_mode'='true'); +INSERT INTO json2_fulltext_chinese_tantivy VALUES + (1, '{"text":"错误 日志 ERROR"}', '错误 日志 ERROR'), + (2, '{"text":"正常 日志 error"}', '正常 日志 error'); +ADMIN FLUSH_TABLE('json2_fulltext_chinese_tantivy'); +SELECT ts FROM json2_fulltext_chinese_tantivy WHERE matches(j.text, '错误') ORDER BY ts; +SELECT ts FROM json2_fulltext_chinese_tantivy WHERE matches(ordinary, '错误') ORDER BY ts; +SELECT ts FROM json2_fulltext_chinese_tantivy WHERE matches(j.text, 'ERROR') ORDER BY ts; +SELECT ts FROM json2_fulltext_chinese_tantivy WHERE matches(ordinary, 'ERROR') ORDER BY ts; +SELECT ts FROM json2_fulltext_chinese_tantivy WHERE matches_term(lower(j.text), 'error') ORDER BY ts; +SELECT ts FROM json2_fulltext_chinese_tantivy WHERE matches_term(lower(ordinary), 'error') ORDER BY ts; +DROP TABLE json2_fulltext_chinese_tantivy; + +-- Old SSTs, hint changes, restart, and backend changes. +CREATE TABLE json2_fulltext_evolution (ts TIMESTAMP TIME INDEX, j JSON2(max_auto_expanded_paths=0)) WITH ('append_mode'='true'); +INSERT INTO json2_fulltext_evolution VALUES (1, '{"message":"error old"}'); +ADMIN FLUSH_TABLE('json2_fulltext_evolution'); +ALTER TABLE json2_fulltext_evolution MODIFY COLUMN j JSON2(max_auto_expanded_paths=0, message STRING FULLTEXT INDEX WITH (granularity='1')); +INSERT INTO json2_fulltext_evolution VALUES (2, '{"message":"error new"}'); +ADMIN FLUSH_TABLE('json2_fulltext_evolution'); +SELECT ts FROM json2_fulltext_evolution WHERE matches_term(j.message, 'error') ORDER BY ts; +ALTER TABLE json2_fulltext_evolution MODIFY COLUMN j JSON2(max_auto_expanded_paths=0, message STRING FULLTEXT INDEX WITH (backend='tantivy', analyzer='Chinese', case_sensitive='true')); +INSERT INTO json2_fulltext_evolution VALUES (3, '{"message":"错误 日志 error"}'); +ADMIN FLUSH_TABLE('json2_fulltext_evolution'); +SELECT ts FROM json2_fulltext_evolution WHERE matches_term(j.message, 'error') ORDER BY ts; +-- SQLNESS ARG restart=true +SHOW CREATE TABLE json2_fulltext_evolution; +SELECT ts FROM json2_fulltext_evolution WHERE matches_term(j.message, 'error') ORDER BY ts; +ADMIN COMPACT_TABLE('json2_fulltext_evolution', 'swcs', '86400'); +SELECT ts FROM json2_fulltext_evolution WHERE matches_term(j.message, 'error') ORDER BY ts; +ALTER TABLE json2_fulltext_evolution MODIFY COLUMN j JSON2(max_auto_expanded_paths=0, message BIGINT); +SELECT COUNT(*) FROM json2_fulltext_evolution; +DROP TABLE json2_fulltext_evolution; diff --git a/tests/cases/standalone/common/types/json/json2_inverted_index.result b/tests/cases/standalone/common/types/json/json2_inverted_index.result index 8d9ee9c3ece..dddc7c405d6 100644 --- a/tests/cases/standalone/common/types/json/json2_inverted_index.result +++ b/tests/cases/standalone/common/types/json/json2_inverted_index.result @@ -136,11 +136,3 @@ CREATE TABLE json2_inverted_invalid ( Error: 2000(InvalidSyntax), Invalid SQL, error: unsupported JSON2 type hint data type: TIMESTAMP; supported types: STRING, BIGINT, BIGINT UNSIGNED, DOUBLE, BOOLEAN; supported aliases: INT64, UINT64, FLOAT64 --- JSON hints do not support fulltext indexes. -CREATE TABLE json2_inverted_invalid ( - ts TIMESTAMP TIME INDEX, - attrs JSON2 (message STRING FULLTEXT INDEX) -); - -Error: 2000(InvalidSyntax), Invalid SQL syntax: sql parser error: Expected: JSON2 type hint option, found: FULLTEXT at Line: 3, Column: 33 - diff --git a/tests/cases/standalone/common/types/json/json2_inverted_index.sql b/tests/cases/standalone/common/types/json/json2_inverted_index.sql index aad6e414cdd..fdc9e8530d9 100644 --- a/tests/cases/standalone/common/types/json/json2_inverted_index.sql +++ b/tests/cases/standalone/common/types/json/json2_inverted_index.sql @@ -65,9 +65,3 @@ CREATE TABLE json2_inverted_invalid ( ts TIMESTAMP TIME INDEX, attrs JSON2 (event_time TIMESTAMP INVERTED INDEX) ); - --- JSON hints do not support fulltext indexes. -CREATE TABLE json2_inverted_invalid ( - ts TIMESTAMP TIME INDEX, - attrs JSON2 (message STRING FULLTEXT INDEX) -); diff --git a/tests/cases/standalone/common/view/create.result b/tests/cases/standalone/common/view/create.result index e8c53070189..ee2e984bb27 100644 --- a/tests/cases/standalone/common/view/create.result +++ b/tests/cases/standalone/common/view/create.result @@ -105,6 +105,7 @@ ORDER BY TABLE_NAME, TABLE_TYPE; |greptime|information_schema|column_privileges|LOCALTEMPORARY|ID|ID|ID|ID|ID|ID||ID|Fixed|ID|ID|ID|DATETIME|DATETIME||utf8_bin|ID|greptime.semantic.table_scope=global||Y| |greptime|information_schema|column_statistics|LOCALTEMPORARY|ID|ID|ID|ID|ID|ID||ID|Fixed|ID|ID|ID|DATETIME|DATETIME||utf8_bin|ID|greptime.semantic.table_scope=global||Y| |greptime|information_schema|columns|LOCALTEMPORARY|ID|ID|ID|ID|ID|ID||ID|Fixed|ID|ID|ID|DATETIME|DATETIME||utf8_bin|ID|greptime.semantic.table_scope=catalog||Y| +|greptime|information_schema|compaction_tasks|LOCALTEMPORARY|ID|ID|ID|ID|ID|ID||ID|Fixed|ID|ID|ID|DATETIME|DATETIME||utf8_bin|ID|greptime.semantic.table_scope=global||Y| |greptime|information_schema|engines|LOCALTEMPORARY|ID|ID|ID|ID|ID|ID||ID|Fixed|ID|ID|ID|DATETIME|DATETIME||utf8_bin|ID|greptime.semantic.table_scope=public_global||Y| |greptime|information_schema|events|LOCALTEMPORARY|ID|ID|ID|ID|ID|ID||ID|Fixed|ID|ID|ID|DATETIME|DATETIME||utf8_bin|ID|greptime.semantic.table_scope=global||Y| |greptime|information_schema|files|LOCALTEMPORARY|ID|ID|ID|ID|ID|ID||ID|Fixed|ID|ID|ID|DATETIME|DATETIME||utf8_bin|ID|greptime.semantic.table_scope=global||Y| diff --git a/tests/cases/standalone/optimizer/join_filter_pushdown_edge.result b/tests/cases/standalone/optimizer/join_filter_pushdown_edge.result index c9b1f37c9ad..b67375a033e 100644 --- a/tests/cases/standalone/optimizer/join_filter_pushdown_edge.result +++ b/tests/cases/standalone/optimizer/join_filter_pushdown_edge.result @@ -90,47 +90,44 @@ EXPLAIN SELECT f.k, f.val FROM fact f AND f.val > 1.0 AND EXISTS (SELECT 1 FROM vals v WHERE v.x = CAST(f.val AS INT)); -+---------------+---------------------------------------------------------------------------------------------------------------------------------------------------------+ -| plan_type | plan | -+---------------+---------------------------------------------------------------------------------------------------------------------------------------------------------+ -| logical_plan | LeftSemi Join: CAST(f.val AS Int32) = __correlated_sq_1.x | -| | Projection: f.k, f.val | -| | Left Join: f.k = d.k | -| | Projection: f.k, f.val | -| | MergeScan [is_placeholder=false, remote_input=[ | -| | SubqueryAlias: f | -| | Filter: CAST(fact.val AS Int32) IS NOT NULL AND fact.ts >= TimestampMillisecond(1706572800000, None) AND fact.val > Float64(1) | -| | TableScan: fact, partial_filters=[CAST(fact.val AS Int32) IS NOT NULL, fact.ts >= TimestampMillisecond(1706572800000, None), fact.val > Float64(1)] | -| | ]] | -| | Projection: d.k | -| | MergeScan [is_placeholder=false, remote_input=[ | -| | SubqueryAlias: d | -| | Filter: dim.k IS NOT NULL | -| | TableScan: dim, partial_filters=[dim.k IS NOT NULL] | -| | ]] | -| | Projection: __correlated_sq_1.x | -| | MergeScan [is_placeholder=false, remote_input=[ | -| | SubqueryAlias: __correlated_sq_1 | -| | Projection: Int64(1), v.x | -| | SubqueryAlias: v | -| | Filter: vals.x IS NOT NULL | -| | TableScan: vals, partial_filters=[vals.x IS NOT NULL] | -| | ]] | -| physical_plan | HashJoinExec: mode=Partitioned, join_type=LeftSemi, on=[(CAST(f.val AS Int32)@2, x@0)], projection=[k@0, val@1] | ++---------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------+ +| plan_type | plan | ++---------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------+ +| logical_plan | LeftSemi Join: CAST(f.val AS Int32) = __correlated_sq_1.x | +| | Projection: f.k, f.val | +| | Left Join: f.k = d.k | +| | MergeScan [is_placeholder=false, remote_input=[ | +| | Projection: f.k, f.val | +| | SubqueryAlias: f | +| | Filter: CAST(fact.val AS Int32) IS NOT NULL AND fact.ts >= TimestampMillisecond(1706572800000, None) AND fact.val > Float64(1) | +| | TableScan: fact, partial_filters=[CAST(fact.val AS Int32) IS NOT NULL, fact.ts >= TimestampMillisecond(1706572800000, None), fact.val > Float64(1)] | +| | ]] | +| | MergeScan [is_placeholder=false, remote_input=[ | +| | Projection: d.k | +| | SubqueryAlias: d | +| | Filter: dim.k IS NOT NULL | +| | TableScan: dim, partial_filters=[dim.k IS NOT NULL] | +| | ]] | +| | MergeScan [is_placeholder=false, remote_input=[ | +| | Projection: __correlated_sq_1.x | +| | SubqueryAlias: __correlated_sq_1 | +| | Projection: Int64(1), v.x | +| | SubqueryAlias: v | +| | Filter: vals.x IS NOT NULL | +| | TableScan: vals, partial_filters=[vals.x IS NOT NULL] | +| | ]] | +| physical_plan | HashJoinExec: mode=Partitioned, join_type=LeftSemi, on=[(CAST(f.val AS Int32)@2, x@0)], projection=[k@0, val@1] | | | RepartitionExec: partitioning=Hash([REDACTED -| | ProjectionExec: expr=[k@0 as k, val@1 as val, CAST(val@1 AS Int32) as CAST(f.val AS Int32)] | -| | HashJoinExec: mode=Partitioned, join_type=Left, on=[(k@0, k@0)], projection=[k@0, val@1] | +| | ProjectionExec: expr=[k@0 as k, val@1 as val, CAST(val@1 AS Int32) as CAST(f.val AS Int32)] | +| | HashJoinExec: mode=Partitioned, join_type=Left, on=[(k@0, k@0)], projection=[k@0, val@1] | | | RepartitionExec: partitioning=Hash([REDACTED -| | ProjectionExec: expr=[k@1 as k, val@2 as val] | -| | MergeScanExec: REDACTED +| | MergeScanExec: REDACTED | | RepartitionExec: partitioning=Hash([REDACTED -| | ProjectionExec: expr=[k@1 as k] | -| | MergeScanExec: REDACTED +| | MergeScanExec: REDACTED | | RepartitionExec: partitioning=Hash([REDACTED -| | ProjectionExec: expr=[x@1 as x] | -| | MergeScanExec: REDACTED -| | | -+---------------+---------------------------------------------------------------------------------------------------------------------------------------------------------+ +| | MergeScanExec: REDACTED +| | | ++---------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------+ SELECT f.k, f.val, d.label FROM fact f LEFT JOIN dim d ON f.k = d.k diff --git a/tests/cases/standalone/optimizer/lateral_join_guard.result b/tests/cases/standalone/optimizer/lateral_join_guard.result index d2a565089e3..9f78657e6a6 100644 --- a/tests/cases/standalone/optimizer/lateral_join_guard.result +++ b/tests/cases/standalone/optimizer/lateral_join_guard.result @@ -67,11 +67,11 @@ ORDER BY f.k; | logical_plan | Sort: f.k ASC NULLS LAST | | | Projection: f.k, d.threshold | | | Inner Join: f.k = d.k Filter: f.val > d.threshold | -| | Projection: f.k, f.val | -| | MergeScan [is_placeholder=false, remote_input=[ | -| | SubqueryAlias: f | -| | Filter: lateral_fact.k IS NOT NULL | -| | TableScan: lateral_fact, partial_filters=[lateral_fact.k IS NOT NULL] | +| | MergeScan [is_placeholder=false, remote_input=[ | +| | Projection: f.k, f.val | +| | SubqueryAlias: f | +| | Filter: lateral_fact.k IS NOT NULL | +| | TableScan: lateral_fact, partial_filters=[lateral_fact.k IS NOT NULL] | | | ]] | | | MergeScan [is_placeholder=false, remote_input=[ | | | SubqueryAlias: d | @@ -84,8 +84,7 @@ ORDER BY f.k; | | SortExec: expr=[k@0 ASC NULLS LAST], preserve_partitioning=[true] | | | HashJoinExec: mode=Partitioned, join_type=Inner, on=[(k@0, k@1)], filter=val@0 > threshold@1, projection=[k@0, threshold@2] | | | RepartitionExec: partitioning=Hash([k@0], REDACTED), input_partitions=REDACTED| -| | ProjectionExec: expr=[k@1 as k, val@2 as val] | -| | MergeScanExec: REDACTED +| | MergeScanExec: REDACTED | | RepartitionExec: partitioning=Hash([k@1], REDACTED), input_partitions=REDACTED| | | MergeScanExec: REDACTED | | | diff --git a/tests/cases/standalone/optimizer/rewrite_set_comparison.result b/tests/cases/standalone/optimizer/rewrite_set_comparison.result index f7463099de2..af54de5a378 100644 --- a/tests/cases/standalone/optimizer/rewrite_set_comparison.result +++ b/tests/cases/standalone/optimizer/rewrite_set_comparison.result @@ -58,9 +58,9 @@ EXPLAIN SELECT v FROM sc_t WHERE v > ANY(SELECT v FROM sc_s) ORDER BY v; | | LeftMark Join: Filter: sc_t.v > __correlated_sq_2.v IS NULL | | | Filter: __correlated_sq_1.mark OR NOT __correlated_sq_1.mark AND Boolean(NULL) | | | LeftMark Join: Filter: sc_t.v > __correlated_sq_1.v IS TRUE | -| | Projection: sc_t.v | -| | MergeScan [is_placeholder=false, remote_input=[ | -| | TableScan: sc_t | +| | MergeScan [is_placeholder=false, remote_input=[ | +| | Projection: sc_t.v | +| | TableScan: sc_t | | | ]] | | | MergeScan [is_placeholder=false, remote_input=[ | | | Projection: __correlated_sq_1.v | @@ -81,8 +81,7 @@ EXPLAIN SELECT v FROM sc_t WHERE v > ANY(SELECT v FROM sc_s) ORDER BY v; | | CoalescePartitionsExec | | | FilterExec: mark@1 OR NOT mark@1 AND NULL | | | NestedLoopJoinExec: join_type=LeftMark, filter=(v@0 > v@1) IS NOT DISTINCT FROM true | -| | ProjectionExec: expr=[v@1 as v] | -| | MergeScanExec: REDACTED +| | MergeScanExec: REDACTED | | RepartitionExec: partitioning=RoundRobinBatch(4), input_partitions=1 | | | MergeScanExec: REDACTED | | RepartitionExec: partitioning=RoundRobinBatch(4), input_partitions=1 | @@ -113,9 +112,9 @@ EXPLAIN SELECT v FROM sc_t WHERE v != ALL(SELECT v FROM sc_s) ORDER BY v; | | Projection: sc_t.v | | | Filter: NOT __correlated_sq_1.mark | | | LeftMark Join: Filter: sc_t.v != __correlated_sq_1.v IS FALSE | -| | Projection: sc_t.v | -| | MergeScan [is_placeholder=false, remote_input=[ | -| | TableScan: sc_t | +| | MergeScan [is_placeholder=false, remote_input=[ | +| | Projection: sc_t.v | +| | TableScan: sc_t | | | ]] | | | MergeScan [is_placeholder=false, remote_input=[ | | | Projection: __correlated_sq_1.v | @@ -136,8 +135,7 @@ EXPLAIN SELECT v FROM sc_t WHERE v != ALL(SELECT v FROM sc_s) ORDER BY v; | | CoalescePartitionsExec | | | FilterExec: NOT mark@1, projection=[v@0] | | | NestedLoopJoinExec: join_type=LeftMark, filter=(v@0 != v@1) IS NOT DISTINCT FROM false | -| | ProjectionExec: expr=[v@1 as v] | -| | MergeScanExec: REDACTED +| | MergeScanExec: REDACTED | | RepartitionExec: partitioning=RoundRobinBatch(4), input_partitions=1 | | | MergeScanExec: REDACTED | | RepartitionExec: partitioning=RoundRobinBatch(4), input_partitions=1 | diff --git a/tests/cases/standalone/optimizer/scalar_subquery_prepass.result b/tests/cases/standalone/optimizer/scalar_subquery_prepass.result index 2ed894e016a..f1885e5491d 100644 --- a/tests/cases/standalone/optimizer/scalar_subquery_prepass.result +++ b/tests/cases/standalone/optimizer/scalar_subquery_prepass.result @@ -66,29 +66,27 @@ ORDER BY f.k; | logical_plan | Sort: f.k ASC NULLS LAST | | | Projection: f.k, f.val | | | Inner Join: f.k = __scalar_sq_1.k Filter: f.val > __scalar_sq_1.max(d.threshold) | -| | Projection: f.k, f.val | -| | MergeScan [is_placeholder=false, remote_input=[ | -| | SubqueryAlias: f | -| | TableScan: scalar_fact | +| | MergeScan [is_placeholder=false, remote_input=[ | +| | Projection: f.k, f.val | +| | SubqueryAlias: f | +| | TableScan: scalar_fact | | | ]] | -| | Projection: __scalar_sq_1.max(d.threshold), __scalar_sq_1.k | -| | MergeScan [is_placeholder=false, remote_input=[ | -| | SubqueryAlias: __scalar_sq_1 | -| | Projection: max(d.threshold), d.k, __always_true | -| | Aggregate: groupBy=[[d.k, Boolean(true) AS __always_true]], aggr=[[max(d.threshold)]] | -| | SubqueryAlias: d | -| | Filter: scalar_dim.k IS NOT NULL | -| | TableScan: scalar_dim, partial_filters=[scalar_dim.k IS NOT NULL] | +| | MergeScan [is_placeholder=false, remote_input=[ | +| | Projection: __scalar_sq_1.max(d.threshold), __scalar_sq_1.k | +| | SubqueryAlias: __scalar_sq_1 | +| | Projection: max(d.threshold), d.k, __always_true | +| | Aggregate: groupBy=[[d.k, Boolean(true) AS __always_true]], aggr=[[max(d.threshold)]] | +| | SubqueryAlias: d | +| | Filter: scalar_dim.k IS NOT NULL | +| | TableScan: scalar_dim, partial_filters=[scalar_dim.k IS NOT NULL] | | | ]] | | physical_plan | SortPreservingMergeExec: [k@0 ASC NULLS LAST] | | | SortExec: expr=[k@0 ASC NULLS LAST], preserve_partitioning=[true] | | | HashJoinExec: mode=Partitioned, join_type=Inner, on=[(k@0, k@1)], filter=val@0 > max(d.threshold)@1, projection=[k@0, val@1] | | | RepartitionExec: partitioning=Hash([REDACTED -| | ProjectionExec: expr=[k@1 as k, val@2 as val] | -| | MergeScanExec: REDACTED +| | MergeScanExec: REDACTED | | RepartitionExec: partitioning=Hash([REDACTED -| | ProjectionExec: expr=[max(d.threshold)@0 as max(d.threshold), k@1 as k] | -| | MergeScanExec: REDACTED +| | MergeScanExec: REDACTED | | | +---------------+----------------------------------------------------------------------------------------------------------------------------------+ diff --git a/tests/cases/standalone/optimizer/time_index_filter_pushdown.result b/tests/cases/standalone/optimizer/time_index_filter_pushdown.result index 106a78c49d2..787119875bd 100644 --- a/tests/cases/standalone/optimizer/time_index_filter_pushdown.result +++ b/tests/cases/standalone/optimizer/time_index_filter_pushdown.result @@ -261,26 +261,25 @@ WHERE +-+-+-+ | 0_| 0_|_ScalarSubqueryExec REDACTED |_|_|_FilterExec: greptime_timestamp@2 = scalar_subquery(1686535800000000000) REDACTED -|_|_|_ProjectionExec: expr=[rack@0 as rack, os@1 as os, greptime_timestamp@4 as greptime_timestamp] REDACTED |_|_|_CooperativeExec REDACTED |_|_|_MergeScanExec: REDACTED |_|_|_MergeSortExec: [greptime_timestamp@0 DESC], fetch=1 REDACTED |_|_|_MergeScanExec: REDACTED |_|_|_| | 1_| 0_|_CooperativeExec REDACTED -|_|_|_UnorderedScan: REDACTED, "dyn_filters": ["DynamicFilter [ greptime_timestamp@4 = 1686535800000000000 ]"] +|_|_|_UnorderedScan: REDACTED, "dyn_filters": ["DynamicFilter [ greptime_timestamp@2 = 1686535800000000000 ]"] |_|_|_| | 1_| 1_|_CooperativeExec REDACTED -|_|_|_UnorderedScan: REDACTED, "dyn_filters": ["DynamicFilter [ greptime_timestamp@4 = 1686535800000000000 ]"] +|_|_|_UnorderedScan: REDACTED, "dyn_filters": ["DynamicFilter [ greptime_timestamp@2 = 1686535800000000000 ]"] |_|_|_| | 1_| 2_|_CooperativeExec REDACTED -|_|_|_UnorderedScan: REDACTED, "dyn_filters": ["DynamicFilter [ greptime_timestamp@4 = 1686535800000000000 ]"] +|_|_|_UnorderedScan: REDACTED, "dyn_filters": ["DynamicFilter [ greptime_timestamp@2 = 1686535800000000000 ]"] |_|_|_| | 1_| 3_|_CooperativeExec REDACTED -|_|_|_UnorderedScan: REDACTED, "dyn_filters": ["DynamicFilter [ greptime_timestamp@4 = 1686535800000000000 ]"] +|_|_|_UnorderedScan: REDACTED, "dyn_filters": ["DynamicFilter [ greptime_timestamp@2 = 1686535800000000000 ]"] |_|_|_| | 1_| 4_|_CooperativeExec REDACTED -|_|_|_UnorderedScan: REDACTED, "dyn_filters": ["DynamicFilter [ greptime_timestamp@4 = 1686535800000000000 ]"] +|_|_|_UnorderedScan: REDACTED, "dyn_filters": ["DynamicFilter [ greptime_timestamp@2 = 1686535800000000000 ]"] |_|_|_| | 1_| 0_|_FilterExec: DynamicFilter [ REDACTED ] REDACTED |_|_|_SortPreservingMergeExec: [greptime_timestamp@0 DESC], fetch=1 REDACTED diff --git a/tests/compatibility/README.md b/tests/compatibility/README.md index 53ecda81048..b84b55c92e5 100644 --- a/tests/compatibility/README.md +++ b/tests/compatibility/README.md @@ -29,6 +29,25 @@ Frozen objects of the object store WAL are checked byte for byte by the format t `log-store`. The SQL runner cannot cover the object store WAL: it owns `wal.provider`. See the [fixture notes](wal/object_store/README.md). +## Manifest fixtures + +[Table-compaction fixtures](manifest/table_compaction/README.md) are exercised by +mito2's Rust tests. They cover ordinary file-edit compatibility, supported SST +levels, and explicit rejection of unpublished prototype task-state records. + +The inline sketch-index fixtures in `src/mito2/src/manifest/action.rs` cover both +file-level and column-level descriptors and mixed builtin/sketch indexes. They run without the enterprise feature: + +```shell +cargo nextest run -p mito2 -E 'test(test_sketch_index_manifest_fixture)' +``` + +These fixtures verify supported-reader decoding, not downgrade support for binaries +that predate the new index types. Upgrade all manifest readers before enabling a +writer that emits these descriptors; downgrade only to readers that recognize them. +The OSS build does not generate sketch payloads, so SQL restart cases cannot create +these descriptors through an OSS writer. + ## Quick Start ```shell diff --git a/tests/compatibility/cases/json2_fulltext_index/case.toml b/tests/compatibility/cases/json2_fulltext_index/case.toml new file mode 100644 index 00000000000..21d4de0514a --- /dev/null +++ b/tests/compatibility/cases/json2_fulltext_index/case.toml @@ -0,0 +1,8 @@ +name = "json2_fulltext_index" +reason = "Old JSON2 metadata without fulltext hints remains readable after enabling path indexes." +introduced_by = "JSON2 path fulltext index" +topologies = ["standalone", "distributed"] +from_range = [">=v1.3.0"] +to_range = ["*"] +features = ["json2", "metadata", "index"] +owner = "storage" diff --git a/tests/compatibility/cases/json2_fulltext_index/setup.sql b/tests/compatibility/cases/json2_fulltext_index/setup.sql new file mode 100644 index 00000000000..57156b1104d --- /dev/null +++ b/tests/compatibility/cases/json2_fulltext_index/setup.sql @@ -0,0 +1,3 @@ +CREATE TABLE logs (ts TIMESTAMP TIME INDEX, j JSON2(max_auto_expanded_paths=0)) WITH ('append_mode'='true'); +INSERT INTO logs VALUES (1, '{"message":"error old"}'); +ADMIN FLUSH_TABLE('logs'); diff --git a/tests/compatibility/cases/json2_fulltext_index/verify.result b/tests/compatibility/cases/json2_fulltext_index/verify.result new file mode 100644 index 00000000000..3d741a39bfb --- /dev/null +++ b/tests/compatibility/cases/json2_fulltext_index/verify.result @@ -0,0 +1,82 @@ +SELECT ts FROM logs WHERE matches_term(j.message, 'error') ORDER BY ts; + ++-------------------------+ +| ts | ++-------------------------+ +| 1970-01-01T00:00:00.001 | ++-------------------------+ + +ALTER TABLE logs MODIFY COLUMN j JSON2(max_auto_expanded_paths=0, message STRING FULLTEXT INDEX WITH (granularity='1')); + +Affected Rows: 0 + +INSERT INTO logs VALUES (2, '{"message":"error new"}'); + +Affected Rows: 1 + +ADMIN FLUSH_TABLE('logs'); + ++---------------------------+ +| ADMIN FLUSH_TABLE('logs') | ++---------------------------+ +| 0 | ++---------------------------+ + +SHOW CREATE TABLE logs; + ++-------+---------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| Table | Create Table | ++-------+---------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| logs | CREATE TABLE IF NOT EXISTS "logs" ( | +| | "ts" TIMESTAMP(3) NOT NULL, | +| | "j" JSON2( | +| | max_auto_expanded_paths = 0, | +| | "message" STRING FULLTEXT INDEX WITH (analyzer = 'English', case_sensitive = 'false', backend = 'bloom', granularity = '1', false_positive_rate = '0.01') | +| | ) NULL, | +| | TIME INDEX ("ts") | +| | ) | +| | | +| | ENGINE=mito | +| | WITH( | +| | append_mode = 'true' | +| | ) | ++-------+---------------------------------------------------------------------------------------------------------------------------------------------------------------+ + +SELECT ts FROM logs WHERE matches_term(j.message, 'error') ORDER BY ts; + ++-------------------------+ +| ts | ++-------------------------+ +| 1970-01-01T00:00:00.001 | +| 1970-01-01T00:00:00.002 | ++-------------------------+ + +-- SQLNESS ARG restart=true +SHOW CREATE TABLE logs; + ++-------+---------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| Table | Create Table | ++-------+---------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| logs | CREATE TABLE IF NOT EXISTS "logs" ( | +| | "ts" TIMESTAMP(3) NOT NULL, | +| | "j" JSON2( | +| | max_auto_expanded_paths = 0, | +| | "message" STRING FULLTEXT INDEX WITH (analyzer = 'English', case_sensitive = 'false', backend = 'bloom', granularity = '1', false_positive_rate = '0.01') | +| | ) NULL, | +| | TIME INDEX ("ts") | +| | ) | +| | | +| | ENGINE=mito | +| | WITH( | +| | append_mode = 'true' | +| | ) | ++-------+---------------------------------------------------------------------------------------------------------------------------------------------------------------+ + +SELECT ts FROM logs WHERE matches_term(j.message, 'error') ORDER BY ts; + ++-------------------------+ +| ts | ++-------------------------+ +| 1970-01-01T00:00:00.001 | +| 1970-01-01T00:00:00.002 | ++-------------------------+ diff --git a/tests/compatibility/cases/json2_fulltext_index/verify.sql b/tests/compatibility/cases/json2_fulltext_index/verify.sql new file mode 100644 index 00000000000..43567267691 --- /dev/null +++ b/tests/compatibility/cases/json2_fulltext_index/verify.sql @@ -0,0 +1,9 @@ +SELECT ts FROM logs WHERE matches_term(j.message, 'error') ORDER BY ts; +ALTER TABLE logs MODIFY COLUMN j JSON2(max_auto_expanded_paths=0, message STRING FULLTEXT INDEX WITH (granularity='1')); +INSERT INTO logs VALUES (2, '{"message":"error new"}'); +ADMIN FLUSH_TABLE('logs'); +SHOW CREATE TABLE logs; +SELECT ts FROM logs WHERE matches_term(j.message, 'error') ORDER BY ts; +-- SQLNESS ARG restart=true +SHOW CREATE TABLE logs; +SELECT ts FROM logs WHERE matches_term(j.message, 'error') ORDER BY ts; diff --git a/tests/compatibility/manifest/table_compaction/README.md b/tests/compatibility/manifest/table_compaction/README.md new file mode 100644 index 00000000000..7244199462e --- /dev/null +++ b/tests/compatibility/manifest/table_compaction/README.md @@ -0,0 +1,25 @@ +# File-only compaction manifest compatibility + +The hand-authored frozen fixtures use the JSON schema of `RegionEdit` and +`RegionManifest` at `4092fe6549`. They are schema fixtures, not captures from a +released binary. They preserve L0/L1 metadata, sequences and flush boundaries. + +V1 publishes compaction results using ordinary file edits. It adds no task IDs, +phases, receipts, request epochs or extension-state fields to the manifest. +Task retries may be submitted more than once; publication checks current inputs. + +```sh +cargo nextest run -p mito2 -E 'test(manifest::tests::compatibility)' +cargo nextest run -p mito2 --features enterprise -E 'test(manifest::tests::compatibility)' +``` + +The tests exercise legacy delta/checkpoint reads and verify that serialization +still contains no task-state fields. Optional future core fields remain readable. +Unknown SST levels are rejected; the shared sentinel level (the u8 maximum) +requires Enterprise capability. +This does not establish downgrade safety after shared files are introduced. + +The earlier, unpublished prototype persisted `table_compaction` / `extensions` +task records. Canonical delta/checkpoint decoders reject those records in both +builds rather than silently dropping recovery evidence. They require explicit +migration; this version does not resume that prototype's Prepare/Commit protocol. diff --git a/tests/compatibility/manifest/table_compaction/legacy-edit.json b/tests/compatibility/manifest/table_compaction/legacy-edit.json new file mode 100644 index 00000000000..81ffccccc2e --- /dev/null +++ b/tests/compatibility/manifest/table_compaction/legacy-edit.json @@ -0,0 +1,29 @@ +{ + "actions": [{ + "Edit": { + "files_to_add": [ + { + "region_id": 4294967297, + "file_id": "4b220a70-2b03-4641-9687-b65d94641208", + "time_range": [{"value": 0, "unit": "Millisecond"}, {"value": 10, "unit": "Millisecond"}], + "level": 0, + "file_size": 100, + "sequence": 7 + }, + { + "region_id": 4294967297, + "file_id": "4b220a70-2b03-4641-9687-b65d94641209", + "time_range": [{"value": 0, "unit": "Millisecond"}, {"value": 10, "unit": "Millisecond"}], + "level": 1, + "file_size": 100, + "sequence": 8 + } + ], + "files_to_remove": [], + "compaction_time_window": "1h", + "flushed_entry_id": 5, + "flushed_sequence": 8, + "committed_sequence": 8 + } + }] +} diff --git a/tests/compatibility/manifest/table_compaction/legacy-manifest.json b/tests/compatibility/manifest/table_compaction/legacy-manifest.json new file mode 100644 index 00000000000..38c7ef735ca --- /dev/null +++ b/tests/compatibility/manifest/table_compaction/legacy-manifest.json @@ -0,0 +1,26 @@ +{ + "metadata": { + "column_metadatas": [{ + "column_schema": { + "name": "ts", + "data_type": {"Timestamp": {"Millisecond": null}}, + "is_nullable": false, + "is_time_index": true, + "default_constraint": null, + "metadata": {} + }, + "semantic_type": "Timestamp", + "column_id": 0 + }], + "primary_key": [], + "region_id": 4294967297, + "schema_version": 0 + }, + "files": {}, + "flushed_entry_id": 5, + "flushed_sequence": 8, + "committed_sequence": 8, + "manifest_version": 12, + "truncated_entry_id": null, + "compaction_time_window": "1h" +} diff --git a/tests/perf/test_ci_runner_scripts.py b/tests/perf/test_ci_runner_scripts.py index c703e41c62b..b1c8f118bfb 100644 --- a/tests/perf/test_ci_runner_scripts.py +++ b/tests/perf/test_ci_runner_scripts.py @@ -158,9 +158,11 @@ class ProviderConfigTest(unittest.TestCase): -class BenchmarkSetupTest(unittest.TestCase): - def run_setup(self, missing_tools="", docker_installed=True, docker_ready=True): - action = (SCRIPTS.parent / "actions/setup-benchmark/action.yml").read_text() +class LinuxRunnerSetupTest(unittest.TestCase): + def run_setup(self, missing_tools="", docker_installed=True, docker_ready=True, + tools="curl jq python3 rsync", architecture="x86_64", + expected_arch="x86_64", docker_access=True, expect_success=True): + action = (SCRIPTS.parent / "actions/setup-linux-runner/action.yml").read_text() steps = re.findall(r" run: \|\n((?: .*\n|\n)+)", action) self.assertEqual(len(steps), 2) script = "\n".join(textwrap.dedent(step) for step in steps) @@ -168,9 +170,9 @@ class BenchmarkSetupTest(unittest.TestCase): # changes availability, so the second pass must perform no mutations. prelude = r""" function . { ID=ubuntu; VERSION_CODENAME=noble; } -uname() { echo x86_64; } +uname() { echo "$TEST_ARCH"; } dpkg() { echo amd64; } -curl() { echo fixture-key; } +curl() { printf 'curl %s\n' "$*" >> "$CALLS"; echo fixture-key; } command() { if [[ "$1" == -v ]]; then if [[ "$2" == docker ]]; then [[ "$DOCKER_INSTALLED" == true ]]; return; fi @@ -179,7 +181,7 @@ command() { fi builtin command "$@" } -docker() { [[ "$DOCKER_READY" == true ]]; } +docker() { [[ "$DOCKER_READY" == true && "$DOCKER_ACCESS" == true ]]; } sudo() { printf '%s\n' "$*" >> "$CALLS" if [[ "$*" == *' apt-get install '* ]]; then @@ -196,10 +198,17 @@ sudo() { calls.touch() env = os.environ | {"CALLS": str(calls), "MISSING_TOOLS": missing_tools, "DOCKER_INSTALLED": str(docker_installed).lower(), - "DOCKER_READY": str(docker_ready).lower()} + "DOCKER_READY": str(docker_ready).lower(), + "DOCKER_ACCESS": str(docker_access).lower(), + "REQUIRED_TOOLS": tools, "TEST_ARCH": architecture, + "EXPECTED_ARCH": expected_arch} result = subprocess.run(["bash", "-c", prelude + script + '\nprintf "SECOND PASS\\n" >> "$CALLS"\n' + script], env=env, capture_output=True, text=True) + if not expect_success: + self.assertNotEqual(result.returncode, 0) + self.assertNotIn("SECOND PASS", calls.read_text()) + return calls.read_text() self.assertEqual(result.returncode, 0, result.stderr) first, second = calls.read_text().split("SECOND PASS\n") self.assertEqual(second, "", "Second setup must reuse installed dependencies") @@ -218,11 +227,32 @@ sudo() { calls = self.run_setup(docker_installed=False, docker_ready=False) self.assertIn("NEEDRESTART_MODE=l", calls) self.assertIn("docker-ce docker-ce-cli containerd.io docker-buildx-plugin", calls) + self.assertLess(calls.index("--no-install-recommends curl ca-certificates"), + calls.index("curl -fsSL https://download.docker.com/linux/ubuntu/gpg")) self.assertIn("systemctl enable --now docker", calls) def test_existing_stopped_docker_is_started_without_installation(self): self.assertEqual(self.run_setup(docker_ready=False), "-n systemctl enable --now docker\n") + def test_release_tools_on_both_architectures(self): + for architecture in ("x86_64", "aarch64"): + with self.subTest(architecture=architecture): + calls = self.run_setup(missing_tools="make shasum", tools="make shasum", + architecture=architecture, expected_arch="") + self.assertEqual(calls.splitlines(), [ + "-n apt-get update", + "-n env DEBIAN_FRONTEND=noninteractive NEEDRESTART_MODE=l " + "apt-get install -y --no-install-recommends make libdigest-sha-perl", + ]) + + def test_benchmark_rejects_arm_before_installing(self): + self.assertEqual(self.run_setup(missing_tools="jq", architecture="aarch64", + expect_success=False), "") + + def test_inaccessible_docker_fails_even_after_starting_service(self): + calls = self.run_setup(docker_access=False, expect_success=False) + self.assertEqual(calls, "-n systemctl enable --now docker\n") + class AwsProvisionTest(unittest.TestCase): def test_host_policy_matches_aliyun_before_runner_activation(self): @@ -595,7 +625,7 @@ class BenchmarkImagePullTest(unittest.TestCase): for reference in ("RUNTIME_IMAGE", "RESOLVED_RUNTIME_IMAGE", "reference"): self.assertIn(f'pull-benchmark-image.sh "${reference}"', long_range) self.assertLess(long_range.index('pull-benchmark-image.sh "$reference"'), - long_range.index('- name: Warm serial and concurrent benchmarks')) + long_range.index('- name: Generate shared dataset and split target plans')) self.assertIn('pull-benchmark-image.sh "$reference"', agent) self.assertLess(agent.index('resolve_image runtime'), agent.index('- name: Generate dataset once')) self.assertIn('pull-benchmark-image.sh "$RUNTIME_IMAGE"', traces) diff --git a/tests/perf/test_o11ybench_storage.py b/tests/perf/test_o11ybench_storage.py new file mode 100644 index 00000000000..1a1718dd107 --- /dev/null +++ b/tests/perf/test_o11ybench_storage.py @@ -0,0 +1,186 @@ +# Copyright 2023 Greptime Team +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Offline contracts for File/S3 benchmark arm selection.""" +import importlib.util +import copy +import json +import tempfile +from pathlib import Path +import unittest + +ROOT = Path(__file__).resolve().parents[2] +spec = importlib.util.spec_from_file_location('storage', ROOT / '.github/scripts/o11ybench-storage.py') +storage = importlib.util.module_from_spec(spec) +spec.loader.exec_module(storage) + + +class StorageTests(unittest.TestCase): + def test_trace_partial_query_audit(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + report = root / 'report.json' + summary = root / 'ci-summary.md' + participant = dict(id='victoriatraces', target='victoriatraces', role='comparison') + result = dict(participant='victoriatraces', health='recorded healthy snapshots', + queries=dict(T01=dict(status='passed'), T06=dict(status='failed', reason='HTTP 400'), + T08=dict(status='unsupported'))) + data = dict(workloads=[dict(id='traces', participants=[participant], + scenarios=[dict(id='main', results=[result])])]) + + def run(payload, allow=True): + report.write_text(json.dumps(payload)) + summary.write_text('original summary\n') + return storage.audit(root, report, ['victoriatraces'], 'file', + allow_trace_query_failures=allow) + + with self.assertRaisesRegex(ValueError, 'failed or unavailable'): + run(data, allow=False) + output = run(data) + self.assertTrue(output['passed']) + self.assertEqual(output['query_failures'], [dict(workload='traces', scenario='main', + participant='victoriatraces', query='T06', reason='HTTP 400')]) + self.assertEqual(json.loads(report.read_text()), data) + self.assertIn('not an all-pass query run', summary.read_text()) + self.assertIn('victoriatraces / T06: failed', summary.read_text()) + for workload in ('metrics', 'agent'): + changed = copy.deepcopy(data) + changed['workloads'][0]['id'] = workload + with self.subTest(workload=workload), self.assertRaisesRegex(ValueError, 'failed or unavailable'): + run(changed) + for status in ('failed', 'unsupported'): + changed = copy.deepcopy(data) + changed['workloads'][0]['scenarios'][0]['results'][0]['queries']['T01']['status'] = status + with self.subTest(status=status), self.assertRaisesRegex(ValueError, 'no successful'): + run(changed) + for health in (None, 'unhealthy', 'incomplete health snapshots'): + changed = copy.deepcopy(data) + changed['workloads'][0]['scenarios'][0]['results'][0]['health'] = health + with self.subTest(health=health), self.assertRaisesRegex(ValueError, 'unhealthy trace evidence'): + run(changed) + changed = copy.deepcopy(data) + changed['workloads'][0]['scenarios'][0]['results'][0]['queries']['T06']['status'] = 'unavailable' + with self.assertRaisesRegex(ValueError, 'failed or unavailable'): + run(changed) + changed = copy.deepcopy(data) + changed['workloads'][0]['scenarios'][0]['results'] = [] + with self.assertRaisesRegex(ValueError, 'missing trace participant'): + run(changed) + changed['workloads'][0]['scenarios'] = [] + with self.assertRaisesRegex(ValueError, 'missing trace scenarios'): + run(changed) + manifest = root / 'o11ybench/target/run-manifest.json' + manifest.parent.mkdir(parents=True) + manifest.write_text('{"status":"failed"}') + with self.assertRaisesRegex(ValueError, 'incomplete target manifest'): + run(data) + + def test_trace_partial_query_workflow_scope(self): + for name in ('tracesbench', 'agent-observability', 'vmbench-long-range'): + text = (ROOT / '.github/workflows' / (name + '.yml')).read_text() + self.assertEqual(text.count('--allow-trace-query-failures'), int(name == 'tracesbench')) + + def test_admission(self): + self.assertEqual(storage.validate({}), 'file') + env = dict(GREPTIMEDB_STORAGE='both', RUN_GREPTIMEDB='true', PROVIDER='AWS', + S3_BUCKET='test', S3_REGION='us-east-1', RUNNER_REGION='us-east-1') + self.assertEqual(storage.validate(env), 'both') + for key, value in [('PROVIDER', 'Aliyun'), ('RUNNER_REGION', 'us-west-2'), + ('S3_BUCKET', ''), ('RUN_GREPTIMEDB', 'false'), ('GREPTIMEDB_STORAGE', 'invalid')]: + with self.assertRaises(ValueError): + storage.validate(dict(env, **{key: value})) + def test_execution_must_not_expand_arms(self): + command = ['runner', '--stage', 'target', '--root', '/run', '--owner', 'owner'] + with self.assertRaises(ValueError): + storage.commands(command, 'both') + + def test_metrics_split_preserves_data_and_target_contract(self): + plan = dict(output_root='/tmp/o11ybench-test', run_id='test', + data=dict(generate=True, data_home='/tmp/o11ybench-test/data'), + targets=[dict(name='greptimedb', storage=dict(type='file')), + dict(name='greptimedb-s3', storage=dict(type='s3', root='owned/prefix/')), + dict(name='prometheus', kind='prometheus')], + report=dict(root='old', index_html='old/index.html'), + artifacts=dict(run_manifest='old/run-manifest.json'), + query=dict(modes=['serial'], serial_tries=5)) + original = copy.deepcopy(plan) + children = storage.split_metrics(plan) + self.assertEqual(plan, original) + self.assertEqual(set(children), {'greptimedb', 'greptimedb-s3', 'prometheus'}) + for name, child in children.items(): + self.assertEqual(child['query'], plan['query']) + self.assertEqual(child['data'], dict(plan['data'], generate=False)) + self.assertEqual(len(child['targets']), 1) + self.assertEqual(child['targets'][0]['name'], name) + self.assertEqual(child['output_root'], '/tmp/o11ybench-test/o11ybench/o11ybench-' + name) + self.assertTrue(child['report']['root'].startswith(child['output_root'])) + self.assertNotEqual(children['greptimedb']['run_id'], children['greptimedb-s3']['run_id']) + + def test_prometheus_workflow_wiring(self): + text = (ROOT / '.github/workflows/vmbench-long-range.yml').read_text() + step = text.split(' - name: Load and benchmark Prometheus\n', 1)[1].split(' - name:', 1)[0] + self.assertIn("steps.generate.outcome == 'success' && inputs.run_prometheus", step) + self.assertIn('metrics-run --target prometheus', step) + self.assertIn('for target in greptimedb victoriametrics prometheus;', text) + cleanup = text.split(' - name: Clean up owned containers', 1)[1].split(' - name:', 1)[0] + self.assertIn('greptimedb-s3-baseline victoriametrics prometheus; do', cleanup) + + def test_missing_s3_arm_is_not_a_success(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + report = root / 'report.json' + report.write_text(json.dumps(dict(workloads=[dict(participants=[ + dict(target='greptimedb', role='candidate', storage=dict(type='file'))], scenarios=[])]))) + with self.assertRaisesRegex(ValueError, 'participant mismatch'): + storage.audit(root, report, ['greptimedb'], 'both') + + def test_s3_summary_is_explicit_when_missing(self): + with tempfile.TemporaryDirectory() as tmp: + text = storage.summary('agent', Path(tmp), ['greptimedb'], 'benchmark', 'both') + self.assertIn('GreptimeDB File', text) + self.assertIn('GreptimeDB S3', text) + self.assertIn('S3 cleanup: **failed / unavailable**', text) + + def test_cleanup_both(self): + command = ['runner', '--stage', 'cleanup', '--root', '/run', '--owner', 'owner'] + calls = storage.commands(command, 'both') + self.assertEqual(len(calls), 2) + self.assertTrue(all('--greptimedb-storage' not in c for c in calls)) + def test_cleanup_s3_only_still_visits_primary_competitors(self): + command = ['runner', '--stage', 'cleanup', '--root', '/run', '--owner', 'owner'] + calls = storage.commands(command, 's3') + self.assertEqual(len(calls), 2) + self.assertEqual(calls[1][calls[1].index('--root') + 1], '/run/s3') + + def test_workflow_wiring(self): + for name in ('agent-observability', 'tracesbench', 'vmbench-long-range'): + text = (ROOT / '.github/workflows' / (name + '.yml')).read_text() + self.assertIn('options: [file, s3, both]', text) + self.assertIn('o11ybench-storage.py validate', text) + self.assertIn('o11ybench-storage.py audit', text) + self.assertIn('ci-summary.md', text) + self.assertIn('AWS_SECRET_ACCESS_KEY:', text) + self.assertNotIn('o11ybench-storage.py run -- bash o11ybench/scripts/run-agent-observability.sh --stage target', text) + if name == 'vmbench-long-range': + self.assertIn('name: Load and benchmark GreptimeDB File', text) + self.assertIn('name: Load and benchmark GreptimeDB S3', text) + self.assertIn('metrics-prepare', text) + self.assertIn('metrics-validate', text) + else: + self.assertIn('--stage target --greptimedb-storage file', text) + self.assertIn('--stage target --greptimedb-storage s3', text) + + +if __name__ == '__main__': + unittest.main()