chore(ci): merge main and preserve helper tooling tests

Signed-off-by: WenyXu <wenymedia@gmail.com>
This commit is contained in:
WenyXu
2026-10-29 07:56:44 +00:00
172 changed files with 14721 additions and 4351 deletions
@@ -0,0 +1,53 @@
name: GitHub Script Tests
description: Validate CI scripts before starting expensive jobs
runs:
using: composite
steps:
- uses: actions/setup-node@v4
with:
node-version: 24
- name: Run Node GitHub script tests
shell: bash
run: node --test .github/scripts/query-regression-comment.test.cjs .github/scripts/heavy-ci-policy.test.cjs .github/scripts/tests/nightly-merge.test.cjs
- name: Setup uv
uses: astral-sh/setup-uv@v3
with:
version: "latest"
- name: Run check-version script tests
shell: bash
run: uv run --no-project python .github/scripts/check-version-test.py
- name: Run release Linux architecture tests
shell: bash
run: python3 .github/scripts/release-linux-architectures-test.py
- name: Run previous-release-tag script tests
shell: bash
run: python3 .github/scripts/previous-release-tag-test.py
- name: Run enterprise license check tests
shell: bash
run: python3 scripts/check-enterprise-license-test.py
- name: Run fuzz orchestration script tests
shell: bash
run: .github/scripts/run-fuzz-targets-test.sh
- name: Run CI comment-command tests
shell: bash
run: python3 .github/scripts/tests/test_ci_slash.py
- name: Run CI scope gate tests
shell: bash
run: python3 .github/ci/tests/test_ci_scope.py
- name: Run metric snapshot benchmark tests
shell: bash
run: python3 -m unittest discover -s .github/scripts/tests -p 'test_metric_snapshot*.py'
- name: Run query-regression Python tooling tests
shell: bash
run: |
python3 tests/perf/test_query_regression_runner_compaction_toctou.py
python3 tests/perf/test_query_regression_runner_otlp_trace_load.py
python3 tests/perf/test_query_regression_summary_otlp.py
python3 tests/perf/test_query_regression_case_selection.py
python3 tests/perf/test_query_regression_helpers.py
python3 tests/perf/test_query_regression_nightly_refs.py
python3 tests/perf/test_query_regression_slash.py
python3 tests/perf/test_aliyun_ecs_runner_scripts.py
python3 tests/perf/test_ci_runner_scripts.py
python3 tests/perf/test_agent_observability_summary.py
python3 tests/perf/test_tracesbench_summary.py
+170
View File
@@ -0,0 +1,170 @@
# Integration CI admission gate
`integration.yml` filters its expensive jobs — fuzz, export/import E2E, and the
sqlness KvBackend legs — by the diff. Fuzz additionally follows the event policy
in [Heavy CI scheduling](../heavy-ci.md): PR opening or ready-for-review events,
scheduled runs, and explicit manual profiles. A scope verdict cannot override
that event policy.
The gate can only *skip* work, never add it, and it fails open: when the verdict
is missing or uncertain, every gated job runs.
| File | Role |
|---|---|
| `ci_scope.py` | the classifier: reads the diff, writes `$GITHUB_OUTPUT` |
| `scope-rules.toml` | the policy: which paths select which suite, as data |
| `ci_scope_rules.py` | loads and validates the policy; `--check-paths` |
| `tests/` | unit tests, and `fixtures/scope-cases.toml` golden cases |
Two words appear everywhere below. A **suite** is one matrix leg of a gated job,
named `<gate>/<leg>`. A **gate** is one `$GITHUB_OUTPUT` key that switches a
whole job.
## What is gated
Only `integration.yml`, and only these jobs:
| Gated job | Runs |
|---|---|
| `prepare-fuzz-targets` | the fuzz targets only |
| `fuzztest` | standalone fuzz, 2 legs |
| `unstable-fuzztest` | unstable standalone create-table fuzz, 1 leg |
| `distributed-fuzztest` | distributed fuzz with remote WAL, 4 legs |
| `distributed-fuzztest-with-chaos` | Chaos Mesh, 3 legs |
| `build-greptime-ci` | the profile-CI binary only |
| `export-import-v2-e2e` | CLI `COPY DATABASE` export/import against S3 |
| `sqlness-kvbackend` | sqlness with PostgreSQL and MySQL as the metadata store |
The legs themselves are the `matrix` entries in `integration.yml`; the rules
file repeats their ids so a verdict can name them.
Everything else always runs: `rust.yml`, `checks.yml`, `docs.yml`, the debug
`build`, the required `sqlness` job (Basic, Remote WAL, Flat format), `compat`
and `compat-updater-check`. None of the gated jobs is in the required-check
matrix in `docs.yml`, so a skipped job can never block a merge.
Two choices follow from that rule. The two KvBackend legs sit in their own
`sqlness-kvbackend` job because a job-level `if:` cannot read `matrix`, so
gating them inside `sqlness` would skip required checks and make the pull
request unmergeable. The multi-language SDK job stays ungated: it takes about
three minutes, less than the cost of getting its verdict wrong.
## How a verdict is made
First match wins:
1. **Forced** — `merge_group`, `schedule`, `workflow_dispatch`, the `ci:full`
label or `CI_SCOPE_FORCE_ALL`. All scope outputs allow execution; job event
conditions and manual profile selection still apply.
2. **Too large to judge** — more than 300 changed files. Everything runs.
3. **Always-run file changed** — `Cargo.toml`, `Cargo.lock`, `tests-fuzz/**`,
this directory, or anything else that changes what the suites build or how
they start. Everything runs.
4. **Uncovered change** — a path under `src/` that no suite claims. This is the
net for a crate added, split or renamed after the rules were written.
Everything runs.
5. **Path rules** — the suites whose globs match the changed files, and only
those.
The code is the source of truth for the details; its module docstring is worth
reading before changing it.
## Why a check was skipped
The run page's summary pane answers this without opening a log: one row per
suite, with its verdict, the rule that decided it, and up to three of the
changed files that matched.
The step log of the `CI Scope` job has the same information in text form. It
starts with `CI scope: mode=… full=…` (`grep '^CI scope'` finds it), then one
line per suite — `run` or `skip`, source, reason — then `gates:` with the exact
values the jobs read.
A degraded decision is never silent. A failed label or file lookup emits
`::warning::` and widens the gate to every suite.
## Forcing a full run
Add the `ci:full` label to the pull request and click "Re-run all jobs". The
label is read through the API at run time, not from the event payload, so one
added after the first run still counts. `/ci` dispatch
(`.github/scripts/ci-slash.py`), the `CI_SCOPE_FORCE_ALL` repository variable
and every merge-queue run also run everything: the classifier returns a forced
plan there, so a wrong skip is still exercised before the change lands. None of
the gated jobs is a required check, so a failure in the queue does not block the
merge by itself.
`CI_SCOPE_FORCE_ALL` is the switch to flip while debugging the rules themselves.
## Changing the rules
`scope-rules.toml` is data, not code: `ci_scope_rules.py` loads it with the
standard library's `tomllib`. Two things are validated:
- the shape — an unknown or cyclic `@group` reference, a `gate` that disagrees
with the suite id, a gate missing from `[gates]`, or an exemption without a
`reason` all raise;
- that every glob still points at something that exists, so a renamed or
deleted crate fails the check instead of silently matching nothing.
Run both with `make check-ci-scope`, or the path half alone with
`python3 .github/ci/ci_scope_rules.py --check-paths`. The same command runs in
the `CI Scope Rules` job of `checks.yml`, on `ubuntu-slim` — the image the
classifier itself uses, so a path that exists there also exists when the verdict
is computed.
A malformed file fails the classify step, and because every step of that job is
`continue-on-error`, every gated job runs instead.
`[[matching.exempt]]` lists paths outside the gate's remit: they select no suite
and never widen the gate. Each one carries a `reason`, and the loader rejects an
empty one — what CI never runs is the part a reader must be able to justify.
`tests/fixtures/scope-cases.toml` is test data, not configuration: a diff shape
and the suites it must start. `ScopeCaseTests` replays each case through the
classifier, so a rule edit that changes behaviour fails with the case name
instead of silently rerouting CI. The cases carry no pull request numbers;
`git log` has those.
## Adding a suite
1. Add a `[suites."<gate>/<leg>"]` table to `scope-rules.toml` with `gate`,
`paths` (globs or `@group` references) and a one-line `description`. The id
is `<gate>/<matrix leg id>`, and `gate` is that id with `-` replaced by `_`;
the loader and `test_suite_metadata` both enforce it.
2. Add the matching matrix leg to the job in `integration.yml`.
3. Gate the job's `if:` with the matching output, and list `scope` in its
`needs`. A new gate also needs a key in `derive_outputs` and in the `scope`
job's `outputs`; `test_every_gate_routes_to_an_output` fails when that
routing is missing.
4. Add a case to `tests/fixtures/scope-cases.toml` and run
`python3 .github/ci/tests/test_ci_scope.py`. `CrateCoverageTests` separately
fails when a workspace crate matches no suite and is not excused in
`UNMAPPED_CRATES`: the runtime net would run everything, but the rule table
is what should be updated.
## Ground rules for the workflow
These six rules keep the gate failing open. Break one and either CI runs jobs it
should have skipped, or a classifier failure takes CI down with it.
- **Read the output as `!= 'false'`.** An absent output means "run"; writing
`== 'true'` inverts the failure direction.
- **Start every gate with `!cancelled()`.** Without a status function the
condition carries an implicit `success()` over `needs`, so a `scope` job that
times out would skip the gates. Other dependencies are therefore required
explicitly with `needs.<job>.result == 'success'`.
- **Every fallible step of `scope` is `continue-on-error: true`.** GitHub skips
the dependents of a *failed* job, so a classifier crash must leave the job
green with no outputs rather than take CI down with it.
- **Rules come from the base revision.** The `scope` job checks out
`pull_request.base.sha` (or `merge_group.base_sha`), so a pull request cannot
weaken its own gate. On the first pull request that introduces this directory
the base has no `ci_scope.py`: the step fails, no outputs are written, and
every gate runs.
- **One gate per job, never per leg.** GitHub does not expose `matrix` to
`jobs.<job_id>.if`. Per-suite verdicts stay visible in the log.
- **Pass the run's `head`/`base` SHAs and let the classifier compare them with
the pull request's live revisions.** A re-run keeps the original SHAs while
GitHub serves the *current* file list; without the comparison the new diff
would be judged against the old tree. With it, a mismatch runs everything.
+623
View File
@@ -0,0 +1,623 @@
#!/usr/bin/env python3
# Copyright 2023 Greptime Team
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Decide which integration CI suites must run for one pull request.
Pipeline, in priority order:
1. forced mode -- `merge_group`, `schedule`, `workflow_dispatch`,
`CI_SCOPE_FORCE_ALL`, or the `ci:full` label. Every suite runs.
2. always-run floor -- a changed file matches `ALWAYS_RUN`. Every suite runs.
3. uncovered build change -- a path under `SRC_TREE` that no suite claims, so a
crate added or renamed later still runs everything.
4. static path matches -- glob match of the changed files against the suite
catalog in `scope-rules.toml`. Paths under `EXEMPT_TREES` are outside the
gate's remit and are dropped first: `@server` claims `src/query/**`, which
would otherwise put a PromQL-only change through the whole fleet.
The verdict is deterministic: the same diff always produces the same plan, and
a change that no rule explains falls through to "run everything".
The plan maps to `$GITHUB_OUTPUT` keys that the `integration.yml` gate jobs
consume; `--dry-run` prints them as JSON.
"""
import argparse
import json
import os
import re
import sys
import urllib.error
import urllib.request
from ci_scope_rules import (
ALWAYS_RUN,
EXEMPT_TREES,
SRC_TREE,
SUITES,
suite_group,
suite_paths,
)
MAX_FILES = 300
HTTP_TIMEOUT = 45
FORCED_EVENTS = {"merge_group", "schedule", "workflow_dispatch"}
# A diff with no code, config or workflow file never needs a suite.
CODE_FILE = re.compile(
r"\.(rs|toml|lock|sh|ya?ml)$|(^|/)Makefile$|(^|/)Cargo\.toml$|\.sql$"
)
FUZZ_GATES = ("fuzz_standalone", "fuzz_distributed", "fuzz_chaos")
class ScopeError(Exception):
"""A handled failure: the caller falls back instead of crashing."""
# ---------------------------------------------------------------------------
# HTTP seam (tests replace `_request`)
# ---------------------------------------------------------------------------
def _request(method, url, headers, body=None, timeout=HTTP_TIMEOUT):
request = urllib.request.Request(url, data=body, headers=headers, method=method)
try:
with urllib.request.urlopen(request, timeout=timeout) as response:
return response.status, response.read()
except urllib.error.HTTPError as err:
return err.code, err.read()
except (urllib.error.URLError, TimeoutError, OSError) as err:
raise ScopeError(f"{method} {url}: {err}") from err
def _get(url, headers, timeout=HTTP_TIMEOUT):
return _request("GET", url, headers, None, timeout)
def _post(url, headers, body, timeout=HTTP_TIMEOUT):
return _request("POST", url, headers, body, timeout)
def get_json(url, headers, timeout=HTTP_TIMEOUT):
"""GET returning (status, parsed json); transport failures raise `ScopeError`."""
status, raw = _get(url, headers, timeout)
try:
payload = json.loads(raw.decode("utf-8", "replace")) if raw else None
except json.JSONDecodeError:
payload = None
return status, payload
# ---------------------------------------------------------------------------
# Path matching
# ---------------------------------------------------------------------------
def glob_to_regex(pattern):
"""Translate a repo glob into an anchored regexp.
`**/` also matches zero directories, `**` spans `/`, `*` and `?` do not.
"""
out = ["^"]
index = 0
while index < len(pattern):
char = pattern[index]
if char == "*":
end = index
while end < len(pattern) and pattern[end] == "*":
end += 1
if end - index >= 2:
if end < len(pattern) and pattern[end] == "/":
out.append("(?:.*/)?")
index = end + 1
continue
out.append(".*")
else:
out.append("[^/]*")
index = end
elif char == "?":
out.append("[^/]")
index += 1
else:
out.append(re.escape(char))
index += 1
out.append("$")
return re.compile("".join(out))
def compile_patterns(patterns):
return [glob_to_regex(pattern) for pattern in patterns]
def matches_any(filename, compiled):
return any(regex.match(filename) for regex in compiled)
# ---------------------------------------------------------------------------
# GitHub API
# ---------------------------------------------------------------------------
def github_api(method, path, token, payload=None):
base = os.environ.get("GITHUB_API_URL", "https://api.github.com").rstrip("/")
url = base + path
headers = {
"Accept": "application/vnd.github+json",
"User-Agent": "greptimedb-ci-scope",
}
if token:
headers["Authorization"] = "Bearer " + token
body = None
if payload is not None:
body = json.dumps(payload).encode()
headers["Content-Type"] = "application/json"
if method == "GET":
return get_json(url, headers)
status, raw = _request(method, url, headers, body, HTTP_TIMEOUT)
try:
parsed = json.loads(raw.decode("utf-8", "replace")) if raw else None
except json.JSONDecodeError:
parsed = None
return status, parsed
def fetch_changed_files(repo, number, token):
"""Return (files, truncated). `truncated` means the PR has more than MAX_FILES."""
files = []
page = 1
while True:
status, payload = github_api(
"GET", f"/repos/{repo}/pulls/{number}/files?per_page=100&page={page}", token
)
if status != 200 or not isinstance(payload, list):
raise ScopeError(f"cannot list pull request files (HTTP {status})")
for item in payload:
if not isinstance(item, dict):
continue
patch = item.get("patch")
files.append(
{
"filename": item.get("filename", ""),
"previous_filename": item.get("previous_filename") or "",
"status": item.get("status", "modified"),
"additions": item.get("additions", 0),
"deletions": item.get("deletions", 0),
"patch": patch if isinstance(patch, str) else "",
"patch_included": isinstance(patch, str) and bool(patch),
}
)
if len(payload) < 100:
return files, False
if len(files) >= MAX_FILES:
# Keep `per_page=100`: with `per_page=1`, page N is item N, so the
# probe would answer "is there a file 4?" instead of "file 301?".
status, extra = github_api(
"GET",
f"/repos/{repo}/pulls/{number}/files?per_page=100&page={page + 1}",
token,
)
if status != 200 or not isinstance(extra, list):
raise ScopeError(
"cannot confirm the changed file list is complete "
f"(HTTP {status})"
)
del files[MAX_FILES:]
return files, bool(extra)
page += 1
def fetch_pull(repo, number, token):
"""Return (labels, head sha, base sha) for one pull request."""
status, payload = github_api("GET", f"/repos/{repo}/pulls/{number}", token)
if status != 200 or not isinstance(payload, dict):
raise ScopeError(f"cannot read pull request (HTTP {status})")
labels = payload.get("labels") or []
head = ((payload.get("head") or {}).get("sha") or "").strip()
base = ((payload.get("base") or {}).get("sha") or "").strip()
names = {label.get("name", "") for label in labels if isinstance(label, dict)}
return names, head, base
def revision_drift(args, head, base):
"""Return a note when the tested revisions are no longer the live ones.
A re-run keeps the run's original SHAs while the file list served by GitHub
is the pull request's current one. After a force-push the classifier would
judge the new diff for the old tree, so a mismatch runs every suite instead.
"""
for supplied, live, name in (
(args.head_sha, head, "head"),
(args.base_sha, base, "base"),
):
if supplied and live and supplied.lower() != live.lower():
return (
f"pull request {name} moved from {supplied[:12]} to "
f"{live[:12]} after this run started"
)
return ""
# ---------------------------------------------------------------------------
# Decisions
# ---------------------------------------------------------------------------
def file_paths(item):
"""Every path the change touched; a rename keeps the deleted side too."""
names = [item["filename"]]
previous = item.get("previous_filename")
if previous and previous != item["filename"]:
names.append(previous)
return names
def gated_paths(item):
"""The paths of one changed file that the gate judges.
A path under `EXEMPT_TREES` is outside the remit: it selects no suite, and
it is not a change that "no rule covers", so it cannot widen the gate.
"""
return [name for name in file_paths(item) if not name.startswith(EXEMPT_TREES)]
def path_matches(files):
"""Return (always_run_hits, {suite_id: [matching file paths]})."""
always_compiled = compile_patterns(ALWAYS_RUN)
suite_matchers = {
suite_id: compile_patterns(suite_paths(suite))
for suite_id, suite in SUITES.items()
}
always_hits = set()
matches = {suite_id: set() for suite_id in SUITES}
for item in files:
for name in file_paths(item):
if matches_any(name, always_compiled):
always_hits.add(name)
for name in gated_paths(item):
for suite_id, compiled in suite_matchers.items():
if matches_any(name, compiled):
matches[suite_id].add(name)
return sorted(always_hits), {
suite_id: sorted(matched) for suite_id, matched in matches.items()
}
def uncovered_changes(files, matches):
"""True when a change can reach code that no suite path claims.
This is the net for a crate that was added, split or renamed after the rules
were written: without it such a change matches no suite and would skip every
gated job. A single unmatched path is enough, even when other paths in the
same diff match a suite.
"""
return first_uncovered(files, matches) is not None
def first_uncovered(files, matches):
"""The first changed path that no suite claims, or None.
Naming it is what makes the widening explainable in the log.
"""
matched = {name for names in matches.values() for name in names}
return next(
(
name
for item in files
for name in gated_paths(item)
if name.startswith(SRC_TREE) and name not in matched
),
None,
)
def has_meaningful_changes(files):
return any(CODE_FILE.search(item["filename"]) for item in files)
def finalize(plan):
"""`full` means every gated suite runs, whatever produced the decision."""
plan["full"] = all(entry["run"] for entry in plan["suites"].values())
return plan
def all_suites(run, reason, source):
return {
suite_id: {"run": run, "source": source, "reason": reason}
for suite_id in SUITES
}
def full_plan(plan, reason, source, mode="static"):
"""Every suite runs; `finalize` derives `full` from the verdicts."""
plan.update(mode=mode, suites=all_suites(True, reason, source))
return finalize(plan)
def forced_reason(args, labels):
"""Return why every suite must run, or an empty string."""
event = args.event or os.environ.get("GITHUB_EVENT_NAME") or "pull_request"
if event in FORCED_EVENTS:
return f"event={event}"
if os.environ.get("CI_SCOPE_FORCE_ALL", "").strip().lower() in {
"1",
"true",
"yes",
"on",
}:
return "CI_SCOPE_FORCE_ALL"
if "ci:full" in labels:
return "label ci:full"
return ""
def build_plan(args, token):
notes = []
plan = {
"mode": "static",
"head_sha": args.head_sha or "",
"base_sha": args.base_sha or "",
"full": False,
"suites": {},
"matching": {},
"notes": notes,
}
# Events and variables that force a run need no GitHub call at all; the
# `ci:full` label is the only reason to read the pull request early.
forced = forced_reason(args, set())
labels, head_live, base_live = set(), "", ""
if args.pr and not forced:
try:
labels, head_live, base_live = fetch_pull(
args.repo, args.pr, token
)
except ScopeError as err:
# A failed lookup must widen the gate, never narrow it.
notes.append(f"pull request lookup failed: {err}")
return full_plan(plan, "pull request lookup failed", "always-run")
forced = forced_reason(args, labels)
if forced:
notes.append(f"forced: {forced}")
return full_plan(plan, f"forced by {forced}", "forced", mode="forced")
if not args.pr:
raise ScopeError("--pr is required unless the event forces every suite")
drift = revision_drift(args, head_live, base_live)
if drift:
notes.append(drift)
return full_plan(plan, drift, "always-run")
files, truncated = fetch_changed_files(args.repo, args.pr, token)
if truncated:
notes.append(f"changed file list truncated at {MAX_FILES}")
return full_plan(
plan,
f"pull request has more than {MAX_FILES} changed files",
"always-run",
)
always_hits, matches = path_matches(files)
# Keep the evidence: the step summary explains a verdict by naming the files
# that matched, which is what triage asks for first.
plan["matching"] = {suite_id: sorted(names) for suite_id, names in matches.items()}
if always_hits:
notes.append(f"always-run: {', '.join(sorted(always_hits)[:5])}")
return full_plan(
plan,
"always-run path: " + ", ".join(sorted(always_hits)[:3]),
"always-run",
)
first = first_uncovered(files, matches)
if first is not None:
notes.append(f"uncovered build change: {first}")
return full_plan(plan, f"uncovered build change: {first}", "uncovered")
static_run = {suite_id: bool(matched) for suite_id, matched in matches.items()}
if not has_meaningful_changes(files) and not any(static_run.values()):
plan.update(
mode="static",
full=False,
suites={
suite_id: {
"run": False,
"source": "static",
"reason": "no code, config or workflow file changed",
}
for suite_id in SUITES
},
)
notes.append("no meaningful changes: skip every suite")
return finalize(plan)
plan.update(
mode="static",
suites={
suite_id: {
"run": static_run[suite_id],
"source": "static",
"reason": ("path rule: " + ", ".join(matches[suite_id][:3]))
if matches[suite_id]
else "no path rule matched",
}
for suite_id in SUITES
},
)
return finalize(plan)
def derive_outputs(plan):
"""Flatten the plan into the `$GITHUB_OUTPUT` keys the workflow gates on.
Every gate in `SUITES` must route to a key here, otherwise its suites are
classified but never switch a job; `test_every_gate_routes_to_an_output`
asks this function directly, so a new gate fails there until it is routed.
Job-level `if:` cannot read the `matrix` context, so the workflow gates a
whole fuzz gate instead of individual matrix legs; the per-suite verdicts
stay visible in the step log.
"""
def suites_of(gate):
return [
suite_id
for suite_id, entry in plan["suites"].items()
if entry["run"] and SUITES[suite_id]["gate"] == gate
]
outputs = {}
legs = {}
for gate in FUZZ_GATES:
running = suites_of(gate)
legs[gate] = [suite_group(suite_id) for suite_id in running]
legs[gate] = [leg for leg in legs[gate] if leg]
outputs[gate] = "true" if running else "false"
unstable = bool(suites_of("fuzz_unstable"))
# Every gate outside the fuzz group switches exactly one job of its own.
for gate in sorted({suite["gate"] for suite in SUITES.values()}):
if gate not in FUZZ_GATES:
outputs[gate] = "true" if suites_of(gate) else "false"
outputs["any_fuzz"] = (
"true"
if unstable or any(outputs[gate] == "true" for gate in FUZZ_GATES)
else "false"
)
distributed = outputs["fuzz_distributed"] == "true" or outputs["fuzz_chaos"] == "true"
outputs["build_ci_needed"] = "true" if unstable or distributed else "false"
return outputs, legs
def render_log(plan):
"""One line per suite plus the emitted gates, for the step log.
Triage starts in the run log, so the verdict has to be readable there
without any other artifact.
"""
head = f"CI scope: mode={plan['mode']} full={'true' if plan['full'] else 'false'}"
lines = [head]
width = max((len(suite_id) for suite_id in plan["suites"]), default=0)
for suite_id, entry in plan["suites"].items():
lines.append(
f" {'run ' if entry['run'] else 'skip'} {suite_id:<{width}} "
f"{entry['source']:<12} {entry['reason']}"
)
outputs, _ = derive_outputs(plan)
lines.append(
" gates: " + " ".join(f"{key}={value}" for key, value in outputs.items())
)
for note in plan["notes"]:
lines.append(f" note: {note}")
return "\n".join(lines)
SUMMARY_MAX_FILES = 3
def render_summary(plan):
"""Markdown for the job summary: the matching evidence behind each verdict.
The step log answers "what ran"; this answers "why", which is the question
when a pull request unexpectedly skips or starts a suite.
"""
lines = [
f"### CI scope: mode={plan['mode']}, full={'true' if plan['full'] else 'false'}",
"",
"| suite | verdict | rule | matched files |",
"| --- | --- | --- | --- |",
]
matching = plan.get("matching") or {}
for suite_id, entry in plan["suites"].items():
matched = matching.get(suite_id) or []
shown = ", ".join(f"`{name}`" for name in matched[:SUMMARY_MAX_FILES])
if len(matched) > SUMMARY_MAX_FILES:
shown += f" +{len(matched) - SUMMARY_MAX_FILES} more"
lines.append(
f"| `{suite_id}` | {'run' if entry['run'] else 'skip'} | "
f"{entry['source']} | {shown or '—'} |"
)
if plan["notes"]:
lines += ["", "<details><summary>notes</summary>", ""]
lines += [f"- {note}" for note in plan["notes"]]
lines += ["", "</details>"]
return "\n".join(lines)
def log_annotations(plan):
"""Workflow-run annotations for every degraded decision.
A lookup failure widens the gate; it must be visible in the run list without
opening the job log, otherwise it looks like a confident verdict.
"""
annotations = []
for note in plan["notes"]:
if note.startswith("pull request lookup failed"):
suffix = "every suite runs"
level = "warning"
else:
continue
message = f"CI scope: {note}; {suffix}"[:300]
annotations.append(f"::{level}::{message}")
return annotations
def emit(plan, args):
outputs, _ = derive_outputs(plan)
if args.dry_run:
print(json.dumps(outputs, indent=2))
elif args.github_output:
with open(args.github_output, "a", encoding="utf-8") as handle:
for key, value in outputs.items():
handle.write(f"{key}={value}\n")
if args.summary:
with open(args.summary, "a", encoding="utf-8") as handle:
handle.write(render_summary(plan) + "\n")
def parse_args(argv):
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument("--repo", default=os.environ.get("GITHUB_REPOSITORY", ""))
parser.add_argument("--pr", type=int)
parser.add_argument("--head-sha", default="")
parser.add_argument("--base-sha", default="")
parser.add_argument(
"--event",
choices=["pull_request", "merge_group", "schedule", "workflow_dispatch"],
)
parser.add_argument("--github-output")
parser.add_argument(
"--summary",
help="append the markdown matching table to this file ($GITHUB_STEP_SUMMARY)",
)
parser.add_argument("--dry-run", action="store_true")
return parser.parse_args(argv)
def main(argv=None):
args = parse_args(argv)
token = os.environ.get("GITHUB_TOKEN") or os.environ.get("GH_TOKEN") or ""
plan = build_plan(args, token)
for annotation in log_annotations(plan):
print(annotation)
print(render_log(plan))
emit(plan, args)
return 0
if __name__ == "__main__":
sys.exit(main())
+277
View File
@@ -0,0 +1,277 @@
#!/usr/bin/env python3
# Copyright 2023 Greptime Team
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Policy for the integration CI admission gate.
The rules are data and live in `.github/ci/scope-rules.toml` so they can be
reviewed and changed without touching the classifier. This module parses that
file once at import, validates it, and exposes the names `ci_scope.py` uses.
A malformed file raises at import: the classifier job's steps are
`continue-on-error`, so a broken rules file leaves the gate outputs empty and
every gated job runs.
"""
import argparse
import pathlib
import sys
import tomllib
RULES_PATH = pathlib.Path(__file__).resolve().with_name("scope-rules.toml")
# `.github/ci/scope-rules.toml`: parents[0] is `.github/ci`, parents[2] the repo.
REPO_ROOT = RULES_PATH.parents[2]
class RulesError(ValueError):
"""The rules file is missing, malformed or internally inconsistent."""
def _require(table, key, where):
if key not in table:
raise RulesError(f"{where} is missing `{key}`")
return table[key]
def _strings(value, where):
if not isinstance(value, list) or not all(isinstance(item, str) for item in value):
raise RulesError(f"{where} must be an array of strings")
return list(value)
def _trees(entries, where):
"""Normalise `[[matching.*_tree]]` tables into bare path prefixes.
Each entry carries a `reason`: the exclusions decide what CI never runs, so
the justification is part of the contract, not a comment.
"""
if not isinstance(entries, list):
raise RulesError(f"{where} must be an array of tables")
paths = []
for index, entry in enumerate(entries):
if not isinstance(entry, dict):
raise RulesError(f"{where}[{index}] is not a table")
path = _require(entry, "path", f"{where}[{index}]")
if not isinstance(path, str) or not path:
raise RulesError(f"{where}[{index}].path must be a non-empty string")
reason = _require(entry, "reason", f"{where}[{index}]")
if not isinstance(reason, str) or not reason.strip():
raise RulesError(f"{where}[{index}].reason must explain the exclusion")
paths.append(path)
return paths
def validate(data):
"""Check the shape of a parsed rules document and return it normalised."""
if not isinstance(data, dict):
raise RulesError("rules document is not a table")
matching = _require(data, "matching", "the rules file")
gates_in = _require(data, "gates", "the rules file")
groups_in = _require(data, "groups", "the rules file")
suites_in = _require(data, "suites", "the rules file")
groups = {}
for name, paths in groups_in.items():
groups[name] = _strings(paths, f"groups.{name}")
def expand(entries, stack=()):
out = []
for entry in entries:
if not entry.startswith("@"):
out.append(entry)
continue
name = entry[1:]
if name not in groups:
raise RulesError(f"unknown path group `{entry}`")
if name in stack:
raise RulesError(f"path group cycle: {' -> '.join(stack + (name,))}")
out.extend(expand(groups[name], stack + (name,)))
return out
for name in groups:
expand([f"@{name}"]) # every group must resolve on its own
suites = {}
for suite_id, suite in suites_in.items():
if not isinstance(suite, dict):
raise RulesError(f"suites.{suite_id} is not a table")
gate = _require(suite, "gate", f"suites.{suite_id}")
paths = _strings(
_require(suite, "paths", f"suites.{suite_id}"), f"suites.{suite_id}.paths"
)
description = _require(suite, "description", f"suites.{suite_id}")
if not isinstance(description, str) or not description.strip():
raise RulesError(f"suites.{suite_id}.description is empty")
# `gate/leg` for a matrix job, or a bare gate for a single-leg job.
prefix = suite_id.split("/", 1)[0].replace("-", "_")
if prefix != gate:
raise RulesError(
f"suites.{suite_id}.gate is `{gate}`, expected `{prefix}`"
)
expand(paths)
suites[suite_id] = {
"gate": gate,
"paths": paths,
"description": description,
}
gate_jobs = {}
for gate, job in gates_in.items():
if not isinstance(job, str) or not job:
raise RulesError(f"gates.{gate} must name a job id")
gate_jobs[gate] = job
used = {suite["gate"] for suite in suites.values()}
unknown = sorted(used - set(gate_jobs))
if unknown:
raise RulesError(f"suites use gates missing from [gates]: {', '.join(unknown)}")
dead = sorted(set(gate_jobs) - used)
if dead:
raise RulesError(f"[gates] names gates no suite uses: {', '.join(dead)}")
return {
"always_run": _strings(
_require(matching, "always_run", "matching"), "matching.always_run"
),
"src_tree": _require(matching, "src_tree", "matching"),
"exempt_trees": _trees(
_require(matching, "exempt", "matching"), "matching.exempt"
),
"gates": gate_jobs,
"groups": groups,
"suites": suites,
}
def load(path=None):
"""Parse and validate the rules file."""
path = RULES_PATH if path is None else path
try:
raw = pathlib.Path(path).read_bytes()
except OSError as err:
raise RulesError(f"cannot read {path}: {err}") from err
try:
data = tomllib.loads(raw.decode("utf-8"))
except (tomllib.TOMLDecodeError, UnicodeDecodeError) as err:
raise RulesError(f"{path} is not valid TOML: {err}") from err
return validate(data)
_RULES = load()
ALWAYS_RUN = _RULES["always_run"]
SRC_TREE = _RULES["src_tree"]
EXEMPT_TREES = tuple(_RULES["exempt_trees"])
GATE_JOBS = _RULES["gates"]
PATH_GROUPS = _RULES["groups"]
SUITES = _RULES["suites"]
def main(argv=None):
"""Validate the rules file and print what it holds; non-zero on failure."""
parser = argparse.ArgumentParser(description="Validate the CI scope rules.")
parser.add_argument(
"--check-paths",
action="store_true",
help="also fail when a pattern's literal prefix does not exist",
)
args = parser.parse_args(argv)
try:
rules = load()
except RulesError as err:
print(f"scope rules invalid: {err}", file=sys.stderr)
return 1
if args.check_paths:
missing = missing_paths(rules)
for pattern, prefix in missing:
print(f"missing path: {pattern} (nothing under {prefix})", file=sys.stderr)
return 1 if missing else 0
print(
f"scope rules ok: {len(rules['suites'])} suites, "
f"{len(rules['groups'])} path groups, "
f"{len(rules['always_run'])} always-run entries"
)
return 0
def suite_group(suite_id):
"""Return the matrix group id encoded in a suite id, or None."""
_, _, group = suite_id.partition("/")
return group or None
def expand_paths(entries, groups=None):
"""Expand `@group` references, including groups nested in other groups."""
groups = PATH_GROUPS if groups is None else groups
patterns = []
for entry in entries:
if entry.startswith("@"):
patterns.extend(expand_paths(groups[entry[1:]], groups))
else:
patterns.append(entry)
return patterns
def suite_paths(suite):
"""Expand `@group` references in one suite definition into globs."""
return expand_paths(suite["paths"])
def _literal_prefix(pattern):
"""Return the longest leading path that the glob cannot vary.
Everything from the first `*`, `?` or `[` onwards is variable. When that
wildcard sits inside a segment the incomplete segment is dropped, so
`src/a/foo*.rs` yields `src/a/`; a wildcard in the very first segment (for
example `*.md`) yields `""` because the whole path is variable.
"""
cuts = [pattern.find(ch) for ch in "*?[" if ch in pattern]
if not cuts:
return pattern
prefix = pattern[: min(cuts)]
if "/" not in prefix:
return ""
return prefix.rsplit("/", 1)[0] + "/"
def _all_patterns(rules):
"""Every glob the rules mention, with `@group` references expanded."""
patterns = []
for key in ("always_run", "exempt_trees"):
patterns.extend(expand_paths(rules[key], rules["groups"]))
for suite in rules["suites"].values():
patterns.extend(expand_paths(suite["paths"], rules["groups"]))
return patterns
def missing_paths(rules=None, root=None):
"""Return `(pattern, prefix)` for patterns whose literal prefix is absent.
A rule that names a directory nobody renamed would otherwise match nothing
forever, silently narrowing the gate. A pattern with no fixed prefix is
skipped: there is nothing on disk to check.
"""
rules = _RULES if rules is None else rules
root = pathlib.Path(REPO_ROOT if root is None else root)
missing = set()
for pattern in _all_patterns(rules):
prefix = _literal_prefix(pattern)
if prefix and not (root / prefix).exists():
missing.add((pattern, prefix))
return sorted(missing)
if __name__ == "__main__":
sys.exit(main())
+285
View File
@@ -0,0 +1,285 @@
# Rules for the integration CI admission gate.
#
# Data only: `ci_scope_rules.py` loads this file with the stdlib `tomllib`, and
# `ci_scope.py` matches diffs against it. Edit this file, not the code, when a
# suite's paths change.
#
# Conventions
# -----------
# - `**` crosses directories, `*` does not; a trailing `/**` covers everything
# under a directory.
# - `@name` inside `suites.*.paths` expands `[groups].name`, and groups may
# reference other groups. Expansion is recursive.
# - A suite id is `<gate>/<matrix group id>`; `gate` is the `$GITHUB_OUTPUT`
# key that switches the job, and it must equal the id prefix with `-`
# replaced by `_`.
# - Everything here is a floor, never a filter: an unmatched `src/` path runs
# every suite, and a malformed file fails the classifier job, whose steps are
# `continue-on-error`, so the gated jobs run.
[matching]
# A changed file matching one of these runs every suite.
# Put here anything that changes what the suites build or how they start.
always_run = [
"Cargo.toml",
"Cargo.lock",
"rust-toolchain.toml",
".cargo/**",
"tests-fuzz/**",
"tests-integration/**",
"config/**",
"docker/**",
".github/ci/**",
".github/workflows/integration.yml",
".github/actions/**",
# Both run through a composite action, so neither appears in the workflow:
# `setup-kind` starts the cluster for the distributed and chaos jobs, and
# `fuzz-test` seeds the corpus every fuzz job starts from.
".github/scripts/kind-with-registry.sh",
".github/scripts/prepare-fuzz-corpus.sh",
".github/scripts/run-fuzz-targets.sh",
".github/scripts/collect-fuzz-target-artifacts.sh",
".github/scripts/wait-kafka-ready.sh",
".github/scripts/pull-test-deps-images.sh",
]
# A change under `src/` that no suite claims runs every suite: that is the net
# for a crate added, split or renamed after these rules were written.
src_tree = "src/"
# Paths outside the gate's remit. They select no suite, and they do not count as
# "no rule covers this" either, so they never widen the gate. Each needs a
# `reason`: what CI covers them instead.
[[matching.exempt]]
path = "src/promql/"
reason = "PromQL crate: rust.yml and the promql sqlness cases own it; the fuzz suites speak SQL."
[[matching.exempt]]
path = "src/query/src/promql/"
reason = "PromQL module inside `src/query`, which `@server` claims as `src/query/**`."
[[matching.exempt]]
path = "src/flow/"
reason = "Flow engine: rust.yml and the flow sqlness cases own it; no fuzz suite loads it."
# Which job each gate switches. The keys are `$GITHUB_OUTPUT` names; the values
# are job ids in `integration.yml`. The classifier cannot read YAML, so the
# mapping is data here, and a test proves both directions line up.
[gates]
fuzz_standalone = "fuzztest"
fuzz_unstable = "unstable-fuzztest"
fuzz_distributed = "distributed-fuzztest"
fuzz_chaos = "distributed-fuzztest-with-chaos"
export_import_v2 = "export-import-v2-e2e"
sqlness_kvbackend = "sqlness-kvbackend"
[groups]
server = [
"src/operator/**",
"src/sql/**",
"src/catalog/**",
"src/datatypes/**",
"src/table/**",
"src/store-api/**",
"src/session/**",
"src/api/**",
"src/servers/**",
"src/frontend/**",
# Also covers `src/query/src/promql/`, which is exempt (see
# `[[matching.exempt]]`): a PromQL-only change must not run the fuzz fleet.
"src/query/**",
"src/partition/**",
"src/index/**",
"src/object-store/**",
"src/cache/**",
"src/puffin/**",
"src/auth/**",
"src/client/**",
"src/log-query/**",
"src/pipeline/**",
"src/plugins/**",
"src/cmd/**",
"src/standalone/**",
"src/datanode/**",
"src/common/base/**",
"src/common/batcher/**",
"src/common/cache/**",
"src/common/catalog/**",
"src/common/config/**",
"src/common/datasource/**",
"src/common/decimal/**",
"src/common/error/**",
"src/common/event-recorder/**",
"src/common/frontend/**",
"src/common/function/**",
"src/common/grpc/**",
"src/common/grpc-expr/**",
"src/common/greptimedb-telemetry/**",
"src/common/macro/**",
"src/common/mem-prof/**",
"src/common/memory-manager/**",
"src/common/options/**",
"src/common/plugins/**",
"src/common/pprof/**",
"src/common/query/**",
"src/common/recordbatch/**",
"src/common/runtime/**",
"src/common/session/**",
"src/common/sql/**",
"src/common/stat/**",
"src/common/substrait/**",
"src/common/telemetry/**",
"src/common/test-util/**",
"src/common/time/**",
"src/common/version/**",
"src/common/workload/**",
]
# Storage engines and WAL.
engine = [
"src/mito2/**",
"src/mito-codec/**",
"src/metric-engine/**",
"src/file-engine/**",
"src/log-store/**",
"src/common/wal/**",
]
# DDL and procedure code standalone executes in-process: it builds a
# `DdlManager` and runs `LocalProcedureExecutor` without any metasrv.
meta-core = [
"src/common/meta/**",
"src/common/procedure/**",
"src/common/procedure-test/**",
]
# Everything that sits on the KV backend the two sqlness KvBackend legs
# exercise: the backend implementations, the metadata service and the startup
# wiring that picks a backend.
kv-backend = [
# The runner implements `--setup-pg`/`--setup-mysql`, which only these legs pass.
"tests/runner/**",
"src/common/meta/**",
"src/meta-srv/**",
"src/meta-client/**",
"src/common/procedure/**",
"src/cmd/**",
"src/common/config/**",
"src/common/options/**",
]
# Adds the metasrv/meta-client crates on top of the in-process DDL code.
meta = [
"src/meta-srv/**",
"src/meta-client/**",
"@meta-core",
]
[suites."fuzz-standalone/database-and-regular-table"]
gate = "fuzz_standalone"
paths = [
"@server",
"@engine",
"@meta-core",
]
description = "Standalone-server black-box fuzz of CREATE DATABASE/TABLE, ALTER, INSERT over MySQL."
[suites."fuzz-standalone/logical-table"]
gate = "fuzz_standalone"
paths = [
"@server",
"@engine",
"@meta-core",
]
description = "Standalone logical-table DDL/INSERT fuzz (mito2 logical tables)."
[suites."fuzz-unstable/standalone"]
gate = "fuzz_unstable"
paths = [
"@server",
"@engine",
"@meta-core",
]
description = "Unstable standalone create-table fuzz (nix build feature)."
[suites."fuzz-distributed/database-and-regular-table"]
gate = "fuzz_distributed"
paths = [
"@server",
"@engine",
"@meta",
]
description = "Distributed (frontend/datanode/metasrv, remote WAL) DDL/DML fuzz."
[suites."fuzz-distributed/logical-table"]
gate = "fuzz_distributed"
paths = [
"@server",
"@engine",
"@meta",
]
description = "Distributed logical-table fuzz."
[suites."fuzz-distributed/repartition"]
gate = "fuzz_distributed"
paths = [
"@server",
"@engine",
"@meta",
]
description = "Distributed repartition ALTER TABLE + GC fuzz."
[suites."fuzz-distributed/logical-pruning"]
gate = "fuzz_distributed"
paths = [
"@engine",
"@meta",
]
description = "Remote-WAL logical table pruning of stale manifests."
[suites."fuzz-chaos/migration"]
gate = "fuzz_chaos"
paths = [
"@server",
"@engine",
"@meta",
]
description = "Region migration under Chaos Mesh, mito and metric engines."
[suites."fuzz-chaos/failover"]
gate = "fuzz_chaos"
paths = [
"@server",
"@engine",
"@meta",
]
description = "Region failover under Chaos Mesh, mito and metric engines."
[suites."fuzz-chaos/repartition"]
gate = "fuzz_chaos"
paths = [
"@server",
"@engine",
"@meta",
]
description = "Repartition + GC under Chaos Mesh."
[suites."export-import-v2"]
gate = "export_import_v2"
paths = [
"src/cli/**",
"@server",
"@engine",
"@meta-core",
]
description = "CLI COPY DATABASE export/import v2 end-to-end against S3."
[suites."sqlness-kvbackend/metasrv-postgres"]
gate = "sqlness_kvbackend"
paths = ["@kv-backend"]
description = "Sqlness with PostgreSQL as the metadata KV backend."
[suites."sqlness-kvbackend/metasrv-mysql"]
gate = "sqlness_kvbackend"
paths = ["@kv-backend"]
description = "Sqlness with MySQL as the metadata KV backend."
+158
View File
@@ -0,0 +1,158 @@
# Golden cases for the admission gate.
#
# `tests/test_ci_scope.py` replays every case through the real classifier,
# so an edit to `scope-rules.toml` that changes behaviour fails with the case
# name here. The cases encode intent, not implementation: each one says which
# suites a kind of change must start.
#
# `suites` is a list of globs over suite ids; `["*"]` means every suite and
# `[]` means none.
[[case]]
name = "server crate: the whole fuzz fleet except the pruning suite"
note = "A change to `src/api` reaches every suite that builds the server binary."
paths = [
"src/api/src/lib.rs",
]
suites = [
"fuzz-standalone/database-and-regular-table",
"fuzz-standalone/logical-table",
"fuzz-unstable/standalone",
"fuzz-distributed/database-and-regular-table",
"fuzz-distributed/logical-table",
"fuzz-distributed/repartition",
"fuzz-chaos/migration",
"fuzz-chaos/failover",
"fuzz-chaos/repartition",
"export-import-v2",
]
[[case]]
name = "storage engine: every fuzz suite, including remote-WAL pruning"
note = "logical-pruning needs engine and DDL code, so an engine change starts it."
paths = [
"src/mito2/src/lib.rs",
]
suites = [
"fuzz-standalone/*",
"fuzz-unstable/*",
"fuzz-distributed/*",
"fuzz-chaos/*",
"export-import-v2",
]
[[case]]
name = "in-process DDL code registers the procedures standalone executes"
paths = [
"src/common/meta/src/lib.rs",
]
suites = [
"fuzz-standalone/*",
"fuzz-unstable/*",
"fuzz-distributed/*",
"fuzz-chaos/*",
"export-import-v2",
"sqlness-kvbackend/*",
]
[[case]]
name = "metasrv only: distributed and chaos families"
note = "Standalone builds a DdlManager in-process and never links a metasrv."
paths = [
"src/meta-srv/src/discovery/lease.rs",
]
suites = [
"fuzz-distributed/database-and-regular-table",
"fuzz-distributed/logical-table",
"fuzz-distributed/repartition",
"fuzz-distributed/logical-pruning",
"fuzz-chaos/migration",
"fuzz-chaos/failover",
"fuzz-chaos/repartition",
"sqlness-kvbackend/*",
]
[[case]]
name = "CLI only touches the export/import path"
paths = [
"src/cli/src/lib.rs",
]
suites = [
"export-import-v2",
]
[[case]]
name = "PromQL crate: no suite"
note = "rust.yml and the promql sqlness cases own it; the fuzz suites speak SQL."
paths = [
"src/promql/src/lib.rs",
]
suites = []
[[case]]
name = "PromQL module inside the query crate is not fuzzable either"
note = "`@server` claims `src/query/**`, so the module must be exempt."
paths = [
"src/query/src/promql/src/lib.rs",
]
suites = []
[[case]]
name = "flow engine: no suite"
paths = [
"src/flow/src/lib.rs",
]
suites = []
[[case]]
name = "mixed diff: the PromQL file subtracts nothing"
note = "The engine change still starts every suite."
paths = [
"src/mito2/src/lib.rs",
"src/promql/src/lib.rs",
]
suites = [
"fuzz-standalone/*",
"fuzz-unstable/*",
"fuzz-distributed/*",
"fuzz-chaos/*",
"export-import-v2",
]
[[case]]
name = "crate added after the rules were written"
note = "No suite claims it, so the gate widens instead of skipping everything."
paths = [
"src/brand-new/src/lib.rs",
]
suites = ["*"]
[[case]]
name = "integration harness change"
paths = [
"tests-integration/tests/fuzz.rs",
]
suites = ["*"]
[[case]]
name = "documentation only"
paths = [
"docs/readme.md",
]
suites = []
[[case]]
name = "kind registry setup: every suite"
note = "The distributed and chaos fuzz jobs start their cluster with this script."
paths = [
".github/scripts/kind-with-registry.sh",
]
suites = ["*"]
[[case]]
name = "fuzz corpus seeding: every suite"
note = "Every fuzz job seeds its corpus through the `fuzz-test` action first."
paths = [
".github/scripts/prepare-fuzz-corpus.sh",
]
suites = ["*"]
+1018
View File
File diff suppressed because it is too large Load Diff
+28
View File
@@ -0,0 +1,28 @@
# Heavy CI scheduling
Checks, Rust CI, and Integration CI each run the shared GitHub script test
action before expensive builds and tests. A failed, skipped, or cancelled
script-test job blocks those jobs, including manually dispatched runs. Each
workflow runs its own preflight so it does not wait on another workflow run.
Rust CI keeps the Windows compilation check on PRs and merge groups. Windows
nextest and Windows SQLness run in the existing Nightly CI workflow, which also
supports manual dispatch. Its existing schedule is Tuesday through Friday at
07:00 Asia/Shanghai, not every day. No new Windows test job is added.
Integration CI admits fuzz when a non-draft PR is opened or marked ready for
review, selecting suites with the existing diff-scope classifier. Its weekday
schedule (23:00 Asia/Shanghai, Monday through Friday) runs all fuzz suites. Ordinary pushes and reopening do not run fuzz; core
integration checks still run. Merge groups continue to skip fuzz.
Re-running an ordinary push-triggered Integration CI run does not enable fuzz.
A new push can cancel an earlier ready-for-review run. Use an explicit fuzz
profile through the CI entry points below when later changes need fuzz coverage.
For a same-repository branch, use **Run workflow** and select `fuzz_profile`
(`standalone`, `distributed`, `chaos`, or `all`). The default `none` runs core
integration without fuzz. The existing `/ci fuzz ...` commands remain available
for same-repository draft PRs with their existing authorization rules.
Validate job admission with `node --test .github/scripts/heavy-ci-policy.test.cjs`.
These tests verify triggering decisions, not runner availability or performance.
+45
View File
@@ -0,0 +1,45 @@
# Nightly merge
The PR template opts new PRs into the `merge nightly` label. The Nightly Merge
workflow reconciles the label on PR creation, edits, and reopening. Existing PRs
without the checkbox can opt in by adding the label manually; label sync leaves
their labels unchanged. Unchecking removes the label; it does not
request an immediate merge or cancel an existing queue entry/auto-merge request.
Every day at 02:10, 03:10, 04:10, 05:10, 06:10, 07:10, and 08:10
Asia/Shanghai (UTC+8), the workflow enqueues up to five eligible PRs targeting
`main` per run, oldest first. Already queued PRs do not count toward this limit.
GitHub may delay scheduled runs.
The label alone controls nightly opt-in; the enqueue job does not check the PR
body. PRs must be approved and clean, and have all
review threads resolved. Drafts are skipped.
Already queued PRs and manually enabled auto-merge requests are left alone;
Maintainers can use **Merge when ready** to proceed earlier. Unready PRs wait for a later
scheduled run; this workflow never enables auto-merge on their behalf.
## Repository setup
- Create the `merge nightly` label before enabling the workflow.
- Require the merge queue, reviews, status checks, and conversation resolution
on `main`. Conversation resolution must also be enforced by GitHub to cover
new comments arriving between the script's check and enqueueing.
- Ensure the existing `GH_PERSONAL_ACCESS_TOKEN` automation secret can read PRs
and review threads and enqueue PRs in this repository. Do not grant it a
branch-rule bypass. This credential is already referenced by other workflows;
its actual permissions have not been validated by the local tests.
- Run **Nightly Merge** manually with the default `dry_run: true` first and
inspect its job summary. Setting it to false explicitly enqueues outside the
scheduled time as well. Merge queue build concurrency is configured separately
in GitHub; this workflow does not change it.
The workflow never checks out or executes PR code. Label reconciliation uses
`GITHUB_TOKEN`; enqueueing uses the automation credential so downstream CI can
run. No runner remains allocated while waiting for the nightly schedule.
## Local validation
Run `actionlint .github/workflows/nightly-merge.yml .github/workflows/checks.yml`
and `node --test .github/scripts/tests/nightly-merge.test.cjs`.
The tests execute the actual inline workflow scripts with mocked GitHub APIs,
including one-factor comparisons against an eligible PR. They do not validate
live GitHub permissions, branch rules, or runner savings.
+11
View File
@@ -25,3 +25,14 @@ Please convert it to a draft if some of the following conditions are not met.
- [ ] API changes are backward compatible.
- [ ] Schema or data changes are backward compatible.
- [ ] This PR needs to be backported to release branches, and I have added the `backport-<target>` labels (e.g. `backport-v1.3` targets `release/v1.3`).
## Merge timing
- [x] Merge during the nightly window <!-- nightly-merge -->
<!--
Eligible PRs enter the merge queue hourly from 02:10 through 08:10 Beijing time (UTC+8), up to five per run.
Uncheck to opt out and remove the `merge nightly` label; this does not enable immediate merging.
Maintainers can use **Merge when ready** to merge earlier.
Changing this checkbox does not cancel an existing queue entry or manually enabled auto-merge.
-->
+105
View File
@@ -0,0 +1,105 @@
const { readFileSync } = require('node:fs');
const { resolve } = require('node:path');
const assert = require('node:assert/strict');
const { test } = require('node:test');
const workflows = resolve(__dirname, '../workflows');
const integration = readFileSync(resolve(workflows, 'integration.yml'), 'utf8');
const suites = ['fuzztest', 'unstable-fuzztest', 'distributed-fuzztest', 'distributed-fuzztest-with-chaos'];
const prerequisites = ['prepare-fuzz-targets', 'build-greptime-ci'];
function enabled(job, { event = 'pull_request', action = 'synchronize', draft = false, attempt = 1, profile = 'none', repository = 'GreptimeTeam/greptimedb', outputs = {}, results = {}, cancelled = false, workflow = integration } = {}) {
const block = workflow.split(` ${job}:\n`)[1].split(/\n [a-z][\w-]*:/)[0];
if (block.includes("needs['github-script-tests']")) {
assert.match(block, /^ needs: \[.*github-script-tests.*\]/m);
}
const expression = block.match(/^ if: \$\{\{ (.+) \}\}/m)[1];
// These job guards use only operators whose semantics match JS for this fixture.
return new Function('github', 'inputs', 'needs', 'cancelled', `return (${expression});`)(
{ repository, event_name: event, event: { action, pull_request: { draft } }, run_attempt: attempt },
{ fuzz_profile: profile, ci_command: false },
{ scope: { outputs }, ...Object.fromEntries(['github-script-tests', 'build', ...prerequisites].map(name => [name, { result: results[name] || 'success' }])) },
() => cancelled
);
}
test('fuzz event policy on ready PR admission and schedule, not every update', () => {
for (const job of [...suites, ...prerequisites]) {
for (const action of ['opened', 'ready_for_review']) assert.equal(enabled(job, { action }), true, job);
for (const action of ['synchronize', 'reopened']) assert.equal(enabled(job, { action }), false, job);
assert.equal(enabled(job, { event: 'schedule' }), true, job);
assert.equal(enabled(job, { event: 'merge_group' }), false, job);
assert.equal(enabled(job, { attempt: 2 }), false, job);
assert.equal(enabled(job, { action: 'opened', draft: true }), false, job);
assert.equal(enabled(job, { attempt: 2, draft: true }), false, job);
assert.equal(enabled(job, { event: 'schedule', repository: 'fork/greptimedb' }), false, job);
}
});
test('manual profiles select only their suite and all required build jobs', () => {
const expected = { none: [], standalone: suites.slice(0, 2), distributed: [suites[2]], chaos: [suites[3]], all: suites };
for (const [profile, jobs] of Object.entries(expected)) {
assert.deepEqual(suites.filter(job => enabled(job, { event: 'workflow_dispatch', profile })), jobs);
for (const job of prerequisites) assert.equal(enabled(job, { event: 'workflow_dispatch', profile }), profile !== 'none');
}
});
test('core integration tests still run on PR updates and merge groups', () => {
for (const job of ['build', 'sqlness', 'export-import-v2-e2e', 'run-multi-lang-tests']) {
assert.equal(enabled(job), true, job);
assert.equal(enabled(job, { event: 'merge_group' }), true, job);
}
});
test('Windows compilation stays in Rust CI; test coverage remains in Nightly CI', () => {
const rust = readFileSync(resolve(workflows, 'rust.yml'), 'utf8');
const nightly = readFileSync(resolve(workflows, 'nightly-ci.yml'), 'utf8');
assert.match(rust, /^ check-windows:/m);
assert.doesNotMatch(rust, /^ test-windows:/m);
assert.match(nightly, /^ test-on-windows:/m);
assert.match(nightly, /^ sqlness-windows:/m);
assert.match(nightly, /cargo nextest run -F dashboard/);
assert.match(nightly, /^ workflow_dispatch:/m);
});
test('scope exclusions and dependency failures compose with the event policy', () => {
const gates = {
'prepare-fuzz-targets': 'any_fuzz', 'build-greptime-ci': 'build_ci_needed',
fuzztest: 'fuzz_standalone', 'unstable-fuzztest': 'fuzz_unstable',
'distributed-fuzztest': 'fuzz_distributed', 'distributed-fuzztest-with-chaos': 'fuzz_chaos'
};
for (const [job, gate] of Object.entries(gates)) {
assert.equal(enabled(job, { action: 'opened', outputs: { [gate]: 'false' } }), false, job);
assert.equal(enabled(job, { action: 'opened', outputs: {} }), true, job);
assert.equal(enabled(job, { outputs: { [gate]: 'true' } }), false, job);
assert.equal(enabled(job, { action: 'opened', cancelled: true }), false, job);
}
for (const job of suites) {
for (const result of ['failure', 'skipped', 'cancelled']) {
assert.equal(enabled(job, { action: 'opened', results: { 'prepare-fuzz-targets': result } }), false, job);
const build = job === 'fuzztest' ? 'build' : 'build-greptime-ci';
assert.equal(enabled(job, { action: 'opened', results: { [build]: result } }), false, job);
}
}
});
test('script tests must pass before any expensive integration job can start', () => {
const jobs = ['build', 'sqlness', 'sqlness-kvbackend', 'export-import-v2-e2e',
'run-multi-lang-tests', 'compat', ...prerequisites, ...suites];
for (const job of jobs) {
assert.equal(enabled(job, { action: 'opened' }), true, job);
for (const result of ['failure', 'skipped', 'cancelled']) {
assert.equal(enabled(job, { action: 'opened', results: { 'github-script-tests': result } }), false, job);
}
}
});
test('script tests gate expensive Rust and Checks jobs', () => {
for (const [file, jobs] of [
['rust.yml', ['clippy', 'check-riscv64', 'check-windows', 'test', 'coverage']],
['checks.yml', ['check']]
]) {
const workflow = readFileSync(resolve(workflows, file), 'utf8');
for (const job of jobs) {
const event = job === 'coverage' ? 'merge_group' : 'workflow_dispatch';
assert.equal(enabled(job, { workflow, event }), true, job);
for (const result of ['failure', 'skipped', 'cancelled']) {
assert.equal(enabled(job, { workflow, event, results: { 'github-script-tests': result } }), false, job);
}
}
}
});
@@ -0,0 +1,125 @@
// 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.
// Run with: node --test .github/scripts/tests/nightly-merge.test.cjs
const { readFileSync } = require('node:fs');
const { resolve } = require('node:path');
const assert = require('node:assert/strict');
const { test } = require('node:test');
const AsyncFunction = Object.getPrototypeOf(async function () {}).constructor;
const workflow = readFileSync(resolve(__dirname, '../../workflows/nightly-merge.yml'), 'utf8');
const scripts = [...workflow.matchAll(/ script: \|\n((?: .*\n|\n)+)/g)]
.map(match => new AsyncFunction('github', 'context', 'core', 'process', match[1].replace(/^ /gm, '')));
assert.equal(scripts.length, 2);
const checked = '- [x] Merge during the nightly window <!-- nightly-merge -->';
async function run({ sync = false, body = checked, labels = ['merge nightly'],
detail = {}, current = {}, threads = [[true]], count = 1, dryRun = false,
failFirst = false } = {}) {
const calls = [];
let page = 0;
const github = {
rest: {
pulls: { get: async () => ({ data: { state: 'open', draft: false, base: { ref: 'main' },
body, labels: labels.map(name => ({ name })), ...current } }) },
issues: {
listForRepo: () => {},
addLabels: async args => calls.push(['add', args.labels]),
removeLabel: async args => calls.push(['remove', args.name])
}
},
paginate: async () => Array.from({ length: count }, (_, i) => ({ number: i + 1, pull_request: {} })),
graphql: async (query, args) => {
if (query.includes('mutation')) {
calls.push(['enqueue', args]);
if (failFirst && calls.filter(call => call[0] === 'enqueue').length === 1) throw Error('head changed');
return {};
}
if (query.includes('reviewThreads')) {
const index = page++ % threads.length;
calls.push(['threads', args.cursor]);
return { repository: { pullRequest: { reviewThreads: {
nodes: threads[index].map(isResolved => ({ isResolved })),
pageInfo: { hasNextPage: index + 1 < threads.length, endCursor: `page-${index}` }
} } } };
}
return { repository: { pullRequest: { id: `PR_${args.number}`, headRefOid: 'abc',
reviewDecision: 'APPROVED', mergeStateStatus: 'CLEAN', ...detail } } };
}
};
const summary = { addHeading() { return this; }, addTable(rows) { calls.push(['summary', rows]); return this; }, async write() {} };
await scripts[sync ? 0 : 1](github,
{ repo: { owner: 'GreptimeTeam', repo: 'greptimedb' }, payload: { pull_request: { number: 1 } } },
{ summary, info() {}, warning() {}, setFailed: message => calls.push(['failed', message]) },
{ env: { DRY_RUN: String(dryRun) } });
return calls;
}
test('label sync grants PR label write permission without checking out PR code', () => {
const syncJob = workflow.split(' sync-label:\n')[1].split(' enqueue:\n')[0];
assert.match(syncJob, /^ pull-requests: write$/m);
assert.doesNotMatch(syncJob, /uses: actions\/checkout/);
});
test('template opts in and checkbox edits reconcile only the nightly label', async () => {
assert.ok(readFileSync(resolve(__dirname, '../../pull_request_template.md'), 'utf8').includes(checked));
assert.deepEqual(await run({ sync: true, labels: ['bug'] }), [['add', ['merge nightly']]]);
assert.deepEqual(await run({ sync: true }), []);
for (const body of [checked.replace('[x]', '[ ]')]) {
assert.deepEqual(await run({ sync: true, body }), [['remove', 'merge nightly']]);
}
assert.deepEqual(await run({ sync: true, body: checked.replace('[x]', '[X]'), labels: [] }), [['add', ['merge nightly']]]);
});
test('eligible PR is enqueued with its checked head; dry run performs no mutation', async () => {
assert.deepEqual((await run()).filter(c => c[0] === 'enqueue'), [['enqueue', { id: 'PR_1', sha: 'abc' }]]);
assert.equal((await run({ dryRun: true })).some(c => c[0] === 'enqueue'), false);
});
test('each eligibility gate independently prevents enqueueing', async () => {
for (const options of [
{ labels: [] },
{ current: { draft: true } }, { current: { state: 'closed' } }, { current: { base: { ref: 'release/v1.3' } } },
{ detail: { reviewDecision: 'REVIEW_REQUIRED' } }, { detail: { reviewDecision: 'CHANGES_REQUESTED' } },
{ detail: { mergeStateStatus: 'BLOCKED' } }, { detail: { mergeStateStatus: 'UNKNOWN' } },
{ detail: { mergeQueueEntry: { id: 'entry' } } }, { detail: { autoMergeRequest: { enabledAt: 'now' } } },
{ threads: [[false]] }, { threads: [[true], [false]] }
]) {
assert.equal((await run(options)).some(c => c[0] === 'enqueue'), false, JSON.stringify(options));
}
});
test('all thread pages are checked before enqueueing', async () => {
const calls = await run({ threads: [[true], [true]] });
assert.deepEqual(calls.filter(c => c[0] === 'threads'), [['threads', null], ['threads', 'page-0']]);
assert.equal(calls.filter(c => c[0] === 'enqueue').length, 1);
});
test('per-run cap and individual failures do not prevent later candidates', async () => {
assert.equal((await run({ count: 8 })).filter(c => c[0] === 'enqueue').length, 5);
const calls = await run({ count: 2, failFirst: true });
assert.equal(calls.filter(c => c[0] === 'enqueue').length, 2);
assert.equal(calls.filter(c => c[0] === 'failed').length, 1);
});
test('label-only opt-in survives PRs without a template and does not require a checkbox', async () => {
for (const body of ['', null, 'Existing PR description', `> ${checked}`]) {
assert.deepEqual(await run({ sync: true, body }), []);
assert.deepEqual(await run({ sync: true, body, labels: [] }), []);
assert.equal((await run({ body })).filter(call => call[0] === 'enqueue').length, 1);
assert.equal((await run({ body, labels: [] })).some(call => call[0] === 'enqueue'), false);
}
// The label is authoritative for admission, even before checkbox synchronization.
assert.equal((await run({ body: checked.replace('[x]', '[ ]') })).some(call => call[0] === 'enqueue'), true);
});
+1 -1
View File
@@ -136,7 +136,7 @@ class CiSlashTest(unittest.TestCase):
def test_fork_rerun_gates_cover_standard_jobs(self):
import re
for name, count in [("rust", 7), ("integration", 5), ("checks", 5), ("docs", 3)]:
for name, count in [("rust", 6), ("integration", 8), ("checks", 6), ("docs", 3)]:
workflow = (SCRIPT.parents[1] / "workflows" / (name + ".yml")).read_text()
gates = re.findall(r"^ if:.*github.run_attempt > 1.*$", workflow, re.MULTILINE)
self.assertEqual(len(gates), count, name)
+19 -36
View File
@@ -71,45 +71,28 @@ jobs:
- uses: actions/checkout@v4
with:
persist-credentials: false
- uses: actions/setup-node@v4
- uses: ./.github/actions/github-script-tests
scope-rules:
if: ${{ github.repository == 'GreptimeTeam/greptimedb' && (github.event_name != 'pull_request' || github.event.pull_request.draft == false || github.run_attempt > 1) }}
name: CI Scope Rules
# Same runner image as the `scope` job in integration.yml: if the rules file
# stops parsing there, the gate silently runs every job, so this check exists
# to fail the pull request instead.
runs-on: ubuntu-slim
timeout-minutes: 5
steps:
- uses: actions/checkout@v4
with:
node-version: 24
- name: Run Node GitHub script tests
run: node --test .github/scripts/query-regression-comment.test.cjs
- name: Setup uv
uses: astral-sh/setup-uv@v3
with:
version: "latest"
- name: Run check-version script tests
run: uv run --no-project python .github/scripts/check-version-test.py
- name: Run release Linux architecture tests
run: python3 .github/scripts/release-linux-architectures-test.py
- name: Run previous-release-tag script tests
run: python3 .github/scripts/previous-release-tag-test.py
- name: Run enterprise license check tests
run: python3 scripts/check-enterprise-license-test.py
- name: Run fuzz orchestration script tests
run: .github/scripts/run-fuzz-targets-test.sh
- name: Run CI comment-command tests
run: python3 .github/scripts/tests/test_ci_slash.py
- name: Run metric snapshot benchmark tests
run: python3 -m unittest discover -s .github/scripts/tests -p 'test_metric_snapshot*.py'
- name: Run query-regression Python tooling tests
run: |
python3 tests/perf/test_query_regression_runner_compaction_toctou.py
python3 tests/perf/test_query_regression_runner_otlp_trace_load.py
python3 tests/perf/test_query_regression_summary_otlp.py
python3 tests/perf/test_query_regression_case_selection.py
python3 tests/perf/test_query_regression_helpers.py
python3 tests/perf/test_query_regression_nightly_refs.py
python3 tests/perf/test_query_regression_slash.py
python3 tests/perf/test_aliyun_ecs_runner_scripts.py
python3 tests/perf/test_ci_runner_scripts.py
python3 tests/perf/test_agent_observability_summary.py
python3 tests/perf/test_tracesbench_summary.py
persist-credentials: false
- name: Show the interpreter
run: python3 -VV
- name: Validate .github/ci/scope-rules.toml
run: python3 .github/ci/ci_scope_rules.py --check-paths
check:
if: ${{ github.repository == 'GreptimeTeam/greptimedb' && (github.event_name != 'pull_request' || github.event.pull_request.draft == false || github.run_attempt > 1) }}
if: ${{ needs['github-script-tests'].result == 'success' && github.repository == 'GreptimeTeam/greptimedb' && (github.event_name != 'pull_request' || github.event.pull_request.draft == false || github.run_attempt > 1) }}
needs: [github-script-tests]
name: Check
runs-on: ${{ matrix.os }}
strategy:
+145 -46
View File
@@ -21,7 +21,7 @@ on:
default: false
type: boolean
fuzz_profile:
description: Fuzz profile selected by /ci fuzz
description: Fuzz profile for a manual run or /ci fuzz
required: false
default: none
type: choice
@@ -42,8 +42,71 @@ concurrency:
cancel-in-progress: true
jobs:
build:
github-script-tests:
if: ${{ github.repository == 'GreptimeTeam/greptimedb' && (github.event_name != 'pull_request' || github.event.pull_request.draft == false || github.run_attempt > 1) }}
name: GitHub Script Tests (Integration CI)
runs-on: ubuntu-latest
timeout-minutes: 5
steps:
- uses: actions/checkout@v4
with:
persist-credentials: false
- uses: ./.github/actions/github-script-tests
# Which jobs this gate skips, and why: .github/ci/README.md.
scope:
name: CI Scope
if: ${{ github.repository == 'GreptimeTeam/greptimedb' && (github.event_name != 'pull_request' || github.event.pull_request.draft == false || github.run_attempt > 1) }}
# ubuntu-slim ships python3, git and curl; this job only classifies.
runs-on: ubuntu-slim
timeout-minutes: 10
permissions:
contents: read
# `/pulls/{n}` and `/pulls/{n}/files`. An explicit block sets every
# unlisted permission to none, and a 403 here would silently widen every
# gate instead of classifying.
pull-requests: read
outputs:
any_fuzz: ${{ steps.classify.outputs.any_fuzz }}
build_ci_needed: ${{ steps.classify.outputs.build_ci_needed }}
fuzz_standalone: ${{ steps.classify.outputs.fuzz_standalone }}
fuzz_distributed: ${{ steps.classify.outputs.fuzz_distributed }}
fuzz_chaos: ${{ steps.classify.outputs.fuzz_chaos }}
fuzz_unstable: ${{ steps.classify.outputs.fuzz_unstable }}
export_import_v2: ${{ steps.classify.outputs.export_import_v2 }}
sqlness_kvbackend: ${{ steps.classify.outputs.sqlness_kvbackend }}
steps:
# Rules come from the pull request base (the queue base on merge_group),
# so a pull request cannot weaken its own gate. If this job or the Classify
# step fails, the outputs stay empty and every gate below treats an absent
# value as "run", which keeps CI fail-open.
- uses: actions/checkout@v4
# A checkout failure leaves the outputs empty, which every gate treats
# as "run"; letting the step fail would skip the gates instead.
continue-on-error: true
with:
ref: ${{ github.event.pull_request.base.sha || github.event.merge_group.base_sha || github.sha }}
persist-credentials: false
- name: Classify
id: classify
continue-on-error: true
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
CI_SCOPE_FORCE_ALL: ${{ vars.CI_SCOPE_FORCE_ALL || 'false' }}
run: |
args=(--repo "$GITHUB_REPOSITORY" --event "$GITHUB_EVENT_NAME"
--github-output "$GITHUB_OUTPUT"
--summary "$GITHUB_STEP_SUMMARY")
if [[ "${GITHUB_EVENT_NAME}" == "pull_request" ]]; then
args+=(--pr "${{ github.event.pull_request.number }}"
--head-sha "${{ github.event.pull_request.head.sha }}"
--base-sha "${{ github.event.pull_request.base.sha }}")
fi
python3 .github/ci/ci_scope.py "${args[@]}"
build:
if: ${{ needs['github-script-tests'].result == 'success' && github.repository == 'GreptimeTeam/greptimedb' && (github.event_name != 'pull_request' || github.event.pull_request.draft == false || github.run_attempt > 1) }}
needs: [github-script-tests]
name: Build GreptimeDB binaries
runs-on: ${{ matrix.os }}
strategy:
@@ -104,9 +167,9 @@ jobs:
version: current
sqlness:
if: ${{ github.repository == 'GreptimeTeam/greptimedb' && (github.event_name != 'pull_request' || github.event.pull_request.draft == false || github.run_attempt > 1) }}
if: ${{ needs['github-script-tests'].result == 'success' && github.repository == 'GreptimeTeam/greptimedb' && (github.event_name != 'pull_request' || github.event.pull_request.draft == false || github.run_attempt > 1) }}
name: Sqlness Test (${{ matrix.mode.name }})
needs: build
needs: [github-script-tests, build]
runs-on: ${{ matrix.os }}
strategy:
fail-fast: false
@@ -116,28 +179,12 @@ jobs:
- name: "Basic"
opts: ""
kafka: false
postgres: false
mysql: false
- name: "Remote WAL"
opts: "-w kafka -k 127.0.0.1:9092"
kafka: true
postgres: false
mysql: false
- name: "PostgreSQL KvBackend"
opts: "--setup-pg postgresql://greptimedb:admin@127.0.0.1:5432/postgres"
kafka: false
postgres: true
mysql: false
- name: "MySQL KvBackend"
opts: "--setup-mysql mysql://greptimedb:admin@127.0.0.1:3306/mysql"
kafka: false
postgres: false
mysql: true
- name: "Flat format"
opts: "--enable-flat-format"
kafka: false
postgres: false
mysql: false
timeout-minutes: 60
steps:
- uses: actions/checkout@v4
@@ -149,16 +196,6 @@ jobs:
working-directory: tests-integration/fixtures
run: ../../.github/scripts/pull-test-deps-images.sh && docker compose up -d --wait kafka
- if: matrix.mode.postgres
name: Setup PostgreSQL
working-directory: tests-integration/fixtures
run: ../../.github/scripts/pull-test-deps-images.sh && docker compose up -d --wait postgres
- if: matrix.mode.mysql
name: Setup MySQL
working-directory: tests-integration/fixtures
run: ../../.github/scripts/pull-test-deps-images.sh && docker compose up -d --wait mysql
- name: Download pre-built binaries
uses: actions/download-artifact@v4
with:
@@ -183,10 +220,68 @@ jobs:
/tmp/sqlness*
retention-days: 3
sqlness-kvbackend:
# The two foreign KV backends are the only sqlness legs that are not
# required checks, so they are the only ones this gate may skip. They run
# the same cases as the `Basic` leg, so the diff only matters when it can
# reach the backend itself; the merge queue runs them regardless.
if: ${{ !cancelled() && needs['github-script-tests'].result == 'success' && github.repository == 'GreptimeTeam/greptimedb' && (github.event_name != 'pull_request' || github.event.pull_request.draft == false || github.run_attempt > 1) && needs.build.result == 'success' && needs.scope.outputs.sqlness_kvbackend != 'false' }}
name: Sqlness Test (${{ matrix.mode.name }})
needs: [github-script-tests, scope, build]
runs-on: ${{ matrix.os }}
strategy:
fail-fast: false
matrix:
os: [ ubuntu-latest ]
mode:
- name: "Metasrv on PostgreSQL"
id: "metasrv-postgres"
opts: "--setup-pg postgresql://greptimedb:admin@127.0.0.1:5432/postgres"
postgres: true
mysql: false
- name: "Metasrv on MySQL"
id: "metasrv-mysql"
opts: "--setup-mysql mysql://greptimedb:admin@127.0.0.1:3306/mysql"
postgres: false
mysql: true
timeout-minutes: 60
steps:
- uses: actions/checkout@v4
with:
persist-credentials: false
- if: matrix.mode.postgres
name: Setup PostgreSQL
working-directory: tests-integration/fixtures
run: ../../.github/scripts/pull-test-deps-images.sh && docker compose up -d --wait postgres
- if: matrix.mode.mysql
name: Setup MySQL
working-directory: tests-integration/fixtures
run: ../../.github/scripts/pull-test-deps-images.sh && docker compose up -d --wait mysql
- name: Download pre-built binaries
uses: actions/download-artifact@v4
with:
name: bins
path: .
- name: Unzip binaries
run: tar -xvf ./bins.tar.gz
- name: Run sqlness
run: RUST_BACKTRACE=1 ./bins/sqlness-runner bare ${{ matrix.mode.opts }} -c ./tests/cases --bins-dir ./bins --preserve-state
- name: Upload sqlness logs
if: failure()
uses: actions/upload-artifact@v4
with:
name: sqlness-logs-${{ matrix.mode.name }}
path: |
/tmp/sqlness*
retention-days: 3
export-import-v2-e2e:
if: ${{ github.repository == 'GreptimeTeam/greptimedb' && (github.event_name != 'pull_request' || github.event.pull_request.draft == false || github.run_attempt > 1) }}
if: ${{ !cancelled() && needs['github-script-tests'].result == 'success' && github.repository == 'GreptimeTeam/greptimedb' && (github.event_name != 'pull_request' || github.event.pull_request.draft == false || github.run_attempt > 1) && needs.build.result == 'success' && needs.scope.outputs.export_import_v2 != 'false' }}
name: Export/Import V2 E2E Test
needs: build
needs: [github-script-tests, scope, build]
runs-on: ubuntu-latest
timeout-minutes: 60
steps:
@@ -254,9 +349,9 @@ jobs:
retention-days: 3
run-multi-lang-tests:
if: ${{ github.repository == 'GreptimeTeam/greptimedb' && (github.event_name != 'pull_request' || github.event.pull_request.draft == false || github.run_attempt > 1) }}
if: ${{ needs['github-script-tests'].result == 'success' && github.repository == 'GreptimeTeam/greptimedb' && (github.event_name != 'pull_request' || github.event.pull_request.draft == false || github.run_attempt > 1) }}
name: Run Multi-language SDK Tests
needs: build
needs: [github-script-tests, build]
uses: ./.github/workflows/run-multi-lang-tests.yml
with:
artifact-name: bins
@@ -279,9 +374,9 @@ jobs:
run: python3 .github/scripts/update-compat-versions.py --check --published-only --check-anchors
compat:
if: ${{ github.repository == 'GreptimeTeam/greptimedb' && (github.event_name == 'merge_group' || github.event_name == 'workflow_dispatch' || github.event_name == 'schedule' || (github.event_name == 'pull_request' && (github.event.action == 'ready_for_review' || (github.event.action == 'opened' && github.event.pull_request.draft == false)))) }}
if: ${{ needs['github-script-tests'].result == 'success' && github.repository == 'GreptimeTeam/greptimedb' && (github.event_name == 'merge_group' || github.event_name == 'workflow_dispatch' || github.event_name == 'schedule' || (github.event_name == 'pull_request' && (github.event.action == 'ready_for_review' || (github.event.action == 'opened' && github.event.pull_request.draft == false)))) }}
name: Compatibility Test (recent releases)
needs: build
needs: [github-script-tests, build]
runs-on: ubuntu-latest
timeout-minutes: 30
steps:
@@ -318,9 +413,12 @@ jobs:
path: /tmp/sqlness-compat*
retention-days: 3
# Fuzz runs on opening a ready PR, marking it ready, manual dispatch, and
# the scheduled main run. Synchronize events keep the core integration tests.
prepare-fuzz-targets:
if: ${{ github.repository == 'GreptimeTeam/greptimedb' && ((github.event_name == 'pull_request' && github.event.pull_request.draft == false) || (github.event_name == 'workflow_dispatch' && inputs.ci_command)) && (github.event_name == 'pull_request' || inputs.fuzz_profile != 'none') }}
if: ${{ !cancelled() && needs['github-script-tests'].result == 'success' && github.repository == 'GreptimeTeam/greptimedb' && (github.event_name == 'schedule' || (github.event_name == 'pull_request' && github.event.pull_request.draft == false && (github.event.action == 'opened' || github.event.action == 'ready_for_review')) || (github.event_name == 'workflow_dispatch' && (inputs.fuzz_profile != 'none'))) && needs.scope.outputs.any_fuzz != 'false' }}
name: Prepare Fuzz Targets
needs: [github-script-tests, scope]
runs-on: ubuntu-latest
timeout-minutes: 60
steps:
@@ -433,9 +531,9 @@ jobs:
if-no-files-found: error
fuzztest:
if: ${{ github.repository == 'GreptimeTeam/greptimedb' && ((github.event_name == 'pull_request' && github.event.pull_request.draft == false) || (github.event_name == 'workflow_dispatch' && inputs.ci_command)) && (github.event_name == 'pull_request' || inputs.fuzz_profile == 'standalone' || inputs.fuzz_profile == 'all') }}
if: ${{ !cancelled() && needs['github-script-tests'].result == 'success' && github.repository == 'GreptimeTeam/greptimedb' && (github.event_name == 'schedule' || (github.event_name == 'pull_request' && github.event.pull_request.draft == false && (github.event.action == 'opened' || github.event.action == 'ready_for_review')) || (github.event_name == 'workflow_dispatch' && (inputs.fuzz_profile == 'standalone' || inputs.fuzz_profile == 'all'))) && needs.build.result == 'success' && needs['prepare-fuzz-targets'].result == 'success' && needs.scope.outputs.fuzz_standalone != 'false' }}
name: Fuzz Test (Standalone, ${{ matrix.group.name }})
needs: [build, prepare-fuzz-targets]
needs: [github-script-tests, build, prepare-fuzz-targets, scope]
runs-on: ubuntu-latest
timeout-minutes: 60
strategy:
@@ -514,9 +612,9 @@ jobs:
artifact-name: fuzz-standalone-${{ matrix.group.id }}
unstable-fuzztest:
if: ${{ github.repository == 'GreptimeTeam/greptimedb' && ((github.event_name == 'pull_request' && github.event.pull_request.draft == false) || (github.event_name == 'workflow_dispatch' && inputs.ci_command)) && (github.event_name == 'pull_request' || inputs.fuzz_profile == 'standalone' || inputs.fuzz_profile == 'all') }}
if: ${{ !cancelled() && needs['github-script-tests'].result == 'success' && github.repository == 'GreptimeTeam/greptimedb' && (github.event_name == 'schedule' || (github.event_name == 'pull_request' && github.event.pull_request.draft == false && (github.event.action == 'opened' || github.event.action == 'ready_for_review')) || (github.event_name == 'workflow_dispatch' && (inputs.fuzz_profile == 'standalone' || inputs.fuzz_profile == 'all'))) && needs['build-greptime-ci'].result == 'success' && needs['prepare-fuzz-targets'].result == 'success' && needs.scope.outputs.fuzz_unstable != 'false' }}
name: Unstable Fuzz Test
needs: [build-greptime-ci, prepare-fuzz-targets]
needs: [github-script-tests, build-greptime-ci, prepare-fuzz-targets, scope]
runs-on: ubuntu-latest
timeout-minutes: 60
steps:
@@ -574,8 +672,9 @@ jobs:
artifact-name: fuzz-unstable-standalone
build-greptime-ci:
if: ${{ github.repository == 'GreptimeTeam/greptimedb' && ((github.event_name == 'pull_request' && github.event.pull_request.draft == false) || (github.event_name == 'workflow_dispatch' && inputs.ci_command && inputs.fuzz_profile != 'none')) }}
if: ${{ !cancelled() && needs['github-script-tests'].result == 'success' && github.repository == 'GreptimeTeam/greptimedb' && (github.event_name == 'schedule' || (github.event_name == 'pull_request' && github.event.pull_request.draft == false && (github.event.action == 'opened' || github.event.action == 'ready_for_review')) || (github.event_name == 'workflow_dispatch' && (inputs.fuzz_profile != 'none'))) && needs.scope.outputs.build_ci_needed != 'false' }}
name: Build GreptimeDB binary (profile-CI)
needs: [github-script-tests, scope]
runs-on: ${{ matrix.os }}
strategy:
matrix:
@@ -634,10 +733,10 @@ jobs:
version: current
distributed-fuzztest:
if: ${{ github.repository == 'GreptimeTeam/greptimedb' && ((github.event_name == 'pull_request' && github.event.pull_request.draft == false) || (github.event_name == 'workflow_dispatch' && inputs.ci_command)) && (github.event_name == 'pull_request' || inputs.fuzz_profile == 'distributed' || inputs.fuzz_profile == 'all') }}
if: ${{ !cancelled() && needs['github-script-tests'].result == 'success' && github.repository == 'GreptimeTeam/greptimedb' && (github.event_name == 'schedule' || (github.event_name == 'pull_request' && github.event.pull_request.draft == false && (github.event.action == 'opened' || github.event.action == 'ready_for_review')) || (github.event_name == 'workflow_dispatch' && (inputs.fuzz_profile == 'distributed' || inputs.fuzz_profile == 'all'))) && needs['build-greptime-ci'].result == 'success' && needs['prepare-fuzz-targets'].result == 'success' && needs.scope.outputs.fuzz_distributed != 'false' }}
name: Fuzz Test (Distributed, ${{ matrix.mode.name }}, ${{ matrix.group.name }})
runs-on: ubuntu-latest
needs: [build-greptime-ci, prepare-fuzz-targets]
needs: [github-script-tests, build-greptime-ci, prepare-fuzz-targets, scope]
timeout-minutes: 60
strategy:
fail-fast: false
@@ -873,10 +972,10 @@ jobs:
docker system prune -f
distributed-fuzztest-with-chaos:
if: ${{ github.repository == 'GreptimeTeam/greptimedb' && ((github.event_name == 'pull_request' && github.event.pull_request.draft == false) || (github.event_name == 'workflow_dispatch' && inputs.ci_command)) && (github.event_name == 'pull_request' || inputs.fuzz_profile == 'chaos' || inputs.fuzz_profile == 'all') }}
if: ${{ !cancelled() && needs['github-script-tests'].result == 'success' && github.repository == 'GreptimeTeam/greptimedb' && (github.event_name == 'schedule' || (github.event_name == 'pull_request' && github.event.pull_request.draft == false && (github.event.action == 'opened' || github.event.action == 'ready_for_review')) || (github.event_name == 'workflow_dispatch' && (inputs.fuzz_profile == 'chaos' || inputs.fuzz_profile == 'all'))) && needs['build-greptime-ci'].result == 'success' && needs['prepare-fuzz-targets'].result == 'success' && needs.scope.outputs.fuzz_chaos != 'false' }}
name: Fuzz Test with Chaos (Distributed, ${{ matrix.mode.name }}, ${{ matrix.group.name }})
runs-on: ubuntu-latest
needs: [build-greptime-ci, prepare-fuzz-targets]
needs: [github-script-tests, build-greptime-ci, prepare-fuzz-targets, scope]
timeout-minutes: 60
strategy:
fail-fast: false
+142
View File
@@ -0,0 +1,142 @@
# Setup and behavior: .github/nightly-merge.md
name: Nightly Merge
on:
pull_request_target:
types: [opened, edited, reopened]
schedule:
# Hourly from 02:10 through 08:10 Asia/Shanghai (UTC+8), inclusive.
# GitHub may delay scheduled runs.
- cron: '10 0,18-23 * * *'
workflow_dispatch:
inputs:
dry_run:
description: List eligible PRs without adding them to the merge queue
type: boolean
default: true
permissions: {}
jobs:
sync-label:
if: github.repository == 'GreptimeTeam/greptimedb' && github.event_name == 'pull_request_target'
runs-on: ubuntu-latest
timeout-minutes: 5
permissions:
# PR label mutations require pull-request write permission.
pull-requests: write
issues: write
concurrency:
group: nightly-merge-label-${{ github.event.pull_request.number }}
cancel-in-progress: false
steps:
# No checkout: PR contents are untrusted data, never executable code.
- uses: actions/github-script@v7
with:
script: |
const { owner, repo } = context.repo;
const issue_number = context.payload.pull_request.number;
const { data: pr } = await github.rest.pulls.get({ owner, repo, pull_number: issue_number });
const checkbox = /^- \[([ xX])\] Merge during the nightly window <!-- nightly-merge -->\s*$/m.exec(pr.body || '');
// PRs without the template manage their opt-in through the label.
if (!checkbox) return;
const selected = checkbox[1].toLowerCase() === 'x';
const label = 'merge nightly';
const labeled = pr.labels.some(item => item.name === label);
if (selected && !labeled) {
await github.rest.issues.addLabels({ owner, repo, issue_number, labels: [label] });
} else if (!selected && labeled) {
await github.rest.issues.removeLabel({ owner, repo, issue_number, name: label });
}
enqueue:
if: github.repository == 'GreptimeTeam/greptimedb' && github.event_name != 'pull_request_target'
runs-on: ubuntu-latest
timeout-minutes: 10
concurrency:
group: nightly-merge-enqueue
cancel-in-progress: false
steps:
# Reuses the automation credential used by backport and compat updates.
# A PAT (or App token) lets subsequent merge_group workflows run.
- uses: actions/github-script@v7
env:
DRY_RUN: ${{ github.event_name == 'workflow_dispatch' && inputs.dry_run }}
with:
github-token: ${{ secrets.GH_PERSONAL_ACCESS_TOKEN }}
script: |
const { owner, repo } = context.repo;
const dryRun = process.env.DRY_RUN === 'true';
const candidates = await github.paginate(github.rest.issues.listForRepo, {
owner, repo, state: 'open', labels: 'merge nightly',
sort: 'created', direction: 'asc', per_page: 100
});
const rows = [];
let enqueued = 0;
for (const candidate of candidates) {
if (!candidate.pull_request || enqueued >= 5) continue;
const number = candidate.number;
try {
// Fetch current labels and PR state, not the earlier list snapshot.
const { data: current } = await github.rest.pulls.get({ owner, repo, pull_number: number });
if (current.state !== 'open' || current.draft || current.base.ref !== 'main' ||
!current.labels.some(label => label.name === 'merge nightly')) {
rows.push([String(number), 'Skipped: not opted in, draft, closed, or not targeting main']);
continue;
}
const { repository: { pullRequest: pr } } = await github.graphql(`
query($owner: String!, $repo: String!, $number: Int!) {
repository(owner: $owner, name: $repo) {
pullRequest(number: $number) {
id headRefOid reviewDecision mergeStateStatus
mergeQueueEntry { id }
autoMergeRequest { enabledAt }
}
}
}`, { owner, repo, number });
if (pr.mergeQueueEntry || pr.autoMergeRequest ||
pr.reviewDecision !== 'APPROVED' || pr.mergeStateStatus !== 'CLEAN') {
rows.push([String(number), 'Skipped: already queued/auto-merge enabled, or not approved and clean']);
continue;
}
let cursor = null;
let unresolved = false;
do {
const { repository: { pullRequest: { reviewThreads } } } = await github.graphql(`
query($owner: String!, $repo: String!, $number: Int!, $cursor: String) {
repository(owner: $owner, name: $repo) {
pullRequest(number: $number) {
reviewThreads(first: 100, after: $cursor) {
nodes { isResolved }
pageInfo { hasNextPage endCursor }
}
}
}
}`, { owner, repo, number, cursor });
unresolved = reviewThreads.nodes.some(thread => !thread.isResolved);
cursor = reviewThreads.pageInfo.hasNextPage ? reviewThreads.pageInfo.endCursor : null;
} while (cursor && !unresolved);
if (unresolved) {
rows.push([String(number), 'Skipped: unresolved review threads']);
continue;
}
if (!dryRun) {
// GitHub enforces branch rules; never bypass or enable auto-merge.
await github.graphql(`
mutation($id: ID!, $sha: GitObjectID!) {
enqueuePullRequest(input: {pullRequestId: $id, expectedHeadOid: $sha}) {
mergeQueueEntry { id }
}
}`, { id: pr.id, sha: pr.headRefOid });
}
enqueued++;
rows.push([String(number), dryRun ? 'Would enqueue' : 'Enqueued']);
} catch (error) {
core.warning(`PR #${number}: ${error.message}`);
rows.push([String(number), 'Failed: see workflow logs']);
core.setFailed('Some PRs could not be processed; see workflow logs.');
}
}
for (const [number, result] of rows) core.info(`PR #${number}: ${result}`);
await core.summary.addHeading(dryRun ? 'Nightly merge (dry run)' : 'Nightly merge')
.addTable([['PR', 'Result'], ...rows]).write();
+23 -48
View File
@@ -31,6 +31,17 @@ concurrency:
cancel-in-progress: true
jobs:
github-script-tests:
if: ${{ github.repository == 'GreptimeTeam/greptimedb' && (github.event_name != 'pull_request' || github.event.pull_request.draft == false || github.run_attempt > 1) }}
name: GitHub Script Tests (Rust CI)
runs-on: ubuntu-latest
timeout-minutes: 5
steps:
- uses: actions/checkout@v4
with:
persist-credentials: false
- uses: ./.github/actions/github-script-tests
fmt:
if: ${{ github.repository == 'GreptimeTeam/greptimedb' && (github.event_name != 'pull_request' || github.event.pull_request.draft == false || github.run_attempt > 1) }}
name: Rustfmt
@@ -50,7 +61,8 @@ jobs:
run: make fmt-check
clippy:
if: ${{ github.repository == 'GreptimeTeam/greptimedb' && (github.event_name != 'pull_request' || github.event.pull_request.draft == false || github.run_attempt > 1) }}
if: ${{ needs['github-script-tests'].result == 'success' && github.repository == 'GreptimeTeam/greptimedb' && (github.event_name != 'pull_request' || github.event.pull_request.draft == false || github.run_attempt > 1) }}
needs: [github-script-tests]
name: Clippy
runs-on: ubuntu-latest
timeout-minutes: 60
@@ -94,7 +106,9 @@ jobs:
run: make check-udeps
check-riscv64:
if: ${{ github.repository == 'GreptimeTeam/greptimedb' && (github.event_name != 'pull_request' || github.event.pull_request.draft == false || github.run_attempt > 1) }}
# Keep platform coverage on the weekday schedule and allow manual checks.
if: ${{ needs['github-script-tests'].result == 'success' && github.repository == 'GreptimeTeam/greptimedb' && (github.event_name == 'schedule' || github.event_name == 'workflow_dispatch') }}
needs: [github-script-tests]
name: Check riscv64 build
runs-on: ubuntu-latest
timeout-minutes: 90
@@ -120,7 +134,9 @@ jobs:
run: cargo check --locked --workspace --all-targets --features servers/dashboard --target riscv64gc-unknown-linux-gnu
check-windows:
if: ${{ github.repository == 'GreptimeTeam/greptimedb' && (github.event_name != 'pull_request' || github.event.pull_request.draft == false || github.run_attempt > 1) }}
# Keep platform coverage on the weekday schedule and allow manual checks.
if: ${{ needs['github-script-tests'].result == 'success' && github.repository == 'GreptimeTeam/greptimedb' && (github.event_name == 'schedule' || github.event_name == 'workflow_dispatch') }}
needs: [github-script-tests]
name: Check Windows build
runs-on: windows-2022
timeout-minutes: 60
@@ -148,48 +164,6 @@ jobs:
env:
RUSTFLAGS: "-D warnings"
test-windows:
if: ${{ github.repository == 'GreptimeTeam/greptimedb' && (github.event_name != 'pull_request' || github.event.pull_request.draft == false) }}
name: Test Windows
runs-on: windows-2022
timeout-minutes: 90
env:
CARGO_INCREMENTAL: 0
CARGO_PROFILE_DEV_DEBUG: 0
CARGO_PROFILE_TEST_DEBUG: 0
RUSTFLAGS: "-D warnings -C linker=lld-link"
RUST_BACKTRACE: 1
RUST_MIN_STACK: 8388608 # 8MB
steps:
- run: git config --global core.autocrlf false
- uses: actions/checkout@v4
with:
persist-credentials: false
- uses: ./.github/actions/setup-cyborg
- uses: taiki-e/install-action@v2
with:
tool: protoc@3.23.4
- uses: KyleMayes/install-llvm-action@v1
with:
version: "14.0"
- uses: actions-rust-lang/setup-rust-toolchain@v1
with:
cache: false
- name: Rust Cache
uses: Swatinem/rust-cache@v2
with:
shared-key: "test-windows"
cache-all-crates: "true"
save-if: ${{ github.ref == 'refs/heads/main' }}
- name: Install Cargo Nextest
uses: taiki-e/install-action@nextest
- name: Install WSL distribution
uses: Vampire/setup-wsl@v2
with:
distribution: Ubuntu-22.04
- name: Run Windows tests
run: cargo nextest run --locked --workspace -F dashboard --no-fail-fast
conflict-check:
if: ${{ github.repository == 'GreptimeTeam/greptimedb' && (github.event_name != 'pull_request' || github.event.pull_request.draft == false || github.run_attempt > 1) }}
name: Check for conflict
@@ -202,10 +176,10 @@ jobs:
uses: olivernybroe/action-conflict-finder@v4.0
test:
if: ${{ github.repository == 'GreptimeTeam/greptimedb' && github.event_name != 'merge_group' && (github.event_name != 'pull_request' || github.event.pull_request.draft == false || github.run_attempt > 1) }}
if: ${{ needs['github-script-tests'].result == 'success' && github.repository == 'GreptimeTeam/greptimedb' && github.event_name != 'merge_group' && (github.event_name != 'pull_request' || github.event.pull_request.draft == false || github.run_attempt > 1) }}
runs-on: ubuntu-22.04-arm
timeout-minutes: 60
needs: [conflict-check, clippy, fmt, check-udeps]
needs: [github-script-tests, conflict-check, clippy, fmt, check-udeps]
steps:
- uses: actions/checkout@v4
with:
@@ -258,7 +232,8 @@ jobs:
UNITTEST_LOG_DIR: "__unittest_logs"
coverage:
if: ${{ github.repository == 'GreptimeTeam/greptimedb' && github.event_name == 'merge_group' }}
if: ${{ needs['github-script-tests'].result == 'success' && github.repository == 'GreptimeTeam/greptimedb' && github.event_name == 'merge_group' }}
needs: [github-script-tests]
runs-on: ubuntu-22.04-8-cores
timeout-minutes: 60
steps:
Generated
+49 -36
View File
@@ -2340,6 +2340,19 @@ dependencies = [
"tokio",
]
[[package]]
name = "common-cache"
version = "1.4.0-alpha.0"
dependencies = [
"async-trait",
"bytes",
"common-base",
"futures",
"moka",
"prometheus 0.14.0",
"tokio",
]
[[package]]
name = "common-catalog"
version = "1.4.0-alpha.0"
@@ -2588,7 +2601,6 @@ dependencies = [
"tokio-util",
"tonic 0.14.2",
"tower 0.5.2",
"uuid",
"vec1",
]
@@ -3757,7 +3769,7 @@ checksum = "a4ae5f15dda3c708c0ade84bfee31ccab44a3da4f88015ed22f63732abe300c8"
[[package]]
name = "datafusion"
version = "55.1.0"
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=e3221b8f74b15c7192621576e5d1e354a6cf097a#e3221b8f74b15c7192621576e5d1e354a6cf097a"
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7"
dependencies = [
"arrow 59.2.0",
"arrow-schema 59.2.0",
@@ -3809,7 +3821,7 @@ dependencies = [
[[package]]
name = "datafusion-catalog"
version = "55.1.0"
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=e3221b8f74b15c7192621576e5d1e354a6cf097a#e3221b8f74b15c7192621576e5d1e354a6cf097a"
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7"
dependencies = [
"arrow 59.2.0",
"async-trait",
@@ -3833,7 +3845,7 @@ dependencies = [
[[package]]
name = "datafusion-catalog-listing"
version = "55.1.0"
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=e3221b8f74b15c7192621576e5d1e354a6cf097a#e3221b8f74b15c7192621576e5d1e354a6cf097a"
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7"
dependencies = [
"arrow 59.2.0",
"async-trait",
@@ -3856,7 +3868,7 @@ dependencies = [
[[package]]
name = "datafusion-common"
version = "55.1.0"
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=e3221b8f74b15c7192621576e5d1e354a6cf097a#e3221b8f74b15c7192621576e5d1e354a6cf097a"
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7"
dependencies = [
"arrow 59.2.0",
"arrow-ipc 59.2.0",
@@ -3882,7 +3894,7 @@ dependencies = [
[[package]]
name = "datafusion-common-runtime"
version = "55.1.0"
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=e3221b8f74b15c7192621576e5d1e354a6cf097a#e3221b8f74b15c7192621576e5d1e354a6cf097a"
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7"
dependencies = [
"futures",
"log",
@@ -3892,7 +3904,7 @@ dependencies = [
[[package]]
name = "datafusion-datasource"
version = "55.1.0"
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=e3221b8f74b15c7192621576e5d1e354a6cf097a#e3221b8f74b15c7192621576e5d1e354a6cf097a"
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7"
dependencies = [
"arrow 59.2.0",
"async-compression",
@@ -3928,7 +3940,7 @@ dependencies = [
[[package]]
name = "datafusion-datasource-arrow"
version = "55.1.0"
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=e3221b8f74b15c7192621576e5d1e354a6cf097a#e3221b8f74b15c7192621576e5d1e354a6cf097a"
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7"
dependencies = [
"arrow 59.2.0",
"arrow-ipc 59.2.0",
@@ -3952,7 +3964,7 @@ dependencies = [
[[package]]
name = "datafusion-datasource-csv"
version = "55.1.0"
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=e3221b8f74b15c7192621576e5d1e354a6cf097a#e3221b8f74b15c7192621576e5d1e354a6cf097a"
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7"
dependencies = [
"arrow 59.2.0",
"async-trait",
@@ -3975,7 +3987,7 @@ dependencies = [
[[package]]
name = "datafusion-datasource-json"
version = "55.1.0"
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=e3221b8f74b15c7192621576e5d1e354a6cf097a#e3221b8f74b15c7192621576e5d1e354a6cf097a"
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7"
dependencies = [
"arrow 59.2.0",
"async-trait",
@@ -3998,7 +4010,7 @@ dependencies = [
[[package]]
name = "datafusion-datasource-parquet"
version = "55.1.0"
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=e3221b8f74b15c7192621576e5d1e354a6cf097a#e3221b8f74b15c7192621576e5d1e354a6cf097a"
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7"
dependencies = [
"arrow 59.2.0",
"arrow-schema 59.2.0",
@@ -4030,12 +4042,12 @@ dependencies = [
[[package]]
name = "datafusion-doc"
version = "55.1.0"
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=e3221b8f74b15c7192621576e5d1e354a6cf097a#e3221b8f74b15c7192621576e5d1e354a6cf097a"
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7"
[[package]]
name = "datafusion-execution"
version = "55.1.0"
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=e3221b8f74b15c7192621576e5d1e354a6cf097a#e3221b8f74b15c7192621576e5d1e354a6cf097a"
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7"
dependencies = [
"arrow 59.2.0",
"arrow-buffer 59.2.0",
@@ -4060,7 +4072,7 @@ dependencies = [
[[package]]
name = "datafusion-expr"
version = "55.1.0"
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=e3221b8f74b15c7192621576e5d1e354a6cf097a#e3221b8f74b15c7192621576e5d1e354a6cf097a"
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7"
dependencies = [
"arrow 59.2.0",
"arrow-schema 59.2.0",
@@ -4084,7 +4096,7 @@ dependencies = [
[[package]]
name = "datafusion-expr-common"
version = "55.1.0"
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=e3221b8f74b15c7192621576e5d1e354a6cf097a#e3221b8f74b15c7192621576e5d1e354a6cf097a"
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7"
dependencies = [
"arrow 59.2.0",
"datafusion-common",
@@ -4095,7 +4107,7 @@ dependencies = [
[[package]]
name = "datafusion-functions"
version = "55.1.0"
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=e3221b8f74b15c7192621576e5d1e354a6cf097a#e3221b8f74b15c7192621576e5d1e354a6cf097a"
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7"
dependencies = [
"arrow 59.2.0",
"arrow-buffer 59.2.0",
@@ -4126,7 +4138,7 @@ dependencies = [
[[package]]
name = "datafusion-functions-aggregate"
version = "55.1.0"
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=e3221b8f74b15c7192621576e5d1e354a6cf097a#e3221b8f74b15c7192621576e5d1e354a6cf097a"
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7"
dependencies = [
"arrow 59.2.0",
"datafusion-common",
@@ -4146,7 +4158,7 @@ dependencies = [
[[package]]
name = "datafusion-functions-aggregate-common"
version = "55.1.0"
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=e3221b8f74b15c7192621576e5d1e354a6cf097a#e3221b8f74b15c7192621576e5d1e354a6cf097a"
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7"
dependencies = [
"arrow 59.2.0",
"datafusion-common",
@@ -4157,7 +4169,7 @@ dependencies = [
[[package]]
name = "datafusion-functions-nested"
version = "55.1.0"
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=e3221b8f74b15c7192621576e5d1e354a6cf097a#e3221b8f74b15c7192621576e5d1e354a6cf097a"
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7"
dependencies = [
"arrow 59.2.0",
"arrow-ord 59.2.0",
@@ -4181,7 +4193,7 @@ dependencies = [
[[package]]
name = "datafusion-functions-table"
version = "55.1.0"
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=e3221b8f74b15c7192621576e5d1e354a6cf097a#e3221b8f74b15c7192621576e5d1e354a6cf097a"
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7"
dependencies = [
"arrow 59.2.0",
"async-trait",
@@ -4196,7 +4208,7 @@ dependencies = [
[[package]]
name = "datafusion-functions-window"
version = "55.1.0"
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=e3221b8f74b15c7192621576e5d1e354a6cf097a#e3221b8f74b15c7192621576e5d1e354a6cf097a"
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7"
dependencies = [
"arrow 59.2.0",
"datafusion-common",
@@ -4212,7 +4224,7 @@ dependencies = [
[[package]]
name = "datafusion-functions-window-common"
version = "55.1.0"
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=e3221b8f74b15c7192621576e5d1e354a6cf097a#e3221b8f74b15c7192621576e5d1e354a6cf097a"
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7"
dependencies = [
"datafusion-common",
"datafusion-physical-expr-common",
@@ -4221,7 +4233,7 @@ dependencies = [
[[package]]
name = "datafusion-macros"
version = "55.1.0"
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=e3221b8f74b15c7192621576e5d1e354a6cf097a#e3221b8f74b15c7192621576e5d1e354a6cf097a"
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7"
dependencies = [
"datafusion-doc",
"quote",
@@ -4231,7 +4243,7 @@ dependencies = [
[[package]]
name = "datafusion-optimizer"
version = "55.1.0"
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=e3221b8f74b15c7192621576e5d1e354a6cf097a#e3221b8f74b15c7192621576e5d1e354a6cf097a"
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7"
dependencies = [
"arrow 59.2.0",
"chrono",
@@ -4279,7 +4291,7 @@ dependencies = [
[[package]]
name = "datafusion-physical-expr"
version = "55.1.0"
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=e3221b8f74b15c7192621576e5d1e354a6cf097a#e3221b8f74b15c7192621576e5d1e354a6cf097a"
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7"
dependencies = [
"arrow 59.2.0",
"arrow-schema 59.2.0",
@@ -4302,7 +4314,7 @@ dependencies = [
[[package]]
name = "datafusion-physical-expr-adapter"
version = "55.1.0"
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=e3221b8f74b15c7192621576e5d1e354a6cf097a#e3221b8f74b15c7192621576e5d1e354a6cf097a"
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7"
dependencies = [
"arrow 59.2.0",
"datafusion-common",
@@ -4316,7 +4328,7 @@ dependencies = [
[[package]]
name = "datafusion-physical-expr-common"
version = "55.1.0"
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=e3221b8f74b15c7192621576e5d1e354a6cf097a#e3221b8f74b15c7192621576e5d1e354a6cf097a"
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7"
dependencies = [
"arrow 59.2.0",
"chrono",
@@ -4333,7 +4345,7 @@ dependencies = [
[[package]]
name = "datafusion-physical-optimizer"
version = "55.1.0"
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=e3221b8f74b15c7192621576e5d1e354a6cf097a#e3221b8f74b15c7192621576e5d1e354a6cf097a"
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7"
dependencies = [
"arrow 59.2.0",
"datafusion-common",
@@ -4352,7 +4364,7 @@ dependencies = [
[[package]]
name = "datafusion-physical-plan"
version = "55.1.0"
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=e3221b8f74b15c7192621576e5d1e354a6cf097a#e3221b8f74b15c7192621576e5d1e354a6cf097a"
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7"
dependencies = [
"arrow 59.2.0",
"arrow-data 59.2.0",
@@ -4389,7 +4401,7 @@ dependencies = [
[[package]]
name = "datafusion-proto"
version = "55.1.0"
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=e3221b8f74b15c7192621576e5d1e354a6cf097a#e3221b8f74b15c7192621576e5d1e354a6cf097a"
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7"
dependencies = [
"arrow 59.2.0",
"datafusion-catalog",
@@ -4415,7 +4427,7 @@ dependencies = [
[[package]]
name = "datafusion-proto-common"
version = "55.1.0"
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=e3221b8f74b15c7192621576e5d1e354a6cf097a#e3221b8f74b15c7192621576e5d1e354a6cf097a"
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7"
dependencies = [
"arrow 59.2.0",
"datafusion-common",
@@ -4425,7 +4437,7 @@ dependencies = [
[[package]]
name = "datafusion-proto-models"
version = "55.1.0"
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=e3221b8f74b15c7192621576e5d1e354a6cf097a#e3221b8f74b15c7192621576e5d1e354a6cf097a"
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7"
dependencies = [
"datafusion-common",
"datafusion-proto-common",
@@ -4435,7 +4447,7 @@ dependencies = [
[[package]]
name = "datafusion-pruning"
version = "55.1.0"
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=e3221b8f74b15c7192621576e5d1e354a6cf097a#e3221b8f74b15c7192621576e5d1e354a6cf097a"
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7"
dependencies = [
"arrow 59.2.0",
"datafusion-common",
@@ -4450,7 +4462,7 @@ dependencies = [
[[package]]
name = "datafusion-session"
version = "55.1.0"
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=e3221b8f74b15c7192621576e5d1e354a6cf097a#e3221b8f74b15c7192621576e5d1e354a6cf097a"
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7"
dependencies = [
"arrow-schema 59.2.0",
"async-trait",
@@ -4464,7 +4476,7 @@ dependencies = [
[[package]]
name = "datafusion-sql"
version = "55.1.0"
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=e3221b8f74b15c7192621576e5d1e354a6cf097a#e3221b8f74b15c7192621576e5d1e354a6cf097a"
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7"
dependencies = [
"arrow 59.2.0",
"bigdecimal 0.4.8",
@@ -4483,7 +4495,7 @@ dependencies = [
[[package]]
name = "datafusion-substrait"
version = "55.1.0"
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=e3221b8f74b15c7192621576e5d1e354a6cf097a#e3221b8f74b15c7192621576e5d1e354a6cf097a"
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7"
dependencies = [
"async-recursion",
"async-trait",
@@ -4554,6 +4566,7 @@ dependencies = [
"prometheus 0.14.0",
"prost 0.14.1",
"query",
"rand 0.9.4",
"reqwest 0.13.4",
"serde",
"serde_json",
+17 -16
View File
@@ -9,6 +9,7 @@ members = [
"src/cmd",
"src/common/base",
"src/common/batcher",
"src/common/cache",
"src/common/catalog",
"src/common/config",
"src/common/datasource",
@@ -367,22 +368,22 @@ rev = "f743c3a5fe8c1f57363eac5866c356b7d91f9b39"
[patch.crates-io]
substrait = { git = "https://github.com/GreptimeTeam/substrait-rs.git", rev = "91ec978b0649417ad3da8390e7a515baec723b1b" }
datafusion = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "e3221b8f74b15c7192621576e5d1e354a6cf097a" }
datafusion-common = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "e3221b8f74b15c7192621576e5d1e354a6cf097a" }
datafusion-datasource = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "e3221b8f74b15c7192621576e5d1e354a6cf097a" }
datafusion-execution = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "e3221b8f74b15c7192621576e5d1e354a6cf097a" }
datafusion-expr = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "e3221b8f74b15c7192621576e5d1e354a6cf097a" }
datafusion-expr-common = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "e3221b8f74b15c7192621576e5d1e354a6cf097a" }
datafusion-functions = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "e3221b8f74b15c7192621576e5d1e354a6cf097a" }
datafusion-functions-aggregate-common = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "e3221b8f74b15c7192621576e5d1e354a6cf097a" }
datafusion-functions-window-common = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "e3221b8f74b15c7192621576e5d1e354a6cf097a" }
datafusion-optimizer = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "e3221b8f74b15c7192621576e5d1e354a6cf097a" }
datafusion-physical-expr = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "e3221b8f74b15c7192621576e5d1e354a6cf097a" }
datafusion-physical-expr-common = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "e3221b8f74b15c7192621576e5d1e354a6cf097a" }
datafusion-physical-plan = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "e3221b8f74b15c7192621576e5d1e354a6cf097a" }
datafusion-proto = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "e3221b8f74b15c7192621576e5d1e354a6cf097a" }
datafusion-sql = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "e3221b8f74b15c7192621576e5d1e354a6cf097a" }
datafusion-substrait = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "e3221b8f74b15c7192621576e5d1e354a6cf097a" }
datafusion = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "cc5534492d5408831395609cdafb6520c7d514b7" }
datafusion-common = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "cc5534492d5408831395609cdafb6520c7d514b7" }
datafusion-datasource = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "cc5534492d5408831395609cdafb6520c7d514b7" }
datafusion-execution = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "cc5534492d5408831395609cdafb6520c7d514b7" }
datafusion-expr = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "cc5534492d5408831395609cdafb6520c7d514b7" }
datafusion-expr-common = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "cc5534492d5408831395609cdafb6520c7d514b7" }
datafusion-functions = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "cc5534492d5408831395609cdafb6520c7d514b7" }
datafusion-functions-aggregate-common = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "cc5534492d5408831395609cdafb6520c7d514b7" }
datafusion-functions-window-common = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "cc5534492d5408831395609cdafb6520c7d514b7" }
datafusion-optimizer = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "cc5534492d5408831395609cdafb6520c7d514b7" }
datafusion-physical-expr = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "cc5534492d5408831395609cdafb6520c7d514b7" }
datafusion-physical-expr-common = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "cc5534492d5408831395609cdafb6520c7d514b7" }
datafusion-physical-plan = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "cc5534492d5408831395609cdafb6520c7d514b7" }
datafusion-proto = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "cc5534492d5408831395609cdafb6520c7d514b7" }
datafusion-sql = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "cc5534492d5408831395609cdafb6520c7d514b7" }
datafusion-substrait = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "cc5534492d5408831395609cdafb6520c7d514b7" }
datafusion-pg-catalog = { git = "https://github.com/datafusion-contrib/datafusion-postgres.git", rev = "3ae0a6cb30b1c5131687f4637247ff4f84ac11e4" }
arrow-pg = { git = "https://github.com/datafusion-contrib/datafusion-postgres.git", rev = "3ae0a6cb30b1c5131687f4637247ff4f84ac11e4" }
sqlparser = { git = "https://github.com/GreptimeTeam/sqlparser-rs.git", rev = "9e9019bb1c7040ed956f654e39378dd42ab17884" }
+4
View File
@@ -249,6 +249,10 @@ fmt-check: ## Check code format.
check-enterprise-license: ## Check enterprise-gated files are listed in both license configs.
python3 scripts/check-enterprise-license.py
.PHONY: check-ci-scope
check-ci-scope: ## Check the CI scope rules still match existing paths.
python3 .github/ci/ci_scope_rules.py --check-paths
.PHONY: start-etcd
start-etcd: ## Start single node etcd for testing purpose.
docker run --rm -d --network=host -p 2379-2380:2379-2380 ${ETCD_IMAGE}
+4
View File
@@ -153,6 +153,7 @@
| `storage` | -- | -- | The data storage options. |
| `storage.data_home` | String | `./greptimedb_data` | The working home directory. |
| `storage.copy_root` | String | `./greptimedb_data/copy` | Root directory for standalone SQL access to local files.<br/>Relative SQL paths are resolved below this directory. Absolute paths are accepted only when<br/>they are inside this directory. Defaults to `<data_home>/copy`.<br/>Distributed deployments always reject SQL access to local files.<br/>Upgrade note: COPY commands and existing external tables that reference paths outside this<br/>directory will fail. Move those files below the copy root, set this option to a dedicated<br/>directory containing them, or migrate the files to object storage before upgrading. |
| `storage.probe_on_startup` | Bool | `true` | Whether to probe every remote object storage when the datanode starts.<br/>The probe writes, reads, overwrites, lists and deletes an object under<br/>`.greptime_probe/`, and a failure aborts startup. The probe lives at the storage<br/>root, so the credentials must allow writes and deletes below the root. Disable it<br/>when the credentials are scoped to narrower prefixes or when the storage may be<br/>unavailable at startup. |
| `storage.type` | String | `File` | The storage type used to store the data.<br/>- `File`: the data is stored in the local file system.<br/>- `S3`: the data is stored in the S3 object storage.<br/>- `Gcs`: the data is stored in the Google Cloud Storage.<br/>- `Azblob`: the data is stored in the Azure Blob Storage.<br/>- `Oss`: the data is stored in the Aliyun OSS.<br/>- `Hdfs`: the data is stored in the Hadoop Distributed File System. |
| `storage.bucket` | String | Unset | The S3 bucket name.<br/>**It's only used when the storage type is `S3`, `Oss` and `Gcs`**. |
| `storage.root` | String | Unset | The directory or object prefix under which data is stored.<br/>**It's only used when the storage type is `S3`, `Oss`, `Gcs`, `Azblob` and `Hdfs`**. |
@@ -193,6 +194,7 @@
| `region_engine.mito.max_background_purges` | Integer | Auto | Max number of running background purge jobs (default: number of cpu cores). |
| `region_engine.mito.experimental_compaction_memory_limit` | String | 0 | Memory budget for compaction tasks.<br/>Supports absolute size (e.g., "2GiB", "512MB") or percentage of system memory (e.g., "50%").<br/>Setting it to 0 or "unlimited" disables the limit. |
| `region_engine.mito.experimental_compaction_on_exhausted` | String | wait | Behavior when compaction cannot acquire memory from the budget.<br/>Options: "wait" (default, 10s), "wait(<duration>)", "fail" |
| `region_engine.mito.experimental_compaction_output_parallelism` | Integer | 1 | Default per-output parallelism for input decoding and SST column encoding.<br/>Each stage is bounded independently; this is not a global thread limit.<br/>Values below 2 disable parallel decoding/encoding, but not the merge pipeline.<br/>Tables can override it with 'compaction.experimental_output_parallelism' (positive integer). |
| `region_engine.mito.auto_flush_interval` | String | `10m` | Interval to auto flush a region if it has not flushed yet. |
| `region_engine.mito.global_write_buffer_size` | String | Auto | Global write buffer size for all regions. If not set, it's default to 1/8 of OS memory with a max limitation of 1GB. |
| `region_engine.mito.global_write_buffer_reject_size` | String | Auto | Global write buffer size threshold to reject write requests. If not set, it's default to 2 times of `global_write_buffer_size`. |
@@ -630,6 +632,7 @@
| `query.experimental_spill_compression` | String | `uncompressed` | Compression for spilled data files: "uncompressed" (default), "lz4_frame", "zstd".<br/>Ignored unless mode is "custom". |
| `storage` | -- | -- | The data storage options. |
| `storage.data_home` | String | `./greptimedb_data` | The working home directory. |
| `storage.probe_on_startup` | Bool | `true` | Whether to probe every remote object storage when the datanode starts.<br/>The probe writes, reads, overwrites, lists and deletes an object under<br/>`.greptime_probe/`, and a failure aborts startup. The probe lives at the storage<br/>root, so the credentials must allow writes and deletes below the root. Disable it<br/>when the credentials are scoped to narrower prefixes or when the storage may be<br/>unavailable at startup. |
| `storage.type` | String | `File` | The storage type used to store the data.<br/>- `File`: the data is stored in the local file system.<br/>- `S3`: the data is stored in the S3 object storage.<br/>- `Gcs`: the data is stored in the Google Cloud Storage.<br/>- `Azblob`: the data is stored in the Azure Blob Storage.<br/>- `Oss`: the data is stored in the Aliyun OSS.<br/>- `Hdfs`: the data is stored in the Hadoop Distributed File System. |
| `storage.bucket` | String | Unset | The S3 bucket name.<br/>**It's only used when the storage type is `S3`, `Oss` and `Gcs`**. |
| `storage.root` | String | Unset | The directory or object prefix under which data is stored.<br/>**It's only used when the storage type is `S3`, `Oss`, `Gcs`, `Azblob` and `Hdfs`**. |
@@ -672,6 +675,7 @@
| `region_engine.mito.max_background_purges` | Integer | Auto | Max number of running background purge jobs (default: number of cpu cores). |
| `region_engine.mito.experimental_compaction_memory_limit` | String | 0 | Memory budget for compaction tasks.<br/>Supports absolute size (e.g., "2GiB", "512MB") or percentage of system memory (e.g., "50%").<br/>Setting it to 0 or "unlimited" disables the limit. |
| `region_engine.mito.experimental_compaction_on_exhausted` | String | wait | Behavior when compaction cannot acquire memory from the budget.<br/>Options: "wait" (default, 10s), "wait(<duration>)", "fail" |
| `region_engine.mito.experimental_compaction_output_parallelism` | Integer | 1 | Default per-output parallelism for input decoding and SST column encoding.<br/>Each stage is bounded independently; this is not a global thread limit.<br/>Values below 2 disable parallel decoding/encoding, but not the merge pipeline.<br/>Tables can override it with 'compaction.experimental_output_parallelism' (positive integer). |
| `region_engine.mito.auto_flush_interval` | String | `10m` | Interval to auto flush a region if it has not flushed yet. |
| `region_engine.mito.global_write_buffer_size` | String | Auto | Global write buffer size for all regions. If not set, it's default to 1/8 of OS memory with a max limitation of 1GB. |
| `region_engine.mito.global_write_buffer_reject_size` | String | Auto | Global write buffer size threshold to reject write requests. If not set, it's default to 2 times of `global_write_buffer_size` |
+15
View File
@@ -375,6 +375,14 @@ memory_pool_size = "50%"
## The working home directory.
data_home = "./greptimedb_data"
## Whether to probe every remote object storage when the datanode starts.
## The probe writes, reads, overwrites, lists and deletes an object under
## `.greptime_probe/`, and a failure aborts startup. The probe lives at the storage
## root, so the credentials must allow writes and deletes below the root. Disable it
## when the credentials are scoped to narrower prefixes or when the storage may be
## unavailable at startup.
probe_on_startup = true
## The storage type used to store the data.
## - `File`: the data is stored in the local file system.
## - `S3`: the data is stored in the S3 object storage.
@@ -590,6 +598,13 @@ compress_manifest = false
## @toml2docs:none-default="wait"
#+ experimental_compaction_on_exhausted = "wait"
## Default per-output parallelism for input decoding and SST column encoding.
## Each stage is bounded independently; this is not a global thread limit.
## Values below 2 disable parallel decoding/encoding, but not the merge pipeline.
## Tables can override it with 'compaction.experimental_output_parallelism' (positive integer).
## @toml2docs:none-default="1"
#+ experimental_compaction_output_parallelism = 1
## Interval to auto flush a region if it has not flushed yet.
auto_flush_interval = "10m"
+15
View File
@@ -603,6 +603,14 @@ data_home = "./greptimedb_data"
## directory containing them, or migrate the files to object storage before upgrading.
#+ copy_root = "./greptimedb_data/copy"
## Whether to probe every remote object storage when the datanode starts.
## The probe writes, reads, overwrites, lists and deletes an object under
## `.greptime_probe/`, and a failure aborts startup. The probe lives at the storage
## root, so the credentials must allow writes and deletes below the root. Disable it
## when the credentials are scoped to narrower prefixes or when the storage may be
## unavailable at startup.
probe_on_startup = true
## The storage type used to store the data.
## - `File`: the data is stored in the local file system.
## - `S3`: the data is stored in the S3 object storage.
@@ -805,6 +813,13 @@ compress_manifest = false
## @toml2docs:none-default="wait"
#+ experimental_compaction_on_exhausted = "wait"
## Default per-output parallelism for input decoding and SST column encoding.
## Each stage is bounded independently; this is not a global thread limit.
## Values below 2 disable parallel decoding/encoding, but not the merge pipeline.
## Tables can override it with 'compaction.experimental_output_parallelism' (positive integer).
## @toml2docs:none-default="1"
#+ experimental_compaction_output_parallelism = 1
## Interval to auto flush a region if it has not flushed yet.
auto_flush_interval = "10m"
-5
View File
@@ -15,11 +15,6 @@ headerPath = "licenses/enterprise-header.txt"
# with the "# enterprise" block in `licenserc.toml`'s `excludes` — both are
# enforced by `make check-enterprise-license`.
includes = [
"src/common/grpc/src/flow_write.rs",
"src/frontend/src/instance/flow_write.rs",
"src/datanode/src/region_server/flow_write.rs",
"src/operator/src/insert/flow_write.rs",
"src/flow/src/batching_mode/frontend_client/flow_write.rs",
"src/common/meta/src/rpc/ddl/trigger.rs",
"src/operator/src/expr_helper/trigger.rs",
"src/sql/src/statements/alter/trigger.rs",
-5
View File
@@ -31,11 +31,6 @@ excludes = [
# Keep this list in sync with that file's `includes`; enforced by
# `make check-enterprise-license`.
# enterprise:start
"src/common/grpc/src/flow_write.rs",
"src/frontend/src/instance/flow_write.rs",
"src/datanode/src/region_server/flow_write.rs",
"src/operator/src/insert/flow_write.rs",
"src/flow/src/batching_mode/frontend_client/flow_write.rs",
"src/common/meta/src/rpc/ddl/trigger.rs",
"src/operator/src/expr_helper/trigger.rs",
"src/sql/src/statements/alter/trigger.rs",
@@ -470,6 +470,7 @@ pub(super) async fn run_direct_sst(args: DirectArgs) {
row_group_size: scenario.layout.row_group_size,
max_file_size: None,
float_field_encoding: Default::default(),
..Default::default()
};
let infos = match format {
FormatType::Flat => writer.write_all_flat(source, Some(sequence), &opts).await,
+19
View File
@@ -0,0 +1,19 @@
[package]
name = "common-cache"
version.workspace = true
edition.workspace = true
license.workspace = true
[lints]
workspace = true
[dependencies]
bytes.workspace = true
common-base.workspace = true
futures.workspace = true
moka = { workspace = true, features = ["future"] }
prometheus.workspace = true
[dev-dependencies]
async-trait.workspace = true
tokio = { workspace = true, features = ["macros", "rt", "sync"] }
+473
View File
@@ -0,0 +1,473 @@
// 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::borrow::Borrow;
use std::hash::Hash;
use std::sync::Arc;
use crate::metrics::{CacheMetrics, CacheSizeMetric, CacheSizeRegistration};
/// Reason for releasing an entry from the cache.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RemovalCause {
/// The entry reached its expiration time.
Expired,
/// The entry was explicitly invalidated.
Explicit,
/// A new value replaced the entry.
Replaced,
/// The entry was removed to satisfy the capacity policy.
Size,
}
impl RemovalCause {
/// Returns the established eviction metric label.
pub fn as_str(self) -> &'static str {
match self {
Self::Expired => "expired",
Self::Explicit => "explicit",
Self::Replaced => "replaced",
Self::Size => "size",
}
}
}
impl From<moka::notification::RemovalCause> for RemovalCause {
fn from(value: moka::notification::RemovalCause) -> Self {
match value {
moka::notification::RemovalCause::Expired => Self::Expired,
moka::notification::RemovalCause::Explicit => Self::Explicit,
moka::notification::RemovalCause::Replaced => Self::Replaced,
moka::notification::RemovalCause::Size => Self::Size,
}
}
}
/// A weighted memory cache with backend-provided asynchronous load deduplication.
/// Values should be inexpensive to clone, such as `Arc<T>` or `Bytes`.
/// Capacity is maintained asynchronously; insertion does not guarantee retention.
#[derive(Clone)]
pub struct Cache<K, V> {
inner: moka::future::Cache<K, V>,
capacity: u64,
size_registration: Option<CacheSizeRegistration>,
metrics: Option<Arc<CacheMetrics>>,
}
impl<K, V> Cache<K, V>
where
K: Eq + Hash + Send + Sync + 'static,
V: Clone + Send + Sync + 'static,
{
/// Creates a cache with the caller's weight and eviction accounting.
pub fn new<W, L>(name: &str, capacity: u64, weigher: W, listener: L) -> Self
where
W: Fn(&K, &V) -> u32 + Send + Sync + 'static,
L: Fn(Arc<K>, V, RemovalCause) + Send + Sync + 'static,
{
Self {
inner: moka::future::Cache::builder()
.name(name)
.max_capacity(capacity)
.support_invalidation_closures()
.weigher(weigher)
.eviction_listener(move |key, value, cause| listener(key, value, cause.into()))
.build(),
capacity,
size_registration: None,
metrics: None,
}
}
/// Attaches caller-bound metrics without changing existing hit/miss accounting.
pub fn with_metrics(mut self, metrics: Arc<CacheMetrics>) -> Self {
self.metrics = Some(metrics);
self
}
/// Samples this cache's retained weight when the caller collects byte metrics.
pub fn with_size_metric(mut self, metric: CacheSizeMetric) -> Self {
let cache = self.inner.clone();
self.size_registration = Some(metric.register(move || cache.weighted_size()));
self
}
/// Gets a completed value without starting a load.
pub fn get<'a, Q>(&'a self, key: &'a Q) -> impl Future<Output = Option<V>> + Send + 'a
where
K: Borrow<Q>,
Q: Hash + Eq + Sync + ?Sized,
{
self.inner.get(key)
}
/// Shares a successful load among concurrent callers with the same key and error type.
/// Errors are shared with current waiters but are not retained as cached values.
/// Cancelling the active loader lets a remaining caller execute its own loader.
pub async fn try_get_with<Q, F, E>(&self, key: &Q, load: F) -> Result<V, Arc<E>>
where
K: Borrow<Q>,
Q: ToOwned<Owned = K> + Hash + Eq + ?Sized,
F: Future<Output = Result<V, E>>,
E: Send + Sync + 'static,
{
let request = self
.metrics
.as_ref()
.map(|metrics| metrics.requests.start());
let result = self
.inner
.try_get_with_by_ref(key, async {
// Only the backend-selected loader contributes physical load metrics.
let operation = self.metrics.as_ref().map(|metrics| metrics.loads.start());
let result = load.await;
if let Some(operation) = operation {
operation.finish(&result);
}
result
})
.await;
if let Some(request) = request {
request.finish(&result);
}
result
}
/// Submits a completed value to the cache's admission and eviction policy.
pub async fn insert(&self, key: K, value: V) {
self.inner.insert(key, value).await;
}
/// Invalidates a completed entry. This does not cancel a concurrent loader.
pub async fn invalidate<Q>(&self, key: &Q)
where
K: Borrow<Q>,
Q: Hash + Eq + ?Sized,
{
self.inner.invalidate(key).await;
}
/// Invalidates completed entries matching a predicate. Pending loaders are not fenced.
/// Physical removal and eviction accounting run asynchronously.
pub fn invalidate_if<F>(&self, predicate: F) -> std::io::Result<()>
where
F: Fn(&K, &V) -> bool + Send + Sync + 'static,
{
self.inner
.invalidate_entries_if(predicate)
.map(|_| ())
.map_err(std::io::Error::other)
}
/// Returns the configured weight capacity.
pub fn capacity(&self) -> u64 {
self.capacity
}
/// Returns the approximate number of retained entries.
pub fn entry_count(&self) -> u64 {
self.inner.entry_count()
}
/// Returns the approximate total retained weight.
pub fn weighted_size(&self) -> u64 {
self.inner.weighted_size()
}
/// Applies pending admission, eviction, and accounting work.
pub async fn run_pending_tasks(&self) {
self.inner.run_pending_tasks().await;
}
}
#[cfg(test)]
mod tests {
use std::sync::atomic::{AtomicUsize, Ordering};
use tokio::sync::Notify;
use super::*;
// This is also a compile-time contract for generic callers crossing async-trait boundaries.
fn send_lookup<'a, K, V, Q>(
cache: &'a Cache<K, V>,
key: &'a Q,
) -> impl Future<Output = Option<V>> + Send + 'a
where
K: Borrow<Q> + Eq + Hash + Send + Sync + 'static,
V: Clone + Send + Sync + 'static,
Q: Hash + Eq + Sync + ?Sized,
{
cache.get(key)
}
#[tokio::test]
async fn test_borrowed_lookup_has_a_send_future() {
let cache = cache(1024);
cache
.insert("key".to_string(), Arc::new("value".to_string()))
.await;
let future: futures::future::BoxFuture<'_, Option<Arc<String>>> =
Box::pin(send_lookup(&cache, "key"));
assert_eq!(future.await.as_deref().map(String::as_str), Some("value"));
}
#[tokio::test]
async fn test_predicate_invalidation_preserves_other_entries() {
let cache = cache(1024);
cache
.insert("old".to_string(), Arc::new("a".to_string()))
.await;
cache
.insert("keep".to_string(), Arc::new("b".to_string()))
.await;
cache.run_pending_tasks().await;
cache.invalidate_if(|key, _| key == "old").unwrap();
assert!(cache.get("old").await.is_none());
assert_eq!(
cache.get("keep").await.as_deref().map(String::as_str),
Some("b")
);
}
fn cache(capacity: u64) -> Cache<String, Arc<String>> {
Cache::new(
"test",
capacity,
|_, value: &Arc<String>| value.len() as u32,
|_, _, _| {},
)
}
fn operation_metrics(name: &str) -> crate::metrics::OperationMetrics {
use prometheus::{Histogram, HistogramOpts, IntCounter, IntGauge};
crate::metrics::OperationMetrics {
started: IntCounter::new(format!("{name}_started"), "test").unwrap(),
succeeded: IntCounter::new(format!("{name}_succeeded"), "test").unwrap(),
failed: IntCounter::new(format!("{name}_failed"), "test").unwrap(),
cancelled: IntCounter::new(format!("{name}_cancelled"), "test").unwrap(),
active: IntGauge::new(format!("{name}_active"), "test").unwrap(),
elapsed: Histogram::with_opts(HistogramOpts::new(format!("{name}_seconds"), "test"))
.unwrap(),
}
}
fn instrumented_cache() -> (Cache<String, Arc<String>>, Arc<CacheMetrics>) {
let metrics = Arc::new(CacheMetrics {
requests: operation_metrics("requests"),
loads: operation_metrics("loads"),
});
(cache(1024).with_metrics(metrics.clone()), metrics)
}
#[tokio::test]
async fn test_metrics_distinguish_requests_from_executed_loads() {
let (cache, metrics) = instrumented_cache();
// Merely constructing an async call does not start an operation.
drop(cache.try_get_with("unused", async { Ok::<_, ()>(Arc::new(String::new())) }));
assert_eq!(0, metrics.requests.started.get());
let gate = Notify::new();
let mut first = Box::pin(cache.try_get_with("key", async {
gate.notified().await;
Ok::<_, ()>(Arc::new("value".to_string()))
}));
let mut second = Box::pin(cache.try_get_with("key", async { Err::<Arc<String>, _>(()) }));
assert!(futures::poll!(&mut first).is_pending());
assert!(futures::poll!(&mut second).is_pending());
assert_eq!(2, metrics.requests.active.get());
assert_eq!(1, metrics.loads.active.get());
gate.notify_waiters();
let (first, second) = tokio::join!(first, second);
assert!(Arc::ptr_eq(&first.unwrap(), &second.unwrap()));
cache
.try_get_with("key", async { Err::<Arc<String>, _>(()) })
.await
.unwrap();
assert_eq!(3, metrics.requests.started.get());
assert_eq!(3, metrics.requests.succeeded.get());
assert_eq!(1, metrics.loads.started.get());
assert_eq!(1, metrics.loads.succeeded.get());
assert_eq!(0, metrics.requests.active.get());
assert_eq!(0, metrics.loads.active.get());
assert_eq!(3, metrics.requests.elapsed.get_sample_count());
assert_eq!(1, metrics.loads.elapsed.get_sample_count());
assert_eq!(0, metrics.requests.failed.get());
assert_eq!(0, metrics.requests.cancelled.get());
}
#[tokio::test]
async fn test_metrics_release_active_work_on_cancellation_and_error() {
let (cache, metrics) = instrumented_cache();
let mut producer =
Box::pin(cache.try_get_with("key", std::future::pending::<Result<Arc<String>, ()>>()));
let mut waiter =
Box::pin(cache.try_get_with("key", std::future::pending::<Result<Arc<String>, ()>>()));
assert!(futures::poll!(&mut producer).is_pending());
assert!(futures::poll!(&mut waiter).is_pending());
drop(waiter);
assert_eq!(1, metrics.requests.cancelled.get());
assert_eq!(0, metrics.loads.cancelled.get());
drop(producer);
assert_eq!(2, metrics.requests.cancelled.get());
assert_eq!(1, metrics.loads.cancelled.get());
let result = cache
.try_get_with("key", async { Err::<Arc<String>, _>(()) })
.await;
assert!(result.is_err());
assert_eq!(1, metrics.requests.failed.get());
assert_eq!(1, metrics.loads.failed.get());
assert_eq!(0, metrics.requests.active.get());
assert_eq!(0, metrics.loads.active.get());
assert_eq!(3, metrics.requests.elapsed.get_sample_count());
assert_eq!(2, metrics.loads.elapsed.get_sample_count());
}
#[tokio::test]
async fn test_instrumented_loading_future_is_send() {
fn assert_send<T: Send>(value: T) -> T {
value
}
let (cache, _) = instrumented_cache();
assert_send(
cache.try_get_with("key", async { Ok::<_, ()>(Arc::new("value".to_string())) }),
)
.await
.unwrap();
}
#[tokio::test]
async fn test_shares_load_and_bypasses_loader_on_hit() {
let cache = cache(1024);
let calls = AtomicUsize::new(0);
let gate = Notify::new();
let load = || async {
calls.fetch_add(1, Ordering::Relaxed);
gate.notified().await;
Ok::<_, ()>(Arc::new("value".to_string()))
};
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!(1, calls.load(Ordering::Relaxed));
gate.notify_waiters();
let (first, second) = tokio::join!(first, second);
let first = first.unwrap();
assert!(Arc::ptr_eq(&first, &second.unwrap()));
let hit = cache
.try_get_with("key", async { Err::<Arc<String>, _>(()) })
.await
.unwrap();
assert!(Arc::ptr_eq(&first, &hit));
}
#[tokio::test]
async fn test_remaining_waiter_loads_after_producer_cancellation() {
let (cache, metrics) = instrumented_cache();
let mut first =
Box::pin(cache.try_get_with("key", std::future::pending::<Result<Arc<String>, ()>>()));
assert!(futures::poll!(&mut first).is_pending());
let mut second = Box::pin(
cache.try_get_with("key", async { Ok::<_, ()>(Arc::new("retry".to_string())) }),
);
assert!(futures::poll!(&mut second).is_pending());
drop(first);
assert_eq!("retry", second.await.unwrap().as_str());
assert_eq!(2, metrics.requests.started.get());
assert_eq!(1, metrics.requests.cancelled.get());
assert_eq!(1, metrics.requests.succeeded.get());
assert_eq!(2, metrics.loads.started.get());
assert_eq!(1, metrics.loads.cancelled.get());
assert_eq!(1, metrics.loads.succeeded.get());
assert_eq!(0, metrics.requests.active.get());
assert_eq!(0, metrics.loads.active.get());
}
#[tokio::test]
async fn test_errors_are_shared_but_not_cached() {
let (cache, metrics) = instrumented_cache();
let calls = AtomicUsize::new(0);
let gate = Notify::new();
let load = || async {
calls.fetch_add(1, Ordering::Relaxed);
gate.notified().await;
Err::<Arc<String>, _>("read failed")
};
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();
let (first, second) = tokio::join!(first, second);
assert!(Arc::ptr_eq(&first.unwrap_err(), &second.unwrap_err()));
assert_eq!(2, metrics.requests.failed.get());
assert_eq!(1, metrics.loads.failed.get());
assert_eq!(0, metrics.requests.active.get());
assert_eq!(0, metrics.loads.active.get());
assert_eq!(1, calls.load(Ordering::Relaxed));
assert!(cache.get("key").await.is_none());
assert_eq!(
"retry",
cache
.try_get_with("key", async {
Ok::<_, &'static str>(Arc::new("retry".to_string()))
})
.await
.unwrap()
.as_str()
);
}
#[tokio::test]
async fn test_sampled_size_sums_instances_and_preserves_manual_bytes() {
use crate::metrics::CacheSizeMetrics;
use prometheus::Opts;
use prometheus::core::Collector;
let metrics =
CacheSizeMetrics::new(Opts::new("test_cache_bytes", "test"), &["type"]).unwrap();
let manual = metrics.with_label_values(&["shared"]);
manual.set(3);
let make_cache = || {
Cache::new("sampled", 100, |_: &u64, _: &Arc<String>| 7, |_, _, _| {})
.with_size_metric(metrics.bind(&["shared"]))
};
let a = make_cache();
let b = make_cache();
let sample = || {
metrics.collect()[0].get_metric()[0]
.get_gauge()
.as_ref()
.map_or(0.0, |gauge| gauge.value())
};
a.insert(1, Arc::new("one".into())).await;
b.insert(2, Arc::new("two".into())).await;
a.run_pending_tasks().await;
b.run_pending_tasks().await;
assert_eq!(17.0, sample());
assert_eq!(3, manual.get());
let consumer = a.get(&1).await.unwrap();
a.invalidate(&1).await;
a.run_pending_tasks().await;
assert_eq!(10.0, sample());
drop(consumer);
let cloned = b.clone();
drop(b);
assert_eq!(10.0, sample());
drop(cloned);
assert_eq!(3.0, sample());
}
}
+23
View File
@@ -0,0 +1,23 @@
// 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 memory cache primitives with native asynchronous load deduplication.
mod cache;
pub mod metrics;
pub mod page;
pub mod paged;
pub use cache::{Cache, RemovalCause};
+194
View File
@@ -0,0 +1,194 @@
// 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, Mutex, Weak};
use std::time::Instant;
use prometheus::core::{Collector, Desc};
use prometheus::proto::{Gauge, MetricFamily};
use prometheus::{Histogram, IntCounter, IntGauge, IntGaugeVec, Opts};
/// Caller-bound metrics for native cache loading. No collectors are registered here.
/// Requests count only `try_get_with` calls, including its cache hits and callers sharing
/// another request's load. Plain `get` calls are not counted. Loads count
/// only loader futures actually polled by the backend; their difference is not a waiter count.
#[derive(Clone)]
pub struct CacheMetrics {
pub requests: OperationMetrics,
pub loads: OperationMetrics,
}
/// Metrics for one operation, with labels bound once when constructing a cache.
/// Completion counters are mutually exclusive. Dropping an unfinished future is cancellation.
#[derive(Clone)]
pub struct OperationMetrics {
pub started: IntCounter,
pub succeeded: IntCounter,
pub failed: IntCounter,
pub cancelled: IntCounter,
pub active: IntGauge,
/// Wall-clock lifetime, including suspended time, for every outcome.
pub elapsed: Histogram,
}
impl OperationMetrics {
/// Starts tracking an operation and its elapsed time.
pub(crate) fn start(&self) -> OperationGuard<'_> {
self.started.inc();
self.active.inc();
OperationGuard {
metrics: self,
started: Instant::now(),
completed: false,
}
}
}
/// Tracks an operation, recording cancellation if dropped before completion.
pub(crate) struct OperationGuard<'a> {
metrics: &'a OperationMetrics,
started: Instant,
completed: bool,
}
impl OperationGuard<'_> {
/// Records success or failure and completes the operation.
pub(crate) fn finish<T, E>(mut self, result: &Result<T, E>) {
if result.is_ok() {
self.metrics.succeeded.inc();
} else {
self.metrics.failed.inc();
}
self.completed = true;
}
}
impl Drop for OperationGuard<'_> {
fn drop(&mut self) {
if !self.completed {
self.metrics.cancelled.inc();
}
self.metrics.active.dec();
self.metrics
.elapsed
.observe(self.started.elapsed().as_secs_f64());
}
}
/// Cache byte metrics combining manually maintained gauges and sampled cache weights.
/// Sampling does not force backend maintenance or include pending loader values.
#[derive(Clone)]
pub struct CacheSizeMetrics {
gauges: IntGaugeVec,
sources: Arc<Mutex<Vec<CacheSizeSource>>>,
}
/// A byte metric with labels bound for one or more cache instances.
#[derive(Clone)]
pub struct CacheSizeMetric {
metrics: CacheSizeMetrics,
gauge: IntGauge,
}
/// Keeps a cache instance registered for size sampling while any owner remains.
#[derive(Clone)]
pub struct CacheSizeRegistration {
_reader: Arc<dyn Fn() -> u64 + Send + Sync>,
}
struct CacheSizeSource {
gauge: IntGauge,
read: Weak<dyn Fn() -> u64 + Send + Sync>,
}
impl CacheSizeMetrics {
/// Creates an unregistered collector. Register a clone with the caller's registry.
pub fn new(opts: Opts, labels: &[&str]) -> prometheus::Result<Self> {
Ok(Self {
gauges: IntGaugeVec::new(opts, labels)?,
sources: Arc::new(Mutex::new(Vec::new())),
})
}
/// Returns the backing gauges for callers retaining manual accounting.
pub fn gauges(&self) -> &IntGaugeVec {
&self.gauges
}
/// Returns a manually maintained gauge for existing non-cache accounting.
pub fn with_label_values(&self, labels: &[&str]) -> IntGauge {
self.gauges.with_label_values(labels)
}
/// Binds labels for sampled cache weights. Instances sharing labels are summed.
pub fn bind(&self, labels: &[&str]) -> CacheSizeMetric {
CacheSizeMetric {
metrics: self.clone(),
gauge: self.gauges.with_label_values(labels),
}
}
}
impl CacheSizeMetric {
/// Registers a cache-level weight reader without retaining it in the collector.
/// Keep the returned registration alongside the cache, including in its clones.
pub fn register(
&self,
read: impl Fn() -> u64 + Send + Sync + 'static,
) -> CacheSizeRegistration {
let read: Arc<dyn Fn() -> u64 + Send + Sync> = Arc::new(read);
self.metrics
.sources
.lock()
.unwrap_or_else(|e| e.into_inner())
.push(CacheSizeSource {
gauge: self.gauge.clone(),
read: Arc::downgrade(&read),
});
CacheSizeRegistration { _reader: read }
}
}
impl Collector for CacheSizeMetrics {
fn desc(&self) -> Vec<&Desc> {
self.gauges.desc()
}
fn collect(&self) -> Vec<MetricFamily> {
let mut families = self.gauges.collect();
let mut sources = self.sources.lock().unwrap_or_else(|e| e.into_inner());
sources.retain(|source| {
let Some(read) = source.read.upgrade() else {
return false;
};
let labels = source.gauge.collect();
for family in &mut families {
for metric in family.mut_metric() {
if metric.get_label() == labels[0].get_metric()[0].get_label() {
let bytes = metric
.get_gauge()
.as_ref()
.map_or(0.0, |gauge| gauge.value())
+ read() as f64;
let mut gauge = Gauge::default();
gauge.set_value(bytes);
metric.set_gauge(gauge);
}
}
}
true
});
families
}
}
+156
View File
@@ -0,0 +1,156 @@
// 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.
//! Fixed-size byte page layout for immutable cached content.
use std::io;
use std::num::NonZeroU64;
use std::ops::Range;
/// Fixed-size logical byte pages within one immutable file.
#[derive(Debug, Clone, Copy)]
pub struct PageLayout {
page_size: NonZeroU64,
file_size: u64,
}
impl PageLayout {
/// Creates a layout. The final page is clipped to the file size.
pub fn new(page_size: NonZeroU64, file_size: u64) -> Self {
Self {
page_size,
file_size,
}
}
/// Returns the half-open page-ID range intersecting a byte request.
///
/// Requests are clipped at EOF. Empty or wholly out-of-file requests return
/// an empty range; reversed ranges are rejected. This does not allocate one
/// entry per page, even for large files.
pub fn page_ids(&self, request: Range<u64>) -> io::Result<Range<u64>> {
validate_range(&request)?;
let start = request.start.min(self.file_size);
let end = request.end.min(self.file_size);
let first = start / self.page_size.get();
if start == end {
return Ok(first..first);
}
// end > 0 here. Unlike (end + page_size - 1) / page_size,
// this expression cannot overflow at the end of a large file.
let last = (end - 1) / self.page_size.get();
Ok(first..last + 1)
}
/// Returns a page's file byte range, or `None` for a page outside the file.
pub fn page_range(&self, page_id: u64) -> Option<Range<u64>> {
let start = page_id.checked_mul(self.page_size.get())?;
if start >= self.file_size {
return None;
}
let len = self.page_size.get().min(self.file_size - start);
Some(start..start + len)
}
/// Returns the requested slice relative to a page's buffer.
///
/// Returns `None` if the page and request do not intersect. The caller can
/// borrow this slice for an immediate response; caching a slice of a much
/// larger I/O buffer may retain that entire allocation and needs a copy.
pub fn request_slice(
&self,
page_id: u64,
request: Range<u64>,
) -> io::Result<Option<Range<usize>>> {
validate_range(&request)?;
let Some(page) = self.page_range(page_id) else {
return Ok(None);
};
let start = request.start.max(page.start);
let end = request.end.min(page.end);
if start >= end {
return Ok(None);
}
Ok(Some(
to_usize(start - page.start)?..to_usize(end - page.start)?,
))
}
}
fn validate_range(range: &Range<u64>) -> io::Result<()> {
if range.start > range.end {
return Err(invalid_input("Byte range start exceeds end"));
}
Ok(())
}
fn to_usize(value: u64) -> io::Result<usize> {
usize::try_from(value).map_err(|_| invalid_input("Byte offset exceeds addressable memory"))
}
fn invalid_input(message: &'static str) -> io::Error {
io::Error::new(io::ErrorKind::InvalidInput, message)
}
#[cfg(test)]
mod tests {
use super::*;
fn nonzero(value: u64) -> NonZeroU64 {
NonZeroU64::new(value).unwrap()
}
#[test]
fn test_page_alignment_and_eof() {
let layout = PageLayout::new(nonzero(64), 150);
for (request, expected) in [
(0..0, 0..0),
(0..64, 0..1),
(32..96, 0..2),
(64..128, 1..2),
(128..200, 2..3),
(150..200, 2..2),
] {
assert_eq!(layout.page_ids(request).unwrap(), expected);
}
assert_eq!(layout.page_range(2), Some(128..150));
assert_eq!(layout.page_range(3), None);
assert_eq!(layout.request_slice(0, 32..96).unwrap(), Some(32..64));
assert_eq!(layout.request_slice(1, 32..96).unwrap(), Some(0..32));
assert_eq!(layout.request_slice(2, 128..200).unwrap(), Some(0..22));
assert_eq!(layout.request_slice(1, 0..64).unwrap(), None);
assert_eq!(PageLayout::new(nonzero(64), 0).page_range(0), None);
assert!(layout.page_ids(Range { start: 2, end: 1 }).is_err());
assert!(layout.request_slice(0, Range { start: 2, end: 1 }).is_err());
}
#[test]
fn test_large_file_boundaries() {
let layout = PageLayout::new(nonzero(1), u64::MAX);
assert_eq!(layout.page_ids(0..u64::MAX).unwrap(), 0..u64::MAX);
assert_eq!(
layout.page_range(u64::MAX - 1),
Some(u64::MAX - 1..u64::MAX)
);
assert_eq!(layout.page_range(u64::MAX), None);
let layout = PageLayout::new(nonzero(64), u64::MAX);
assert_eq!(layout.page_range(u64::MAX), None);
let last = u64::MAX / 64;
assert_eq!(layout.page_range(last), Some(last * 64..u64::MAX));
assert_eq!(
layout.page_ids(u64::MAX - 1..u64::MAX).unwrap(),
last..last + 1
);
}
}
+384
View File
@@ -0,0 +1,384 @@
// 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.
//! Immutable byte pages backed by native cache loading and direct range reads.
#[cfg(test)]
mod tests;
use std::collections::{BTreeMap, BTreeSet};
use std::future::Future;
use std::hash::Hash;
use std::io;
use std::num::NonZeroU64;
use std::ops::Range;
use std::sync::Arc;
use std::task::Poll;
use bytes::{Bytes, BytesMut};
use common_base::range_read::RangeReader;
use futures::channel::{mpsc, oneshot};
use futures::{StreamExt, future};
use crate::metrics::{CacheMetrics, CacheSizeMetric};
use crate::page::PageLayout;
use crate::{Cache, RemovalCause};
/// Business-level events; callers retain their existing hit/miss metric units.
pub enum PageEvent {
/// Unique logical page lookups in one request, before any missing loads execute.
Lookup { hits: usize, misses: usize },
/// One successful native page loader, excluding waiters and hits.
Loaded { bytes: u64 },
/// Backend weight, not process RSS; sampled after fetch/maintenance.
Residency { usage: u64, capacity: u64 },
/// Backend eviction, excluding unadmitted values released by their owners.
Evicted { cause: RemovalCause },
}
/// Caller-bound metrics without storage-engine dependencies or global registrations.
#[derive(Clone)]
pub struct PageCacheObserver {
pub bytes: CacheSizeMetric,
pub loads: Option<Arc<CacheMetrics>>,
pub events: Arc<dyn Fn(PageEvent) + Send + Sync>,
}
/// Byte accounting for one successful fetch. Hits are initial lookups, not waiters.
#[derive(Debug, Default)]
pub struct PageFetchStats {
pub cache_hit: usize,
pub cache_miss: usize,
/// Requested intersections already cached; overlapping requests count repeatedly.
pub cached_bytes: u64,
pub cached_fragments: usize,
/// Original request lengths, including duplicates and overlaps.
pub requested_bytes: u64,
/// Sum of unique logical page lengths, clipped at EOF, including cache hits.
pub aligned_bytes: u64,
/// Union of original request byte ranges, excluding overlaps.
pub unique_requested_bytes: u64,
}
/// Caches fixed-size byte pages of immutable content identified by `K`.
/// File identity must include any version needed to distinguish different contents.
/// Missing pages elected by this fetch are submitted through [`RangeReader::read_vec`].
pub struct PagedCache<K> {
cache: Cache<(K, u64), Arc<CachedPage>>,
page_size: u64,
observer: PageCacheObserver,
}
impl<K: Hash + Eq + Clone + Send + Sync + 'static> PagedCache<K> {
/// Creates an independent cache budget. Zero page size is rejected by fetch.
pub fn new(
name: &str,
capacity: u64,
page_size: u64,
weigher: impl Fn(&(K, u64), &Bytes) -> u32 + Send + Sync + 'static,
observer: PageCacheObserver,
) -> Self {
let events = observer.events.clone();
let mut cache = Cache::new(
name,
capacity,
move |key, value: &Arc<CachedPage>| weigher(key, &value.bytes),
move |_, _, cause| {
events(PageEvent::Evicted { cause });
},
)
.with_size_metric(observer.bytes.clone());
if let Some(metrics) = &observer.loads {
cache = cache.with_metrics(metrics.clone());
}
Self {
cache,
page_size,
observer,
}
}
/// Invalidates completed pages. Concurrent loads are not fenced.
pub fn invalidate_if(
&self,
predicate: impl Fn(&K) -> bool + Send + Sync + 'static,
) -> io::Result<()> {
self.cache
.invalidate_if(move |(file, _), _| predicate(file))
}
/// Looks up a completed page without updating business lookup counters.
pub async fn contains(&self, file: &K, page_id: u64) -> bool {
self.cache.get(&(file.clone(), page_id)).await.is_some()
}
/// Recovers immutable file size from a requested page already in memory.
pub async fn known_file_size(&self, file: &K, ranges: &[Range<u64>]) -> Option<u64> {
let layout = PageLayout::new(NonZeroU64::new(self.page_size)?, u64::MAX);
for range in ranges {
for id in layout.page_ids(range.clone()).ok()? {
if let Some(page) = self.cache.get(&(file.clone(), id)).await {
return Some(page.file_size);
}
}
}
None
}
/// Applies pending cache admission and eviction work.
pub async fn run_pending_tasks(&self) {
self.cache.run_pending_tasks().await;
self.observe_residency();
}
/// Fetches bytes in input order. The reader must address the same immutable
/// content as `file`. Each successful loader reads one complete missing page.
pub async fn fetch<R: RangeReader + ?Sized>(
&self,
file: K,
file_size: u64,
ranges: &[Range<u64>],
reader: &R,
) -> Result<(Vec<Bytes>, PageFetchStats), Arc<io::Error>> {
if ranges.iter().any(|r| r.start > r.end || r.end > file_size) {
return Err(invalid_request());
}
let page_size = NonZeroU64::new(self.page_size).ok_or_else(invalid_request)?;
let layout = PageLayout::new(page_size, file_size);
let mut stats = PageFetchStats::default();
let mut ids = BTreeSet::new();
for range in ranges {
stats.requested_bytes = stats
.requested_bytes
.checked_add(range.end - range.start)
.ok_or_else(invalid_request)?;
ids.extend(layout.page_ids(range.clone()).map_err(Arc::new)?);
}
stats.unique_requested_bytes = unique_requested_bytes(ranges);
let mut pages = BTreeMap::new();
let mut missing = Vec::new();
for id in ids {
let range = layout.page_range(id).ok_or_else(invalid_request)?;
stats.aligned_bytes += range.end - range.start;
if let Some(page) = self.cache.get(&(file.clone(), id)).await {
check_file_size(&page, file_size)?;
pages.insert(id, page.bytes.clone());
} else {
missing.push(id);
}
}
for range in ranges {
for id in layout.page_ids(range.clone()).map_err(Arc::new)? {
if pages.contains_key(&id) {
let slice = layout
.request_slice(id, range.clone())
.map_err(Arc::new)?
.ok_or_else(invalid_request)?;
stats.cached_bytes += slice.len() as u64;
stats.cached_fragments += 1;
}
}
}
stats.cache_hit = pages.len();
stats.cache_miss = missing.len();
(self.observer.events)(PageEvent::Lookup {
hits: stats.cache_hit,
misses: stats.cache_miss,
});
if !missing.is_empty() {
let (requests, receiver) = mpsc::unbounded();
let batch_size = missing.len().max(1);
let mut loads = missing
.into_iter()
.map(|id| {
let requests = requests.clone();
let key = (file.clone(), id);
Box::pin(future::maybe_done(async move {
let range = layout.page_range(id).ok_or_else(invalid_request)?;
let page = self
.cache
.try_get_with(&key, async {
let (send, receive) =
oneshot::channel::<Result<Bytes, Arc<io::Error>>>();
requests
.unbounded_send((range.clone(), send))
.map_err(|_| io::Error::other("Page read batch closed"))?;
let bytes = receive
.await
.map_err(|_| io::Error::other("Page read batch cancelled"))?
.map_err(|error: Arc<io::Error>| {
io::Error::new(error.kind(), error)
})?;
if bytes.len() as u64 != range.end - range.start {
return Err(io::Error::new(
io::ErrorKind::UnexpectedEof,
"Invalid page response length",
));
}
// Detach readers' shared backing buffers from cache accounting.
Ok(self
.create_cached_page(file_size, Bytes::copy_from_slice(&bytes)))
})
.await?;
check_file_size(&page, file_size)?;
Ok::<_, Arc<io::Error>>((id, page.bytes.clone()))
}))
})
.collect::<Vec<_>>();
// Poll every page before driving I/O, so executor fairness limits do not
// split one fetch's immediately available misses into separate batches.
let loads = future::poll_fn(move |cx| {
let mut complete = true;
for load in &mut loads {
complete &= load.as_mut().poll(cx).is_ready();
if let Some(Err(error)) = load.as_mut().output_mut() {
return Poll::Ready(Err(error.clone()));
}
}
if !complete {
return Poll::Pending;
}
Poll::Ready(
loads
.iter_mut()
.map(|load| load.as_mut().take_output().ok_or_else(invalid_request)?)
.collect::<Result<Vec<_>, _>>(),
)
});
// The channel contains only loaders elected by Moka for this fetch. Waiters
// enqueue nothing; a waiter promoted after cancellation can enqueue later.
drop(requests);
let read_batches = async {
let mut batches = receiver.ready_chunks(batch_size);
while let Some(batch) = batches.next().await {
let (ranges, replies): (Vec<_>, Vec<_>) = batch.into_iter().unzip();
let result = reader.read_vec(&ranges).await.and_then(|bytes| {
if bytes.len() == ranges.len() {
Ok(bytes)
} else {
Err(io::Error::new(
io::ErrorKind::InvalidData,
"Invalid page response count",
))
}
});
match result {
Ok(bytes) => {
for (reply, bytes) in replies.into_iter().zip(bytes) {
let _ = reply.send(Ok(bytes));
}
}
Err(error) => {
let error = Arc::new(error);
for reply in replies {
let _ = reply.send(Err(error.clone()));
}
}
}
}
Ok::<(), Arc<io::Error>>(())
};
let (loaded, ()) = future::try_join(loads, read_batches).await?;
pages.extend(loaded);
}
let mut output = Vec::with_capacity(ranges.len());
for range in ranges {
if range.is_empty() {
output.push(Bytes::new());
continue;
}
let ids = layout.page_ids(range.clone()).map_err(Arc::new)?;
if ids.end - ids.start == 1 {
let slice = layout
.request_slice(ids.start, range.clone())
.map_err(Arc::new)?
.ok_or_else(invalid_request)?;
let page = pages.get(&ids.start).ok_or_else(invalid_request)?;
if slice.end > page.len() {
return Err(invalid_request());
}
output.push(page.slice(slice));
continue;
}
let len = usize::try_from(range.end - range.start).map_err(|_| invalid_request())?;
let mut assembled = BytesMut::with_capacity(len);
for id in ids {
let slice = layout
.request_slice(id, range.clone())
.map_err(Arc::new)?
.ok_or_else(invalid_request)?;
let page = pages.get(&id).ok_or_else(invalid_request)?;
if slice.end > page.len() {
return Err(invalid_request());
}
assembled.extend_from_slice(&page[slice]);
}
if assembled.len() != len {
return Err(invalid_request());
}
output.push(assembled.freeze());
}
self.observe_residency();
Ok((output, stats))
}
fn create_cached_page(&self, file_size: u64, bytes: Bytes) -> Arc<CachedPage> {
(self.observer.events)(PageEvent::Loaded {
bytes: bytes.len() as u64,
});
Arc::new(CachedPage { file_size, bytes })
}
fn observe_residency(&self) {
(self.observer.events)(PageEvent::Residency {
usage: self.cache.weighted_size(),
capacity: self.cache.capacity(),
});
}
}
struct CachedPage {
file_size: u64,
bytes: Bytes,
}
fn invalid_request() -> Arc<io::Error> {
Arc::new(io::Error::new(
io::ErrorKind::InvalidInput,
"Invalid cached page range",
))
}
fn check_file_size(page: &CachedPage, expected: u64) -> Result<(), Arc<io::Error>> {
if page.file_size != expected {
return Err(Arc::new(io::Error::new(
io::ErrorKind::InvalidInput,
"Cached content identity used with inconsistent file sizes",
)));
}
Ok(())
}
/// Counts the union of request ranges already validated by fetch.
fn unique_requested_bytes(ranges: &[Range<u64>]) -> u64 {
let mut ranges = ranges.to_vec();
ranges.sort_unstable_by_key(|range| range.start);
let mut end = 0;
let mut bytes = 0;
for range in ranges {
bytes += range.end.saturating_sub(range.start.max(end));
end = end.max(range.end);
}
bytes
}
+492
View File
@@ -0,0 +1,492 @@
// 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::future::Future;
use std::pin::Pin;
use std::sync::Mutex;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::time::Duration;
use async_trait::async_trait;
use common_base::range_read::Metadata;
use tokio::sync::Semaphore;
use super::*;
#[derive(Default)]
struct Reader {
reads: Mutex<Vec<Range<u64>>>,
batches: Mutex<Vec<Vec<Range<u64>>>>,
gate: Option<Semaphore>,
error: Option<io::ErrorKind>,
}
impl Reader {
fn gated() -> Self {
Self {
gate: Some(Semaphore::new(0)),
..Default::default()
}
}
fn count(&self) -> usize {
self.reads.lock().unwrap().len()
}
fn release(&self) {
self.gate.as_ref().unwrap().add_permits(64);
}
}
#[async_trait]
impl RangeReader for Reader {
async fn metadata(&self) -> io::Result<Metadata> {
Ok(Metadata { content_length: 16 })
}
async fn read_vec(&self, ranges: &[Range<u64>]) -> io::Result<Vec<Bytes>> {
self.batches.lock().unwrap().push(ranges.to_vec());
future::try_join_all(ranges.iter().map(|range| self.read(range.clone()))).await
}
async fn read(&self, range: Range<u64>) -> io::Result<Bytes> {
self.reads.lock().unwrap().push(range.clone());
if let Some(gate) = &self.gate {
gate.acquire().await.unwrap().forget();
}
if let Some(kind) = self.error {
return Err(io::Error::new(kind, "backend failed"));
}
Ok(Bytes::from(range.map(|n| n as u8).collect::<Vec<_>>()))
}
}
struct Observation {
loaded: AtomicUsize,
bytes: crate::metrics::CacheSizeMetrics,
}
impl Observation {
fn bytes(&self) -> i64 {
use prometheus::core::Collector;
self.bytes.collect()[0].get_metric()[0]
.get_gauge()
.as_ref()
.unwrap()
.value() as i64
}
}
fn cache() -> (PagedCache<u64>, Arc<Observation>) {
let observation = Arc::new(Observation {
loaded: AtomicUsize::new(0),
bytes: crate::metrics::CacheSizeMetrics::new(
prometheus::Opts::new("test_page_bytes", "test"),
&[],
)
.unwrap(),
});
let events = observation.clone();
let observer = PageCacheObserver {
bytes: observation.bytes.bind(&[]),
loads: None,
events: Arc::new(move |event| {
if let PageEvent::Loaded { .. } = event {
events.loaded.fetch_add(1, Ordering::Relaxed);
}
}),
};
(
PagedCache::new("pages", 1024, 4, |_, bytes| bytes.len() as u32, observer),
observation,
)
}
async fn start_read<F: Future>(mut future: Pin<&mut F>, reader: &Reader, count: usize) {
tokio::time::timeout(Duration::from_secs(5), async {
loop {
assert!(futures::poll!(future.as_mut()).is_pending());
if reader.count() >= count {
break;
}
tokio::task::yield_now().await;
}
})
.await
.unwrap();
}
#[tokio::test]
async fn test_partial_hits_overlaps_and_eof_preserve_order() {
let (cache, observation) = cache();
let reader = Reader::default();
let (first, stats) = cache.fetch(1, 10, &[2..6, 4..5], &reader).await.unwrap();
assert_eq!(
first,
vec![Bytes::from_static(&[2, 3, 4, 5]), Bytes::from_static(&[4])]
);
assert_eq!((stats.cache_hit, stats.cache_miss), (0, 2));
assert_eq!(
(
stats.requested_bytes,
stats.unique_requested_bytes,
stats.aligned_bytes
),
(5, 4, 8)
);
let (second, stats) = cache
.fetch(1, 10, &[6..10, 1..3, 10..10], &reader)
.await
.unwrap();
assert_eq!(
second,
vec![
Bytes::from_static(&[6, 7, 8, 9]),
Bytes::from_static(&[1, 2]),
Bytes::new()
]
);
assert_eq!((stats.cache_hit, stats.cache_miss), (2, 1));
assert_eq!((stats.cached_bytes, stats.cached_fragments), (4, 2));
assert_eq!(observation.loaded.load(Ordering::Relaxed), 3);
assert_eq!(
cache
.known_file_size(&1, std::slice::from_ref(&(8..9)))
.await,
Some(10)
);
assert_eq!(*reader.reads.lock().unwrap(), vec![0..4, 4..8, 8..10]);
cache.run_pending_tasks().await;
assert_eq!(observation.bytes(), 10);
cache.invalidate_if(|file| *file == 1).unwrap();
cache.run_pending_tasks().await;
assert!(!cache.contains(&1, 0).await);
assert_eq!(observation.bytes(), 0);
// Returned values remain valid after invalidation, while cache accounting is released.
assert_eq!(&second[0][..], &[6, 7, 8, 9]);
}
#[tokio::test]
async fn test_overlapping_fetches_share_pages_and_only_read_missing_bytes() {
let (cache, observation) = cache();
let reader = Reader::gated();
let first_range = 0..8;
let first_ranges = std::slice::from_ref(&first_range);
let second_range = 4..12;
let second_ranges = std::slice::from_ref(&second_range);
let mut first = Box::pin(cache.fetch(1, 16, first_ranges, &reader));
start_read(first.as_mut(), &reader, 2).await;
let mut second = Box::pin(cache.fetch(1, 16, second_ranges, &reader));
start_read(second.as_mut(), &reader, 3).await;
reader.release();
let (first, second) = tokio::time::timeout(Duration::from_secs(5), async {
tokio::join!(first, second)
})
.await
.unwrap();
assert_eq!(&first.unwrap().0[0][..], &(0..8).collect::<Vec<u8>>());
assert_eq!(&second.unwrap().0[0][..], &(4..12).collect::<Vec<u8>>());
assert_eq!(*reader.reads.lock().unwrap(), vec![0..4, 4..8, 8..12]);
assert_eq!(observation.loaded.load(Ordering::Relaxed), 3);
}
#[tokio::test]
async fn test_cancelling_owner_allows_waiter_to_finish() {
let (cache, observation) = cache();
let reader = Reader::gated();
let range = 0..4;
let ranges = std::slice::from_ref(&range);
let mut owner = Box::pin(cache.fetch(1, 16, ranges, &reader));
start_read(owner.as_mut(), &reader, 1).await;
let mut waiter = Box::pin(cache.fetch(1, 16, ranges, &reader));
assert!(futures::poll!(&mut waiter).is_pending());
assert_eq!(reader.count(), 1);
drop(owner);
reader.release();
let result = tokio::time::timeout(Duration::from_secs(5), waiter)
.await
.unwrap()
.unwrap();
assert_eq!(&result.0[0][..], &[0, 1, 2, 3]);
assert_eq!(reader.count(), 2);
assert_eq!(observation.loaded.load(Ordering::Relaxed), 1);
}
#[tokio::test]
async fn test_cancelling_waiter_does_not_cancel_owner() {
let (cache, _) = cache();
let reader = Reader::gated();
let range = 0..4;
let ranges = std::slice::from_ref(&range);
let mut owner = Box::pin(cache.fetch(1, 16, ranges, &reader));
start_read(owner.as_mut(), &reader, 1).await;
let mut waiter = Box::pin(cache.fetch(1, 16, ranges, &reader));
assert!(futures::poll!(&mut waiter).is_pending());
drop(waiter);
reader.release();
let result = tokio::time::timeout(Duration::from_secs(5), owner)
.await
.unwrap()
.unwrap();
assert_eq!(&result.0[0][..], &[0, 1, 2, 3]);
assert_eq!(reader.count(), 1);
}
#[tokio::test]
async fn test_backend_error_is_shared_and_not_cached() {
let (cache, observation) = cache();
let reader = Reader {
error: Some(io::ErrorKind::BrokenPipe),
..Reader::gated()
};
let range = 0..4;
let ranges = std::slice::from_ref(&range);
let mut owner = Box::pin(cache.fetch(1, 16, ranges, &reader));
start_read(owner.as_mut(), &reader, 1).await;
let mut waiter = Box::pin(cache.fetch(1, 16, ranges, &reader));
assert!(futures::poll!(&mut waiter).is_pending());
reader.release();
let (owner, waiter) = tokio::time::timeout(Duration::from_secs(5), async {
tokio::join!(owner, waiter)
})
.await
.unwrap();
for result in [owner, waiter] {
let error = result.unwrap_err();
assert_eq!(error.kind(), io::ErrorKind::BrokenPipe);
assert!(error.to_string().contains("backend failed"));
}
assert_eq!(reader.count(), 1);
assert_eq!(observation.loaded.load(Ordering::Relaxed), 0);
// The failed load was not cached.
let healthy = Reader::default();
assert!(cache.fetch(1, 16, ranges, &healthy).await.is_ok());
assert_eq!(healthy.count(), 1);
}
#[tokio::test]
async fn test_completed_page_rejects_conflicting_file_size() {
let (cache, _) = cache();
let reader = Reader::default();
let range = 0..4;
let ranges = std::slice::from_ref(&range);
cache.fetch(1, 16, ranges, &reader).await.unwrap();
assert!(cache.fetch(1, 12, ranges, &reader).await.is_err());
assert_eq!(reader.count(), 1);
// A different identity remains independent.
assert!(cache.fetch(2, 12, ranges, &reader).await.is_ok());
}
#[tokio::test]
async fn test_shared_load_rejects_conflicting_file_size() {
let (cache, _) = cache();
let reader = Reader::gated();
let range = 0..4;
let ranges = std::slice::from_ref(&range);
let mut owner = Box::pin(cache.fetch(1, 16, ranges, &reader));
start_read(owner.as_mut(), &reader, 1).await;
let mut conflicting = Box::pin(cache.fetch(1, 12, ranges, &reader));
assert!(futures::poll!(&mut conflicting).is_pending());
reader.release();
let (owner, conflicting) = tokio::time::timeout(Duration::from_secs(5), async {
tokio::join!(owner, conflicting)
})
.await
.unwrap();
assert!(owner.is_ok());
assert!(conflicting.is_err());
assert_eq!(reader.count(), 1);
}
#[tokio::test]
async fn test_empty_and_invalid_requests_do_not_issue_reads() {
let (cache, _) = cache();
let reader = Reader::default();
assert!(cache.fetch(1, 0, &[], &reader).await.unwrap().0.is_empty());
assert_eq!(
cache.fetch(1, 0, &[0..0, 0..0], &reader).await.unwrap().0,
vec![Bytes::new(), Bytes::new()]
);
for ranges in [vec![Range { start: 2, end: 1 }], vec![0..17, 0..0]] {
assert!(cache.fetch(1, 16, &ranges, &reader).await.is_err());
}
assert_eq!(reader.count(), 0);
}
// Keep the Send contract visible before a caller erases this future in async-trait.
fn send_fetch<'a, K, R>(
cache: &'a PagedCache<K>,
file: K,
ranges: &'a [Range<u64>],
reader: &'a R,
) -> impl Future<Output = Result<(Vec<Bytes>, PageFetchStats), Arc<io::Error>>> + Send + 'a
where
K: Hash + Eq + Clone + Send + Sync + 'static,
R: RangeReader + ?Sized,
{
cache.fetch(file, 16, ranges, reader)
}
#[tokio::test]
async fn test_generic_page_fetch_has_a_send_future() {
let (cache, _) = cache();
let reader = Reader::default();
let range = 1..7;
let ranges = std::slice::from_ref(&range);
let future: futures::future::BoxFuture<'_, _> =
Box::pin(send_fetch(&cache, 1, ranges, &reader));
let (bytes, _) = future.await.unwrap();
assert_eq!(bytes, vec![Bytes::from_static(&[1, 2, 3, 4, 5, 6])]);
}
#[tokio::test]
async fn test_direct_page_rejects_wrong_lengths_without_caching() {
struct FixedReader(usize);
#[async_trait]
impl RangeReader for FixedReader {
async fn metadata(&self) -> io::Result<Metadata> {
unreachable!("fetch already has the immutable file size")
}
async fn read(&self, _: Range<u64>) -> io::Result<Bytes> {
Ok(Bytes::from(vec![7; self.0]))
}
}
for response_size in [3, 5] {
let (cache, observation) = cache();
let range = 0..4;
let ranges = std::slice::from_ref(&range);
let error = cache
.fetch(1, 8, ranges, &FixedReader(response_size))
.await
.unwrap_err();
assert_eq!(error.kind(), io::ErrorKind::UnexpectedEof);
assert_eq!(observation.loaded.load(Ordering::Relaxed), 0);
assert!(!cache.contains(&1, 0).await);
let reader = Reader::default();
assert!(cache.fetch(1, 8, ranges, &reader).await.is_ok());
assert_eq!(reader.count(), 1);
}
}
#[tokio::test]
async fn test_direct_page_detaches_shared_backing_buffer() {
struct SliceReader(Bytes);
#[async_trait]
impl RangeReader for SliceReader {
async fn metadata(&self) -> io::Result<Metadata> {
unreachable!("fetch already has the immutable file size")
}
async fn read(&self, range: Range<u64>) -> io::Result<Bytes> {
Ok(self.0.slice(range.start as usize..range.end as usize))
}
}
let (cache, observation) = cache();
let reader = SliceReader(Bytes::from(vec![7; 1024]));
let range = 0..4;
let (output, _) = cache
.fetch(1, 1024, std::slice::from_ref(&range), &reader)
.await
.unwrap();
assert_eq!(output[0].as_ref(), [7; 4]);
assert_ne!(output[0].as_ptr(), reader.0.as_ptr());
cache.run_pending_tasks().await;
assert_eq!(observation.bytes(), 4);
}
#[tokio::test]
async fn test_direct_page_larger_than_eight_mib_is_not_split() {
let (base, _) = cache();
let page_size = 9 * 1024 * 1024;
let cache = PagedCache::new(
"large_pages",
page_size * 2,
page_size,
|_: &(u64, u64), bytes: &Bytes| bytes.len() as u32,
base.observer.clone(),
);
let reader = Reader::default();
let range = 0..1;
let (output, _) = cache
.fetch(1, page_size, std::slice::from_ref(&range), &reader)
.await
.unwrap();
assert_eq!(output[0].as_ref(), [0]);
assert_eq!(
reader.reads.lock().unwrap().as_slice(),
std::slice::from_ref(&(0..page_size))
);
}
#[test]
fn test_unique_requested_bytes() {
for (ranges, expected) in [
(vec![], 0),
(vec![4..4, 0..0], 0),
(vec![8..12, 2..6, 4..10, 2..6], 10),
(vec![0..4, 4..8, 12..16], 12),
(vec![0..u64::MAX, 1..2], u64::MAX),
] {
assert_eq!(unique_requested_bytes(&ranges), expected);
}
}
#[tokio::test]
async fn test_missing_pages_use_batch_reads() {
let (cache, _) = cache();
let reader = Reader::default();
let range = 0..512;
let ranges = std::slice::from_ref(&range);
let (bytes, _) = cache.fetch(1, 512, ranges, &reader).await.unwrap();
assert_eq!(
bytes[0],
Bytes::from((0..512).map(|n| n as u8).collect::<Vec<_>>())
);
assert_eq!(
*reader.batches.lock().unwrap(),
vec![(0..128).map(|n| n * 4..n * 4 + 4).collect::<Vec<_>>()]
);
cache.fetch(1, 512, ranges, &reader).await.unwrap();
assert_eq!(reader.batches.lock().unwrap().len(), 1);
}
#[tokio::test]
async fn test_shared_error_cancels_other_pending_batch() {
let (cache, _) = cache();
let failed = Reader {
error: Some(io::ErrorKind::BrokenPipe),
..Reader::gated()
};
let blocked = Reader::gated();
let owner_range = 0..4;
let waiter_range = 0..8;
let mut owner = Box::pin(cache.fetch(1, 16, std::slice::from_ref(&owner_range), &failed));
start_read(owner.as_mut(), &failed, 1).await;
let mut waiter = Box::pin(cache.fetch(1, 16, std::slice::from_ref(&waiter_range), &blocked));
start_read(waiter.as_mut(), &blocked, 1).await;
failed.release();
assert_eq!(owner.await.unwrap_err().kind(), io::ErrorKind::BrokenPipe);
// The unrelated page stays blocked; the shared error must cancel its I/O.
let error = tokio::time::timeout(Duration::from_secs(5), waiter)
.await
.unwrap()
.unwrap_err();
assert_eq!(error.kind(), io::ErrorKind::BrokenPipe);
let healthy = Reader::default();
assert!(
cache
.fetch(1, 16, std::slice::from_ref(&waiter_range), &healthy)
.await
.is_ok()
);
}
+15 -1
View File
@@ -354,7 +354,11 @@ mod tests {
builder.primary_key_encoding(encoding);
for (id, name, ty) in columns {
builder.push_column_metadata(ColumnMetadata {
column_schema: ColumnSchema::new((*name).to_string(), ty.clone(), true),
column_schema: ColumnSchema::new(
(*name).to_string(),
ty.clone(),
!ReservedColumnId::is_reserved(*id),
),
semantic_type: SemanticType::Tag,
column_id: *id,
});
@@ -440,6 +444,16 @@ mod tests {
#[test]
fn test_decode_sparse_primary_key() {
let columns = vec![
(
ReservedColumnId::table_id(),
"__table_id",
ConcreteDataType::uint32_datatype(),
),
(
ReservedColumnId::tsid(),
"__tsid",
ConcreteDataType::uint64_datatype(),
),
(10, "k0", ConcreteDataType::string_datatype()),
(11, "k1", ConcreteDataType::string_datatype()),
];
-4
View File
@@ -7,9 +7,6 @@ license.workspace = true
[lints]
workspace = true
[features]
enterprise = []
[dependencies]
api.workspace = true
arrow-flight.workspace = true
@@ -35,7 +32,6 @@ tokio.workspace = true
tokio-util.workspace = true
tonic.workspace = true
tower.workspace = true
uuid.workspace = true
vec1 = "1.12"
[dev-dependencies]
-477
View File
@@ -1,477 +0,0 @@
// 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::HashMap;
use std::sync::{Arc, Mutex};
use common_error::ext::{ErrorExt, StackError};
use common_error::status_code::StatusCode;
use common_recordbatch::{RecordBatch, RecordBatches};
use datatypes::arrow::array::{Array, StringArray};
use datatypes::prelude::{ConcreteDataType, VectorRef};
use datatypes::schema::{ColumnSchema, Schema};
use datatypes::vectors::StringVector;
use serde::{Deserialize, Serialize};
use tokio::sync::watch;
use uuid::Uuid;
pub const COMMAND_KEY: &str = "flow_write_command";
pub const CHILD_KEY: &str = "flow_write_child";
/// The control command carried by a Flow write request.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum Command {
Open { nonce: String },
Write { capability: String },
Close { capability: String },
}
impl Command {
/// Serializes this command as JSON.
pub fn encode(&self) -> serde_json::Result<String> {
serde_json::to_string(self)
}
/// Parses a serialized command.
pub fn decode(value: &str) -> serde_json::Result<Self> {
serde_json::from_str(value)
}
}
/// A safe terminal application error.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct TerminalError {
pub code: u32,
pub message: String,
}
impl std::fmt::Display for TerminalError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.message)
}
}
impl std::error::Error for TerminalError {}
impl StackError for TerminalError {
fn debug_fmt(&self, layer: usize, buf: &mut Vec<String>) {
buf.push(format!("{layer}: {self:?}"));
}
fn next(&self) -> Option<&dyn StackError> {
None
}
}
impl ErrorExt for TerminalError {
fn status_code(&self) -> StatusCode {
StatusCode::from_u32(self.code).unwrap_or(StatusCode::Internal)
}
fn as_any(&self) -> &dyn std::any::Any {
self
}
}
/// A finite response for a tracked Flow write.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum Reply {
Opened {
capability: String,
},
Closed,
Complete {
rows: usize,
cost: usize,
metrics: Option<common_recordbatch::adapter::RecordBatchMetrics>,
error: Option<TerminalError>,
},
}
fn envelope_schema() -> Arc<Schema> {
Arc::new(Schema::new(vec![ColumnSchema::new(
"envelope",
ConcreteDataType::string_datatype(),
false,
)]))
}
fn response_error(reason: impl Into<String>) -> common_recordbatch::error::Error {
common_recordbatch::error::Error::CreateRecordBatches {
reason: reason.into(),
location: snafu::Location::new(file!(), line!(), column!()),
}
}
/// Encodes a reply in the finite one-string-column record-batch envelope.
pub fn reply_batches(reply: &Reply) -> common_recordbatch::error::Result<RecordBatches> {
let value = serde_json::to_string(reply).map_err(|e| response_error(e.to_string()))?;
let batch = RecordBatch::new(
envelope_schema(),
vec![Arc::new(StringVector::from(vec![value])) as VectorRef],
)?;
RecordBatches::try_new(batch.schema.clone(), vec![batch])
}
/// Decodes a reply from its finite one-string-column record-batch envelope.
pub fn decode_reply(batches: &RecordBatches) -> common_recordbatch::error::Result<Reply> {
let batch = batches
.iter()
.next()
.ok_or_else(|| response_error("missing reply batch"))?;
if batches.iter().count() != 1 || batch.num_columns() != 1 || batch.num_rows() != 1 {
return Err(response_error("reply must be exactly one string value"));
}
let values = batch.columns()[0]
.as_any()
.downcast_ref::<StringArray>()
.ok_or_else(|| response_error("reply value is not a string"))?;
if values.is_null(0) {
return Err(response_error("reply value is null"));
}
let value = values.value(0);
serde_json::from_str(value).map_err(|e| response_error(e.to_string()))
}
/// Errors that reject admission or indicate that an admitted writer was lost.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum RegistryError {
UnknownCapability,
Closing,
WriterLost,
PayloadMismatch,
}
impl std::fmt::Display for RegistryError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{self:?}")
}
}
impl std::error::Error for RegistryError {}
impl StackError for RegistryError {
fn debug_fmt(&self, layer: usize, buf: &mut Vec<String>) {
buf.push(format!("{layer}: {self:?}"));
}
fn next(&self) -> Option<&dyn StackError> {
None
}
}
impl ErrorExt for RegistryError {
fn status_code(&self) -> StatusCode {
StatusCode::InvalidArguments
}
fn as_any(&self) -> &dyn std::any::Any {
self
}
}
/// Result of atomically admitting or joining a payload.
#[derive(Debug)]
pub enum Admission<R> {
Start(watch::Sender<Option<Arc<R>>>),
Join(watch::Receiver<Option<Arc<R>>>),
}
#[derive(Debug)]
struct Entry<P, R> {
payload: Option<P>,
sender: Option<watch::Sender<Option<Arc<R>>>>,
receiver: watch::Receiver<Option<Arc<R>>>,
closing: bool,
}
#[derive(Debug)]
struct State<P, R> {
openers: HashMap<String, String>,
entries: HashMap<String, Entry<P, R>>,
}
/// Receiver-issued capabilities for single-write admission and completion sharing.
#[derive(Debug)]
pub struct FlowWriteRegistry<P, R> {
state: Mutex<State<P, R>>,
}
impl<P, R> Default for FlowWriteRegistry<P, R> {
fn default() -> Self {
Self {
state: Mutex::new(State {
openers: HashMap::new(),
entries: HashMap::new(),
}),
}
}
}
impl<P: PartialEq, R: Send + Sync + 'static> FlowWriteRegistry<P, R> {
/// Returns the active capability for this opener nonce, creating one if needed.
pub fn open(&self, nonce: &str) -> Result<String, RegistryError> {
let mut state = self
.state
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
if let Some(capability) = state.openers.get(nonce) {
if state
.entries
.get(capability)
.is_some_and(|entry| entry.closing)
{
return Err(RegistryError::Closing);
}
return Ok(capability.clone());
}
let capability = Uuid::new_v4().to_string();
let (sender, receiver) = watch::channel(None);
state.openers.insert(nonce.to_string(), capability.clone());
state.entries.insert(
capability.clone(),
Entry {
payload: None,
sender: Some(sender),
receiver,
closing: false,
},
);
Ok(capability)
}
/// Atomically starts one payload or joins its identical in-flight completion.
pub fn admit(&self, capability: &str, payload: P) -> Result<Admission<R>, RegistryError> {
let mut state = self
.state
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
let entry = state
.entries
.get_mut(capability)
.ok_or(RegistryError::UnknownCapability)?;
if entry.closing {
return Err(RegistryError::Closing);
}
match &entry.payload {
Some(existing) if existing != &payload => Err(RegistryError::PayloadMismatch),
Some(_) => Ok(Admission::Join(entry.receiver.clone())),
None => {
entry.payload = Some(payload);
let sender = entry.sender.take().ok_or(RegistryError::Closing)?;
Ok(Admission::Start(sender))
}
}
}
/// Closes admission, drains an admitted writer, then deletes the capability.
pub async fn close(&self, capability: &str) -> Result<(), RegistryError> {
let receiver = {
let mut state = self
.state
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
let Some(entry) = state.entries.get_mut(capability) else {
return Ok(());
};
entry.closing = true;
if entry.payload.is_none() {
state.entries.remove(capability);
state.openers.retain(|_, value| value != capability);
return Ok(());
}
entry.receiver.clone()
};
wait_completion(receiver).await?;
let mut state = self
.state
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
state.entries.remove(capability);
state.openers.retain(|_, value| value != capability);
Ok(())
}
}
/// Waits for an admitted writer's positive terminal completion.
pub async fn wait_completion<R>(
mut receiver: watch::Receiver<Option<Arc<R>>>,
) -> Result<Arc<R>, RegistryError> {
loop {
if let Some(value) = receiver.borrow().clone() {
return Ok(value);
}
if receiver.changed().await.is_err() {
return Err(RegistryError::WriterLost);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::Barrier;
use std::thread;
#[tokio::test]
async fn concurrent_admission_has_one_owner_and_same_payload_joins() {
let registry = Arc::new(FlowWriteRegistry::<String, usize>::default());
let cap = registry.open("nonce").unwrap();
let barrier = Arc::new(Barrier::new(8));
let mut workers = Vec::new();
for _ in 0..8 {
let registry = registry.clone();
let cap = cap.clone();
let barrier = barrier.clone();
workers.push(thread::spawn(move || {
barrier.wait();
registry.admit(&cap, "payload".into()).unwrap()
}));
}
let admissions: Vec<_> = workers.into_iter().map(|w| w.join().unwrap()).collect();
assert_eq!(
admissions
.iter()
.filter(|a| matches!(a, Admission::Start(_)))
.count(),
1
);
let sender = admissions
.into_iter()
.find_map(|a| match a {
Admission::Start(s) => Some(s),
_ => None,
})
.unwrap();
sender.send(Some(Arc::new(7))).unwrap();
registry.close(&cap).await.unwrap();
}
#[tokio::test]
async fn close_drains_active_writer_and_deletes_old_capability() {
let registry = Arc::new(FlowWriteRegistry::<String, usize>::default());
let cap = registry.open("first").unwrap();
let Admission::Start(sender) = registry.admit(&cap, "payload".into()).unwrap() else {
panic!()
};
let close_registry = registry.clone();
let close_cap = cap.clone();
let close = tokio::spawn(async move { close_registry.close(&close_cap).await });
tokio::task::yield_now().await;
assert!(matches!(
registry.admit(&cap, "payload".into()),
Err(RegistryError::Closing)
));
assert!(!close.is_finished());
sender.send(Some(Arc::new(9))).unwrap();
close.await.unwrap().unwrap();
assert!(matches!(
registry.admit(&cap, "payload".into()),
Err(RegistryError::UnknownCapability)
));
registry.close(&cap).await.unwrap();
let new_cap = registry.open("first").unwrap();
assert_ne!(cap, new_cap);
assert!(matches!(
registry.admit(&cap, "late".into()),
Err(RegistryError::UnknownCapability)
));
assert!(matches!(
registry.admit(&new_cap, "new".into()).unwrap(),
Admission::Start(_)
));
}
#[tokio::test]
async fn writer_loss_is_not_completion() {
let registry = FlowWriteRegistry::<String, usize>::default();
let cap = registry.open("nonce").unwrap();
let Admission::Start(sender) = registry.admit(&cap, "payload".into()).unwrap() else {
panic!()
};
let Admission::Join(receiver) = registry.admit(&cap, "payload".into()).unwrap() else {
panic!()
};
drop(sender);
assert_eq!(
wait_completion(receiver).await.unwrap_err(),
RegistryError::WriterLost
);
assert_eq!(
registry.close(&cap).await.unwrap_err(),
RegistryError::WriterLost
);
}
#[test]
fn command_and_reply_envelope_round_trip_and_malformed_envelopes() {
let command = Command::Open { nonce: "n".into() };
assert_eq!(
Command::decode(&command.encode().unwrap()).unwrap(),
command
);
let reply = Reply::Complete {
rows: 2,
cost: 3,
metrics: Some(common_recordbatch::adapter::RecordBatchMetrics::default()),
error: Some(TerminalError {
code: 4,
message: "terminal".into(),
}),
};
let batches = reply_batches(&reply).unwrap();
let decoded = decode_reply(&batches).unwrap();
assert!(matches!(
decoded,
Reply::Complete {
rows: 2,
cost: 3,
error: Some(_),
..
}
));
let schema = envelope_schema();
let two_rows = RecordBatch::new(
schema.clone(),
vec![Arc::new(StringVector::from(vec!["a", "b"])) as VectorRef],
)
.unwrap();
assert!(
decode_reply(&RecordBatches::try_new(schema.clone(), vec![two_rows]).unwrap()).is_err()
);
let int_schema = Arc::new(Schema::new(vec![ColumnSchema::new(
"envelope",
ConcreteDataType::int32_datatype(),
false,
)]));
let non_string = RecordBatch::new(
int_schema.clone(),
vec![Arc::new(datatypes::vectors::Int32Vector::from(vec![Some(1)])) as VectorRef],
)
.unwrap();
assert!(
decode_reply(&RecordBatches::try_new(int_schema, vec![non_string]).unwrap()).is_err()
);
let invalid_json = RecordBatch::new(
envelope_schema(),
vec![Arc::new(StringVector::from(vec!["not json"])) as VectorRef],
)
.unwrap();
assert!(
decode_reply(
&RecordBatches::try_new(invalid_json.schema.clone(), vec![invalid_json]).unwrap()
)
.is_err()
);
}
}
-2
View File
@@ -15,8 +15,6 @@
pub mod channel_manager;
pub mod error;
pub mod flight;
#[cfg(feature = "enterprise")]
pub mod flow_write;
pub mod precision;
pub mod reloadable_tls;
pub mod select;
+1
View File
@@ -33,5 +33,6 @@ pub use crate::procedure::{
ContextProviderRef, EventContext, EventTrigger, LockKey, Output, ParseIdError, PoisonKey,
PoisonKeys, Procedure, ProcedureContext, ProcedureId, ProcedureInfo, ProcedureManager,
ProcedureManagerRef, ProcedureState, ProcedureWithId, RetryPhase, Status, StringKey,
SubprocedureRecovery,
};
pub use crate::watcher::Watcher;
+107 -72
View File
@@ -12,6 +12,7 @@
// See the License for the specific language governing permissions and
// limitations under the License.
mod recovery;
mod runner;
use std::collections::hash_map::Entry;
@@ -32,9 +33,9 @@ use tokio::sync::watch::{self, Receiver, Sender};
use tokio::sync::{Mutex as TokioMutex, Notify};
use crate::error::{
self, CheckStatusSnafu, DuplicateProcedureSnafu, Error, LoaderConflictSnafu,
ManagerNotStartSnafu, ManagerPasuedSnafu, PoisonKeyNotDefinedSnafu, ProcedureNotFoundSnafu,
Result, StartRemoveOutdatedMetaTaskSnafu, StopRemoveOutdatedMetaTaskSnafu,
CheckStatusSnafu, DuplicateProcedureSnafu, Error, LoaderConflictSnafu, ManagerNotStartSnafu,
ManagerPasuedSnafu, PoisonKeyNotDefinedSnafu, ProcedureNotFoundSnafu, Result,
StartRemoveOutdatedMetaTaskSnafu, StopRemoveOutdatedMetaTaskSnafu,
TooManyRunningProceduresSnafu,
};
use crate::local::runner::Runner;
@@ -44,7 +45,8 @@ use crate::store::poison_store::PoisonStoreRef;
use crate::store::{ProcedureMessage, ProcedureMessages, ProcedureStore, StateStoreRef};
use crate::{
BoxedProcedure, ContextProvider, EventTrigger, LockKey, PoisonKey, ProcedureContext,
ProcedureId, ProcedureManager, ProcedureState, ProcedureWithId, StringKey, Watcher,
ProcedureId, ProcedureManager, ProcedureState, ProcedureWithId, StringKey,
SubprocedureRecovery, Watcher,
};
/// The expired time of a procedure's metadata.
@@ -81,6 +83,8 @@ pub(crate) struct ProcedureMeta {
type_name: String,
/// Parent procedure id.
parent_id: Option<ProcedureId>,
/// Recovery policy captured when the procedure is submitted as a child.
subprocedure_recovery: SubprocedureRecovery,
/// Context associated with the root submission.
context: ProcedureContext,
/// Notify to wait for subprocedures.
@@ -116,6 +120,7 @@ impl ProcedureMeta {
ProcedureMeta {
id,
parent_id,
subprocedure_recovery: SubprocedureRecovery::Discard,
context,
child_notify: Notify::new(),
lock_key,
@@ -129,6 +134,12 @@ impl ProcedureMeta {
}
}
/// Sets the recovery policy for this subprocedure.
fn with_subprocedure_recovery(mut self, recovery: SubprocedureRecovery) -> Self {
self.subprocedure_recovery = recovery;
self
}
/// Returns current [ProcedureState].
fn state(&self) -> ProcedureState {
self.state_receiver.borrow().clone()
@@ -724,7 +735,6 @@ impl LocalManager {
origin: RootSubmissionOrigin,
) -> Result<Watcher> {
ensure!(self.manager_ctx.running(), ManagerNotStartSnafu);
let meta = Arc::new(ProcedureMeta::new(
procedure_id,
procedure_state,
@@ -735,6 +745,16 @@ impl LocalManager {
procedure.type_name(),
));
let event_recorder = self.event_recorder.0.lock().unwrap();
// Serialize admission and registration so concurrent fresh submissions cannot
// exceed the limit. Recovery resumes already accepted work and bypasses it.
if matches!(origin, RootSubmissionOrigin::Fresh) {
ensure!(
self.manager_ctx.num_running_procedures() < self.config.max_running_procedures,
TooManyRunningProceduresSnafu {
max_running_procedures: self.config.max_running_procedures,
}
);
}
let runner = Runner {
meta: meta.clone(),
procedure,
@@ -750,21 +770,13 @@ impl LocalManager {
rollback_retry_attempt: 0,
};
let watcher = meta.state_receiver.clone();
ensure!(
self.manager_ctx.num_running_procedures() < self.config.max_running_procedures,
TooManyRunningProceduresSnafu {
max_running_procedures: self.config.max_running_procedures,
}
);
// Inserts meta into the manager before actually spawnd the runner.
ensure!(
self.manager_ctx.try_insert_procedure(meta),
DuplicateProcedureSnafu { procedure_id },
);
let watcher = runner.meta.state_receiver.clone();
let initial_event = runner.build_event(origin.event_trigger());
let tracing_context = TracingContext::from_current_span();
@@ -773,7 +785,7 @@ impl LocalManager {
self.manager_ctx.spawn_runner_task(procedure_id, || {
common_runtime::spawn_global(async move {
let span = tracing_context.attach(tracing::info_span!(
"LocalManager::submit_root_procedure",
"LocalManager::submit_root_procedure",
procedure_name = %runner.meta.type_name,
procedure_id = %runner.meta.id,
));
@@ -798,60 +810,6 @@ impl LocalManager {
Ok(watcher)
}
fn submit_recovered_messages(
&self,
messages: HashMap<ProcedureId, ProcedureMessage>,
init_state: InitProcedureState,
) {
for (procedure_id, message) in &messages {
if message.parent_id.is_none() {
// This is the root procedure. We only submit the root procedure as it will
// submit sub-procedures to the manager.
let Some(mut loaded_procedure) = self
.manager_ctx
.load_one_procedure_from_message(*procedure_id, message)
else {
// Try to load other procedures.
continue;
};
info!(
"Recover root procedure {}-{}, step: {}",
loaded_procedure.procedure.type_name(),
procedure_id,
loaded_procedure.step
);
let procedure_state = match init_state {
InitProcedureState::RollingBack => ProcedureState::RollingBack {
error: Arc::new(
error::RollbackProcedureRecoveredSnafu {
error: message.error.clone().unwrap_or("Unknown error".to_string()),
}
.build(),
),
},
InitProcedureState::Running => ProcedureState::Running,
};
if let Err(e) = loaded_procedure.procedure.recover() {
error!(e; "Failed to recover procedure {}", procedure_id);
}
if let Err(e) = self.submit_root(
*procedure_id,
procedure_state,
loaded_procedure.step,
loaded_procedure.procedure,
message.context.clone(),
RootSubmissionOrigin::Recovery,
) {
error!(e; "Failed to recover procedure {}", procedure_id);
}
}
}
}
/// Recovers unfinished procedures and reruns them.
async fn recover(&self) -> Result<()> {
info!("LocalManager start to recover");
@@ -862,9 +820,13 @@ impl LocalManager {
rollback_messages,
finished_ids,
} = self.procedure_store.load_messages().await?;
// Submits recovered messages first.
self.submit_recovered_messages(rollback_messages, InitProcedureState::RollingBack);
self.submit_recovered_messages(messages, InitProcedureState::Running);
let rollback_messages = rollback_messages
.into_iter()
.map(|(id, message)| (id, message, InitProcedureState::RollingBack));
let messages = messages
.into_iter()
.map(|(id, message)| (id, message, InitProcedureState::Running));
self.submit_recovered_messages(rollback_messages.chain(messages));
if !finished_ids.is_empty() {
info!(
@@ -2352,6 +2314,79 @@ mod tests {
);
}
#[tokio::test]
async fn test_concurrent_root_submission_respects_limit() {
struct ConcurrentProcedure(Arc<std::sync::Barrier>);
#[async_trait::async_trait]
impl Procedure for ConcurrentProcedure {
fn type_name(&self) -> &str {
"ConcurrentProcedure"
}
async fn execute(&mut self, _ctx: &Context) -> Result<Status> {
std::future::pending().await
}
fn dump(&self) -> Result<String> {
Ok(String::new())
}
fn lock_key(&self) -> LockKey {
// Both submissions reach metadata construction before either registers.
self.0.wait();
LockKey::default()
}
}
let dir = create_temp_dir("concurrent_root_submission");
let state_store = Arc::new(ObjectStateStore::new(test_util::new_object_store(&dir)));
let manager = LocalManager::new(
ManagerConfig {
max_running_procedures: 1,
..Default::default()
},
state_store,
Arc::new(InMemoryPoisonStore::new()),
None,
None,
);
manager.manager_ctx.start();
let barrier = Arc::new(std::sync::Barrier::new(2));
let results = std::thread::scope(|scope| {
let handles: Vec<_> = (0..2)
.map(|_| {
let barrier = barrier.clone();
let manager = &manager;
scope.spawn(move || {
manager.submit_root(
ProcedureId::random(),
ProcedureState::Running,
0,
Box::new(ConcurrentProcedure(barrier)),
ProcedureContext::default(),
RootSubmissionOrigin::Fresh,
)
})
})
.collect();
handles
.into_iter()
.map(|h| h.join().unwrap())
.collect::<Vec<_>>()
});
manager.stop().await.unwrap();
assert_eq!(1, results.iter().filter(|result| result.is_ok()).count());
assert_eq!(
1,
results
.iter()
.filter(|result| matches!(result, Err(Error::TooManyRunningProcedures { .. })))
.count()
);
}
#[tokio::test]
async fn test_too_many_running_procedures() {
let dir = create_temp_dir("too_many_running_procedures");
+582
View File
@@ -0,0 +1,582 @@
// 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_telemetry::{error, info};
use crate::error;
use crate::local::{LocalManager, RootSubmissionOrigin};
use crate::procedure::InitProcedureState;
use crate::store::ProcedureMessage;
use crate::{ProcedureId, ProcedureState, ProcedureWithId};
/// A loaded procedure ready to resume from its checkpoint.
struct RecoveredProcedure {
procedure: ProcedureWithId,
state: ProcedureState,
step: u32,
}
impl LocalManager {
/// Loads all eligible procedures before starting any recovered runner.
pub(crate) fn submit_recovered_messages(
&self,
messages: impl IntoIterator<Item = (ProcedureId, ProcedureMessage, InitProcedureState)>,
) {
// Load both rollback and execution checkpoints before spawning. Loaders
// rebuild trackers that parents consult before submitting new work.
let procedures: Vec<_> = messages
.into_iter()
.filter_map(|(id, message, state)| self.load_recovered_procedure(id, message, state))
.collect();
for RecoveredProcedure {
procedure,
state,
step,
} in procedures
{
let procedure_id = procedure.id;
// Detached children use the existing root lifecycle and cleanup.
if let Err(e) = self.submit_root(
procedure_id,
state,
step,
procedure.procedure,
procedure.context,
RootSubmissionOrigin::Recovery,
) {
error!(e; "Failed to recover procedure {}", procedure_id);
}
}
}
fn load_recovered_procedure(
&self,
procedure_id: ProcedureId,
message: ProcedureMessage,
init_state: InitProcedureState,
) -> Option<RecoveredProcedure> {
if message.parent_id.is_some() && message.subprocedure_recovery.is_discard() {
return None;
}
// The loader logs failures; skip them without adding a duplicate error.
let mut loaded = self
.manager_ctx
.load_one_procedure_from_message(procedure_id, &message)?;
match message.parent_id {
Some(parent_id) => info!(
"Recover detached subprocedure {}-{}, former parent: {}, step: {}",
loaded.procedure.type_name(),
procedure_id,
parent_id,
loaded.step
),
None => info!(
"Recover root procedure {}-{}, step: {}",
loaded.procedure.type_name(),
procedure_id,
loaded.step
),
}
let state = match init_state {
InitProcedureState::Running => ProcedureState::Running,
InitProcedureState::RollingBack => ProcedureState::RollingBack {
error: Arc::new(
error::RollbackProcedureRecoveredSnafu {
error: message.error.unwrap_or_else(|| "Unknown error".to_string()),
}
.build(),
),
},
};
if let Err(e) = loaded.procedure.recover() {
error!(e; "Failed to recover procedure {}", procedure_id);
}
Some(RecoveredProcedure {
procedure: ProcedureWithId {
id: procedure_id,
procedure: loaded.procedure,
context: message.context,
},
state,
step: loaded.step,
})
}
}
#[cfg(test)]
mod tests {
use std::sync::atomic::{AtomicUsize, Ordering};
use std::time::Duration;
use async_trait::async_trait;
use common_test_util::temp_dir::create_temp_dir;
use tokio::sync::Notify;
use tokio::time::timeout;
use super::*;
use crate::error::Result;
use crate::local::{ManagerConfig, test_util};
use crate::store::state_store::ObjectStateStore;
use crate::test_util::InMemoryPoisonStore;
use crate::{
Context, LockKey, Procedure, ProcedureContext, ProcedureManager, Status,
SubprocedureRecovery,
};
struct MockParentProcedure {
child: Option<ProcedureWithId>,
recovery: SubprocedureRecovery,
}
#[async_trait]
impl Procedure for MockParentProcedure {
fn type_name(&self) -> &str {
"MockParentProcedure"
}
async fn execute(&mut self, _: &Context) -> Result<Status> {
let Some(child) = self.child.take() else {
return Ok(Status::done());
};
Ok(match self.recovery {
SubprocedureRecovery::Discard => Status::suspended(vec![child], false),
SubprocedureRecovery::Detach => Status::Suspended {
subprocedures: vec![child],
persist: false,
recovery: SubprocedureRecovery::Detach,
},
})
}
fn dump(&self) -> Result<String> {
unreachable!("The fixture deliberately does not checkpoint the parent")
}
fn lock_key(&self) -> LockKey {
LockKey::default()
}
}
#[derive(Clone)]
struct MockChildProcedure {
checkpointed: bool,
init_state: InitProcedureState,
entered: Arc<Notify>,
release: Arc<Notify>,
recoveries: Arc<AtomicUsize>,
rollbacks: Arc<AtomicUsize>,
}
#[async_trait]
impl Procedure for MockChildProcedure {
fn type_name(&self) -> &str {
"MockChildProcedure"
}
async fn execute(&mut self, _: &Context) -> Result<Status> {
if matches!(self.init_state, InitProcedureState::RollingBack) {
return error::UnexpectedSnafu {
err_msg: "Child needs rollback",
}
.fail();
}
if !self.checkpointed {
self.checkpointed = true;
return Ok(Status::executing(true));
}
self.entered.notify_one();
self.release.notified().await;
Ok(Status::done())
}
fn recover(&mut self) -> Result<()> {
self.recoveries.fetch_add(1, Ordering::Relaxed);
// The next execution checkpoint must persist the detached root identity.
self.checkpointed = false;
Ok(())
}
fn dump(&self) -> Result<String> {
Ok(self.checkpointed.to_string())
}
fn lock_key(&self) -> LockKey {
LockKey::default()
}
fn rollback_supported(&self) -> bool {
true
}
async fn rollback(&mut self, _: &Context) -> Result<()> {
self.rollbacks.fetch_add(1, Ordering::Relaxed);
self.entered.notify_one();
self.release.notified().await;
Ok(())
}
}
#[tokio::test]
async fn test_detach_child_after_restart() {
check_child_recovery(SubprocedureRecovery::Detach, InitProcedureState::Running).await;
}
#[tokio::test]
async fn test_detach_rollback_child_after_restart() {
check_child_recovery(
SubprocedureRecovery::Detach,
InitProcedureState::RollingBack,
)
.await;
}
#[tokio::test]
async fn test_discard_child_after_restart() {
check_child_recovery(SubprocedureRecovery::Discard, InitProcedureState::Running).await;
}
#[tokio::test]
async fn test_discard_rollback_child_after_restart() {
check_child_recovery(
SubprocedureRecovery::Discard,
InitProcedureState::RollingBack,
)
.await;
}
#[tokio::test]
async fn test_load_all_procedures_before_spawning() {
// Cover both checkpoint kinds and both cross-kind parent/child orderings.
for (parent_rollback, child_rollback) in
[(false, false), (false, true), (true, false), (true, true)]
{
let dir = create_temp_dir("load-before-spawn");
let manager = LocalManager::new(
ManagerConfig::default(),
Arc::new(ObjectStateStore::new(test_util::new_object_store(&dir))),
Arc::new(InMemoryPoisonStore::new()),
None,
None,
);
let manager_ctx = manager.manager_ctx.clone();
let loads = Arc::new(AtomicUsize::new(0));
let recoveries = Arc::new(AtomicUsize::new(0));
let loaded_count = loads.clone();
let recovered_count = recoveries.clone();
manager
.register_loader(
"MockChildProcedure",
Box::new(move |data| {
// A loader must never observe an already spawned parent.
// This check is deterministic even if its runner has not run yet.
assert!(manager_ctx.runner_tasks.lock().unwrap().is_empty());
loaded_count.fetch_add(1, Ordering::Relaxed);
Ok(Box::new(MockChildProcedure {
checkpointed: data.parse().unwrap(),
init_state: InitProcedureState::Running,
entered: Arc::new(Notify::new()),
release: Arc::new(Notify::new()),
recoveries: recovered_count.clone(),
rollbacks: Arc::new(AtomicUsize::new(0)),
}))
}),
)
.unwrap();
let parent_id = ProcedureId::random();
let child_id = ProcedureId::random();
for (id, parent, rollback) in [
(parent_id, None, parent_rollback),
(child_id, Some(parent_id), child_rollback),
] {
let message = ProcedureMessage {
type_name: "MockChildProcedure".to_string(),
data: "true".to_string(),
parent_id: parent,
subprocedure_recovery: SubprocedureRecovery::Detach,
step: 7,
error: rollback.then(|| "Needs rollback".to_string()),
context: ProcedureContext::default(),
};
if rollback {
manager
.procedure_store
.rollback_procedure(id, message)
.await
.unwrap();
} else {
manager
.procedure_store
.store_procedure_message(id, &message)
.await
.unwrap();
}
}
manager.start().await.unwrap();
assert_eq!(loads.load(Ordering::Relaxed), 2);
assert_eq!(recoveries.load(Ordering::Relaxed), 2);
assert_eq!(manager.manager_ctx.runner_tasks.lock().unwrap().len(), 2);
manager.stop().await.unwrap();
}
}
#[tokio::test]
async fn test_recover_roots_and_detached_children_over_limit() {
let dir = create_temp_dir("detached-recovery-limit");
let manager = LocalManager::new(
ManagerConfig {
max_running_procedures: 1,
..Default::default()
},
Arc::new(ObjectStateStore::new(test_util::new_object_store(&dir))),
Arc::new(InMemoryPoisonStore::new()),
None,
None,
);
manager
.register_loader(
"MockChildProcedure",
Box::new(|data| {
Ok(Box::new(MockChildProcedure {
checkpointed: data.parse().unwrap(),
init_state: InitProcedureState::Running,
entered: Arc::new(Notify::new()),
release: Arc::new(Notify::new()),
recoveries: Arc::new(AtomicUsize::new(0)),
rollbacks: Arc::new(AtomicUsize::new(0)),
}))
}),
)
.unwrap();
let root_id = ProcedureId::random();
let child_ids = [ProcedureId::random(), ProcedureId::random()];
let root = ProcedureMessage {
type_name: "MockChildProcedure".to_string(),
data: "true".to_string(),
parent_id: None,
subprocedure_recovery: SubprocedureRecovery::Discard,
step: 7,
error: None,
context: ProcedureContext::default(),
};
manager
.procedure_store
.store_procedure_message(root_id, &root)
.await
.unwrap();
for child_id in child_ids {
let child = ProcedureMessage {
parent_id: Some(root_id),
subprocedure_recovery: SubprocedureRecovery::Detach,
..root.clone()
};
manager
.procedure_store
.store_procedure_message(child_id, &child)
.await
.unwrap();
}
manager.start().await.unwrap();
{
let procedures = manager.manager_ctx.procedures.read().unwrap();
assert_eq!(procedures.len(), 3);
for id in [root_id, child_ids[0], child_ids[1]] {
let meta = &procedures[&id];
assert_eq!(meta.parent_id, None);
assert_eq!(meta.num_children(), 0);
}
}
// Wait for detached children to checkpoint as roots, then verify that
// recovery retained their nonzero step rather than restarting from zero.
timeout(Duration::from_secs(5), async {
loop {
let stored = manager.procedure_store.load_messages().await.unwrap();
if child_ids.iter().all(|id| {
stored
.messages
.get(id)
.is_some_and(|message| message.parent_id.is_none())
}) {
for child_id in child_ids {
assert_eq!(stored.messages[&child_id].step, 7);
}
break;
}
tokio::task::yield_now().await;
}
})
.await
.unwrap();
manager.stop().await.unwrap();
}
async fn check_child_recovery(policy: SubprocedureRecovery, init_state: InitProcedureState) {
let dir = create_temp_dir("child-recovery");
let state_store = Arc::new(ObjectStateStore::new(test_util::new_object_store(&dir)));
let manager = LocalManager::new(
ManagerConfig {
max_running_procedures: 1,
..Default::default()
},
state_store,
Arc::new(InMemoryPoisonStore::new()),
None,
None,
);
let child_id = ProcedureId::random();
let entered = Arc::new(Notify::new());
let release = Arc::new(Notify::new());
let recoveries = Arc::new(AtomicUsize::new(0));
let rollbacks = Arc::new(AtomicUsize::new(0));
let child = MockChildProcedure {
checkpointed: false,
init_state: init_state.clone(),
entered: entered.clone(),
release: release.clone(),
recoveries: recoveries.clone(),
rollbacks: rollbacks.clone(),
};
let loaded_child = child.clone();
manager
.register_loader(
"MockChildProcedure",
Box::new(move |data| {
assert_eq!(
policy,
SubprocedureRecovery::Detach,
"Discarded children must not be loaded"
);
let mut child = loaded_child.clone();
child.checkpointed = data.parse().unwrap();
Ok(Box::new(child))
}),
)
.unwrap();
manager.start().await.unwrap();
let parent = ProcedureWithId::with_random_id(Box::new(MockParentProcedure {
child: Some(ProcedureWithId {
id: child_id,
procedure: Box::new(child),
context: ProcedureContext::default(),
}),
recovery: policy,
}))
.with_context(ProcedureContext {
actor: Some("alice".to_string()),
..Default::default()
});
let parent_id = parent.id;
manager.submit(parent).await.unwrap();
timeout(Duration::from_secs(5), entered.notified())
.await
.unwrap();
// The first child checkpoint carries the submission policy, even though
// Status::Suspended.persist was false and the parent has no checkpoint.
let stored = manager.procedure_store.load_messages().await.unwrap();
let checkpoint = match init_state {
InitProcedureState::Running => &stored.messages[&child_id],
InitProcedureState::RollingBack => &stored.rollback_messages[&child_id],
}
.clone();
assert_eq!(checkpoint.parent_id, Some(parent_id));
assert_eq!(checkpoint.subprocedure_recovery, policy);
assert_eq!(checkpoint.context.actor.as_deref(), Some("alice"));
assert_eq!(checkpoint.step, 0);
if matches!(init_state, InitProcedureState::RollingBack) {
assert!(!stored.messages.contains_key(&child_id));
assert_eq!(checkpoint.data, "false");
}
assert!(!stored.messages.contains_key(&parent_id));
manager.stop().await.unwrap();
manager.start().await.unwrap();
if policy == SubprocedureRecovery::Discard {
assert!(manager.procedure_state(child_id).await.unwrap().is_none());
assert_eq!(recoveries.load(Ordering::Relaxed), 0);
let stored = manager.procedure_store.load_messages().await.unwrap();
let retained = match init_state {
InitProcedureState::Running => &stored.messages[&child_id],
InitProcedureState::RollingBack => &stored.rollback_messages[&child_id],
};
assert_eq!(retained, &checkpoint);
manager.stop().await.unwrap();
return;
}
// The original parent is absent. The child owns its cleanup as a root,
// and remains recoverable across a second restart.
for restart in 1..=2 {
timeout(Duration::from_secs(5), entered.notified())
.await
.unwrap();
assert!(manager.procedure_state(parent_id).await.unwrap().is_none());
let meta = manager.manager_ctx.procedures.read().unwrap()[&child_id].clone();
assert_eq!(meta.parent_id, None);
assert_eq!(meta.context, checkpoint.context);
assert_eq!(recoveries.load(Ordering::Relaxed), restart);
let stored = manager.procedure_store.load_messages().await.unwrap();
match init_state {
InitProcedureState::Running => {
let recovered = &stored.messages[&child_id];
assert_eq!(recovered.parent_id, None);
assert_eq!(recovered.step, checkpoint.step);
assert_eq!(recovered.context, checkpoint.context);
}
InitProcedureState::RollingBack => {
assert!(meta.state().is_rolling_back());
assert_eq!(stored.rollback_messages[&child_id], checkpoint);
}
}
if restart == 1 {
manager.stop().await.unwrap();
manager.start().await.unwrap();
}
}
release.notify_one();
timeout(Duration::from_secs(5), async {
while manager
.manager_ctx
.runner_tasks
.lock()
.unwrap()
.contains_key(&child_id)
{
tokio::task::yield_now().await;
}
})
.await
.unwrap();
let stored = manager.procedure_store.load_messages().await.unwrap();
assert!(stored.messages.is_empty());
assert!(stored.rollback_messages.is_empty());
assert!(stored.finished_ids.is_empty());
let state = manager.procedure_state(child_id).await.unwrap().unwrap();
match init_state {
InitProcedureState::Running => {
assert!(state.is_done());
assert_eq!(rollbacks.load(Ordering::Relaxed), 0);
}
InitProcedureState::RollingBack => {
assert!(state.is_failed());
assert_eq!(rollbacks.load(Ordering::Relaxed), 3);
}
}
manager.stop().await.unwrap();
}
}
+37 -12
View File
@@ -35,7 +35,7 @@ use crate::rwlock::OwnedKeyRwLockGuard;
use crate::store::{ProcedureMessage, ProcedureStore};
use crate::{
BoxedProcedure, ChildSubmissionOutcome, Context, Error, EventContext, EventTrigger, Procedure,
ProcedureId, ProcedureState, ProcedureWithId, RetryPhase, Status,
ProcedureId, ProcedureState, ProcedureWithId, RetryPhase, Status, SubprocedureRecovery,
};
/// A guard to cleanup procedure state.
@@ -390,7 +390,11 @@ impl Runner {
self.meta.set_state(ProcedureState::Running);
}
}
Status::Suspended { subprocedures, .. } => {
Status::Suspended {
subprocedures,
recovery,
..
} => {
let prev_state = self.meta.state();
if !matches!(prev_state, ProcedureState::Running) {
info!(
@@ -401,7 +405,7 @@ impl Runner {
);
self.meta.set_state(ProcedureState::Running);
}
self.on_suspended(subprocedures).await;
self.on_suspended(subprocedures, recovery).await;
}
Status::Done { output } => {
if let Err(e) = self.commit_procedure().await {
@@ -488,6 +492,7 @@ impl Runner {
procedure_id: ProcedureId,
procedure_state: ProcedureState,
procedure: BoxedProcedure,
recovery: SubprocedureRecovery,
) -> (ChildSubmissionOutcome, Option<ProcedureEvent>) {
if !self.running() {
warn!(
@@ -505,7 +510,7 @@ impl Runner {
let step = 0;
let meta = Arc::new(ProcedureMeta::new(
let meta = ProcedureMeta::new(
procedure_id,
procedure_state,
Some(self.meta.id),
@@ -513,7 +518,9 @@ impl Runner {
procedure.lock_key(),
procedure.poison_keys(),
procedure.type_name(),
));
)
.with_subprocedure_recovery(recovery);
let meta = Arc::new(meta);
let runner = Runner {
meta: meta.clone(),
procedure,
@@ -578,7 +585,11 @@ impl Runner {
time::sleep(d).await;
}
async fn on_suspended(&mut self, subprocedures: Vec<ProcedureWithId>) {
async fn on_suspended(
&mut self,
subprocedures: Vec<ProcedureWithId>,
recovery: SubprocedureRecovery,
) {
let has_child = !subprocedures.is_empty();
// Pre-check: detect potential deadlocks BEFORE submitting any subprocedure.
@@ -629,6 +640,7 @@ impl Runner {
subprocedure.id,
ProcedureState::Running,
subprocedure.procedure,
recovery,
);
if let Some(event) = submitted_event
&& let Some(recorder) = self.event_recorder.as_ref()
@@ -664,13 +676,17 @@ impl Runner {
let data = self.procedure.dump()?;
self.store
.store_procedure_with_context(
.store_procedure_message(
self.meta.id,
self.step,
type_name,
data,
self.meta.parent_id,
self.meta.context.clone(),
&ProcedureMessage {
type_name,
data,
parent_id: self.meta.parent_id,
subprocedure_recovery: self.meta.subprocedure_recovery,
step: self.step,
error: None,
context: self.meta.context.clone(),
},
)
.await
.map_err(|e| {
@@ -709,6 +725,7 @@ impl Runner {
type_name,
data,
parent_id: self.meta.parent_id,
subprocedure_recovery: self.meta.subprocedure_recovery,
step: self.step,
error: Some(error),
context: self.meta.context.clone(),
@@ -1061,6 +1078,7 @@ mod tests {
let exec_fn = move |_| {
async move {
Ok(Status::Suspended {
recovery: SubprocedureRecovery::Discard,
subprocedures: Vec::new(),
persist: false,
})
@@ -1138,6 +1156,7 @@ mod tests {
if times == 1 {
// Submit subprocedures.
Ok(Status::Suspended {
recovery: SubprocedureRecovery::Discard,
subprocedures: children_ids
.into_iter()
.zip(keys)
@@ -1165,6 +1184,7 @@ mod tests {
} else {
// Return suspended to wait for notify.
Ok(Status::Suspended {
recovery: SubprocedureRecovery::Discard,
subprocedures: Vec::new(),
persist: false,
})
@@ -1491,6 +1511,7 @@ mod tests {
};
Ok(Status::Suspended {
recovery: SubprocedureRecovery::Discard,
subprocedures: vec![ProcedureWithId {
id: child_id,
procedure: Box::new(fail),
@@ -1684,6 +1705,7 @@ mod tests {
};
Ok(Status::Suspended {
recovery: SubprocedureRecovery::Discard,
subprocedures: vec![ProcedureWithId {
id: child_id,
procedure: Box::new(fail),
@@ -1704,6 +1726,7 @@ mod tests {
} else {
// Return suspended to wait for notify.
Ok(Status::Suspended {
recovery: SubprocedureRecovery::Discard,
subprocedures: Vec::new(),
persist: false,
})
@@ -2205,6 +2228,7 @@ mod tests {
rollback_fn: None,
};
Ok(Status::Suspended {
recovery: SubprocedureRecovery::Discard,
subprocedures: vec![ProcedureWithId {
id: child_id,
procedure: Box::new(child),
@@ -2262,6 +2286,7 @@ mod tests {
rollback_fn: None,
};
Ok(Status::Suspended {
recovery: SubprocedureRecovery::Discard,
subprocedures: vec![ProcedureWithId {
id: child_id,
procedure: Box::new(child),
+33
View File
@@ -56,6 +56,33 @@ impl ProcedureContext {
}
}
/// Controls how children submitted by [`Status::Suspended`] are handled after a restart.
///
/// The policy is captured at submission and persisted with each child's checkpoints.
/// It does not change parent-child ownership during normal execution. A child without
/// a persisted checkpoint cannot be recovered, regardless of its policy.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
pub enum SubprocedureRecovery {
/// Does not recover the child. The parent decides whether to resubmit its work.
/// This does not roll back side effects or delete the child's persisted records.
#[default]
Discard,
/// Resumes the child's persisted execution or rollback as an independent root.
/// Its original id and context are retained, but its parent link is removed.
/// Completion no longer notifies the former parent.
/// All eligible procedures are loaded and their recovery hooks are called before
/// any recovered runner starts. Runner execution is not ordered relative to the
/// former parent; callers must prevent conflicting work when the parent recovers.
Detach,
}
impl SubprocedureRecovery {
/// Returns whether the child is excluded from recovery.
pub(crate) fn is_discard(&self) -> bool {
matches!(self, Self::Discard)
}
}
/// Procedure execution status.
#[derive(Debug)]
pub enum Status {
@@ -69,6 +96,8 @@ pub enum Status {
/// The procedure has suspended itself and is waiting for subprocedures.
Suspended {
subprocedures: Vec<ProcedureWithId>,
/// Recovery policy for every child in this submission, recorded at its first checkpoint.
recovery: SubprocedureRecovery,
/// Whether the framework needs to persist the procedure.
persist: bool,
},
@@ -85,9 +114,11 @@ pub enum Status {
impl Status {
/// Returns a [Status::Suspended] with given `subprocedures` and `persist` flag.
/// Children default to [`SubprocedureRecovery::Discard`].
pub fn suspended(subprocedures: Vec<ProcedureWithId>, persist: bool) -> Status {
Status::Suspended {
subprocedures,
recovery: SubprocedureRecovery::Discard,
persist,
}
}
@@ -785,12 +816,14 @@ mod tests {
assert!(status.need_clean_poisons());
let status = Status::Suspended {
recovery: SubprocedureRecovery::Discard,
subprocedures: Vec::new(),
persist: false,
};
assert!(!status.need_persist());
let status = Status::Suspended {
recovery: SubprocedureRecovery::Discard,
subprocedures: Vec::new(),
persist: true,
};
+33 -2
View File
@@ -22,7 +22,7 @@ use snafu::ResultExt;
use crate::error::{Result, ToJsonSnafu};
pub(crate) use crate::store::state_store::StateStoreRef;
use crate::{ProcedureContext, ProcedureId};
use crate::{ProcedureContext, ProcedureId, SubprocedureRecovery};
pub mod poison_store;
pub mod state_store;
@@ -50,6 +50,9 @@ pub struct ProcedureMessage {
pub data: String,
/// Parent procedure id.
pub parent_id: Option<ProcedureId>,
/// Recovery policy for a child submission, ignored for root procedures.
#[serde(default, skip_serializing_if = "SubprocedureRecovery::is_discard")]
pub subprocedure_recovery: SubprocedureRecovery,
/// Current step.
pub step: u32,
/// Errors raised during the procedure.
@@ -111,6 +114,7 @@ impl ProcedureStore {
.await
}
#[cfg(test)]
pub(crate) async fn store_procedure_with_context(
&self,
procedure_id: ProcedureId,
@@ -124,14 +128,24 @@ impl ProcedureStore {
type_name,
data,
parent_id,
subprocedure_recovery: SubprocedureRecovery::Discard,
step,
error: None,
context,
};
self.store_procedure_message(procedure_id, &message).await
}
/// Persists a procedure checkpoint with its recovery policy and submission context.
pub(crate) async fn store_procedure_message(
&self,
procedure_id: ProcedureId,
message: &ProcedureMessage,
) -> Result<()> {
let key = ParsedKey {
prefix: &self.proc_path,
procedure_id,
step,
step: message.step,
key_type: KeyType::Step,
}
.to_string();
@@ -486,6 +500,7 @@ mod tests {
type_name: "TestMessage".to_string(),
data: "no parent id".to_string(),
parent_id: None,
subprocedure_recovery: SubprocedureRecovery::Discard,
step: 4,
error: None,
context: ProcedureContext::default(),
@@ -529,6 +544,20 @@ mod tests {
assert_eq!(legacy.context, ProcedureContext::default());
}
#[test]
fn test_subprocedure_recovery_serialization() {
let legacy = r#"{"type_name":"TestMessage","data":"checkpoint","parent_id":null,"step":4}"#;
let mut message: ProcedureMessage = serde_json::from_str(legacy).unwrap();
assert_eq!(message.subprocedure_recovery, SubprocedureRecovery::Discard);
assert_eq!(serde_json::to_string(&message).unwrap(), legacy);
message.subprocedure_recovery = SubprocedureRecovery::Detach;
let json = serde_json::to_string(&message).unwrap();
assert_eq!(
serde_json::from_str::<ProcedureMessage>(&json).unwrap(),
message
);
}
struct MockProcedure {
data: String,
}
@@ -589,6 +618,7 @@ mod tests {
type_name: "MockProcedure".to_string(),
data: "test store procedure".to_string(),
parent_id: None,
subprocedure_recovery: SubprocedureRecovery::Discard,
step: 0,
error: None,
context: ProcedureContext::default(),
@@ -638,6 +668,7 @@ mod tests {
type_name,
data,
parent_id: None,
subprocedure_recovery: SubprocedureRecovery::Discard,
step: 1,
error: None,
context: ProcedureContext::default(),
+2 -1
View File
@@ -6,7 +6,7 @@ license.workspace = true
[features]
testing = []
enterprise = ["mito2/enterprise", "common-grpc/enterprise"]
enterprise = ["mito2/enterprise"]
[lints]
workspace = true
@@ -61,6 +61,7 @@ partition.workspace = true
prometheus.workspace = true
prost.workspace = true
query.workspace = true
rand.workspace = true
reqwest.workspace = true
serde.workspace = true
serde_json.workspace = true
+107 -22
View File
@@ -134,13 +134,18 @@ impl RegionAliveKeeper {
}
}
/// Renews the lease of regions to `deadline`.
async fn renew_region_leases(&self, regions: &[GrantedRegion], deadline: Instant) {
/// Renews the lease of regions to `deadline`, granted for a heartbeat sent at `sent_at`.
async fn renew_region_leases(
&self,
regions: &[GrantedRegion],
sent_at: Instant,
deadline: Instant,
) {
for region in regions {
let (role, region_id) = (region.role().into(), RegionId::from(region.region_id));
if let Some(handle) = self.find_handle(region_id).await {
handle
.reset_deadline(role, deadline, region.extensions.clone())
.reset_deadline(role, sent_at, deadline, region.extensions.clone())
.await;
} else {
warn!(
@@ -281,7 +286,7 @@ impl HeartbeatResponseHandler for RegionAliveKeeper {
if let Some(mito) = self.region_server.mito_engine() {
mito.renew_node_lease(deadline.into_std());
}
self.renew_region_leases(&region_lease.regions, deadline)
self.renew_region_leases(&region_lease.regions, start_instant, deadline)
.await;
self.close_staled_regions(&region_lease.closeable_region_ids)
.await;
@@ -296,8 +301,8 @@ enum CountdownCommand {
/// 4 * `heartbeat_interval_millis`
Start(u64),
/// Reset countdown deadline to the given instance.
/// (NextRole, Deadline, ExtensionInfo)
Reset((RegionRole, Instant, HashMap<String, Vec<u8>>)),
/// (NextRole, HeartbeatSentAt, Deadline, ExtensionInfo)
Reset((RegionRole, Instant, Instant, HashMap<String, Vec<u8>>)),
/// Returns the current deadline of the countdown task.
#[cfg(test)]
Deadline(oneshot::Sender<Instant>),
@@ -377,12 +382,18 @@ impl CountdownTaskHandle {
async fn reset_deadline(
&self,
role: RegionRole,
sent_at: Instant,
deadline: Instant,
extension_info: HashMap<String, Vec<u8>>,
) {
if let Err(e) = self
.tx
.send(CountdownCommand::Reset((role, deadline, extension_info)))
.send(CountdownCommand::Reset((
role,
sent_at,
deadline,
extension_info,
)))
.await
{
warn!(
@@ -436,20 +447,25 @@ impl CountdownTask {
started = true;
}
},
Some(CountdownCommand::Reset((role, deadline, extension_info))) => {
Some(CountdownCommand::Reset((role, sent_at, deadline, extension_info))) => {
let prev_role_leader = self.region_server.is_region_leader(self.region_id).unwrap_or(false);
if let Err(err) = self.region_server.set_region_role_with_lease(self.region_id, role, deadline.into_std()) {
if err.status_code() == StatusCode::RegionNotFound {
// Table metadata in metasrv is deleted after its regions are dropped.
// The datanode may still receive lease renewal responses that depend on the metadata
// during the short period before it is removed.
warn!(err; "Failed to set region role to {role} for region {region_id}");
} else {
error!(err; "Failed to set region role to {role} for region {region_id}");
let applied = match self.region_server.set_region_role_with_lease(self.region_id, role, sent_at.into_std(), deadline.into_std()) {
Ok(applied) => applied,
Err(err) => {
if err.status_code() == StatusCode::RegionNotFound {
// Table metadata in metasrv is deleted after its regions are dropped.
// The datanode may still receive lease renewal responses that depend on the metadata
// during the short period before it is removed.
warn!(err; "Failed to set region role to {role} for region {region_id}");
} else {
error!(err; "Failed to set region role to {role} for region {region_id}");
}
false
}
};
// Finalize leadership: persist backfilled metadata.
} else if !prev_role_leader && role == RegionRole::Leader
// Finalize leadership if the grant was applied: persist backfilled metadata.
if applied && !prev_role_leader && role == RegionRole::Leader
&& let Err(err) = self
.region_server
.set_region_role_state_gracefully(self.region_id, SettableRegionRoleState::Leader)
@@ -503,26 +519,42 @@ impl CountdownTask {
#[cfg(test)]
mod test {
use std::sync::atomic::AtomicUsize;
use api::v1::Rows;
use api::v1::meta::{HeartbeatResponse, RegionLease};
use common_meta::heartbeat::mailbox::HeartbeatMailbox;
use mito2::config::MitoConfig;
use mito2::engine::MITO_ENGINE_NAME;
use mito2::test_util::{CreateRequestBuilder, TestEnv, build_rows, rows_schema};
use store_api::region_engine::RegionEngine;
use store_api::region_engine::{
RegionEngine, SetRegionRoleStateResponse, SetRegionRoleStateSuccess,
};
use store_api::region_request::{
EnterStagingRequest, RegionPutRequest, StagingPartitionDirective,
};
use super::*;
use crate::tests::mock_region_server;
use crate::tests::{MockRegionEngine, mock_region_server};
/// Handles a heartbeat response that grants `regions` for a heartbeat sent now.
async fn handle_lease_response(alive_keeper: &RegionAliveKeeper, regions: Vec<GrantedRegion>) {
let sent_at = alive_keeper.epoch().elapsed();
handle_lease_response_sent_at(alive_keeper, sent_at, regions).await;
}
/// Handles a heartbeat response that grants `regions` for a heartbeat sent at `sent_at`
/// after the epoch.
async fn handle_lease_response_sent_at(
alive_keeper: &RegionAliveKeeper,
sent_at: Duration,
regions: Vec<GrantedRegion>,
) {
let (tx, _rx) = mpsc::channel(1);
let response = HeartbeatResponse {
region_lease: Some(RegionLease {
regions,
duration_since_epoch: alive_keeper.epoch().elapsed().as_millis() as u64,
duration_since_epoch: sent_at.as_millis() as u64,
// The countdown of a granted region does not expire during the test.
lease_seconds: 86400,
closeable_region_ids: vec![],
@@ -534,6 +566,38 @@ mod test {
alive_keeper.handle(&mut ctx).await.unwrap();
}
#[tokio::test(flavor = "multi_thread")]
async fn ignored_leader_grant_does_not_finalize_leadership() {
common_telemetry::init_default_ut_logging();
let region_server = mock_region_server();
let finalized = Arc::new(AtomicUsize::new(0));
let (engine, _) = MockRegionEngine::with_custom_apply_fn(MITO_ENGINE_NAME, |engine| {
// The engine ignores the grant, so the region stays a follower.
engine.mock_role = Some(Some(RegionRole::Follower));
let finalized = finalized.clone();
engine.handle_set_readonly_gracefully_mock_fn = Some(Box::new(move |_| {
finalized.fetch_add(1, Ordering::Relaxed);
Ok(SetRegionRoleStateResponse::success(
SetRegionRoleStateSuccess::mito(0),
))
}));
});
let region_id = RegionId::new(1024, 1);
region_server.register_test_region(region_id, engine);
let alive_keeper =
RegionAliveKeeper::new(region_server.clone(), None, Duration::from_millis(100));
alive_keeper.register_region(region_id).await;
let grant = GrantedRegion {
region_id: region_id.as_u64(),
role: api::v1::meta::RegionRole::Leader.into(),
extensions: HashMap::new(),
};
handle_lease_response(&alive_keeper, vec![grant]).await;
// The countdown task has handled the grant once it answers.
alive_keeper.deadline(region_id).await.unwrap();
assert_eq!(0, finalized.load(Ordering::Relaxed));
}
#[tokio::test(flavor = "multi_thread")]
async fn lease_responses_let_regions_write() {
common_telemetry::init_default_ut_logging();
@@ -583,10 +647,26 @@ mod test {
role: api::v1::meta::RegionRole::Leader.into(),
extensions: HashMap::new(),
};
handle_lease_response(&alive_keeper, vec![grant]).await;
handle_lease_response(&alive_keeper, vec![grant.clone()]).await;
// The countdown task has applied the grant once it answers.
alive_keeper.deadline(region_id).await.unwrap();
put(region_id).await.unwrap();
// A grant for a heartbeat sent before a downgrade does not make the region a leader again.
let sent_before = alive_keeper.epoch().elapsed();
region_server
.set_region_role_state_gracefully(region_id, SettableRegionRoleState::Follower)
.await
.unwrap();
handle_lease_response_sent_at(&alive_keeper, sent_before, vec![grant.clone()]).await;
alive_keeper.deadline(region_id).await.unwrap();
assert_eq!(region_server.is_region_leader(region_id), Some(false));
// Send times have millisecond precision, so the next heartbeat is sent after the downgrade.
tokio::time::sleep(Duration::from_millis(2)).await;
handle_lease_response(&alive_keeper, vec![grant]).await;
alive_keeper.deadline(region_id).await.unwrap();
put(region_id).await.unwrap();
}
#[tokio::test(flavor = "multi_thread")]
@@ -641,6 +721,7 @@ mod test {
role: api::v1::meta::RegionRole::Leader.into(),
extensions: HashMap::new(),
}],
Instant::now(),
Instant::now() + Duration::from_millis(200),
)
.await;
@@ -694,6 +775,7 @@ mod test {
countdown_handle
.reset_deadline(
RegionRole::Leader,
Instant::now(),
Instant::now() + Duration::from_millis(heartbeat_interval_millis * 5),
HashMap::new(),
)
@@ -744,6 +826,7 @@ mod test {
role: api::v1::meta::RegionRole::StagingLeader.into(),
extensions: HashMap::new(),
}],
Instant::now(),
Instant::now() + Duration::from_millis(3000),
)
.await;
@@ -792,6 +875,7 @@ mod test {
role: api::v1::meta::RegionRole::Leader.into(),
extensions: HashMap::new(),
}],
Instant::now(),
Instant::now() + Duration::from_millis(3000),
)
.await;
@@ -834,6 +918,7 @@ mod test {
role: api::v1::meta::RegionRole::StagingLeader.into(),
extensions: HashMap::new(),
}],
Instant::now(),
Instant::now() + Duration::from_millis(3000),
)
.await;
+22
View File
@@ -44,6 +44,14 @@ pub struct StorageConfig {
/// Defaults to `<data_home>/copy` when `data_home` is a local path.
/// Distributed deployments always disable SQL access to local files.
pub copy_root: Option<String>,
/// Whether to probe every remote object storage when the datanode starts.
///
/// The probe writes, reads, overwrites, lists and deletes an object under
/// `.greptime_probe/`, and a failure aborts startup. The probe lives at the
/// storage root, so the credentials must allow writes and deletes below the root.
/// Disable it when the credentials are scoped to narrower prefixes or when the
/// storage may be unavailable at startup.
pub probe_on_startup: bool,
#[serde(flatten)]
pub store: ObjectStoreConfig,
/// Object storage providers
@@ -62,6 +70,7 @@ impl Default for StorageConfig {
Self {
data_home: DEFAULT_DATA_HOME.to_string(),
copy_root: None,
probe_on_startup: true,
store: ObjectStoreConfig::default(),
providers: vec![],
}
@@ -203,6 +212,19 @@ mod tests {
let _parsed: DatanodeOptions = toml::from_str(&toml_string).unwrap();
}
#[test]
fn test_probe_on_startup() {
assert!(DatanodeOptions::default().storage.probe_on_startup);
let toml_str = r#"
[storage]
type = "File"
probe_on_startup = false
"#;
let opts: DatanodeOptions = toml::from_str(toml_str).unwrap();
assert!(!opts.storage.probe_on_startup);
}
#[test]
fn test_secstr() {
let toml_str = r#"
+154 -10
View File
@@ -44,6 +44,7 @@ use common_wal::config::kafka::DatanodeKafkaConfig;
use common_wal::config::object_store::{ObjectStoreWalConfig, STANDALONE_GENERATION};
use common_wal::config::raft_engine::RaftEngineConfig;
use file_engine::engine::FileRegionEngine;
use futures::future::join_all;
use log_store::ObjectStoreLogStore;
use log_store::kafka::log_store::KafkaLogStore;
use log_store::noop::log_store::NoopLogStore;
@@ -466,20 +467,83 @@ impl DatanodeBuilder {
.await
}
/// Builds [ObjectStoreManager] from [StorageConfig].
pub async fn build_object_store_manager(cfg: &StorageConfig) -> Result<ObjectStoreManagerRef> {
/// Builds [ObjectStoreManager] from [StorageConfig] and probes every remote
/// object store it contains, unless `probe_on_startup` is disabled.
///
/// The probe fails the build when a store rejects any of the operations the
/// engines rely on, so a misconfigured storage surfaces here instead of failing
/// on the first write.
pub async fn build_object_store_manager(
cfg: &StorageConfig,
node_id: u64,
) -> Result<ObjectStoreManagerRef> {
let object_store = store::new_object_store(cfg.store.clone(), &cfg.data_home).await?;
let default_name = cfg.store.config_name();
let mut object_store_manager = ObjectStoreManager::new(default_name, object_store);
for store in &cfg.providers {
object_store_manager.add(
store.config_name(),
store::new_object_store(store.clone(), &cfg.data_home).await?,
);
let mut checks = Vec::with_capacity(1 + cfg.providers.len());
if cfg.store.is_object_storage() {
checks.push((default_name.to_string(), object_store.clone()));
}
let mut object_store_manager = ObjectStoreManager::new(default_name, object_store);
for provider in &cfg.providers {
let name = provider.config_name();
let object_store = store::new_object_store(provider.clone(), &cfg.data_home).await?;
if provider.is_object_storage() {
checks.push((name.to_string(), object_store.clone()));
}
object_store_manager.add(name, object_store);
}
if cfg.probe_on_startup && !checks.is_empty() {
let prefix = store::probe_key_prefix(node_id);
Self::run_probes(&checks, &prefix).await?;
}
Ok(Arc::new(object_store_manager))
}
/// Probes every store in `checks` under its own key prefix.
///
/// Providers often share one object storage, so when there is more than one
/// store each probe starts after a random delay rather than all at once.
///
/// Each check is bounded by [`store::PROBE_TIMEOUT`], so a store that accepts
/// connections but never answers fails startup instead of blocking it, after a
/// best-effort removal of its probe.
async fn run_probes(checks: &[(String, ObjectStore)], prefix: &str) -> Result<()> {
let stagger = checks.len() > 1;
let checks = checks
.iter()
.enumerate()
.map(|(index, (name, object_store))| {
let prefix = format!("{prefix}/{index}");
async move {
if stagger {
tokio::time::sleep(store::probe_start_delay()).await;
}
match tokio::time::timeout(
store::PROBE_TIMEOUT,
store::probe_object_store(object_store, name, &prefix),
)
.await
{
Ok(result) => result,
Err(_) => {
store::remove_probe_object(object_store, &prefix).await;
error::ObjectStoreProbeTimeoutSnafu {
name,
timeout: store::PROBE_TIMEOUT,
}
.fail()
}
}
}
});
for result in join_all(checks).await {
result?;
}
Ok(())
}
#[cfg(test)]
/// Open all regions belong to this datanode.
async fn initialize_region_server(
@@ -573,7 +637,11 @@ impl DatanodeBuilder {
);
region_server.install_remote_dyn_filter_receiver_injector(&self.plugins);
let object_store_manager = Self::build_object_store_manager(&opts.storage).await?;
let object_store_manager = Self::build_object_store_manager(
&opts.storage,
opts.node_id.context(MissingNodeIdSnafu)?,
)
.await?;
let engines = self
.build_store_engines(
object_store_manager,
@@ -1074,6 +1142,7 @@ mod tests {
use cache::build_datanode_layered_cache_registry;
use common_base::Plugins;
use common_base::readable_size::ReadableSize;
use common_base::secrets::SecretString;
use common_config::Configurable;
use common_error::ext::ErrorExt;
use common_error::status_code::StatusCode;
@@ -1092,6 +1161,7 @@ mod tests {
use mito2::engine::MITO_ENGINE_NAME;
use mito2::test_util::{CreateRequestBuilder, build_rows, rows_schema};
use object_store::ObjectStore;
use object_store::config::{S3Config, S3Connection};
use object_store::manager::ObjectStoreManager;
use partition::manager::PartitionRuleManagerRef;
use query::region_query::{RegionQueryHandlerFactory, RegionQueryHandlerFactoryRef};
@@ -1100,7 +1170,7 @@ mod tests {
use store_api::region_request::{PathType, RegionOpenRequest, RegionPutRequest, RegionRequest};
use store_api::storage::RegionId;
use crate::config::{DatanodeOptions, RegionEngineConfig, StorageConfig};
use crate::config::{DatanodeOptions, ObjectStoreConfig, RegionEngineConfig, StorageConfig};
use crate::datanode::{
Datanode, DatanodeBuilder, validate_object_store_wal_config, validate_region_engine_config,
wal_object_store,
@@ -1460,6 +1530,80 @@ mod tests {
);
}
#[tokio::test]
async fn test_object_store_probe_can_be_disabled() {
// The endpoint does not accept connections, so this only succeeds when the
// probe does not run.
let storage = StorageConfig {
store: ObjectStoreConfig::S3(S3Config {
connection: S3Connection {
bucket: "test".to_string(),
endpoint: Some("http://127.0.0.1:1".to_string()),
region: Some("us-east-1".to_string()),
access_key_id: SecretString::from("test".to_string()),
secret_access_key: SecretString::from("test".to_string()),
..Default::default()
},
..Default::default()
}),
probe_on_startup: false,
..Default::default()
};
DatanodeBuilder::build_object_store_manager(&storage, 1)
.await
.unwrap();
}
#[tokio::test]
async fn test_file_store_is_not_probed() {
// The probe is enabled by default, but a File store must skip it.
let data_home = create_temp_dir("object-store-probe-file");
let storage = StorageConfig {
data_home: data_home.path().to_str().unwrap().to_string(),
..Default::default()
};
DatanodeBuilder::build_object_store_manager(&storage, 1)
.await
.unwrap();
// The probe would leave this directory behind if it ran.
assert!(!data_home.path().join(".greptime_probe").exists());
}
#[tokio::test]
async fn test_object_store_probe_failure_aborts_build() {
// The endpoint does not accept connections, so the probe write fails and the
// build must fail with it.
let storage = StorageConfig {
store: ObjectStoreConfig::S3(S3Config {
connection: S3Connection {
bucket: "test".to_string(),
endpoint: Some("http://127.0.0.1:1".to_string()),
region: Some("us-east-1".to_string()),
access_key_id: SecretString::from("test".to_string()),
secret_access_key: SecretString::from("test".to_string()),
..Default::default()
},
..Default::default()
}),
..Default::default()
};
let err = DatanodeBuilder::build_object_store_manager(&storage, 1)
.await
.unwrap_err();
assert_matches!(
err,
Error::ObjectStoreProbe {
name,
step: "write",
..
} if name == storage.store.config_name()
);
}
struct CountingRegionQueryHandlerFactory(Arc<AtomicUsize>);
impl RegionQueryHandlerFactory for CountingRegionQueryHandlerFactory {
+27 -1
View File
@@ -14,6 +14,7 @@
use std::any::Any;
use std::sync::Arc;
use std::time::Duration;
use common_error::define_into_tonic_status;
use common_error::ext::{BoxedError, ErrorExt, RetryHint};
@@ -472,6 +473,24 @@ pub enum Error {
location: Location,
},
#[snafu(display("Failed to run object storage probe for provider '{name}' at step '{step}'"))]
ObjectStoreProbe {
name: String,
step: &'static str,
#[snafu(source)]
error: object_store::Error,
#[snafu(implicit)]
location: Location,
},
#[snafu(display("Object storage probe for provider '{name}' timed out after {timeout:?}"))]
ObjectStoreProbeTimeout {
name: String,
timeout: Duration,
#[snafu(implicit)]
location: Location,
},
#[snafu(display("Not yet implemented: {what}"))]
NotYetImplemented { what: String },
}
@@ -554,6 +573,9 @@ impl ErrorExt for Error {
SerializeJson { .. } => StatusCode::Internal,
ObjectStore { source, .. } => source.status_code(),
ObjectStoreProbe { .. } | ObjectStoreProbeTimeout { .. } => {
StatusCode::StorageUnavailable
}
}
}
@@ -569,7 +591,8 @@ impl ErrorExt for Error {
RegionNotReady { .. } | RegionNotFound { .. } => RetryHint::RetryAfterRouteRefresh,
RegionBusy { .. }
| ConcurrentQueryLimiterClosed { .. }
| ConcurrentQueryLimiterTimeout { .. } => RetryHint::Retryable,
| ConcurrentQueryLimiterTimeout { .. }
| ObjectStoreProbeTimeout { .. } => RetryHint::Retryable,
NewPlanDecoder { source, .. } | ExecuteLogicalPlan { source, .. } => {
source.retry_hint()
}
@@ -593,6 +616,9 @@ impl ErrorExt for Error {
BuildMetricEngine { source, .. } => source.retry_hint(),
ListStorageSsts { source, .. } => source.retry_hint(),
ObjectStore { source, .. } => source.retry_hint(),
ObjectStoreProbe { error, .. } => {
object_store::error::retry_hint_from_opendal_error(error)
}
_ => RetryHint::NonRetryable,
}
}
+6 -22
View File
@@ -13,10 +13,6 @@
// limitations under the License.
mod catalog;
#[cfg(feature = "enterprise")]
mod flow_write;
#[cfg(feature = "enterprise")]
use flow_write::TrackedPayload;
mod registrations;
mod remote_dyn_filter;
@@ -42,8 +38,6 @@ use async_trait::async_trait;
use bytes::Bytes;
use common_error::ext::{BoxedError, ErrorExt};
use common_error::status_code::StatusCode;
#[cfg(feature = "enterprise")]
use common_grpc::flow_write::{COMMAND_KEY, FlowWriteRegistry, Reply};
use common_meta::datanode::TopicStatsReporter;
use common_query::OutputData;
use common_query::request::QueryRequest;
@@ -122,8 +116,6 @@ pub struct RegionServer {
inner: Arc<RegionServerInner>,
flight_compression: FlightCompression,
suspend: Arc<AtomicBool>,
#[cfg(feature = "enterprise")]
flow_write_registry: Arc<FlowWriteRegistry<TrackedPayload, Reply>>,
}
pub struct RegionStat {
@@ -172,8 +164,6 @@ impl RegionServer {
)),
flight_compression,
suspend: Arc::new(AtomicBool::new(false)),
#[cfg(feature = "enterprise")]
flow_write_registry: Arc::new(FlowWriteRegistry::default()),
}
}
@@ -471,20 +461,23 @@ impl RegionServer {
.with_context(|_| HandleRegionRequestSnafu { region_id })
}
/// Sets the role of a region from a lease the metasrv grants until `deadline`.
/// Sets the role of a region from a lease the metasrv grants until `deadline`, in reply to a
/// heartbeat sent at `sent_at`. Returns false if the engine ignores a Leader lease because the
/// region was downgraded or (re)opened after `sent_at`.
pub fn set_region_role_with_lease(
&self,
region_id: RegionId,
role: RegionRole,
sent_at: std::time::Instant,
deadline: std::time::Instant,
) -> Result<()> {
) -> Result<bool> {
let engine = self
.inner
.region_map
.get(&region_id)
.with_context(|| RegionNotFoundSnafu { region_id })?;
engine
.set_region_role_with_lease(region_id, role, deadline)
.set_region_role_with_lease(region_id, role, sent_at, deadline)
.with_context(|_| HandleRegionRequestSnafu { region_id })
}
@@ -1069,15 +1062,6 @@ impl RegionServerHandler for RegionServer {
&self,
request: RegionRequestV1,
) -> ServerResult<RegionResponseV1> {
#[cfg(feature = "enterprise")]
if request
.header
.as_ref()
.and_then(|header| header.query_context.as_ref())
.is_some_and(|context| context.extensions.contains_key(COMMAND_KEY))
{
return self.handle_flow_write_request(request).await;
}
let accept_partial_result = request
.header
.as_ref()
@@ -1,969 +0,0 @@
// 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.
//! Datanode receiver for tracked Flow writes.
//!
//! A single immutable operation per receiver-issued capability: the first
//! admitted `Write` becomes the owner and executes the Inserts exactly once on
//! the region engines; concurrent or retried identical writers join the
//! owner's completion. Dropping a waiter (for example a lost RPC response)
//! never cancels the engine work, and closing a capability rejects later
//! writes with that capability. If the owner's outcome becomes unknown (a
//! child ingest worker was lost), no positive terminal completion is
//! published: waiters observe `WriterLost`; the capability admits no second
//! owner, so no overlapping engine write can be produced.
use std::sync::Arc;
use api::v1::region::RegionRequest as RegionRequestV1;
use api::v1::region::region_request;
use common_error::ext::ErrorExt;
use common_grpc::flow_write::{Admission, COMMAND_KEY, Command, Reply, TerminalError};
use common_runtime::runtime::RuntimeTrait;
use common_telemetry::tracing_context::{FutureExt, TracingContext};
use futures_util::future::join_all;
use prost::Message;
use servers::error::{InvalidQuerySnafu, Result as ServerResult};
use snafu::OptionExt;
use crate::region_server::RegionServer;
/// Payload of a tracked write: encoded Inserts rows (exact bytes, so floats
/// keep bit equality even for NaN), schemas compared by protobuf equality, and
/// semantic header identity (dbname and command-free query context). Retrying
/// with different business data or context is rejected instead of joining.
pub(crate) type TrackedPayload = (
Vec<u8>,
Vec<Option<Vec<api::v1::ColumnSchema>>>,
String,
Option<api::v1::QueryContext>,
);
fn tracked_payload(request: &RegionRequestV1) -> ServerResult<TrackedPayload> {
let body = request.body.as_ref().context(InvalidQuerySnafu {
reason: "Expecting non-empty region request body.",
})?;
if !matches!(body, region_request::Body::Inserts(_)) {
return Err(servers::error::Error::InvalidQuery {
reason: "Tracked Flow write supports Inserts requests only.".to_string(),
location: snafu::Location::new(file!(), line!(), column!()),
});
}
// Oneof is not `prost::Message`; the variant message itself is. Schema
// options contain unordered maps, so compare schemas separately rather than
// letting their wire ordering affect retries; retain encoded rows for NaN.
let (bytes, schemas) = match body {
region_request::Body::Inserts(inserts) => {
let mut inserts = inserts.clone();
let schemas = inserts
.requests
.iter_mut()
.map(|request| {
request
.rows
.as_mut()
.map(|rows| std::mem::take(&mut rows.schema))
})
.collect();
(inserts.encode_to_vec(), schemas)
}
_ => unreachable!("checked above"),
};
let header = request.header.as_ref();
let mut query_context = header.and_then(|header| header.query_context.clone());
if let Some(context) = query_context.as_mut() {
// The command extension differs per control request, not per business.
context.extensions.remove(COMMAND_KEY);
}
Ok((
bytes,
schemas,
header
.map(|header| header.dbname.clone())
.unwrap_or_default(),
query_context,
))
}
fn ensure_empty_control_body(request: &RegionRequestV1) -> ServerResult<()> {
match request.body.as_ref() {
Some(region_request::Body::Inserts(inserts)) if inserts.requests.is_empty() => Ok(()),
_ => Err(servers::error::Error::InvalidQuery {
reason: "Tracked Flow write control requests must carry an empty Inserts body."
.to_string(),
location: snafu::Location::new(file!(), line!(), column!()),
}),
}
}
fn registry_error(error: common_grpc::flow_write::RegistryError) -> servers::error::Error {
servers::error::Error::UnexpectedResult {
reason: format!("Tracked Flow write registry rejected request: {error:?}"),
location: snafu::Location::new(file!(), line!(), column!()),
}
}
fn response(reply: Reply) -> ServerResult<api::v1::region::RegionResponse> {
let encoded =
serde_json::to_vec(&reply).map_err(|error| servers::error::Error::UnexpectedResult {
reason: format!("Failed to encode tracked Flow write reply: {error}"),
location: snafu::Location::new(file!(), line!(), column!()),
})?;
let mut extensions = std::collections::HashMap::new();
extensions.insert(COMMAND_KEY.to_string(), encoded);
Ok(api::v1::region::RegionResponse {
header: Some(api::v1::ResponseHeader {
status: Some(api::v1::Status {
status_code: common_error::status_code::StatusCode::Success as _,
..Default::default()
}),
}),
affected_rows: 0,
extensions,
metadata: Vec::new(),
failures: Vec::new(),
})
}
impl RegionServer {
pub(crate) async fn handle_flow_write_request(
&self,
request: RegionRequestV1,
) -> ServerResult<api::v1::region::RegionResponse> {
let command = request
.header
.as_ref()
.and_then(|header| header.query_context.as_ref())
.and_then(|context| context.extensions.get(COMMAND_KEY))
.and_then(|value| Command::decode(value).ok());
let command = match command {
Some(command) => command,
None => {
// The extension exists but is not a decodable command: reject
// before any ordinary DML dispatch.
return Err(InvalidQuerySnafu {
reason: "Malformed tracked Flow write command.",
}
.build());
}
};
match command {
Command::Open { nonce } => {
ensure_empty_control_body(&request)?;
let capability = self
.flow_write_registry
.open(&nonce)
.map_err(registry_error)?;
response(Reply::Opened { capability })
}
Command::Close { capability } => {
ensure_empty_control_body(&request)?;
self.flow_write_registry
.close(&capability)
.await
.map_err(registry_error)?;
response(Reply::Closed)
}
Command::Write { capability } => {
let payload = tracked_payload(&request)?;
let admission = self
.flow_write_registry
.admit(&capability, payload)
.map_err(registry_error)?;
let reply = match admission {
Admission::Start(owner) => {
// Subscribe before the owner sender moves into the
// spawned task: this caller stays a plain waiter whose
// drop cannot cancel the engine work.
let receiver = owner.subscribe();
let server = self.clone();
let body = request.body;
let header = request.header;
self.inner.runtime.spawn(async move {
let completion = server
.run_tracked_write(header, body)
.trace(TracingContext::from_current_span().attach(
common_telemetry::tracing::info_span!(
"RegionServer::tracked_flow_write"
),
))
.await;
match completion {
Some(reply) => {
let _ = owner.send(Some(Arc::new(reply)));
}
None => {
// Unknown worker outcome: no positive terminal
// result is published. Dropping the sender lets
// waiters observe `WriterLost`.
drop(owner);
}
}
});
common_grpc::flow_write::wait_completion(receiver)
.await
.map_err(registry_error)?
}
Admission::Join(waiter) => common_grpc::flow_write::wait_completion(waiter)
.await
.map_err(registry_error)?,
};
response((*reply).clone())
}
}
}
/// Executes one admitted tracked write. Returns `None` only when the
/// outcome is unknown (a child worker was lost); malformed request bodies
/// are terminal because no child was ever dispatched.
async fn run_tracked_write(
&self,
header: Option<api::v1::region::RegionRequestHeader>,
body: Option<region_request::Body>,
) -> Option<Reply> {
let requests =
match body.map(store_api::region_request::RegionRequest::try_from_request_body) {
Some(Ok(requests)) => requests,
Some(Err(error)) => {
return Some(Reply::Complete {
rows: 0,
cost: 0,
metrics: None,
error: Some(TerminalError {
code: error.status_code() as u32,
message: error.output_msg(),
}),
});
}
// `None` is unreachable here: the Write path already rejected an
// empty body before admission. Treat it as unknown rather than
// inventing a terminal result.
None => return None,
};
let tracing = header
.as_ref()
.map(|header| TracingContext::from_w3c(&header.tracing_context))
.unwrap_or_default();
let mut unknown_worker = false;
let mut first_error: Option<crate::error::Error> = None;
let mut affected_rows = 0usize;
let tasks = requests.into_iter().map(|(region_id, request)| {
let span = tracing.attach(common_telemetry::tracing::info_span!(
"RegionServer::tracked_region_write",
region_id = region_id.to_string()
));
async move { self.handle_request(region_id, request).trace(span).await }
});
// Drain every per-region child before any terminal decision. A lost
// ingest worker (`RuntimeJoin`) is unknown and outranks any ordinary
// application error observed during the same drain.
for result in join_all(tasks).await {
match result {
Ok(response) => affected_rows += response.affected_rows,
Err(crate::error::Error::RuntimeJoin { .. }) => {
unknown_worker = true;
}
Err(error) if first_error.is_none() => first_error = Some(error),
Err(_) => {}
}
}
if unknown_worker {
return None;
}
Some(match first_error {
None => Reply::Complete {
rows: affected_rows,
cost: affected_rows,
metrics: None,
error: None,
},
Some(error) => Reply::Complete {
rows: 0,
cost: 0,
metrics: None,
error: Some(TerminalError {
code: error.status_code() as u32,
message: error.output_msg(),
}),
},
})
}
}
#[cfg(test)]
mod tests {
use std::collections::HashMap;
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use api::region::RegionResponse;
use api::v1::region::region_request::Body;
use api::v1::region::{
InsertRequest, InsertRequests, RegionRequest as Request, RegionRequestHeader,
};
use api::v1::{ColumnDataType, ColumnSchema, QueryContext, Row, Rows, SemanticType, Value};
use common_grpc::flow_write::{self, Command, Reply};
use servers::grpc::region_server::RegionServerHandler;
use store_api::region_engine::{RegionEngine, RegionEngineRef};
use store_api::storage::RegionId;
use tokio::sync::Notify;
use tokio::time::{Duration, timeout};
use super::*;
use crate::tests::{MockRegionEngine, mock_region_server};
#[derive(Clone, Default)]
struct Gate {
entered: Arc<AtomicUsize>,
notified: Arc<Notify>,
open: Arc<AtomicUsize>,
fail: bool,
}
impl Gate {
async fn wait_entered(&self, count: usize) {
timeout(Duration::from_secs(5), async {
loop {
let notified = self.notified.notified();
tokio::pin!(notified);
notified.as_mut().enable();
if self.entered.load(Ordering::SeqCst) >= count {
break;
}
notified.await;
}
})
.await
.unwrap();
}
fn release(&self) {
self.open.store(1, Ordering::SeqCst);
self.notified.notify_waiters();
}
async fn wait_open(&self) {
loop {
let notified = self.notified.notified();
tokio::pin!(notified);
notified.as_mut().enable();
if self.open.load(Ordering::SeqCst) != 0 {
break;
}
notified.await;
}
}
}
struct GatedEngine {
gate: Gate,
inner: Arc<MockRegionEngine>,
panic_id: Option<u64>,
}
#[async_trait::async_trait]
impl RegionEngine for GatedEngine {
fn name(&self) -> &str {
self.inner.name()
}
async fn handle_request(
&self,
id: RegionId,
_request: store_api::region_request::RegionRequest,
) -> Result<RegionResponse, common_error::ext::BoxedError> {
self.gate.entered.fetch_add(1, Ordering::SeqCst);
self.gate.notified.notify_waiters();
if self.panic_id == Some(id.as_u64()) {
panic!("test ingest panic");
}
if self.gate.fail && id.as_u64() == 1 {
return Err(common_error::ext::BoxedError::new(
crate::error::RegionNotFoundSnafu { region_id: id }.build(),
));
}
self.gate.wait_open().await;
Ok(RegionResponse::new(1))
}
async fn handle_query(
&self,
id: RegionId,
req: store_api::storage::ScanRequest,
) -> Result<store_api::region_engine::RegionScannerRef, common_error::ext::BoxedError>
{
self.inner.handle_query(id, req).await
}
async fn get_committed_sequence(
&self,
id: RegionId,
) -> Result<store_api::storage::SequenceNumber, common_error::ext::BoxedError> {
self.inner.get_committed_sequence(id).await
}
async fn get_metadata(
&self,
id: RegionId,
) -> Result<store_api::metadata::RegionMetadataRef, common_error::ext::BoxedError> {
self.inner.get_metadata(id).await
}
fn region_statistic(
&self,
id: RegionId,
) -> Option<store_api::region_engine::RegionStatistic> {
self.inner.region_statistic(id)
}
async fn stop(&self) -> Result<(), common_error::ext::BoxedError> {
self.inner.stop().await
}
fn set_region_role(
&self,
id: RegionId,
role: store_api::region_engine::RegionRole,
) -> Result<(), common_error::ext::BoxedError> {
self.inner.set_region_role(id, role)
}
fn set_region_role_with_lease(
&self,
id: RegionId,
role: store_api::region_engine::RegionRole,
deadline: std::time::Instant,
) -> Result<(), common_error::ext::BoxedError> {
self.inner.set_region_role_with_lease(id, role, deadline)
}
async fn sync_region(
&self,
id: RegionId,
req: store_api::region_engine::SyncRegionFromRequest,
) -> Result<store_api::region_engine::SyncRegionFromResponse, common_error::ext::BoxedError>
{
self.inner.sync_region(id, req).await
}
async fn remap_manifests(
&self,
req: store_api::region_engine::RemapManifestsRequest,
) -> Result<store_api::region_engine::RemapManifestsResponse, common_error::ext::BoxedError>
{
self.inner.remap_manifests(req).await
}
async fn set_region_role_state_gracefully(
&self,
id: RegionId,
state: store_api::region_engine::SettableRegionRoleState,
) -> Result<
store_api::region_engine::SetRegionRoleStateResponse,
common_error::ext::BoxedError,
> {
self.inner.set_region_role_state_gracefully(id, state).await
}
fn role(&self, id: RegionId) -> Option<store_api::region_engine::RegionRole> {
self.inner.role(id)
}
fn as_any(&self) -> &dyn std::any::Any {
self
}
}
fn body(ids: &[u64], nan: bool) -> Body {
Body::Inserts(InsertRequests {
requests: ids
.iter()
.map(|id| InsertRequest {
region_id: *id,
rows: Some(Rows {
schema: vec![
ColumnSchema {
column_name: "ts".into(),
datatype: ColumnDataType::TimestampMillisecond as i32,
semantic_type: SemanticType::Timestamp as i32,
datatype_extension: None,
options: None,
},
ColumnSchema {
column_name: "v".into(),
datatype: ColumnDataType::Float64 as i32,
semantic_type: SemanticType::Field as i32,
datatype_extension: None,
options: None,
},
],
rows: vec![Row {
values: vec![
Value {
value_data: Some(
api::v1::value::ValueData::TimestampMillisecondValue(1),
),
},
Value {
value_data: Some(api::v1::value::ValueData::F64Value(if nan {
f64::NAN
} else {
7.
})),
},
],
}],
}),
partition_expr_version: None,
skip_wal: false,
})
.collect(),
})
}
fn request(cmd: Command, body: Option<Body>) -> Request {
let mut extensions = HashMap::new();
extensions.insert(flow_write::COMMAND_KEY.into(), cmd.encode().unwrap());
Request {
header: Some(RegionRequestHeader {
dbname: "db".into(),
tracing_context: Default::default(),
query_context: Some(QueryContext {
extensions,
..Default::default()
}),
}),
body,
}
}
fn decode(resp: &api::v1::region::RegionResponse) -> Reply {
assert_eq!(
resp.header
.as_ref()
.unwrap()
.status
.as_ref()
.unwrap()
.status_code,
common_error::status_code::StatusCode::Success as u32
);
serde_json::from_slice(resp.extensions.get(flow_write::COMMAND_KEY).unwrap()).unwrap()
}
async fn open(s: &RegionServer) -> String {
match decode(
&s.handle_region_request(request(
Command::Open { nonce: "n".into() },
Some(Body::Inserts(InsertRequests { requests: vec![] })),
))
.await
.unwrap(),
) {
Reply::Opened { capability } => capability,
x => panic!("{x:?}"),
}
}
fn setup(gate: Gate, panic_id: Option<u64>, ids: &[u64]) -> RegionServer {
let s = mock_region_server();
let (inner, _) = MockRegionEngine::new("mock");
let engine: RegionEngineRef = Arc::new(GatedEngine {
gate,
inner,
panic_id,
});
for id in ids {
s.inner.region_map.insert(
RegionId::from_u64(*id),
super::super::RegionEngineWithStatus::Ready(engine.clone()),
);
}
s
}
fn write(cap: &str, ids: &[u64], nan: bool) -> Request {
request(
Command::Write {
capability: cap.into(),
},
Some(body(ids, nan)),
)
}
#[tokio::test]
async fn dropped_rpc_retry_and_close_drain_exactly_once() {
let gate = Gate::default();
let s = setup(gate.clone(), None, &[1, 2]);
let cap = open(&s).await;
let w = write(&cap, &[1, 2], false);
let first = tokio::spawn({
let s = s.clone();
let w = w.clone();
async move { s.handle_region_request(w).await }
});
gate.wait_entered(2).await;
first.abort();
// Exercise the same actual registry admission used by retry, before release.
let payload = tracked_payload(&w).unwrap();
let Admission::Join(waiter) = s.flow_write_registry.admit(&cap, payload).unwrap() else {
panic!("retry did not join")
};
let mut retry_waiter = tokio::spawn(common_grpc::flow_write::wait_completion(waiter));
assert!(
timeout(Duration::from_millis(20), &mut retry_waiter)
.await
.is_err()
);
let mut closer = tokio::spawn({
let s = s.clone();
let cap = cap.clone();
async move {
s.handle_region_request(request(
Command::Close { capability: cap },
Some(Body::Inserts(InsertRequests { requests: vec![] })),
))
.await
}
});
assert!(
timeout(Duration::from_millis(20), &mut closer)
.await
.is_err()
);
gate.release();
let joined = timeout(Duration::from_secs(5), &mut retry_waiter)
.await
.unwrap()
.unwrap()
.unwrap();
assert!(matches!(
*joined,
Reply::Complete {
rows: 2,
error: None,
..
}
));
assert!(matches!(
decode(
&timeout(Duration::from_secs(5), &mut closer)
.await
.unwrap()
.unwrap()
.unwrap()
),
Reply::Closed
));
assert!(
s.handle_region_request(write(&cap, &[1], false))
.await
.is_err()
);
let cap2 = open(&s).await;
gate.release();
let r = s
.handle_region_request(write(&cap2, &[1], false))
.await
.unwrap();
assert!(matches!(decode(&r), Reply::Complete { rows: 1, .. }));
assert!(
s.handle_region_request(write(&cap, &[1], false))
.await
.is_err()
);
assert_eq!(gate.entered.load(Ordering::SeqCst), 3);
let close2 = request(
Command::Close { capability: cap2 },
Some(Body::Inserts(InsertRequests { requests: vec![] })),
);
assert!(matches!(
decode(&s.handle_region_request(close2).await.unwrap()),
Reply::Closed
));
}
#[tokio::test]
async fn application_error_waits_for_sibling_and_panic_overrides_it() {
let gate = Gate {
fail: true,
..Default::default()
};
let s = setup(gate.clone(), None, &[1, 2]);
let cap = open(&s).await;
let task = tokio::spawn({
let s = s.clone();
async move { s.handle_region_request(write(&cap, &[1, 2], false)).await }
});
gate.wait_entered(2).await;
// The ordinary error is immediate for region 1, but region 2 remains gated.
assert!(!task.is_finished());
gate.release();
let r = timeout(Duration::from_secs(5), task)
.await
.unwrap()
.unwrap()
.unwrap();
assert!(matches!(decode(&r), Reply::Complete { error: Some(_), .. }));
let gate = Gate {
fail: true,
..Default::default()
};
let s = setup(gate.clone(), Some(2), &[1, 2, 3]);
let cap = open(&s).await;
let task = tokio::spawn({
let s = s.clone();
let cap = cap.clone();
async move {
s.handle_region_request(write(&cap, &[1, 2, 3], false))
.await
}
});
gate.wait_entered(3).await;
assert!(!task.is_finished());
gate.release();
assert!(
timeout(Duration::from_secs(5), task)
.await
.unwrap()
.unwrap()
.is_err()
);
assert!(
s.handle_region_request(write(&cap, &[1, 2, 3], false))
.await
.is_err()
);
assert_eq!(gate.entered.load(Ordering::SeqCst), 3);
}
#[tokio::test]
async fn decoded_schema_option_maps_join_live_nan_write() {
let gate = Gate::default();
let s = setup(gate.clone(), None, &[1]);
let cap = open(&s).await;
let mut original = write(&cap, &[1], true);
let Body::Inserts(inserts) = original.body.as_mut().unwrap() else {
unreachable!()
};
inserts.requests[0].rows.as_mut().unwrap().schema[1].options =
Some(api::v1::ColumnOptions {
options: [
("alpha".to_string(), "one".to_string()),
("beta".to_string(), "two".to_string()),
("gamma".to_string(), "three".to_string()),
]
.into_iter()
.collect(),
});
let encoded = original.encode_to_vec();
let Body::Inserts(original_inserts) = original.body.as_ref().unwrap() else {
unreachable!()
};
let original_rows = original_inserts.requests[0].rows.clone();
let original_body_bytes = original_inserts.encode_to_vec();
let mut retries = Vec::new();
let mut found_different_wire_order = false;
for _ in 0..128 {
let decoded = Request::decode(encoded.as_slice()).unwrap();
let Body::Inserts(decoded_inserts) = decoded.body.as_ref().unwrap() else {
unreachable!()
};
assert_eq!(
decoded_inserts.requests[0].rows.as_ref().unwrap().schema,
original_rows.as_ref().unwrap().schema
);
assert_eq!(
tracked_payload(&decoded).unwrap(),
tracked_payload(&original).unwrap()
);
found_different_wire_order |= decoded_inserts.encode_to_vec() != original_body_bytes;
retries.push(decoded);
if found_different_wire_order && retries.len() >= 16 {
break;
}
}
assert!(found_different_wire_order);
let owner = tokio::spawn({
let s = s.clone();
async move { s.handle_region_request(original).await }
});
gate.wait_entered(1).await;
let retry_tasks: Vec<_> = retries
.into_iter()
.map(|retry| {
let s = s.clone();
tokio::spawn(async move { s.handle_region_request(retry).await })
})
.collect();
tokio::task::yield_now().await;
assert!(retry_tasks.iter().all(|retry| !retry.is_finished()));
assert_eq!(gate.entered.load(Ordering::SeqCst), 1);
gate.release();
let owner_reply = decode(
&timeout(Duration::from_secs(5), owner)
.await
.unwrap()
.unwrap()
.unwrap(),
);
assert!(matches!(
&owner_reply,
Reply::Complete {
rows: 1,
error: None,
..
}
));
let owner_reply_json = serde_json::to_string(&owner_reply).unwrap();
for retry in retry_tasks {
let retry_reply = decode(
&timeout(Duration::from_secs(5), retry)
.await
.unwrap()
.unwrap()
.unwrap(),
);
assert!(matches!(
&retry_reply,
Reply::Complete {
rows: 1,
error: None,
..
}
));
assert_eq!(
serde_json::to_string(&retry_reply).unwrap(),
owner_reply_json
);
}
assert_eq!(gate.entered.load(Ordering::SeqCst), 1);
let replay = Request::decode(encoded.as_slice()).unwrap();
assert!(matches!(
decode(&s.handle_region_request(replay.clone()).await.unwrap()),
Reply::Complete { rows: 1, .. }
));
let mut changed_schema = replay.clone();
let Body::Inserts(inserts) = changed_schema.body.as_mut().unwrap() else {
unreachable!()
};
inserts.requests[0].rows.as_mut().unwrap().schema[1]
.options
.as_mut()
.unwrap()
.options
.insert("gamma".into(), "changed".into());
assert!(s.handle_region_request(changed_schema).await.is_err());
let close = request(
Command::Close {
capability: cap.clone(),
},
Some(Body::Inserts(InsertRequests { requests: vec![] })),
);
assert!(matches!(
decode(&s.handle_region_request(close).await.unwrap()),
Reply::Closed
));
assert!(s.handle_region_request(replay).await.is_err());
assert_eq!(gate.entered.load(Ordering::SeqCst), 1);
}
#[tokio::test]
async fn payload_identity_nan_semantics_and_pre_admission_rejection() {
let s = mock_region_server();
let cap = open(&s).await;
let a = write(&cap, &[1], true);
let b = write(&cap, &[1], true);
assert_eq!(tracked_payload(&a).unwrap(), tracked_payload(&b).unwrap());
let owner = match s
.flow_write_registry
.admit(&cap, tracked_payload(&a).unwrap())
.unwrap()
{
Admission::Start(owner) => owner,
_ => panic!(),
};
let mut semantic_mismatch = b.clone();
semantic_mismatch.header.as_mut().unwrap().dbname = "other_db".into();
assert_eq!(
s.flow_write_registry
.admit(&cap, tracked_payload(&semantic_mismatch).unwrap())
.unwrap_err(),
flow_write::RegistryError::PayloadMismatch
);
semantic_mismatch = b.clone();
semantic_mismatch
.header
.as_mut()
.unwrap()
.query_context
.as_mut()
.unwrap()
.extensions
.insert("flow_lane".into(), "changed".into());
assert_eq!(
s.flow_write_registry
.admit(&cap, tracked_payload(&semantic_mismatch).unwrap())
.unwrap_err(),
flow_write::RegistryError::PayloadMismatch
);
let Admission::Join(waiter) = s
.flow_write_registry
.admit(&cap, tracked_payload(&b).unwrap())
.unwrap()
else {
panic!()
};
let mut joined = tokio::spawn(common_grpc::flow_write::wait_completion(waiter));
assert!(
timeout(Duration::from_millis(20), &mut joined)
.await
.is_err()
);
owner
.send(Some(Arc::new(Reply::Complete {
rows: 1,
cost: 1,
metrics: None,
error: None,
})))
.unwrap();
assert!(matches!(
*timeout(Duration::from_secs(5), &mut joined)
.await
.unwrap()
.unwrap()
.unwrap(),
Reply::Complete { rows: 1, .. }
));
s.flow_write_registry.close(&cap).await.unwrap();
assert_ne!(
tracked_payload(&a).unwrap(),
tracked_payload(&write(&cap, &[1], false)).unwrap()
);
assert!(
s.handle_region_request(request(
Command::Write {
capability: cap.clone()
},
Some(Body::Deletes(Default::default()))
))
.await
.is_err()
);
let fresh = open(&s).await;
let mut bad = request(
Command::Write {
capability: fresh.clone(),
},
Some(body(&[1], false)),
);
bad.header
.as_mut()
.unwrap()
.query_context
.as_mut()
.unwrap()
.extensions
.insert(flow_write::COMMAND_KEY.into(), "not-json".into());
assert!(s.handle_region_request(bad).await.is_err());
s.flow_write_registry.close(&fresh).await.unwrap();
}
}
+219 -2
View File
@@ -14,11 +14,14 @@
//! object storage utilities
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use common_telemetry::{info, warn};
use futures::TryStreamExt;
use object_store::factory::new_raw_object_store;
use object_store::util::{clean_temp_dir, join_dir, with_instrument_layers, with_retry_layers};
use object_store::{ATOMIC_WRITE_DIR, ObjectStore};
use snafu::prelude::*;
use object_store::{ATOMIC_WRITE_DIR, Error as ObjectStoreError, ErrorKind, ObjectStore};
use snafu::{IntoError, prelude::*};
use crate::config::ObjectStoreConfig;
use crate::error::{self, Result};
@@ -84,3 +87,217 @@ pub async fn new_object_store(store: ObjectStoreConfig, data_home: &str) -> Resu
let object_store = with_instrument_layers(object_store, true);
Ok(object_store)
}
/// The content written by [`probe_object_store`].
const PROBE_CONTENT: &[u8] = b"greptimedb object store probe";
/// The content appended by [`probe_object_store`] to exercise read-modify-write.
const PROBE_SUFFIX: &[u8] = b" - read-modify-write";
/// The directory that holds the objects created by [`probe_object_store`].
const PROBE_DIR: &str = ".greptime_probe";
/// The budget of one [`probe_object_store`] call, including the retries an object
/// store makes on top of its 30s request timeout.
pub(crate) const PROBE_TIMEOUT: Duration = Duration::from_secs(180);
/// The maximum random delay before a probe starts. It is short enough that startup
/// waits at most this delay, and it spreads out the probes of providers that share
/// an object storage.
const PROBE_STAGGER: Duration = Duration::from_millis(500);
/// The budget of the best-effort cleanup after a timed-out probe, kept short so an
/// unresponsive store cannot block startup a second time.
const PROBE_CLEANUP_TIMEOUT: Duration = Duration::from_secs(10);
/// Returns a random delay in `[0, PROBE_STAGGER)`.
pub(crate) fn probe_start_delay() -> Duration {
Duration::from_nanos(rand::random_range(0..PROBE_STAGGER.as_nanos() as u64))
}
/// Returns a unique key prefix for [`probe_object_store`], so datanodes sharing
/// the same bucket and root do not collide.
pub(crate) fn probe_key_prefix(node_id: u64) -> String {
let nanos = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_nanos();
format!("{PROBE_DIR}/{node_id}-{}-{nanos}", std::process::id())
}
/// Returns the object key [`probe_object_store`] probes under `prefix`.
fn probe_object_key(prefix: &str) -> String {
format!("{prefix}/probe")
}
/// Checks that `store` supports the operations the storage engines rely on: write,
/// read, overwrite, list and delete.
///
/// The probe object is removed before returning, after a failed step too. A caller
/// that abandons the check early must call [`remove_probe_object`].
pub(crate) async fn probe_object_store(
store: &ObjectStore,
name: &str,
prefix: &str,
) -> Result<()> {
let key = probe_object_key(prefix);
let check = async {
store
.write(&key, PROBE_CONTENT)
.await
.context(error::ObjectStoreProbeSnafu {
name,
step: "write",
})?;
verify_content(store, name, &key, PROBE_CONTENT).await?;
// Object stores cannot append in place, so this reads the object, appends to
// it and overwrites it, exercising an overwrite of an existing object.
let mut content = store
.read(&key)
.await
.context(error::ObjectStoreProbeSnafu { name, step: "read" })?
.to_vec();
content.extend_from_slice(PROBE_SUFFIX);
store
.write(&key, content.clone())
.await
.context(error::ObjectStoreProbeSnafu {
name,
step: "overwrite",
})?;
verify_content(store, name, &key, &content).await?;
let mut lister = store
.lister_with(&format!("{prefix}/"))
.await
.context(error::ObjectStoreProbeSnafu { name, step: "list" })?;
while let Some(entry) = lister
.try_next()
.await
.context(error::ObjectStoreProbeSnafu { name, step: "list" })?
{
if entry.path() == key {
return Ok(());
}
}
Err(
error::ObjectStoreProbeSnafu { name, step: "list" }.into_error(ObjectStoreError::new(
ErrorKind::Unexpected,
format!("'{key}' is not visible in the listing"),
)),
)
}
.await;
match store.delete(&key).await {
Ok(()) => check,
Err(err) if check.is_err() => {
warn!(
err;
"Failed to remove the object storage probe object '{}' of provider '{}'",
key,
name
);
check
}
Err(err) => Err(err).context(error::ObjectStoreProbeSnafu {
name,
step: "delete",
}),
}
}
async fn verify_content(store: &ObjectStore, name: &str, key: &str, expected: &[u8]) -> Result<()> {
let got = store
.read(key)
.await
.context(error::ObjectStoreProbeSnafu { name, step: "read" })?;
if got.to_vec() != expected {
return Err(
error::ObjectStoreProbeSnafu { name, step: "read" }.into_error(ObjectStoreError::new(
ErrorKind::Unexpected,
format!("content of '{key}' differs from what was written"),
)),
);
}
Ok(())
}
/// Removes the probe object of a probe that did not finish.
///
/// It has its own short budget, and failures only log: the caller reports the timeout.
pub(crate) async fn remove_probe_object(store: &ObjectStore, prefix: &str) {
let key = probe_object_key(prefix);
match tokio::time::timeout(PROBE_CLEANUP_TIMEOUT, store.delete(&key)).await {
Ok(Ok(())) => {}
Ok(Err(err)) => warn!(
err;
"Failed to remove the object storage probe object '{}'", key
),
Err(_) => warn!(
"Timed out removing the object storage probe object '{}'",
key
),
}
}
#[cfg(test)]
mod tests {
use common_test_util::temp_dir::create_temp_dir;
use object_store::services::Fs;
use super::*;
fn new_fs_store(root: &str) -> ObjectStore {
ObjectStore::new(Fs::default().root(root)).unwrap()
}
#[tokio::test]
async fn test_probe_object_store() {
let dir = create_temp_dir("object-store-probe");
let store = new_fs_store(dir.path().to_str().unwrap());
let prefix = probe_key_prefix(1);
probe_object_store(&store, "fs", &prefix).await.unwrap();
// The lister also returns the listed directory itself, so only check that the
// probe object is gone.
let key = format!("{prefix}/probe");
let mut lister = store.lister_with(&format!("{prefix}/")).await.unwrap();
while let Some(entry) = lister.try_next().await.unwrap() {
assert_ne!(entry.path(), key);
}
}
#[tokio::test]
async fn test_probe_object_store_write_failure() {
let dir = create_temp_dir("object-store-probe-write-failure");
let root = dir.path().join("not-a-directory");
std::fs::write(&root, b"").unwrap();
let store = new_fs_store(root.to_str().unwrap());
let err = probe_object_store(&store, "broken", &probe_key_prefix(1))
.await
.unwrap_err();
assert!(
err.to_string()
.contains("probe for provider 'broken' at step 'write'")
);
}
#[tokio::test]
async fn test_remove_probe_object() {
let dir = create_temp_dir("object-store-probe-cleanup");
let store = new_fs_store(dir.path().to_str().unwrap());
let prefix = probe_key_prefix(1);
let key = probe_object_key(&prefix);
store.write(&key, PROBE_CONTENT).await.unwrap();
remove_probe_object(&store, &prefix).await;
assert!(store.read(&key).await.is_err());
}
}
+5 -3
View File
@@ -292,10 +292,12 @@ impl RegionEngine for MockRegionEngine {
fn set_region_role_with_lease(
&self,
_region_id: RegionId,
_role: RegionRole,
role: RegionRole,
_sent_at: std::time::Instant,
_deadline: std::time::Instant,
) -> Result<(), BoxedError> {
Ok(())
) -> Result<bool, BoxedError> {
// A mocked role stays, so a grant of another role is not applied.
Ok(self.mock_role.flatten().is_none_or(|mocked| mocked == role))
}
async fn set_region_role_state_gracefully(
+2 -1
View File
@@ -117,7 +117,8 @@ fn parse_version(metadata: &str) -> crate::error::Result<Option<u8>> {
}
/// Returns the remainder field of a JSON2 v2 root.
pub(crate) fn json2_remainder_field(field: &Field) -> crate::error::Result<Option<&FieldRef>> {
/// Validates the layout version and remainder type, returning `None` for legacy layouts.
pub fn json2_remainder_field(field: &Field) -> crate::error::Result<Option<&FieldRef>> {
let layout = Json2PhysicalLayout::try_from_root(field)?;
if !layout.is_version_2() {
return Ok(None);
+3 -2
View File
@@ -137,9 +137,10 @@ impl RegionEngine for FileRegionEngine {
&self,
region_id: RegionId,
role: RegionRole,
_sent_at: Instant,
_deadline: Instant,
) -> Result<(), BoxedError> {
self.set_region_role(region_id, role)
) -> Result<bool, BoxedError> {
self.set_region_role(region_id, role).map(|_| true)
}
async fn set_region_role_state_gracefully(
+1 -1
View File
@@ -5,7 +5,7 @@ edition.workspace = true
license.workspace = true
[features]
enterprise = ["common-grpc/enterprise", "session/enterprise"]
enterprise = []
[lints]
workspace = true
@@ -95,12 +95,8 @@ pub enum FrontendClient {
control_channel_manager: ChannelManager,
query: QueryOptions,
batch_opts: BatchingModeOptions,
#[cfg(feature = "enterprise")]
tracked_writes: bool,
},
Standalone {
#[cfg(feature = "enterprise")]
tracked_writes: bool,
/// for the sake of simplicity still use grpc even in standalone mode
/// notice the client here should all be lazy, so that can wait after frontend is booted then make conn
database_client: HandlerMutable,
@@ -109,26 +105,6 @@ pub enum FrontendClient {
}
impl FrontendClient {
#[cfg(feature = "enterprise")]
pub fn with_tracked_writes(&self) -> Self {
let mut client = self.clone();
match &mut client {
Self::Distributed { tracked_writes, .. } | Self::Standalone { tracked_writes, .. } => {
*tracked_writes = true;
}
}
client
}
#[cfg(feature = "enterprise")]
fn tracked_writes_enabled(&self) -> bool {
match self {
Self::Distributed { tracked_writes, .. } | Self::Standalone { tracked_writes, .. } => {
*tracked_writes
}
}
}
/// Create a new empty frontend client, with a `HandlerMutable` to set the grpc handler later
pub fn from_empty_grpc_handler(query: QueryOptions) -> (Self, HandlerMutable) {
let is_initialized = Arc::new(SetOnce::new());
@@ -140,8 +116,6 @@ impl FrontendClient {
Self::Standalone {
database_client: handler.clone(),
query,
#[cfg(feature = "enterprise")]
tracked_writes: false,
},
handler,
)
@@ -178,8 +152,6 @@ impl FrontendClient {
control_channel_manager,
query,
batch_opts,
#[cfg(feature = "enterprise")]
tracked_writes: false,
})
}
@@ -196,8 +168,6 @@ impl FrontendClient {
Self::Standalone {
database_client: handler,
query,
#[cfg(feature = "enterprise")]
tracked_writes: false,
}
}
}
@@ -235,39 +205,7 @@ impl DatabaseWithPeer {
}
}
#[cfg(feature = "enterprise")]
pub(crate) mod flow_write;
impl FrontendClient {
/// Preflight tracked-write support by opening and closing a capability without writing.
#[cfg(feature = "enterprise")]
pub async fn check_tracked_writes(&self, catalog: &str, schema: &str) -> Result<(), Error> {
if !self.tracked_writes_enabled() {
return UnexpectedSnafu {
reason: "Tracked writes are not enabled on this frontend client",
}
.fail();
}
flow_write::check_tracked_writes(self, catalog, schema).await
}
/// Execute a finite SQL write with receiver-issued completion tracking.
#[cfg(feature = "enterprise")]
pub async fn tracked_sql_write(
&self,
catalog: &str,
schema: &str,
sql: &str,
) -> Result<OutputWithMetrics, Error> {
if !self.tracked_writes_enabled() {
return UnexpectedSnafu {
reason: "Tracked writes are not enabled on this frontend client",
}
.fail();
}
flow_write::tracked_sql_write(self, catalog, schema, sql).await
}
/// scan for available frontend from metadata
pub(crate) async fn scan_for_frontend(&self) -> Result<Vec<Peer>, Error> {
let Self::Distributed { meta_client, .. } = self else {
@@ -558,33 +496,6 @@ impl FrontendClient {
peer_desc: &mut Option<PeerDesc>,
) -> Result<OutputWithMetrics, Error> {
let flow_extensions = build_flow_extensions(extensions)?;
#[cfg(feature = "enterprise")]
if self.tracked_writes_enabled() && is_tracked_insert_request(&request) {
let effective_extensions: HashMap<String, String> = extensions
.iter()
.map(|(key, value)| ((*key).to_string(), (*value).to_string()))
.collect();
if effective_extensions.contains_key(common_grpc::flow_write::COMMAND_KEY) {
return UnexpectedSnafu {
reason: "Client-supplied tracked Flow command is forbidden",
}
.fail();
}
let effective_extension_refs: Vec<(&str, &str)> = effective_extensions
.iter()
.map(|(key, value)| (key.as_str(), value.as_str()))
.collect();
return flow_write::tracked_query(
self,
catalog,
schema,
Some(request),
&effective_extension_refs,
snapshot_seqs,
peer_desc,
)
.await;
}
match self {
FrontendClient::Distributed {
query, batch_opts, ..
@@ -835,15 +746,6 @@ impl FrontendClient {
}
}
#[cfg(feature = "enterprise")]
fn is_tracked_insert_request(request: &QueryRequest) -> bool {
match request.query.as_ref() {
Some(Query::InsertIntoPlan(_)) => true,
Some(Query::Sql(sql)) => sql.trim_start().to_ascii_uppercase().starts_with("INSERT "),
_ => false,
}
}
fn build_flow_extensions(extensions: &[(&str, &str)]) -> Result<FlowQueryExtensions, Error> {
let flow_extensions = HashMap::from_iter(
extensions
@@ -1,758 +0,0 @@
// 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::HashMap;
use std::sync::Arc;
use std::time::Duration;
use api::v1::query_request::Query;
use api::v1::{QueryRequest, greptime_request::Request};
use client::OutputWithMetrics;
use common_error::ext::{BoxedError, ErrorExt};
use common_error::status_code::StatusCode;
use common_grpc::flow_write::{self, COMMAND_KEY, Command, Reply, TerminalError};
use common_query::{Output, OutputData, OutputMeta};
use common_telemetry::warn;
use session::context::{Channel, QueryContextBuilder, generate_remote_query_id};
use snafu::OptionExt;
use tokio::time::sleep;
use crate::Error;
use crate::batching_mode::frontend_client::{DatabaseWithPeer, FrontendClient, PeerDesc};
use crate::error::UnexpectedSnafu;
const RETRY_PACE: Duration = Duration::from_secs(1);
pub(crate) async fn tracked_sql_write(
frontend: &FrontendClient,
catalog: &str,
schema: &str,
sql: &str,
) -> Result<OutputWithMetrics, Error> {
tracked_query(
frontend,
catalog,
schema,
Some(QueryRequest {
query: Some(Query::Sql(sql.to_string())),
}),
&[],
&HashMap::new(),
&mut None,
)
.await
}
pub(crate) async fn check_tracked_writes(
frontend: &FrontendClient,
catalog: &str,
schema: &str,
) -> Result<(), Error> {
tracked_query(
frontend,
catalog,
schema,
None,
&[],
&HashMap::new(),
&mut None,
)
.await
.map(|_| ())
}
pub(crate) async fn tracked_query(
frontend: &FrontendClient,
catalog: &str,
schema: &str,
request: Option<QueryRequest>,
extensions: &[(&str, &str)],
snapshot_seqs: &HashMap<u64, u64>,
peer_desc: &mut Option<PeerDesc>,
) -> Result<OutputWithMetrics, Error> {
let (selected, handler, parallelism, read_preference, timeout) = match frontend {
FrontendClient::Distributed {
query, batch_opts, ..
} => (
Some(
frontend
.get_random_active_frontend(catalog, schema)
.await
.map_err(prewrite_error)?,
),
None,
query.parallelism.to_string(),
Some(batch_opts.read_preference.as_ref().to_string()),
batch_opts.experimental_flight_do_get_timeout,
),
FrontendClient::Standalone {
database_client,
query,
..
} => {
let handler = database_client
.handler
.lock()
.map_err(|e| {
prewrite_reason(
format!("Failed to lock database client: {e}"),
StatusCode::Internal,
)
})?
.as_ref()
.context(UnexpectedSnafu {
reason: "Standalone's frontend instance is not set",
})
.map_err(prewrite_error)?
.upgrade()
.context(UnexpectedSnafu {
reason: "Failed to upgrade database client",
})
.map_err(prewrite_error)?;
(
None,
Some(handler),
query.parallelism.to_string(),
None,
RETRY_PACE,
)
}
};
*peer_desc = Some(match &selected {
Some(DatabaseWithPeer { peer, .. }) => PeerDesc::Dist { peer: peer.clone() },
None => PeerDesc::Standalone,
});
let nonce = generate_remote_query_id();
let mut command = Command::Open { nonce };
let mut completion: Option<(
usize,
usize,
Option<common_recordbatch::adapter::RecordBatchMetrics>,
Option<TerminalError>,
)> = None;
loop {
let encoded = command.encode().map_err(|error| {
UnexpectedSnafu {
reason: format!("Failed to encode tracked Flow command: {error}"),
}
.build()
})?;
let mut operation_extensions: Vec<(String, String)> = extensions
.iter()
.filter(|(key, _)| *key != COMMAND_KEY)
.map(|(key, value)| ((*key).to_string(), (*value).to_string()))
.collect();
operation_extensions.push((COMMAND_KEY.to_string(), encoded));
let extension_refs: Vec<(&str, &str)> = operation_extensions
.iter()
.map(|(k, v)| (k.as_str(), v.as_str()))
.collect();
let phase_request = match &command {
Command::Write { .. } => request
.as_ref()
.context(UnexpectedSnafu {
reason: "Tracked Flow write command has no request",
})?
.clone(),
Command::Open { .. } | Command::Close { .. } => QueryRequest {
query: Some(Query::Sql(String::new())),
},
};
let response = if let Some(DatabaseWithPeer { database, .. }) = &selected {
let mut hints = vec![(
query::datafusion::QUERY_PARALLELISM_HINT,
parallelism.as_str(),
)];
if let Some(preference) = read_preference.as_deref() {
hints.push((session::hints::READ_PREFERENCE_HINT, preference));
}
database
.flight_request()
.with_hints(&hints)
.with_flow_extensions(&extension_refs)
.with_snapshot_seqs(snapshot_seqs)
.with_timeout(timeout)
.query_with_terminal_metrics(phase_request)
.await
.map(|output| output.output)
.map_err(|e| (e.status_code(), e.to_string()))
} else {
let mut ctx_extensions: HashMap<String, String> =
operation_extensions.into_iter().collect();
ctx_extensions.insert(
query::datafusion::QUERY_PARALLELISM_HINT.to_string(),
parallelism.clone(),
);
let ctx = QueryContextBuilder::default()
.current_catalog(catalog.to_string())
.current_schema(schema.to_string())
.channel(Channel::Internal)
.extensions(ctx_extensions)
.snapshot_seqs(Arc::new(std::sync::RwLock::new(snapshot_seqs.clone())))
.build();
let handler = handler.as_ref().ok_or_else(|| {
UnexpectedSnafu {
reason: "Standalone handler was not pinned",
}
.build()
})?;
handler
.do_query(Request::Query(phase_request), Arc::new(ctx))
.await
.map_err(|e| (e.status_code(), e.to_string()))
};
let reply = match response {
Ok(output) => match decode_output(output).await {
Ok(reply) => Some(reply),
Err(e) if matches!(&command, Command::Open { .. }) => {
return Err(prewrite_reason(
format!("Frontend does not support tracked Flow writes: {e}"),
StatusCode::Unsupported,
));
}
Err(e) => {
warn!("Malformed tracked Flow {:?} reply: {}", command, e);
None
}
},
Err((code, msg)) => {
// Only Open is pre-admission; definitive rejection there is safe to surface.
if matches!(&command, Command::Open { .. }) && is_definitive_rejection(code) {
return Err(prewrite_reason(
format!("Frontend rejected tracked Flow open: {msg}"),
code,
));
}
warn!(
"Tracked Flow {:?} transport failure (code={:?}): {}",
command, code, msg
);
None
}
};
match (command.clone(), reply) {
(Command::Open { .. }, Some(Reply::Opened { capability: cap })) if !cap.is_empty() => {
command = if request.is_some() {
Command::Write { capability: cap }
} else {
Command::Close { capability: cap }
};
continue;
}
(Command::Open { .. }, Some(other)) => {
return Err(prewrite_reason(
format!("Invalid tracked Flow open reply: {other:?}"),
StatusCode::InvalidArguments,
));
}
(
Command::Write { capability },
Some(Reply::Complete {
rows,
cost,
metrics,
error,
}),
) => {
completion = Some((rows, cost, metrics, error));
command = Command::Close { capability };
continue;
}
(Command::Write { .. }, Some(other)) => {
warn!("Unexpected tracked Flow write reply: {other:?}")
}
(Command::Close { .. }, Some(Reply::Closed)) => {
let Some((rows, cost, metrics, error)) = completion.take() else {
if request.is_none() {
return Ok(OutputWithMetrics::from_output(Output::new(
OutputData::AffectedRows(0),
OutputMeta::default(),
)));
}
return UnexpectedSnafu {
reason: "Close completed without positive write result",
}
.fail();
};
if let Some(error) = error {
return Err(Error::External {
source: BoxedError::new(error),
location: snafu::Location::new(file!(), line!(), column!()),
});
}
let output = OutputWithMetrics::from_output(Output::new(
OutputData::AffectedRows(rows),
OutputMeta {
cost,
..Default::default()
},
));
output.metrics.update(metrics);
return Ok(output);
}
(Command::Close { .. }, Some(other)) => {
warn!("Unexpected tracked Flow close reply: {other:?}")
}
(_, None) => {}
}
sleep(RETRY_PACE).await;
}
}
fn prewrite_error(error: Error) -> Error {
let status = error.status_code();
prewrite_reason(error.to_string(), status)
}
/// Returns true when a tracked Flow command error is a definitive, non-retryable
/// rejection from the frontend rather than an ambiguous transport failure. These
/// codes indicate the frontend itself refused the command (unsupported protocol,
/// malformed/empty command, or wrong channel), so retrying the same pinned
/// frontend can never succeed; the caller must fail fast instead of looping.
fn is_definitive_rejection(code: StatusCode) -> bool {
matches!(
code,
StatusCode::Unsupported | StatusCode::InvalidArguments | StatusCode::PermissionDenied
)
}
fn prewrite_reason(message: String, status: StatusCode) -> Error {
Error::External {
source: BoxedError::new(TerminalError {
code: status as u32,
message,
}),
location: snafu::Location::new(file!(), line!(), column!()),
}
}
async fn decode_output(output: Output) -> Result<Reply, String> {
let batches = match output.data {
OutputData::RecordBatches(batches) => batches,
OutputData::Stream(stream) => common_recordbatch::util::collect_batches(stream)
.await
.map_err(|e| e.to_string())?,
_ => return Err("tracked control request returned a non-record-batch result".to_string()),
};
flow_write::decode_reply(&batches).map_err(|e| e.to_string())
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::atomic::{AtomicUsize, Ordering};
use common_error::ext::{BoxedError, PlainError};
use common_error::status_code::StatusCode;
use session::context::QueryContextRef;
#[derive(Debug, Default)]
struct LostReplyHandler {
opens: AtomicUsize,
writes: AtomicUsize,
closes: AtomicUsize,
executions: AtomicUsize,
registry: common_grpc::flow_write::FlowWriteRegistry<String, Reply>,
capabilities: std::sync::Mutex<HashMap<String, String>>,
}
#[async_trait::async_trait]
impl super::super::GrpcQueryHandlerWithBoxedError for LostReplyHandler {
async fn do_query(
&self,
request: Request,
ctx: QueryContextRef,
) -> Result<Output, BoxedError> {
let encoded = ctx.extensions().get(COMMAND_KEY).cloned().ok_or_else(|| {
BoxedError::new(PlainError::new(
"missing command".into(),
StatusCode::Unexpected,
))
})?;
match Command::decode(&encoded).map_err(|error| {
BoxedError::new(PlainError::new(
error.to_string(),
StatusCode::InvalidArguments,
))
})? {
Command::Open { nonce } => {
let call = self.opens.fetch_add(1, Ordering::SeqCst);
let capability = self.registry.open(&nonce).unwrap();
let previous = self
.capabilities
.lock()
.unwrap()
.insert(nonce, capability.clone());
if let Some(previous) = previous {
assert_eq!(previous, capability);
}
if call == 0 {
return Err(transport_error("lost Open reply"));
}
assert_empty_sql(&request);
response(Reply::Opened { capability })
}
Command::Write { capability } => {
let sql = request_sql(&request);
let call = self.writes.fetch_add(1, Ordering::SeqCst);
let admission = self.registry.admit(&capability, sql.clone()).unwrap();
let result = match admission {
common_grpc::flow_write::Admission::Start(sender) => {
self.executions.fetch_add(1, Ordering::SeqCst);
let reply = Reply::Complete {
rows: 1,
cost: 9,
metrics: Some(common_recordbatch::adapter::RecordBatchMetrics {
region_watermarks: vec![
common_recordbatch::adapter::RegionWatermarkEntry {
region_id: 41,
watermark: Some(17),
},
],
..Default::default()
}),
error: None,
};
sender.send(Some(Arc::new(reply.clone()))).unwrap();
reply
}
common_grpc::flow_write::Admission::Join(receiver) => {
common_grpc::flow_write::wait_completion(receiver)
.await
.unwrap()
.as_ref()
.clone()
}
};
if call == 0 {
return Err(transport_error("lost Write reply"));
}
response(result)
}
Command::Close { capability } => {
let call = self.closes.fetch_add(1, Ordering::SeqCst);
self.registry.close(&capability).await.unwrap();
if call == 0 {
return Err(transport_error("lost Close reply"));
}
response(Reply::Closed)
}
}
}
}
fn request_sql(request: &Request) -> String {
match request {
Request::Query(query) => match query.query.as_ref() {
Some(Query::Sql(sql)) => sql.clone(),
other => panic!("expected SQL INSERT, got {other:?}"),
},
other => panic!("expected Query request, got {other:?}"),
}
}
fn assert_empty_sql(request: &Request) {
assert!(
matches!(request, Request::Query(QueryRequest { query: Some(Query::Sql(sql)) }) if sql.is_empty())
);
}
fn transport_error(message: &str) -> BoxedError {
BoxedError::new(PlainError::new(
message.to_string(),
StatusCode::StorageUnavailable,
))
}
fn response(reply: Reply) -> Result<Output, BoxedError> {
let batches = flow_write::reply_batches(&reply).map_err(BoxedError::new)?;
Ok(Output::new_with_record_batches(batches))
}
#[tokio::test]
async fn retries_same_open_write_and_close_capability_and_executes_once() {
let handler = Arc::new(LostReplyHandler::default());
let trait_handler: Arc<dyn super::super::GrpcQueryHandlerWithBoxedError> = handler.clone();
let weak = Arc::downgrade(&trait_handler);
let frontend =
FrontendClient::from_grpc_handler(weak, query::options::QueryOptions::default())
.with_tracked_writes();
let output = frontend
.tracked_sql_write("greptime", "public", "INSERT INTO t VALUES (7)")
.await
.unwrap();
assert!(matches!(output.output.data, OutputData::AffectedRows(1)));
assert_eq!(output.output.meta.cost, 9);
assert_eq!(
output.metrics.region_watermark_map(),
Some(HashMap::from([(41, 17)]))
);
assert_eq!(handler.opens.load(Ordering::SeqCst), 2);
assert_eq!(handler.writes.load(Ordering::SeqCst), 2);
assert_eq!(handler.closes.load(Ordering::SeqCst), 2);
assert_eq!(handler.executions.load(Ordering::SeqCst), 1);
let second = frontend
.tracked_sql_write("greptime", "public", "INSERT INTO t VALUES (8)")
.await
.unwrap();
assert!(matches!(second.output.data, OutputData::AffectedRows(1)));
assert_eq!(handler.executions.load(Ordering::SeqCst), 2);
}
/// A legacy frontend that does not understand the tracked-write extension
/// processes `Open` as an ordinary empty-SQL query and rejects it with
/// `InvalidArguments`. That is a definitive application rejection, not an
/// ambiguous transport failure: the client must fail fast instead of
/// retrying the same pinned frontend forever.
#[derive(Debug, Default)]
struct LegacyRejectHandler {
opens: AtomicUsize,
}
#[async_trait::async_trait]
impl super::super::GrpcQueryHandlerWithBoxedError for LegacyRejectHandler {
async fn do_query(
&self,
_request: Request,
_ctx: QueryContextRef,
) -> Result<Output, BoxedError> {
self.opens.fetch_add(1, Ordering::SeqCst);
Err(BoxedError::new(PlainError::new(
"empty statements".to_string(),
StatusCode::InvalidArguments,
)))
}
}
#[derive(Debug)]
struct PreflightHandler {
opens: AtomicUsize,
closes: AtomicUsize,
reject_open: bool,
}
#[async_trait::async_trait]
impl super::super::GrpcQueryHandlerWithBoxedError for PreflightHandler {
async fn do_query(
&self,
request: Request,
ctx: QueryContextRef,
) -> Result<Output, BoxedError> {
let encoded = ctx.extensions().get(COMMAND_KEY).cloned().unwrap();
assert_empty_sql(&request);
match Command::decode(&encoded).unwrap() {
Command::Open { .. } => {
self.opens.fetch_add(1, Ordering::SeqCst);
if self.reject_open {
Err(BoxedError::new(PlainError::new(
"preflight rejected".into(),
StatusCode::PermissionDenied,
)))
} else {
response(Reply::Opened {
capability: "preflight-capability".into(),
})
}
}
Command::Close { capability } => {
assert_eq!(capability, "preflight-capability");
self.closes.fetch_add(1, Ordering::SeqCst);
response(Reply::Closed)
}
Command::Write { .. } => panic!("preflight must not write"),
}
}
}
#[tokio::test]
async fn preflight_opens_and_closes_without_writing() {
let handler = Arc::new(PreflightHandler {
opens: AtomicUsize::default(),
closes: AtomicUsize::default(),
reject_open: false,
});
let trait_handler: Arc<dyn super::super::GrpcQueryHandlerWithBoxedError> = handler.clone();
let frontend = FrontendClient::from_grpc_handler(
Arc::downgrade(&trait_handler),
query::options::QueryOptions::default(),
)
.with_tracked_writes();
tokio::time::timeout(
Duration::from_secs(10),
frontend.check_tracked_writes("greptime", "public"),
)
.await
.expect("tracked-write preflight should finish within 10 seconds")
.unwrap();
assert_eq!(handler.opens.load(Ordering::SeqCst), 1);
assert_eq!(handler.closes.load(Ordering::SeqCst), 1);
}
#[tokio::test]
async fn preflight_preserves_definitive_open_error() {
let handler = Arc::new(PreflightHandler {
opens: AtomicUsize::default(),
closes: AtomicUsize::default(),
reject_open: true,
});
let trait_handler: Arc<dyn super::super::GrpcQueryHandlerWithBoxedError> = handler.clone();
let frontend = FrontendClient::from_grpc_handler(
Arc::downgrade(&trait_handler),
query::options::QueryOptions::default(),
)
.with_tracked_writes();
let error = tokio::time::timeout(
Duration::from_secs(10),
frontend.check_tracked_writes("greptime", "public"),
)
.await
.expect("tracked-write preflight rejection should finish within 10 seconds")
.unwrap_err();
assert_eq!(error.status_code(), StatusCode::PermissionDenied);
assert!(matches!(
&error,
Error::External { source, .. }
if source.as_any().downcast_ref::<TerminalError>().is_some_and(|terminal| {
terminal.code == StatusCode::PermissionDenied as u32
&& terminal.message.contains("preflight rejected")
})
));
assert_eq!(handler.opens.load(Ordering::SeqCst), 1);
assert_eq!(handler.closes.load(Ordering::SeqCst), 0);
}
#[derive(Debug)]
struct RejectionRetryHandler {
status: StatusCode,
opens: AtomicUsize,
writes: AtomicUsize,
closes: AtomicUsize,
capability: std::sync::Mutex<Option<String>>,
}
#[async_trait::async_trait]
impl super::super::GrpcQueryHandlerWithBoxedError for RejectionRetryHandler {
async fn do_query(
&self,
request: Request,
ctx: QueryContextRef,
) -> Result<Output, BoxedError> {
let encoded = ctx.extensions().get(COMMAND_KEY).cloned().unwrap();
match Command::decode(&encoded).unwrap() {
Command::Open { nonce } => {
assert_empty_sql(&request);
self.opens.fetch_add(1, Ordering::SeqCst);
let mut capability = self.capability.lock().unwrap();
let value = capability.get_or_insert_with(|| nonce);
response(Reply::Opened {
capability: value.clone(),
})
}
Command::Write { capability } => {
assert_eq!(request_sql(&request), "INSERT INTO t VALUES (11)");
assert_eq!(self.capability.lock().unwrap().as_ref(), Some(&capability));
if self.writes.fetch_add(1, Ordering::SeqCst) == 0 {
Err(BoxedError::new(PlainError::new(
"write rejection".into(),
self.status,
)))
} else {
response(Reply::Complete {
rows: 2,
cost: 0,
metrics: None,
error: None,
})
}
}
Command::Close { capability } => {
assert_empty_sql(&request);
assert_eq!(self.capability.lock().unwrap().as_ref(), Some(&capability));
if self.closes.fetch_add(1, Ordering::SeqCst) == 0 {
Err(BoxedError::new(PlainError::new(
"close rejection".into(),
self.status,
)))
} else {
response(Reply::Closed)
}
}
}
}
}
#[tokio::test]
async fn post_admission_rejections_retry_same_capability_until_close() {
for status in [
StatusCode::Unsupported,
StatusCode::InvalidArguments,
StatusCode::PermissionDenied,
] {
let handler = Arc::new(RejectionRetryHandler {
status,
opens: AtomicUsize::default(),
writes: AtomicUsize::default(),
closes: AtomicUsize::default(),
capability: std::sync::Mutex::new(None),
});
let trait_handler: Arc<dyn super::super::GrpcQueryHandlerWithBoxedError> =
handler.clone();
let frontend = FrontendClient::from_grpc_handler(
Arc::downgrade(&trait_handler),
query::options::QueryOptions::default(),
)
.with_tracked_writes();
let output = tokio::time::timeout(
Duration::from_secs(10),
frontend.tracked_sql_write("greptime", "public", "INSERT INTO t VALUES (11)"),
)
.await
.expect("post-admission retries should finish within 10 seconds")
.unwrap();
assert!(matches!(output.output.data, OutputData::AffectedRows(2)));
assert_eq!(handler.opens.load(Ordering::SeqCst), 1);
assert_eq!(handler.writes.load(Ordering::SeqCst), 2);
assert_eq!(handler.closes.load(Ordering::SeqCst), 2);
}
}
#[tokio::test]
async fn fails_fast_on_definitive_open_rejection() {
let handler = Arc::new(LegacyRejectHandler::default());
let trait_handler: Arc<dyn super::super::GrpcQueryHandlerWithBoxedError> = handler.clone();
let weak = Arc::downgrade(&trait_handler);
let frontend =
FrontendClient::from_grpc_handler(weak, query::options::QueryOptions::default())
.with_tracked_writes();
let result = tokio::time::timeout(
Duration::from_secs(10),
frontend.tracked_sql_write("greptime", "public", "INSERT INTO t VALUES (7)"),
)
.await
.expect("definitive Open rejection should finish within 10 seconds");
let err = result.expect_err("definitive Open rejection must not be retried forever");
assert_eq!(err.status_code(), StatusCode::InvalidArguments);
// The durable-execution layer keys repair off a TerminalError inside
// Error::External; pin that exact shape so a refactor cannot silently
// downgrade the rejection to an unresolved (permanently stalled) error.
assert!(
matches!(&err, Error::External { source, .. } if source.as_any().is::<common_grpc::flow_write::TerminalError>()),
"expected Error::External carrying TerminalError, got {err:?}"
);
assert_eq!(
handler.opens.load(Ordering::SeqCst),
1,
"Open must not be retried after a definitive rejection"
);
}
}
-2
View File
@@ -7,8 +7,6 @@ license.workspace = true
[features]
testing = []
enterprise = [
"common-grpc/enterprise",
"session/enterprise",
"common-meta/enterprise",
"operator/enterprise",
"sql/enterprise",
-31
View File
@@ -17,8 +17,6 @@ mod copy_in;
mod dashboard;
mod entity_graph;
mod export_database;
#[cfg(feature = "enterprise")]
mod flow_write;
mod grpc;
mod import_packed;
mod influxdb;
@@ -136,13 +134,6 @@ pub struct Instance {
trace_aux_limiter: Option<RequestLimiter>,
otlp_resource_info: bool,
suspend: Arc<AtomicBool>,
#[cfg(feature = "enterprise")]
flow_write_registry: Arc<
common_grpc::flow_write::FlowWriteRegistry<
flow_write::WritePayload,
common_grpc::flow_write::Reply,
>,
>,
}
impl Instance {
@@ -332,17 +323,6 @@ impl Instance {
timeout_recorder,
);
#[cfg(feature = "enterprise")]
let result = if query_ctx.channel() == Channel::Internal
&& query_ctx.extension(common_grpc::flow_write::CHILD_KEY) == Some("1")
{
query_fut.await
} else {
CancellableFuture::new(query_fut, ticket.cancellation_handle.clone())
.await
.map_err(|_| error::CancelledSnafu.build())?
};
#[cfg(not(feature = "enterprise"))]
let result = CancellableFuture::new(query_fut, ticket.cancellation_handle.clone())
.await
.map_err(|_| error::CancelledSnafu.build())?;
@@ -913,17 +893,6 @@ impl Instance {
let query_fut = self.exec_plan_with_timeout(plan, query_ctx.clone(), timeout_recorder);
#[cfg(feature = "enterprise")]
let result = if query_ctx.channel() == Channel::Internal
&& query_ctx.extension(common_grpc::flow_write::CHILD_KEY) == Some("1")
{
query_fut.await
} else {
CancellableFuture::new(query_fut, ticket.cancellation_handle.clone())
.await
.map_err(|_| error::CancelledSnafu.build())?
};
#[cfg(not(feature = "enterprise"))]
let result = CancellableFuture::new(query_fut, ticket.cancellation_handle.clone())
.await
.map_err(|_| error::CancelledSnafu.build())?;
-2
View File
@@ -438,8 +438,6 @@ impl FrontendBuilder {
trace_aux_limiter,
otlp_resource_info: self.options.otlp.experimental_enable_resource_info,
suspend: Arc::new(AtomicBool::new(false)),
#[cfg(feature = "enterprise")]
flow_write_registry: Default::default(),
})
}
}
-227
View File
@@ -1,227 +0,0 @@
// 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::{greptime_request::Request, query_request::Query};
use common_error::ext::ErrorExt;
use common_grpc::flow_write::{
Admission, CHILD_KEY, COMMAND_KEY, Command, Reply, TerminalError, wait_completion,
};
use common_query::{Output, OutputData};
use servers::error::{self as server_error, Error as ServerError};
use servers::interceptor::GrpcQueryInterceptor;
use servers::query_handler::grpc::GrpcQueryHandler;
use session::context::QueryContextRef;
use crate::instance::Instance;
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct WritePayload {
request: Request,
catalog: String,
schema: String,
snapshots: Vec<(u64, u64)>,
sst_min_sequences: Vec<(u64, u64)>,
extensions: Vec<(String, String)>,
}
impl WritePayload {
fn new(request: &Request, ctx: &QueryContextRef) -> Result<Self, String> {
if !is_finite_insert(request) {
return Err("tracked flow writes require INSERT or InsertIntoPlan".to_string());
}
let mut snapshots: Vec<_> = ctx.snapshots().into_iter().collect();
snapshots.sort_unstable();
let mut sst_min_sequences: Vec<_> = ctx.sst_min_sequences().into_iter().collect();
sst_min_sequences.sort_unstable();
let mut extensions: Vec<_> = ctx
.extensions()
.into_iter()
.filter(|(key, _)| {
key != COMMAND_KEY
&& key != CHILD_KEY
&& key != session::context::REMOTE_QUERY_ID_EXTENSION_KEY
})
.collect();
extensions.sort_unstable();
Ok(Self {
request: request.clone(),
catalog: ctx.current_catalog().to_string(),
schema: ctx.current_schema(),
snapshots,
sst_min_sequences,
extensions,
})
}
}
fn is_finite_insert(request: &Request) -> bool {
match request {
Request::Query(query) => match query.query.as_ref() {
Some(Query::InsertIntoPlan(_)) => true,
Some(Query::Sql(sql)) => sql.split_whitespace().next().is_some_and(|statement| {
statement
.trim_end_matches(';')
.eq_ignore_ascii_case("INSERT")
}),
_ => false,
},
_ => false,
}
}
impl Instance {
fn intercept_control(
&self,
request: &Request,
ctx: &QueryContextRef,
) -> server_error::Result<()> {
let interceptor = self
.plugins
.get::<servers::interceptor::GrpcQueryInterceptorRef<crate::error::Error>>();
interceptor
.as_ref()
.pre_execute(request, ctx.clone())
.map_err(|error| ServerError::ExecuteQuery {
source: common_error::ext::BoxedError::new(error),
location: snafu::Location::new(file!(), line!(), column!()),
})
}
pub(crate) async fn handle_flow_write_request(
&self,
request: Request,
ctx: QueryContextRef,
encoded_command: String,
) -> server_error::Result<Output> {
let command = Command::decode(&encoded_command).map_err(|e| ServerError::InvalidQuery {
reason: e.to_string(),
location: snafu::Location::new(file!(), line!(), column!()),
})?;
let reply = match command {
Command::Open { nonce } => {
self.intercept_control(&request, &ctx)?;
if !is_empty_control(&request) {
return Err(ServerError::InvalidQuery {
reason: "Open requires an empty SQL request".into(),
location: snafu::Location::new(file!(), line!(), column!()),
});
}
Reply::Opened {
capability: self
.flow_write_registry
.open(&nonce)
.map_err(registry_error)?,
}
}
Command::Close { capability } => {
self.intercept_control(&request, &ctx)?;
if !is_empty_control(&request) {
return Err(ServerError::InvalidQuery {
reason: "Close requires an empty SQL request".into(),
location: snafu::Location::new(file!(), line!(), column!()),
});
}
self.flow_write_registry
.close(&capability)
.await
.map_err(registry_error)?;
Reply::Closed
}
Command::Write { capability } => {
let payload = WritePayload::new(&request, &ctx).map_err(|reason| {
ServerError::InvalidQuery {
reason,
location: snafu::Location::new(file!(), line!(), column!()),
}
})?;
match self
.flow_write_registry
.admit(&capability, payload)
.map_err(registry_error)?
{
Admission::Join(receiver) => {
(*wait_completion(receiver).await.map_err(registry_error)?).clone()
}
Admission::Start(sender) => {
let receiver = sender.subscribe();
let instance = self.clone();
let mut child_ctx = (*ctx).clone();
child_ctx.remove_extension(COMMAND_KEY);
child_ctx.set_extension(CHILD_KEY, "1");
let child_ctx = Arc::new(child_ctx);
common_runtime::spawn_global(async move {
let terminal = match instance.do_query(request, child_ctx).await {
Ok(output) => terminal_reply(output),
Err(error) => Reply::Complete {
rows: 0,
cost: 0,
metrics: None,
error: Some(TerminalError {
code: error.status_code() as u32,
message: error.output_msg(),
}),
},
};
let _ = sender.send(Some(Arc::new(terminal)));
});
(*wait_completion(receiver).await.map_err(registry_error)?).clone()
}
}
}
};
let batches = common_grpc::flow_write::reply_batches(&reply).map_err(|e| {
ServerError::InvalidQuery {
reason: e.to_string(),
location: snafu::Location::new(file!(), line!(), column!()),
}
})?;
Ok(Output::new_with_record_batches(batches))
}
}
fn is_empty_control(request: &Request) -> bool {
matches!(request, Request::Query(query) if matches!(&query.query, Some(Query::Sql(sql)) if sql.trim().is_empty()))
}
fn terminal_reply(output: Output) -> Reply {
let (rows, cost) = output.extract_rows_and_cost();
let metrics = output
.meta
.plan
.clone()
.and_then(query::metrics::terminal_recordbatch_metrics_from_plan);
match output.data {
OutputData::AffectedRows(_) => Reply::Complete {
rows,
cost,
metrics,
error: None,
},
_ => Reply::Complete {
rows: 0,
cost,
metrics,
error: Some(TerminalError {
code: 1001,
message: "tracked INSERT did not produce finite affected rows".into(),
}),
},
}
}
fn registry_error(error: common_grpc::flow_write::RegistryError) -> ServerError {
ServerError::InvalidQuery {
reason: format!("flow write capability rejected: {error:?}"),
location: snafu::Location::new(file!(), line!(), column!()),
}
}
-14
View File
@@ -66,20 +66,6 @@ impl GrpcQueryHandler for Instance {
request: Request,
ctx: QueryContextRef,
) -> server_error::Result<Output> {
#[cfg(feature = "enterprise")]
if let Some(command) = ctx
.extension(common_grpc::flow_write::COMMAND_KEY)
.map(str::to_string)
{
if ctx.channel() != session::context::Channel::Internal {
return Err(server_error::Error::InvalidQuery {
reason: "flow write commands are only accepted on the internal channel".into(),
location: snafu::Location::new(file!(), line!(), column!()),
});
}
return self.handle_flow_write_request(request, ctx, command).await;
}
let result: Result<Output> = async {
let interceptor_ref = self.plugins.get::<GrpcQueryInterceptorRef<Error>>();
let interceptor = interceptor_ref.as_ref();
+1
View File
@@ -429,6 +429,7 @@ where
user_provider.clone(),
Some(self.instance.process_manager().clone()),
)
.with_influxdb_handler(instance.clone())
.with_batching_enabled(postgres_batching),
) as Box<dyn Server>;
+458 -53
View File
@@ -40,7 +40,8 @@ use crate::kafka::consumer::{ConsumerBuilder, RecordsBuffer, RegionWalRange};
use crate::kafka::periodic_offset_fetcher::PeriodicOffsetFetcher;
use crate::kafka::producer::OrderedBatchProducerRef;
use crate::kafka::util::record::{
ESTIMATED_META_SIZE, Record, convert_to_kafka_records, maybe_emit_entry, remaining_entries,
ESTIMATED_META_SIZE, Record, convert_to_kafka_records, is_record_meta_key, maybe_emit_entry,
remaining_entries,
};
use crate::metrics;
@@ -408,26 +409,41 @@ impl LogStore for KafkaLogStore {
);
// Ignores no-op records.
if kafka_record.value.is_none() {
if check_termination(offset, end_offset) {
if let Some(entries) = remaining_entries(&provider, &mut entry_records) {
yield Ok(entries);
if kafka_record.value.is_some() {
let key = kafka_record.key;
match Record::try_from_parts(key.as_deref(), kafka_record.value) {
Ok(record) => {
// Tries to construct an entry from records consumed so far.
if let Some(mut entry) =
maybe_emit_entry(&provider, record, &mut entry_records)?
{
// We don't rely on the EntryId generated by mito2.
// Instead, we use the offset return from Kafka as EntryId.
// Therefore, we MUST overwrite the EntryId with RecordOffset.
entry.set_entry_id(offset as u64);
yield Ok(vec![entry]);
}
}
Err(err) => {
// A key that cannot be decoded is skipped only when the log store
// never wrote it. A key that is a JSON object with a `version`
// field may be a `RecordMeta` written by an incompatible version,
// for example one with a newer `RecordType` variant read after a
// rollback or during a rolling upgrade; skipping it would lose the
// entry once the WAL is pruned past its offset, so it stays fatal.
if key.as_deref().is_some_and(is_record_meta_key) {
yield Err(err);
return;
}
warn!(
"Skipping unparsable record at offset {} of topic {}, reason: {}",
offset, provider.topic, err
);
}
break;
}
continue;
}
let record = Record::try_from(kafka_record)?;
// Tries to construct an entry from records consumed so far.
if let Some(mut entry) = maybe_emit_entry(&provider, record, &mut entry_records)? {
// We don't rely on the EntryId generated by mito2.
// Instead, we use the offset return from Kafka as EntryId.
// Therefore, we MUST overwrite the EntryId with RecordOffset.
entry.set_entry_id(offset as u64);
yield Ok(vec![entry]);
}
// The termination check runs for every consumed record, including skipped ones.
if check_termination(offset, end_offset) {
if let Some(entries) = remaining_entries(&provider, &mut entry_records) {
yield Ok(entries);
@@ -529,21 +545,25 @@ mod tests {
use common_base::readable_size::ReadableSize;
use common_meta::datanode::TopicStatsReporter;
use common_telemetry::info;
use common_telemetry::tracing::warn;
use common_wal::config::kafka::DatanodeKafkaConfig;
use common_wal::config::kafka::common::KafkaConnectionConfig;
use common_wal::maybe_skip_kafka_integration_test;
use common_wal::test_util::get_kafka_endpoints;
use dashmap::DashMap;
use futures::TryStreamExt;
use rand::Rng;
use rand::prelude::SliceRandom;
use rskafka::client::partition::OffsetAt;
use rskafka::client::partition::{Compression, OffsetAt};
use rskafka::record::Record as KafkaRecord;
use store_api::logstore::LogStore;
use store_api::logstore::entry::{Entry, MultiplePartEntry, MultiplePartHeader, NaiveEntry};
use store_api::logstore::provider::Provider;
use store_api::storage::RegionId;
use super::build_entry;
use crate::error;
use crate::kafka::log_store::{KafkaLogStore, PeriodicTopicStatsReporter, TopicStat};
use crate::kafka::util::record::{ESTIMATED_META_SIZE, convert_to_kafka_records};
#[test]
fn test_build_naive_entry() {
@@ -630,26 +650,76 @@ mod tests {
.unwrap();
}
async fn new_test_logstore(max_batch_bytes: ReadableSize) -> KafkaLogStore {
let config = DatanodeKafkaConfig {
connection: KafkaConnectionConfig {
broker_endpoints: get_kafka_endpoints(),
..Default::default()
},
max_batch_bytes,
..Default::default()
};
KafkaLogStore::try_new(&config).await.unwrap()
}
async fn produce_records(
logstore: &KafkaLogStore,
provider: &Provider,
records: Vec<KafkaRecord>,
) {
// A freshly created topic can be missing from the broker's metadata for a short
// while; `try_create_client` already retries that case.
let client = logstore
.client_manager
.get_or_insert(provider.as_kafka_provider().unwrap())
.await
.unwrap()
.client()
.clone();
client
.produce(records, Compression::NoCompression)
.await
.unwrap();
}
/// Builds a record that was not written by this log store.
fn foreign_record(key: Option<&[u8]>) -> KafkaRecord {
KafkaRecord {
key: key.map(|key| key.to_vec()),
value: Some(b"foreign payload".to_vec()),
timestamp: chrono::Utc::now(),
headers: Default::default(),
}
}
/// Returns the log end offset of the topic, i.e. the exclusive end of the range that
/// `read` consumes.
async fn log_end_offset(logstore: &KafkaLogStore, provider: &Provider) -> i64 {
let client = logstore
.client_manager
.get_or_insert(provider.as_kafka_provider().unwrap())
.await
.unwrap();
client.client().get_offset(OffsetAt::Latest).await.unwrap()
}
/// Returns one record per kind of key that the log store never writes: a missing key, a
/// key that is not JSON, a JSON value that is not an object, and a JSON object without a
/// `version` field.
fn foreign_records() -> Vec<KafkaRecord> {
vec![
foreign_record(None),
foreign_record(Some(b"not-a-json-key")),
foreign_record(Some(b"[1, 2, 3]")),
foreign_record(Some(br#"{"hello": "world"}"#)),
]
}
#[tokio::test]
async fn test_append_batch_basic() {
common_telemetry::init_default_ut_logging();
let Ok(broker_endpoints) = std::env::var("GT_KAFKA_ENDPOINTS") else {
warn!("The endpoints is empty, skipping the test 'test_append_batch_basic'");
return;
};
let broker_endpoints = broker_endpoints
.split(',')
.map(|s| s.trim().to_string())
.collect::<Vec<_>>();
let config = DatanodeKafkaConfig {
connection: KafkaConnectionConfig {
broker_endpoints,
..Default::default()
},
max_batch_bytes: ReadableSize::kb(32),
..Default::default()
};
let logstore = KafkaLogStore::try_new(&config).await.unwrap();
maybe_skip_kafka_integration_test!();
let logstore = new_test_logstore(ReadableSize::kb(32)).await;
let topic_name = uuid::Uuid::new_v4().to_string();
prepare_topic(&logstore, &topic_name).await;
let provider = Provider::kafka_provider(topic_name);
@@ -715,25 +785,10 @@ mod tests {
#[tokio::test]
async fn test_append_batch_basic_large() {
common_telemetry::init_default_ut_logging();
let Ok(broker_endpoints) = std::env::var("GT_KAFKA_ENDPOINTS") else {
warn!("The endpoints is empty, skipping the test 'test_append_batch_basic_large'");
return;
};
maybe_skip_kafka_integration_test!();
let data_size_kb = rand::rng().random_range(9..31usize);
info!("Entry size: {}Ki", data_size_kb);
let broker_endpoints = broker_endpoints
.split(',')
.map(|s| s.trim().to_string())
.collect::<Vec<_>>();
let config = DatanodeKafkaConfig {
connection: KafkaConnectionConfig {
broker_endpoints,
..Default::default()
},
max_batch_bytes: ReadableSize::kb(8),
..Default::default()
};
let logstore = KafkaLogStore::try_new(&config).await.unwrap();
let logstore = new_test_logstore(ReadableSize::kb(8)).await;
let topic_name = uuid::Uuid::new_v4().to_string();
prepare_topic(&logstore, &topic_name).await;
let provider = Provider::kafka_provider(topic_name);
@@ -788,6 +843,356 @@ mod tests {
assert_eq!(high_wathermark, (data_size_kb as u64 / 8 + 1) * 20 * 5 - 1);
}
#[tokio::test]
async fn test_read_skips_unparsable_record_inside_multipart_entry() {
maybe_skip_kafka_integration_test!();
let logstore = new_test_logstore(ReadableSize::kb(8)).await;
let topic_name = uuid::Uuid::new_v4().to_string();
prepare_topic(&logstore, &topic_name).await;
let provider = Provider::kafka_provider(topic_name);
let region_id = RegionId::new(1, 1);
// Splits the entry into First, Middle(1) and Last.
let max_data_size = 8 * 1024 - ESTIMATED_META_SIZE;
let data = vec![7u8; max_data_size * 2 + 10];
let entry = logstore
.entry(data.clone(), 0, region_id, &provider)
.unwrap();
assert_matches!(entry, Entry::MultiplePart(_));
let mut records = convert_to_kafka_records(entry).unwrap();
assert_eq!(records.len(), 3);
let last = records.pop().unwrap();
// Places an unparsable record before the entry and between every pair of parts.
produce_records(
&logstore,
&provider,
vec![foreign_record(Some(b"not-a-json-key"))],
)
.await;
produce_records(&logstore, &provider, vec![records[0].clone()]).await;
produce_records(
&logstore,
&provider,
vec![foreign_record(Some(br#"{"hello": "world"}"#))],
)
.await;
produce_records(&logstore, &provider, vec![records[1].clone()]).await;
produce_records(
&logstore,
&provider,
vec![foreign_record(Some(b"not-a-json-key"))],
)
.await;
produce_records(&logstore, &provider, vec![last]).await;
let entries = logstore
.read(&provider, 0)
.await
.unwrap()
.try_collect::<Vec<_>>()
.await
.unwrap()
.into_iter()
.flatten()
.collect::<Vec<_>>();
assert_eq!(entries.len(), 1);
let entry = entries
.into_iter()
.next()
.unwrap()
.into_multiple_part_entry()
.unwrap();
assert_eq!(
entry.headers,
vec![
MultiplePartHeader::First,
MultiplePartHeader::Middle(1),
MultiplePartHeader::Last
]
);
assert_eq!(entry.parts.concat(), data);
}
#[tokio::test]
async fn test_read_skips_unparsable_record_across_regions() {
maybe_skip_kafka_integration_test!();
let logstore = new_test_logstore(ReadableSize::kb(8)).await;
let topic_name = uuid::Uuid::new_v4().to_string();
prepare_topic(&logstore, &topic_name).await;
let provider = Provider::kafka_provider(topic_name);
let region_a = RegionId::new(1, 1);
let region_b = RegionId::new(1, 2);
let max_data_size = 8 * 1024 - ESTIMATED_META_SIZE;
let data_a = vec![1u8; max_data_size * 2 + 10];
let data_b = vec![2u8; max_data_size * 2 + 10];
let records_a = convert_to_kafka_records(
logstore
.entry(data_a.clone(), 0, region_a, &provider)
.unwrap(),
)
.unwrap();
let records_b = convert_to_kafka_records(
logstore
.entry(data_b.clone(), 0, region_b, &provider)
.unwrap(),
)
.unwrap();
assert_eq!(records_a.len(), 3);
assert_eq!(records_b.len(), 3);
// Interleaves the parts of both entries with unparsable records.
for i in 0..3 {
produce_records(&logstore, &provider, vec![records_a[i].clone()]).await;
produce_records(&logstore, &provider, vec![records_b[i].clone()]).await;
produce_records(
&logstore,
&provider,
vec![foreign_record(Some(b"not-a-json-key"))],
)
.await;
}
let entries = logstore
.read(&provider, 0)
.await
.unwrap()
.try_collect::<Vec<_>>()
.await
.unwrap()
.into_iter()
.flatten()
.collect::<Vec<_>>();
assert_eq!(entries.len(), 2);
let mut entries = entries
.into_iter()
.map(|entry| (entry.region_id(), entry.into_multiple_part_entry().unwrap()))
.collect::<HashMap<_, _>>();
assert_eq!(entries.remove(&region_a).unwrap().parts.concat(), data_a);
assert_eq!(entries.remove(&region_b).unwrap().parts.concat(), data_b);
assert!(entries.is_empty());
}
#[tokio::test]
async fn test_read_finishes_when_last_record_is_unparsable() {
maybe_skip_kafka_integration_test!();
let logstore = new_test_logstore(ReadableSize::kb(32)).await;
let topic_name = uuid::Uuid::new_v4().to_string();
prepare_topic(&logstore, &topic_name).await;
let provider = Provider::kafka_provider(topic_name);
let region_id = RegionId::new(1, 1);
let mut expected = generate_entries(&logstore, &provider, 3, region_id, 128);
logstore.append_batch(expected.clone()).await.unwrap();
// Appends an unparsable record as the last record of the read range.
produce_records(
&logstore,
&provider,
vec![foreign_record(Some(b"not-a-json-key"))],
)
.await;
let entries = tokio::time::timeout(
Duration::from_secs(30),
logstore
.read(&provider, 0)
.await
.unwrap()
.try_collect::<Vec<_>>(),
)
.await
.expect("read should finish after skipping the unparsable record")
.unwrap()
.into_iter()
.flatten()
.collect::<Vec<_>>();
expected.iter_mut().for_each(|entry| entry.set_entry_id(0));
let mut entries = entries;
entries.iter_mut().for_each(|entry| entry.set_entry_id(0));
assert_eq!(entries, expected);
}
#[tokio::test]
async fn test_read_skips_foreign_records_of_every_kind() {
maybe_skip_kafka_integration_test!();
let logstore = new_test_logstore(ReadableSize::kb(32)).await;
let topic_name = uuid::Uuid::new_v4().to_string();
prepare_topic(&logstore, &topic_name).await;
let provider = Provider::kafka_provider(topic_name);
// Places every kind of unparsable record before the first entry.
for record in foreign_records() {
produce_records(&logstore, &provider, vec![record]).await;
}
let region_id = RegionId::new(1, 1);
let mut expected = generate_entries(&logstore, &provider, 1, region_id, 128);
logstore.append_batch(expected.clone()).await.unwrap();
let entries = logstore
.read(&provider, 0)
.await
.unwrap()
.try_collect::<Vec<_>>()
.await
.unwrap()
.into_iter()
.flatten()
.collect::<Vec<_>>();
expected.iter_mut().for_each(|entry| entry.set_entry_id(0));
let mut entries = entries;
entries.iter_mut().for_each(|entry| entry.set_entry_id(0));
assert_eq!(entries, expected);
}
#[tokio::test]
async fn test_read_finishes_when_topic_only_has_foreign_records() {
maybe_skip_kafka_integration_test!();
let logstore = new_test_logstore(ReadableSize::kb(32)).await;
let topic_name = uuid::Uuid::new_v4().to_string();
prepare_topic(&logstore, &topic_name).await;
let provider = Provider::kafka_provider(topic_name);
for record in foreign_records() {
produce_records(&logstore, &provider, vec![record]).await;
}
// Asserts the read range covers the produced records; an empty range would let `read`
// return without exercising the skip path.
assert_eq!(log_end_offset(&logstore, &provider).await, 4);
let entries = tokio::time::timeout(
Duration::from_secs(30),
logstore
.read(&provider, 0)
.await
.unwrap()
.try_collect::<Vec<_>>(),
)
.await
.expect("read should finish after skipping all unparsable records")
.unwrap();
assert!(entries.into_iter().flatten().next().is_none());
}
#[tokio::test]
async fn test_read_fails_on_incompatible_record_meta() {
maybe_skip_kafka_integration_test!();
let logstore = new_test_logstore(ReadableSize::kb(32)).await;
// Keys that look like a `RecordMeta` but cannot be decoded by this version. They may
// come from an incompatible version of the log store, so the read must not skip them.
let keys: [&[u8]; 2] = [
// A `RecordType` variant this version does not know.
br#"{"version": 0, "tp": "Compressed", "entry_id": 0, "ns": {"region_id": 1, "topic": ""}}"#,
// A field with the wrong type.
br#"{"version": "0", "tp": "Full", "entry_id": 0, "ns": {"region_id": 1, "topic": ""}}"#,
];
for key in keys {
let topic_name = uuid::Uuid::new_v4().to_string();
prepare_topic(&logstore, &topic_name).await;
let provider = Provider::kafka_provider(topic_name);
produce_records(&logstore, &provider, vec![foreign_record(Some(key))]).await;
let err = logstore
.read(&provider, 0)
.await
.unwrap()
.try_collect::<Vec<Vec<Entry>>>()
.await
.unwrap_err();
assert_matches!(err, error::Error::DecodeJson { .. });
}
}
#[tokio::test]
async fn test_read_fails_on_missing_middle_part() {
maybe_skip_kafka_integration_test!();
let logstore = new_test_logstore(ReadableSize::kb(8)).await;
let topic_name = uuid::Uuid::new_v4().to_string();
prepare_topic(&logstore, &topic_name).await;
let provider = Provider::kafka_provider(topic_name);
let region_id = RegionId::new(1, 1);
// Splits the entry into First, Middle(1), Middle(2) and Last.
let max_data_size = 8 * 1024 - ESTIMATED_META_SIZE;
let data = vec![7u8; max_data_size * 3 + 10];
let entry = logstore.entry(data, 0, region_id, &provider).unwrap();
let records = convert_to_kafka_records(entry).unwrap();
assert_eq!(records.len(), 4);
// Only a missing part of an entry we wrote is fatal; a foreign record is skipped
// because it cannot be one of our parts.
produce_records(
&logstore,
&provider,
vec![foreign_record(Some(b"not-a-json-key"))],
)
.await;
produce_records(&logstore, &provider, vec![records[0].clone()]).await;
produce_records(&logstore, &provider, vec![records[2].clone()]).await;
let err = logstore
.read(&provider, 0)
.await
.unwrap()
.try_collect::<Vec<Vec<Entry>>>()
.await
.unwrap_err();
assert_matches!(err, error::Error::IllegalSequence { .. });
}
#[tokio::test]
async fn test_read_succeeds_on_two_part_entry() {
maybe_skip_kafka_integration_test!();
let logstore = new_test_logstore(ReadableSize::kb(8)).await;
let topic_name = uuid::Uuid::new_v4().to_string();
prepare_topic(&logstore, &topic_name).await;
let provider = Provider::kafka_provider(topic_name);
let region_id = RegionId::new(1, 1);
// Splits the entry into First and Last, without any middle part.
let max_data_size = 8 * 1024 - ESTIMATED_META_SIZE;
let data = vec![7u8; max_data_size + 10];
let entry = logstore
.entry(data.clone(), 0, region_id, &provider)
.unwrap();
let records = convert_to_kafka_records(entry).unwrap();
assert_eq!(records.len(), 2);
for record in records {
produce_records(&logstore, &provider, vec![record]).await;
}
let entries = logstore
.read(&provider, 0)
.await
.unwrap()
.try_collect::<Vec<_>>()
.await
.unwrap()
.into_iter()
.flatten()
.collect::<Vec<_>>();
assert_eq!(entries.len(), 1);
let entry = entries
.into_iter()
.next()
.unwrap()
.into_multiple_part_entry()
.unwrap();
assert_eq!(
entry.headers,
vec![MultiplePartHeader::First, MultiplePartHeader::Last]
);
assert_eq!(entry.parts.concat(), data);
}
#[tokio::test]
async fn test_topic_stats_reporter() {
common_telemetry::init_default_ut_logging();
+45 -7
View File
@@ -108,17 +108,32 @@ impl TryFrom<Record> for KafkaRecord {
}
// TODO(niebayes): improve the performance of decoding kafka record.
impl TryFrom<KafkaRecord> for Record {
type Error = crate::error::Error;
fn try_from(kafka_record: KafkaRecord) -> Result<Self> {
let key = kafka_record.key.context(MissingKeySnafu)?;
let meta = serde_json::from_slice(&key).context(DecodeJsonSnafu)?;
let data = kafka_record.value.context(MissingValueSnafu)?;
impl Record {
/// Decodes a record from the key and value of a [`KafkaRecord`].
///
/// The key is borrowed so that callers can inspect it if decoding fails, e.g. to
/// tell a foreign key apart from a [`RecordMeta`] written by an incompatible version
/// of the log store.
pub(crate) fn try_from_parts(key: Option<&[u8]>, value: Option<Vec<u8>>) -> Result<Self> {
let key = key.context(MissingKeySnafu)?;
let meta = serde_json::from_slice(key).context(DecodeJsonSnafu)?;
let data = value.context(MissingValueSnafu)?;
Ok(Self { meta, data })
}
}
/// Returns whether a key is a JSON object with a `version` field, i.e. whether it may have
/// been written as a [`RecordMeta`] key.
///
/// A `RecordMeta` key that cannot be decoded may come from an incompatible version of the
/// log store, so the reader must not treat such a key as a foreign record.
pub(crate) fn is_record_meta_key(key: &[u8]) -> bool {
matches!(
serde_json::from_slice::<serde_json::Value>(key),
Ok(serde_json::Value::Object(fields)) if fields.contains_key("version")
)
}
pub(crate) fn convert_to_kafka_records(entry: Entry) -> Result<Vec<KafkaRecord>> {
match entry {
Entry::Naive(entry) => Ok(vec![KafkaRecord::try_from(Record {
@@ -559,6 +574,29 @@ mod tests {
assert_eq!(full_entry.entry_id(), 3);
}
#[test]
fn test_is_record_meta_key() {
let meta = RecordMeta {
version: VERSION,
tp: RecordType::Full,
entry_id: 1,
ns: NamespaceImpl {
region_id: RegionId::new(1, 1).as_u64(),
topic: "greptimedb_wal_topic".to_string(),
},
};
assert!(is_record_meta_key(&serde_json::to_vec(&meta).unwrap()));
// A `RecordMeta` key this version cannot decode, e.g. one with a new `RecordType`
// variant.
assert!(is_record_meta_key(
br#"{"version": 0, "tp": "Compressed", "entry_id": 0, "ns": {"region_id": 1, "topic": ""}}"#
));
// Keys the log store never writes.
assert!(!is_record_meta_key(b"not-a-json-key"));
assert!(!is_record_meta_key(b"[1, 2, 3]"));
assert!(!is_record_meta_key(br#"{"hello": "world"}"#));
}
#[test]
fn test_meta_size() {
let meta = RecordMeta {
+21 -14
View File
@@ -96,16 +96,15 @@ impl ObjectStoreIo {
/// call, twice, and then deletes it.
pub(crate) async fn probe_conditional_create(&self) -> Result<()> {
let path = format!("{}{}", self.probe_prefix, Uuid::new_v4());
let create = || {
self.store
.write_with(&path, PROBE_CONTENT)
.if_not_exists(true)
};
create().await.context(WalObjectStoreSnafu {
operation: "write",
path: path.clone(),
})?;
let recreated = create().await;
self.put_path_if_absent(path.clone(), Bytes::from_static(PROBE_CONTENT))
.await?;
// Sent directly: only the store's own refusal shows that it honours
// the condition, and a read-back would find the first create's object.
let recreated = self
.store
.write_with(&path, PROBE_CONTENT)
.if_not_exists(true)
.await;
if let Err(error) = self.store.delete(&path).await {
warn!(error; "Failed to delete the conditional create probe {path} of the object store WAL");
}
@@ -134,15 +133,23 @@ impl ObjectStoreIo {
}
}
/// Creates the object `object_seq` unless it already exists. A retry with
/// the same content is accepted, different content is rejected.
/// Creates the object `object_seq` unless it already exists, see
/// [`Self::put_path_if_absent`].
pub(crate) async fn put_if_absent(&self, object_seq: u64, content: Bytes) -> Result<PutResult> {
self.put_path_if_absent(self.object_path(object_seq), content)
.await
}
/// Creates `path` unless it already exists. A retry with the same content
/// is accepted, different content is rejected: a create the store stored
/// but whose response was lost can be retried, by the caller or by the
/// retry layer, and then finds its own object.
///
/// When the store reports that the object exists but the read that
/// compares its content fails, the read failure is returned, so that its
/// retry hint says whether comparing again may settle the outcome. Any
/// other create failure is returned as the write failure it is.
pub(crate) async fn put_if_absent(&self, object_seq: u64, content: Bytes) -> Result<PutResult> {
let path = self.object_path(object_seq);
async fn put_path_if_absent(&self, path: String, content: Bytes) -> Result<PutResult> {
let write_result = self
.store
.write_with(&path, content.clone())
+49 -20
View File
@@ -4038,6 +4038,25 @@ mod tests {
}
}
/// A writer that writes the object and then reports a failure, as a
/// create whose response is lost.
struct LosingWriter(oio::Writer);
impl oio::Write for LosingWriter {
async fn write(&mut self, buffer: mock::Buffer) -> mock::Result<()> {
self.0.write(buffer).await
}
async fn close(&mut self) -> mock::Result<mock::Metadata> {
self.0.close().await?;
Err(mock::Error::new(mock::ErrorKind::Unexpected, "lost response").set_temporary())
}
async fn abort(&mut self) -> mock::Result<()> {
self.0.abort().await
}
}
async fn keys(object_store: &ObjectStore) -> Vec<String> {
let mut keys = object_store
.list_with(&format!("{PREFIX}/"))
@@ -4096,6 +4115,35 @@ mod tests {
assert!(keys(&object_store).await.is_empty());
}
#[tokio::test]
async fn test_store_open_accepts_a_retried_first_probe_create() {
let _serialized = SERIALIZED.lock().await;
let object_store = memory_store();
let lose_next = Arc::new(AtomicBool::new(true));
let losing = lose_next.clone();
let retrying = object_store.clone().layer(
MockLayerBuilder::default()
.writer_factory(Arc::new(move |_, _, inner| {
if losing.swap(false, Ordering::SeqCst) {
Box::new(LosingWriter(inner))
} else {
inner
}
}))
.build()
.unwrap(),
);
// The first write of the open is the first create of the probe.
let store = open(retrying, &eager()).await;
assert!(!lose_next.load(Ordering::SeqCst));
store.stop().await.unwrap();
assert_eq!(
vec![object_path(&object_store, 0)],
keys(&object_store).await
);
}
#[tokio::test]
async fn test_store_recovery_ignores_a_probe_left_behind() {
let _serialized = SERIALIZED.lock().await;
@@ -10500,7 +10548,7 @@ mod tests {
/// object store access through the store, one case per fault, and checks
/// that every row of the *Failure matrix* has one.
mod fault_matrix {
use object_store::layers::mock::{self, MockLayerBuilder, oio};
use object_store::layers::mock::MockLayerBuilder;
use prometheus::Histogram;
use super::*;
@@ -11459,25 +11507,6 @@ mod tests {
assert!(!lose_next.load(Ordering::SeqCst));
}
/// A writer that writes the object and then reports a failure, as a
/// create whose response is lost.
struct LosingWriter(oio::Writer);
impl oio::Write for LosingWriter {
async fn write(&mut self, buffer: mock::Buffer) -> mock::Result<()> {
self.0.write(buffer).await
}
async fn close(&mut self) -> mock::Result<mock::Metadata> {
self.0.close().await?;
Err(mock::Error::new(mock::ErrorKind::Unexpected, "lost response").set_temporary())
}
async fn abort(&mut self) -> mock::Result<()> {
self.0.abort().await
}
}
/// Object 2 is created and object 3 in flight when object 1 fails.
async fn create_fails_transiently_durable() {
let (store, io, mut parked) = open_parking_creates(memory_store(), &eager()).await;
+99 -11
View File
@@ -630,13 +630,13 @@ impl Context {
Ok(datanode_table_value)
}
/// Notifies the RegionSupervisor to register failure detectors of failed region.
/// Notifies the RegionSupervisor to register failure detectors of the given regions on the
/// source peer.
///
/// The original failure detector was removed once the procedure was triggered.
/// Now, we need to register the failure detector for the failed region again.
pub async fn register_failure_detectors(&self) {
pub async fn register_failure_detectors(&self, region_ids: &[RegionId]) {
let datanode_id = self.persistent_ctx.from_peer.id;
let region_ids = &self.persistent_ctx.region_ids;
let detecting_regions = region_ids
.iter()
.map(|region_id| (datanode_id, *region_id))
@@ -650,10 +650,10 @@ impl Context {
);
}
/// Notifies the RegionSupervisor to reset failure detectors of candidate regions.
pub async fn reset_failure_detectors_for_candidate_regions(&self) {
/// Notifies the RegionSupervisor to reset failure detectors of the given regions on the target
/// peer.
pub async fn reset_failure_detectors(&self, region_ids: &[RegionId]) {
let datanode_id = self.persistent_ctx.to_peer.id;
let region_ids = &self.persistent_ctx.region_ids;
let detecting_regions = region_ids
.iter()
.map(|region_id| (datanode_id, *region_id))
@@ -662,7 +662,7 @@ impl Context {
.reset_failure_detectors(detecting_regions)
.await;
info!(
"Reset failure detectors after migration success for datanode {}, regions {:?}",
"Reset failure detectors of regions for datanode {}, regions {:?}",
datanode_id, region_ids
);
}
@@ -878,12 +878,29 @@ impl RegionMigrationProcedure {
.with_label_values(&["rollback"])
.start_timer();
let ctx = &self.context;
let to_peer_id = ctx.persistent_ctx.to_peer.id;
let table_regions = ctx.persistent_ctx.table_regions();
// Regions whose route was switched to the target before the procedure aborted.
let mut switched_regions = Vec::new();
for (table_id, regions) in table_regions {
let table_lock = TableLock::Write(table_id).into();
let _guard = procedure_ctx.provider.acquire_lock(&table_lock).await;
let table_route = ctx.get_table_route_value(table_id).await?;
let table_route = match ctx.get_table_route_value(table_id).await {
Ok(table_route) => table_route,
// The table has been dropped meanwhile.
Err(error::Error::TableRouteNotFound { .. }) => continue,
Err(err) => return Err(err),
};
let region_routes = table_route.region_routes().unwrap();
switched_regions.extend(
region_routes
.iter()
.filter(|route| regions.contains(&route.region.id))
.filter(|route| {
route.leader_peer.as_ref().map(|peer| peer.id) == Some(to_peer_id)
})
.map(|route| route.region.id),
);
let downgraded = region_routes
.iter()
.filter(|route| regions.contains(&route.region.id))
@@ -912,7 +929,24 @@ impl RegionMigrationProcedure {
self.context
.deregister_failure_detectors_for_candidate_regions()
.await;
self.context.register_failure_detectors().await;
// The switched regions are served by the target, so they are monitored there instead.
let unswitched_regions = ctx
.persistent_ctx
.region_ids
.iter()
.filter(|region_id| !switched_regions.contains(region_id))
.copied()
.collect::<Vec<_>>();
self.context
.register_failure_detectors(&unswitched_regions)
.await;
// The target's next heartbeat would register these detectors again, but nothing would if
// the target stopped before sending one.
if !switched_regions.is_empty() {
self.context
.reset_failure_detectors(&switched_regions)
.await;
}
Ok(())
}
@@ -1014,8 +1048,8 @@ mod tests {
use common_meta::distributed_time_constants::default_distributed_time_constants;
use common_meta::instruction::Instruction;
use common_meta::key::test_utils::new_test_table_info;
use common_meta::rpc::router::{Region, RegionRoute};
use common_meta::key::test_utils::{new_test_table_info, new_test_table_info_with_name};
use common_meta::rpc::router::{LeaderState, Region, RegionRoute};
use super::*;
use crate::handler::HeartbeatMailbox;
@@ -1025,12 +1059,66 @@ mod tests {
new_downgrade_region_reply, new_flush_region_reply_for_region, new_open_region_reply,
new_upgrade_region_reply,
};
use crate::region::supervisor::{Event, RegionFailureDetectorControl};
use crate::service::mailbox::Channel;
fn new_persistent_context() -> PersistentContext {
test_util::new_persistent_context(1, 2, RegionId::new(1024, 1))
}
#[tokio::test]
async fn test_rollback_registers_detectors_for_switched_regions() {
let env = TestingEnv::new();
// The route switch aborted after the table of `switched` was switched to the target and
// before the table of `unswitched`, whose leader is still downgrading; the table of
// `dropped` has been dropped.
let switched = RegionId::new(1024, 1);
let unswitched = RegionId::new(1025, 1);
let dropped = RegionId::new(1026, 1);
for (region_id, leader) in [(switched, 2), (unswitched, 1)] {
let table_id = region_id.table_id();
let table_info = new_test_table_info_with_name(table_id, &format!("table_{table_id}"));
let region_routes = vec![RegionRoute {
region: Region::new_test(region_id),
leader_peer: Some(Peer::empty(leader)),
leader_state: (region_id == unswitched).then_some(LeaderState::Downgrading),
..Default::default()
}];
env.create_physical_table_metadata(table_info, region_routes)
.await;
}
let mut persistent_ctx = new_persistent_context();
persistent_ctx.region_ids = vec![switched, unswitched, dropped];
let (tx, mut rx) = tokio::sync::mpsc::channel(8);
let mut context_factory = env.context_factory();
context_factory.region_failure_detector_controller =
Arc::new(RegionFailureDetectorControl::new(tx));
let mut procedure = RegionMigrationProcedure::new(persistent_ctx, context_factory, vec![]);
procedure
.rollback_inner(&new_procedure_context())
.await
.unwrap();
// The target's detectors are replaced by the source's, except for `switched`, which stays
// monitored on the target.
let target = [switched, unswitched, dropped].map(|region_id| (2, region_id));
let source = [unswitched, dropped].map(|region_id| (1, region_id));
assert_matches!(rx.try_recv(), Ok(Event::DeregisterFailureDetectors(r)) if r == target);
assert_matches!(rx.try_recv(), Ok(Event::RegisterFailureDetectors(r)) if r == source);
assert_matches!(rx.try_recv(), Ok(Event::ResetFailureDetectors(r)) if r == [(2, switched)]);
assert!(rx.try_recv().is_err());
let table_route = env
.table_metadata_manager()
.table_route_manager()
.table_route_storage()
.get(unswitched.table_id())
.await
.unwrap()
.unwrap();
assert_eq!(table_route.region_routes().unwrap()[0].leader_state, None);
}
#[test]
fn test_lock_key() {
let persistent_context = new_persistent_context();
@@ -64,7 +64,8 @@ impl UpdateMetadata {
"Rolling back downgraded leader region table route success, table_id: {table_id}, regions: {regions:?}"
);
}
ctx.register_failure_detectors().await;
ctx.register_failure_detectors(&ctx.persistent_ctx.region_ids)
.await;
Ok(())
}
@@ -215,7 +215,8 @@ impl UpdateMetadata {
}
ctx.deregister_failure_detectors().await;
ctx.reset_failure_detectors_for_candidate_regions().await;
ctx.reset_failure_detectors(&ctx.persistent_ctx.region_ids)
.await;
// Consumes the guard.
ctx.volatile_ctx.opening_region_guards.clear();
+47 -7
View File
@@ -388,23 +388,27 @@ impl RegionEngine for MetricEngine {
&self,
region_id: RegionId,
role: RegionRole,
sent_at: Instant,
deadline: Instant,
) -> Result<(), BoxedError> {
// ignore the region not found error
) -> Result<bool, BoxedError> {
// The metadata region goes first. If it ignores the grant, the data region, whose role the
// engine reports, must not take it either. A region that is not found is ignored.
for x in [
utils::to_metadata_region_id(region_id),
utils::to_data_region_id(region_id),
] {
if let Err(e) = self
match self
.inner
.mito
.set_region_role_with_lease(x, role, deadline)
&& e.status_code() != StatusCode::RegionNotFound
.set_region_role_with_lease(x, role, sent_at, deadline)
{
return Err(e);
Ok(true) => {}
Ok(false) => return Ok(false),
Err(e) if e.status_code() != StatusCode::RegionNotFound => return Err(e),
Err(_) => {}
}
}
Ok(())
Ok(true)
}
async fn sync_region(
@@ -887,6 +891,42 @@ mod test {
assert!(!object_store.exists(&data_region_dir).await.unwrap());
}
#[tokio::test]
async fn test_leader_grant_ignored_by_metadata_region_leaves_data_region() {
let env = TestEnv::new().await;
env.init_metric_region().await;
let (engine, mito) = (env.metric(), env.mito());
let physical_region_id = env.default_physical_region_id();
let lease = std::time::Duration::from_secs(10);
// The data region is downgraded before the heartbeat is sent, the metadata region after it.
let downgrade = |region_id| {
mito.set_region_role_state_gracefully(region_id, SettableRegionRoleState::Follower)
};
downgrade(utils::to_data_region_id(physical_region_id))
.await
.unwrap();
let sent_at = Instant::now();
downgrade(utils::to_metadata_region_id(physical_region_id))
.await
.unwrap();
let grant = |sent_at: Instant| {
engine
.set_region_role_with_lease(
physical_region_id,
RegionRole::Leader,
sent_at,
sent_at + lease,
)
.unwrap()
};
assert!(!grant(sent_at));
assert_eq!(engine.role(physical_region_id), Some(RegionRole::Follower));
assert!(grant(Instant::now()));
assert_eq!(engine.role(physical_region_id), Some(RegionRole::Leader));
}
#[tokio::test]
async fn test_role() {
let env = TestEnv::new().await;
+1 -1
View File
@@ -2379,7 +2379,7 @@ mod tests {
let at = |n| start + n * Duration::from_secs(10);
let grant = |n| {
engine
.set_region_role_with_lease(physical_region_id, RegionRole::Leader, at(n))
.set_region_role_with_lease(physical_region_id, RegionRole::Leader, start, at(n))
.unwrap()
};
let expire = |n| mito.freeze_lease_clock(at(n));
+118 -3
View File
@@ -16,7 +16,8 @@ use std::sync::Arc;
use api::v1::SemanticType;
use common_telemetry::{debug, error, tracing};
use datafusion::logical_expr::{self, Expr};
use datafusion::common::ScalarValue;
use datafusion::logical_expr::{self, Expr, Operator};
use snafu::{OptionExt, ResultExt};
use store_api::metadata::{RegionMetadataBuilder, RegionMetadataRef};
use store_api::metric_engine_consts::DATA_SCHEMA_TABLE_ID_COLUMN_NAME;
@@ -60,10 +61,31 @@ impl MetricEngineInner {
.with_label_values(&["read_physical"])
.start_timer();
self.mito
// PromQL scans physical regions with a table-ID filter to access `__tsid`.
let logical_region = request
.filters
.iter()
.flat_map(logical_expr::utils::split_conjunction)
.any(|expr| {
let Expr::BinaryExpr(expr) = expr else {
return false;
};
expr.op == Operator::Eq
&& matches!(
(expr.left.as_ref(), expr.right.as_ref()),
(Expr::Column(column), Expr::Literal(ScalarValue::UInt32(Some(_)), _))
| (Expr::Literal(ScalarValue::UInt32(Some(_)), _), Expr::Column(column))
if column.name == DATA_SCHEMA_TABLE_ID_COLUMN_NAME
)
});
let mut scanner = self
.mito
.handle_query(region_id, request)
.await
.context(MitoReadOperationSnafu)
.context(MitoReadOperationSnafu)?;
scanner.set_logical_region(logical_region);
Ok(scanner)
}
async fn read_logical_region(
@@ -399,6 +421,99 @@ mod test {
);
}
#[tokio::test]
async fn test_single_logical_region_scan_properties() {
let env = TestEnv::new().await;
env.init_metric_region().await;
let physical_region_id = env.default_physical_region_id();
let logical_region_id = env.default_logical_region_id();
let table_id = logical_expr::col(DATA_SCHEMA_TABLE_ID_COLUMN_NAME);
let table_filter = table_id
.clone()
.eq(logical_expr::lit(logical_region_id.table_id()));
let job_filter = logical_expr::col("job").eq(logical_expr::lit("api"));
for (filters, logical_region) in [
(vec![], false),
(vec![table_filter.clone()], true),
(
vec![logical_expr::lit(logical_region_id.table_id()).eq(table_id.clone())],
true,
),
(vec![job_filter.clone(), table_filter.clone()], true),
(vec![job_filter.clone().and(table_filter.clone())], true),
(
vec![
table_filter.clone().and(
job_filter
.clone()
.or(logical_expr::col("job").eq(logical_expr::lit("db"))),
),
],
true,
),
(
vec![
table_filter
.clone()
.or(table_id.clone().eq(logical_expr::lit(4u32))),
],
false,
),
(vec![table_filter.clone().or(job_filter.clone())], false),
(
vec![table_id.clone().not_eq(logical_expr::lit(4u32))],
false,
),
(vec![table_id.clone().gt(logical_expr::lit(4u32))], false),
(
vec![table_id.eq(logical_expr::lit(ScalarValue::UInt32(None)))],
false,
),
(vec![job_filter], false),
] {
let scanner = env
.metric()
.handle_query(
physical_region_id,
ScanRequest {
filters: filters.clone(),
distribution: Some(TimeSeriesDistribution::PerSeries),
..Default::default()
},
)
.await
.unwrap();
assert_eq!(
scanner.properties().is_logical_region(),
logical_region,
"{filters:?}"
);
}
let scanner = env
.metric()
.handle_query(logical_region_id, ScanRequest::default())
.await
.unwrap();
assert!(scanner.properties().is_logical_region());
// A table-ID filter alone cannot grant metric guarantees to a Mito scan.
let scanner = env
.mito()
.handle_query(
utils::to_data_region_id(physical_region_id),
ScanRequest {
filters: vec![table_filter],
distribution: Some(TimeSeriesDistribution::PerSeries),
..Default::default()
},
)
.await
.unwrap();
assert!(!scanner.properties().is_logical_region());
}
#[tokio::test]
async fn test_transform_scan_req() {
let env = TestEnv::new().await;
+19 -8
View File
@@ -175,24 +175,35 @@ pub fn build_primary_key_codec_with_fields(
/// Finds the checked boundary of an Option<String>, shared by Dense and Sparse.
/// This validates framing, not UTF-8; consumers decoding strings validate UTF-8.
pub(crate) fn encoded_string_len(bytes: &[u8]) -> memcomparable::Result<usize> {
encoded_string_info::<false>(bytes).map(|(len, _)| len)
}
/// Checks string framing and optionally detects ASCII in the same pass.
/// Framing-only readers compile out payload inspection and ignore the ASCII result.
pub(crate) fn encoded_string_info<const CHECK_ASCII: bool>(
bytes: &[u8],
) -> memcomparable::Result<(usize, bool)> {
match bytes.first().copied().ok_or(memcomparable::Error::Eof)? {
0 => return Ok(1),
0 => return Ok((1, true)),
1 => {}
marker => return Err(memcomparable::Error::InvalidTagEncoding(marker as usize)),
}
match bytes.get(1).copied().ok_or(memcomparable::Error::Eof)? {
0 => return Ok(2),
0 => return Ok((2, true)),
1 => {}
marker => return Err(memcomparable::Error::InvalidBytesEncoding(marker)),
}
let mut end = 2;
loop {
let chunk = bytes.get(end..end + 9).ok_or(memcomparable::Error::Eof)?;
end += 9;
match chunk[8] {
1..=8 => return Ok(end),
let mut ascii_bits = 0_u64;
for (index, chunk) in bytes[2..].as_chunks::<9>().0.iter().enumerate() {
let [word @ .., marker] = *chunk;
if CHECK_ASCII {
ascii_bits |= u64::from_ne_bytes(word);
}
match marker {
1..=8 => return Ok((2 + (index + 1) * 9, ascii_bits & 0x8080_8080_8080_8080 == 0)),
9 => {}
marker => return Err(memcomparable::Error::InvalidBytesEncoding(marker)),
}
}
Err(memcomparable::Error::Eof)
}
+280 -46
View File
@@ -23,7 +23,7 @@ use datatypes::prelude::ConcreteDataType;
use datatypes::value::{Value, ValueRef};
use memcomparable::{Deserializer, Serializer};
use serde::{Deserialize, Serialize};
use snafu::{ResultExt, ensure};
use snafu::{OptionExt, ResultExt, ensure};
use store_api::codec::PrimaryKeyEncoding;
use store_api::metadata::RegionMetadataRef;
use store_api::storage::ColumnId;
@@ -39,30 +39,28 @@ use crate::row_converter::dense::SortField;
pub use crate::row_converter::sparse::checked::SparsePrimaryKeyView;
use crate::row_converter::{CompositeValues, PrimaryKeyCodec, PrimaryKeyFilter};
/// A codec for sparse key of metrics.
/// A codec for sparse keys with reserved table ID and TSID columns.
///
/// ## Encoding format
/// Each primary key is encoded as a sequence of `(column_id, value)` pairs:
/// - The first two fields are always the reserved `table_id` (uint32) and `tsid` (uint64).
/// - User-defined labels follow, sorted by **column name** in lexicographical order.
/// - Null values are omitted (not encoded).
/// - Keys start with reserved `table_id` (uint32) and `tsid` (uint64).
/// - String tags follow the reserved prefix; null tags are omitted.
///
/// The `column_id` is encoded as a 4-byte big-endian integer, and the value is encoded
/// using memcomparable serialization.
///
/// `decode_leftmost` always decodes the first value from the encoded bytes (i.e., the
/// `table_id` field).
/// `decode_leftmost` returns the reserved `table_id` value.
///
/// ## Requirements
/// It requires the input primary key columns are sorted by the column name in lexicographical order.
/// It encodes the column id of the physical region.
/// Encoders supply columns in the layout's order using stable physical-region IDs.
#[derive(Clone, Debug)]
pub struct SparsePrimaryKeyCodec {
inner: Arc<SparsePrimaryKeyCodecInner>,
}
#[derive(Debug)]
#[derive(Debug, Clone)]
struct SparsePrimaryKeyCodecInner {
fields: Option<Vec<(ColumnId, SortField)>>,
// Internal fields
table_id_field: SortField,
// Internal fields
@@ -146,6 +144,66 @@ const TSID_VALUE_OFFSET: usize = COLUMN_ID_ENCODE_SIZE + 5 + COLUMN_ID_ENCODE_SI
/// Byte offset where tag columns start (after 9-byte table_id + 13-byte tsid entries).
const TAGS_START_OFFSET: usize = COLUMN_ID_ENCODE_SIZE + 5 + COLUMN_ID_ENCODE_SIZE + 9;
/// Validates complete sparse keys without materializing their values.
///
/// Scratch buffers retain capacity between keys; validation does not depend on region metadata.
#[derive(Default)]
pub struct SparsePrimaryKeyValidator {
column_ids: Vec<ColumnId>,
label_buf: Vec<u8>,
}
impl SparsePrimaryKeyValidator {
/// Checks the prefix, all label framing and UTF-8, and rejects duplicate or reserved labels.
pub fn validate(&mut self, bytes: &[u8]) -> Result<()> {
self.column_ids.clear();
validate_prefix(bytes)?;
let mut remaining = &bytes[TAGS_START_OFFSET..];
while !remaining.is_empty() {
let id = remaining.first_chunk::<COLUMN_ID_ENCODE_SIZE>().context(
InvalidSparsePrimaryKeySnafu {
reason: "truncated label column id",
},
)?;
let column_id = u32::from_be_bytes(*id);
ensure!(
!ReservedColumnId::is_reserved(column_id),
InvalidSparsePrimaryKeySnafu {
reason: "reserved column id in sparse labels",
}
);
self.column_ids.push(column_id);
let encoded = &remaining[COLUMN_ID_ENCODE_SIZE..];
let (length, ascii) = crate::row_converter::encoded_string_info::<true>(encoded)
.context(DeserializeFieldSnafu)?;
let encoded = &encoded[..length];
// Framing is already checked; ASCII needs no unchunking to establish valid UTF-8.
if !ascii {
self.label_buf.clear();
self.label_buf.reserve(length);
Deserializer::new(&encoded[1..])
.read_bytes_into(&mut self.label_buf)
.context(DeserializeFieldSnafu)?;
std::str::from_utf8(&self.label_buf).map_err(|_| {
InvalidSparsePrimaryKeySnafu {
reason: "label is not valid UTF-8",
}
.build()
})?;
}
remaining = &remaining[COLUMN_ID_ENCODE_SIZE + length..];
}
self.column_ids.sort_unstable();
ensure!(
!self.column_ids.windows(2).any(|pair| pair[0] == pair[1]),
InvalidSparsePrimaryKeySnafu {
reason: "duplicate column id in sparse key",
}
);
Ok(())
}
}
/// Inline capacity for the small-vec fast path of [`SparseOffsetsCache`].
///
/// Most sparse primary keys carry only a handful of tags, so a linear scan
@@ -225,6 +283,7 @@ impl SparsePrimaryKeyCodec {
let columns = columns_ids.collect();
Self {
inner: Arc::new(SparsePrimaryKeyCodecInner {
fields: None,
table_id_field: SortField::new(ConcreteDataType::uint32_datatype()),
tsid_field: SortField::new(ConcreteDataType::uint64_datatype()),
label_field: SortField::new(ConcreteDataType::string_datatype()),
@@ -235,7 +294,16 @@ impl SparsePrimaryKeyCodec {
/// Creates a new [`SparsePrimaryKeyCodec`] instance.
pub fn new(region_metadata: &RegionMetadataRef) -> Self {
Self::from_columns(region_metadata.primary_key_columns().map(|c| c.column_id))
let fields = region_metadata
.primary_key_columns()
.map(|c| {
(
c.column_id,
SortField::new(c.column_schema.data_type.clone()),
)
})
.collect();
Self::with_fields(fields)
}
/// Returns a new [`SparsePrimaryKeyCodec`] instance.
@@ -244,6 +312,7 @@ impl SparsePrimaryKeyCodec {
pub fn schemaless() -> Self {
Self {
inner: Arc::new(SparsePrimaryKeyCodecInner {
fields: None,
table_id_field: SortField::new(ConcreteDataType::uint32_datatype()),
tsid_field: SortField::new(ConcreteDataType::uint64_datatype()),
label_field: SortField::new(ConcreteDataType::string_datatype()),
@@ -252,27 +321,20 @@ impl SparsePrimaryKeyCodec {
}
}
/// Creates a new [`SparsePrimaryKeyCodec`] instance with additional label `fields`.
/// Creates a schema-aware sparse codec.
pub fn with_fields(fields: Vec<(ColumnId, SortField)>) -> Self {
Self {
inner: Arc::new(SparsePrimaryKeyCodecInner {
columns: Some(fields.iter().map(|f| f.0).collect()),
table_id_field: SortField::new(ConcreteDataType::uint32_datatype()),
tsid_field: SortField::new(ConcreteDataType::uint64_datatype()),
label_field: SortField::new(ConcreteDataType::string_datatype()),
}),
}
let mut codec = Self::from_columns(fields.iter().map(|f| f.0));
Arc::make_mut(&mut codec.inner).fields = Some(fields);
codec
}
/// Returns the field of the given column id.
fn get_field(&self, column_id: ColumnId) -> Option<&SortField> {
// if the `columns` is not specified, all unknown columns is primary key(label field).
if let Some(columns) = &self.inner.columns
&& !columns.contains(&column_id)
{
return None;
}
match column_id {
RESERVED_COLUMN_ID_TABLE_ID => Some(&self.inner.table_id_field),
RESERVED_COLUMN_ID_TSID => Some(&self.inner.tsid_field),
@@ -405,32 +467,50 @@ impl SparsePrimaryKeyCodec {
/// Decodes the given bytes into a [`SparseValues`].
fn decode_sparse(&self, bytes: &[u8]) -> Result<SparseValues> {
let mut deserializer = Deserializer::new(bytes);
let mut values = SparseValues::with_capacity(16);
let column_id = u32::deserialize(&mut deserializer).context(DeserializeFieldSnafu)?;
let value = self.inner.table_id_field.deserialize(&mut deserializer)?;
values.insert(column_id, value);
let column_id = u32::deserialize(&mut deserializer).context(DeserializeFieldSnafu)?;
let value = self.inner.tsid_field.deserialize(&mut deserializer)?;
values.insert(column_id, value);
while deserializer.has_remaining() {
let column_id = u32::deserialize(&mut deserializer).context(DeserializeFieldSnafu)?;
let value = self.inner.label_field.deserialize(&mut deserializer)?;
let (table_id, tsid) = self.decode_ids(bytes)?;
values.insert(RESERVED_COLUMN_ID_TABLE_ID, Value::UInt32(table_id));
values.insert(RESERVED_COLUMN_ID_TSID, Value::UInt64(tsid));
let mut remaining = &bytes[TAGS_START_OFFSET..];
while !remaining.is_empty() {
let id = remaining.first_chunk::<COLUMN_ID_ENCODE_SIZE>().context(
InvalidSparsePrimaryKeySnafu {
reason: "truncated label column id",
},
)?;
let column_id = u32::from_be_bytes(*id);
ensure!(
!ReservedColumnId::is_reserved(column_id),
InvalidSparsePrimaryKeySnafu {
reason: "reserved column id in sparse labels"
}
);
let encoded = &remaining[COLUMN_ID_ENCODE_SIZE..];
let length =
crate::row_converter::encoded_string_len(encoded).context(DeserializeFieldSnafu)?;
let value = self
.inner
.label_field
.deserialize(&mut Deserializer::new(&encoded[..length]))?;
ensure!(
values.get(&column_id).is_none(),
InvalidSparsePrimaryKeySnafu {
reason: "duplicate column id in sparse key",
}
);
values.insert(column_id, value);
remaining = &encoded[length..];
}
Ok(values)
}
/// Decodes the given bytes into a [`Value`].
/// Decodes the reserved table ID from the key prefix.
fn decode_leftmost(&self, bytes: &[u8]) -> Result<Option<Value>> {
let mut deserializer = Deserializer::new(bytes);
// Skip the column id.
deserializer.advance(COLUMN_ID_ENCODE_SIZE);
let value = self.inner.table_id_field.deserialize(&mut deserializer)?;
Ok(Some(value))
if bytes.is_empty() {
return Ok(None);
}
self.decode_ids(bytes)
.map(|(table_id, _)| Some(Value::UInt32(table_id)))
}
/// Returns the offset of the given column id in the given primary key.
@@ -529,11 +609,18 @@ impl SparsePrimaryKeyCodec {
}
impl PrimaryKeyCodec for SparsePrimaryKeyCodec {
fn encode_key_value(&self, _key_value: &KeyValue, _buffer: &mut Vec<u8>) -> Result<()> {
UnsupportedOperationSnafu {
err_msg: "The encode_key_value method is not supported in SparsePrimaryKeyCodec.",
}
.fail()
fn encode_key_value(&self, key_value: &KeyValue, buffer: &mut Vec<u8>) -> Result<()> {
let fields = self
.inner
.fields
.as_ref()
.context(UnsupportedOperationSnafu {
err_msg: "raw row encoding requires primary key metadata",
})?;
self.encode_to_vec(
fields.iter().map(|f| f.0).zip(key_value.primary_keys()),
buffer,
)
}
fn encode_values(&self, values: &[(ColumnId, Value)], buffer: &mut Vec<u8>) -> Result<()> {
@@ -581,6 +668,21 @@ impl PrimaryKeyCodec for SparsePrimaryKeyCodec {
}
}
fn validate_prefix(pk: &[u8]) -> Result<()> {
ensure!(
pk.len() >= TAGS_START_OFFSET
&& pk[..COLUMN_ID_ENCODE_SIZE] == RESERVED_COLUMN_ID_TABLE_ID.to_be_bytes()
&& pk[TSID_VALUE_OFFSET - COLUMN_ID_ENCODE_SIZE..TSID_VALUE_OFFSET]
== RESERVED_COLUMN_ID_TSID.to_be_bytes()
&& pk[TABLE_ID_VALUE_OFFSET] == 1
&& pk[TSID_VALUE_OFFSET] == 1,
InvalidSparsePrimaryKeySnafu {
reason: "invalid table_id/tsid prefix"
}
);
Ok(())
}
#[cfg(test)]
mod tests {
use std::sync::Arc;
@@ -846,6 +948,12 @@ mod tests {
assert!(!buffer.is_empty());
let result = codec.decode_leftmost(&buffer).unwrap().unwrap();
assert_eq!(result, Value::UInt32(42));
assert_eq!(codec.decode_leftmost(&[]).unwrap(), None);
assert!(
codec
.decode_leftmost(&buffer[..TAGS_START_OFFSET - 1])
.is_err()
);
}
#[test]
@@ -863,6 +971,132 @@ mod tests {
assert!(codec.decode_ids(&buffer[..buffer.len() - 1]).is_err());
}
#[test]
fn test_sparse_validator_matches_decoder() {
let codec = SparsePrimaryKeyCodec::schemaless();
let mut validator = SparsePrimaryKeyValidator::default();
let mut prefix = Vec::new();
codec.encode_internal(0, 0, &mut prefix).unwrap();
let mut cases = vec![prefix.clone()];
let mut max_prefix = Vec::new();
codec
.encode_internal(u32::MAX, u64::MAX, &mut max_prefix)
.unwrap();
cases.push(max_prefix);
for label in ["", "a", "12345678", "123456789", "1234567🦀末尾", "日本語"]
.into_iter()
.map(String::from)
.chain([
"a".repeat(128),
format!("{}🦀", "a".repeat(127)),
format!("🦀{}", "a".repeat(127)),
])
{
let mut key = prefix.clone();
codec
.encode_raw_tag_value([(37, label.as_bytes())].into_iter(), &mut key)
.unwrap();
assert!(validator.validate(&key).is_ok());
cases.push(key);
}
// Null labels, unknown IDs and arbitrary label order are accepted by the decoder.
let mut labels = prefix.clone();
labels.extend_from_slice(&12_u32.to_be_bytes());
labels.push(0);
codec
.encode_raw_tag_value(
[(999, b"unknown".as_slice()), (0, b"first".as_slice())].into_iter(),
&mut labels,
)
.unwrap();
assert!(validator.validate(&labels).is_ok());
cases.push(labels.clone());
// Padding outside the significant bytes has never been required to be zero.
let mut padded = cases[3].clone();
let padding_offset = padded.len() - 2;
padded[padding_offset] = 0xff;
assert!(codec.decode(&padded).is_ok());
assert!(validator.validate(&padded).is_ok());
cases.push(padded);
for id in [
12,
RESERVED_COLUMN_ID_TABLE_ID,
RESERVED_COLUMN_ID_TSID,
u32::MAX,
] {
let mut invalid = labels.clone();
invalid.extend_from_slice(&id.to_be_bytes());
invalid.push(0);
assert!(codec.decode(&invalid).is_err());
assert!(validator.validate(&invalid).is_err());
cases.push(invalid);
}
for label in [
b"\xff".as_slice(),
b"\xc0\xaf",
b"\xed\xa0\x80",
b"1234567\xf4\x90\x80\x80",
] {
let mut invalid = prefix.clone();
codec
.encode_raw_tag_value([(37, label)].into_iter(), &mut invalid)
.unwrap();
assert!(codec.decode(&invalid).is_err());
assert!(validator.validate(&invalid).is_err());
cases.push(invalid);
}
// Reuse the same scratch state across successes and failures, including every
// truncation and byte substitution in this corpus of framing and UTF-8 boundaries.
let mut compare = |bytes: &[u8]| {
assert_eq!(
validator.validate(bytes).is_ok(),
codec.decode(bytes).is_ok(),
"{bytes:02x?}"
);
};
for key in cases {
compare(&key);
for end in 0..key.len() {
compare(&key[..end]);
}
for offset in 0..key.len() {
let mut mutated = key.clone();
for byte in 0..=u8::MAX {
mutated[offset] = byte;
compare(&mutated);
}
}
}
}
#[test]
fn test_sparse_validator_reuses_state_for_unordered_columns() {
let codec = SparsePrimaryKeyCodec::schemaless();
let mut validator = SparsePrimaryKeyValidator::default();
for num_tags in [512, 32, 1] {
let mut key = Vec::new();
codec.encode_internal(0, 0, &mut key).unwrap();
codec
.encode_raw_tag_value(
(0..num_tags).map(|index| (index * 17 % num_tags, "1234567🦀".as_bytes())),
&mut key,
)
.unwrap();
assert!(validator.validate(&key).is_ok());
let mut duplicate = key.clone();
duplicate.extend_from_slice(&0_u32.to_be_bytes());
duplicate.push(0);
assert!(validator.validate(&duplicate).is_err());
assert!(validator.validate(&key).is_ok());
}
}
#[test]
fn test_has_column() {
let region_metadata = test_region_metadata();
@@ -21,6 +21,7 @@ use crate::row_converter::encoded_string_len;
use crate::row_converter::sparse::{
COLUMN_ID_ENCODE_SIZE, RESERVED_COLUMN_ID_TABLE_ID, RESERVED_COLUMN_ID_TSID,
SparseOffsetsCache, TABLE_ID_VALUE_OFFSET, TAGS_START_OFFSET, TSID_VALUE_OFFSET,
validate_prefix,
};
/// A borrowing view of one sparse primary key, with checked, lazy field lookup.
@@ -35,17 +36,7 @@ pub struct SparsePrimaryKeyView<'a, 'b> {
impl<'a, 'b> SparsePrimaryKeyView<'a, 'b> {
/// Validates the fixed prefix and binds fresh offset discovery to this key.
pub fn new(pk: &'a [u8], cache: &'b mut SparseOffsetsCache) -> Result<Self> {
ensure!(
pk.len() >= TAGS_START_OFFSET
&& pk[..COLUMN_ID_ENCODE_SIZE] == RESERVED_COLUMN_ID_TABLE_ID.to_be_bytes()
&& pk[TSID_VALUE_OFFSET - COLUMN_ID_ENCODE_SIZE..TSID_VALUE_OFFSET]
== RESERVED_COLUMN_ID_TSID.to_be_bytes()
&& pk[TABLE_ID_VALUE_OFFSET] == 1
&& pk[TSID_VALUE_OFFSET] == 1,
InvalidSparsePrimaryKeySnafu {
reason: "invalid table_id/tsid prefix"
}
);
validate_prefix(pk)?;
cache.clear();
Ok(Self { pk, cache })
}
+4
View File
@@ -159,3 +159,7 @@ required-features = ["testing"]
name = "bench_compaction_merge"
harness = false
required-features = ["test"]
[[bench]]
name = "bench_sparse_write"
harness = false
+2 -1
View File
@@ -60,7 +60,8 @@ fn input(shape: &Shape) -> (RegionMetadataRef, HashSet<ColumnId>, RecordBatch) {
let mut pk = vec![ReservedColumnId::table_id(), ReservedColumnId::tsid()];
let mut inverted_columns = HashSet::new();
let mut add_tag = |id, name: String, data_type, indexed| {
let mut schema = ColumnSchema::new(name, data_type, true).with_inverted_index(false);
let mut schema = ColumnSchema::new(name, data_type, !ReservedColumnId::is_reserved(id))
.with_inverted_index(false);
if indexed && shape.inverted {
inverted_columns.insert(id);
}
+5 -1
View File
@@ -77,7 +77,11 @@ fn metadata(tags: u32) -> RegionMetadataRef {
primary_key.push(column_id);
builder.push_column_metadata(ColumnMetadata {
column_id,
column_schema: ColumnSchema::new(name, data_type, true),
column_schema: ColumnSchema::new(
name,
data_type,
!ReservedColumnId::is_reserved(column_id),
),
semantic_type: SemanticType::Tag,
});
}
+391
View File
@@ -0,0 +1,391 @@
// 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.
//! Measures the sparse row and bulk conversion paths used by ingestion and WAL replay.
//! Input preparation, TSID calculation, protocol decoding, and I/O are excluded.
use std::hint::black_box;
use std::sync::Arc;
use api::helper::{ColumnDataTypeWrapper, to_grpc_value};
use api::v1::value::ValueData;
use api::v1::{ColumnDataType, Mutation, OpType, Row, Rows, SemanticType, WriteHint};
use criterion::{BatchSize, BenchmarkId, Criterion, Throughput, criterion_group, criterion_main};
use datatypes::arrow::array::{
ArrayRef, BinaryArray, BinaryDictionaryBuilder, Float64Array, TimestampMillisecondArray,
};
use datatypes::arrow::compute;
use datatypes::arrow::datatypes::{DataType, Field, Schema, UInt32Type};
use datatypes::arrow::record_batch::RecordBatch;
use datatypes::data_type::ConcreteDataType;
use datatypes::schema::ColumnSchema;
use mito_codec::key_values::KeyValues;
use mito_codec::row_converter::{self, CompositeValues, PrimaryKeyCodec, SparsePrimaryKeyCodec};
use mito2::memtable::bulk::part::{self, BulkPart, BulkPartConverter};
use mito2::sst::{self, FlatSchemaOptions};
use store_api::codec::PrimaryKeyEncoding;
use store_api::metadata::{ColumnMetadata, RegionMetadataBuilder, RegionMetadataRef};
use store_api::metric_engine_consts::{
DATA_SCHEMA_TABLE_ID_COLUMN_NAME, DATA_SCHEMA_TSID_COLUMN_NAME,
};
use store_api::storage::RegionId;
use store_api::storage::consts::{PRIMARY_KEY_COLUMN_NAME, ReservedColumnId};
const ROWS_PER_BATCH: usize = 4096;
const TABLE_ID: u32 = 1024;
fn build_metadata(num_tags: u32) -> RegionMetadataRef {
let mut builder = RegionMetadataBuilder::new(RegionId::new(TABLE_ID, 0));
let mut primary_key = vec![ReservedColumnId::table_id(), ReservedColumnId::tsid()];
for (name, data_type, column_id) in [
(
DATA_SCHEMA_TABLE_ID_COLUMN_NAME,
ConcreteDataType::uint32_datatype(),
ReservedColumnId::table_id(),
),
(
DATA_SCHEMA_TSID_COLUMN_NAME,
ConcreteDataType::uint64_datatype(),
ReservedColumnId::tsid(),
),
] {
builder.push_column_metadata(ColumnMetadata {
column_schema: ColumnSchema::new(name, data_type, false),
semantic_type: SemanticType::Tag,
column_id,
});
}
for index in 0..num_tags {
let column_id = index * 17 % num_tags;
builder.push_column_metadata(ColumnMetadata {
column_schema: ColumnSchema::new(
format!("tag_{column_id}"),
ConcreteDataType::string_datatype(),
true,
),
semantic_type: SemanticType::Tag,
column_id,
});
primary_key.push(column_id);
}
builder
.push_column_metadata(ColumnMetadata {
column_schema: ColumnSchema::new(
"ts",
ConcreteDataType::timestamp_millisecond_datatype(),
false,
),
semantic_type: SemanticType::Timestamp,
column_id: num_tags,
})
.push_column_metadata(ColumnMetadata {
column_schema: ColumnSchema::new("value", ConcreteDataType::float64_datatype(), true),
semantic_type: SemanticType::Field,
column_id: num_tags + 1,
})
.primary_key(primary_key)
.primary_key_encoding(PrimaryKeyEncoding::Sparse);
Arc::new(builder.build().unwrap())
}
fn build_keys(num_series: usize, num_tags: u32, value_bytes: usize, unicode: bool) -> Vec<Vec<u8>> {
let codec = SparsePrimaryKeyCodec::schemaless();
(0..num_series)
.map(|series| {
let tags: Vec<_> = (0..num_tags)
.map(|index| {
// Label name order need not match physical column ID order.
let column_id = index * 17 % num_tags;
let mut value = format!("{series:08x}{column_id:08x}").into_bytes();
assert!(value.len() <= value_bytes);
value.resize(value_bytes, b'x');
if unicode {
// The code point crosses an eight-byte encoding chunk boundary.
let start = value_bytes - 9;
value[start..start + 4].copy_from_slice("🦀".as_bytes());
}
(column_id, value)
})
.collect();
let mut key = Vec::new();
// Permute distinct TSIDs so even one-row-per-series input needs sorting.
let tsid = (series * 17 % num_series) as u64;
codec.encode_internal(TABLE_ID, tsid, &mut key).unwrap();
codec
.encode_raw_tag_value(
tags.iter().map(|(id, value)| (*id, value.as_slice())),
&mut key,
)
.unwrap();
assert_eq!(codec.decode_ids(&key).unwrap(), (TABLE_ID, tsid));
key
})
.collect()
}
fn build_rows(metadata: &RegionMetadataRef, keys: &[Vec<u8>]) -> KeyValues {
let schema = [
(
PRIMARY_KEY_COLUMN_NAME,
ColumnDataType::Binary,
SemanticType::Tag,
),
(
"ts",
ColumnDataType::TimestampMillisecond,
SemanticType::Timestamp,
),
("value", ColumnDataType::Float64, SemanticType::Field),
]
.into_iter()
.map(|(name, data_type, semantic_type)| api::v1::ColumnSchema {
column_name: name.to_string(),
datatype: data_type as i32,
semantic_type: semantic_type as i32,
..Default::default()
})
.collect();
let rows = (0..ROWS_PER_BATCH)
.map(|row| Row {
values: vec![
ValueData::BinaryValue(keys[row % keys.len()].clone()).into(),
ValueData::TimestampMillisecondValue((row / keys.len()) as i64 * 1000).into(),
ValueData::F64Value(row as f64).into(),
],
})
.collect();
KeyValues::new(
metadata,
Mutation {
op_type: OpType::Put as i32,
sequence: 1,
rows: Some(Rows { schema, rows }),
write_hint: Some(WriteHint {
primary_key_encoding: api::v1::PrimaryKeyEncoding::Sparse.into(),
}),
},
)
.unwrap()
}
fn build_bulk(keys: &[Vec<u8>], dictionary: bool) -> BulkPart {
let key_column: ArrayRef = if dictionary {
let mut builder = BinaryDictionaryBuilder::<UInt32Type>::new();
for row in 0..ROWS_PER_BATCH {
builder.append(&keys[row % keys.len()]).unwrap();
}
let array = builder.finish();
assert_eq!(array.values().len(), keys.len());
Arc::new(array)
} else {
Arc::new(BinaryArray::from_iter_values(
(0..ROWS_PER_BATCH).map(|row| &keys[row % keys.len()]),
))
};
let columns: Vec<ArrayRef> = vec![
key_column,
Arc::new(TimestampMillisecondArray::from_iter_values(
(0..ROWS_PER_BATCH).map(|row| (row / keys.len()) as i64 * 1000),
)),
Arc::new(Float64Array::from_iter_values(
(0..ROWS_PER_BATCH).map(|row| row as f64),
)),
];
let schema = Arc::new(Schema::new(
[PRIMARY_KEY_COLUMN_NAME, "ts", "value"]
.into_iter()
.zip(&columns)
.map(|(name, column)| Field::new(name, column.data_type().clone(), false))
.collect::<Vec<_>>(),
));
BulkPart {
batch: RecordBatch::try_new(schema, columns).unwrap(),
min_timestamp: 0,
max_timestamp: (ROWS_PER_BATCH / keys.len() - 1) as i64 * 1000,
sequence: 1,
min_sequence: 1,
timestamp_index: 1,
raw_data: None,
}
}
fn build_raw_rows(metadata: &RegionMetadataRef, keys: &[Vec<u8>]) -> KeyValues {
let codec = SparsePrimaryKeyCodec::schemaless();
let tags: Vec<Vec<_>> = keys
.iter()
.map(|key| {
let CompositeValues::Sparse(values) = codec.decode(key).unwrap() else {
unreachable!()
};
metadata
.primary_key
.iter()
.map(|id| to_grpc_value(values.get(id).unwrap().clone()))
.collect()
})
.collect();
let schema = metadata
.column_metadatas
.iter()
.map(|column| api::v1::ColumnSchema {
column_name: column.column_schema.name.clone(),
datatype: ColumnDataTypeWrapper::try_from(column.column_schema.data_type.clone())
.unwrap()
.datatype() as i32,
semantic_type: column.semantic_type as i32,
..Default::default()
})
.collect();
let rows = (0..ROWS_PER_BATCH)
.map(|row| {
let mut values = tags[row % tags.len()].clone();
values.push(
ValueData::TimestampMillisecondValue((row / tags.len()) as i64 * 1000).into(),
);
values.push(ValueData::F64Value(row as f64).into());
Row { values }
})
.collect();
KeyValues::new(
metadata,
Mutation {
op_type: OpType::Put as i32,
sequence: 1,
rows: Some(Rows { schema, rows }),
write_hint: None,
},
)
.unwrap()
}
// Check every output row outside timing, including repeated series and the sort order.
fn check_output(part: &BulkPart, keys: &[Vec<u8>]) {
assert_eq!(part.batch.num_rows(), ROWS_PER_BATCH);
let encoded = compute::cast(
part.batch.column_by_name(PRIMARY_KEY_COLUMN_NAME).unwrap(),
&DataType::Binary,
)
.unwrap();
let encoded = encoded.as_any().downcast_ref::<BinaryArray>().unwrap();
let timestamps = part
.batch
.column_by_name("ts")
.unwrap()
.as_any()
.downcast_ref::<TimestampMillisecondArray>()
.unwrap();
let values = part
.batch
.column_by_name("value")
.unwrap()
.as_any()
.downcast_ref::<Float64Array>()
.unwrap();
let rows_per_series = ROWS_PER_BATCH / keys.len();
let mut series_order: Vec<_> = (0..keys.len()).collect();
series_order.sort_unstable_by_key(|&series| &keys[series]);
for row in 0..ROWS_PER_BATCH {
let series = series_order[row / rows_per_series];
let sample = row % rows_per_series;
assert_eq!(encoded.value(row), keys[series]);
assert_eq!(timestamps.value(row), sample as i64 * 1000);
assert_eq!(values.value(row), (sample * keys.len() + series) as f64);
}
}
fn bench_sparse_write(c: &mut Criterion) {
let mut group = c.benchmark_group("sparse_write");
group.throughput(Throughput::Elements(ROWS_PER_BATCH as u64));
for (num_tags, value_bytes, unicode) in [
(8, 16, false),
(32, 16, false),
(32, 128, false),
(32, 128, true),
(512, 16, true),
] {
let metadata = build_metadata(num_tags);
let codec = row_converter::build_primary_key_codec(&metadata);
let schema = sst::to_flat_sst_arrow_schema(
&metadata,
&FlatSchemaOptions::from_encoding(PrimaryKeyEncoding::Sparse),
);
for num_series in [64, ROWS_PER_BATCH] {
let suffix = if unicode { "_unicode" } else { "" };
let name = format!("{num_tags}tags_{value_bytes}bytes_{num_series}series{suffix}");
let keys = build_keys(num_series, num_tags, value_bytes, unicode);
let rows = build_rows(&metadata, &keys);
let new_converter = || {
BulkPartConverter::new(
&metadata,
schema.clone(),
ROWS_PER_BATCH,
codec.clone(),
true,
)
};
let mut converter = new_converter();
converter.append_key_values(&rows).unwrap();
check_output(&converter.convert().unwrap(), &keys);
group.bench_function(BenchmarkId::new("rows", &name), |b| {
b.iter_batched(
new_converter,
|mut converter| {
converter.append_key_values(black_box(&rows)).unwrap();
black_box(converter.convert().unwrap())
},
// A wide-label batch can own tens of MiB; do not retain many outputs.
BatchSize::PerIteration,
);
});
for (input, dictionary) in [("bulk_binary", false), ("bulk_dictionary", true)] {
let part = build_bulk(&keys, dictionary);
let convert = |part| {
part::convert_bulk_part(part, &metadata, codec.clone(), schema.clone(), true)
.unwrap()
.unwrap()
};
check_output(&convert(part.clone()), &keys);
group.bench_function(BenchmarkId::new(input, &name), |b| {
b.iter_batched(
|| part.clone(),
|part| black_box(convert(part)),
BatchSize::PerIteration,
);
});
}
let raw_rows = build_raw_rows(&metadata, &keys);
let mut converter = new_converter();
converter.append_key_values(&raw_rows).unwrap();
check_output(&converter.convert().unwrap(), &keys);
group.bench_function(BenchmarkId::new("raw_rows", &name), |b| {
b.iter_batched(
new_converter,
|mut converter| {
converter.append_key_values(black_box(&raw_rows)).unwrap();
black_box(converter.convert().unwrap())
},
BatchSize::PerIteration,
);
});
}
}
group.finish();
}
criterion_group!(benches, bench_sparse_write);
criterion_main!(benches);
+206 -101
View File
@@ -17,9 +17,9 @@ use std::sync::Arc;
use std::time::Duration;
use common_base::Plugins;
use common_base::cancellation::{CancellableFuture, CancellationHandle};
use common_base::cancellation::CancellationHandle;
use common_meta::key::SchemaMetadataManagerRef;
use common_telemetry::{debug, info, warn};
use common_telemetry::{info, warn};
use common_time::TimeToLive;
use either::Either;
use itertools::Itertools;
@@ -37,7 +37,7 @@ use crate::access_layer::{
};
use crate::cache::{CacheManager, CacheManagerRef};
use crate::compaction::picker::PickerOutput;
use crate::compaction::reader::CompactionSstReaderBuilder;
use crate::compaction::reader::{CompactionSstReaderBuilder, spawn_merge};
use crate::compaction::unit::CompactionUnit;
use crate::compaction::{CompactionOutput, find_dynamic_options};
use crate::config::MitoConfig;
@@ -59,6 +59,7 @@ use crate::sst::index::intermediate::IntermediateManager;
use crate::sst::index::puffin_manager::PuffinManagerFactory;
use crate::sst::location::region_dir_from_table_dir;
use crate::sst::parquet::metadata::extract_primary_key_range;
use crate::sst::parquet::parallel_writer::EncodeRuntime;
use crate::sst::parquet::{SstInfo, WriteOptions};
use crate::sst::version::{SstVersion, SstVersionRef};
@@ -590,8 +591,9 @@ impl SstMerger for DefaultSstMerger {
filter_deleted: output.filter_deleted,
time_range: output.output_time_range,
merge_mode,
read_parallelism: write_opts.encode_parallelism,
};
let source = builder.build_flat_sst_reader().await?;
let source = spawn_merge(builder.build_flat_sst_reader().await?);
let mut metrics = Metrics::new(WriteType::Compaction);
let region_metadata = context.region_metadata.clone();
@@ -705,6 +707,10 @@ impl DefaultCompactor {
///
/// This is the public entry point for external crates that want a
/// cancellable compactor without opting into uncommitted-SST tracking.
///
/// Cancellation stops new output batches. Already spawned outputs finish,
/// and their successful SSTs remain in the returned [`MergeOutput`]. This
/// can delay cancellation until the current batch completes.
pub fn new_with_cancel_handle(cancel_handle: Arc<CancellationHandle>) -> Self {
Self {
merger: DefaultSstMerger,
@@ -753,6 +759,14 @@ impl<M: SstMerger> DefaultCompactor<M> {
max_file_size: unit.max_file_size,
row_group_size: context.region_options.row_group_size(),
float_field_encoding: context.region_options.float_field_encoding,
encode_parallelism: context
.region_options
.compaction_output_parallelism_or(
context
.engine_config
.experimental_compaction_output_parallelism,
),
encode_runtime: EncodeRuntime::Compact,
},
)
.await?;
@@ -796,6 +810,14 @@ where
max_file_size: picker_output.max_file_size,
row_group_size: compaction_region.region_options.row_group_size(),
float_field_encoding: compaction_region.region_options.float_field_encoding,
encode_parallelism: compaction_region
.region_options
.compaction_output_parallelism_or(
compaction_region
.engine_config
.experimental_compaction_output_parallelism,
),
encode_runtime: EncodeRuntime::Compact,
};
let merger = self.merger.clone();
let context = context.clone();
@@ -820,7 +842,7 @@ where
+ picker_output.expired_ssts.len(),
);
while !tasks.is_empty() {
while !tasks.is_empty() && !self.cancel_handle.is_cancelled() {
let mut chunk: Vec<(Vec<FileMeta>, _)> = Vec::with_capacity(internal_parallelism);
for _ in 0..internal_parallelism {
if let Some(task) = tasks.pop() {
@@ -835,61 +857,41 @@ where
})
.collect();
while let Some((inputs, mut handle)) = spawned.pop() {
let abort_handle = handle.abort_handle();
match CancellableFuture::new(&mut handle, self.cancel_handle.clone()).await {
Ok(Ok(Ok((files, infos)))) => {
// Like merge_unit, cancellation must not drop a writer mid-output:
// its blocking encoders would detach and finalized SSTs could lose
// their owner. Join the whole batch and retain every successful output.
let mut join_error = None;
while let Some((inputs, handle)) = spawned.pop() {
match handle.await {
Ok(Ok((files, infos))) => {
output_files.extend(files);
if hook.is_some() {
all_sst_infos.extend(infos);
}
compacted_inputs.extend(inputs);
}
Ok(Ok(Err(e))) => {
Ok(Err(e)) => {
warn!(
e; "Failed to merge compaction output for region: {}, inputs: [{}]",
region_id,
inputs.iter().map(|f| f.file_id.to_string()).join(",")
);
}
Ok(Err(e)) => {
Err(e) => {
warn!(
"Region {} compaction task join error for inputs: [{}], skipping: {}",
"Region {} compaction task join error for inputs: [{}]: {}",
region_id,
inputs.iter().map(|f| f.file_id.to_string()).join(","),
e
);
// If the cancel handle is cancelled,
// cancel the remaining tasks before returns the error.
if self.cancel_handle.is_cancelled() {
abort_handle.abort();
for (_, handle) in &spawned {
handle.abort();
}
for (_, handle) in spawned {
let _ = handle.await;
}
}
return Err(e).context(error::JoinSnafu);
}
Err(_) => {
debug!(
"Compaction merge cancelled for region: {}, aborting remaining {} spawned tasks",
region_id,
spawned.len(),
);
abort_handle.abort();
for (_, handle) in &spawned {
handle.abort();
}
let _ = handle.await;
for (_, handle) in spawned {
let _ = handle.await;
}
break;
// Drain siblings before propagating the first join error.
join_error.get_or_insert(e);
}
}
}
if let Some(e) = join_error {
return Err(e).context(error::JoinSnafu);
}
if self.cancel_handle.is_cancelled() {
info!("Compaction merge cancelled for region: {}", region_id);
@@ -927,17 +929,22 @@ where
#[cfg(test)]
mod tests {
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};
use std::sync::{Arc, Mutex, Weak};
use std::time::Duration;
use datatypes::arrow::record_batch::RecordBatch;
use parquet::arrow::ArrowWriter;
use store_api::storage::{FileId, RegionId};
use tokio::time::sleep;
use tokio::sync::{mpsc, oneshot};
use tokio::time::timeout;
use super::{DefaultCompactor, *};
use crate::compaction::memory_manager::new_compaction_memory_manager;
use crate::compaction::picker::PickerOutput;
use crate::error::Result;
use crate::sst::file::FileHandle;
use crate::sst::file_purger::NoopFilePurger;
use crate::test_util::sst_util::new_record_batch_by_range;
fn dummy_file_meta() -> FileMeta {
FileMeta {
@@ -1244,6 +1251,7 @@ mod tests {
filter_deleted: true,
time_range: None,
merge_mode: MergeMode::LastRow,
read_parallelism: 1,
}
.build_flat_sst_reader()
.await
@@ -1503,85 +1511,182 @@ mod tests {
);
}
#[derive(Debug)]
struct PendingEncoding {
input_id: FileId,
output_id: FileId,
batch: Weak<RecordBatch>,
release: oneshot::Sender<()>,
}
/// A merger with real blocking Parquet encoding and deterministic lifetime gates.
#[derive(Clone)]
struct BlockingMerger {
call_idx: Arc<AtomicUsize>,
struct GatedEncodingMerger {
started: mpsc::UnboundedSender<PendingEncoding>,
panic_input: Option<FileId>,
}
#[async_trait::async_trait]
impl SstMerger for BlockingMerger {
impl SstMerger for GatedEncodingMerger {
async fn merge_single_output(
&self,
_context: CompactionContext,
_output: CompactionOutput,
output: CompactionOutput,
_write_opts: WriteOptions,
) -> Result<(Vec<FileMeta>, Vec<SstInfo>)> {
self.call_idx.fetch_add(1, Ordering::SeqCst);
std::future::pending().await
let input_id = output.inputs[0].meta_ref().file_id;
let mut file = dummy_file_meta();
let batch = Arc::new(new_record_batch_by_range(&["a", "b"], 0, 4));
let (release, wait) = oneshot::channel();
let pending = PendingEncoding {
input_id,
output_id: file.file_id,
batch: Arc::downgrade(&batch),
release,
};
let started = self.started.clone();
file.file_size = common_runtime::spawn_blocking_compact(move || {
started.send(pending).unwrap();
wait.blocking_recv().unwrap();
let mut bytes = Vec::new();
let mut writer = ArrowWriter::try_new(&mut bytes, batch.schema(), None)?;
writer.write(&batch)?;
writer.close()?;
Ok::<_, parquet::errors::ParquetError>(bytes.len() as u64)
})
.await
.context(error::JoinSnafu)?
.context(error::WriteParquetSnafu)?;
if self.panic_input == Some(input_id) {
panic!("merge task panicked");
}
Ok((vec![file], Vec::new()))
}
}
#[tokio::test(flavor = "multi_thread")]
async fn test_merge_ssts_cancels_spawned_tasks() {
common_telemetry::init_default_ut_logging();
let mut compaction_region = new_test_compaction_region().await;
compaction_region.max_parallelism = 2;
#[rstest::rstest]
#[case::successful_outputs(false)]
#[case::join_error(true)]
#[tokio::test]
async fn test_merge_ssts_cancellation_waits_for_encoders(#[case] panic_merge: bool) {
let mut region = new_test_compaction_region().await;
region.max_parallelism = 2;
region.region_options.compaction_output_parallelism = Some(2);
let inputs: Vec<_> = (0..3).map(|_| dummy_file_meta()).collect();
let picker_output = PickerOutput {
outputs: inputs
.iter()
.map(|input| CompactionOutput {
output_level: 1,
inputs: vec![new_file_handle(input.clone())],
filter_deleted: false,
output_time_range: None,
})
.collect(),
..Default::default()
};
let cancel_handle = Arc::new(CancellationHandle::default());
let call_idx = Arc::new(AtomicUsize::new(0));
let (started_tx, mut started_rx) = mpsc::unbounded_channel();
let compactor = DefaultCompactor {
merger: BlockingMerger {
call_idx: call_idx.clone(),
merger: GatedEncodingMerger {
started: started_tx,
// Outputs are popped from the back, then joined in reverse order.
panic_input: panic_merge.then_some(inputs[1].file_id),
},
cancel_handle: cancel_handle.clone(),
uncommitted: None,
};
let picker_output = PickerOutput {
outputs: vec![
CompactionOutput {
output_level: 1,
inputs: vec![new_file_handle(dummy_file_meta())],
filter_deleted: false,
output_time_range: None,
},
CompactionOutput {
output_level: 1,
inputs: vec![new_file_handle(dummy_file_meta())],
filter_deleted: false,
output_time_range: None,
},
CompactionOutput {
output_level: 1,
inputs: vec![new_file_handle(dummy_file_meta())],
filter_deleted: false,
output_time_range: None,
},
],
expired_ssts: vec![],
time_window_size: 3600,
max_file_size: None,
};
let task = tokio::spawn(async move {
compactor
.merge_ssts(&compaction_region, picker_output)
.await
let memory = new_compaction_memory_manager(1024 * 1024);
let budget = memory.try_acquire(memory.limit_bytes()).unwrap();
let mut merge = Box::pin(async {
let _budget = budget;
compactor.merge_ssts(&region, picker_output).await
});
sleep(Duration::from_millis(100)).await;
assert!(futures::poll!(merge.as_mut()).is_pending());
let mut encoders = Vec::new();
for _ in 0..2 {
encoders.push(
timeout(Duration::from_secs(10), started_rx.recv())
.await
.unwrap()
.unwrap(),
);
}
cancel_handle.cancel();
assert!(futures::poll!(merge.as_mut()).is_pending());
assert!(memory.try_acquire(memory.limit_bytes()).is_none());
assert!(
encoders
.iter()
.all(|encoder| encoder.batch.upgrade().is_some())
);
let retained_batches: Vec<_> = encoders
.iter()
.map(|encoder| encoder.batch.clone())
.collect();
let mut expected_inputs: Vec<_> = encoders.iter().map(|encoder| encoder.input_id).collect();
let mut expected_outputs: Vec<_> =
encoders.iter().map(|encoder| encoder.output_id).collect();
for encoder in encoders {
encoder.release.send(()).unwrap();
}
let result = timeout(Duration::from_secs(10), merge).await.unwrap();
assert!(
retained_batches
.iter()
.all(|batch| batch.upgrade().is_none())
);
assert!(memory.try_acquire(memory.limit_bytes()).is_some());
assert!(
started_rx.try_recv().is_err(),
"cancelled work must not start another output"
);
if panic_merge {
assert!(matches!(result, Err(error::Error::Join { error, .. }) if error.is_panic()));
} else {
let merged = result.unwrap();
let mut removed: Vec<_> = merged
.files_to_remove
.iter()
.map(|file| file.file_id)
.collect();
let mut added: Vec<_> = merged
.files_to_add
.iter()
.map(|file| file.file_id)
.collect();
for ids in [
&mut removed,
&mut added,
&mut expected_inputs,
&mut expected_outputs,
] {
ids.sort_by(|a, b| a.as_bytes().cmp(b.as_bytes()));
}
assert_eq!(expected_inputs, removed);
assert_eq!(expected_outputs, added);
assert!(merged.files_to_add.iter().all(|file| file.file_size > 0));
}
}
let merge_output = task
.await
.expect("merge_ssts should stop after cancellation")
.unwrap();
let started = call_idx.load(Ordering::SeqCst);
assert!(merge_output.files_to_add.is_empty());
assert!(merge_output.files_to_remove.is_empty());
assert_eq!(started, 2);
#[tokio::test]
async fn test_merge_ssts_cancelled_before_start_skips_outputs() {
let region = new_test_compaction_region().await;
let merger = MockMerger::new(vec![Ok(vec![dummy_file_meta()])]);
let calls = merger.call_idx.clone();
let compactor = DefaultCompactor::with_merger(merger);
compactor.cancel_handle.cancel();
let picker_output = PickerOutput {
outputs: vec![CompactionOutput {
output_level: 1,
inputs: vec![new_file_handle(dummy_file_meta())],
filter_deleted: false,
output_time_range: None,
}],
..Default::default()
};
let merged = compactor.merge_ssts(&region, picker_output).await.unwrap();
assert!(merged.is_empty());
assert_eq!(0, calls.load(Ordering::SeqCst));
}
}
+16
View File
@@ -36,6 +36,7 @@ use crate::read::flat_projection::FlatProjectionMapper;
use crate::read::read_columns::ReadColumns;
use crate::read::scan_region::{PredicateGroup, ScanInput};
use crate::read::seq_scan::SeqScan;
use crate::read::stream::spawn_compact_stream;
use crate::region::options::MergeMode;
use crate::sst::file::FileHandle;
use crate::sst::parquet::reader::MetadataCacheMetrics;
@@ -51,6 +52,8 @@ pub(crate) struct CompactionSstReaderBuilder<'a> {
pub(crate) filter_deleted: bool,
pub(crate) time_range: Option<TimestampRange>,
pub(crate) merge_mode: MergeMode,
/// Max number of inputs decoded concurrently ahead of the merge.
pub(crate) read_parallelism: usize,
}
impl CompactionSstReaderBuilder<'_> {
@@ -131,6 +134,7 @@ impl CompactionSstReaderBuilder<'_> {
.with_json2_rewrite_targets(targets)
.with_files(self.inputs.to_vec())
.with_compaction(true)
.with_compaction_read_parallelism(self.read_parallelism)
.with_batch_size(batch_size)
.with_append_mode(self.append_mode)
// We use special cache strategy for compaction.
@@ -180,6 +184,17 @@ impl CompactionSstReaderBuilder<'_> {
}
}
/// Number of merged batches buffered between the merge task and the SST writer.
const MERGED_BATCH_CHANNEL_SIZE: usize = 2;
/// Reads and merges `source` on a separate task, so the SST writer can encode
/// merged batches while the next ones are being read and merged.
pub(crate) fn spawn_merge(source: FlatSource) -> FlatSource {
let schema = source.schema().clone();
let stream = spawn_compact_stream(source.into_stream(), MERGED_BATCH_CHANNEL_SIZE, None);
FlatSource::new_stream(schema, stream)
}
/// Converts time range to predicates so that rows outside the range will be filtered.
fn time_range_to_predicate(
range: TimestampRange,
@@ -304,6 +319,7 @@ mod tests {
filter_deleted: true,
time_range: None,
merge_mode: MergeMode::LastRow,
read_parallelism: 1,
}
.build_flat_sst_reader()
.await
@@ -1846,6 +1846,7 @@ async fn test_compaction_bypass_in_staging_mode() {
manifest_cache: None,
},
FormatType::PrimaryKey,
false,
&Default::default(),
)
.await
+1
View File
@@ -356,6 +356,7 @@ mod tests {
auto_flush_interval: None,
compaction: Default::default(),
compaction_override: false,
compaction_output_parallelism: None,
storage: None,
append_mode: false,
skip_wal: false,
+5
View File
@@ -129,6 +129,10 @@ pub struct MitoConfig {
pub experimental_compaction_memory_limit: MemoryLimit,
/// Behavior when compaction cannot acquire memory from the budget.
pub experimental_compaction_on_exhausted: OnExhaustedPolicy,
/// Default per-output parallelism for input decoding and SST column encoding,
/// bounded independently per stage. Values below 2 disable both.
/// Tables can override it with `compaction.experimental_output_parallelism`.
pub experimental_compaction_output_parallelism: usize,
// Flush configs:
/// Interval to auto flush a region if it has not flushed yet (default 10 min).
@@ -247,6 +251,7 @@ impl Default for MitoConfig {
max_background_purges: get_total_cpu_cores(),
experimental_compaction_memory_limit: MemoryLimit::Unlimited,
experimental_compaction_on_exhausted: OnExhaustedPolicy::default(),
experimental_compaction_output_parallelism: 1,
auto_flush_interval: Duration::from_secs(10 * 60),
global_write_buffer_size: ReadableSize::gb(1),
global_write_buffer_reject_size: ReadableSize::gb(2),
+11 -3
View File
@@ -74,6 +74,8 @@ mod scan_corrupt;
#[cfg(test)]
mod scan_test;
#[cfg(test)]
mod sequence_test;
#[cfg(test)]
mod set_role_state_test;
#[cfg(test)]
mod skip_wal_test;
@@ -1603,15 +1605,21 @@ impl RegionEngine for MitoEngine {
&self,
region_id: RegionId,
role: RegionRole,
sent_at: Instant,
deadline: Instant,
) -> Result<(), BoxedError> {
) -> Result<bool, BoxedError> {
let region = self.inner.find_region(region_id).map_err(BoxedError::new)?;
// Before the role, and even if the role leaves the region's state unchanged.
if role.writable() {
region.leader_deadline.extend(deadline);
region.manifest_ctx.leader_deadline.extend(deadline);
}
if role == RegionRole::Leader {
return Ok(region
.manifest_ctx
.promote_unless_downgrade_started_after(sent_at, region_id));
}
region.set_role(role);
Ok(())
Ok(true)
}
async fn set_region_role_state_gracefully(
+65
View File
@@ -2073,6 +2073,68 @@ async fn test_alter_twcs_option_enables_compaction_override() {
assert!(compaction_override());
}
#[tokio::test]
async fn test_alter_compaction_output_parallelism_preserves_existing_snapshots() {
let mut env = TestEnv::new().await;
let engine = env.create_engine(MitoConfig::default()).await;
let region_id = RegionId::new(1, 1);
engine
.handle_request(
region_id,
RegionRequest::Create(
CreateRequestBuilder::new()
.insert_option("compaction.experimental_output_parallelism", "4")
.build(),
),
)
.await
.unwrap();
let region = engine.get_region(region_id).unwrap();
let initial_version = region.version();
assert_eq!(
Some(4),
initial_version.options.compaction_output_parallelism
);
for (kind, expected) in [
(
AlterKind::SetRegionOptions {
options: vec![SetRegionOption::CompactionOutputParallelism(Some(1))],
},
Some(1),
),
(
AlterKind::UnsetRegionOptions {
keys: vec![UnsetRegionOption::CompactionOutputParallelism],
},
None,
),
] {
engine
.handle_request(region_id, RegionRequest::Alter(RegionAlterRequest { kind }))
.await
.unwrap();
let version = region.version();
assert_eq!(expected, version.options.compaction_output_parallelism);
assert!(!version.options.compaction_override);
assert_eq!(
initial_version.options.compaction,
version.options.compaction
);
assert_eq!(
Some(4),
initial_version.options.compaction_output_parallelism
);
}
// Direct engine callers must get the same validation as SQL callers.
let invalid = RegionRequest::Alter(RegionAlterRequest {
kind: AlterKind::SetRegionOptions {
options: vec![SetRegionOption::CompactionOutputParallelism(Some(0))],
},
});
assert!(engine.handle_request(region_id, invalid).await.is_err());
assert_eq!(None, region.version().options.compaction_output_parallelism);
}
#[tokio::test]
async fn test_mixed_region_options_are_published_after_flush() {
let mut env = TestEnv::new().await;
@@ -2122,6 +2184,7 @@ async fn test_mixed_region_options_are_published_after_flush() {
"2h".to_string(),
),
SetRegionOption::MaxRowGroupRowCount(Some(1024)),
SetRegionOption::CompactionOutputParallelism(Some(4)),
],
},
}),
@@ -2135,6 +2198,7 @@ async fn test_mixed_region_options_are_published_after_flush() {
assert_eq!(None, version.options.ttl);
assert!(!version.options.compaction_override);
assert_eq!(None, version.options.max_row_group_row_count);
assert_eq!(None, version.options.compaction_output_parallelism);
listener.wake_flush();
alter_job.await.unwrap();
@@ -2143,6 +2207,7 @@ async fn test_mixed_region_options_are_published_after_flush() {
assert_eq!(Some(Duration::from_secs(500).into()), version.options.ttl);
assert!(version.options.compaction_override);
assert_eq!(Some(1024), version.options.max_row_group_row_count);
assert_eq!(Some(4), version.options.compaction_output_parallelism);
}
#[tokio::test(flavor = "multi_thread")]
@@ -22,8 +22,8 @@ use common_error::status_code::StatusCode;
use common_recordbatch::{DfRecordBatch, RecordBatches};
use common_test_util::flight::encode_to_flight_data;
use datatypes::arrow::array::{
ArrayRef, Float64Array, Int64Array, LargeStringArray, ListArray, StringArray, StringViewArray,
TimestampMillisecondArray, TimestampSecondArray,
ArrayRef, BinaryArray, Float64Array, Int64Array, LargeStringArray, ListArray, StringArray,
StringViewArray, TimestampMillisecondArray, TimestampSecondArray,
};
use datatypes::arrow::datatypes::{Field, Int64Type, Schema};
use datatypes::prelude::ConcreteDataType;
@@ -91,6 +91,101 @@ async fn scan_num_rows(engine: &MitoEngine, region_id: RegionId) -> usize {
batches.iter().map(|batch| batch.num_rows()).sum()
}
#[tokio::test]
async fn test_encoded_sparse_keys_reject_whole_batch_and_replay() {
use api::v1::value::ValueData;
use api::v1::{ColumnDataType, WriteHint};
use mito_codec::row_converter::SparsePrimaryKeyCodec;
for bulk in [false, true] {
let mut env = TestEnv::new().await;
let engine = env.create_engine(MitoConfig::default()).await;
let region_id = RegionId::new(1, 1);
let mut create = CreateRequestBuilder::new()
.insert_option("primary_key_encoding", "sparse")
.build();
let reserved = crate::test_util::sst_util::sst_region_metadata_with_encoding(
store_api::codec::PrimaryKeyEncoding::Sparse,
);
create
.column_metadatas
.extend(reserved.column_metadatas.into_iter().take(2));
create
.primary_key
.splice(0..0, reserved.primary_key.into_iter().take(2));
let table_dir = create.table_dir.clone();
let options = create.options.clone();
let mut schema = rows_schema(&create);
schema.truncate(3);
schema[0].column_name = "__primary_key".to_string();
schema[0].datatype = ColumnDataType::Binary as i32;
schema.swap(1, 2);
engine
.handle_request(region_id, RegionRequest::Create(create))
.await
.unwrap();
let codec = SparsePrimaryKeyCodec::schemaless();
let mut key = Vec::new();
codec.encode_internal(42, 7, &mut key).unwrap();
codec
.encode_raw_tag_value([(0, "1234567🦀".as_bytes())].into_iter(), &mut key)
.unwrap();
let mut malformed = key.clone();
malformed.push(0); // A truncated label ID after a valid Unicode label.
let request = |second: &[u8]| {
if bulk {
bulk_request(
region_id,
vec![
column(
"__primary_key",
Arc::new(BinaryArray::from_vec(vec![key.as_slice(), second])),
),
field(),
ts(),
],
)
} else {
let mut rows = build_rows(0, 2);
for (row, key) in rows.iter_mut().zip([key.as_slice(), second]) {
row.values[0].value_data = Some(ValueData::BinaryValue(key.to_vec()));
row.values.swap(1, 2);
}
RegionRequest::Put(RegionPutRequest {
rows: Rows {
schema: schema.clone(),
rows,
},
hint: Some(WriteHint {
primary_key_encoding: api::v1::PrimaryKeyEncoding::Sparse as i32,
}),
skip_wal: false,
partition_expr_version: None,
})
}
};
let error = engine
.handle_request(region_id, request(&malformed))
.await
.unwrap_err();
assert_eq!(StatusCode::InvalidArguments, error.status_code());
assert_eq!(0, scan_num_rows(&engine, region_id).await);
// Byte validation follows WAL append; replay must also discard the malformed batch.
reopen_region(&engine, region_id, table_dir.clone(), true, options.clone()).await;
assert_eq!(0, scan_num_rows(&engine, region_id).await);
engine
.handle_request(region_id, request(&key))
.await
.unwrap();
assert_eq!(2, scan_num_rows(&engine, region_id).await);
reopen_region(&engine, region_id, table_dir, true, options).await;
assert_eq!(2, scan_num_rows(&engine, region_id).await);
engine.stop().await.unwrap();
}
}
/// Batches that do not match the region schema are rejected before they are
/// appended to the WAL, and the region keeps accepting writes.
#[tokio::test]
@@ -128,6 +223,28 @@ async fn test_bulk_insert_rejects_batches_not_matching_schema() {
column("ts", Arc::new(TimestampSecondArray::from(vec![0, 1]))),
],
vec![tag(), field()],
vec![field(), ts()],
vec![
column("tag_0", Arc::new(Int64Array::from(vec![1, 2]))),
field(),
ts(),
],
vec![
column(
"__primary_key",
Arc::new(Float64Array::from(vec![1.0, 2.0])),
),
field(),
ts(),
],
vec![
column(
"__primary_key",
Arc::new(BinaryArray::from(vec![None::<&[u8]>; 2])),
),
field(),
ts(),
],
vec![
tag(),
column("field_0", Arc::new(StringArray::from(vec!["1", "2"]))),
@@ -301,6 +418,7 @@ async fn test_bulk_insert_fills_columns_missing_from_aligned_batch() {
let engine = env.create_engine(MitoConfig::default()).await;
let region_id = RegionId::new(1, i as u32 + 1);
let request = CreateRequestBuilder::new()
.tag_num(2)
.insert_option("sst_format", sst_format)
.build();
let table_dir = request.table_dir.clone();
@@ -325,5 +443,192 @@ async fn test_bulk_insert_fills_columns_missing_from_aligned_batch() {
assert_eq!(2, response.affected_rows, "{sst_format}");
reopen_region(&engine, region_id, table_dir, true, options).await;
assert_eq!(2, scan_num_rows(&engine, region_id).await, "{sst_format}");
let stream = engine
.scan_to_stream(region_id, ScanRequest::default())
.await
.unwrap();
let batches = RecordBatches::try_collect(stream).await.unwrap();
for batch in batches.iter() {
let tag = batch.column_by_name("tag_1").unwrap();
assert_eq!(tag.null_count(), batch.num_rows());
}
}
}
#[tokio::test]
async fn test_bulk_insert_json2_physical_layout() {
use datatypes::arrow::array::{NullArray, StructArray};
use datatypes::arrow::datatypes::DataType;
use datatypes::extension::json::{Json2ExtensionType, JsonMetadata};
use datatypes::json::JsonSettings;
use datatypes::types::json_type::JsonNativeType;
for encoding in ["dense", "sparse"] {
for layout in ["v2", "legacy", "missing"] {
let mut env = TestEnv::new().await;
let engine = env.create_engine(MitoConfig::default()).await;
let region_id = RegionId::new(1, 1);
let settings = JsonSettings::default();
let mut request = CreateRequestBuilder::new()
.field_datatype(ConcreteDataType::json2(JsonNativeType::Null))
.insert_option("sst_format", "flat")
.insert_option("primary_key_encoding", encoding)
.build();
if encoding == "sparse" {
let reserved = crate::test_util::sst_util::sst_region_metadata_with_encoding(
store_api::codec::PrimaryKeyEncoding::Sparse,
);
request
.column_metadatas
.extend(reserved.column_metadatas.into_iter().take(2));
request
.primary_key
.splice(0..0, reserved.primary_key.into_iter().take(2));
}
let key_columns = if encoding == "sparse" {
let codec = mito_codec::row_converter::SparsePrimaryKeyCodec::schemaless();
let keys: Vec<_> = (1..=2)
.map(|tsid| {
let mut key = Vec::new();
codec.encode_internal(42, tsid, &mut key).unwrap();
key
})
.collect();
vec![
column(
"__primary_key",
Arc::new(BinaryArray::from_iter_values(&keys)),
),
ts(),
]
} else {
vec![tag(), ts()]
};
let json_column = &mut request.column_metadatas[1].column_schema;
json_column.with_extension_type(&Json2ExtensionType::new(Arc::new(JsonMetadata::new(
settings.clone(),
))));
let mut columns = key_columns.clone();
if layout != "missing" {
let (array, metadata) = if layout == "legacy" {
let array = Arc::new(StructArray::from(vec![(
Arc::new(Field::new("trace_id", DataType::Utf8, true)),
Arc::new(StringArray::from(vec!["abc", "def"])) as ArrayRef,
)])) as ArrayRef;
(array, JsonMetadata::new_v1(settings.clone()))
} else {
let mut builder = json_column.create_mutable_vector(2);
for id in ["abc", "def"] {
let value = settings
.encode(serde_json::json!({"trace_id": id}))
.unwrap();
builder.try_push_value_ref(&value.as_value_ref()).unwrap();
}
(
builder.to_vector().to_arrow_array(),
JsonMetadata::new(settings.clone()),
)
};
let field = Field::new("field_0", array.data_type().clone(), true)
.with_extension_type(Json2ExtensionType::new(Arc::new(metadata)));
columns.push((field, array));
}
let table_dir = request.table_dir.clone();
let options = request.options.clone();
engine
.handle_request(region_id, RegionRequest::Create(request))
.await
.unwrap();
if layout == "v2" {
let malformed = Arc::new(StructArray::from(vec![(
Arc::new(Field::new(
datatypes::json::JSON2_REMAINDER_FIELD_NAME,
DataType::Int64,
true,
)),
Arc::new(Int64Array::from(vec![1, 2])) as ArrayRef,
)])) as ArrayRef;
for malformed in [
malformed,
Arc::new(StringArray::from(vec!["abc", "def"])) as ArrayRef,
] {
let malformed_field =
Field::new("field_0", malformed.data_type().clone(), true)
.with_extension_type(Json2ExtensionType::new(Arc::new(
JsonMetadata::new(settings.clone()),
)));
let error = engine
.handle_request(
region_id,
bulk_request(
region_id,
[key_columns.clone(), vec![(malformed_field, malformed)]].concat(),
),
)
.await
.unwrap_err();
assert_eq!(error.status_code(), StatusCode::InvalidArguments);
}
let mut invalid_layout =
serde_json::to_value(JsonMetadata::new(settings.clone())).unwrap();
invalid_layout["layout_version"] = serde_json::json!(3);
let mut null_field = Field::new("field_0", DataType::Null, true)
.with_extension_type(Json2ExtensionType::new(Arc::new(JsonMetadata::new(
settings.clone(),
))));
null_field.metadata_mut().insert(
arrow_schema::extension::EXTENSION_TYPE_METADATA_KEY.to_string(),
invalid_layout.to_string(),
);
let error = engine
.handle_request(
region_id,
bulk_request(
region_id,
[
key_columns.clone(),
vec![(null_field, Arc::new(NullArray::new(2)) as ArrayRef)],
]
.concat(),
),
)
.await
.unwrap_err();
assert_eq!(error.status_code(), StatusCode::InvalidArguments);
}
let response = engine
.handle_request(region_id, bulk_request(region_id, columns))
.await
.unwrap();
assert_eq!(response.affected_rows, 2);
for phase in 0..3 {
if phase == 1 {
reopen_region(&engine, region_id, table_dir.clone(), true, options.clone())
.await;
} else if phase == 2 {
crate::test_util::flush_region(&engine, region_id, None).await;
}
let stream = engine
.scan_to_stream(region_id, ScanRequest::default())
.await
.unwrap();
let batches = RecordBatches::try_collect(stream).await.unwrap();
assert_eq!(batches.iter().map(|b| b.num_rows()).sum::<usize>(), 2);
let printed = batches.pretty_print().unwrap();
if layout != "missing" {
assert!(
printed.contains("abc") && printed.contains("def"),
"{encoding}/{layout}/{phase}: {printed}"
);
} else {
for batch in batches.iter() {
assert_eq!(
batch.column_by_name("field_0").unwrap().null_count(),
batch.num_rows()
);
}
}
}
}
}
}
+267 -24
View File
@@ -14,6 +14,7 @@
use std::assert_matches;
use std::collections::HashMap;
use std::sync::Arc;
use api::v1::Rows;
use common_error::ext::ErrorExt;
@@ -32,6 +33,7 @@ use store_api::storage::{RegionId, ScanRequest};
use crate::config::MitoConfig;
use crate::engine::MitoEngine;
use crate::error::Error;
use crate::manifest::action::RegionEdit;
use crate::test_util::{
CreateRequestBuilder, LogStoreFactory, TestEnv, build_rows, flush_region,
kafka_log_store_factory, prepare_test_for_kafka_log_store, put_rows,
@@ -168,6 +170,220 @@ async fn test_catchup_with_last_entry_id(factory: Option<LogStoreFactory>) {
assert!(resp.is_ok());
}
#[apply(single_kafka_log_store_factory)]
async fn test_catchup_preserves_region_edit_sequence(
factory: Option<LogStoreFactory>,
#[values(false, true)] open_before_edit: bool,
) {
use store_api::region_engine::SettableRegionRoleState;
common_telemetry::init_default_ut_logging();
let Some(factory) = factory else {
return;
};
let mut env = TestEnv::with_prefix("catchup_edit_sequence")
.await
.with_log_store_factory(factory.clone());
let topic = prepare_test_for_kafka_log_store(&factory).await.unwrap();
let config = MitoConfig {
schedule_compaction_after_edit: false,
..Default::default()
};
let leader_engine = env.create_engine(config.clone()).await;
let follower_engine = env.create_follower_engine(config).await;
let region_id = RegionId::new(1, 1);
let request = CreateRequestBuilder::new()
.kafka_topic(Some(topic.clone()))
.build();
let column_schemas = rows_schema(&request);
let open_request = RegionOpenRequest {
engine: String::new(),
table_dir: request.table_dir.clone(),
path_type: PathType::Bare,
options: HashMap::from([(
WAL_OPTIONS_KEY.to_string(),
serde_json::to_string(&WalOptions::Kafka(KafkaWalOptions::new(topic))).unwrap(),
)]),
skip_wal_replay: true,
checkpoint: None,
requirements: Default::default(),
};
leader_engine
.handle_request(region_id, RegionRequest::Create(request))
.await
.unwrap();
put_rows(
&leader_engine,
region_id,
Rows {
schema: column_schemas.clone(),
rows: build_rows(0, 3),
},
)
.await;
flush_region(&leader_engine, region_id, None).await;
let leader = leader_engine.get_region(region_id).unwrap();
let flushed_entry_id = leader.version().flushed_entry_id;
let flushed_sequence = leader.version().flushed_sequence;
let flushed_rows = scan_region(&leader_engine, region_id)
.await
.pretty_print()
.unwrap();
put_rows(
&leader_engine,
region_id,
Rows {
schema: column_schemas.clone(),
rows: build_rows(3, 5),
},
)
.await;
let unflushed = leader.version_control.current();
let unflushed_entry_id = unflushed.last_entry_id;
assert!(unflushed_entry_id > flushed_entry_id);
assert_eq!(unflushed.version.flushed_entry_id, flushed_entry_id);
if open_before_edit {
follower_engine
.handle_request(region_id, RegionRequest::Open(open_request.clone()))
.await
.unwrap();
}
// Reuses the flushed SST without flushing the second batch.
let file = leader.version().ssts.levels()[0]
.files
.values()
.next()
.unwrap()
.meta_ref()
.clone();
leader_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 edit_sequence = leader.version_control.committed_sequence();
assert!(edit_sequence > unflushed.committed_sequence);
let expected_rows = scan_region(&leader_engine, region_id)
.await
.pretty_print()
.unwrap();
assert_ne!(flushed_rows, expected_rows);
if !open_before_edit {
follower_engine
.handle_request(region_id, RegionRequest::Open(open_request))
.await
.unwrap();
}
let candidate_before_catchup = follower_engine.get_region(region_id).unwrap();
let before_catchup = candidate_before_catchup.version_control.current();
assert!(candidate_before_catchup.provider.is_remote_wal());
assert!(before_catchup.version.memtables.is_empty());
assert_eq!(before_catchup.last_entry_id, flushed_entry_id);
assert_eq!(
before_catchup.committed_sequence,
if open_before_edit {
flushed_sequence
} else {
edit_sequence
}
);
assert_eq!(
scan_region(&follower_engine, region_id)
.await
.pretty_print()
.unwrap(),
flushed_rows
);
let resp = leader_engine
.set_region_role_state_gracefully(region_id, SettableRegionRoleState::Follower)
.await
.unwrap();
let last_entry_id = get_last_entry_id(resp);
assert_eq!(last_entry_id, Some(unflushed_entry_id));
assert_eq!(leader.version().flushed_entry_id, flushed_entry_id);
assert!(!leader.version().memtables.is_empty());
follower_engine
.handle_request(
region_id,
RegionRequest::Catchup(RegionCatchupRequest {
set_writable: true,
entry_id: last_entry_id,
..Default::default()
}),
)
.await
.unwrap();
let candidate = follower_engine.get_region(region_id).unwrap();
assert!(candidate.is_writable());
assert_eq!(
Arc::ptr_eq(
&candidate_before_catchup.version_control,
&candidate.version_control
),
!open_before_edit
);
let recovered = candidate.version_control.current();
assert!(recovered.last_entry_id >= unflushed_entry_id);
assert_eq!(recovered.version.flushed_entry_id, flushed_entry_id);
assert!(recovered.committed_sequence >= edit_sequence);
assert!(recovered.last_sequence >= recovered.committed_sequence);
assert!(!recovered.version.memtables.is_empty());
assert_eq!(
scan_region(&follower_engine, region_id)
.await
.pretty_print()
.unwrap(),
expected_rows
);
put_rows(
&follower_engine,
region_id,
Rows {
schema: column_schemas,
rows: build_rows(5, 6),
},
)
.await;
let current = candidate.version_control.current();
assert_eq!(current.committed_sequence, recovered.last_sequence + 1);
assert!(current.committed_sequence > edit_sequence);
assert!(current.last_sequence >= current.committed_sequence);
let expected = "\
+-------+---------+---------------------+
| tag_0 | field_0 | ts |
+-------+---------+---------------------+
| 0 | 0.0 | 1970-01-01T00:00:00 |
| 1 | 1.0 | 1970-01-01T00:00:01 |
| 2 | 2.0 | 1970-01-01T00:00:02 |
| 3 | 3.0 | 1970-01-01T00:00:03 |
| 4 | 4.0 | 1970-01-01T00:00:04 |
| 5 | 5.0 | 1970-01-01T00:00:05 |
+-------+---------+---------------------+";
assert_eq!(
scan_region(&follower_engine, region_id)
.await
.pretty_print()
.unwrap(),
expected
);
}
#[apply(single_kafka_log_store_factory)]
async fn test_catchup_with_incorrect_last_entry_id(factory: Option<LogStoreFactory>) {
use store_api::region_engine::SettableRegionRoleState;
@@ -536,7 +752,10 @@ async fn scan_region(engine: &MitoEngine, region_id: RegionId) -> RecordBatches
}
#[apply(single_raft_engine_log_store_factory)]
async fn test_local_catchup(factory: Option<LogStoreFactory>) {
async fn test_local_catchup(
factory: Option<LogStoreFactory>,
#[values(false, true)] reopen_before_catchup: bool,
) {
use store_api::region_engine::SettableRegionRoleState;
use crate::test_util::LogStoreImpl;
@@ -599,6 +818,10 @@ async fn test_local_catchup(factory: Option<LogStoreFactory>) {
rows: build_rows(8, 9),
};
put_rows(&leader_engine, region_id, rows).await;
let old_region = leader_engine.get_region(region_id).unwrap();
if !reopen_before_catchup {
old_region.version_control.update_last_sequence(10);
}
let resp = leader_engine
.set_region_role_state_gracefully(region_id, SettableRegionRoleState::Follower)
.await
@@ -606,27 +829,27 @@ async fn test_local_catchup(factory: Option<LogStoreFactory>) {
let last_entry_id = get_last_entry_id(resp);
assert_eq!(last_entry_id.unwrap(), 3);
close_region(&leader_engine, region_id).await;
// Reopen the region, and skip the wal replay.
leader_engine
.handle_request(
region_id,
RegionRequest::Open(RegionOpenRequest {
engine: String::new(),
table_dir: table_dir.clone(),
options: HashMap::new(),
skip_wal_replay: true,
path_type: PathType::Bare,
checkpoint: None,
requirements: Default::default(),
}),
)
.await
.unwrap();
assert_eq!(old_region.version_control.committed_sequence(), 7);
// The last entry id should be 1.
let region = leader_engine.get_region(region_id).unwrap();
assert_eq!(region.version_control.current().last_entry_id, 1);
if reopen_before_catchup {
close_region(&leader_engine, region_id).await;
open_region(&leader_engine, region_id, table_dir, true).await;
}
let region_before_catchup = leader_engine.get_region(region_id).unwrap();
let current = region_before_catchup.version_control.current();
if reopen_before_catchup {
assert!(current.version.memtables.is_empty());
assert_eq!(
(
current.last_sequence,
current.committed_sequence,
current.last_entry_id
),
(3, 3, 1)
);
} else {
assert!(!current.version.memtables.is_empty());
}
// There are 2 entries in the log store.
let (start, end) = log_store.span(&RaftEngineProvider::new(region_id.into()));
@@ -644,9 +867,24 @@ async fn test_local_catchup(factory: Option<LogStoreFactory>) {
)
.await;
assert!(resp.is_ok());
// After catchup, the last entry id should be 3.
let region = leader_engine.get_region(region_id).unwrap();
assert_eq!(region.version_control.current().last_entry_id, 3);
assert_eq!(
Arc::ptr_eq(
&region_before_catchup.version_control,
&region.version_control
),
reopen_before_catchup
);
let expected_last_sequence = if reopen_before_catchup { 3 } else { 10 };
let current = region.version_control.current();
assert_eq!(
(
current.last_sequence,
current.committed_sequence,
current.last_entry_id
),
(expected_last_sequence, 3, 3)
);
// The log store has been obsoleted these 2 entries.
let (start, end) = log_store.span(&RaftEngineProvider::new(region_id.into()));
@@ -654,7 +892,7 @@ async fn test_local_catchup(factory: Option<LogStoreFactory>) {
assert_eq!(end, None);
// For local WAL, entries are not replayed during catchup.
// Therefore, any rows that were not flushed before closing the region will not be visible.
// Therefore, any rows that were not flushed before reopening the region will not be visible.
let batches = scan_region(&leader_engine, region_id).await;
let expected = "\
+-------+---------+---------------------+
@@ -672,6 +910,11 @@ async fn test_local_catchup(factory: Option<LogStoreFactory>) {
rows: build_rows(4, 7),
};
put_rows(&leader_engine, region_id, rows).await;
let current = region.version_control.current();
assert_eq!(
(current.last_sequence, current.committed_sequence),
(expected_last_sequence + 3, expected_last_sequence + 3)
);
let batches = scan_region(&leader_engine, region_id).await;
let expected = "\
+25 -6
View File
@@ -2890,16 +2890,29 @@ async fn test_worker_shutdown_fails_picking_waiter() {
#[tokio::test]
async fn test_compaction_region() {
test_compaction_region_with_format(false).await;
test_compaction_region_with_format(true).await;
for (engine_parallelism, table_parallelism) in [
(1, None),
(4, None),
(1, Some(4)),
(4, Some(1)),
(1, Some(usize::MAX)),
] {
test_compaction_region_with_format(false, engine_parallelism, table_parallelism).await;
test_compaction_region_with_format(true, engine_parallelism, table_parallelism).await;
}
}
async fn test_compaction_region_with_format(flat_format: bool) {
async fn test_compaction_region_with_format(
flat_format: bool,
output_parallelism: usize,
table_parallelism: Option<usize>,
) {
common_telemetry::init_default_ut_logging();
let mut env = TestEnv::new().await;
let engine = env
.create_engine(MitoConfig {
default_flat_format: flat_format,
experimental_compaction_output_parallelism: output_parallelism,
..Default::default()
})
.await;
@@ -2916,10 +2929,16 @@ async fn test_compaction_region_with_format(flat_format: bool) {
)
.await;
let request = CreateRequestBuilder::new()
let mut builder = CreateRequestBuilder::new()
.insert_option("compaction.type", "twcs")
.insert_option("experimental_sst_float_field_encoding", "byte_stream_split")
.build();
.insert_option("experimental_sst_float_field_encoding", "byte_stream_split");
if let Some(parallelism) = table_parallelism {
builder = builder.insert_option(
"compaction.experimental_output_parallelism",
&parallelism.to_string(),
);
}
let request = builder.build();
let column_schemas = request
.column_metadatas
+50 -13
View File
@@ -117,6 +117,46 @@ async fn test_engine_column_compression_validation() {
assert_eq!(StatusCode::InvalidArguments, err.status_code());
}
#[tokio::test]
async fn test_engine_create_sparse_requires_reserved_columns() {
let mut env = TestEnv::new().await;
let engine = env.create_engine(MitoConfig::default()).await;
let region_id = RegionId::new(1, 1);
let mut request = CreateRequestBuilder::new()
.insert_option("primary_key_encoding", "sparse")
.insert_option("sst_format", "flat")
.build();
let error = engine
.handle_request(region_id, RegionRequest::Create(request.clone()))
.await
.unwrap_err();
assert_eq!(StatusCode::InvalidArguments, error.status_code());
assert!(
error
.output_msg()
.contains("sparse primary keys must start with (__table_id, __tsid)")
);
assert!(!engine.is_region_exists(region_id));
let metadata = sst_region_metadata_with_encoding(PrimaryKeyEncoding::Sparse);
request.column_metadatas = metadata.column_metadatas;
request.primary_key = metadata.primary_key;
engine
.handle_request(region_id, RegionRequest::Create(request.clone()))
.await
.unwrap();
let expected = engine.get_region(region_id).unwrap().metadata();
reopen_region(
&engine,
region_id,
request.table_dir,
false,
request.options,
)
.await;
assert_eq!(expected, engine.get_region(region_id).unwrap().metadata());
}
#[tokio::test]
async fn test_engine_create_new_region() {
test_engine_create_new_region_with_format(false).await;
@@ -470,7 +510,7 @@ async fn test_engine_create_preserves_manifest_on_open_error() -> WhateverResult
}
#[tokio::test]
async fn test_engine_create_json2_sparse_requires_flat() -> WhateverResult<()> {
async fn test_engine_create_json2_sparse_forces_flat() -> WhateverResult<()> {
let mut env = TestEnv::with_prefix("create-json2-sparse").await;
let engine = env.create_engine(MitoConfig::default()).await;
let region_id = RegionId::new(1, 1);
@@ -489,21 +529,18 @@ async fn test_engine_create_json2_sparse_requires_flat() -> WhateverResult<()> {
request.column_metadatas = metadata.column_metadatas.clone();
request.primary_key = metadata.primary_key.clone();
request.column_metadatas[4].column_schema = json_column;
let err = engine
.handle_request(region_id, RegionRequest::Create(request.clone()))
.await
.unwrap_err();
assert_eq!(StatusCode::InvalidArguments, err.status_code());
assert!(
err.output_msg()
.contains("JSON2 columns require sst_format=flat")
);
assert!(!engine.is_region_exists(region_id));
request.options.insert("sst_format".into(), "flat".into());
engine
.handle_request(region_id, RegionRequest::Create(request.clone()))
.await?;
assert_eq!(
Some(FormatType::Flat),
engine
.get_region(region_id)
.unwrap()
.version()
.options
.sst_format
);
let schema = rows_schema(&request);
let mut pk_schema = schema[0].clone();
pk_schema.column_name = PRIMARY_KEY_COLUMN_NAME.into();
+67 -1
View File
@@ -26,7 +26,7 @@ use common_time::util::current_time_millis;
use datatypes::arrow::array::{ArrayRef, Float64Array, StringArray, TimestampMillisecondArray};
use datatypes::arrow::datatypes::{DataType, Field, Schema, TimeUnit};
use object_store::ObjectStore;
use store_api::region_engine::RegionEngine;
use store_api::region_engine::{RegionEngine, RegionManifestInfo, RegionRole};
use store_api::region_request::{
RegionBulkInsertsRequest, RegionCloseRequest, RegionPutRequest, RegionRequest,
};
@@ -38,6 +38,7 @@ 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::test_util::{CreateRequestBuilder, TestEnv, build_rows, rows_schema};
use crate::time_provider::mock::MockTimeProvider;
@@ -565,6 +566,71 @@ async fn test_region_edit_with_file_sequence_is_not_merged() {
assert_eq!(Some(3), region_file_sequence(&region, third_file_id));
}
#[tokio::test]
async fn test_failed_region_edit_preserves_sequence() {
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();
region.version_control.update_last_sequence(2);
let manifest_guard = region.manifest_ctx.manifest_manager.write().await;
let (tx, rx) = oneshot::channel();
engine
.inner
.workers
.submit_to_worker(
region_id,
WorkerRequest::EditRegion(RegionEditRequest::new(
region_id,
test_region_edit(region_id, FileId::random()),
false,
tx,
)),
)
.await
.unwrap();
// Sync fails before taking the manifest lock, after the edit starts.
assert!(
engine
.sync_region(region_id, RegionManifestInfo::mito(0, 0, 0).into())
.await
.is_err()
);
assert_eq!(
region.state(),
RegionRoleState::Leader(RegionLeaderState::Editing)
);
assert_eq!(region.version_control.current().last_sequence, 3);
assert_eq!(region.version_control.committed_sequence(), 0);
region.set_role(RegionRole::Follower);
drop(manifest_guard);
assert!(rx.await.unwrap().is_err());
assert_eq!(region.version_control.current().last_sequence, 3);
assert_eq!(region.version_control.committed_sequence(), 0);
region.set_role(RegionRole::Leader);
let file_id = FileId::random();
engine
.edit_region(region_id, test_region_edit(region_id, file_id))
.await
.unwrap();
assert_eq!(region_file_sequence(&region, file_id), Some(4));
let current = region.version_control.current();
assert_eq!((current.last_sequence, current.committed_sequence), (4, 4));
}
#[tokio::test]
async fn test_region_edit_clears_preserve_row_sequence() {
let mut env = TestEnv::new().await;
+107 -5
View File
@@ -13,8 +13,10 @@
// limitations under the License.
//! Tests that a region acknowledges only writes whose WAL append completed within its leader
//! lease.
//! lease, and that Leader grants for heartbeats sent before a downgrade do not make it writable
//! again.
use std::collections::HashMap;
use std::sync::Arc;
use std::time::{Duration, Instant};
@@ -24,8 +26,11 @@ use common_error::ext::{BoxedError, ErrorExt};
use common_recordbatch::RecordBatches;
use rstest::rstest;
use rstest_reuse::apply;
use store_api::region_engine::{RegionEngine, RegionRole};
use store_api::region_request::{RegionCatchupRequest, RegionPutRequest, RegionRequest};
use store_api::region_engine::{RegionEngine, RegionRole, SettableRegionRoleState};
use store_api::region_request::{
EnterStagingRequest, RegionCatchupRequest, RegionPutRequest, RegionRequest,
StagingPartitionDirective,
};
use store_api::storage::{RegionId, ScanRequest};
use tokio::task::JoinHandle;
@@ -34,10 +39,11 @@ use crate::engine::MitoEngine;
use crate::engine::basic_test::build_bulk_insert_request;
use crate::engine::listener::WriteWalListener;
use crate::error::Error;
use crate::region::{RegionLeaderState, RegionRoleState};
use crate::test_util::{
CreateRequestBuilder, LogStoreFactory, TestEnv, build_rows, kafka_log_store_factory,
multiple_log_store_factories, prepare_test_for_kafka_log_store, raft_engine_log_store_factory,
rows_schema,
reopen_region, rows_schema,
};
const LEASE: Duration = Duration::from_secs(10);
@@ -66,10 +72,18 @@ async fn create_region(
fn grant(engine: &MitoEngine, role: RegionRole, deadline: Instant) {
engine
.set_region_role_with_lease(REGION_ID, role, deadline)
.set_region_role_with_lease(REGION_ID, role, Instant::now(), deadline)
.unwrap();
}
/// Grants Leader for a heartbeat sent at `sent_at`, and returns whether the role was applied.
fn grant_leader_at(engine: &MitoEngine, sent_at: Instant) -> bool {
let deadline = Instant::now() + LEASE;
engine
.set_region_role_with_lease(REGION_ID, RegionRole::Leader, sent_at, deadline)
.unwrap()
}
/// Returns a request that writes rows `start..start + 3`.
fn put_request(schema: &[ColumnSchema], start: usize) -> RegionRequest {
let rows = Rows {
@@ -282,3 +296,91 @@ async fn test_upgraded_region_writes_before_leader_grant() {
.unwrap();
put(&engine, REGION_ID, &schema, 0).await.unwrap().unwrap();
}
#[rstest]
#[case::downgrading(SettableRegionRoleState::DowngradingLeader)]
#[case::follower(SettableRegionRoleState::Follower)]
#[tokio::test]
async fn test_stale_leader_grant_after_downgrade(#[case] downgraded_to: SettableRegionRoleState) {
common_telemetry::init_default_ut_logging();
let mut env = TestEnv::with_prefix("stale-leader-grant").await;
let (_listener, engine, _schema) = create_region(&mut env, None).await;
let sent_before = Instant::now() - Duration::from_millis(1);
engine
.set_region_role_state_gracefully(REGION_ID, downgraded_to)
.await
.unwrap();
let downgraded = engine.get_region(REGION_ID).unwrap().state();
// Another downgrade raises the gate again, though the role does not change.
let sent_between = Instant::now();
engine
.set_region_role_state_gracefully(REGION_ID, downgraded_to)
.await
.unwrap();
// Grants for heartbeats sent before either downgrade arrive late.
assert!(!grant_leader_at(&engine, sent_before));
assert!(!grant_leader_at(&engine, sent_between));
assert_eq!(downgraded, engine.get_region(REGION_ID).unwrap().state());
assert!(grant_leader_at(&engine, Instant::now()));
assert!(engine.get_region(REGION_ID).unwrap().is_writable());
}
#[rstest]
#[case::catchup(false)]
#[case::close_and_open(true)]
#[tokio::test]
async fn test_reopened_region_ignores_earlier_grants(#[case] close: bool) {
common_telemetry::init_default_ut_logging();
let mut env = TestEnv::with_prefix("reopened-region-grant").await;
let (_listener, engine, schema) = create_region(&mut env, None).await;
grant(&engine, RegionRole::Leader, Instant::now() + LEASE);
// The memtable is not empty, so the catchup below reopens the region.
put(&engine, REGION_ID, &schema, 0).await.unwrap().unwrap();
let sent_before = Instant::now() - Duration::from_millis(1);
let region = engine.get_region(REGION_ID).unwrap();
if close {
let table_dir = CreateRequestBuilder::new().build().table_dir;
reopen_region(&engine, REGION_ID, table_dir, false, HashMap::new()).await;
} else {
engine
.set_region_role_state_gracefully(REGION_ID, SettableRegionRoleState::Follower)
.await
.unwrap();
let request = RegionRequest::Catchup(RegionCatchupRequest::default());
engine.handle_request(REGION_ID, request).await.unwrap();
}
assert!(!Arc::ptr_eq(
&region,
&engine.get_region(REGION_ID).unwrap()
));
assert!(!grant_leader_at(&engine, sent_before));
assert!(!engine.get_region(REGION_ID).unwrap().is_writable());
grant(&engine, RegionRole::Leader, Instant::now() + LEASE);
assert!(engine.get_region(REGION_ID).unwrap().is_writable());
}
#[tokio::test]
async fn test_leader_grant_exits_staging() {
common_telemetry::init_default_ut_logging();
let mut env = TestEnv::with_prefix("staging-leader-grant").await;
let (_listener, engine, _schema) = create_region(&mut env, None).await;
let request = EnterStagingRequest {
partition_directive: StagingPartitionDirective::RejectAllWrites,
};
engine
.handle_request(REGION_ID, RegionRequest::EnterStaging(request))
.await
.unwrap();
let state = || engine.get_region(REGION_ID).unwrap().state();
assert_eq!(RegionRoleState::Leader(RegionLeaderState::Staging), state());
grant(&engine, RegionRole::Leader, Instant::now() + LEASE);
assert_eq!(
RegionRoleState::Leader(RegionLeaderState::Writable),
state()
);
}
@@ -1251,8 +1251,21 @@ async fn test_reopen_after_a_failed_create_shows_only_the_acknowledged_write() {
assert_eq!(vec![0, 1], wal_object_seqs(&object_store).await);
assert_eq!(0, latest(&store, REGION_A));
// The same key and timestamp is written again under the same row
// sequence, and acknowledged from object 2.
assert_eq!(
1,
region(&engine, REGION_A)
.version_control
.current()
.last_sequence
);
assert_eq!(
0,
region(&engine, REGION_A)
.version_control
.committed_sequence()
);
// Write the same key and timestamp with a higher sequence in object 2.
let mut writer = SealedWriter {
store: store.clone(),
admitted: 1,
@@ -1266,7 +1279,7 @@ async fn test_reopen_after_a_failed_create_shows_only_the_acknowledged_write() {
assert_eq!(vec![1, 2], wal_object_seqs(&object_store).await);
assert_eq!(entry_id(2, 1), latest(&store, REGION_A));
let region_a = region(&engine, REGION_A);
assert_eq!(1, region_a.version_control.committed_sequence());
assert_eq!(2, region_a.version_control.committed_sequence());
let expected = "\
+-------+---------+---------------------+
| tag_0 | field_0 | ts |
+265
View File
@@ -73,6 +73,271 @@ use crate::test_util;
use crate::test_util::sst_util::{new_sparse_primary_key, sst_region_metadata_with_encoding};
use crate::test_util::{CreateRequestBuilder, TestEnv, reopen_region};
#[tokio::test]
async fn test_sparse_upsert_after_adding_nullable_tag() -> WhateverResult<()> {
use datatypes::schema::ColumnSchema;
use store_api::metadata::ColumnMetadata;
use store_api::region_request::AddColumn;
let mut env = TestEnv::new().await;
let engine = env.create_engine(MitoConfig::default()).await;
let region_id = RegionId::new(1024, 0);
let mut request = CreateRequestBuilder::new()
.tag_num(1)
.field_num(1)
.insert_option("primary_key_encoding", "sparse")
.build();
let reserved = sst_region_metadata_with_encoding(PrimaryKeyEncoding::Sparse);
request
.column_metadatas
.extend(reserved.column_metadatas.into_iter().take(2));
request
.primary_key
.splice(0..0, reserved.primary_key.into_iter().take(2));
let schema = test_util::rows_schema(&request);
engine
.handle_request(region_id, RegionRequest::Create(request))
.await?;
let mut rows = Rows {
schema,
rows: vec![row(vec![
ValueData::StringValue("api".into()),
ValueData::F64Value(1.0),
ValueData::TimestampMillisecondValue(1000),
ValueData::U32Value(42),
ValueData::U64Value(7),
])],
};
test_util::put_rows(&engine, region_id, rows.clone()).await;
test_util::flush_region(&engine, region_id, None).await;
engine
.handle_request(
region_id,
RegionRequest::Alter(RegionAlterRequest {
kind: AlterKind::AddColumns {
columns: vec![AddColumn {
column_metadata: ColumnMetadata {
column_schema: ColumnSchema::new(
"zone",
ConcreteDataType::string_datatype(),
true,
),
semantic_type: SemanticType::Tag,
column_id: 3,
},
location: None,
}],
},
}),
)
.await?;
// The old SST and the new write must still identify the same series before compaction.
rows.rows[0].values[1].value_data = Some(ValueData::F64Value(2.0));
test_util::put_rows(&engine, region_id, rows).await;
for flush in [false, true] {
if flush {
test_util::flush_region(&engine, region_id, None).await;
}
let stream = engine
.scan_to_stream(
region_id,
ScanRequest {
projection: Some(vec![0, 1, 2, 5]),
..Default::default()
},
)
.await?;
let batches = RecordBatches::try_collect(stream).await?;
let expected = "\
+-------+---------+---------------------+------+
| tag_0 | field_0 | ts | zone |
+-------+---------+---------------------+------+
| api | 2.0 | 1970-01-01T00:00:01 | |
+-------+---------+---------------------+------+";
assert_eq!(batches.pretty_print()?, expected);
}
engine.stop().await?;
Ok(())
}
#[tokio::test]
async fn test_exemplar_sparse_storage_lifecycle() -> WhateverResult<()> {
use datatypes::schema::ColumnSchema;
use store_api::metadata::ColumnMetadata;
use store_api::region_request::AddColumn;
use store_api::storage::consts::ReservedColumnId;
for default_flat_format in [false, true] {
let mut env = TestEnv::new().await;
let engine = env
.create_engine(MitoConfig {
default_flat_format,
..Default::default()
})
.await;
let region_id = RegionId::new(1024, 0);
let mut request = CreateRequestBuilder::new()
.tag_num(2)
.field_num(2)
.insert_option("primary_key_encoding", "sparse")
.insert_option("append_mode", "true")
.insert_option("sst_format", "primary_key")
.build();
request.column_metadatas[3].column_schema.data_type =
ConcreteDataType::json2(JsonNativeType::Object(JsonObjectType::new()));
request.column_metadatas[3]
.column_schema
.with_extension_type(&Json2ExtensionType::default());
for (name, column_id, data_type) in [
(
"__table_id",
ReservedColumnId::table_id(),
ConcreteDataType::uint32_datatype(),
),
(
"__tsid",
ReservedColumnId::tsid(),
ConcreteDataType::uint64_datatype(),
),
] {
request.column_metadatas.push(ColumnMetadata {
column_schema: ColumnSchema::new(name, data_type, false),
semantic_type: SemanticType::Tag,
column_id,
});
}
request.primary_key.splice(
0..0,
[ReservedColumnId::table_id(), ReservedColumnId::tsid()],
);
let table_dir = request.table_dir.clone();
let schema = test_util::rows_schema(&request);
engine
.handle_request(region_id, RegionRequest::Create(request))
.await?;
let mut rows = Rows {
schema: schema.clone(),
rows: vec![row(vec![
ValueData::StringValue("metric".into()),
ValueData::StringValue("api".into()),
ValueData::F64Value(1.5),
ValueData::JsonValue(encode_json_value(JsonValue::from(
json!({"trace_id":"abc"}),
))),
ValueData::TimestampMillisecondValue(1),
])],
};
rows.rows[0].values.extend([
ValueData::U32Value(42).into(),
ValueData::U64Value(7).into(),
]);
// Equal series/timestamp observations are preserved in append mode.
rows.rows.push(rows.rows[0].clone());
let mut null_row = rows.rows[0].clone();
null_row.values[0].value_data = None;
null_row.values[1].value_data = None;
// Different source metrics can have the same TSID.
null_row.values[5] = ValueData::U32Value(43).into();
rows.rows.push(null_row);
test_util::put_rows(&engine, region_id, rows.clone()).await;
// Reopen without encoding options, replaying raw rows from WAL.
reopen_region(&engine, region_id, table_dir.clone(), true, HashMap::new()).await;
assert_eq!(
engine.get_primary_key_encoding(region_id).unwrap(),
PrimaryKeyEncoding::Sparse
);
test_util::flush_region(&engine, region_id, None).await;
engine
.handle_request(
region_id,
RegionRequest::Alter(RegionAlterRequest {
kind: AlterKind::AddColumns {
columns: vec![AddColumn {
column_metadata: ColumnMetadata {
column_schema: ColumnSchema::new(
"new_tag",
ConcreteDataType::string_datatype(),
true,
),
semantic_type: SemanticType::Tag,
column_id: 5,
},
location: None,
}],
},
}),
)
.await?;
// A stale writer omits the newly added nullable tag.
test_util::put_rows(&engine, region_id, rows).await;
test_util::flush_region(&engine, region_id, None).await;
engine
.handle_request(
region_id,
RegionRequest::Compact(RegionCompactRequest {
options: compact_request::Options::StrictWindow(StrictWindow {
window_seconds: 86400,
}),
..Default::default()
}),
)
.await?;
reopen_region(
&engine,
region_id,
table_dir.clone(),
true,
HashMap::from([
("primary_key_encoding".into(), "dense".into()),
("sst_format".into(), "primary_key".into()),
]),
)
.await;
reopen_region(&engine, region_id, table_dir, true, HashMap::new()).await;
assert_eq!(
engine.get_primary_key_encoding(region_id).unwrap(),
PrimaryKeyEncoding::Sparse
);
let mut cases = vec![
(vec![], 6),
(vec![col("tag_0").eq(lit("metric"))], 4),
(vec![col("tag_0").is_null()], 2),
];
cases.extend([
(vec![col("__table_id").eq(lit(42u32))], 4),
(vec![col("__table_id").eq(lit(43u32))], 2),
(vec![col("__tsid").eq(lit(7u64))], 6),
]);
for (filters, expected) in cases {
let scanner = engine
.scanner(
region_id,
ScanRequest {
filters,
json_type_hint: HashMap::from([(
"field_1".into(),
JsonNativeType::Variant,
)]),
..Default::default()
},
)
.await?;
let batches = RecordBatches::try_collect(scanner.scan().await?).await?;
assert_eq!(
batches.iter().map(|b| b.num_rows()).sum::<usize>(),
expected
);
for batch in batches.iter() {
let label_index = batch.schema.column_index_by_name("new_tag").unwrap();
assert_eq!(batch.column(label_index).null_count(), batch.num_rows());
}
}
}
Ok(())
}
#[tokio::test]
async fn test_nullable_label_filters_in_memtables_and_ssts() {
use datafusion_expr::{BinaryExpr as LogicalBinaryExpr, Cast, Expr};
+410
View File
@@ -0,0 +1,410 @@
// 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.
//! Mito sequence recovery tests using a memory WAL with store-assigned entry ids.
//! Uses ObjectStore providers; Kafka producers are not tested.
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
use api::v1::Rows;
use common_recordbatch::RecordBatches;
use common_wal::options::{ObjectStoreWalOptions, WAL_OPTIONS_KEY, WalOptions};
use futures::stream;
use log_store::error::{Error, IllegalStateSnafu, Result};
use store_api::logstore::entry::{Entry, NaiveEntry};
use store_api::logstore::provider::Provider;
use store_api::logstore::{AppendBatchResponse, EntryId, LogStore, SendableEntryStream};
use store_api::region_engine::{RegionEngine, RegionRole};
use store_api::region_request::{PathType, RegionOpenRequest, RegionPutRequest, RegionRequest};
use store_api::storage::{RegionId, ScanRequest};
use tokio::sync::oneshot;
use crate::config::MitoConfig;
use crate::engine::MitoEngine;
use crate::test_util::{
CreateRequestBuilder, TestEnv, build_rows_for_key, flush_region, rows_schema,
};
#[derive(Debug)]
enum AppendFault {
Persist,
Partial(RegionId),
Deferred {
release: oneshot::Receiver<()>,
saved: oneshot::Sender<()>,
},
}
#[derive(Debug, Default)]
struct LogState {
entries: HashMap<Provider, Vec<Entry>>,
fault: Option<AppendFault>,
append_calls: usize,
}
impl LogState {
fn save(&mut self, entries: Vec<Entry>) -> AppendBatchResponse {
let mut last_entry_ids = HashMap::new();
for mut entry in entries {
let log = self.entries.entry(entry.provider().clone()).or_default();
// Entry ids start from 1 (zero means no data).
let offset = log.len() as u64 + 1;
entry.set_entry_id(offset);
last_entry_ids.insert(entry.region_id(), offset);
log.push(entry);
}
AppendBatchResponse { last_entry_ids }
}
}
#[derive(Debug, Default)]
struct MemoryLogStore {
state: Arc<Mutex<LogState>>,
}
impl MemoryLogStore {
fn fail_next_append(&self, fault: AppendFault) {
let mut state = self.state.lock().unwrap();
assert!(state.fault.replace(fault).is_none());
}
}
#[async_trait::async_trait]
impl LogStore for MemoryLogStore {
type Error = Error;
async fn stop(&self) -> Result<()> {
Ok(())
}
async fn append_batch(&self, entries: Vec<Entry>) -> Result<AppendBatchResponse> {
let mut state = self.state.lock().unwrap();
state.append_calls += 1;
match state.fault.take() {
None => return Ok(state.save(entries)),
Some(AppendFault::Persist) => {
state.save(entries);
}
Some(AppendFault::Partial(region_id)) => {
state.save(
entries
.into_iter()
.filter(|e| e.region_id() == region_id)
.collect(),
);
}
Some(AppendFault::Deferred { release, saved }) => {
let state = self.state.clone();
common_runtime::spawn_global(async move {
if release.await.is_ok() {
state.lock().unwrap().save(entries);
let _ = saved.send(());
}
});
}
}
IllegalStateSnafu {}.fail()
}
async fn read(
&self,
provider: &Provider,
id: EntryId,
) -> Result<SendableEntryStream<'static, Entry, Error>> {
// Snapshot the log for recovery.
let entries = self
.state
.lock()
.unwrap()
.entries
.get(provider)
.cloned()
.unwrap_or_default();
Ok(Box::pin(stream::iter([Ok(entries
.into_iter()
.filter(|e| e.entry_id() >= id)
.collect())])))
}
async fn create_namespace(&self, _provider: &Provider) -> Result<()> {
Ok(())
}
async fn delete_namespace(&self, _provider: &Provider) -> Result<()> {
Ok(())
}
async fn list_namespaces(&self) -> Result<Vec<Provider>> {
Ok(vec![])
}
async fn obsolete(
&self,
_provider: &Provider,
_region_id: RegionId,
_id: EntryId,
) -> Result<()> {
Ok(())
}
async fn obsolete_all(&self, _provider: &Provider, _region_id: RegionId) -> Result<()> {
Ok(())
}
fn entry(
&self,
data: Vec<u8>,
entry_id: EntryId,
region_id: RegionId,
provider: &Provider,
) -> Result<Entry> {
Ok(Entry::Naive(NaiveEntry {
data,
entry_id,
region_id,
provider: provider.clone(),
}))
}
fn latest_entry_id(&self, provider: &Provider) -> Result<EntryId> {
Ok(self
.state
.lock()
.unwrap()
.entries
.get(provider)
.and_then(|log| log.last())
.map_or(0, Entry::entry_id))
}
}
fn wal_options() -> HashMap<String, String> {
HashMap::from([(
WAL_OPTIONS_KEY.to_string(),
serde_json::to_string(&WalOptions::ObjectStore(ObjectStoreWalOptions::new(
"sequence-test/".to_string(),
)))
.unwrap(),
)])
}
async fn create_region(
engine: &MitoEngine,
region_id: RegionId,
) -> (String, Vec<api::v1::ColumnSchema>) {
let request = CreateRequestBuilder::new()
.insert_option(WAL_OPTIONS_KEY, &wal_options()[WAL_OPTIONS_KEY])
.build();
let table_dir = request.table_dir.clone();
let schema = rows_schema(&request);
engine
.handle_request(region_id, RegionRequest::Create(request))
.await
.unwrap();
(table_dir, schema)
}
async fn open_region(engine: &MitoEngine, region_id: RegionId, table_dir: String) {
engine
.handle_request(
region_id,
RegionRequest::Open(RegionOpenRequest {
engine: String::new(),
table_dir,
path_type: PathType::Bare,
options: wal_options(),
skip_wal_replay: false,
checkpoint: None,
requirements: Default::default(),
}),
)
.await
.unwrap();
engine
.set_region_role(region_id, RegionRole::Leader)
.unwrap();
}
fn put_request(schema: &[api::v1::ColumnSchema], keys: &[(&str, usize)]) -> RegionPutRequest {
RegionPutRequest {
rows: Rows {
schema: schema.to_vec(),
rows: keys
.iter()
.flat_map(|(key, value)| build_rows_for_key(key, 0, 1, *value))
.collect(),
},
skip_wal: false,
hint: None,
partition_expr_version: None,
}
}
async fn scan_rows(engine: &MitoEngine, region_id: RegionId) -> String {
let stream = engine
.scan_to_stream(region_id, ScanRequest::default())
.await
.unwrap();
RecordBatches::try_collect(stream)
.await
.unwrap()
.pretty_print()
.unwrap()
}
#[tokio::test]
async fn test_persisted_wal_error_does_not_overwrite_success() {
for flat_format in [false, true] {
for (deferred, flush) in [(false, false), (true, false), (true, true)] {
let mut env = TestEnv::new().await;
let store = Arc::new(MemoryLogStore::default());
let config = MitoConfig {
default_flat_format: flat_format,
num_workers: 1,
..Default::default()
};
let engine = env
.create_engine_with_log_store(config.clone(), store.clone())
.await;
let region_id = RegionId::new(1, 1);
let (table_dir, schema) = create_region(&engine, region_id).await;
let (release, released) = oneshot::channel();
let (saved, saved_rx) = oneshot::channel();
store.fail_next_append(if deferred {
AppendFault::Deferred {
release: released,
saved,
}
} else {
AppendFault::Persist
});
assert!(
engine
.handle_request(
region_id,
RegionRequest::Put(put_request(&schema, &[("a", 1), ("b", 1)]))
)
.await
.is_err()
);
let failed = engine
.get_region(region_id)
.unwrap()
.version_control
.current();
assert_eq!(failed.committed_sequence, 0);
assert_eq!(failed.last_sequence, 2);
assert_eq!(failed.last_entry_id, 0);
assert_eq!(failed.version.flushed_sequence, 0);
engine
.handle_request(
region_id,
RegionRequest::Put(put_request(&schema, &[("b", 2)])),
)
.await
.unwrap();
if flush {
flush_region(&engine, region_id, None).await;
}
if deferred {
release.send(()).unwrap();
saved_rx.await.unwrap();
}
assert!(
scan_rows(&engine, region_id)
.await
.contains("| b | 2.0")
);
engine.stop().await.unwrap();
drop(engine);
let engine = env.create_engine_with_log_store(config, store).await;
open_region(&engine, region_id, table_dir).await;
let recovered = scan_rows(&engine, region_id).await;
assert!(
recovered.contains("| b | 2.0"),
"deferred={deferred}, flush={flush}, flat={flat_format}: {recovered}"
);
let current = engine
.get_region(region_id)
.unwrap()
.version_control
.current();
assert_eq!(current.committed_sequence, 3);
assert_eq!(current.last_sequence, 3);
engine.stop().await.unwrap();
}
}
}
#[tokio::test]
async fn test_partial_region_append_preserves_all_allocations() {
let mut env = TestEnv::new().await;
let store = Arc::new(MemoryLogStore::default());
let engine = env
.create_engine_with_log_store(
MitoConfig {
num_workers: 1,
..Default::default()
},
store.clone(),
)
.await;
let regions = [RegionId::new(1, 1), RegionId::new(1, 2)];
let mut schemas = Vec::new();
let mut table_dirs = Vec::new();
for id in regions {
let (dir, schema) = create_region(&engine, id).await;
table_dirs.push(dir);
schemas.push(schema);
}
store.fail_next_append(AppendFault::Partial(regions[0]));
let requests = regions
.into_iter()
.zip(&schemas)
.map(|(id, schema)| (id, put_request(schema, &[("a", 1), ("b", 1)])))
.collect();
for (_, response) in Arc::new(engine.clone()).handle_batch_put_requests(requests) {
assert!(response.await.is_err());
}
assert_eq!(store.state.lock().unwrap().append_calls, 1);
for (id, schema) in regions.into_iter().zip(&schemas) {
let region = engine.get_region(id).unwrap();
let current = region.version_control.current();
assert_eq!(
(
current.last_sequence,
current.committed_sequence,
current.last_entry_id
),
(2, 0, 0)
);
assert!(current.version.memtables.is_empty());
assert_eq!(
store.latest_entry_id(&region.provider).unwrap(),
u64::from(id == regions[0])
);
engine
.handle_request(id, RegionRequest::Put(put_request(schema, &[("b", 2)])))
.await
.unwrap();
assert_eq!(region.version_control.current().committed_sequence, 3);
}
engine.stop().await.unwrap();
drop(engine);
let engine = env
.create_engine_with_log_store(MitoConfig::default(), store)
.await;
for (id, dir) in regions.into_iter().zip(table_dirs) {
open_region(&engine, id, dir).await;
assert!(scan_rows(&engine, id).await.contains("| b | 2.0"));
}
engine.stop().await.unwrap();
}
+41 -5
View File
@@ -759,6 +759,39 @@ async fn test_staging_exit_success_with_manifests_with_format(flat_format: bool)
.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] {
engine
.edit_region(
region_id,
RegionEdit {
files_to_add: vec![file.clone()],
files_to_remove: vec![],
timestamp_ms: None,
compaction_time_window: None,
flushed_entry_id: None,
flushed_sequence: None,
committed_sequence: None,
},
)
.await
.unwrap();
let current = region.version_control.current();
assert_eq!(current.last_sequence, expected);
assert_eq!(current.committed_sequence, 10);
}
// Verify we're in staging mode and staging manifests exist
let data_home = env.data_home();
let region_dir = format!("{}/data/test/1024_0000000000", data_home.display());
@@ -770,13 +803,11 @@ async fn test_staging_exit_success_with_manifests_with_format(flat_format: bool)
.unwrap();
assert_eq!(
staging_files_before.len(),
// Two files for flush operation
// One file for entering staging mode
3,
"Staging manifest directory should contain 3 files before exit, got: {:?}",
// Two flushes, two edits and entering staging mode.
5,
"Staging manifest directory should contain 5 files before exit, got: {:?}",
staging_files_before
);
let region = engine.get_region(region_id).unwrap();
{
let manager = region.manifest_ctx.manifest_manager.read().await;
let staging_manifest = manager.staging_manifest().unwrap();
@@ -950,6 +981,11 @@ async fn test_staging_exit_success_with_manifests_with_format(flat_format: bool)
// Verify we're back in normal mode
let workers = &engine.inner.workers;
let region = workers.get_region(region_id).unwrap();
let current = region.version_control.current();
assert_eq!(
(current.last_sequence, current.committed_sequence),
(12, 12)
);
assert!(
!region.is_staging(),
"Region should no longer be in staging mode"
+81 -2
View File
@@ -20,10 +20,10 @@ use common_recordbatch::RecordBatches;
use datatypes::prelude::ConcreteDataType;
use datatypes::schema::ColumnSchema;
use store_api::metadata::ColumnMetadata;
use store_api::region_engine::{RegionEngine, RegionManifestInfo};
use store_api::region_engine::{RegionEngine, RegionManifestInfo, RegionRole};
use store_api::region_request::{
AddColumn, AddColumnLocation, AlterKind, PathType, RegionAlterRequest, RegionOpenRequest,
RegionRequest,
RegionPutRequest, RegionRequest,
};
use store_api::storage::{RegionId, ScanRequest};
@@ -170,6 +170,11 @@ async fn test_sync_after_flush_region_with_format(flat_format: bool) {
.await
.unwrap();
common_telemetry::info!("Scan the region on the follower engine after sync");
let follower = follower_engine.get_region(region_id).unwrap();
assert_eq!(follower.version_control.current().last_sequence, 3);
// Sync does not update committed sequence or entry id.
assert_eq!(follower.version_control.committed_sequence(), 0);
assert_eq!(follower.version_control.current().last_entry_id, 0);
// Scan the region on the follower engine
let expected = "\
+-------+---------+---------------------+
@@ -180,6 +185,80 @@ async fn test_sync_after_flush_region_with_format(flat_format: bool) {
| 2 | 2.0 | 1970-01-01T00:00:02 |
+-------+---------+---------------------+";
scan_check(&follower_engine, region_id, expected, 0, 1).await;
// An edit may have a committed sequence above the flushed sequence.
let file = engine
.get_region(region_id)
.unwrap()
.version()
.ssts
.levels()[0]
.files
.values()
.next()
.unwrap()
.meta_ref()
.clone();
engine
.edit_region(
region_id,
crate::manifest::action::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 manifest_version = engine
.get_region(region_id)
.unwrap()
.manifest_ctx
.manifest_version()
.await;
follower_engine
.sync_region(
region_id,
RegionManifestInfo::mito(manifest_version, 0, 0).into(),
)
.await
.unwrap();
assert_eq!(follower.version_control.current().last_sequence, 4);
assert_eq!(follower.version_control.committed_sequence(), 0);
// Writes after promotion must use a higher sequence.
follower_engine
.set_region_role(region_id, RegionRole::Leader)
.unwrap();
let request = CreateRequestBuilder::new().build();
// Skip WAL to isolate row sequence allocation.
follower_engine
.handle_request(
region_id,
RegionRequest::Put(RegionPutRequest {
rows: Rows {
schema: rows_schema(&request),
rows: build_rows(0, 1),
},
skip_wal: true,
hint: None,
partition_expr_version: None,
}),
)
.await
.unwrap();
assert_eq!(
5,
follower_engine
.get_region(region_id)
.unwrap()
.version_control
.committed_sequence()
);
}
#[tokio::test]
+91
View File
@@ -0,0 +1,91 @@
// 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::LazyLock;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::time::Instant;
/// The instant lease deadlines count from, so that a deadline fits in an [AtomicU64].
static LEASE_EPOCH: LazyLock<Instant> = LazyLock::new(Instant::now);
fn lease_nanos(instant: Instant) -> u64 {
instant.saturating_duration_since(*LEASE_EPOCH).as_nanos() as u64
}
/// A lease deadline in nanoseconds since [LEASE_EPOCH]. It only moves forward; 0 means none.
#[derive(Debug, Default)]
pub(crate) struct Deadline(AtomicU64);
impl Deadline {
pub(crate) fn extend(&self, deadline: Instant) {
self.0.fetch_max(lease_nanos(deadline), Ordering::Relaxed);
}
pub(crate) fn get(&self) -> u64 {
self.0.load(Ordering::Relaxed)
}
}
/// Lease of this node: the latest deadline of the heartbeat responses that carry region leases.
#[derive(Debug, Default)]
pub(crate) struct NodeLease {
/// Whether writes need a lease. Only a datanode the metasrv controls sets it.
enabled: AtomicBool,
deadline: Deadline,
/// The time of the lease checks while a test freezes it, in the unit of [Deadline]; 0 when
/// it is not frozen.
#[cfg(any(test, feature = "test"))]
frozen_now: AtomicU64,
}
impl NodeLease {
pub(crate) fn enable(&self) {
self.enabled.store(true, Ordering::Relaxed);
}
pub(crate) fn is_enabled(&self) -> bool {
self.enabled.load(Ordering::Relaxed)
}
pub(crate) fn renew(&self, deadline: Instant) {
self.deadline.extend(deadline);
}
/// Returns the current time in the unit of [Deadline].
pub(crate) fn now(&self) -> u64 {
#[cfg(any(test, feature = "test"))]
{
let frozen_now = self.frozen_now.load(Ordering::Relaxed);
if frozen_now != 0 {
return frozen_now;
}
}
lease_nanos(Instant::now())
}
#[cfg(any(test, feature = "test"))]
pub(crate) fn freeze_clock(&self, at: Instant) {
self.frozen_now
.store(lease_nanos(at).max(1), Ordering::Relaxed);
}
/// Lets a region created or upgraded on this node write until the node's deadline. The
/// metasrv granted that deadline before the creation or upgrade, so a later migration of the
/// region waits past it. Later responses do not extend it; the region's Leader grants do.
pub(crate) fn seed(&self, leader_deadline: &Deadline) {
leader_deadline
.0
.fetch_max(self.deadline.get(), Ordering::Relaxed);
}
}
+1
View File
@@ -31,6 +31,7 @@ pub mod error;
pub mod extension;
pub mod flush;
pub mod gc;
mod lease;
pub mod manifest;
pub mod memtable;
mod metrics;

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