mirror of
https://github.com/GreptimeTeam/greptimedb.git
synced 2026-11-28 05:34:02 +00:00
chore: merge main into JSONL COPY branch
Signed-off-by: Ning Sun <sunning@greptime.com>
This commit is contained in:
@@ -39,6 +39,12 @@ Double-check with the user.
|
||||
|
||||
## 3. Pick the range and generate
|
||||
|
||||
For every release type, use the release tag's commit as `<tip>` when the tag exists.
|
||||
Resolve the exact tag from the remote (use the peeled `^{}` commit for annotated tags)
|
||||
and exclude commits added to the release branch afterward. Before tagging, pin the
|
||||
intended release commit and record its SHA. Pass that SHA as `--target` when creating
|
||||
the release, then verify the resulting tag before publishing the docs copy.
|
||||
|
||||
Key topology fact: **patch tags** (`v1.0.1`, `v1.0.2`) live on `release/vX.Y` and are **NOT**
|
||||
ancestors of `main` (they are cherry-picks with different SHAs). Up to v1.1 the `.0` tag was
|
||||
the point where `release/vX.Y` left `main`; from v1.2 the branch is cut before the `.0`, and
|
||||
@@ -51,8 +57,8 @@ left `main`, minus what any published `vX.(Y-1).*` release (pre-releases, `.0`,
|
||||
already shipped. The line's own pre-releases (`vX.Y.0-beta.*`) are not subtracted; the `.0`
|
||||
note covers the whole minor.
|
||||
|
||||
Base = the **previous minor tag** (e.g. `v1.1.0`); tip = the tagged `vX.Y.0` commit, resolved as
|
||||
in "Pre-release" below. Split the range at the point where `release/vX.Y` left `main`:
|
||||
Base = the **previous minor tag** (e.g. `v1.1.0`); tip = the release commit resolved above.
|
||||
Split the range at the point where `release/vX.Y` left `main`:
|
||||
```
|
||||
bp=$(git merge-base <remote>/release/vX.Y <remote>/main)
|
||||
```
|
||||
@@ -80,14 +86,14 @@ small Python script is the reliable way — match `pull/<n>)` on lines starting
|
||||
The previous patch tag is an ancestor of the release branch, so a plain range works **when the
|
||||
cherry-picks land as individual commits**:
|
||||
```
|
||||
GITHUB_TOKEN=$(gh auth token) git cliff <prev-patch-tag>..<release-branch-tip> --tag vX.Y.Z -o ...
|
||||
GITHUB_TOKEN=$(gh auth token) git cliff <prev-patch-tag>..<tip> --tag vX.Y.Z -o ...
|
||||
```
|
||||
No extra subtraction (the branch only contains the new cherry-picks).
|
||||
|
||||
**Common case — squashed pick commit.** Patch branches are often a single squashed commit like
|
||||
`chore: pick fixes and bump version to vX.Y.Z (#NNNN)`, so the plain range above yields just
|
||||
that one bullet. First **find the picked PRs**: read the squash commit message
|
||||
(`git log -1 --format=%B <release-branch-tip>`) — each `* fix: ... (#NN)` line is a picked PR.
|
||||
(`git log -1 --format=%B <tip>`) — each `* fix: ... (#NN)` line is a picked PR.
|
||||
Then pick one of two ways to build the changelog (a patch is usually only a few PRs — **ask the
|
||||
user which they prefer**):
|
||||
|
||||
@@ -131,16 +137,6 @@ Either source alone misses PRs: a release body can omit a backport that its tag
|
||||
backport commit can name only the backport PR.
|
||||
|
||||
### Pre-release (`X.Y.Z-{alpha,beta,rc}.N` after an earlier pre-release)
|
||||
**The tip is the tagged commit, not the release branch tip.** Resolve it from the remote and
|
||||
write this SHA in the docs PR body (§8) as what the note was checked against:
|
||||
```
|
||||
git ls-remote --tags <remote> 'vX.Y.Z-beta.N*'
|
||||
```
|
||||
Use the `refs/tags/vX.Y.Z-beta.N` line (its `^{}` line if the tag is annotated), not the
|
||||
build-suffixed tags it also lists. PRs that land on `release/vX.Y` after the tag
|
||||
(`git log --oneline <tag>..<remote>/release/vX.Y`) belong to the next release, even if they are
|
||||
already merged when you write the note.
|
||||
|
||||
The range `<prev-pre-release>..<tag>` usually mixes two kinds of commits: individual backports
|
||||
(`... [Backport release/vX.Y] (#NNNN)`) and squashed pick commits (`chore: backport selected
|
||||
changes for ... (#NNNN)`). In both, the original PRs are the `(#NN)` at the end of body lines;
|
||||
@@ -156,8 +152,8 @@ done | tr -dc '0-9\n' | sort -un
|
||||
List the bullets under the **original** PRs (title and author of the PR merged to `main`), not
|
||||
the backport PRs. Build them with patch (a) or (b) above; for (b), fetch
|
||||
`gh api repos/GreptimeTeam/greptimedb/pulls/<n> --jq '{number,title,author:.user.login,merged_at}'`,
|
||||
group by the `cliff.toml` parsers (first match wins), order by `merged_at`, and put `!` titles
|
||||
under Breaking changes (§6).
|
||||
group by the `cliff.toml` parsers (first match wins), order by `merged_at`, and review `!` titles
|
||||
for user-visible compatibility impact (§6) before assigning a category.
|
||||
|
||||
A squashed pick PR can also contain release-only commits that have no PR. List them:
|
||||
```
|
||||
@@ -179,6 +175,10 @@ them and add the user-facing ones by hand:
|
||||
```
|
||||
git log --format=%s <range> | grep -E '\(#[0-9]+\)$' | grep -vE '^[a-z]+(\([^)]*\))?!?: '
|
||||
```
|
||||
Review generated breaking-change bullets using the same user-impact criteria as §6. Move
|
||||
internal-only entries to ordinary groups, preserving genuine incompatibilities, PR links,
|
||||
and authors.
|
||||
|
||||
Use only the groups in `cliff.toml`. `git cliff` prints a `### Build` section for `build:` commits
|
||||
because no parser matches them; move a user-facing `build(deps)` fix to Bug Fixes and the rest to
|
||||
Miscellaneous Tasks. Keep each bullet list free of blank lines; a blank line turns it into a
|
||||
@@ -217,45 +217,18 @@ line (ask the user; some prefer to keep it).
|
||||
|
||||
## 6. Human-curated sections (insert after the `Release date:` line)
|
||||
|
||||
**Style.** Follow the Google developer documentation style guide: sentence-case headings, active voice, present
|
||||
tense for behavior, American spelling, serial comma, code font for identifiers, bold only for UI
|
||||
names. Keep it short:
|
||||
- Intro: two sentences at most, what the release covers and its main theme.
|
||||
- Highlight: one paragraph of up to four sentences, plus an example if it earns one (see below).
|
||||
- Upgrade note or breaking change: one bullet, one or two sentences: what changes, who is
|
||||
affected, what to do.
|
||||
- Every sentence states a fact the reader acts on or checks. Delete sentences that restate the
|
||||
heading or the previous sentence, transitions, and summaries.
|
||||
- No marketing words (`significantly`, `powerful`, `seamless`, `robust`, `enhanced`), no vague
|
||||
verbs (`supports`, `handles`, `improves`; say what happens), no `several`/`many` when the number
|
||||
is known. Keep the source's hedges; don't add new ones.
|
||||
Write concise, factual English. Rank changes by their impact and explain what changed,
|
||||
why it matters, and any required action. Verify claims against the release's PRs, code,
|
||||
and documentation; preserve their conditions and limitations.
|
||||
|
||||
Example:
|
||||
> Bad: This release significantly enhances write reliability by introducing a robust retry
|
||||
> mechanism that seamlessly handles transient failures.
|
||||
>
|
||||
> Good: In distributed clusters, the frontend retries a failed write up to three times with
|
||||
> exponential backoff. Set `max_retries = 0` to disable retries.
|
||||
|
||||
Mirror past release bodies (`gh release view v1.0.0 --repo GreptimeTeam/greptimedb`):
|
||||
- **Short intro** (see Style).
|
||||
- **`### 👍 Highlights`** — *few, deep* highlights, ranked by user impact. Fixes for silently
|
||||
wrong query results, lost or invisible data, and security issues rank with new features and
|
||||
can be highlights.
|
||||
- Write a fix as its symptom and the affected deployments or usage, not the PR title. Example:
|
||||
"with no traffic, `errors / requests > 0.05` was true, so the alert fired".
|
||||
- State whether a feature is on by default. If an example config uses the default values, say
|
||||
so.
|
||||
- Give an example (SQL / TOML config) only where it helps readers act. Don't pick highlights,
|
||||
or the example, by what is easy to demonstrate.
|
||||
- One highlight covers one change or one user-visible problem. Don't merge unrelated PRs into
|
||||
one entry because they touch the same component.
|
||||
- Sources: the PR body's sections on impact, compatibility, and behavior changes, plus the
|
||||
code and config it touches, not the title alone. Verify examples against the related docs
|
||||
PR/page in the docs repo (`GreptimeTeam/docs`, often checked out locally),
|
||||
`docs/reference/sql/*.md`, `config/*.example.toml`, `config/config.md`.
|
||||
Do **not** mention implementation details, tiny features, or unfinished/experimental-but-not-ready
|
||||
features. Always have the user review and edit the highlights; iterate.
|
||||
- **Short intro** — summarize the release in one or two sentences.
|
||||
- **`### 👍 Highlights`** — select the most consequential changes, including new features,
|
||||
correctness, security, performance, and substantial architectural improvements. Internal changes can
|
||||
be highlights when their technical significance or benefit is supported by evidence;
|
||||
change size alone is not a reason to feature them. Explain enough of the mechanism to
|
||||
make the benefit clear, without turning the note into an implementation walkthrough.
|
||||
Keep related changes together and distinguish shipped benefits from future possibilities.
|
||||
Include usage examples only when needed, and verify them against the released version.
|
||||
- **Dashboard** subsection — don't just bump the version. Read the dashboard PRs in the bundled
|
||||
release (`gh release view <ver> --repo GreptimeTeam/dashboard`; then the linked PRs) and
|
||||
describe the user-facing change. Use the names the UI shows, not the PR titles; check them in
|
||||
@@ -266,22 +239,18 @@ Mirror past release bodies (`gh release view v1.0.0 --repo GreptimeTeam/greptime
|
||||
```
|
||||
Screenshots need absolute `https://` URLs: the body is copied to the GitHub release, where
|
||||
relative and site-root (`/img/...`) paths don't resolve.
|
||||
- **`### Upgrade notes`** and **`### Breaking changes`** — check every PR in the release for:
|
||||
`!` titles; `Compatibility`, `Behavior change`, `Breaking` paragraphs in the body (often a
|
||||
plain `Compatibility:` line, not a heading); unchecked "API changes are backward compatible" /
|
||||
"Schema or data changes are backward compatible" boxes; new config options and their defaults;
|
||||
changed defaults; persisted format changes; rolling-upgrade order; new hard limits. These
|
||||
signals set reading order, not a filter: a limit can sit in plain prose with every box
|
||||
checked, so read the body of every user-facing `feat`/`fix` PR. Examples of what is easy to
|
||||
miss: a 512 MiB cap on decompressed request bodies (#9264); a default step for stepless
|
||||
subqueries (#9481).
|
||||
- **Upgrade notes**: steps operators take — upgrade order, index rebuilds, settings to review.
|
||||
- **Breaking changes**: behavior that used to work and now errors or returns different
|
||||
results. Put the `!` PR bullets here too, after these entries (see `v1.3.0-beta.1`).
|
||||
- **`### Upgrade and compatibility notes`** — distinguish internal changes from changes
|
||||
visible to database users and operators. Include only user-visible compatibility changes
|
||||
and required upgrade actions; state who is affected, what changes, and what to do.
|
||||
Read PR bodies to establish impact: `!` titles and compatibility checkboxes alone do not
|
||||
determine whether a change belongs here. Internal changes without upgrade impact belong in
|
||||
highlights or the ordinary changelog, according to significance. Preserve PR links and
|
||||
contributor attribution. Omit empty sections and avoid repeating information across
|
||||
curated sections.
|
||||
- **Benchmark results** (optional) — state the baseline version (often the previous formal
|
||||
release, not the previous beta), data size, cache state, and hardware. Don't attribute results
|
||||
to single PRs. Leave out results the benchmark marks as not for publication, and smoke-level
|
||||
runs.
|
||||
release, not the previous beta), workload, data size, cache state, and hardware. Attribute results
|
||||
to individual changes only when the measurements isolate their effect. Leave out results the
|
||||
benchmark marks as not for publication, and smoke-level runs.
|
||||
|
||||
## 7. Output
|
||||
|
||||
@@ -323,7 +292,7 @@ The release note is also published as a blog post in **`GreptimeTeam/docs`**.
|
||||
(`.github/pull_request_template.md`) from the checkout used for the release.
|
||||
Fill in every required section; do not rely on hard-coded section names from an older
|
||||
template. The checklist items are the author's to confirm: check the ones you did, and for one
|
||||
that doesn't apply, check it and say why. For pre-releases, state the tagged SHA (§3) under
|
||||
that doesn't apply, check it and say why. State the release SHA (§3) under
|
||||
Verification.
|
||||
- **Build the site before opening the PR.** A new worktree has no `node_modules`. Install with
|
||||
the pnpm version pinned in `package.json` (`packageManager`), as CI does:
|
||||
|
||||
@@ -62,11 +62,12 @@ publishing.
|
||||
|
||||
**Do NOT pre-create the tag.** Creating the release creates the tag and fires the
|
||||
tag-push CI (`.github/workflows/release.yml`) that builds all binaries (**~hours**).
|
||||
Use the exact commit SHA verified for the changelog as `<verified-release-sha>`.
|
||||
Confirm with the user, then:
|
||||
```
|
||||
gh release create vX.Y.Z \
|
||||
--repo GreptimeTeam/greptimedb \
|
||||
--target release/vX.Y \
|
||||
--target <verified-release-sha> \
|
||||
--title "Release vX.Y.Z" \
|
||||
--notes-file CHANGELOG-vX.Y.Z.md \
|
||||
--prerelease
|
||||
@@ -78,7 +79,8 @@ gh release create vX.Y.Z \
|
||||
|
||||
## 4. Open the docs release-note PR (do not wait for CI)
|
||||
|
||||
Right after triggering the release, open the docs draft PR (see the docs section of the
|
||||
Verify that the remote tag resolves to the verified release SHA (peel annotated tags);
|
||||
stop if it differs. Then open the docs draft PR (see the docs section of the
|
||||
`greptimedb-release-note` skill). It only needs the finalized changelog.
|
||||
|
||||
Then **delete the local `CHANGELOG-vX.Y.Z.md`** (its content now lives in the release body
|
||||
|
||||
@@ -50,6 +50,11 @@ inputs:
|
||||
runs:
|
||||
using: composite
|
||||
steps:
|
||||
- name: Set up Linux runner
|
||||
uses: ./.github/actions/setup-linux-runner
|
||||
with:
|
||||
tools: make shasum
|
||||
|
||||
- name: Run integration test
|
||||
if: ${{ inputs.disable-run-tests == 'false' }}
|
||||
shell: bash
|
||||
|
||||
@@ -19,6 +19,12 @@ inputs:
|
||||
runs:
|
||||
using: composite
|
||||
steps:
|
||||
# Ubuntu 26.04 does not apply the runner's /etc/sysctl.conf at boot.
|
||||
# https://github.com/actions/runner-images/issues/15108
|
||||
- name: Configure inotify limits for kind
|
||||
shell: bash
|
||||
run: sudo sysctl -w fs.inotify.max_user_instances=1280 fs.inotify.max_user_watches=655360
|
||||
|
||||
- name: Deploy GreptimeDB by Helm
|
||||
shell: bash
|
||||
env:
|
||||
@@ -28,4 +34,5 @@ runs:
|
||||
AWS_ACCESS_KEY_ID: ${{ inputs.aws-access-key-id }}
|
||||
AWS_SECRET_ACCESS_KEY: ${{ inputs.aws-secret-access-key }}
|
||||
run: |
|
||||
./.github/scripts/deploy-greptimedb.sh
|
||||
# Composite steps do not support timeout-minutes.
|
||||
timeout --kill-after=30s 30m ./.github/scripts/deploy-greptimedb.sh
|
||||
|
||||
+28
-4
@@ -1,19 +1,41 @@
|
||||
name: Set up benchmark dependencies
|
||||
name: Set up Linux runner dependencies
|
||||
description: Reuse installed tools and install missing dependencies on an Ubuntu self-hosted runner
|
||||
inputs:
|
||||
tools:
|
||||
description: Space-separated commands to install if missing (Ubuntu package names, except shasum)
|
||||
required: false
|
||||
default: curl
|
||||
expected-architecture:
|
||||
description: Optional uname architecture required by the workload
|
||||
required: false
|
||||
default: ''
|
||||
runs:
|
||||
using: composite
|
||||
steps:
|
||||
- name: Check host and install missing tools
|
||||
shell: bash
|
||||
env:
|
||||
REQUIRED_TOOLS: ${{ inputs.tools }}
|
||||
EXPECTED_ARCH: ${{ inputs.expected-architecture }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
[[ "$(uname -m)" == x86_64 ]]
|
||||
if [[ -n "$EXPECTED_ARCH" ]]; then
|
||||
[[ "$(uname -m)" == "$EXPECTED_ARCH" ]]
|
||||
fi
|
||||
command -v git
|
||||
missing=()
|
||||
for tool in curl jq python3 rsync; do
|
||||
command -v "$tool" >/dev/null || missing+=("$tool")
|
||||
read -r -a tools <<< "$REQUIRED_TOOLS"
|
||||
for tool in "${tools[@]}"; do
|
||||
if ! command -v "$tool" >/dev/null; then
|
||||
case "$tool" in
|
||||
shasum) missing+=(libdigest-sha-perl) ;;
|
||||
*) missing+=("$tool") ;;
|
||||
esac
|
||||
fi
|
||||
done
|
||||
if ((${#missing[@]})); then
|
||||
. /etc/os-release
|
||||
[[ "$ID" == ubuntu ]]
|
||||
sudo -n apt-get update
|
||||
sudo -n env DEBIAN_FRONTEND=noninteractive NEEDRESTART_MODE=l apt-get install -y --no-install-recommends "${missing[@]}"
|
||||
fi
|
||||
@@ -24,6 +46,8 @@ runs:
|
||||
if ! command -v docker >/dev/null; then
|
||||
. /etc/os-release
|
||||
[[ "$ID" == ubuntu ]]
|
||||
sudo -n apt-get update
|
||||
sudo -n env DEBIAN_FRONTEND=noninteractive NEEDRESTART_MODE=l apt-get install -y --no-install-recommends curl ca-certificates
|
||||
sudo -n install -m 0755 -d /etc/apt/keyrings
|
||||
curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo -n tee /etc/apt/keyrings/docker.asc >/dev/null
|
||||
sudo -n chmod a+r /etc/apt/keyrings/docker.asc
|
||||
@@ -58,11 +58,19 @@ runs:
|
||||
run: |
|
||||
aws s3 rm s3://${{ inputs.aws-ci-test-bucket }}/${{ inputs.data-root }} --recursive
|
||||
- name: Export kind logs
|
||||
if: failure()
|
||||
if: failure() || cancelled()
|
||||
shell: bash
|
||||
run: kind export logs /tmp/kind
|
||||
run: |
|
||||
# Bound the entire collection while leaving the upload step available.
|
||||
timeout --kill-after=30s 5m bash -e -o pipefail <<'EOF'
|
||||
mkdir -p /tmp/kind
|
||||
kubectl --request-timeout=30s get pods -A -o wide > /tmp/kind/pods.txt 2>&1 || true
|
||||
kubectl --request-timeout=30s get events -A --sort-by=.metadata.creationTimestamp > /tmp/kind/events.txt 2>&1 || true
|
||||
kubectl --request-timeout=30s describe pods -A > /tmp/kind/pod-descriptions.txt 2>&1 || true
|
||||
kind export logs /tmp/kind
|
||||
EOF
|
||||
- name: Upload logs
|
||||
if: failure()
|
||||
if: failure() || cancelled()
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: kind-logs
|
||||
|
||||
@@ -20,6 +20,9 @@ inputs:
|
||||
image-id:
|
||||
description: The EC2 image id
|
||||
required: true
|
||||
ec2-volume-size:
|
||||
description: Root volume size in GiB (uses the AMI default when omitted)
|
||||
required: false
|
||||
security-group-id:
|
||||
description: The EC2 security group id
|
||||
required: true
|
||||
@@ -61,6 +64,7 @@ runs:
|
||||
with:
|
||||
mode: start
|
||||
ec2-image-id: ${{ inputs.image-id }}
|
||||
ec2-volume-size: ${{ inputs.ec2-volume-size }}
|
||||
ec2-instance-type: ${{ steps.get-ec2-instance-type.outputs.instance-type }}
|
||||
subnet-id: ${{ inputs.subnet-id }}
|
||||
security-group-id: ${{ inputs.security-group-id }}
|
||||
|
||||
@@ -13,6 +13,10 @@ 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.
|
||||
If GitHub rejects enqueueing because a PR belongs to a stack, the workflow skips
|
||||
it and continues without failing the run or counting it toward the five-PR limit.
|
||||
Other API errors still fail the run. Dry runs do not call the enqueue API, so
|
||||
they cannot detect this stack rejection.
|
||||
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.
|
||||
|
||||
@@ -133,9 +133,10 @@ def benchmark(root, targets):
|
||||
return '\n'.join(lines)
|
||||
|
||||
|
||||
def lifecycle(root, targets):
|
||||
manifest = read(root / 'run-manifest.json')
|
||||
corpus = read(root / 'corpus' / 'summary.json')
|
||||
def lifecycle(root, targets, data_root=None):
|
||||
data_root = data_root or root
|
||||
manifest = read(data_root / 'run-manifest.json')
|
||||
corpus = read(data_root / 'corpus' / 'summary.json')
|
||||
lines = ['# Load / lifecycle summary', '',
|
||||
f'Dataset: **{cell(manifest.get("profile", corpus.get("data_profile", {}).get("id")))}**; rows: **{cell(corpus.get("line_count"))}**; '
|
||||
f'seed: `{cell(corpus.get("seed"))}`.',
|
||||
@@ -161,12 +162,13 @@ def lifecycle(root, targets):
|
||||
physical_rows = []
|
||||
load_rows = []
|
||||
details = ['<details>', '<summary>DDL, index configuration and image provenance</summary>', '']
|
||||
raw_bytes = read(root / 'corpus' / 'size.json').get('raw_jsonl_bytes')
|
||||
raw_bytes = read(data_root / 'corpus' / 'size.json').get('raw_jsonl_bytes')
|
||||
for t in targets:
|
||||
directory = result_dir(root, t)
|
||||
physical = read(directory / 'physical-evidence.json')
|
||||
storage = physical.get('storage', {})
|
||||
total = storage.get('engine_total_bytes')
|
||||
s3 = read(root / f'{t}-1' / 'storage.json').get('type') == 's3'
|
||||
total = None if s3 else storage.get('engine_total_bytes')
|
||||
stats = read(root / f'{t}-1' / 'post-load-docker-stats.json')
|
||||
ratio = f'{raw_bytes / total:.2f}×' if (physical.get('passed') is True and
|
||||
isinstance(raw_bytes, (int, float)) and raw_bytes > 0 and
|
||||
@@ -186,6 +188,7 @@ def lifecycle(root, targets):
|
||||
lines += ['## Load and physical evidence', '', table(['DB', 'Write transport', 'Batches', 'Load smoke rows'], load_rows), '',
|
||||
f'Raw JSONL size: **{size(raw_bytes)}**. Ratio = raw JSONL / engine bytes at collection time; '
|
||||
'not a settled-storage guarantee. CPU/memory are post-load snapshots, not peaks. '
|
||||
'S3 total/compression is omitted: local files exclude remote objects. '
|
||||
'Missing artifacts remain blank; pre-cleanup stats are not substituted.', '',
|
||||
table(['DB', 'Engine size', 'Size ratio', 'Materialization', 'SSTs / active parts',
|
||||
'Post-load CPU', 'Post-load memory / limit'], physical_rows), '', *details, '</details>', '']
|
||||
|
||||
@@ -62,11 +62,12 @@ def row(query, metric, old, new, compatible, reason):
|
||||
improvement_percent=delta, status='comparable' if delta is not None else reason)
|
||||
|
||||
|
||||
def agent(root):
|
||||
def agent(root, storage="file"):
|
||||
candidate, baseline = (root, root / "baseline") if storage == "file" else (root / "s3", root / "baseline/s3")
|
||||
def load(r):
|
||||
return read(r / 'greptimedb-1/greptimedb-1/measured-summary.json')
|
||||
a, b = load(root / 'baseline'), load(root)
|
||||
finished = [r / 'greptimedb-1/exit-code.txt' for r in (root / 'baseline', root)]
|
||||
a, b = load(baseline), load(candidate)
|
||||
finished = [r / 'greptimedb-1/exit-code.txt' for r in (baseline, candidate)]
|
||||
compatible = (all(p.is_file() and p.read_text().strip() == '0' for p in finished)
|
||||
and a.get('passed') is True and b.get('passed') is True
|
||||
and same(a, b, ('contract_sha256', 'data_profile', 'query_window', 'warmup_runs', 'measured_runs')))
|
||||
@@ -81,8 +82,9 @@ def agent(root):
|
||||
return rows
|
||||
|
||||
|
||||
def traces(root):
|
||||
a, b = (read(r / 'runs/greptimedb/run.json') for r in (root / 'baseline', root))
|
||||
def traces(root, storage="file"):
|
||||
candidate, baseline = (root, root / "baseline") if storage == "file" else (root / "s3", root / "baseline/s3")
|
||||
a, b = (read(r / 'runs/greptimedb/run.json') for r in (baseline, candidate))
|
||||
compatible = (a.get('success') is True and b.get('success') is True
|
||||
and same(a, b, ('expected', 'protocol', 'audit_expected', 'corpus'))
|
||||
and same(a.get('execution', {}), b.get('execution', {}),
|
||||
@@ -110,18 +112,22 @@ def traces(root):
|
||||
return rows
|
||||
|
||||
|
||||
def long_range(root):
|
||||
def long_range(root, storage="file"):
|
||||
names = ("greptimedb-baseline", "greptimedb") if storage == "file" else ("greptimedb-s3-baseline", "greptimedb-s3")
|
||||
def target_root(name):
|
||||
nested = root / "o11ybench" / ("o11ybench-" + name)
|
||||
return nested if nested.exists() else root
|
||||
rows = []
|
||||
manifest = read(root / 'run-manifest.json')
|
||||
manifests = {name: read(target_root(name) / 'run-manifest.json') for name in names}
|
||||
healthy = all(
|
||||
all(field in (manifest.get(phase, {}).get(target, {}).get('docker', {}) if phase == 'post_load_results'
|
||||
else manifest.get(phase, {}).get(target, {})).get('state', '').split()
|
||||
all(field in (manifests[target].get(phase, {}).get(target, {}).get('docker', {}) if phase == 'post_load_results'
|
||||
else manifests[target].get(phase, {}).get(target, {})).get('state', '').split()
|
||||
for field in ('Running=true', 'ExitCode=0', 'OOMKilled=false'))
|
||||
for phase in ('post_load_results', 'post_query_results')
|
||||
for target in ('greptimedb-baseline', 'greptimedb'))
|
||||
for target in names)
|
||||
for mode in ('serial', 'concurrent-duration-c1', 'concurrent-duration-c4'):
|
||||
a, b = (read(root / name / 'results-vmbench-long-range' / (mode + '-summary.json'))
|
||||
for name in ('greptimedb-baseline', 'greptimedb'))
|
||||
a, b = (read(target_root(name) / name / 'results-vmbench-long-range' / (mode + '-summary.json'))
|
||||
for name in names)
|
||||
fields = ('workload', 'query_file_sha256', 'start', 'end', 'step', 'profile', 'data_duration',
|
||||
'scrape_interval', 'cache_policy_effective', 'mode', 'connection_mode', 'request_timeout_seconds')
|
||||
fields += ('tries', 'warmup_runs') if mode == 'serial' else ('concurrency', 'duration_seconds', 'warmup_seconds')
|
||||
@@ -178,7 +184,13 @@ def main():
|
||||
parser.error('report requires --root and --kind')
|
||||
document = {'kind': args.kind, 'baseline_tag': os.environ.get('BASELINE_GREPTIMEDB_TAG', ''),
|
||||
'candidate_tag': os.environ.get('GREPTIMEDB_TAG', ''),
|
||||
'rows': {'agent': agent, 'traces': traces, 'long-range': long_range}[args.kind](args.root)}
|
||||
'rows': []}
|
||||
mode = os.environ.get('GREPTIMEDB_STORAGE', 'file')
|
||||
for storage in (['file', 's3'] if mode == 'both' else [mode]):
|
||||
rows = {'agent': agent, 'traces': traces, 'long-range': long_range}[args.kind](args.root, storage)
|
||||
for item in rows:
|
||||
item['query'] = storage.upper() + '/' + item['query']
|
||||
document['rows'].extend(rows)
|
||||
text = render(document)
|
||||
# Preserve partial comparisons even if a target failed before creating output.
|
||||
args.root.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
@@ -13,8 +13,12 @@ AWS uses `aws-ec2-runner-provision.py` and `aws-ec2-runner-teardown.py` directly
|
||||
Repository variables supply `EC2_RUNNER_REGION`, `EC2_RUNNER_SUBNET_ID`, and
|
||||
`EC2_RUNNER_SECURITY_GROUP_ID`; credentials use `AWS_ACCESS_KEY_ID`,
|
||||
`AWS_SECRET_ACCESS_KEY`, and `GH_PERSONAL_ACCESS_TOKEN` secrets.
|
||||
The current region is Singapore (`ap-southeast-1`). By default the script selects
|
||||
the newest available Canonical Ubuntu 24.04 amd64 server AMI in that region
|
||||
The runner region comes from `EC2_RUNNER_REGION` (currently `us-east-1`).
|
||||
The subnet and security group must belong to the selected AWS account and region.
|
||||
For benchmarks using real S3, `AWS_CI_TEST_BUCKET_REGION` must match the runner
|
||||
region; `AWS_CI_TEST_BUCKET` must be accessible with the configured credentials.
|
||||
By default the script selects the newest available Canonical Ubuntu 24.04 amd64
|
||||
server AMI in that region
|
||||
(owner `099720109477`) and logs its ID. Set `BENCHMARK_EC2_IMAGE_ID` to pin a
|
||||
prepared Ubuntu AMI. Existing build CI's `EC2_RUNNER_LINUX_AMD64_IMAGE_ID` is
|
||||
unaffected. Both workflows default `system_disk_gib` to `auto` (also accepting
|
||||
@@ -31,9 +35,12 @@ swappiness 10, disables systemd-oomd and background automatic updates, and sets
|
||||
`OOMPolicy=continue` on the runner service. Explicit setup package installation
|
||||
remains enabled.
|
||||
|
||||
Both benchmark jobs call `.github/actions/setup-benchmark` after checkout. It
|
||||
reuses existing tools, installs missing curl/jq/python3/rsync, installs Docker CE
|
||||
if absent, and checks Docker access. Missing packages require passwordless sudo;
|
||||
Benchmark jobs call `.github/actions/setup-linux-runner` after checkout with
|
||||
`tools: curl jq python3 rsync` and require x86_64. Linux artifact builds reuse
|
||||
the same action with `tools: make shasum` on either amd64 or arm64; the RISC-V
|
||||
cross-build calls it on amd64 too. The action reuses installed commands, maps
|
||||
`shasum` to Ubuntu package `libdigest-sha-perl`, installs Docker CE if absent,
|
||||
and checks Docker access. Missing packages require passwordless sudo;
|
||||
Aliyun's prepared image normally provides the tools and Docker already. Existing
|
||||
Docker installations are preserved, so exact versions need not match between
|
||||
providers. Provisioning must establish Docker permissions before starting the
|
||||
|
||||
@@ -50,7 +50,7 @@ function deploy_etcd_cluster() {
|
||||
-n "$namespace"
|
||||
|
||||
# Wait for etcd cluster to be ready.
|
||||
kubectl rollout status statefulset/etcd -n "$namespace"
|
||||
kubectl rollout status statefulset/etcd -n "$namespace" --timeout=5m
|
||||
}
|
||||
|
||||
# Deploy greptimedb-operator.
|
||||
@@ -81,16 +81,8 @@ function deploy_greptimedb_cluster() {
|
||||
-n "$install_namespace"
|
||||
|
||||
# Wait for greptimedb cluster to be ready.
|
||||
while true; do
|
||||
PHASE=$(kubectl -n "$install_namespace" get gtc "$cluster_name" -o jsonpath='{.status.clusterPhase}')
|
||||
if [ "$PHASE" == "Running" ]; then
|
||||
echo "Cluster is ready"
|
||||
break
|
||||
else
|
||||
echo "Cluster is not ready yet: Current phase: $PHASE"
|
||||
sleep 5 # wait for 5 seconds before check again.
|
||||
fi
|
||||
done
|
||||
kubectl -n "$install_namespace" wait "gtc/$cluster_name" \
|
||||
--for=jsonpath='{.status.clusterPhase}'=Running --timeout=5m
|
||||
|
||||
# Expose greptimedb cluster to local access and check if port-forward is available.
|
||||
kubectl -n "$install_namespace" port-forward svc/"$cluster_name"-frontend \
|
||||
@@ -141,16 +133,8 @@ function deploy_greptimedb_cluster_with_s3_storage() {
|
||||
--set objectStorage.credentials.secretAccessKey="$AWS_SECRET_ACCESS_KEY"
|
||||
|
||||
# Wait for greptimedb cluster to be ready.
|
||||
while true; do
|
||||
PHASE=$(kubectl -n "$install_namespace" get gtc "$cluster_name" -o jsonpath='{.status.clusterPhase}')
|
||||
if [ "$PHASE" == "Running" ]; then
|
||||
echo "Cluster is ready"
|
||||
break
|
||||
else
|
||||
echo "Cluster is not ready yet: Current phase: $PHASE"
|
||||
sleep 5 # wait for 5 seconds before check again.
|
||||
fi
|
||||
done
|
||||
kubectl -n "$install_namespace" wait "gtc/$cluster_name" \
|
||||
--for=jsonpath='{.status.clusterPhase}'=Running --timeout=5m
|
||||
|
||||
# Expose greptimedb cluster to local access.
|
||||
kubectl -n "$install_namespace" port-forward svc/"$cluster_name"-frontend \
|
||||
@@ -168,8 +152,8 @@ function deploy_standalone_greptimedb() {
|
||||
--set image.tag="$GREPTIMEDB_IMAGE_TAG" \
|
||||
-n "$DEFAULT_INSTALL_NAMESPACE"
|
||||
|
||||
# Wait for etcd cluster to be ready.
|
||||
kubectl rollout status statefulset/greptimedb-standalone -n "$DEFAULT_INSTALL_NAMESPACE"
|
||||
# Wait for standalone GreptimeDB to be ready.
|
||||
kubectl rollout status statefulset/greptimedb-standalone -n "$DEFAULT_INSTALL_NAMESPACE" --timeout=5m
|
||||
|
||||
# Expose greptimedb to local access.
|
||||
kubectl -n "$DEFAULT_INSTALL_NAMESPACE" port-forward svc/greptimedb-standalone \
|
||||
|
||||
@@ -105,8 +105,9 @@ class Benchmark:
|
||||
self.endpoint = os.environ.get("S3_ENDPOINT", "")
|
||||
if self.endpoint and not local_smoke:
|
||||
raise ValueError("Custom S3 endpoints are restricted to local smoke")
|
||||
if not local_smoke and os.environ["S3_REGION"] != "ap-southeast-1":
|
||||
raise ValueError("Cloud benchmark requires ap-southeast-1")
|
||||
if not local_smoke and (not os.environ["S3_REGION"].strip()
|
||||
or os.environ["S3_REGION"] != os.environ["RUNNER_REGION"]):
|
||||
raise ValueError("Cloud benchmark requires the same nonempty bucket and runner region")
|
||||
self.containers = set()
|
||||
self.network_created = False
|
||||
self.phases = []
|
||||
@@ -324,7 +325,7 @@ level = "info"
|
||||
lines = ["# Metric packed snapshot benchmark", "", f"Image: `{self.image}`",
|
||||
f"Source commit: `{self.commit}`", "",
|
||||
"Local smoke only; timings are not AWS results." if self.local_smoke else
|
||||
"AWS S3 in ap-southeast-1; source and target use local File storage.", "",
|
||||
f"S3 in {os.environ['S3_REGION']}; source and target use local File storage.", "",
|
||||
"| Round | Phase | Seconds | Result |", "| --- | --- | ---: | --- |"]
|
||||
for phase in self.phases:
|
||||
lines.append(f"| {phase['round']} | {phase['phase']} | {phase['wall_seconds']:.3f} | {phase['outcome']} |")
|
||||
|
||||
@@ -21,7 +21,7 @@
|
||||
"""Budget preflight and strictly scoped S3 operations for the metric snapshot benchmark."""
|
||||
|
||||
import argparse
|
||||
from decimal import Decimal
|
||||
from decimal import Decimal, InvalidOperation
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
@@ -29,8 +29,8 @@ import re
|
||||
import time
|
||||
import urllib.request
|
||||
|
||||
REGION = "ap-southeast-1"
|
||||
HOURLY_USD = Decimal("0.9408")
|
||||
# Historical budget estimate; dispatch can supply a rate for the configured region.
|
||||
DEFAULT_HOURLY_USD = "0.9408"
|
||||
OTHER_RESERVE_USD = Decimal("1.50")
|
||||
|
||||
|
||||
@@ -40,6 +40,16 @@ def owned_prefix(prefix):
|
||||
return prefix
|
||||
|
||||
|
||||
def hourly_estimate(env):
|
||||
try:
|
||||
estimate = Decimal(env.get("EC2_HOURLY_USD", DEFAULT_HOURLY_USD))
|
||||
except InvalidOperation as error:
|
||||
raise ValueError("EC2_HOURLY_USD must be a positive finite estimate") from error
|
||||
if not estimate.is_finite() or estimate <= 0:
|
||||
raise ValueError("EC2_HOURLY_USD must be a positive finite estimate")
|
||||
return estimate
|
||||
|
||||
|
||||
def plan(env):
|
||||
image = env["GREPTIMEDB_IMAGE"]
|
||||
if not re.fullmatch(r"greptime/greptimedb(?:-nightly)?@sha256:[0-9a-f]{64}", image):
|
||||
@@ -49,21 +59,22 @@ def plan(env):
|
||||
tables, minutes = int(env["LOGICAL_TABLES_PER_GROUP"]), int(env["BENCHMARK_TIMEOUT_MINUTES"])
|
||||
if not 50 <= tables <= 10_000 or not 30 <= minutes <= 240:
|
||||
raise ValueError("logical tables per group must be 50..10000; timeout must be 30..240 minutes")
|
||||
if env["S3_REGION"] != REGION or env["RUNNER_REGION"] != REGION:
|
||||
raise ValueError("bucket and runner must both use ap-southeast-1")
|
||||
if not env["S3_REGION"].strip() or env["S3_REGION"] != env["RUNNER_REGION"]:
|
||||
raise ValueError("bucket and runner must use the same nonempty region")
|
||||
if not env["S3_BUCKET"]:
|
||||
raise ValueError("S3 bucket is required")
|
||||
prior = Decimal(env["PRIOR_SPEND_USD"])
|
||||
# Reserve 45m provision, 10m queue allowance and 20m cleanup beyond the job timeout.
|
||||
reservation = HOURLY_USD * Decimal(minutes + 75) / 60 + OTHER_RESERVE_USD
|
||||
hourly = hourly_estimate(env)
|
||||
reservation = hourly * Decimal(minutes + 75) / 60 + OTHER_RESERVE_USD
|
||||
if not prior.is_finite() or prior < 0 or prior >= 15 or prior + reservation > 20:
|
||||
raise ValueError("campaign budget exhausted: prior spend must be below $15 and leave the full attempt reserve within $20")
|
||||
return {"image": image, "expected_commit": env["EXPECTED_COMMIT"],
|
||||
"logical_tables_per_group": tables, "smoke_logical_tables": 500,
|
||||
"timeout_minutes": minutes, "prefix": owned_prefix(env["RUN_PREFIX"]),
|
||||
"instance_type": "c6id.4xlarge", "region": REGION,
|
||||
"instance_type": "c6id.4xlarge", "region": env["S3_REGION"],
|
||||
"prior_estimated_usd": str(prior), "attempt_reserve_usd": str(reservation),
|
||||
"ec2_hourly_usd": str(HOURLY_USD), "other_reserve_usd": str(OTHER_RESERVE_USD),
|
||||
"ec2_hourly_usd": str(hourly), "other_reserve_usd": str(OTHER_RESERVE_USD),
|
||||
"cost_note": "Estimate, not an AWS billing total or a hard spending cap."}
|
||||
|
||||
|
||||
@@ -71,8 +82,8 @@ def client(region):
|
||||
import boto3
|
||||
from botocore.config import Config
|
||||
|
||||
if region != REGION:
|
||||
raise ValueError("S3 region must be ap-southeast-1")
|
||||
if not region.strip():
|
||||
raise ValueError("S3 region is required")
|
||||
return boto3.client("s3", region_name=region, config=Config(
|
||||
connect_timeout=10, read_timeout=30, retries={"mode": "standard", "max_attempts": 3}))
|
||||
|
||||
@@ -193,8 +204,10 @@ def main():
|
||||
if args.started_at is None:
|
||||
parser.error("cost requires --started-at")
|
||||
seconds = max(0, int(time.time()) - args.started_at)
|
||||
estimate = HOURLY_USD * Decimal(seconds) / 3600
|
||||
result = {"allocation_window_seconds": seconds, "ec2_estimate_usd": str(round(estimate, 4)),
|
||||
hourly = hourly_estimate(os.environ)
|
||||
estimate = hourly * Decimal(seconds) / 3600
|
||||
result = {"allocation_window_seconds": seconds, "ec2_hourly_usd": str(hourly),
|
||||
"ec2_estimate_usd": str(round(estimate, 4)),
|
||||
"campaign_estimate_with_other_reserve_usd": str(round(
|
||||
Decimal(os.environ["PRIOR_SPEND_USD"]) + estimate + OTHER_RESERVE_USD, 4)),
|
||||
"note": "Allocation wall-time estimate plus $1.50 reserve for S3, disk and IPv4; not an AWS bill."}
|
||||
|
||||
@@ -0,0 +1,316 @@
|
||||
# Copyright 2023 Greptime Team
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
"""Select File/S3 benchmark arms without changing workload adapters."""
|
||||
import argparse
|
||||
import copy
|
||||
import importlib.util
|
||||
import json
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import os
|
||||
import subprocess
|
||||
|
||||
|
||||
def validate(env):
|
||||
mode = env.get('GREPTIMEDB_STORAGE', 'file')
|
||||
if mode not in ('file', 's3', 'both'):
|
||||
raise ValueError('GREPTIMEDB_STORAGE must be file, s3 or both')
|
||||
if mode != 'file':
|
||||
if env.get('RUN_GREPTIMEDB') != 'true':
|
||||
raise ValueError('S3 requires Run GreptimeDB')
|
||||
if env.get('PROVIDER') != 'AWS':
|
||||
raise ValueError('S3 comparisons require an AWS runner')
|
||||
if not env.get('S3_BUCKET') or not env.get('S3_REGION'):
|
||||
raise ValueError('AWS_CI_TEST_BUCKET and AWS_CI_TEST_BUCKET_REGION must be configured')
|
||||
if env['S3_REGION'] != env.get('RUNNER_REGION'):
|
||||
raise ValueError('S3 bucket and EC2 runner regions must match')
|
||||
return mode
|
||||
|
||||
|
||||
def replace(command, key, value):
|
||||
result = list(command)
|
||||
if key in result:
|
||||
result[result.index(key) + 1] = value
|
||||
else:
|
||||
result += [key, value]
|
||||
return result
|
||||
|
||||
|
||||
def commands(command, mode):
|
||||
"""Recovery visits each owned root; execution uses explicit workflow steps."""
|
||||
stage = command[command.index('--stage') + 1]
|
||||
if stage != 'cleanup':
|
||||
raise ValueError('only cleanup may expand multiple arms')
|
||||
result = [list(command)]
|
||||
if mode != 'file':
|
||||
root = command[command.index('--root') + 1]
|
||||
owner = command[command.index('--owner') + 1]
|
||||
secondary = replace(command, '--root', root + '/s3')
|
||||
result.append(replace(secondary, '--owner', owner + '-s3'))
|
||||
return result
|
||||
|
||||
|
||||
def module(path):
|
||||
sys.path.insert(0, str(path.parent))
|
||||
spec = importlib.util.spec_from_file_location(path.stem.replace('-', '_'), path)
|
||||
result = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(result)
|
||||
return result
|
||||
|
||||
|
||||
def summary(kind, root, targets, section, mode):
|
||||
filename = 'agent-observability-summary.py' if kind == 'agent' else 'tracesbench-summary.py'
|
||||
renderer = module(Path(__file__).with_name(filename))
|
||||
primary = [t for t in targets if t != 'greptimedb' or mode != 's3']
|
||||
arms = [(root, primary, 'File')]
|
||||
if mode != 'file' and 'greptimedb' in targets:
|
||||
arms.append((root / 's3', ['greptimedb'], 'S3'))
|
||||
output = []
|
||||
for arm, selected, label in arms:
|
||||
if not selected:
|
||||
continue
|
||||
output.append('## ' + ('GreptimeDB S3' if label == 'S3' else 'Primary targets (GreptimeDB File)'))
|
||||
if kind == 'agent':
|
||||
body = (renderer.benchmark(arm, selected) if section == 'benchmark'
|
||||
else renderer.lifecycle(arm, selected, data_root=root.parent if root.name == 'baseline' else root))
|
||||
else:
|
||||
report, runs = renderer.load(arm)
|
||||
body = (renderer.benchmark(report, runs, selected) if section == 'benchmark'
|
||||
else renderer.lifecycle(report, runs, arm, selected))
|
||||
body = body.replace('| greptimedb |', '| GreptimeDB ' + label + ' |')
|
||||
body = body.replace('**greptimedb**', '**GreptimeDB ' + label + '**')
|
||||
output.append(body)
|
||||
if label == 'S3':
|
||||
directories = [arm / 'greptimedb-1'] if kind == 'agent' else [arm / 'runs/greptimedb']
|
||||
for directory in directories:
|
||||
for action in ('probe', 'inventory', 'cleanup'):
|
||||
path = directory / ('s3-' + action + '.json')
|
||||
data = json.loads(path.read_text()) if path.exists() else {}
|
||||
status = 'passed' if data.get('passed') is True else 'failed / unavailable'
|
||||
count = data.get('object_count', data.get('deleted_objects', '—'))
|
||||
output.append(f'- S3 {action}: **{status}**; objects: {count}.')
|
||||
return '\n\n'.join(output)
|
||||
|
||||
|
||||
def split_metrics(plan):
|
||||
"""One executor root per target, with the immutable dataset shared by all."""
|
||||
result = {}
|
||||
for target in plan['targets']:
|
||||
child = copy.deepcopy(plan)
|
||||
name = target['name']
|
||||
dest = str(Path(plan['output_root']) / 'o11ybench' / ('o11ybench-' + name))
|
||||
child['output_root'] = dest
|
||||
child['run_id'] = plan['run_id'] + '-' + name
|
||||
child['targets'] = [copy.deepcopy(target)]
|
||||
child['data']['generate'] = False
|
||||
child['report'].update(root=dest + '/report', index_html=dest + '/report/index.html')
|
||||
child['artifacts'] = {k: dest + '/' + Path(v).name for k, v in plan['artifacts'].items()}
|
||||
result[name] = child
|
||||
return result
|
||||
|
||||
|
||||
def metrics(action, args):
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument('--plan', type=Path, required=True)
|
||||
parser.add_argument('--tools', type=Path, required=True)
|
||||
parser.add_argument('--runtime-image', required=True)
|
||||
parser.add_argument('--target')
|
||||
a = parser.parse_args(args)
|
||||
plan = json.loads(a.plan.read_text())
|
||||
plan['runtime_image'] = a.runtime_image
|
||||
executor = module(a.tools / 'scripts/run_benchmark_plan.py')
|
||||
root = Path(plan['output_root'])
|
||||
if action == 'metrics-prepare':
|
||||
executor.require_safe_execute_root(root)
|
||||
root.mkdir(parents=True, exist_ok=False)
|
||||
manifest = executor.build_manifest(plan)
|
||||
executor.run_checked([str(executor.DOWNLOAD_DATA)], manifest,
|
||||
env=executor.generation_environment(plan))
|
||||
(root / 'generation.json').write_text(json.dumps(manifest, indent=2) + '\n')
|
||||
for name, child in split_metrics(plan).items():
|
||||
(a.plan.parent / (name + '.json')).write_text(json.dumps(child, indent=2) + '\n')
|
||||
elif action == 'metrics-run':
|
||||
path = a.plan.parent / (a.target + '.json')
|
||||
child = json.loads(path.read_text())
|
||||
executor.execute_plan(child, executor.build_manifest(child), replace=False)
|
||||
subprocess.run([sys.executable, str(a.tools / 'scripts/check_run_benchmark_plan.py'),
|
||||
'--artifacts', child['output_root']], check=True)
|
||||
else:
|
||||
# Validate every selected target together, retaining cross-target gates.
|
||||
manifests = [executor.build_manifest(child) for child in split_metrics(plan).values()]
|
||||
combined = executor.build_manifest(plan)
|
||||
combined['targets'] = [target for m in manifests for target in m['targets']]
|
||||
for command in executor.validation_commands(combined):
|
||||
subprocess.run(command, check=True)
|
||||
|
||||
|
||||
def overview(path):
|
||||
"""Render the same validated report data into the GitHub job summary."""
|
||||
data = json.loads(path.read_text())
|
||||
renderer = module(Path(__file__).with_name('agent-observability-summary.py'))
|
||||
lines = ['# Storage comparison', '', 'Smoke results are diagnostic; see classification per arm. '
|
||||
'No cold-object-store performance claim. Missing results are not passes.', '']
|
||||
for workload in data['workloads']:
|
||||
labels = {p['id']: p['label'] for p in workload['participants']}
|
||||
for scenario in workload['scenarios']:
|
||||
lines += ['## ' + workload['title'] + ' / ' + scenario['label'], '']
|
||||
rows = []
|
||||
for result in scenario['results']:
|
||||
lines += [labels[result['participant']] + ': ' + str(result.get('classification')), '']
|
||||
for query_id, query in result['queries'].items():
|
||||
m = query['metrics']
|
||||
rows.append([query_id, labels[result['participant']], query['status'],
|
||||
renderer.duration(m.get('p50_ms', m.get('median_ms'))),
|
||||
renderer.duration(m.get('p95_ms')), renderer.duration(m.get('p99_ms'))])
|
||||
lines.append(renderer.table(['Query', 'DB / storage', 'Status', 'P50 / median', 'P95', 'P99'], rows))
|
||||
return '\n'.join(lines)
|
||||
|
||||
|
||||
def audit(root, report, targets, mode, baseline=False, allow_trace_query_failures=False):
|
||||
data = json.loads(report.read_text())
|
||||
actual = {(p['target'], p.get('storage', {}).get('type'), p['role'])
|
||||
for w in data['workloads'] for p in w['participants']}
|
||||
expected = {(t, None, 'comparison') for t in targets if t != 'greptimedb'}
|
||||
modes = ['file', 's3'] if mode == 'both' else [mode]
|
||||
if 'greptimedb' in targets:
|
||||
expected |= {('greptimedb', m, role) for m in modes
|
||||
for role in (['candidate', 'baseline'] if baseline else ['candidate'])}
|
||||
if actual != expected:
|
||||
raise ValueError(f'participant mismatch: expected {sorted(map(str, expected))}, got {sorted(map(str, actual))}')
|
||||
query_failures = []
|
||||
for w in data['workloads']:
|
||||
partial = allow_trace_query_failures and w.get('id') == 'traces'
|
||||
if partial and not w['scenarios']:
|
||||
raise ValueError('missing trace scenarios')
|
||||
for scenario in w['scenarios']:
|
||||
if partial and {r['participant'] for r in scenario['results']} != {p['id'] for p in w['participants']}:
|
||||
raise ValueError('missing trace participant results')
|
||||
for result in scenario['results']:
|
||||
if partial and result.get('health') != 'recorded healthy snapshots':
|
||||
raise ValueError('missing or unhealthy trace evidence: ' + result['participant'])
|
||||
queries = result['queries']
|
||||
if not any(q['status'] == 'passed' for q in queries.values()):
|
||||
raise ValueError('no successful measured queries: ' + result['participant'])
|
||||
if any(q['status'] == 'unavailable' or (q['status'] == 'failed' and not partial)
|
||||
for q in queries.values()):
|
||||
raise ValueError('failed or unavailable queries: ' + result['participant'])
|
||||
for query_id, query in queries.items():
|
||||
if query['status'] == 'failed':
|
||||
query_failures.append(dict(workload=w['id'], scenario=scenario['id'],
|
||||
participant=result['participant'], query=query_id,
|
||||
reason=query.get('reason', '')))
|
||||
for manifest_path in root.glob('o11ybench/*/run-manifest.json'):
|
||||
manifest = json.loads(manifest_path.read_text())
|
||||
if manifest.get('status') != 'passed':
|
||||
raise ValueError('incomplete target manifest: ' + str(manifest_path))
|
||||
probes = list(root.rglob('s3-probe.json'))
|
||||
expected_s3 = sum(m == 's3' for _, m, _ in expected)
|
||||
if len(probes) != expected_s3:
|
||||
raise ValueError('missing or duplicate S3 evidence')
|
||||
for probe in probes:
|
||||
for action in ('probe', 'inventory', 'cleanup'):
|
||||
payload = json.loads(probe.with_name('s3-' + action + '.json').read_text())
|
||||
if payload.get('passed') is not True or (action == 'inventory' and payload.get('object_count', 0) <= 0):
|
||||
raise ValueError('failed S3 ' + action)
|
||||
text = (root / 'ci-summary.md').read_text()
|
||||
for m in modes if 'greptimedb' in targets else []:
|
||||
if m.upper() not in text:
|
||||
raise ValueError('storage mode missing from saved summary: ' + m)
|
||||
result = dict(passed=True, participants=[dict(target=t, storage=m, role=role)
|
||||
for t, m, role in sorted(expected, key=str)], s3_arms=len(probes), query_failures=query_failures)
|
||||
(root / 'artifact-audit.json').write_text(json.dumps(result, indent=2) + '\n')
|
||||
lines = ['## Artifact validation', '', '- Selected participants: ' + str(len(expected)) + '; all present.',
|
||||
'- Query result coverage and S3 probe/inventory/cleanup: passed.', '']
|
||||
if query_failures:
|
||||
lines += ['- Collection completed with query failures; this is not an all-pass query run.', '']
|
||||
lines += [f"- {f['participant']} / {f['query']}: failed (excluded from comparison)."
|
||||
for f in query_failures]
|
||||
lines.append('')
|
||||
renderer = module(Path(__file__).with_name('agent-observability-summary.py'))
|
||||
rows = []
|
||||
for probe in probes:
|
||||
inv = json.loads(probe.with_name('s3-inventory.json').read_text())
|
||||
cleanup = json.loads(probe.with_name('s3-cleanup.json').read_text())
|
||||
rows.append([str(probe.parent.relative_to(root)), inv['object_count'], inv['object_bytes'],
|
||||
cleanup.get('deleted_objects'), 'passed'])
|
||||
if rows:
|
||||
lines.append(renderer.table(['S3 arm', 'Objects', 'Remote bytes', 'Deleted current objects', 'Cleanup'], rows))
|
||||
text = '\n'.join(lines) + '\n'
|
||||
with (root / 'ci-summary.md').open('a') as output:
|
||||
output.write(text)
|
||||
if os.environ.get('GITHUB_STEP_SUMMARY'):
|
||||
with Path(os.environ['GITHUB_STEP_SUMMARY']).open('a') as output:
|
||||
output.write(text)
|
||||
return result
|
||||
|
||||
|
||||
def main():
|
||||
if len(sys.argv) > 1 and sys.argv[1] == 'audit':
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument('--root', type=Path, required=True)
|
||||
parser.add_argument('--report', type=Path, required=True)
|
||||
parser.add_argument('--targets', required=True)
|
||||
parser.add_argument('--allow-trace-query-failures', action='store_true',
|
||||
help='Retain failed Traces queries after native validation; missing results still fail')
|
||||
args = parser.parse_args(sys.argv[2:])
|
||||
print(json.dumps(audit(args.root, args.report, args.targets.split(','),
|
||||
os.environ.get('GREPTIMEDB_STORAGE', 'file'),
|
||||
os.environ.get('COMPARE_GREPTIMEDB') == 'true', args.allow_trace_query_failures)))
|
||||
return
|
||||
if len(sys.argv) > 1 and sys.argv[1] == 'normalize-metrics':
|
||||
path = Path(sys.argv[2])
|
||||
plan = json.loads(path.read_text())
|
||||
for target in plan['targets']:
|
||||
if target.get('storage', {}).get('type') == 's3' and '-s3' not in target['name']:
|
||||
target['name'] = target['name'].replace('-baseline', '-s3-baseline') if target['name'].endswith('-baseline') else target['name'] + '-s3'
|
||||
path.write_text(json.dumps(plan, indent=2) + '\n')
|
||||
return
|
||||
if len(sys.argv) > 1 and sys.argv[1].startswith('metrics-'):
|
||||
metrics(sys.argv[1], sys.argv[2:])
|
||||
return
|
||||
if len(sys.argv) > 1 and sys.argv[1] == 'overview':
|
||||
print(overview(Path(sys.argv[2])))
|
||||
return
|
||||
if len(sys.argv) > 1 and sys.argv[1] == 'summary':
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument('--kind', choices=['agent', 'traces'], required=True)
|
||||
parser.add_argument('--root', type=Path, required=True)
|
||||
parser.add_argument('--targets', required=True)
|
||||
parser.add_argument('--section', choices=['benchmark', 'lifecycle'], required=True)
|
||||
args = parser.parse_args(sys.argv[2:])
|
||||
print(summary(args.kind, args.root, args.targets.split(','), args.section,
|
||||
os.environ.get('GREPTIMEDB_STORAGE', 'file')))
|
||||
return
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('action', choices=['validate', 'run'])
|
||||
parser.add_argument('command', nargs=argparse.REMAINDER)
|
||||
args = parser.parse_args()
|
||||
mode = validate(os.environ)
|
||||
if args.action == 'validate':
|
||||
print('GreptimeDB storage: ' + mode)
|
||||
return
|
||||
command = args.command[1:] if args.command[:1] == ['--'] else args.command
|
||||
planned = commands(command, mode)
|
||||
failed = 0
|
||||
for cmd in planned:
|
||||
result = subprocess.run(cmd)
|
||||
failed = failed or result.returncode
|
||||
# Cleanup must try both arms even if one failed. Target failures remain
|
||||
# visible, while the other arm can still produce diagnostic evidence.
|
||||
raise SystemExit(failed)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -26,7 +26,7 @@ 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 } = {}) {
|
||||
failFirst = false, enqueueError = Error('head changed') } = {}) {
|
||||
const calls = [];
|
||||
let page = 0;
|
||||
const github = {
|
||||
@@ -43,7 +43,7 @@ async function run({ sync = false, body = checked, labels = ['merge nightly'],
|
||||
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');
|
||||
if (failFirst && calls.filter(call => call[0] === 'enqueue').length === 1) throw enqueueError;
|
||||
return {};
|
||||
}
|
||||
if (query.includes('reviewThreads')) {
|
||||
@@ -123,3 +123,31 @@ test('label-only opt-in survives PRs without a template and does not require a c
|
||||
// The label is authoritative for admission, even before checkbox synchronization.
|
||||
assert.equal((await run({ body: checked.replace('[x]', '[ ]') })).some(call => call[0] === 'enqueue'), true);
|
||||
});
|
||||
|
||||
const stackMessage = 'This pull request is part of a stack and must be enqueued using the asynchronous merge REST API. For more information, see https://docs.github.com/rest/pulls/pulls#merge-a-pull-request-asynchronously';
|
||||
|
||||
test('stacked PR rejection is skipped without consuming the successful enqueue cap', async () => {
|
||||
const calls = await run({ count: 7, failFirst: true,
|
||||
enqueueError: Object.assign(Error('GraphQL request failed'), { errors: [{ message: stackMessage }] }) });
|
||||
assert.equal(calls.some(c => c[0] === 'failed'), false);
|
||||
assert.deepEqual(calls.find(c => c[0] === 'summary')[1], [
|
||||
['PR', 'Result'], ['1', 'Skipped: stacked PR'],
|
||||
...[2, 3, 4, 5, 6].map(number => [String(number), 'Enqueued'])
|
||||
]);
|
||||
assert.deepEqual(calls.filter(c => c[0] === 'enqueue').map(c => c[1].id),
|
||||
['PR_1', 'PR_2', 'PR_3', 'PR_4', 'PR_5', 'PR_6']);
|
||||
});
|
||||
|
||||
test('mixed or unstructured errors are not mistaken for a stacked PR rejection', async () => {
|
||||
for (const enqueueError of [
|
||||
Error(stackMessage),
|
||||
Object.assign(Error('GraphQL request failed'), { errors: [] }),
|
||||
Object.assign(Error('GraphQL request failed'), { errors: [{ message: stackMessage }, { message: 'Forbidden' }] })
|
||||
]) {
|
||||
const calls = await run({ count: 2, failFirst: true, enqueueError });
|
||||
assert.equal(calls.filter(c => c[0] === 'failed').length, 1);
|
||||
assert.deepEqual(calls.find(c => c[0] === 'summary')[1], [
|
||||
['PR', 'Result'], ['1', 'Failed: see workflow logs'], ['2', 'Enqueued']
|
||||
]);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -28,6 +28,25 @@ SPEC.loader.exec_module(bench)
|
||||
|
||||
|
||||
class PhaseTests(unittest.TestCase):
|
||||
def test_cloud_region_configuration(self):
|
||||
for bucket, runner, accepted in (("us-east-1", "us-east-1", True),
|
||||
("ap-southeast-1", "ap-southeast-1", True),
|
||||
("us-east-1", "ap-southeast-1", False),
|
||||
("", "", False)):
|
||||
with self.subTest(bucket=bucket, runner=runner), tempfile.TemporaryDirectory() as directory:
|
||||
env = dict(GREPTIMEDB_IMAGE="greptime/greptimedb@sha256:" + "a" * 64,
|
||||
EXPECTED_COMMIT="b" * 40, RUN_PREFIX="metric-snapshot-bench/123-1/",
|
||||
RESULTS=str(Path(directory) / "results"), DATA_ROOT=str(Path(directory) / "data"),
|
||||
S3_REGION=bucket, RUNNER_REGION=runner, S3_ENDPOINT="")
|
||||
with patch.dict(bench.os.environ, env):
|
||||
if accepted:
|
||||
benchmark = bench.Benchmark(local_smoke=False)
|
||||
benchmark.summary()
|
||||
self.assertIn(f"S3 in {bucket};", (benchmark.results / "summary.md").read_text())
|
||||
else:
|
||||
with self.assertRaisesRegex(ValueError, "same nonempty"):
|
||||
bench.Benchmark(local_smoke=False)
|
||||
|
||||
def test_docker_nanosecond_timestamps(self):
|
||||
start = bench.docker_timestamp("2026-10-14T06:06:44.72000818Z")
|
||||
end = bench.docker_timestamp("2026-10-14T06:06:46.123456789Z")
|
||||
|
||||
@@ -20,6 +20,7 @@ import io
|
||||
import json
|
||||
from pathlib import Path
|
||||
import tempfile
|
||||
import types
|
||||
import unittest
|
||||
from unittest import mock
|
||||
|
||||
@@ -82,6 +83,45 @@ class OperationsTest(unittest.TestCase):
|
||||
with self.subTest(changes=changes), self.assertRaises(ValueError):
|
||||
ops.plan(self.env(**changes))
|
||||
|
||||
def test_regions_follow_configuration_and_reject_mismatch_or_empty(self):
|
||||
for region in ("us-east-1", "ap-southeast-1"):
|
||||
with self.subTest(region=region):
|
||||
self.assertEqual(ops.plan(self.env(S3_REGION=region, RUNNER_REGION=region))["region"], region)
|
||||
for bucket, runner in (("us-east-1", "ap-southeast-1"), ("", ""), (" ", " ")):
|
||||
with self.subTest(bucket=bucket, runner=runner), self.assertRaises(ValueError):
|
||||
ops.plan(self.env(S3_REGION=bucket, RUNNER_REGION=runner))
|
||||
|
||||
def test_client_uses_configured_region(self):
|
||||
boto = types.ModuleType("boto3")
|
||||
boto.client = mock.Mock()
|
||||
config = types.ModuleType("botocore.config")
|
||||
config.Config = mock.Mock()
|
||||
with mock.patch.dict("sys.modules", {"boto3": boto, "botocore.config": config}):
|
||||
for region in ("us-east-1", "ap-southeast-1"):
|
||||
ops.client(region)
|
||||
self.assertEqual(boto.client.call_args.kwargs["region_name"], region)
|
||||
with self.assertRaises(ValueError):
|
||||
ops.client("")
|
||||
|
||||
def test_hourly_estimate_controls_reservation_and_cost(self):
|
||||
env = self.env(EC2_HOURLY_USD="2", BENCHMARK_TIMEOUT_MINUTES="30")
|
||||
plan = ops.plan(env)
|
||||
self.assertEqual(plan["ec2_hourly_usd"], "2")
|
||||
self.assertEqual(plan["attempt_reserve_usd"], "5.00")
|
||||
with mock.patch.dict(ops.os.environ, env), mock.patch.object(ops.time, "time", return_value=4600), \
|
||||
mock.patch("sys.argv", ["ops", "cost", "--started-at", "1000"]), \
|
||||
mock.patch("sys.stdout", new_callable=io.StringIO) as output:
|
||||
ops.main()
|
||||
cost = json.loads(output.getvalue())
|
||||
self.assertEqual(cost["ec2_hourly_usd"], "2")
|
||||
self.assertEqual(cost["ec2_estimate_usd"], "2.0000")
|
||||
self.assertEqual(cost["campaign_estimate_with_other_reserve_usd"], "3.5000")
|
||||
for rate in ("", "invalid", "0", "-1", "NaN", "Infinity", "-Infinity"):
|
||||
with self.subTest(rate=rate), self.assertRaises(ValueError):
|
||||
ops.plan(self.env(EC2_HOURLY_USD=rate))
|
||||
with self.assertRaises(ValueError):
|
||||
ops.plan(self.env(EC2_HOURLY_USD="4"))
|
||||
|
||||
def watcher_env(self):
|
||||
return self.env(GITHUB_REPOSITORY="GreptimeTeam/greptimedb", GITHUB_RUN_ID="123",
|
||||
GITHUB_RUN_ATTEMPT="2", GH_TOKEN="test-token", BENCHMARK_TIMEOUT_MINUTES="30")
|
||||
|
||||
@@ -2,6 +2,11 @@ name: Agent Observability Benchmark
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
greptimedb_storage:
|
||||
description: 'GreptimeDB data storage (S3 requires AWS in the bucket region; WAL stays local)'
|
||||
type: choice
|
||||
options: [file, s3, both]
|
||||
default: file
|
||||
run_greptimedb:
|
||||
description: Run GreptimeDB
|
||||
type: boolean
|
||||
@@ -56,7 +61,7 @@ on:
|
||||
type: string
|
||||
required: false
|
||||
runtime_image:
|
||||
description: 'Runtime image: auto = AWS ECR Public or Aliyun ACR by provider; explicit tag/digest overrides'
|
||||
description: 'Runtime image: auto = pinned S3 test runtime on ACR; explicit tag/digest overrides'
|
||||
type: string
|
||||
default: auto
|
||||
required: true
|
||||
@@ -99,6 +104,11 @@ on:
|
||||
permissions:
|
||||
contents: read
|
||||
env:
|
||||
GREPTIMEDB_STORAGE: ${{ inputs.greptimedb_storage || 'file' }}
|
||||
S3_BUCKET: ${{ vars.AWS_CI_TEST_BUCKET }}
|
||||
S3_REGION: ${{ vars.AWS_CI_TEST_BUCKET_REGION }}
|
||||
RUNNER_REGION: ${{ vars.EC2_RUNNER_REGION }}
|
||||
RUN_GREPTIMEDB: ${{ inputs.run_greptimedb }}
|
||||
COMPARE_GREPTIMEDB: ${{ inputs.compare_greptimedb }}
|
||||
BASELINE_GREPTIMEDB_TAG: ${{ inputs.baseline_greptimedb_tag }}
|
||||
PROFILE: ${{ inputs.dataset }}
|
||||
@@ -106,7 +116,7 @@ env:
|
||||
CLICKHOUSE_TAG: ${{ inputs.clickhouse_tag }}
|
||||
VICTORIALOGS_TAG: ${{ inputs.victorialogs_tag }}
|
||||
O11YBENCH_REF: ${{ inputs.o11ybench_ref }}
|
||||
RUNTIME_IMAGE: ${{ inputs.runtime_image != 'auto' && inputs.runtime_image || inputs.provider == 'AWS' && 'public.ecr.aws/i8k6a5e1/greptime/o11ybenchruntime:2f40fb3fdbdc@sha256:8940782216bf5d066308fd71f6e346d950073c41cfb5756c5f3dc8aacf069cbc' || 'greptime-registry.cn-hangzhou.cr.aliyuncs.com/tools/o11ybench-runtime:2f40fb3fdbdc@sha256:8940782216bf5d066308fd71f6e346d950073c41cfb5756c5f3dc8aacf069cbc' }}
|
||||
RUNTIME_IMAGE: ${{ inputs.runtime_image != 'auto' && inputs.runtime_image || 'greptime-registry.cn-hangzhou.cr.aliyuncs.com/tools/o11ybench-runtime:s3-test-b0cf5204d2fc@sha256:c2bf622db6056a2029842f4dc1cc1f37b82773bd45b134a0a83ffe2a8cd62214' }}
|
||||
PROVIDER: ${{ inputs.provider }}
|
||||
REQUESTED_INSTANCE_TYPE: ${{ inputs.instance_type }}
|
||||
SYSTEM_DISK_GIB: ${{ inputs.system_disk_gib }}
|
||||
@@ -130,6 +140,10 @@ jobs:
|
||||
with:
|
||||
path: greptimedb
|
||||
persist-credentials: false
|
||||
- name: Validate GreptimeDB storage
|
||||
run: |
|
||||
python3 greptimedb/tests/perf/test_o11ybench_storage.py
|
||||
python3 greptimedb/.github/scripts/o11ybench-storage.py validate
|
||||
- name: Validate version comparison
|
||||
env:
|
||||
RUN_GREPTIMEDB: ${{ inputs.run_greptimedb }}
|
||||
@@ -287,7 +301,10 @@ jobs:
|
||||
path: greptimedb
|
||||
persist-credentials: false
|
||||
- name: Set up benchmark dependencies
|
||||
uses: ./greptimedb/.github/actions/setup-benchmark
|
||||
uses: ./greptimedb/.github/actions/setup-linux-runner
|
||||
with:
|
||||
tools: curl jq python3 rsync
|
||||
expected-architecture: x86_64
|
||||
- name: Check Docker on ephemeral Linux host
|
||||
shell: bash
|
||||
run: |
|
||||
@@ -367,24 +384,48 @@ jobs:
|
||||
--owner "$OWNER" --runtime-image "$RESOLVED_RUNTIME_IMAGE" \
|
||||
--root "$ARTIFACT_ROOT" --profile "$PROFILE" --db-cpus "$DB_CPUS" --db-memory "$DB_MEMORY"
|
||||
cp "$MANIFEST_PATH" "$ARTIFACT_ROOT/run-manifest.json"
|
||||
- name: Load and benchmark baseline GreptimeDB
|
||||
id: baseline_greptimedb
|
||||
if: ${{ !cancelled() && steps.generate.outcome == 'success' && needs.validate.outputs.greptimedb == 'true' && inputs.compare_greptimedb }}
|
||||
- name: Load and benchmark baseline GreptimeDB (File)
|
||||
id: baseline_greptimedb_file
|
||||
if: ${{ !cancelled() && steps.generate.outcome == 'success' && needs.validate.outputs.greptimedb == 'true' && inputs.greptimedb_storage != 's3' && inputs.compare_greptimedb }}
|
||||
run: |-
|
||||
GITHUB_STEP_SUMMARY= bash o11ybench/scripts/run-agent-observability.sh --stage target --execute \
|
||||
GITHUB_STEP_SUMMARY= bash o11ybench/scripts/run-agent-observability.sh --stage target --greptimedb-storage file --execute \
|
||||
--owner "$OWNER-base" --runtime-image "$RESOLVED_RUNTIME_IMAGE" --root "$ARTIFACT_ROOT/baseline" --data-root "$ARTIFACT_ROOT" \
|
||||
--profile "$PROFILE" --db-cpus "$DB_CPUS" --db-memory "$DB_MEMORY" \
|
||||
--target greptimedb --image "$BASELINE_GREPTIMEDB_IMAGE" \
|
||||
--greptimedb-http-port "$GREPTIMEDB_HTTP_PORT" --greptimedb-grpc-port "$GREPTIMEDB_GRPC_PORT"
|
||||
- name: Load and benchmark greptimedb
|
||||
id: greptimedb
|
||||
if: ${{ !cancelled() && steps.generate.outcome == 'success' && needs.validate.outputs.greptimedb == 'true' }}
|
||||
- name: Load and benchmark baseline GreptimeDB (S3)
|
||||
env:
|
||||
AWS_ACCESS_KEY_ID: ${{ inputs.greptimedb_storage != 'file' && secrets.AWS_ACCESS_KEY_ID || '' }}
|
||||
AWS_SECRET_ACCESS_KEY: ${{ inputs.greptimedb_storage != 'file' && secrets.AWS_SECRET_ACCESS_KEY || '' }}
|
||||
id: baseline_greptimedb_s3
|
||||
if: ${{ !cancelled() && steps.generate.outcome == 'success' && needs.validate.outputs.greptimedb == 'true' && inputs.greptimedb_storage != 'file' && inputs.compare_greptimedb }}
|
||||
run: |-
|
||||
GITHUB_STEP_SUMMARY= bash o11ybench/scripts/run-agent-observability.sh --stage target --execute \
|
||||
GITHUB_STEP_SUMMARY= bash o11ybench/scripts/run-agent-observability.sh --stage target --greptimedb-storage s3 --execute \
|
||||
--owner "$OWNER-base-s3" --runtime-image "$RESOLVED_RUNTIME_IMAGE" --root "$ARTIFACT_ROOT/baseline/s3" --data-root "$ARTIFACT_ROOT" \
|
||||
--profile "$PROFILE" --db-cpus "$DB_CPUS" --db-memory "$DB_MEMORY" \
|
||||
--target greptimedb --image "$BASELINE_GREPTIMEDB_IMAGE" \
|
||||
--greptimedb-http-port "$GREPTIMEDB_HTTP_PORT" --greptimedb-grpc-port "$GREPTIMEDB_GRPC_PORT"
|
||||
- name: Load and benchmark greptimedb (File)
|
||||
id: greptimedb_file
|
||||
if: ${{ !cancelled() && steps.generate.outcome == 'success' && needs.validate.outputs.greptimedb == 'true' && inputs.greptimedb_storage != 's3' }}
|
||||
run: |-
|
||||
GITHUB_STEP_SUMMARY= bash o11ybench/scripts/run-agent-observability.sh --stage target --greptimedb-storage file --execute \
|
||||
--owner "$OWNER" --runtime-image "$RESOLVED_RUNTIME_IMAGE" --root "$ARTIFACT_ROOT" \
|
||||
--profile "$PROFILE" --db-cpus "$DB_CPUS" --db-memory "$DB_MEMORY" \
|
||||
--target greptimedb --image "$GREPTIMEDB_IMAGE" \
|
||||
--greptimedb-http-port "$GREPTIMEDB_HTTP_PORT" --greptimedb-grpc-port "$GREPTIMEDB_GRPC_PORT"
|
||||
- name: Load and benchmark greptimedb (S3)
|
||||
env:
|
||||
AWS_ACCESS_KEY_ID: ${{ inputs.greptimedb_storage != 'file' && secrets.AWS_ACCESS_KEY_ID || '' }}
|
||||
AWS_SECRET_ACCESS_KEY: ${{ inputs.greptimedb_storage != 'file' && secrets.AWS_SECRET_ACCESS_KEY || '' }}
|
||||
id: greptimedb_s3
|
||||
if: ${{ !cancelled() && steps.generate.outcome == 'success' && needs.validate.outputs.greptimedb == 'true' && inputs.greptimedb_storage != 'file' }}
|
||||
run: |-
|
||||
GITHUB_STEP_SUMMARY= bash o11ybench/scripts/run-agent-observability.sh --stage target --greptimedb-storage s3 --execute \
|
||||
--owner "$OWNER-s3" --runtime-image "$RESOLVED_RUNTIME_IMAGE" --root "$ARTIFACT_ROOT/s3" --data-root "$ARTIFACT_ROOT" \
|
||||
--profile "$PROFILE" --db-cpus "$DB_CPUS" --db-memory "$DB_MEMORY" \
|
||||
--target greptimedb --image "$GREPTIMEDB_IMAGE" \
|
||||
--greptimedb-http-port "$GREPTIMEDB_HTTP_PORT" --greptimedb-grpc-port "$GREPTIMEDB_GRPC_PORT"
|
||||
- name: Load and benchmark clickhouse
|
||||
id: clickhouse
|
||||
if: ${{ !cancelled() && steps.generate.outcome == 'success' && needs.validate.outputs.clickhouse == 'true' }}
|
||||
@@ -404,7 +445,7 @@ jobs:
|
||||
--target victorialogs --image "$VICTORIALOGS_IMAGE" \
|
||||
--victorialogs-http-port "$VICTORIALOGS_HTTP_PORT"
|
||||
- name: Compare all three targets
|
||||
if: ${{ !cancelled() && steps.greptimedb.outcome == 'success' && steps.clickhouse.outcome == 'success' && steps.victorialogs.outcome
|
||||
if: ${{ !cancelled() && steps.greptimedb_file.outcome == 'success' && steps.clickhouse.outcome == 'success' && steps.victorialogs.outcome
|
||||
== 'success' }}
|
||||
run: |-
|
||||
docker run --rm --user "$(id -u):$(id -g)" --label "o11ybench.owner=$OWNER" \
|
||||
@@ -415,45 +456,61 @@ jobs:
|
||||
--victorialogs-summary /results/victorialogs-1/victorialogs-1/measured-summary.json \
|
||||
--output /results/comparison.json
|
||||
- name: Clean up owned containers
|
||||
env:
|
||||
AWS_ACCESS_KEY_ID: ${{ inputs.greptimedb_storage != 'file' && secrets.AWS_ACCESS_KEY_ID || '' }}
|
||||
AWS_SECRET_ACCESS_KEY: ${{ inputs.greptimedb_storage != 'file' && secrets.AWS_SECRET_ACCESS_KEY || '' }}
|
||||
if: always()
|
||||
run: |-
|
||||
if [[ -f o11ybench/scripts/run-agent-observability.sh ]]; then
|
||||
GITHUB_STEP_SUMMARY= bash o11ybench/scripts/run-agent-observability.sh --stage cleanup --execute \
|
||||
GITHUB_STEP_SUMMARY= python3 greptimedb/.github/scripts/o11ybench-storage.py run -- bash o11ybench/scripts/run-agent-observability.sh --stage cleanup --execute --runtime-image "$RESOLVED_RUNTIME_IMAGE" \
|
||||
--owner "$OWNER" --root "$ARTIFACT_ROOT"
|
||||
fi
|
||||
- name: Clean up baseline containers
|
||||
env:
|
||||
AWS_ACCESS_KEY_ID: ${{ inputs.greptimedb_storage != 'file' && secrets.AWS_ACCESS_KEY_ID || '' }}
|
||||
AWS_SECRET_ACCESS_KEY: ${{ inputs.greptimedb_storage != 'file' && secrets.AWS_SECRET_ACCESS_KEY || '' }}
|
||||
if: always() && inputs.compare_greptimedb
|
||||
run: |-
|
||||
if [[ -f o11ybench/scripts/run-agent-observability.sh ]]; then
|
||||
GITHUB_STEP_SUMMARY= bash o11ybench/scripts/run-agent-observability.sh --stage cleanup --execute \
|
||||
GITHUB_STEP_SUMMARY= python3 greptimedb/.github/scripts/o11ybench-storage.py run -- bash o11ybench/scripts/run-agent-observability.sh --stage cleanup --execute --runtime-image "$RESOLVED_RUNTIME_IMAGE" \
|
||||
--owner "$OWNER-base" --root "$ARTIFACT_ROOT/baseline"
|
||||
fi
|
||||
- name: Benchmark summary
|
||||
if: always()
|
||||
run: |
|
||||
python3 greptimedb/.github/scripts/agent-observability-summary.py \
|
||||
--root "$ARTIFACT_ROOT" --targets "$TARGETS" --section benchmark >> "$GITHUB_STEP_SUMMARY"
|
||||
python3 greptimedb/.github/scripts/o11ybench-storage.py summary --kind agent \
|
||||
--root "$ARTIFACT_ROOT" --targets "$TARGETS" --section benchmark | tee -a "$ARTIFACT_ROOT/ci-summary.md" >> "$GITHUB_STEP_SUMMARY"
|
||||
- name: Load / lifecycle summary
|
||||
if: always()
|
||||
run: |
|
||||
python3 greptimedb/.github/scripts/agent-observability-summary.py \
|
||||
--root "$ARTIFACT_ROOT" --targets "$TARGETS" --section lifecycle >> "$GITHUB_STEP_SUMMARY"
|
||||
python3 greptimedb/.github/scripts/o11ybench-storage.py summary --kind agent \
|
||||
--root "$ARTIFACT_ROOT" --targets "$TARGETS" --section lifecycle | tee -a "$ARTIFACT_ROOT/ci-summary.md" >> "$GITHUB_STEP_SUMMARY"
|
||||
- name: Baseline load / lifecycle summary
|
||||
if: always() && inputs.compare_greptimedb
|
||||
run: |
|
||||
echo '## Baseline GreptimeDB' >> "$GITHUB_STEP_SUMMARY"
|
||||
python3 greptimedb/.github/scripts/agent-observability-summary.py \
|
||||
--root "$ARTIFACT_ROOT/baseline" --targets greptimedb --section lifecycle >> "$GITHUB_STEP_SUMMARY"
|
||||
echo '## Baseline GreptimeDB' | tee -a "$ARTIFACT_ROOT/ci-summary.md" >> "$GITHUB_STEP_SUMMARY"
|
||||
python3 greptimedb/.github/scripts/o11ybench-storage.py summary --kind agent \
|
||||
--root "$ARTIFACT_ROOT/baseline" --targets greptimedb --section lifecycle | tee -a "$ARTIFACT_ROOT/ci-summary.md" >> "$GITHUB_STEP_SUMMARY"
|
||||
- name: GreptimeDB version comparison
|
||||
if: always() && inputs.compare_greptimedb
|
||||
run: |
|
||||
python3 greptimedb/.github/scripts/benchmark-version-comparison.py report --kind agent --root "$ARTIFACT_ROOT" >> "$GITHUB_STEP_SUMMARY"
|
||||
python3 greptimedb/.github/scripts/benchmark-version-comparison.py report --kind agent --root "$ARTIFACT_ROOT" | tee -a "$ARTIFACT_ROOT/ci-summary.md" >> "$GITHUB_STEP_SUMMARY"
|
||||
- name: Render storage comparison overview
|
||||
if: always() && steps.generate.outcome == 'success'
|
||||
run: |
|
||||
python3 o11ybench/scripts/build_query_performance_report.py --agent "$ARTIFACT_ROOT" \
|
||||
--output "$ARTIFACT_ROOT-query-report.html" --json-output "$ARTIFACT_ROOT-query-report.json"
|
||||
python3 greptimedb/.github/scripts/o11ybench-storage.py overview "$ARTIFACT_ROOT-query-report.json" \
|
||||
| tee -a "$ARTIFACT_ROOT/ci-summary.md" >> "$GITHUB_STEP_SUMMARY"
|
||||
python3 greptimedb/.github/scripts/o11ybench-storage.py audit --root "$ARTIFACT_ROOT" \
|
||||
--report "$ARTIFACT_ROOT-query-report.json" --targets "$TARGETS"
|
||||
- name: Upload results (no dataset)
|
||||
if: always()
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: agent-observability-${{ github.run_id }}-${{ github.run_attempt }}
|
||||
path: |-
|
||||
${{ env.ARTIFACT_ROOT }}-query-report.*
|
||||
${{ env.MANIFEST_PATH }}
|
||||
${{ env.ARTIFACT_ROOT }}
|
||||
!${{ env.ARTIFACT_ROOT }}/corpus/agent_observations.jsonl
|
||||
|
||||
@@ -4,6 +4,11 @@ name: GreptimeDB Development Build
|
||||
on:
|
||||
workflow_dispatch: # Allows you to run this workflow manually.
|
||||
inputs:
|
||||
ec2_volume_size:
|
||||
description: Root volume size in GiB for each EC2 build runner
|
||||
type: number
|
||||
required: false
|
||||
default: 500
|
||||
large-page-size:
|
||||
description: Build GreptimeDB with large page size (65536).
|
||||
type: boolean
|
||||
@@ -133,6 +138,7 @@ jobs:
|
||||
aws-region: ${{ vars.EC2_RUNNER_REGION }}
|
||||
github-token: ${{ secrets.GH_PERSONAL_ACCESS_TOKEN }}
|
||||
image-id: ${{ vars.EC2_RUNNER_LINUX_AMD64_IMAGE_ID }}
|
||||
ec2-volume-size: ${{ inputs.ec2_volume_size || 500 }}
|
||||
security-group-id: ${{ vars.EC2_RUNNER_SECURITY_GROUP_ID }}
|
||||
subnet-id: ${{ vars.EC2_RUNNER_SUBNET_ID }}
|
||||
|
||||
@@ -147,6 +153,7 @@ jobs:
|
||||
aws-region: ${{ vars.EC2_RUNNER_REGION }}
|
||||
github-token: ${{ secrets.GH_PERSONAL_ACCESS_TOKEN }}
|
||||
image-id: ${{ vars.EC2_RUNNER_LINUX_ARM64_IMAGE_ID }}
|
||||
ec2-volume-size: ${{ inputs.ec2_volume_size || 500 }}
|
||||
security-group-id: ${{ vars.EC2_RUNNER_SECURITY_GROUP_ID }}
|
||||
subnet-id: ${{ vars.EC2_RUNNER_SUBNET_ID }}
|
||||
|
||||
@@ -185,8 +192,8 @@ jobs:
|
||||
large-page-size: ${{ inputs.large-page-size }}
|
||||
aws-ci-test-bucket: ${{ vars.AWS_CI_TEST_BUCKET }}
|
||||
aws-region: ${{ vars.AWS_CI_TEST_BUCKET_REGION }}
|
||||
aws-access-key-id: ${{ secrets.AWS_CI_TEST_ACCESS_KEY_ID }}
|
||||
aws-secret-access-key: ${{ secrets.AWS_CI_TEST_SECRET_ACCESS_KEY }}
|
||||
aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }}
|
||||
aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
|
||||
|
||||
build-linux-arm64-artifacts:
|
||||
name: Build linux-arm64 artifacts
|
||||
@@ -223,8 +230,8 @@ jobs:
|
||||
large-page-size: ${{ inputs.large-page-size }}
|
||||
aws-ci-test-bucket: ${{ vars.AWS_CI_TEST_BUCKET }}
|
||||
aws-region: ${{ vars.AWS_CI_TEST_BUCKET_REGION }}
|
||||
aws-access-key-id: ${{ secrets.AWS_CI_TEST_ACCESS_KEY_ID }}
|
||||
aws-secret-access-key: ${{ secrets.AWS_CI_TEST_SECRET_ACCESS_KEY }}
|
||||
aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }}
|
||||
aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
|
||||
|
||||
release-images-to-dockerhub:
|
||||
name: Build and push images to DockerHub
|
||||
|
||||
@@ -18,6 +18,11 @@ on:
|
||||
description: 'Setup, 500-table smoke and full run timeout, 30..240 minutes'
|
||||
type: number
|
||||
default: 240
|
||||
ec2_hourly_usd:
|
||||
description: 'Positive EC2 hourly USD budget estimate; historical default, not live regional pricing'
|
||||
required: true
|
||||
type: string
|
||||
default: '0.9408'
|
||||
prior_spend_usd:
|
||||
description: 'Cumulative estimated cloud spend for all earlier attempts in this $20 campaign'
|
||||
required: true
|
||||
@@ -34,6 +39,7 @@ env:
|
||||
LOGICAL_TABLES_PER_GROUP: ${{ inputs.logical_tables_per_group }}
|
||||
BENCHMARK_TIMEOUT_MINUTES: ${{ inputs.benchmark_timeout_minutes }}
|
||||
PRIOR_SPEND_USD: ${{ inputs.prior_spend_usd }}
|
||||
EC2_HOURLY_USD: ${{ inputs.ec2_hourly_usd }}
|
||||
RUN_PREFIX: metric-snapshot-bench/${{ github.run_id }}-${{ github.run_attempt }}/
|
||||
S3_BUCKET: ${{ vars.AWS_CI_TEST_BUCKET }}
|
||||
S3_REGION: ${{ vars.AWS_CI_TEST_BUCKET_REGION }}
|
||||
@@ -66,8 +72,8 @@ jobs:
|
||||
- uses: astral-sh/setup-uv@v6
|
||||
- name: Check S3 access before allocating EC2
|
||||
env:
|
||||
AWS_ACCESS_KEY_ID: ${{ secrets.AWS_CI_TEST_ACCESS_KEY_ID }}
|
||||
AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_CI_TEST_SECRET_ACCESS_KEY }}
|
||||
AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }}
|
||||
AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
|
||||
run: uv run greptimedb/.github/scripts/metric-snapshot-s3-ops.py probe
|
||||
- name: Resolve the fixed benchmark runner
|
||||
id: runner
|
||||
@@ -125,7 +131,10 @@ jobs:
|
||||
path: greptimedb
|
||||
persist-credentials: false
|
||||
- name: Set up benchmark dependencies
|
||||
uses: ./greptimedb/.github/actions/setup-benchmark
|
||||
uses: ./greptimedb/.github/actions/setup-linux-runner
|
||||
with:
|
||||
tools: curl jq python3 rsync
|
||||
expected-architecture: x86_64
|
||||
- uses: astral-sh/setup-uv@v6
|
||||
- name: Mount the temporary local File data disk
|
||||
run: |
|
||||
@@ -148,20 +157,20 @@ jobs:
|
||||
findmnt -no SOURCE,FSTYPE -T "$DISK_ROOT"
|
||||
- name: Probe the real same-region S3 bucket
|
||||
env:
|
||||
AWS_ACCESS_KEY_ID: ${{ secrets.AWS_CI_TEST_ACCESS_KEY_ID }}
|
||||
AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_CI_TEST_SECRET_ACCESS_KEY }}
|
||||
AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }}
|
||||
AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
|
||||
run: uv run greptimedb/.github/scripts/metric-snapshot-s3-ops.py probe
|
||||
- name: Run the 500-table smoke, then one full packed export and restore
|
||||
env:
|
||||
AWS_ACCESS_KEY_ID: ${{ secrets.AWS_CI_TEST_ACCESS_KEY_ID }}
|
||||
AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_CI_TEST_SECRET_ACCESS_KEY }}
|
||||
AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }}
|
||||
AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
|
||||
run: python3 greptimedb/.github/scripts/metric-snapshot-s3-bench.py run
|
||||
- name: Check results for credentials
|
||||
id: scrub
|
||||
if: always()
|
||||
env:
|
||||
AWS_ACCESS_KEY_ID: ${{ secrets.AWS_CI_TEST_ACCESS_KEY_ID }}
|
||||
AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_CI_TEST_SECRET_ACCESS_KEY }}
|
||||
AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }}
|
||||
AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
|
||||
run: python3 greptimedb/.github/scripts/metric-snapshot-s3-ops.py scrub
|
||||
- name: Publish the readable result
|
||||
if: ${{ always() && steps.scrub.outcome == 'success' }}
|
||||
@@ -220,8 +229,8 @@ jobs:
|
||||
- name: Remove and verify only this run's S3 prefix
|
||||
if: always()
|
||||
env:
|
||||
AWS_ACCESS_KEY_ID: ${{ secrets.AWS_CI_TEST_ACCESS_KEY_ID }}
|
||||
AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_CI_TEST_SECRET_ACCESS_KEY }}
|
||||
AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }}
|
||||
AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
|
||||
run: uv run greptimedb/.github/scripts/metric-snapshot-s3-ops.py cleanup
|
||||
- name: Estimate the cumulative cloud cost
|
||||
if: ${{ always() && needs.provision.outputs.started_at != '' }}
|
||||
|
||||
@@ -9,6 +9,11 @@ on:
|
||||
- cron: '0 0 * * 1-5'
|
||||
workflow_dispatch: # Allows you to run this workflow manually.
|
||||
inputs:
|
||||
ec2_volume_size:
|
||||
description: Root volume size in GiB for each EC2 build runner
|
||||
type: number
|
||||
required: false
|
||||
default: 500
|
||||
linux_amd64_runner:
|
||||
type: choice
|
||||
description: The runner uses to build linux-amd64 artifacts
|
||||
@@ -113,6 +118,7 @@ jobs:
|
||||
aws-region: ${{ vars.EC2_RUNNER_REGION }}
|
||||
github-token: ${{ secrets.GH_PERSONAL_ACCESS_TOKEN }}
|
||||
image-id: ${{ vars.EC2_RUNNER_LINUX_AMD64_IMAGE_ID }}
|
||||
ec2-volume-size: ${{ inputs.ec2_volume_size || 500 }}
|
||||
security-group-id: ${{ vars.EC2_RUNNER_SECURITY_GROUP_ID }}
|
||||
subnet-id: ${{ vars.EC2_RUNNER_SUBNET_ID }}
|
||||
|
||||
@@ -127,6 +133,7 @@ jobs:
|
||||
aws-region: ${{ vars.EC2_RUNNER_REGION }}
|
||||
github-token: ${{ secrets.GH_PERSONAL_ACCESS_TOKEN }}
|
||||
image-id: ${{ vars.EC2_RUNNER_LINUX_ARM64_IMAGE_ID }}
|
||||
ec2-volume-size: ${{ inputs.ec2_volume_size || 500 }}
|
||||
security-group-id: ${{ vars.EC2_RUNNER_SECURITY_GROUP_ID }}
|
||||
subnet-id: ${{ vars.EC2_RUNNER_SUBNET_ID }}
|
||||
|
||||
@@ -153,8 +160,8 @@ jobs:
|
||||
image-namespace: ${{ vars.ECR_IMAGE_NAMESPACE }}
|
||||
aws-ci-test-bucket: ${{ vars.AWS_CI_TEST_BUCKET }}
|
||||
aws-region: ${{ vars.AWS_CI_TEST_BUCKET_REGION }}
|
||||
aws-access-key-id: ${{ secrets.AWS_CI_TEST_ACCESS_KEY_ID }}
|
||||
aws-secret-access-key: ${{ secrets.AWS_CI_TEST_SECRET_ACCESS_KEY }}
|
||||
aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }}
|
||||
aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
|
||||
|
||||
build-linux-arm64-artifacts:
|
||||
name: Build linux-arm64 artifacts
|
||||
@@ -179,8 +186,8 @@ jobs:
|
||||
image-namespace: ${{ vars.ECR_IMAGE_NAMESPACE }}
|
||||
aws-ci-test-bucket: ${{ vars.AWS_CI_TEST_BUCKET }}
|
||||
aws-region: ${{ vars.AWS_CI_TEST_BUCKET_REGION }}
|
||||
aws-access-key-id: ${{ secrets.AWS_CI_TEST_ACCESS_KEY_ID }}
|
||||
aws-secret-access-key: ${{ secrets.AWS_CI_TEST_SECRET_ACCESS_KEY }}
|
||||
aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }}
|
||||
aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
|
||||
|
||||
release-images-to-dockerhub:
|
||||
name: Build and push images to DockerHub
|
||||
|
||||
@@ -14,6 +14,7 @@ jobs:
|
||||
name: Run sqlness test
|
||||
if: ${{ github.repository == 'GreptimeTeam/greptimedb' }}
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 45
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
@@ -30,10 +31,10 @@ jobs:
|
||||
data-root: sqlness-test
|
||||
aws-ci-test-bucket: ${{ vars.AWS_CI_TEST_BUCKET }}
|
||||
aws-region: ${{ vars.AWS_CI_TEST_BUCKET_REGION }}
|
||||
aws-access-key-id: ${{ secrets.AWS_CI_TEST_ACCESS_KEY_ID }}
|
||||
aws-secret-access-key: ${{ secrets.AWS_CI_TEST_SECRET_ACCESS_KEY }}
|
||||
aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }}
|
||||
aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
|
||||
- name: Upload sqlness logs
|
||||
if: failure()
|
||||
if: failure() || cancelled()
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: sqlness-logs-kind
|
||||
@@ -113,8 +114,8 @@ jobs:
|
||||
RUST_MIN_STACK: 8388608 # 8MB
|
||||
CARGO_INCREMENTAL: 0
|
||||
GT_S3_BUCKET: ${{ vars.AWS_CI_TEST_BUCKET }}
|
||||
GT_S3_ACCESS_KEY_ID: ${{ secrets.AWS_CI_TEST_ACCESS_KEY_ID }}
|
||||
GT_S3_ACCESS_KEY: ${{ secrets.AWS_CI_TEST_SECRET_ACCESS_KEY }}
|
||||
GT_S3_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }}
|
||||
GT_S3_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
|
||||
GT_S3_REGION: ${{ vars.AWS_CI_TEST_BUCKET_REGION }}
|
||||
GT_ETCD_TLS_ENDPOINTS: https://127.0.0.1:2378
|
||||
GT_ETCD_ENDPOINTS: http://127.0.0.1:2379
|
||||
@@ -167,8 +168,8 @@ jobs:
|
||||
RUST_MIN_STACK: 8388608 # 8 MiB, aligned with Rust CI and release tests.
|
||||
CARGO_INCREMENTAL: 0
|
||||
GT_S3_BUCKET: ${{ vars.AWS_CI_TEST_BUCKET }}
|
||||
GT_S3_ACCESS_KEY_ID: ${{ secrets.AWS_CI_TEST_ACCESS_KEY_ID }}
|
||||
GT_S3_ACCESS_KEY: ${{ secrets.AWS_CI_TEST_SECRET_ACCESS_KEY }}
|
||||
GT_S3_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }}
|
||||
GT_S3_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
|
||||
GT_S3_REGION: ${{ vars.AWS_CI_TEST_BUCKET_REGION }}
|
||||
UNITTEST_LOG_DIR: "__unittest_logs"
|
||||
|
||||
|
||||
@@ -112,6 +112,8 @@ jobs:
|
||||
id: start-linux-runner
|
||||
with:
|
||||
runner: ${{ vars.LARGE_IOPS_RUNNER }}
|
||||
# Database data, WAL, and compaction files use the root volume.
|
||||
ec2-volume-size: "500"
|
||||
aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }}
|
||||
aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
|
||||
aws-region: ${{ vars.EC2_RUNNER_REGION }}
|
||||
|
||||
@@ -122,12 +122,23 @@ jobs:
|
||||
}
|
||||
if (!dryRun) {
|
||||
// GitHub enforces branch rules; never bypass or enable auto-merge.
|
||||
await github.graphql(`
|
||||
try {
|
||||
await github.graphql(`
|
||||
mutation($id: ID!, $sha: GitObjectID!) {
|
||||
enqueuePullRequest(input: {pullRequestId: $id, expectedHeadOid: $sha}) {
|
||||
mergeQueueEntry { id }
|
||||
}
|
||||
}`, { id: pr.id, sha: pr.headRefOid });
|
||||
} catch (error) {
|
||||
// Stacked PRs require a different API and are not handled by this workflow.
|
||||
const stackError = 'This pull request is part of a stack and must be enqueued using the asynchronous merge REST API.';
|
||||
if (error.errors?.length && error.errors.every(item => item.message?.startsWith(stackError))) {
|
||||
core.warning(`PR #${number}: skipped stacked PR`);
|
||||
rows.push([String(number), 'Skipped: stacked PR']);
|
||||
continue;
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
enqueued++;
|
||||
rows.push([String(number), dryRun ? 'Would enqueue' : 'Enqueued']);
|
||||
|
||||
@@ -205,7 +205,10 @@ jobs:
|
||||
path: greptimedb
|
||||
persist-credentials: false
|
||||
- name: Set up benchmark dependencies
|
||||
uses: ./greptimedb/.github/actions/setup-benchmark
|
||||
uses: ./greptimedb/.github/actions/setup-linux-runner
|
||||
with:
|
||||
tools: curl jq python3 rsync
|
||||
expected-architecture: x86_64
|
||||
- uses: astral-sh/setup-uv@v6
|
||||
- name: Start the MinIO fixture
|
||||
if: inputs.smoke
|
||||
@@ -235,8 +238,8 @@ jobs:
|
||||
--runtime-image "$RUNTIME_IMAGE" --instance-type "$INSTANCE_TYPE" --region "$S3_REGION" --prefix "$RUN_PREFIX"
|
||||
- name: Probe the bucket
|
||||
env:
|
||||
AWS_ACCESS_KEY_ID: ${{ inputs.smoke && 'superpower_ci_user' || secrets.AWS_CI_TEST_ACCESS_KEY_ID }}
|
||||
AWS_SECRET_ACCESS_KEY: ${{ inputs.smoke && 'superpower_password' || secrets.AWS_CI_TEST_SECRET_ACCESS_KEY }}
|
||||
AWS_ACCESS_KEY_ID: ${{ inputs.smoke && 'superpower_ci_user' || secrets.AWS_ACCESS_KEY_ID }}
|
||||
AWS_SECRET_ACCESS_KEY: ${{ inputs.smoke && 'superpower_password' || secrets.AWS_SECRET_ACCESS_KEY }}
|
||||
run: uv run greptimedb/.github/scripts/oswal-s3-bench.py probe --bucket "$S3_BUCKET" --region "$S3_REGION" --endpoint "$S3_ENDPOINT" --prefix "$RUN_PREFIX"
|
||||
- name: Put the Raft Engine WAL on the instance store
|
||||
run: bash greptimedb/.github/scripts/oswal-s3-bench-run.sh wal-disk "$WAL_ROOT"
|
||||
@@ -244,8 +247,8 @@ jobs:
|
||||
run: bash greptimedb/.github/scripts/oswal-s3-bench-run.sh generate
|
||||
- name: Load every cell
|
||||
env:
|
||||
AWS_ACCESS_KEY_ID: ${{ inputs.smoke && 'superpower_ci_user' || secrets.AWS_CI_TEST_ACCESS_KEY_ID }}
|
||||
AWS_SECRET_ACCESS_KEY: ${{ inputs.smoke && 'superpower_password' || secrets.AWS_CI_TEST_SECRET_ACCESS_KEY }}
|
||||
AWS_ACCESS_KEY_ID: ${{ inputs.smoke && 'superpower_ci_user' || secrets.AWS_ACCESS_KEY_ID }}
|
||||
AWS_SECRET_ACCESS_KEY: ${{ inputs.smoke && 'superpower_password' || secrets.AWS_SECRET_ACCESS_KEY }}
|
||||
run: bash greptimedb/.github/scripts/oswal-s3-bench-run.sh cells
|
||||
- name: Summary
|
||||
if: always()
|
||||
@@ -253,14 +256,14 @@ jobs:
|
||||
- name: Delete the run's S3 prefix
|
||||
if: always()
|
||||
env:
|
||||
AWS_ACCESS_KEY_ID: ${{ inputs.smoke && 'superpower_ci_user' || secrets.AWS_CI_TEST_ACCESS_KEY_ID }}
|
||||
AWS_SECRET_ACCESS_KEY: ${{ inputs.smoke && 'superpower_password' || secrets.AWS_CI_TEST_SECRET_ACCESS_KEY }}
|
||||
AWS_ACCESS_KEY_ID: ${{ inputs.smoke && 'superpower_ci_user' || secrets.AWS_ACCESS_KEY_ID }}
|
||||
AWS_SECRET_ACCESS_KEY: ${{ inputs.smoke && 'superpower_password' || secrets.AWS_SECRET_ACCESS_KEY }}
|
||||
run: uv run greptimedb/.github/scripts/oswal-s3-bench.py cleanup --bucket "$S3_BUCKET" --region "$S3_REGION" --endpoint "$S3_ENDPOINT" --prefix "$RUN_PREFIX"
|
||||
- name: Check the results hold no credentials
|
||||
if: always()
|
||||
env:
|
||||
AWS_ACCESS_KEY_ID: ${{ inputs.smoke && 'superpower_ci_user' || secrets.AWS_CI_TEST_ACCESS_KEY_ID }}
|
||||
AWS_SECRET_ACCESS_KEY: ${{ inputs.smoke && 'superpower_password' || secrets.AWS_CI_TEST_SECRET_ACCESS_KEY }}
|
||||
AWS_ACCESS_KEY_ID: ${{ inputs.smoke && 'superpower_ci_user' || secrets.AWS_ACCESS_KEY_ID }}
|
||||
AWS_SECRET_ACCESS_KEY: ${{ inputs.smoke && 'superpower_password' || secrets.AWS_SECRET_ACCESS_KEY }}
|
||||
run: bash greptimedb/.github/scripts/oswal-s3-bench-run.sh scrub
|
||||
- name: Upload results (no corpus)
|
||||
if: always()
|
||||
|
||||
@@ -20,6 +20,11 @@ on:
|
||||
- cron: '0 0 * * 1-5'
|
||||
workflow_dispatch: # Allows you to run this workflow manually.
|
||||
inputs:
|
||||
ec2_volume_size:
|
||||
description: Root volume size in GiB for each EC2 build runner
|
||||
type: number
|
||||
required: false
|
||||
default: 500
|
||||
linux_amd64_runner:
|
||||
type: choice
|
||||
description: The runner uses to build linux-amd64 artifacts
|
||||
@@ -215,6 +220,7 @@ jobs:
|
||||
aws-region: ${{ vars.EC2_RUNNER_REGION }}
|
||||
github-token: ${{ secrets.GH_PERSONAL_ACCESS_TOKEN }}
|
||||
image-id: ${{ vars.EC2_RUNNER_LINUX_AMD64_IMAGE_ID }}
|
||||
ec2-volume-size: ${{ inputs.ec2_volume_size || 500 }}
|
||||
security-group-id: ${{ vars.EC2_RUNNER_SECURITY_GROUP_ID }}
|
||||
subnet-id: ${{ vars.EC2_RUNNER_SUBNET_ID }}
|
||||
|
||||
@@ -229,6 +235,7 @@ jobs:
|
||||
aws-region: ${{ vars.EC2_RUNNER_REGION }}
|
||||
github-token: ${{ secrets.GH_PERSONAL_ACCESS_TOKEN }}
|
||||
image-id: ${{ vars.EC2_RUNNER_LINUX_ARM64_IMAGE_ID }}
|
||||
ec2-volume-size: ${{ inputs.ec2_volume_size || 500 }}
|
||||
security-group-id: ${{ vars.EC2_RUNNER_SECURITY_GROUP_ID }}
|
||||
subnet-id: ${{ vars.EC2_RUNNER_SUBNET_ID }}
|
||||
|
||||
@@ -255,8 +262,8 @@ jobs:
|
||||
image-namespace: ${{ vars.ECR_IMAGE_NAMESPACE }}
|
||||
aws-ci-test-bucket: ${{ vars.AWS_CI_TEST_BUCKET }}
|
||||
aws-region: ${{ vars.AWS_CI_TEST_BUCKET_REGION }}
|
||||
aws-access-key-id: ${{ secrets.AWS_CI_TEST_ACCESS_KEY_ID }}
|
||||
aws-secret-access-key: ${{ secrets.AWS_CI_TEST_SECRET_ACCESS_KEY }}
|
||||
aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }}
|
||||
aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
|
||||
|
||||
build-linux-arm64-artifacts:
|
||||
name: Build linux-arm64 artifacts
|
||||
@@ -282,8 +289,8 @@ jobs:
|
||||
large-page-size: true
|
||||
aws-ci-test-bucket: ${{ vars.AWS_CI_TEST_BUCKET }}
|
||||
aws-region: ${{ vars.AWS_CI_TEST_BUCKET_REGION }}
|
||||
aws-access-key-id: ${{ secrets.AWS_CI_TEST_ACCESS_KEY_ID }}
|
||||
aws-secret-access-key: ${{ secrets.AWS_CI_TEST_SECRET_ACCESS_KEY }}
|
||||
aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }}
|
||||
aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
|
||||
|
||||
build-linux-riscv64-artifacts:
|
||||
name: Build linux-riscv64 artifacts
|
||||
@@ -298,6 +305,11 @@ jobs:
|
||||
fetch-depth: 0
|
||||
persist-credentials: false
|
||||
|
||||
- name: Set up Linux runner
|
||||
uses: ./.github/actions/setup-linux-runner
|
||||
with:
|
||||
tools: make shasum
|
||||
|
||||
- name: Prepare riscv64 dev-builder image
|
||||
shell: bash
|
||||
env:
|
||||
|
||||
@@ -2,6 +2,11 @@ name: Tracesbench
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
greptimedb_storage:
|
||||
description: 'GreptimeDB data storage (S3 requires AWS in the bucket region; WAL stays local)'
|
||||
type: choice
|
||||
options: [file, s3, both]
|
||||
default: file
|
||||
run_greptimedb:
|
||||
description: Run GreptimeDB
|
||||
type: boolean
|
||||
@@ -39,7 +44,7 @@ on:
|
||||
default: sanity
|
||||
required: true
|
||||
runtime_image:
|
||||
description: 'Runtime image: auto = AWS ECR Public or Aliyun ACR by provider; explicit tag/digest overrides'
|
||||
description: 'Runtime image: auto = pinned S3 test runtime on ACR; explicit tag/digest overrides'
|
||||
type: string
|
||||
default: auto
|
||||
required: true
|
||||
@@ -107,6 +112,11 @@ on:
|
||||
permissions:
|
||||
contents: read
|
||||
env:
|
||||
GREPTIMEDB_STORAGE: ${{ inputs.greptimedb_storage || 'file' }}
|
||||
S3_BUCKET: ${{ vars.AWS_CI_TEST_BUCKET }}
|
||||
S3_REGION: ${{ vars.AWS_CI_TEST_BUCKET_REGION }}
|
||||
RUNNER_REGION: ${{ vars.EC2_RUNNER_REGION }}
|
||||
RUN_GREPTIMEDB: ${{ inputs.run_greptimedb }}
|
||||
COMPARE_GREPTIMEDB: ${{ inputs.compare_greptimedb }}
|
||||
BASELINE_GREPTIMEDB_TAG: ${{ inputs.baseline_greptimedb_tag }}
|
||||
DATASET: ${{ inputs.dataset }}
|
||||
@@ -114,7 +124,7 @@ env:
|
||||
RUNTIME_CPUS: ${{ inputs.runtime_cpus }}
|
||||
RUNTIME_MEMORY: ${{ inputs.runtime_memory }}
|
||||
BENCHMARK_ROOT: ${{ inputs.benchmark_root }}
|
||||
RUNTIME_IMAGE: ${{ inputs.runtime_image != 'auto' && inputs.runtime_image || inputs.provider == 'AWS' && 'public.ecr.aws/i8k6a5e1/greptime/o11ybenchruntime:77a84e1c8136@sha256:c482993ec177b026235d6cd0c61d4fb6d6f1088bc78bdc0e5964a5398de6dba0' || 'greptime-registry.cn-hangzhou.cr.aliyuncs.com/tools/o11ybench-runtime:77a84e1c8136@sha256:c482993ec177b026235d6cd0c61d4fb6d6f1088bc78bdc0e5964a5398de6dba0' }}
|
||||
RUNTIME_IMAGE: ${{ inputs.runtime_image != 'auto' && inputs.runtime_image || 'greptime-registry.cn-hangzhou.cr.aliyuncs.com/tools/o11ybench-runtime:s3-test-b0cf5204d2fc@sha256:c2bf622db6056a2029842f4dc1cc1f37b82773bd45b134a0a83ffe2a8cd62214' }}
|
||||
PROVIDER: ${{ inputs.provider }}
|
||||
REQUESTED_INSTANCE_TYPE: ${{ inputs.instance_type }}
|
||||
SYSTEM_DISK_GIB: ${{ inputs.system_disk_gib }}
|
||||
@@ -162,6 +172,10 @@ jobs:
|
||||
[[ "$GREPTIMEDB_TAG" =~ ^[a-zA-Z0-9_][a-zA-Z0-9_.-]{0,127}$ ]] || { echo 'Invalid GreptimeDB image tag' >&2; exit 1; }
|
||||
fi
|
||||
printf 'targets=%s\n' "$selected" >> "$GITHUB_OUTPUT"
|
||||
- name: Validate GreptimeDB storage
|
||||
run: |
|
||||
python3 greptimedb/tests/perf/test_o11ybench_storage.py
|
||||
python3 greptimedb/.github/scripts/o11ybench-storage.py validate
|
||||
- name: Validate version comparison
|
||||
env:
|
||||
RUN_GREPTIMEDB: ${{ inputs.run_greptimedb }}
|
||||
@@ -317,7 +331,10 @@ jobs:
|
||||
path: greptimedb
|
||||
persist-credentials: false
|
||||
- name: Set up benchmark dependencies
|
||||
uses: ./greptimedb/.github/actions/setup-benchmark
|
||||
uses: ./greptimedb/.github/actions/setup-linux-runner
|
||||
with:
|
||||
tools: curl jq python3 rsync
|
||||
expected-architecture: x86_64
|
||||
- name: Checkout matching benchmark tools
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
@@ -386,22 +403,44 @@ jobs:
|
||||
python3 o11ybench/scripts/run_tracesbench_docker.py --stage generate \
|
||||
--dataset "$DATASET" --runtime-cpus "$RUNTIME_CPUS" --runtime-memory "$RUNTIME_MEMORY" \
|
||||
--root "$RUN_ROOT" --owner "$OWNER" --runtime-image "$RESOLVED_RUNTIME_IMAGE"
|
||||
- name: Baseline GreptimeDB load, correctness and benchmark
|
||||
if: ${{ !cancelled() && steps.generate.outcome == 'success' && needs.validate.outputs.greptimedb == 'true' && inputs.compare_greptimedb }}
|
||||
- name: Baseline GreptimeDB load, correctness and benchmark (File)
|
||||
if: ${{ !cancelled() && steps.generate.outcome == 'success' && needs.validate.outputs.greptimedb == 'true' && inputs.greptimedb_storage != 's3' && inputs.compare_greptimedb }}
|
||||
run: |
|
||||
python3 o11ybench/scripts/run_tracesbench_docker.py --stage target --target greptimedb --port 14000 --greptimedb-image "$BASELINE_GREPTIMEDB_IMAGE" \
|
||||
python3 o11ybench/scripts/run_tracesbench_docker.py --stage target --greptimedb-storage file --target greptimedb --port 14000 --greptimedb-image "$BASELINE_GREPTIMEDB_IMAGE" \
|
||||
--db-cpus "$DB_CPUS" --db-memory "$DB_MEMORY" --query-timeout-seconds "$QUERY_TIMEOUT_SECONDS" --load-workers "$LOAD_WORKERS" \
|
||||
--dataset "$DATASET" --runtime-cpus "$RUNTIME_CPUS" --runtime-memory "$RUNTIME_MEMORY" \
|
||||
--root "$RUN_ROOT/baseline" --data-root "$RUN_ROOT" --owner "$OWNER-base" --runtime-image "$RESOLVED_RUNTIME_IMAGE"
|
||||
python3 o11ybench/scripts/check_tracesbench_query_plans.py "$RUN_ROOT/baseline/runs/greptimedb"
|
||||
- name: GreptimeDB load, correctness and benchmark
|
||||
if: ${{ !cancelled() && steps.generate.outcome == 'success' && needs.validate.outputs.greptimedb == 'true' }}
|
||||
- name: Baseline GreptimeDB load, correctness and benchmark (S3)
|
||||
env:
|
||||
AWS_ACCESS_KEY_ID: ${{ inputs.greptimedb_storage != 'file' && secrets.AWS_ACCESS_KEY_ID || '' }}
|
||||
AWS_SECRET_ACCESS_KEY: ${{ inputs.greptimedb_storage != 'file' && secrets.AWS_SECRET_ACCESS_KEY || '' }}
|
||||
if: ${{ !cancelled() && steps.generate.outcome == 'success' && needs.validate.outputs.greptimedb == 'true' && inputs.greptimedb_storage != 'file' && inputs.compare_greptimedb }}
|
||||
run: |
|
||||
python3 o11ybench/scripts/run_tracesbench_docker.py --stage target --target greptimedb --port 14000 --greptimedb-image "$GREPTIMEDB_IMAGE" \
|
||||
python3 o11ybench/scripts/run_tracesbench_docker.py --stage target --greptimedb-storage s3 --target greptimedb --port 14000 --greptimedb-image "$BASELINE_GREPTIMEDB_IMAGE" \
|
||||
--db-cpus "$DB_CPUS" --db-memory "$DB_MEMORY" --query-timeout-seconds "$QUERY_TIMEOUT_SECONDS" --load-workers "$LOAD_WORKERS" \
|
||||
--dataset "$DATASET" --runtime-cpus "$RUNTIME_CPUS" --runtime-memory "$RUNTIME_MEMORY" \
|
||||
--root "$RUN_ROOT/baseline/s3" --data-root "$RUN_ROOT" --owner "$OWNER-base-s3" --runtime-image "$RESOLVED_RUNTIME_IMAGE"
|
||||
python3 o11ybench/scripts/check_tracesbench_query_plans.py "$RUN_ROOT/baseline/s3/runs/greptimedb"
|
||||
- name: GreptimeDB load, correctness and benchmark (File)
|
||||
if: ${{ !cancelled() && steps.generate.outcome == 'success' && needs.validate.outputs.greptimedb == 'true' && inputs.greptimedb_storage != 's3' }}
|
||||
run: |
|
||||
python3 o11ybench/scripts/run_tracesbench_docker.py --stage target --greptimedb-storage file --target greptimedb --port 14000 --greptimedb-image "$GREPTIMEDB_IMAGE" \
|
||||
--db-cpus "$DB_CPUS" --db-memory "$DB_MEMORY" --query-timeout-seconds "$QUERY_TIMEOUT_SECONDS" --load-workers "$LOAD_WORKERS" \
|
||||
--dataset "$DATASET" --runtime-cpus "$RUNTIME_CPUS" --runtime-memory "$RUNTIME_MEMORY" \
|
||||
--root "$RUN_ROOT" --owner "$OWNER" --runtime-image "$RESOLVED_RUNTIME_IMAGE"
|
||||
python3 o11ybench/scripts/check_tracesbench_query_plans.py "$RUN_ROOT/runs/greptimedb"
|
||||
- name: GreptimeDB load, correctness and benchmark (S3)
|
||||
env:
|
||||
AWS_ACCESS_KEY_ID: ${{ inputs.greptimedb_storage != 'file' && secrets.AWS_ACCESS_KEY_ID || '' }}
|
||||
AWS_SECRET_ACCESS_KEY: ${{ inputs.greptimedb_storage != 'file' && secrets.AWS_SECRET_ACCESS_KEY || '' }}
|
||||
if: ${{ !cancelled() && steps.generate.outcome == 'success' && needs.validate.outputs.greptimedb == 'true' && inputs.greptimedb_storage != 'file' }}
|
||||
run: |
|
||||
python3 o11ybench/scripts/run_tracesbench_docker.py --stage target --greptimedb-storage s3 --target greptimedb --port 14000 --greptimedb-image "$GREPTIMEDB_IMAGE" \
|
||||
--db-cpus "$DB_CPUS" --db-memory "$DB_MEMORY" --query-timeout-seconds "$QUERY_TIMEOUT_SECONDS" --load-workers "$LOAD_WORKERS" \
|
||||
--dataset "$DATASET" --runtime-cpus "$RUNTIME_CPUS" --runtime-memory "$RUNTIME_MEMORY" \
|
||||
--root "$RUN_ROOT/s3" --data-root "$RUN_ROOT" --owner "$OWNER-s3" --runtime-image "$RESOLVED_RUNTIME_IMAGE"
|
||||
python3 o11ybench/scripts/check_tracesbench_query_plans.py "$RUN_ROOT/s3/runs/greptimedb"
|
||||
- name: VictoriaTraces load, correctness and benchmark
|
||||
if: ${{ !cancelled() && steps.generate.outcome == 'success' && needs.validate.outputs.victoriatraces == 'true' }}
|
||||
run: |
|
||||
@@ -419,49 +458,80 @@ jobs:
|
||||
- name: GreptimeDB version comparison
|
||||
if: always() && inputs.compare_greptimedb
|
||||
run: |
|
||||
python3 greptimedb/.github/scripts/benchmark-version-comparison.py report --kind traces --root "$RUN_ROOT" >> "$GITHUB_STEP_SUMMARY"
|
||||
- name: Validate and render report
|
||||
python3 greptimedb/.github/scripts/benchmark-version-comparison.py report --kind traces --root "$RUN_ROOT" | tee -a "$RUN_ROOT/ci-summary.md" >> "$GITHUB_STEP_SUMMARY"
|
||||
- name: Validate and render primary report
|
||||
if: always() && steps.generate.outcome == 'success'
|
||||
env:
|
||||
AWS_ACCESS_KEY_ID: ${{ inputs.greptimedb_storage != 'file' && secrets.AWS_ACCESS_KEY_ID || '' }}
|
||||
AWS_SECRET_ACCESS_KEY: ${{ inputs.greptimedb_storage != 'file' && secrets.AWS_SECRET_ACCESS_KEY || '' }}
|
||||
COMPARE_GREPTIMEDB: ${{ inputs.compare_greptimedb }}
|
||||
run: |
|
||||
if [[ "$GREPTIMEDB_STORAGE" == s3 ]]; then
|
||||
TARGETS=$(tr "," "\n" <<< "$TARGETS" | sed "/^greptimedb$/d" | paste -sd, -)
|
||||
[[ -n "$TARGETS" ]] || exit 0
|
||||
fi
|
||||
comparison_args=()
|
||||
if [[ "$COMPARE_GREPTIMEDB" == true ]]; then
|
||||
if [[ "$COMPARE_GREPTIMEDB" == true && "$GREPTIMEDB_STORAGE" != s3 ]]; then
|
||||
comparison_args+=(--baseline-run "$RUN_ROOT/baseline/runs/greptimedb/run.json")
|
||||
fi
|
||||
python3 o11ybench/scripts/run_tracesbench_docker.py --stage report --targets "$TARGETS" "${comparison_args[@]}" \
|
||||
python3 o11ybench/scripts/run_tracesbench_docker.py --stage report --targets "${TARGETS}" "${comparison_args[@]}" \
|
||||
--dataset "$DATASET" --runtime-cpus "$RUNTIME_CPUS" --runtime-memory "$RUNTIME_MEMORY" \
|
||||
--root "$RUN_ROOT" --owner "$OWNER" --runtime-image "$RESOLVED_RUNTIME_IMAGE"
|
||||
- name: Validate and render S3 report
|
||||
if: always() && steps.generate.outcome == 'success' && inputs.greptimedb_storage != 'file'
|
||||
run: |
|
||||
python3 o11ybench/scripts/run_tracesbench_docker.py --stage report --targets greptimedb \
|
||||
--dataset "$DATASET" --runtime-cpus "$RUNTIME_CPUS" --runtime-memory "$RUNTIME_MEMORY" \
|
||||
--root "$RUN_ROOT/s3" --data-root "$RUN_ROOT" --owner "$OWNER-s3" --runtime-image "$RESOLVED_RUNTIME_IMAGE"
|
||||
- name: Clean up owned containers
|
||||
env:
|
||||
AWS_ACCESS_KEY_ID: ${{ inputs.greptimedb_storage != 'file' && secrets.AWS_ACCESS_KEY_ID || '' }}
|
||||
AWS_SECRET_ACCESS_KEY: ${{ inputs.greptimedb_storage != 'file' && secrets.AWS_SECRET_ACCESS_KEY || '' }}
|
||||
if: always() && steps.runtime.outcome == 'success'
|
||||
run: |
|
||||
python3 o11ybench/scripts/run_tracesbench_docker.py --stage cleanup \
|
||||
python3 greptimedb/.github/scripts/o11ybench-storage.py run -- python3 o11ybench/scripts/run_tracesbench_docker.py --stage cleanup \
|
||||
--dataset "$DATASET" --runtime-cpus "$RUNTIME_CPUS" --runtime-memory "$RUNTIME_MEMORY" \
|
||||
--root "$RUN_ROOT" --owner "$OWNER" --runtime-image "$RESOLVED_RUNTIME_IMAGE"
|
||||
- name: Clean up baseline containers
|
||||
env:
|
||||
AWS_ACCESS_KEY_ID: ${{ inputs.greptimedb_storage != 'file' && secrets.AWS_ACCESS_KEY_ID || '' }}
|
||||
AWS_SECRET_ACCESS_KEY: ${{ inputs.greptimedb_storage != 'file' && secrets.AWS_SECRET_ACCESS_KEY || '' }}
|
||||
if: always() && steps.runtime.outcome == 'success' && inputs.compare_greptimedb
|
||||
run: |
|
||||
python3 o11ybench/scripts/run_tracesbench_docker.py --stage cleanup \
|
||||
python3 greptimedb/.github/scripts/o11ybench-storage.py run -- python3 o11ybench/scripts/run_tracesbench_docker.py --stage cleanup \
|
||||
--root "$RUN_ROOT/baseline" --owner "$OWNER-base" --runtime-image "$RESOLVED_RUNTIME_IMAGE"
|
||||
- name: Benchmark summary
|
||||
if: always()
|
||||
run: python3 greptimedb/.github/scripts/tracesbench-summary.py --root "$RUN_ROOT" --targets "$TARGETS" --section benchmark >> "$GITHUB_STEP_SUMMARY"
|
||||
run: python3 greptimedb/.github/scripts/o11ybench-storage.py summary --kind traces --root "$RUN_ROOT" --targets "$TARGETS" --section benchmark | tee -a "$RUN_ROOT/ci-summary.md" >> "$GITHUB_STEP_SUMMARY"
|
||||
- name: Load / lifecycle summary
|
||||
if: always()
|
||||
run: python3 greptimedb/.github/scripts/tracesbench-summary.py --root "$RUN_ROOT" --targets "$TARGETS" --section lifecycle >> "$GITHUB_STEP_SUMMARY"
|
||||
run: python3 greptimedb/.github/scripts/o11ybench-storage.py summary --kind traces --root "$RUN_ROOT" --targets "$TARGETS" --section lifecycle | tee -a "$RUN_ROOT/ci-summary.md" >> "$GITHUB_STEP_SUMMARY"
|
||||
- name: Baseline load / lifecycle summary
|
||||
if: always() && inputs.compare_greptimedb
|
||||
run: |
|
||||
echo '## Baseline GreptimeDB' >> "$GITHUB_STEP_SUMMARY"
|
||||
python3 greptimedb/.github/scripts/tracesbench-summary.py \
|
||||
--root "$RUN_ROOT/baseline" --targets greptimedb --section lifecycle >> "$GITHUB_STEP_SUMMARY"
|
||||
echo '## Baseline GreptimeDB' | tee -a "$RUN_ROOT/ci-summary.md" >> "$GITHUB_STEP_SUMMARY"
|
||||
python3 greptimedb/.github/scripts/o11ybench-storage.py summary --kind traces \
|
||||
--root "$RUN_ROOT/baseline" --targets greptimedb --section lifecycle | tee -a "$RUN_ROOT/ci-summary.md" >> "$GITHUB_STEP_SUMMARY"
|
||||
- name: Render storage comparison overview
|
||||
if: always() && steps.generate.outcome == 'success'
|
||||
run: |
|
||||
mkdir -p "$RUN_ROOT/metadata"
|
||||
cp "$METADATA_ROOT"/*-image.json "$RUN_ROOT/metadata/"
|
||||
python3 o11ybench/scripts/build_query_performance_report.py --traces "$RUN_ROOT" \
|
||||
--output "$RUN_ROOT-query-report.html" --json-output "$RUN_ROOT-query-report.json"
|
||||
python3 greptimedb/.github/scripts/o11ybench-storage.py overview "$RUN_ROOT-query-report.json" \
|
||||
| tee -a "$RUN_ROOT/ci-summary.md" >> "$GITHUB_STEP_SUMMARY"
|
||||
python3 greptimedb/.github/scripts/o11ybench-storage.py audit --root "$RUN_ROOT" \
|
||||
--report "$RUN_ROOT-query-report.json" --targets "$TARGETS" --allow-trace-query-failures
|
||||
- name: Stage benchmark artifacts
|
||||
if: always()
|
||||
run: |
|
||||
mkdir -p "$RUNNER_TEMP/tracesbench-artifacts"
|
||||
cp "$RUN_ROOT"-query-report.* "$RUNNER_TEMP/tracesbench-artifacts/" 2>/dev/null || true
|
||||
if [[ -d "$METADATA_ROOT" ]]; then
|
||||
rsync -a --no-owner --no-group "$METADATA_ROOT" "$RUNNER_TEMP/tracesbench-artifacts/"
|
||||
fi
|
||||
for entry in runs report report.json report.md version-comparison.json version-comparison.md; do
|
||||
for entry in artifact-audit.json metadata runs report report.json report.md ci-summary.md version-comparison.json version-comparison.md; do
|
||||
if [[ -e "$RUN_ROOT/$entry" ]]; then
|
||||
rsync -a --no-owner --no-group "$RUN_ROOT/$entry" "$RUNNER_TEMP/tracesbench-artifacts/"
|
||||
fi
|
||||
@@ -470,6 +540,12 @@ jobs:
|
||||
mkdir -p "$RUNNER_TEMP/tracesbench-artifacts/baseline"
|
||||
rsync -a --no-owner --no-group "$RUN_ROOT/baseline/runs" "$RUNNER_TEMP/tracesbench-artifacts/baseline/"
|
||||
fi
|
||||
for arm in s3 baseline/s3; do
|
||||
if [[ -d "$RUN_ROOT/$arm" ]]; then
|
||||
mkdir -p "$RUNNER_TEMP/tracesbench-artifacts/$arm"
|
||||
rsync -a --no-owner --no-group --exclude scratch --exclude corpora "$RUN_ROOT/$arm/" "$RUNNER_TEMP/tracesbench-artifacts/$arm/"
|
||||
fi
|
||||
done
|
||||
- name: Upload HTML and results (no corpus)
|
||||
if: always()
|
||||
uses: actions/upload-artifact@v4
|
||||
|
||||
@@ -2,6 +2,11 @@ name: VMBench Long Range
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
greptimedb_storage:
|
||||
description: 'GreptimeDB data storage (S3 requires AWS in the bucket region; WAL stays local)'
|
||||
type: choice
|
||||
options: [file, s3, both]
|
||||
default: file
|
||||
run_greptimedb:
|
||||
description: Run GreptimeDB
|
||||
type: boolean
|
||||
@@ -12,6 +17,11 @@ on:
|
||||
type: boolean
|
||||
default: false
|
||||
required: false
|
||||
run_prometheus:
|
||||
description: Run Prometheus (requires a runtime image with managed Prometheus support)
|
||||
type: boolean
|
||||
default: false
|
||||
required: false
|
||||
range_preset:
|
||||
description: Long-range query window (fixed dataset per preset)
|
||||
type: choice
|
||||
@@ -40,8 +50,13 @@ on:
|
||||
type: string
|
||||
default: v1.114.0@sha256:227ad53fd57a4b4430624898a1be0cac39431e1235fa0dc92f567cce38969344
|
||||
required: true
|
||||
prometheus_tag:
|
||||
description: Docker Hub prom/prometheus tag or tag@sha256 digest
|
||||
type: string
|
||||
default: v3.2.1@sha256:6927e0919a144aa7616fd0137d4816816d42f6b816de3af269ab065250859a62
|
||||
required: true
|
||||
runtime_image:
|
||||
description: 'Runtime image: auto = AWS ECR Public or Aliyun ACR by provider; explicit tag/digest overrides'
|
||||
description: 'Runtime image: auto = pinned Prometheus/File/S3 runtime on ACR; explicit tag/digest overrides'
|
||||
type: string
|
||||
default: auto
|
||||
required: true
|
||||
@@ -89,13 +104,19 @@ on:
|
||||
permissions:
|
||||
contents: read
|
||||
env:
|
||||
GREPTIMEDB_STORAGE: ${{ inputs.greptimedb_storage || 'file' }}
|
||||
S3_BUCKET: ${{ vars.AWS_CI_TEST_BUCKET }}
|
||||
S3_REGION: ${{ vars.AWS_CI_TEST_BUCKET_REGION }}
|
||||
RUNNER_REGION: ${{ vars.EC2_RUNNER_REGION }}
|
||||
RUN_GREPTIMEDB: ${{ inputs.run_greptimedb }}
|
||||
COMPARE_GREPTIMEDB: ${{ inputs.compare_greptimedb }}
|
||||
BASELINE_GREPTIMEDB_TAG: ${{ inputs.baseline_greptimedb_tag }}
|
||||
BENCHMARK_ROOT: ${{ inputs.benchmark_root }}
|
||||
RANGE_PRESET: ${{ inputs.range_preset }}
|
||||
GREPTIMEDB_TAG: ${{ inputs.greptimedb_tag }}
|
||||
VICTORIAMETRICS_TAG: ${{ inputs.victoriametrics_tag }}
|
||||
RUNTIME_IMAGE: ${{ inputs.runtime_image != 'auto' && inputs.runtime_image || inputs.provider == 'AWS' && 'public.ecr.aws/i8k6a5e1/greptime/o11ybenchruntime:b43785b56f42@sha256:e38811eb68caf3682ba56f5591a3e8e27e78e7983a923abb29fa2d7cd8fdbd46' || 'greptime-registry.cn-hangzhou.cr.aliyuncs.com/tools/o11ybench-runtime:b43785b56f42@sha256:e38811eb68caf3682ba56f5591a3e8e27e78e7983a923abb29fa2d7cd8fdbd46' }}
|
||||
PROMETHEUS_TAG: ${{ inputs.prometheus_tag }}
|
||||
RUNTIME_IMAGE: ${{ inputs.runtime_image != 'auto' && inputs.runtime_image || 'greptime-registry.cn-hangzhou.cr.aliyuncs.com/tools/o11ybench-runtime:345b6f7c-prometheus-s3@sha256:39d207f4a9c479b8614b8283e2d049fc8f430fcbd2b3362ce3035cfbf294edf9' }}
|
||||
PROVIDER: ${{ inputs.provider }}
|
||||
REQUESTED_INSTANCE_TYPE: ${{ inputs.instance_type }}
|
||||
SYSTEM_DISK_GIB: ${{ inputs.system_disk_gib }}
|
||||
@@ -119,6 +140,10 @@ jobs:
|
||||
with:
|
||||
path: greptimedb
|
||||
persist-credentials: false
|
||||
- name: Validate GreptimeDB storage
|
||||
run: |
|
||||
python3 greptimedb/tests/perf/test_o11ybench_storage.py
|
||||
python3 greptimedb/.github/scripts/o11ybench-storage.py validate
|
||||
- name: Validate version comparison
|
||||
env:
|
||||
RUN_GREPTIMEDB: ${{ inputs.run_greptimedb }}
|
||||
@@ -149,6 +174,7 @@ jobs:
|
||||
env:
|
||||
RUN_GREPTIMEDB: ${{ inputs.run_greptimedb }}
|
||||
RUN_VICTORIAMETRICS: ${{ inputs.run_victoriametrics }}
|
||||
RUN_PROMETHEUS: ${{ inputs.run_prometheus }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
[[ "$BENCHMARK_ROOT" == /* && "$BENCHMARK_ROOT" != / && "$BENCHMARK_ROOT" != */ ]]
|
||||
@@ -173,17 +199,18 @@ jobs:
|
||||
[[ "$revision" =~ ^[0-9a-f]{40}$ ]]
|
||||
printf 'runtime_image=%s\no11ybench_ref=%s\nsystem_disk_gib=%s\n' "$resolved" "$revision" "$SYSTEM_DISK_GIB" >> "$GITHUB_OUTPUT"
|
||||
printf 'run_id=long-range-%s-%s\nplan_artifact=vmbench-plan-%s-%s\n' "$GITHUB_RUN_ID" "$GITHUB_RUN_ATTEMPT" "$GITHUB_RUN_ID" "$GITHUB_RUN_ATTEMPT" >> "$GITHUB_OUTPUT"
|
||||
args=(--workload vmbench-long-range --range-preset "$RANGE_PRESET"
|
||||
args=(--workload vmbench-long-range --range-preset "$RANGE_PRESET" --greptimedb-storage "$GREPTIMEDB_STORAGE"
|
||||
--db-cpus "$DB_CPUS" --db-memory "$DB_MEMORY"
|
||||
--run-classification controlled_server_benchmark --no-open-browser)
|
||||
if [[ "$COMPARE_GREPTIMEDB" == true ]]; then
|
||||
args+=(--target "greptimedb:name=greptimedb-baseline,image=greptime/greptimedb:$BASELINE_GREPTIMEDB_TAG,url=http://127.0.0.1:14000/v1/prometheus/api/v1/query_range")
|
||||
fi
|
||||
# Tags become target-spec fields; reject separators before passing them to the planner.
|
||||
for target in greptimedb victoriametrics; do
|
||||
for target in greptimedb victoriametrics prometheus; do
|
||||
case "$target" in
|
||||
greptimedb) enabled=$RUN_GREPTIMEDB; tag=$GREPTIMEDB_TAG; repo=greptime/greptimedb; url=http://127.0.0.1:14000/v1/prometheus/api/v1/query_range ;;
|
||||
victoriametrics) enabled=$RUN_VICTORIAMETRICS; tag=$VICTORIAMETRICS_TAG; repo=victoriametrics/victoria-metrics; url=http://127.0.0.1:18428/api/v1/query_range ;;
|
||||
prometheus) enabled=$RUN_PROMETHEUS; tag=$PROMETHEUS_TAG; repo=prom/prometheus; url=http://127.0.0.1:19090/api/v1/query_range ;;
|
||||
esac
|
||||
[[ "$enabled" == true ]] || continue
|
||||
[[ "$tag" =~ ^[a-zA-Z0-9_][a-zA-Z0-9_.-]{0,127}(@sha256:[0-9a-f]{64})?$ ]]
|
||||
@@ -192,10 +219,11 @@ jobs:
|
||||
# The packaged planner owns profile, target and resource-limit validation.
|
||||
mkdir -p "$RUNNER_TEMP/vmbench-plans"
|
||||
# Keep the original warm defaults: serial 5/1 and c1/c4 30s/5s.
|
||||
docker run --rm "$resolved" scripts/o11ybench_plan.py "${args[@]}" \
|
||||
docker run --rm -e S3_BUCKET -e S3_REGION "$resolved" scripts/o11ybench_plan.py "${args[@]}" \
|
||||
--run-id "long-range-$GITHUB_RUN_ID-$GITHUB_RUN_ATTEMPT-warm" \
|
||||
--output-root "$BENCHMARK_ROOT/o11ybench/o11ybench-long-range-$GITHUB_RUN_ID-$GITHUB_RUN_ATTEMPT-warm" \
|
||||
--cache-policy warm > "$RUNNER_TEMP/vmbench-plans/warm.json"
|
||||
python3 greptimedb/.github/scripts/o11ybench-storage.py normalize-metrics "$RUNNER_TEMP/vmbench-plans/warm.json"
|
||||
- uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: vmbench-plan-${{ github.run_id }}-${{ github.run_attempt }}
|
||||
@@ -278,7 +306,10 @@ jobs:
|
||||
path: greptimedb
|
||||
persist-credentials: false
|
||||
- name: Set up benchmark dependencies
|
||||
uses: ./greptimedb/.github/actions/setup-benchmark
|
||||
uses: ./greptimedb/.github/actions/setup-linux-runner
|
||||
with:
|
||||
tools: curl jq python3 rsync
|
||||
expected-architecture: x86_64
|
||||
- name: Checkout matching benchmark tools
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
@@ -337,25 +368,92 @@ jobs:
|
||||
--plan "$METADATA_ROOT/warm.json" --runtime-image "$RESOLVED_RUNTIME_IMAGE" --dry-run \
|
||||
> "$METADATA_ROOT/warm-execution-plan.json"
|
||||
cat "$METADATA_ROOT/warm-execution-plan.json"
|
||||
- name: Warm serial and concurrent benchmarks
|
||||
- name: Generate shared dataset and split target plans
|
||||
id: generate
|
||||
run: |
|
||||
set -euo pipefail
|
||||
python3 -u o11ybench/scripts/run_benchmark_plan.py \
|
||||
--plan "$METADATA_ROOT/warm.json" --runtime-image "$RESOLVED_RUNTIME_IMAGE" --execute \
|
||||
2>&1 | tee "$METADATA_ROOT/warm-execution.log"
|
||||
python3 o11ybench/scripts/check_run_benchmark_plan.py --artifacts "$ARTIFACT_ROOT-warm"
|
||||
python3 greptimedb/.github/scripts/o11ybench-storage.py metrics-prepare \
|
||||
--plan "$METADATA_ROOT/warm.json" --tools o11ybench --runtime-image "$RESOLVED_RUNTIME_IMAGE"
|
||||
- name: Load and benchmark Baseline GreptimeDB File
|
||||
if: ${{ !cancelled() && steps.generate.outcome == 'success' && inputs.compare_greptimedb && inputs.greptimedb_storage != 's3' }}
|
||||
run: |
|
||||
python3 greptimedb/.github/scripts/o11ybench-storage.py metrics-run --target greptimedb-baseline \
|
||||
--plan "$METADATA_ROOT/warm.json" --tools o11ybench --runtime-image "$RESOLVED_RUNTIME_IMAGE"
|
||||
- name: Load and benchmark Baseline GreptimeDB S3
|
||||
if: ${{ !cancelled() && steps.generate.outcome == 'success' && inputs.compare_greptimedb && inputs.greptimedb_storage != 'file' }}
|
||||
env:
|
||||
AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }}
|
||||
AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
|
||||
run: |
|
||||
python3 greptimedb/.github/scripts/o11ybench-storage.py metrics-run --target greptimedb-s3-baseline \
|
||||
--plan "$METADATA_ROOT/warm.json" --tools o11ybench --runtime-image "$RESOLVED_RUNTIME_IMAGE"
|
||||
- name: Load and benchmark GreptimeDB File
|
||||
if: ${{ !cancelled() && steps.generate.outcome == 'success' && inputs.run_greptimedb && inputs.greptimedb_storage != 's3' }}
|
||||
run: |
|
||||
python3 greptimedb/.github/scripts/o11ybench-storage.py metrics-run --target greptimedb \
|
||||
--plan "$METADATA_ROOT/warm.json" --tools o11ybench --runtime-image "$RESOLVED_RUNTIME_IMAGE"
|
||||
- name: Load and benchmark GreptimeDB S3
|
||||
if: ${{ !cancelled() && steps.generate.outcome == 'success' && inputs.run_greptimedb && inputs.greptimedb_storage != 'file' }}
|
||||
env:
|
||||
AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }}
|
||||
AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
|
||||
run: |
|
||||
python3 greptimedb/.github/scripts/o11ybench-storage.py metrics-run --target greptimedb-s3 \
|
||||
--plan "$METADATA_ROOT/warm.json" --tools o11ybench --runtime-image "$RESOLVED_RUNTIME_IMAGE"
|
||||
- name: Load and benchmark VictoriaMetrics
|
||||
if: ${{ !cancelled() && steps.generate.outcome == 'success' && inputs.run_victoriametrics }}
|
||||
run: |
|
||||
python3 greptimedb/.github/scripts/o11ybench-storage.py metrics-run --target victoriametrics \
|
||||
--plan "$METADATA_ROOT/warm.json" --tools o11ybench --runtime-image "$RESOLVED_RUNTIME_IMAGE"
|
||||
- name: Load and benchmark Prometheus
|
||||
if: ${{ !cancelled() && steps.generate.outcome == 'success' && inputs.run_prometheus }}
|
||||
run: |
|
||||
python3 greptimedb/.github/scripts/o11ybench-storage.py metrics-run --target prometheus \
|
||||
--plan "$METADATA_ROOT/warm.json" --tools o11ybench --runtime-image "$RESOLVED_RUNTIME_IMAGE"
|
||||
- name: Validate all selected target results
|
||||
if: always() && steps.generate.outcome == 'success'
|
||||
run: |
|
||||
python3 greptimedb/.github/scripts/o11ybench-storage.py metrics-validate \
|
||||
--plan "$METADATA_ROOT/warm.json" --tools o11ybench --runtime-image "$RESOLVED_RUNTIME_IMAGE"
|
||||
- name: Clean up owned containers
|
||||
env:
|
||||
AWS_ACCESS_KEY_ID: ${{ inputs.greptimedb_storage != 'file' && secrets.AWS_ACCESS_KEY_ID || '' }}
|
||||
AWS_SECRET_ACCESS_KEY: ${{ inputs.greptimedb_storage != 'file' && secrets.AWS_SECRET_ACCESS_KEY || '' }}
|
||||
if: always()
|
||||
run: |
|
||||
docker ps -aq --filter "label=o11ybench.run-id=$RUN_ID-warm" | xargs -r docker rm -fv
|
||||
for name in greptimedb greptimedb-s3 greptimedb-baseline greptimedb-s3-baseline victoriametrics prometheus; do
|
||||
plan="$METADATA_ROOT/$name.json"
|
||||
[[ -f "$plan" ]] || continue
|
||||
run_id=$(jq -r '.run_id // empty' "$plan")
|
||||
[[ -n "$run_id" ]] || continue
|
||||
docker ps -aq --filter "label=o11ybench.run-id=$run_id" | xargs -r docker rm -fv
|
||||
done
|
||||
if [[ -d "$ARTIFACT_ROOT-warm" ]]; then
|
||||
for probe in "$ARTIFACT_ROOT-warm"/o11ybench/*/*/s3-probe.json; do
|
||||
[[ -f "$probe" ]] || continue
|
||||
python3 o11ybench/scripts/greptimedb_storage.py recover --runtime-image "$RESOLVED_RUNTIME_IMAGE" --output "${probe%/*}"
|
||||
done
|
||||
fi
|
||||
- name: GreptimeDB version comparison
|
||||
if: always() && inputs.compare_greptimedb
|
||||
run: |
|
||||
python3 greptimedb/.github/scripts/benchmark-version-comparison.py report --kind long-range --root "$ARTIFACT_ROOT-warm" >> "$GITHUB_STEP_SUMMARY"
|
||||
python3 greptimedb/.github/scripts/benchmark-version-comparison.py report --kind long-range --root "$ARTIFACT_ROOT-warm" | tee -a "$ARTIFACT_ROOT-warm/ci-summary.md" >> "$GITHUB_STEP_SUMMARY"
|
||||
- name: Render storage comparison overview
|
||||
if: always() && steps.generate.outcome == 'success'
|
||||
run: |
|
||||
mkdir -p "$ARTIFACT_ROOT-warm/metadata"
|
||||
cp "$METADATA_ROOT"/*-image.json "$ARTIFACT_ROOT-warm/metadata/"
|
||||
python3 o11ybench/scripts/build_query_performance_report.py --metrics "$ARTIFACT_ROOT-warm" \
|
||||
--output "$ARTIFACT_ROOT-warm-query-report.html" --json-output "$ARTIFACT_ROOT-warm-query-report.json"
|
||||
python3 greptimedb/.github/scripts/o11ybench-storage.py overview "$ARTIFACT_ROOT-warm-query-report.json" \
|
||||
| tee -a "$ARTIFACT_ROOT-warm/ci-summary.md" >> "$GITHUB_STEP_SUMMARY"
|
||||
python3 greptimedb/.github/scripts/o11ybench-storage.py audit --root "$ARTIFACT_ROOT-warm" \
|
||||
--report "$ARTIFACT_ROOT-warm-query-report.json" --targets "$(jq -r '[.targets[].kind] | unique | join(",")' "$METADATA_ROOT/warm.json")"
|
||||
- name: Stage benchmark artifacts
|
||||
if: always()
|
||||
run: |
|
||||
mkdir -p "$RUNNER_TEMP/vmbench-artifacts"
|
||||
cp "$ARTIFACT_ROOT-warm"-query-report.* "$RUNNER_TEMP/vmbench-artifacts/" 2>/dev/null || true
|
||||
if [[ -d "$METADATA_ROOT" ]]; then
|
||||
rsync -a --no-owner --no-group "$METADATA_ROOT" "$RUNNER_TEMP/vmbench-artifacts/"
|
||||
fi
|
||||
|
||||
Generated
+82
-61
@@ -1657,7 +1657,7 @@ dependencies = [
|
||||
"maybe-owned",
|
||||
"rustix 1.0.7",
|
||||
"rustix-linux-procfs",
|
||||
"windows-sys 0.60.2",
|
||||
"windows-sys 0.61.2",
|
||||
"winx",
|
||||
]
|
||||
|
||||
@@ -2285,7 +2285,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "117725a109d387c937a1533ce01b450cbde6b88abceea8473c4d7a85853cda3c"
|
||||
dependencies = [
|
||||
"lazy_static",
|
||||
"windows-sys 0.48.0",
|
||||
"windows-sys 0.59.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2501,6 +2501,7 @@ dependencies = [
|
||||
"arrow 59.2.0",
|
||||
"arrow-schema 59.2.0",
|
||||
"async-trait",
|
||||
"auth",
|
||||
"axum 0.8.4",
|
||||
"bincode",
|
||||
"catalog",
|
||||
@@ -2534,6 +2535,7 @@ dependencies = [
|
||||
"mito-codec",
|
||||
"nalgebra",
|
||||
"num-traits",
|
||||
"partition",
|
||||
"paste",
|
||||
"pretty_assertions",
|
||||
"regex",
|
||||
@@ -2812,6 +2814,7 @@ dependencies = [
|
||||
"common-time",
|
||||
"datafusion",
|
||||
"datafusion-common",
|
||||
"datafusion-datasource",
|
||||
"datafusion-expr",
|
||||
"datafusion-proto",
|
||||
"datatypes",
|
||||
@@ -3769,7 +3772,7 @@ checksum = "a4ae5f15dda3c708c0ade84bfee31ccab44a3da4f88015ed22f63732abe300c8"
|
||||
[[package]]
|
||||
name = "datafusion"
|
||||
version = "55.1.0"
|
||||
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7"
|
||||
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=638a77fb504e86f85ef6053c552bbee1ed814fb9#638a77fb504e86f85ef6053c552bbee1ed814fb9"
|
||||
dependencies = [
|
||||
"arrow 59.2.0",
|
||||
"arrow-schema 59.2.0",
|
||||
@@ -3821,7 +3824,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "datafusion-catalog"
|
||||
version = "55.1.0"
|
||||
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7"
|
||||
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=638a77fb504e86f85ef6053c552bbee1ed814fb9#638a77fb504e86f85ef6053c552bbee1ed814fb9"
|
||||
dependencies = [
|
||||
"arrow 59.2.0",
|
||||
"async-trait",
|
||||
@@ -3845,7 +3848,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "datafusion-catalog-listing"
|
||||
version = "55.1.0"
|
||||
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7"
|
||||
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=638a77fb504e86f85ef6053c552bbee1ed814fb9#638a77fb504e86f85ef6053c552bbee1ed814fb9"
|
||||
dependencies = [
|
||||
"arrow 59.2.0",
|
||||
"async-trait",
|
||||
@@ -3868,7 +3871,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "datafusion-common"
|
||||
version = "55.1.0"
|
||||
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7"
|
||||
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=638a77fb504e86f85ef6053c552bbee1ed814fb9#638a77fb504e86f85ef6053c552bbee1ed814fb9"
|
||||
dependencies = [
|
||||
"arrow 59.2.0",
|
||||
"arrow-ipc 59.2.0",
|
||||
@@ -3894,7 +3897,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "datafusion-common-runtime"
|
||||
version = "55.1.0"
|
||||
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7"
|
||||
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=638a77fb504e86f85ef6053c552bbee1ed814fb9#638a77fb504e86f85ef6053c552bbee1ed814fb9"
|
||||
dependencies = [
|
||||
"futures",
|
||||
"log",
|
||||
@@ -3904,7 +3907,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "datafusion-datasource"
|
||||
version = "55.1.0"
|
||||
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7"
|
||||
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=638a77fb504e86f85ef6053c552bbee1ed814fb9#638a77fb504e86f85ef6053c552bbee1ed814fb9"
|
||||
dependencies = [
|
||||
"arrow 59.2.0",
|
||||
"async-compression",
|
||||
@@ -3940,7 +3943,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "datafusion-datasource-arrow"
|
||||
version = "55.1.0"
|
||||
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7"
|
||||
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=638a77fb504e86f85ef6053c552bbee1ed814fb9#638a77fb504e86f85ef6053c552bbee1ed814fb9"
|
||||
dependencies = [
|
||||
"arrow 59.2.0",
|
||||
"arrow-ipc 59.2.0",
|
||||
@@ -3964,7 +3967,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "datafusion-datasource-csv"
|
||||
version = "55.1.0"
|
||||
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7"
|
||||
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=638a77fb504e86f85ef6053c552bbee1ed814fb9#638a77fb504e86f85ef6053c552bbee1ed814fb9"
|
||||
dependencies = [
|
||||
"arrow 59.2.0",
|
||||
"async-trait",
|
||||
@@ -3987,7 +3990,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "datafusion-datasource-json"
|
||||
version = "55.1.0"
|
||||
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7"
|
||||
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=638a77fb504e86f85ef6053c552bbee1ed814fb9#638a77fb504e86f85ef6053c552bbee1ed814fb9"
|
||||
dependencies = [
|
||||
"arrow 59.2.0",
|
||||
"async-trait",
|
||||
@@ -4010,7 +4013,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "datafusion-datasource-parquet"
|
||||
version = "55.1.0"
|
||||
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7"
|
||||
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=638a77fb504e86f85ef6053c552bbee1ed814fb9#638a77fb504e86f85ef6053c552bbee1ed814fb9"
|
||||
dependencies = [
|
||||
"arrow 59.2.0",
|
||||
"arrow-schema 59.2.0",
|
||||
@@ -4042,12 +4045,12 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "datafusion-doc"
|
||||
version = "55.1.0"
|
||||
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7"
|
||||
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=638a77fb504e86f85ef6053c552bbee1ed814fb9#638a77fb504e86f85ef6053c552bbee1ed814fb9"
|
||||
|
||||
[[package]]
|
||||
name = "datafusion-execution"
|
||||
version = "55.1.0"
|
||||
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7"
|
||||
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=638a77fb504e86f85ef6053c552bbee1ed814fb9#638a77fb504e86f85ef6053c552bbee1ed814fb9"
|
||||
dependencies = [
|
||||
"arrow 59.2.0",
|
||||
"arrow-buffer 59.2.0",
|
||||
@@ -4072,7 +4075,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "datafusion-expr"
|
||||
version = "55.1.0"
|
||||
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7"
|
||||
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=638a77fb504e86f85ef6053c552bbee1ed814fb9#638a77fb504e86f85ef6053c552bbee1ed814fb9"
|
||||
dependencies = [
|
||||
"arrow 59.2.0",
|
||||
"arrow-schema 59.2.0",
|
||||
@@ -4096,7 +4099,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "datafusion-expr-common"
|
||||
version = "55.1.0"
|
||||
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7"
|
||||
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=638a77fb504e86f85ef6053c552bbee1ed814fb9#638a77fb504e86f85ef6053c552bbee1ed814fb9"
|
||||
dependencies = [
|
||||
"arrow 59.2.0",
|
||||
"datafusion-common",
|
||||
@@ -4107,7 +4110,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "datafusion-functions"
|
||||
version = "55.1.0"
|
||||
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7"
|
||||
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=638a77fb504e86f85ef6053c552bbee1ed814fb9#638a77fb504e86f85ef6053c552bbee1ed814fb9"
|
||||
dependencies = [
|
||||
"arrow 59.2.0",
|
||||
"arrow-buffer 59.2.0",
|
||||
@@ -4138,7 +4141,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "datafusion-functions-aggregate"
|
||||
version = "55.1.0"
|
||||
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7"
|
||||
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=638a77fb504e86f85ef6053c552bbee1ed814fb9#638a77fb504e86f85ef6053c552bbee1ed814fb9"
|
||||
dependencies = [
|
||||
"arrow 59.2.0",
|
||||
"datafusion-common",
|
||||
@@ -4158,7 +4161,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "datafusion-functions-aggregate-common"
|
||||
version = "55.1.0"
|
||||
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7"
|
||||
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=638a77fb504e86f85ef6053c552bbee1ed814fb9#638a77fb504e86f85ef6053c552bbee1ed814fb9"
|
||||
dependencies = [
|
||||
"arrow 59.2.0",
|
||||
"datafusion-common",
|
||||
@@ -4169,7 +4172,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "datafusion-functions-nested"
|
||||
version = "55.1.0"
|
||||
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7"
|
||||
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=638a77fb504e86f85ef6053c552bbee1ed814fb9#638a77fb504e86f85ef6053c552bbee1ed814fb9"
|
||||
dependencies = [
|
||||
"arrow 59.2.0",
|
||||
"arrow-ord 59.2.0",
|
||||
@@ -4193,7 +4196,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "datafusion-functions-table"
|
||||
version = "55.1.0"
|
||||
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7"
|
||||
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=638a77fb504e86f85ef6053c552bbee1ed814fb9#638a77fb504e86f85ef6053c552bbee1ed814fb9"
|
||||
dependencies = [
|
||||
"arrow 59.2.0",
|
||||
"async-trait",
|
||||
@@ -4208,7 +4211,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "datafusion-functions-window"
|
||||
version = "55.1.0"
|
||||
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7"
|
||||
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=638a77fb504e86f85ef6053c552bbee1ed814fb9#638a77fb504e86f85ef6053c552bbee1ed814fb9"
|
||||
dependencies = [
|
||||
"arrow 59.2.0",
|
||||
"datafusion-common",
|
||||
@@ -4224,7 +4227,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "datafusion-functions-window-common"
|
||||
version = "55.1.0"
|
||||
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7"
|
||||
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=638a77fb504e86f85ef6053c552bbee1ed814fb9#638a77fb504e86f85ef6053c552bbee1ed814fb9"
|
||||
dependencies = [
|
||||
"datafusion-common",
|
||||
"datafusion-physical-expr-common",
|
||||
@@ -4233,7 +4236,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "datafusion-macros"
|
||||
version = "55.1.0"
|
||||
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7"
|
||||
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=638a77fb504e86f85ef6053c552bbee1ed814fb9#638a77fb504e86f85ef6053c552bbee1ed814fb9"
|
||||
dependencies = [
|
||||
"datafusion-doc",
|
||||
"quote",
|
||||
@@ -4243,7 +4246,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "datafusion-optimizer"
|
||||
version = "55.1.0"
|
||||
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7"
|
||||
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=638a77fb504e86f85ef6053c552bbee1ed814fb9#638a77fb504e86f85ef6053c552bbee1ed814fb9"
|
||||
dependencies = [
|
||||
"arrow 59.2.0",
|
||||
"chrono",
|
||||
@@ -4291,7 +4294,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "datafusion-physical-expr"
|
||||
version = "55.1.0"
|
||||
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7"
|
||||
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=638a77fb504e86f85ef6053c552bbee1ed814fb9#638a77fb504e86f85ef6053c552bbee1ed814fb9"
|
||||
dependencies = [
|
||||
"arrow 59.2.0",
|
||||
"arrow-schema 59.2.0",
|
||||
@@ -4314,7 +4317,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "datafusion-physical-expr-adapter"
|
||||
version = "55.1.0"
|
||||
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7"
|
||||
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=638a77fb504e86f85ef6053c552bbee1ed814fb9#638a77fb504e86f85ef6053c552bbee1ed814fb9"
|
||||
dependencies = [
|
||||
"arrow 59.2.0",
|
||||
"datafusion-common",
|
||||
@@ -4328,7 +4331,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "datafusion-physical-expr-common"
|
||||
version = "55.1.0"
|
||||
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7"
|
||||
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=638a77fb504e86f85ef6053c552bbee1ed814fb9#638a77fb504e86f85ef6053c552bbee1ed814fb9"
|
||||
dependencies = [
|
||||
"arrow 59.2.0",
|
||||
"chrono",
|
||||
@@ -4345,7 +4348,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "datafusion-physical-optimizer"
|
||||
version = "55.1.0"
|
||||
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7"
|
||||
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=638a77fb504e86f85ef6053c552bbee1ed814fb9#638a77fb504e86f85ef6053c552bbee1ed814fb9"
|
||||
dependencies = [
|
||||
"arrow 59.2.0",
|
||||
"datafusion-common",
|
||||
@@ -4364,7 +4367,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "datafusion-physical-plan"
|
||||
version = "55.1.0"
|
||||
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7"
|
||||
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=638a77fb504e86f85ef6053c552bbee1ed814fb9#638a77fb504e86f85ef6053c552bbee1ed814fb9"
|
||||
dependencies = [
|
||||
"arrow 59.2.0",
|
||||
"arrow-data 59.2.0",
|
||||
@@ -4401,7 +4404,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "datafusion-proto"
|
||||
version = "55.1.0"
|
||||
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7"
|
||||
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=638a77fb504e86f85ef6053c552bbee1ed814fb9#638a77fb504e86f85ef6053c552bbee1ed814fb9"
|
||||
dependencies = [
|
||||
"arrow 59.2.0",
|
||||
"datafusion-catalog",
|
||||
@@ -4427,7 +4430,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "datafusion-proto-common"
|
||||
version = "55.1.0"
|
||||
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7"
|
||||
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=638a77fb504e86f85ef6053c552bbee1ed814fb9#638a77fb504e86f85ef6053c552bbee1ed814fb9"
|
||||
dependencies = [
|
||||
"arrow 59.2.0",
|
||||
"datafusion-common",
|
||||
@@ -4437,7 +4440,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "datafusion-proto-models"
|
||||
version = "55.1.0"
|
||||
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7"
|
||||
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=638a77fb504e86f85ef6053c552bbee1ed814fb9#638a77fb504e86f85ef6053c552bbee1ed814fb9"
|
||||
dependencies = [
|
||||
"datafusion-common",
|
||||
"datafusion-proto-common",
|
||||
@@ -4447,7 +4450,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "datafusion-pruning"
|
||||
version = "55.1.0"
|
||||
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7"
|
||||
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=638a77fb504e86f85ef6053c552bbee1ed814fb9#638a77fb504e86f85ef6053c552bbee1ed814fb9"
|
||||
dependencies = [
|
||||
"arrow 59.2.0",
|
||||
"datafusion-common",
|
||||
@@ -4462,7 +4465,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "datafusion-session"
|
||||
version = "55.1.0"
|
||||
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7"
|
||||
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=638a77fb504e86f85ef6053c552bbee1ed814fb9#638a77fb504e86f85ef6053c552bbee1ed814fb9"
|
||||
dependencies = [
|
||||
"arrow-schema 59.2.0",
|
||||
"async-trait",
|
||||
@@ -4476,7 +4479,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "datafusion-sql"
|
||||
version = "55.1.0"
|
||||
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7"
|
||||
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=638a77fb504e86f85ef6053c552bbee1ed814fb9#638a77fb504e86f85ef6053c552bbee1ed814fb9"
|
||||
dependencies = [
|
||||
"arrow 59.2.0",
|
||||
"bigdecimal 0.4.8",
|
||||
@@ -4495,7 +4498,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "datafusion-substrait"
|
||||
version = "55.1.0"
|
||||
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7"
|
||||
source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=638a77fb504e86f85ef6053c552bbee1ed814fb9#638a77fb504e86f85ef6053c552bbee1ed814fb9"
|
||||
dependencies = [
|
||||
"async-recursion",
|
||||
"async-trait",
|
||||
@@ -4517,6 +4520,7 @@ version = "1.4.0-alpha.0"
|
||||
dependencies = [
|
||||
"api",
|
||||
"arrow-flight",
|
||||
"async-stream",
|
||||
"async-trait",
|
||||
"bytes",
|
||||
"cache",
|
||||
@@ -4612,7 +4616,6 @@ dependencies = [
|
||||
"parquet-variant-compute",
|
||||
"parquet-variant-json",
|
||||
"paste",
|
||||
"regex",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"snafu 0.8.6",
|
||||
@@ -6157,7 +6160,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "greptime-proto"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/GreptimeTeam/greptime-proto.git?rev=9eb24ddd94ddb9295bff9e596834832a7d8ba008#9eb24ddd94ddb9295bff9e596834832a7d8ba008"
|
||||
source = "git+https://github.com/GreptimeTeam/greptime-proto.git?rev=5870f5adc4d601173e742888e7db2032a690b583#5870f5adc4d601173e742888e7db2032a690b583"
|
||||
dependencies = [
|
||||
"prost 0.14.1",
|
||||
"prost-types 0.14.1",
|
||||
@@ -6250,11 +6253,11 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "halfbrown"
|
||||
version = "0.3.0"
|
||||
version = "0.4.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "aa2c385c6df70fd180bbb673d93039dbd2cd34e41d782600bdf6e1ca7bce39aa"
|
||||
checksum = "0c7ed2f2edad8a14c8186b847909a41fbb9c3eafa44f88bd891114ed5019da09"
|
||||
dependencies = [
|
||||
"hashbrown 0.15.4",
|
||||
"hashbrown 0.16.1",
|
||||
"serde",
|
||||
]
|
||||
|
||||
@@ -6769,7 +6772,7 @@ dependencies = [
|
||||
"libc",
|
||||
"percent-encoding",
|
||||
"pin-project-lite",
|
||||
"socket2 0.5.10",
|
||||
"socket2 0.6.4",
|
||||
"tokio",
|
||||
"tower-service",
|
||||
"tracing",
|
||||
@@ -7244,6 +7247,17 @@ version = "4.0.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0d762194228a2f1c11063e46e32e5acb96e66e906382b9eb5441f2e0504bbd5a"
|
||||
|
||||
[[package]]
|
||||
name = "intern-arc"
|
||||
version = "0.6.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2fe5735fd955e619f30a5257c8ce5234354cbe72d8a04a24414c9004125f02b2"
|
||||
dependencies = [
|
||||
"loom",
|
||||
"once_cell",
|
||||
"parking_lot 0.12.4",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "inventory"
|
||||
version = "0.3.20"
|
||||
@@ -7583,7 +7597,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "jsonb"
|
||||
version = "0.5.6"
|
||||
source = "git+https://github.com/GreptimeTeam/jsonb?rev=dd1e2341e3df35e9de38959328caa7628e81b6b1#dd1e2341e3df35e9de38959328caa7628e81b6b1"
|
||||
source = "git+https://github.com/GreptimeTeam/jsonb?rev=5a6472858d860ac034075c17253f41617bdfa956#5a6472858d860ac034075c17253f41617bdfa956"
|
||||
dependencies = [
|
||||
"byteorder",
|
||||
"ethnum",
|
||||
@@ -8194,6 +8208,7 @@ dependencies = [
|
||||
"bytes",
|
||||
"chrono",
|
||||
"common-base",
|
||||
"common-cache",
|
||||
"common-config",
|
||||
"common-error",
|
||||
"common-macro",
|
||||
@@ -8831,6 +8846,7 @@ dependencies = [
|
||||
"humantime",
|
||||
"humantime-serde",
|
||||
"index",
|
||||
"intern-arc",
|
||||
"itertools 0.14.0",
|
||||
"lazy_static",
|
||||
"log-store",
|
||||
@@ -9332,7 +9348,7 @@ version = "0.50.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5"
|
||||
dependencies = [
|
||||
"windows-sys 0.60.2",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -9727,6 +9743,9 @@ name = "once_cell"
|
||||
version = "1.21.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
|
||||
dependencies = [
|
||||
"parking_lot_core 0.9.11",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "once_cell_polyfill"
|
||||
@@ -10180,6 +10199,7 @@ dependencies = [
|
||||
"ahash 0.8.12",
|
||||
"api",
|
||||
"arrow 59.2.0",
|
||||
"arrow-schema 59.2.0",
|
||||
"async-stream",
|
||||
"async-trait",
|
||||
"axum 0.8.4",
|
||||
@@ -10814,9 +10834,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "pgwire"
|
||||
version = "0.42.1"
|
||||
version = "0.42.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1452e6541bcc64e166ff9d350c25c09334c0c80e8f60fde5e36ff81768eeaa55"
|
||||
checksum = "69354d96ef951739b5ccc75a99a8a1b09bc164afde265be9656ddab87395b481"
|
||||
dependencies = [
|
||||
"async-trait",
|
||||
"aws-lc-rs",
|
||||
@@ -11604,7 +11624,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ac6c3320f9abac597dcbc668774ef006702672474aad53c6d596b62e487b40b1"
|
||||
dependencies = [
|
||||
"heck 0.5.0",
|
||||
"itertools 0.10.5",
|
||||
"itertools 0.14.0",
|
||||
"log",
|
||||
"multimap",
|
||||
"once_cell",
|
||||
@@ -11652,7 +11672,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8a56d757972c98b346a9b766e3f02746cde6dd1cd1d1d563472929fdd74bec4d"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"itertools 0.10.5",
|
||||
"itertools 0.14.0",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.117",
|
||||
@@ -11665,7 +11685,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9120690fafc389a67ba3803df527d0ec9cbbc9cc45e4cc20b332996dfb672425"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"itertools 0.10.5",
|
||||
"itertools 0.14.0",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.117",
|
||||
@@ -11962,6 +11982,7 @@ dependencies = [
|
||||
"async-stream",
|
||||
"async-trait",
|
||||
"bytes",
|
||||
"cache",
|
||||
"catalog",
|
||||
"chrono",
|
||||
"common-base",
|
||||
@@ -11972,6 +11993,7 @@ dependencies = [
|
||||
"common-macro",
|
||||
"common-meta",
|
||||
"common-plugins",
|
||||
"common-procedure",
|
||||
"common-query",
|
||||
"common-recordbatch",
|
||||
"common-runtime",
|
||||
@@ -13219,7 +13241,7 @@ dependencies = [
|
||||
"security-framework 3.7.0",
|
||||
"security-framework-sys",
|
||||
"webpki-root-certs",
|
||||
"windows-sys 0.60.2",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -13988,13 +14010,11 @@ checksum = "d66dc143e6b11c1eddc06d5c423cfc97062865baf299914ab64caa38182078fe"
|
||||
|
||||
[[package]]
|
||||
name = "simd-json"
|
||||
version = "0.15.1"
|
||||
version = "0.19.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c962f626b54771990066e5435ec8331d1462576cd2d1e62f24076ae014f92112"
|
||||
checksum = "e8f2e4d523646f7da6dde3983bd18ede0babc21c258ab708b3dd93ea0259719d"
|
||||
dependencies = [
|
||||
"getrandom 0.3.4",
|
||||
"halfbrown",
|
||||
"ref-cast",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"simdutf8",
|
||||
@@ -14143,7 +14163,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "52d1cfed4120b4d927bf7c0f86d2087a4a7d6027c906d9f9d525a80573b9be51"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"windows-sys 0.60.2",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -14714,7 +14734,7 @@ dependencies = [
|
||||
"cfg-if",
|
||||
"libc",
|
||||
"psm",
|
||||
"windows-sys 0.60.2",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -14723,6 +14743,7 @@ version = "1.4.0-alpha.0"
|
||||
dependencies = [
|
||||
"api",
|
||||
"async-trait",
|
||||
"auth",
|
||||
"catalog",
|
||||
"client",
|
||||
"common-base",
|
||||
@@ -15338,7 +15359,7 @@ dependencies = [
|
||||
"getrandom 0.3.4",
|
||||
"once_cell",
|
||||
"rustix 1.0.7",
|
||||
"windows-sys 0.60.2",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -16591,9 +16612,9 @@ checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65"
|
||||
|
||||
[[package]]
|
||||
name = "value-trait"
|
||||
version = "0.11.0"
|
||||
version = "0.12.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0508fce11ad19e0aab49ce20b6bec7f8f82902ded31df1c9fc61b90f0eb396b8"
|
||||
checksum = "545a3d7089f11f1741d12963c057adf9443fc24325110a6a6daf582e825fd51b"
|
||||
dependencies = [
|
||||
"float-cmp",
|
||||
"halfbrown",
|
||||
@@ -17108,7 +17129,7 @@ version = "0.1.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cf221c93e13a30d793f7645a0e7762c55d169dbb0a49671918a2319d289b10bb"
|
||||
dependencies = [
|
||||
"windows-sys 0.48.0",
|
||||
"windows-sys 0.59.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
|
||||
+20
-19
@@ -164,7 +164,7 @@ fs2 = "0.4"
|
||||
fst = "0.4.7"
|
||||
futures = "0.3"
|
||||
futures-util = "0.3"
|
||||
greptime-proto = { git = "https://github.com/GreptimeTeam/greptime-proto.git", rev = "9eb24ddd94ddb9295bff9e596834832a7d8ba008" }
|
||||
greptime-proto = { git = "https://github.com/GreptimeTeam/greptime-proto.git", rev = "5870f5adc4d601173e742888e7db2032a690b583" }
|
||||
hdfs-native = "0.14.6"
|
||||
hex = "0.4"
|
||||
hostname = "0.4.0"
|
||||
@@ -175,8 +175,9 @@ hyper = "1.1"
|
||||
hyper-util = "0.1"
|
||||
icu_properties = "2.0.1"
|
||||
indicatif = "0.17"
|
||||
intern-arc = "0.6.2"
|
||||
itertools = "0.14"
|
||||
jsonb = { git = "https://github.com/GreptimeTeam/jsonb", rev = "dd1e2341e3df35e9de38959328caa7628e81b6b1", default-features = false, features = [
|
||||
jsonb = { git = "https://github.com/GreptimeTeam/jsonb", rev = "5a6472858d860ac034075c17253f41617bdfa956", default-features = false, features = [
|
||||
"databend",
|
||||
] }
|
||||
lazy_static = "1.4"
|
||||
@@ -248,7 +249,7 @@ serde_json = { version = "1.0", features = ["float_roundtrip"] }
|
||||
serde_with = "3"
|
||||
serde_yaml_ng = "0.10"
|
||||
sha2 = "0.10"
|
||||
simd-json = "0.15"
|
||||
simd-json = "0.19"
|
||||
similar-asserts = "1.6.0"
|
||||
smallvec = { version = "1", features = ["serde"] }
|
||||
snafu = "0.8"
|
||||
@@ -371,22 +372,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 = "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 = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "638a77fb504e86f85ef6053c552bbee1ed814fb9" }
|
||||
datafusion-common = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "638a77fb504e86f85ef6053c552bbee1ed814fb9" }
|
||||
datafusion-datasource = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "638a77fb504e86f85ef6053c552bbee1ed814fb9" }
|
||||
datafusion-execution = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "638a77fb504e86f85ef6053c552bbee1ed814fb9" }
|
||||
datafusion-expr = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "638a77fb504e86f85ef6053c552bbee1ed814fb9" }
|
||||
datafusion-expr-common = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "638a77fb504e86f85ef6053c552bbee1ed814fb9" }
|
||||
datafusion-functions = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "638a77fb504e86f85ef6053c552bbee1ed814fb9" }
|
||||
datafusion-functions-aggregate-common = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "638a77fb504e86f85ef6053c552bbee1ed814fb9" }
|
||||
datafusion-functions-window-common = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "638a77fb504e86f85ef6053c552bbee1ed814fb9" }
|
||||
datafusion-optimizer = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "638a77fb504e86f85ef6053c552bbee1ed814fb9" }
|
||||
datafusion-physical-expr = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "638a77fb504e86f85ef6053c552bbee1ed814fb9" }
|
||||
datafusion-physical-expr-common = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "638a77fb504e86f85ef6053c552bbee1ed814fb9" }
|
||||
datafusion-physical-plan = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "638a77fb504e86f85ef6053c552bbee1ed814fb9" }
|
||||
datafusion-proto = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "638a77fb504e86f85ef6053c552bbee1ed814fb9" }
|
||||
datafusion-sql = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "638a77fb504e86f85ef6053c552bbee1ed814fb9" }
|
||||
datafusion-substrait = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "638a77fb504e86f85ef6053c552bbee1ed814fb9" }
|
||||
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" }
|
||||
|
||||
@@ -9,13 +9,11 @@
|
||||
<h2 align="center">Metrics, logs, and traces.<br/>
|
||||
One engine, on your infrastructure.</h2>
|
||||
|
||||
> A columnar database for metrics, logs, and traces on object storage.
|
||||
> Apache-2.0 licensed core.
|
||||
|
||||
<div align="center">
|
||||
|
||||
<a href="https://docs.greptime.com/user-guide/overview/">User Guide</a> ·
|
||||
<a href="https://greptimedb.rs/">API Docs</a> ·
|
||||
<a href="https://live.greptime.cloud/dashboard/?info=eyJ1c2VybmFtZSI6ImdyZXB0aW1lIiwicGFzc3dvcmQiOiJkZW1vc2Vzc2lvbiJ9&query_guide=1&utm_source=github&utm_medium=readme&utm_campaign=greptimedb#/dashboard/explore">Live Demo</a> ·
|
||||
<a href="https://github.com/GreptimeTeam/greptimedb/issues/7685">Roadmap 2026</a> ·
|
||||
<a href="https://greptime.com/slack">Slack</a>
|
||||
|
||||
@@ -61,76 +59,6 @@ LIMIT 20;
|
||||
Metrics join the same way, on any tag the tables share, such as `service`,
|
||||
`host`, or `pod`.
|
||||
|
||||
## Why You Might Use It
|
||||
|
||||
- You run Prometheus plus Loki or Elasticsearch and want one backend instead of three
|
||||
- You have outgrown Prometheus on cardinality or retention and don't want the Thanos/Mimir operational surface
|
||||
- You are hitting Loki's query performance limits as log volume grows
|
||||
- You need long retention on object storage without a separate analytics stack
|
||||
- You want to query telemetry with SQL, not only a domain query language
|
||||
- You are storing GenAI or agent telemetry ([OTel GenAI conventions](https://opentelemetry.io/docs/specs/semconv/gen-ai/)) alongside infrastructure signals
|
||||
|
||||
Learn more in [Why GreptimeDB](https://docs.greptime.com/user-guide/concepts/why-greptimedb).
|
||||
|
||||
## What's Supported
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Ingest** | [OpenTelemetry (OTLP)](https://docs.greptime.com/user-guide/ingest-data/for-observability/opentelemetry/), [Prometheus Remote Write](https://docs.greptime.com/user-guide/ingest-data/for-observability/prometheus/), [Loki Push](https://docs.greptime.com/user-guide/ingest-data/for-observability/loki), [Elasticsearch Bulk](https://docs.greptime.com/user-guide/ingest-data/for-observability/elasticsearch), [InfluxDB line protocol](https://docs.greptime.com/user-guide/protocols/influxdb-line-protocol), [gRPC](https://docs.greptime.com/user-guide/protocols/grpc/) |
|
||||
| **Query** | [SQL](https://docs.greptime.com/user-guide/query-data/overview/), [PromQL](https://docs.greptime.com/user-guide/query-data/promql/), [Jaeger-compatible trace queries](https://docs.greptime.com/user-guide/query-data/jaeger/), MySQL and PostgreSQL wire protocols |
|
||||
| **Storage** | S3, GCS, Azure Blob and S3-compatible endpoints as [primary storage](https://docs.greptime.com/user-guide/deployments-administration/configuration/#storage-options), with memory and local-disk caches |
|
||||
| **Built in** | Retention policies, downsampling, [continuous aggregation](https://docs.greptime.com/user-guide/flow-computation/overview), explicit table partitioning, and [inverted / skipping / fulltext indexes](https://docs.greptime.com/user-guide/manage-data/data-index) |
|
||||
|
||||
Compute and storage are disaggregated: object storage holds the data, while memory and local-disk caches keep recent and frequently queried data close to compute.
|
||||
|
||||
<p align="center">
|
||||
<a href="https://github.com/GreptimeTeam/greptimedb/raw/main/docs/overview.png" target="_blank" rel="noopener">
|
||||
<img alt="GreptimeDB Overview" src="docs/overview.png" width="900px">
|
||||
</a>
|
||||
</p>
|
||||
|
||||
## Benchmarks
|
||||
|
||||
* [Agent RCA Bench](https://rca-bench.greptime.com/): LLM agents doing root cause analysis
|
||||
over GreptimeDB versus Prometheus + Loki + Tempo. 40% fewer wrong diagnoses, 48% fewer
|
||||
input tokens, 45% lower cost
|
||||
([write-up](https://greptime.com/blogs/2026-09-08-agent-rca-bench-interface-semantic-layer))
|
||||
* [GreptimeDB tops JSONBench's billion-record cold run test](https://greptime.com/blogs/2025-03-18-jsonbench-greptimedb-performance)
|
||||
* [TSBS Benchmark](https://github.com/GreptimeTeam/greptimedb/tree/main/docs/benchmarks/tsbs)
|
||||
* [More benchmark reports](https://docs.greptime.com/user-guide/concepts/features-that-you-concern#how-is-greptimedbs-performance-compared-to-other-solutions)
|
||||
|
||||
## Compatibility and Migration
|
||||
|
||||
Compatibility is per protocol, and query-side coverage is narrower than ingestion.
|
||||
|
||||
| | Compatible | Not compatible |
|
||||
|---|---|---|
|
||||
| **Prometheus** | Remote Write ingestion; PromQL queries | Gaps are listed in [PromQL compatibility](https://docs.greptime.com/user-guide/query-data/promql/) |
|
||||
| **Loki** | Push ingestion; dual-write through Grafana Alloy makes the [cutover gradual](https://greptime.com/blogs/2026-07-23-from-loki-to-greptimedb-dual-write-migration) | LogQL and the rest of the Loki query API |
|
||||
| **Elasticsearch** | `_bulk` ingestion in the open-source core; [QueryDSL](https://docs.greptime.com/enterprise/elasticsearch-compatible/query/) partially, in Enterprise | Most other Elasticsearch APIs |
|
||||
|
||||
## Limitations and Edition Boundary
|
||||
|
||||
Cluster deployment, object storage, the Flow engine, and every ingestion protocol listed above are in the Apache-2.0 build. Repartitioning, region migration, and index creation are manual operations there.
|
||||
|
||||
Read replicas, workload isolation, and automated repartitioning are **GreptimeDB Enterprise** features, along with enterprise security and governance. The [Enterprise overview](https://docs.greptime.com/enterprise/overview/) has the current list, and [pricing](https://www.greptime.com/pricing#differences) has the edition comparison.
|
||||
|
||||
## Architecture
|
||||
|
||||
GreptimeDB can run in two modes:
|
||||
* **Standalone** — single binary for development and small deployments.
|
||||
* **Distributed** — four components, each independently scalable:
|
||||
- **Frontend** — protocol entry (OTel, Prometheus, MySQL/PostgreSQL, gRPC, ingestion APIs for Elasticsearch/InfluxDB/Loki) and the distributed query engine. Stateless, scales horizontally.
|
||||
- **Datanode** — region engine with WAL, memtable, SST, cache, compaction, and indexes. Persists data to object storage. Elastic.
|
||||
- **Metasrv** — metadata, routing, repartitioning, and security. Backed by a pluggable KV layer (etcd or RDS).
|
||||
- **Flownode** (optional) — continuous flow computation (streaming and materialized views).
|
||||
|
||||
For deeper coverage, see the [architecture doc](https://docs.greptime.com/contributor-guide/overview/#architecture) or [DeepWiki](https://deepwiki.com/GreptimeTeam/greptimedb/1-overview).
|
||||
|
||||
<a href="https://github.com/GreptimeTeam/greptimedb/raw/main/docs/architecture.png" target="_blank" rel="noopener">
|
||||
<img alt="GreptimeDB System Overview" src="https://cdn.jsdelivr.net/gh/GreptimeTeam/greptimedb@main/docs/architecture.png">
|
||||
</a>
|
||||
|
||||
## Try GreptimeDB
|
||||
|
||||
**For AI agents** — paste this prompt into your agent:
|
||||
@@ -150,20 +78,81 @@ docker run -p 127.0.0.1:4000-4003:4000-4003 \
|
||||
--mysql-addr 0.0.0.0:4002 \
|
||||
--postgres-addr 0.0.0.0:4003
|
||||
```
|
||||
Dashboard: [http://localhost:4000/dashboard](http://localhost:4000/dashboard)
|
||||
Dashboard: [http://localhost:4000/dashboard](http://localhost:4000/dashboard)
|
||||
Or skip the install and try the [Live Demo](https://live.greptime.cloud/dashboard/?info=eyJ1c2VybmFtZSI6ImdyZXB0aW1lIiwicGFzc3dvcmQiOiJkZW1vc2Vzc2lvbiJ9&query_guide=1&utm_source=github&utm_medium=readme&utm_campaign=greptimedb#/dashboard/explore).
|
||||
|
||||
Read more in the [full Install Guide](https://docs.greptime.com/getting-started/installation/overview).
|
||||
Next: [Quickstart](https://docs.greptime.com/getting-started/quick-start), the [full Install Guide](https://docs.greptime.com/getting-started/installation/overview), [Demo Scenes](https://github.com/GreptimeTeam/demo-scene), and the [FAQ](https://docs.greptime.com/faq-and-others/faq).
|
||||
|
||||
**Troubleshooting:**
|
||||
* Cannot connect to the database? Ensure that ports `4000`, `4001`, `4002`, and `4003` are not blocked by a firewall or used by other services.
|
||||
* Failed to start? Check the container logs with `docker logs greptime` for further details.
|
||||
## Why You Might Use It
|
||||
|
||||
## Getting Started
|
||||
- You run Prometheus plus Loki or Elasticsearch and want one backend instead of three
|
||||
- You have outgrown Prometheus on cardinality or retention and don't want the Thanos/Mimir operational surface
|
||||
- You are hitting Loki's query performance limits as log volume grows
|
||||
- You need long retention on object storage without a separate analytics stack
|
||||
- You want to query telemetry with SQL, not only a domain query language
|
||||
- You are storing GenAI or agent telemetry ([OTel GenAI conventions](https://opentelemetry.io/docs/specs/semconv/gen-ai/)) alongside infrastructure signals
|
||||
|
||||
- [Quickstart](https://docs.greptime.com/getting-started/quick-start)
|
||||
- [User Guide](https://docs.greptime.com/user-guide/overview)
|
||||
- [Demo Scenes](https://github.com/GreptimeTeam/demo-scene)
|
||||
- [FAQ](https://docs.greptime.com/faq-and-others/faq)
|
||||
Learn more in [Why GreptimeDB](https://docs.greptime.com/user-guide/concepts/why-greptimedb).
|
||||
|
||||
## What's Supported
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| **Ingest** | [OpenTelemetry (OTLP)](https://docs.greptime.com/user-guide/ingest-data/for-observability/opentelemetry/), [Prometheus Remote Write](https://docs.greptime.com/user-guide/ingest-data/for-observability/prometheus/) (with [native histograms](https://docs.greptime.com/user-guide/ingest-data/for-observability/prometheus/#native-histograms) over Remote Write 2.0), [Loki Push](https://docs.greptime.com/user-guide/ingest-data/for-observability/loki), [Elasticsearch Bulk](https://docs.greptime.com/user-guide/ingest-data/for-observability/elasticsearch), [InfluxDB line protocol](https://docs.greptime.com/user-guide/protocols/influxdb-line-protocol), [gRPC](https://docs.greptime.com/user-guide/protocols/grpc/) |
|
||||
| **Query** | [SQL](https://docs.greptime.com/user-guide/query-data/overview/), [PromQL](https://docs.greptime.com/user-guide/query-data/promql/), [Jaeger-compatible trace queries](https://docs.greptime.com/user-guide/query-data/jaeger/), MySQL and PostgreSQL wire protocols |
|
||||
| **Storage** | S3, GCS, Azure Blob and S3-compatible endpoints as [primary storage](https://docs.greptime.com/user-guide/deployments-administration/configuration/#storage-options), with memory and local-disk caches |
|
||||
| **Built in** | [Pipelines](https://docs.greptime.com/user-guide/logs/use-custom-pipelines) that parse and transform logs at ingestion, retention policies, downsampling, [continuous aggregation](https://docs.greptime.com/user-guide/flow-computation/overview), explicit table partitioning, and [inverted / skipping / fulltext indexes](https://docs.greptime.com/user-guide/manage-data/data-index) |
|
||||
|
||||
Compute and storage are disaggregated: object storage holds the data, while memory and local-disk caches keep recent and frequently queried data close to compute.
|
||||
|
||||
<p align="center">
|
||||
<a href="https://github.com/GreptimeTeam/greptimedb/raw/main/docs/overview.png" target="_blank" rel="noopener">
|
||||
<img alt="GreptimeDB Overview" src="docs/overview.png" width="900px">
|
||||
</a>
|
||||
</p>
|
||||
|
||||
## Benchmarks
|
||||
|
||||
* [Agent RCA Bench](https://rca-bench.greptime.com/): LLM agents doing root cause analysis
|
||||
over GreptimeDB versus Prometheus + Loki + Tempo, 168 investigations per interface across
|
||||
six models. 40% fewer wrong diagnoses, about 48% fewer input tokens, about 45% lower
|
||||
estimated cost
|
||||
([write-up](https://greptime.com/blogs/2026-09-08-agent-rca-bench-interface-semantic-layer))
|
||||
* [JSONBench billion-record cold run: first place as of March 2025](https://greptime.com/blogs/2025-03-18-jsonbench-greptimedb-performance)
|
||||
* [TSBS Benchmark](https://github.com/GreptimeTeam/greptimedb/tree/main/docs/benchmarks/tsbs)
|
||||
* [More benchmark reports](https://docs.greptime.com/user-guide/concepts/features-that-you-concern#how-is-greptimedbs-performance-compared-to-other-solutions)
|
||||
|
||||
## Compatibility and Migration
|
||||
|
||||
Compatibility is per protocol, and query-side coverage is narrower than ingestion.
|
||||
|
||||
| | Compatible | Not compatible |
|
||||
|---|---|---|
|
||||
| **Prometheus** | Remote Write ingestion; PromQL queries | Gaps are listed in [PromQL compatibility](https://docs.greptime.com/user-guide/query-data/promql/) |
|
||||
| **Loki** | Push ingestion; dual-write through Grafana Alloy makes the [cutover gradual](https://greptime.com/blogs/2026-07-23-from-loki-to-greptimedb-dual-write-migration) | LogQL and the rest of the Loki query API |
|
||||
| **Elasticsearch** | `_bulk` ingestion in the open-source core; [QueryDSL](https://docs.greptime.com/enterprise/elasticsearch-compatible/query/) partially, in Enterprise | Most other Elasticsearch APIs |
|
||||
|
||||
## Limitations and Edition Boundary
|
||||
|
||||
Cluster deployment, object storage, the Flow engine, and every ingestion protocol listed above are in the Apache-2.0 build. Repartitioning and region migration are manual operations there.
|
||||
|
||||
Read replicas, workload isolation, and automated repartitioning are **GreptimeDB Enterprise** features, along with enterprise security and governance. The [Enterprise overview](https://docs.greptime.com/enterprise/overview/) has the current list, and [pricing](https://www.greptime.com/pricing#differences) has the edition comparison. For GreptimeDB Enterprise inquiries, [contact us](https://greptime.com/contactus).
|
||||
|
||||
## Architecture
|
||||
|
||||
GreptimeDB can run in two modes:
|
||||
* **Standalone** — single binary for development and small deployments.
|
||||
* **Distributed** — four components, each independently scalable:
|
||||
- **Frontend** — protocol endpoints and the distributed query engine. Stateless, scales horizontally.
|
||||
- **Datanode** — region engine with WAL, memtable, SST, cache, compaction, and indexes. Persists data to object storage.
|
||||
- **Metasrv** — metadata, region routing, and cluster coordination (DDL procedures, failover, region migration, repartitioning). Backed by a pluggable KV layer (etcd or RDS).
|
||||
- **Flownode** (optional) — continuous flow computation (streaming and materialized views).
|
||||
|
||||
For deeper coverage, see the [architecture doc](https://docs.greptime.com/contributor-guide/overview/#architecture) or [DeepWiki](https://deepwiki.com/GreptimeTeam/greptimedb/1-overview).
|
||||
|
||||
<a href="https://github.com/GreptimeTeam/greptimedb/raw/main/docs/architecture.png" target="_blank" rel="noopener">
|
||||
<img alt="GreptimeDB System Overview" src="https://cdn.jsdelivr.net/gh/GreptimeTeam/greptimedb@main/docs/architecture.png">
|
||||
</a>
|
||||
|
||||
## Build From Source
|
||||
|
||||
@@ -202,12 +191,10 @@ See the [Contribution Guidelines](CONTRIBUTING.md) for the full developer workfl
|
||||
|
||||
GreptimeDB is generally available, with stable APIs and regular releases. It runs in production at scale — [OceanBase Cloud](https://greptime.com/blogs/2025-07-22-user-case-obcloud-log-management-greptimedb) operates 80+ GreptimeDB clusters managing 300 TB of logs, cutting log storage cost by 60%+ after migrating from Grafana Loki. See more in [case studies](https://greptime.com/blogs/?category=Use%20Case).
|
||||
|
||||
Release lines and support windows are in the [version reference](https://docs.greptime.com/nightly/reference/about-greptimedb-version). For where the project is going, read the [v1.0 highlights](https://greptime.com/blogs/2025-11-05-greptimedb-v1-highlights), the [2026 roadmap](https://greptime.com/blogs/2026-02-11-greptimedb-roadmap-2026), and [what we mean by an observability database](https://greptime.com/blogs/2026-08-26-what-is-an-observability-database).
|
||||
Releases follow [Semantic Versioning](https://docs.greptime.com/reference/about-greptimedb-version). For where the project is going, read the [v1.0 highlights](https://greptime.com/blogs/2025-11-05-greptimedb-v1-highlights), the [2026 roadmap](https://github.com/GreptimeTeam/greptimedb/issues/7685), and [what we mean by an observability database](https://greptime.com/blogs/2026-08-26-what-is-an-observability-database).
|
||||
|
||||
## Community
|
||||
|
||||
We invite you to engage and contribute!
|
||||
|
||||
- [Slack](https://greptime.com/slack)
|
||||
- [Discussions](https://github.com/GreptimeTeam/greptimedb/discussions)
|
||||
- [Official Website](https://greptime.com/)
|
||||
@@ -218,6 +205,14 @@ We invite you to engage and contribute!
|
||||
|
||||
If GreptimeDB is useful to you, please star the repo.
|
||||
|
||||
<a href="https://www.star-history.com/?repos=GreptimeTeam%2FGreptimeDB&type=date&legend=top-left">
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/chart?repos=GreptimeTeam/GreptimeDB&type=date&theme=dark&legend=top-left" />
|
||||
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/chart?repos=GreptimeTeam/GreptimeDB&type=date&legend=top-left" />
|
||||
<img alt="Star History Chart" src="https://api.star-history.com/chart?repos=GreptimeTeam/GreptimeDB&type=date&legend=top-left" />
|
||||
</picture>
|
||||
</a>
|
||||
|
||||
<img alt="Known Users" src="https://greptime.com/logo/img/users.png"/>
|
||||
|
||||
## License
|
||||
@@ -230,17 +225,10 @@ A small set of peripheral, enterprise-only features are gated behind the
|
||||
separate [GreptimeDB Enterprise License](LICENSE-ENTERPRISE). Source files under
|
||||
that license carry an explicit Enterprise License header.
|
||||
|
||||
## Commercial Support
|
||||
|
||||
Scaling observability on your infrastructure?
|
||||
[GreptimeDB Enterprise](https://docs.greptime.com/enterprise/overview/) adds the operational,
|
||||
security, and support layer for production deployments.
|
||||
[Contact us](https://greptime.com/contactus) for details.
|
||||
|
||||
## Contributing
|
||||
|
||||
- Read our [Contribution Guidelines](CONTRIBUTING.md).
|
||||
- Explore [Internal Concepts](https://docs.greptime.com/contributor-guide/overview.html) and [DeepWiki](https://deepwiki.com/GreptimeTeam/greptimedb).
|
||||
- Explore [Internal Concepts](https://docs.greptime.com/contributor-guide/overview/) and [DeepWiki](https://deepwiki.com/GreptimeTeam/greptimedb).
|
||||
- Pick up a [good first issue](https://github.com/GreptimeTeam/greptimedb/issues?q=is%3Aissue+is%3Aopen+label%3A%22good+first+issue%22) and join the #contributors [Slack](https://greptime.com/slack) channel.
|
||||
|
||||
[](https://github.com/GreptimeTeam/greptimedb/actions/workflows/integration.yml)
|
||||
|
||||
+4
-2
@@ -190,7 +190,7 @@
|
||||
| `region_engine.mito.experimental_series_index_maintenance_interval` | String | `5m` | Interval between series-index maintenance runs. Zero uses the default of 5 min. |
|
||||
| `region_engine.mito.experimental_series_index_bucket_width` | String | `5days` | Requested minimum series-index bucket width (default: 5 days), rounded up to<br/>an exact multiple of each region's compaction time window. |
|
||||
| `region_engine.mito.max_background_flushes` | Integer | Auto | Max number of running background flush jobs (default: 1/2 of cpu cores). |
|
||||
| `region_engine.mito.max_background_compactions` | Integer | Auto | Max number of running background compaction jobs (default: 1/4 of cpu cores). |
|
||||
| `region_engine.mito.max_background_compactions` | Integer | Auto | Max number of running background compaction jobs (default: 1/4 of cpu cores).<br/>The same limit bounds engine-wide admission of local compaction units and<br/>the merge-output budget of each automatic per-region pick. Outputs sharing<br/>inputs form one unit. Expired SSTs may add one expiration-only unit outside<br/>the merge-output budget; it still consumes a slot in the same admission limit.<br/>Manual compaction keeps using the request's parallelism. |
|
||||
| `region_engine.mito.max_background_purges` | Integer | Auto | Max number of running background purge jobs (default: number of cpu cores). |
|
||||
| `region_engine.mito.experimental_compaction_memory_limit` | String | 0 | Memory budget for compaction tasks.<br/>Supports absolute size (e.g., "2GiB", "512MB") or percentage of system memory (e.g., "50%").<br/>Setting it to 0 or "unlimited" disables the limit. |
|
||||
| `region_engine.mito.experimental_compaction_on_exhausted` | String | wait | Behavior when compaction cannot acquire memory from the budget.<br/>Options: "wait" (default, 10s), "wait(<duration>)", "fail" |
|
||||
@@ -276,6 +276,7 @@
|
||||
| `pipeline` | -- | -- | The pipeline options. |
|
||||
| `pipeline.cache_ttl` | String | `10s` | Time to live of the local pipeline cache. Default is `10s`. |
|
||||
| `pipeline.allow_vrl_host_access` | Bool | `false` | Allow VRL to access the server environment, filesystem, hostname, local timezone,<br/>network, and logs. Default is false. Enable only for trusted pipeline authors.<br/>Applies to pipeline creation, execution, and dry-runs. Requires a restart. |
|
||||
| `pipeline.ignore_errors` | Bool | `false` | Default for the HTTP log ingestion and pipeline dry-run `ignore_errors` parameter.<br/>Explicit request values override this setting. Malformed input may be discarded,<br/>and invalid custom timestamps in identity ingestion fall back to server time.<br/>Pipeline execution errors are controlled separately by `skip_error`.<br/>Default is false. Requires a restart. |
|
||||
| `event_recorder` | -- | -- | Configuration options for the event recorder. |
|
||||
| `event_recorder.ttl` | String | `90d` | TTL for the events table that will be used to store the events. Default is `90d`. |
|
||||
| `event_recorder.event_types` | Array | All | Event types to record. Current available event types: `create_database`,<br/>`alter_database`, `drop_database`, `create_flow`, `drop_flow`,<br/>`create_table`, `create_logical_tables`, `alter_table`, `alter_logical_tables`,<br/>`drop_table`, `undrop_table`, `purge_dropped_table`, `truncate_table`,<br/>`create_view`, `drop_view`, `admin_function`, `reconcile_catalog`,<br/>`reconcile_database`, `reconcile_table`, `reconcile_logical_tables`.<br/>When omitted, all current and future event types are recorded.<br/>Set to an empty array to disable event recording. |
|
||||
@@ -438,6 +439,7 @@
|
||||
| `pipeline` | -- | -- | The pipeline options. |
|
||||
| `pipeline.cache_ttl` | String | `10s` | Time to live of the frontend-local pipeline cache. A pipeline created or deleted on<br/>another frontend takes effect on this one after at most this duration. |
|
||||
| `pipeline.allow_vrl_host_access` | Bool | `false` | Allow VRL to access the server environment, filesystem, hostname, local timezone,<br/>network, and logs. Default is false. Enable only for trusted pipeline authors.<br/>Applies to pipeline creation, execution, and dry-runs. Requires a restart. |
|
||||
| `pipeline.ignore_errors` | Bool | `false` | Default for the HTTP log ingestion and pipeline dry-run `ignore_errors` parameter.<br/>Explicit request values override this setting. Malformed input may be discarded,<br/>and invalid custom timestamps in identity ingestion fall back to server time.<br/>Pipeline execution errors are controlled separately by `skip_error`.<br/>Default is false. Requires a restart. |
|
||||
| `event_recorder` | -- | -- | Configuration options for the event recorder. |
|
||||
| `event_recorder.ttl` | String | `90d` | TTL for the events table that will be used to store the events. Default is `90d`. |
|
||||
| `event_recorder.event_types` | Array | All | Event types to record. Current available event type: `admin_function`.<br/>When omitted, all current and future event types are recorded.<br/>Set to an empty array to disable event recording. |
|
||||
@@ -671,7 +673,7 @@
|
||||
| `region_engine.mito.experimental_series_index_maintenance_interval` | String | `5m` | Interval between series-index maintenance runs. Zero uses the default of 5 min. |
|
||||
| `region_engine.mito.experimental_series_index_bucket_width` | String | `5days` | Requested minimum series-index bucket width (default: 5 days), rounded up to<br/>an exact multiple of each region's compaction time window. |
|
||||
| `region_engine.mito.max_background_flushes` | Integer | Auto | Max number of running background flush jobs (default: 1/2 of cpu cores). |
|
||||
| `region_engine.mito.max_background_compactions` | Integer | Auto | Max number of running background compaction jobs (default: 1/4 of cpu cores). |
|
||||
| `region_engine.mito.max_background_compactions` | Integer | Auto | Max number of running background compaction jobs (default: 1/4 of cpu cores).<br/>The same limit bounds engine-wide admission of local compaction units and<br/>the merge-output budget of each automatic per-region pick. Outputs sharing<br/>inputs form one unit. Expired SSTs may add one expiration-only unit outside<br/>the merge-output budget; it still consumes a slot in the same admission limit.<br/>Manual compaction keeps using the request's parallelism. |
|
||||
| `region_engine.mito.max_background_purges` | Integer | Auto | Max number of running background purge jobs (default: number of cpu cores). |
|
||||
| `region_engine.mito.experimental_compaction_memory_limit` | String | 0 | Memory budget for compaction tasks.<br/>Supports absolute size (e.g., "2GiB", "512MB") or percentage of system memory (e.g., "50%").<br/>Setting it to 0 or "unlimited" disables the limit. |
|
||||
| `region_engine.mito.experimental_compaction_on_exhausted` | String | wait | Behavior when compaction cannot acquire memory from the budget.<br/>Options: "wait" (default, 10s), "wait(<duration>)", "fail" |
|
||||
|
||||
@@ -580,6 +580,11 @@ compress_manifest = false
|
||||
#+ max_background_flushes = 4
|
||||
|
||||
## Max number of running background compaction jobs (default: 1/4 of cpu cores).
|
||||
## The same limit bounds engine-wide admission of local compaction units and
|
||||
## the merge-output budget of each automatic per-region pick. Outputs sharing
|
||||
## inputs form one unit. Expired SSTs may add one expiration-only unit outside
|
||||
## the merge-output budget; it still consumes a slot in the same admission limit.
|
||||
## Manual compaction keeps using the request's parallelism.
|
||||
## @toml2docs:none-default="Auto"
|
||||
#+ max_background_compactions = 2
|
||||
|
||||
|
||||
@@ -519,6 +519,12 @@ cache_ttl = "10s"
|
||||
## network, and logs. Default is false. Enable only for trusted pipeline authors.
|
||||
## Applies to pipeline creation, execution, and dry-runs. Requires a restart.
|
||||
allow_vrl_host_access = false
|
||||
## Default for the HTTP log ingestion and pipeline dry-run `ignore_errors` parameter.
|
||||
## Explicit request values override this setting. Malformed input may be discarded,
|
||||
## and invalid custom timestamps in identity ingestion fall back to server time.
|
||||
## Pipeline execution errors are controlled separately by `skip_error`.
|
||||
## Default is false. Requires a restart.
|
||||
ignore_errors = false
|
||||
|
||||
## Configuration options for the event recorder.
|
||||
[event_recorder]
|
||||
|
||||
@@ -795,6 +795,11 @@ compress_manifest = false
|
||||
#+ max_background_flushes = 4
|
||||
|
||||
## Max number of running background compaction jobs (default: 1/4 of cpu cores).
|
||||
## The same limit bounds engine-wide admission of local compaction units and
|
||||
## the merge-output budget of each automatic per-region pick. Outputs sharing
|
||||
## inputs form one unit. Expired SSTs may add one expiration-only unit outside
|
||||
## the merge-output budget; it still consumes a slot in the same admission limit.
|
||||
## Manual compaction keeps using the request's parallelism.
|
||||
## @toml2docs:none-default="Auto"
|
||||
#+ max_background_compactions = 2
|
||||
|
||||
@@ -1151,6 +1156,12 @@ cache_ttl = "10s"
|
||||
## network, and logs. Default is false. Enable only for trusted pipeline authors.
|
||||
## Applies to pipeline creation, execution, and dry-runs. Requires a restart.
|
||||
allow_vrl_host_access = false
|
||||
## Default for the HTTP log ingestion and pipeline dry-run `ignore_errors` parameter.
|
||||
## Explicit request values override this setting. Malformed input may be discarded,
|
||||
## and invalid custom timestamps in identity ingestion fall back to server time.
|
||||
## Pipeline execution errors are controlled separately by `skip_error`.
|
||||
## Default is false. Requires a restart.
|
||||
ignore_errors = false
|
||||
|
||||
## Configuration options for the event recorder.
|
||||
[event_recorder]
|
||||
|
||||
@@ -1,14 +1,17 @@
|
||||
# Metric snapshot benchmark on AWS S3
|
||||
|
||||
The manual `Metric Snapshot S3 Benchmark` workflow tests packed Metric export and
|
||||
restore against real S3 in `ap-southeast-1`. It must first exist on the repository's
|
||||
default branch for GitHub to register `workflow_dispatch`. It was validated on AWS
|
||||
restore against real S3 in the configured CI bucket region. It must first exist on
|
||||
the repository's default branch for GitHub to register `workflow_dispatch`. It was validated on AWS
|
||||
by run [38544464731](https://github.com/GreptimeTeam/greptimedb/actions/runs/38544464731);
|
||||
[#9573](https://github.com/GreptimeTeam/greptimedb/pull/9573) records its conditions and results.
|
||||
|
||||
## Run
|
||||
|
||||
Use the repository's existing EC2 runner configuration and CI S3 credentials.
|
||||
`AWS_CI_TEST_BUCKET_REGION` and `EC2_RUNNER_REGION` must be nonempty and equal;
|
||||
for example, both can be `us-east-1`. The configured subnet, security group and
|
||||
AMI (if explicitly supplied) must also belong to the runner region.
|
||||
The workflow passes credentials only through CI; no local AWS credentials are
|
||||
needed. Source, target and CLI use the same immutable image. This image's source
|
||||
SHA and required CLI capabilities have been checked:
|
||||
@@ -20,6 +23,7 @@ gh workflow run metric-snapshot-s3-bench.yml \
|
||||
-f expected_commit=f690bbb2040865c0d22b0b57d51612b60ae27cd0 \
|
||||
-f logical_tables_per_group=10000 \
|
||||
-f benchmark_timeout_minutes=240 \
|
||||
-f ec2_hourly_usd=0.9408 \
|
||||
-f prior_spend_usd=0
|
||||
```
|
||||
|
||||
@@ -28,9 +32,12 @@ earlier cloud attempts in the campaign, including failed setup and cleanup.
|
||||
Do not reset the estimate to zero when retrying. The workflow accepts 50–10,000
|
||||
logical tables per group and a 30–240 minute benchmark job timeout.
|
||||
|
||||
The runner is fixed at `c6id.4xlarge` (16 vCPU, 32 GiB RAM). At the recorded
|
||||
Singapore Linux on-demand estimate of $0.9408/hour, the default attempt reserves
|
||||
$6.4392: four benchmark hours, 45 minutes of provisioning, 10 minutes for queueing,
|
||||
The runner is fixed at `c6id.4xlarge` (16 vCPU, 32 GiB RAM). Set
|
||||
`ec2_hourly_usd` to a positive, finite hourly budget estimate appropriate for the
|
||||
selected region and instance. Its default $0.9408/hour preserves the historical
|
||||
Singapore estimate; it is not a live regional price or a guaranteed upper bound.
|
||||
The same estimate is used for preflight reservation and the final cost summary.
|
||||
At that default rate, the default attempt reserves $6.4392: four benchmark hours, 45 minutes of provisioning, 10 minutes for queueing,
|
||||
20 minutes of cleanup, and $1.50 for S3, disk and IPv4 costs. Preflight rejects prior spend at or above
|
||||
$15, or an attempt whose reserve would exceed the cumulative $20 budget.
|
||||
These estimates and checks are not an AWS hard spending cap or an AWS bill.
|
||||
|
||||
@@ -31,7 +31,7 @@ Object storage is already provisioned, already durable across zones, and already
|
||||
# Non-goals
|
||||
|
||||
- Distributed mode. The provider is rejected when a datanode is controlled by a metasrv; the metasrv side has no allocation logic for it yet.
|
||||
- Persistence of the obsolete watermarks that flushes and truncates move. Mito re-establishes each of them when it opens a region, which is what garbage collection reasons from. Only the release of a region that is never opened again, after a drop or an offline cleanup, is persisted, as described under *Entry ids*.
|
||||
- Persistence of the obsolete watermarks that flushes and truncates move. Mito re-establishes each of them when it opens a region, which is what garbage collection reasons from. A close persists a bounded release through the region's safe recovery watermark; a drop or offline cleanup persists the permanent release described under *Entry ids*. Ordinary flush and truncate watermarks are not persisted by the store.
|
||||
- Matching Raft Engine's write latency. The provider trades latency for the absence of local durable WAL state.
|
||||
- Making standalone metadata independent of local disk. The metadata store is unchanged by this RFC.
|
||||
|
||||
@@ -106,7 +106,7 @@ Two rules keep every new id of a region above every id it already has, on a pref
|
||||
|
||||
The second rule is the sequence floor of `obsolete`. Mito calls `obsolete` with the manifest's `flushed_entry_id` when it opens a region, and the actor applies the watermark and a floor derived from that entry id together: the next object sequence is raised to `(entry_id >> 20) + 1` unless it is there already, while zero, the watermark of a region without entries, names no object and needs no floor, so that a watermark assigned under another prefix, or one whose object this prefix no longer holds, is never passed by a new id. The floor moves only the next sequence, never the chain: the next batch still links to its predecessor, so a skipped sequence leaves no gap in the history recovery replays. While the open batch holds ids under the next sequence, the call is refused with a retryable error and records neither the watermark nor the floor, because those ids would fall below the floor. In the `enqueued` mode an id the store itself handed out needs no floor, even before it is durable: it is never handed out again while the store runs, so every later id of the region is greater. In the current single-prefix layout the floor never needs to move for a prefix that holds the region's history, since every watermark Mito hands the store then names an object below the next sequence. A watermark above the newest object holding entries that the store found means the prefix does not hold that history: the history check under *Log store* refuses such an open before Mito calls `obsolete`, and the floor moves only when `accept_missing_history` accepted the loss. Otherwise the rule exists for the cross-prefix cases under *Alignment with cluster mode*. No additional persisted state is introduced.
|
||||
|
||||
Garbage collection deletes the objects below a reclaim boundary that the store persists in every header, so that recovery can tell a collected predecessor from one that never landed. The boundary is computed from the catalog and the watermarks the store already keeps: each region with a recorded watermark contributes the sequence of its first indexed object holding a segment whose largest entry id is above the watermark; a region without a recorded watermark contributes its first indexed object; a region whose watermark is the maximum entry id, after a release in full, contributes nothing; the boundary is the smallest contribution, or the last indexed sequence plus one when nothing contributes, and it never decreases. Whether a segment is flushed is decided per segment from the footer, on the full entry id, so a watermark that stops in the middle of an object keeps the object. The boundary is recomputed after every successful `obsolete`, after every release and after every object is indexed; Mito calls `obsolete` after a flush, after a truncate, when it drops a region and when it opens one, so a restart re-establishes the watermark of every region Mito opens again, and the boundary advances on the same rule. A region that is never opened again needs the release described below. Every sealed batch carries the boundary current at sealing and the start object carries the boundary recovery found, or its own sequence when the recovered chain holds no segment, so a boundary is always at or below the sequence of the object carrying it. The boundary that permits deletion is the one carried by the last indexed object; the boundary of a batch whose create failed or is in flight permits nothing.
|
||||
Garbage collection deletes the objects below a reclaim boundary that the store persists in every header, so that recovery can tell a collected predecessor from one that never landed. The boundary is computed from the catalog and the watermarks the store already keeps: each region with a recorded watermark contributes the sequence of its first indexed object holding a segment whose largest entry id is above the watermark; a region without a recorded watermark contributes its first indexed object; a region whose watermark is the maximum entry id, after a release in full, contributes nothing; the boundary is the smallest contribution, or the last indexed sequence plus one when nothing contributes, and it never decreases. Whether a segment is flushed is decided per segment from the footer, on the full entry id, so a watermark that stops in the middle of an object keeps the object. The boundary is recomputed after every successful `obsolete`, after every release and after every object is indexed; Mito calls `obsolete` after a flush, after a truncate, when it drops a region and when it opens one, so a restart re-establishes the watermark of every region Mito opens again, and the boundary advances on the same rule. Closing a region while the WAL is running queues its safe watermark through the bounded release described below. Once the record is durable, recovery retains that progress even if the region is not reopened; closes after WAL shutdown retain extra history instead. A region that is dropped or cleaned up offline uses a permanent release. Every sealed batch carries the boundary current at sealing and the start object carries the boundary recovery found, or its own sequence when the recovered chain holds no segment, so a boundary is always at or below the sequence of the object carrying it. The boundary that permits deletion is the one carried by the last indexed object; the boundary of a batch whose create failed or is in flight permits nothing.
|
||||
|
||||
Every present object with a sequence below the durable boundary is deletable, on the chain or not: the objects the catalog indexes, the objects recovery listed but did not index, the objects of an earlier epoch that the start object moved past, and the sequences of batches that failed in this run, whose objects may or may not exist. A collection starts after a successful `obsolete`, after a release and after an indexing that raised the durable boundary. Deletes run in the background, at most four at a time and in no particular order, and never hold up admission, sealing, uploads or acknowledgements; an indexed object is unindexed only after its delete succeeded, and the WAL holes recorded for it are dropped with it. Every deleted object is counted in `greptime_logstore_object_store_wal_deleted_objects_total`; a failed delete is logged, counted in `greptime_logstore_object_store_wal_failed_deletes_total` and retried at the next collection, and the object stays indexed meanwhile. An object deleted but not yet unindexed when the process crashes is simply absent at the next recovery, which lists the prefix. Nothing is collected once `stop` has begun or while the store is poisoned; a delete in flight when `stop` begins runs to completion before `stop` returns, and the actor settles every attempt it abandons when it exits.
|
||||
|
||||
@@ -143,22 +143,28 @@ The mode also needs a barrier that the durable mode gets for free. An entry id t
|
||||
| Situation | Sequence | Waiters of the batch | Store |
|
||||
| --- | --- | --- | --- |
|
||||
| create succeeds, or identical retry | advances | acknowledged in sequence order | healthy |
|
||||
| transient I/O error, `durable` mode | consumed and never reused, nor are the sequences of the other failed batches | this and every batch that is not indexed fail, including those whose objects were created; a create still in flight completes as an orphan | healthy: the next batch links to the last indexed object |
|
||||
| transient I/O error, `durable` mode | consumed and never reused, nor are the sequences of the other failed batches | this and every batch that is not indexed fail, including those whose objects were created; a create still in flight completes as an orphan | healthy: the next batch links to the last indexed object; retained release records back off before a release-only retry |
|
||||
| an object of an earlier epoch holds the sequence, `durable` mode | consumed and never reused | as for a transient I/O error | healthy |
|
||||
| transient I/O error, `enqueued` mode | unchanged | already acknowledged, except a release, which waits for the repeat | healthy: the create is repeated after a short delay |
|
||||
| I/O error that requires intervention, `enqueued` mode | unchanged | already acknowledged, except a release, which fails with a retryable error while its record stays in the backlog; later appends and releases are rejected with that error until a create succeeds | failing: the lowest pending create is repeated alone with backoff; the first create that succeeds ends it |
|
||||
| any I/O error, `enqueued` mode after `stop` began | unchanged | already acknowledged, except a release, which fails with the stopped error | the backlog is dropped and `stop` reports the loss |
|
||||
| transient I/O error, `enqueued` mode | unchanged | already acknowledged, except a permanent release, which waits for the repeat | healthy: the create is repeated after a short delay |
|
||||
| I/O error that requires intervention, `enqueued` mode | unchanged | already acknowledged, except a permanent release, which fails with a retryable error while its record stays in the backlog; later appends and permanent releases are rejected with that error until a create succeeds | failing: the lowest pending create is repeated alone with backoff; the first create that succeeds ends it |
|
||||
| any I/O error, `enqueued` mode after `stop` began | unchanged | already acknowledged, except a permanent release, which fails with the stopped error | the backlog is dropped and `stop` reports the loss |
|
||||
| an object of the same or a later epoch holds the sequence, or any conflicting object in the `enqueued` mode | unchanged | every unacknowledged waiter fails, including those of batches whose objects were created but not yet indexed; an `enqueued` acknowledgement already returned cannot be revoked | poisoned |
|
||||
| encoding or catalog error | unchanged | every unacknowledged waiter fails, including those of batches whose objects were created but not yet indexed; an `enqueued` acknowledgement already returned cannot be revoked | poisoned |
|
||||
| create succeeds at the last representable sequence | cannot advance | acknowledged | poisoned: no later batch can be allocated a sequence, every later append fails |
|
||||
| the start object meets an object of an earlier epoch | moves to the next sequence | none admitted yet | construction continues |
|
||||
| the start object meets an object of the same or a later epoch, or its create has an unknown outcome | unchanged | none admitted yet | construction fails; an unknown outcome is retryable |
|
||||
|
||||
A release is a waiter of the batch that carries its record in both modes: it returns when the batch is indexed and fails whenever the batch fails. A store cannot be constructed on a prefix whose largest object already carries the maximum sequence. A poisoned store fails every `LogStore` operation except `stop` with the same terminal error; in particular `obsolete` can no longer move a watermark. In the `durable` mode transient errors are not retried inside the store, but a failed create is reconciled once: the store immediately reads the key back, accepts the batch if the object exists with identical bytes, treats it as a conflict if the bytes differ, and reports the transient error only when the key is absent or that read fails too. So a lost response alone does not fail the append. When the append does fail, neither the store nor Mito keeps the batch: it surfaces through Mito to the caller of the write, and a retry is a new write by the caller under a new sequence. If the create had in fact succeeded and both its response and the read-back were lost, or its request lands only later, the object is an orphan as soon as a later object is acknowledged. Retrying the batch itself inside the store in the `durable` mode would only hide the latency and would hold writes up for as long as an outage lasts; the `enqueued` mode repeats the create with the same bytes, so a create that succeeded without a response is accepted as an identical retry.
|
||||
A permanent release (`release_region` or `obsolete_all`) is a waiter of the batch that carries its record in both modes: it returns when the batch is indexed and fails whenever the batch fails. A store cannot be constructed on a prefix whose largest object already carries the maximum sequence. A poisoned store fails every `LogStore` operation except `stop` with the same terminal error; in particular `obsolete` can no longer move a watermark. In the `durable` mode a failed data batch is not retried inside the store, but a failed create is reconciled once: the store immediately reads the key back, accepts the batch if the object exists with identical bytes, treats it as a conflict if the bytes differ, and reports the transient error only when the key is absent or that read fails too. So a lost response alone does not fail the append. When the append does fail, neither the store nor Mito keeps the batch: it surfaces through Mito to the caller of the write, and a retry is a new write by the caller under a new sequence. If the create had in fact succeeded and both its response and the read-back were lost, or its request lands only later, the object is an orphan as soon as a later object is acknowledged. Retrying the batch itself inside the store in the `durable` mode would only hide the latency and would hold writes up for as long as an outage lasts; the `enqueued` mode repeats the create with the same bytes, so a create that succeeded without a response is accepted as an identical retry.
|
||||
|
||||
**Stopping.** `stop` is idempotent and awaits the actor. Once stop has begun, queued appends are not admitted, no timer or size triggered seal starts, and appends after stop, including empty ones, and releases fail with the stopped error. In the `durable` mode the release records of failed batches and of the batches dropped here are sealed into one more object, which is created before `stop` returns; `stop` reports the error when that create fails too. In the `durable` mode the open batch and every sealed batch whose create has not started are dropped: their waiters receive the stopped error. A create that is already in flight runs to completion; if it succeeds while its batch is still pending, the batch is indexed in order and acknowledged. A transient failure after stop began fails every batch that is not indexed, as it does while the store runs, and those batches receive the stopped error; a create of such a batch that completes later is an orphan and acknowledges nothing. A create that finds a conflicting object of the same or a later epoch after stop began poisons the store as it would while the store runs, but the waiters of the batches that are not indexed receive the stopped error, the conflict is kept only as the terminal error, and `stop` returns successfully once the creates in flight have completed, unless the poisoning drops release records, which `stop` reports by returning the conflict. In the `enqueued` mode the held-back appends receive the stopped error, the open batch is sealed and the whole backlog is uploaded before `stop` returns, by a failing store too; any object store failure in that phase drops the backlog and `stop` returns the error, as described under *Acknowledgement*. A durability wait still pending when the actor exits receives the stopped error, and a delete already in flight runs to completion before `stop` returns.
|
||||
**Bounded releases on close.** `LogStore::release_entries(provider, region_id, entry_id)` queues an inclusive safe recovery watermark. Mito stops the region first, then computes that watermark from one Version snapshot with `cap_wal_release`: the minimum of `flushed_entry_id` and the `after` bounds of this node's pending tails. Both ordinary close and successful flush-on-close use this path; close-time flush eligibility is unchanged. Other WAL providers default to a no-op. In `enqueued` mode the actor clamps both the in-memory and persisted release watermark to the region's durable entry ID at admission, as `obsolete` does. The sequence floor still uses the requested ID so later appends cannot reuse IDs covered by the request.
|
||||
|
||||
**Reading.** `read(provider, entry_id)` returns the region's entries with id at least `entry_id`, in order, fetching only that region's segments with range reads and decoding nothing else, and hides entries at or below the region's obsolete watermark. `obsolete` records the watermark in memory, clamped to the durable entry id in the `enqueued` mode; the watermark is re-established after a restart because Mito calls `obsolete` with the manifest's `flushed_entry_id` when it opens a region, so the store persists no watermark of a region Mito opens again. The release of a region, which `obsolete_all` and `release_region` make, is persisted as described under *Entry ids*. `obsolete_all` hides the whole region. `latest_entry_id` is not affected by the watermark. Every method taking a provider requires `Provider::ObjectStore` with the store's prefix and the caller's region.
|
||||
The actor fences later entry IDs above the requested watermark, updates its in-memory obsolete state, and coalesces pending records by region using the maximum watermark. It acknowledges admission without sealing or waiting for an upload. The next sealed batch carries those records alongside ordinary entries; a timer tick can seal a release-only batch. Failed records remain pending for a later create. While the store is failing or its sealed-batch count, unpersisted bytes or age reaches a backlog threshold, bounded releases are still admitted and coalesced, but timer ticks defer release-only sealing. In `durable` mode any rollback that leaves pending release records starts exponential backoff for the next release-only seal, including a failed data batch that carried releases. The first delay is 100 ms; repeated failures double it up to 30 seconds. The failed sequences remain consumed, and the retained records are coalesced into a later batch. Indexing a batch carrying release records resets the delay to 100 ms. Ordinary data batches and explicit permanent releases can carry pending records before the delay expires; shutdown also seals them despite the delay and backlog thresholds. A rollback that retains releases logs its error and the next release-only retry delay on the first failure, then at most once per 60 seconds until a batch carrying releases is indexed. Shutdown processes pending records using the existing acknowledgement-mode shutdown rules. A crash before persistence may lose reclamation progress and retain extra history. The WAL stops before regions close during shutdown. Bounded hints submitted after stopping begins are ignored successfully, without adding records, warnings or failure counts; their progress must be re-established if the region reopens. A genuine admission failure while the store is running does not fail close: it is logged and increments `greptime_mito_wal_release_admission_failure_total`. The persisted-record metric continues to count persistence, not admission.
|
||||
|
||||
Bounded releases reuse the existing release segment and object format. The release segment's footer entry ID is derived from the sequence of the object carrying it, not from the watermarks in its payload. Recovery includes that segment in `history_end`. Thus a later release of a lower-watermark region still carries history evidence past an earlier release that collection removed. Empty start objects do not provide that evidence, and the existing location check is unchanged. Physical deletion continues to use only the durable reclaim boundary.
|
||||
|
||||
**Stopping.** `stop` is idempotent and awaits the actor. Once stop has begun, queued appends are not admitted, no timer or size triggered seal starts, and appends after stop, including empty ones, and permanent releases fail with the stopped error. Later bounded releases are ignored successfully and retain extra history. In the `durable` mode pending bounded releases and the release records of failed batches and of the batches dropped here are sealed into one more object, which is created before `stop` returns; `stop` reports the error when that create fails too. In the `durable` mode the open batch and every sealed batch whose create has not started are dropped: their waiters receive the stopped error. A create that is already in flight runs to completion; if it succeeds while its batch is still pending, the batch is indexed in order and acknowledged. A transient failure after stop began fails every batch that is not indexed, as it does while the store runs, and those batches receive the stopped error; a create of such a batch that completes later is an orphan and acknowledges nothing. A create that finds a conflicting object of the same or a later epoch after stop began poisons the store as it would while the store runs, but the waiters of the batches that are not indexed receive the stopped error, the conflict is kept only as the terminal error, and `stop` returns successfully once the creates in flight have completed, unless the poisoning drops release records, which `stop` reports by returning the conflict. In the `enqueued` mode the held-back appends receive the stopped error, the open batch is sealed and the whole backlog is uploaded before `stop` returns, by a failing store too; any object store failure in that phase drops the backlog and `stop` returns the error, as described under *Acknowledgement*. A durability wait still pending when the actor exits receives the stopped error, and a delete already in flight runs to completion before `stop` returns.
|
||||
|
||||
**Reading.** `read(provider, entry_id)` returns the region's entries with id at least `entry_id`, in order, fetching only that region's segments with range reads and decoding nothing else, and hides entries at or below the region's obsolete watermark. `obsolete` records the watermark in memory, clamped to the durable entry id in the `enqueued` mode; the watermark is re-established after a restart because Mito calls `obsolete` with the manifest's `flushed_entry_id` when it opens a region, so the store persists no ordinary flush or truncate watermark, but does persist the safe watermark queued when a region closes. The release of a region, which `obsolete_all` and `release_region` make, is persisted as described under *Entry ids*. `obsolete_all` hides the whole region. `latest_entry_id` is not affected by the watermark. Every method taking a provider requires `Provider::ObjectStore` with the store's prefix and the caller's region.
|
||||
|
||||
**History check.** A region persists its prefix, not the object store that holds the prefix, so pointing `storage_provider`, or the bucket or root of the provider it names, at another location, or deleting the objects under the prefix, would let every region open against a prefix without its history, replay nothing and lose its acknowledged writes that were not flushed. Two invariants of a prefix expose such a location without any persisted state of their own. A prefix that a store opened is never empty afterwards, unless the store withdrew its start object as described below: the store writes its start object before it admits an append, and collection deletes only objects below the durable boundary, the boundary of the last indexed object, which is at or below that object's own sequence, since a larger one fails the header check. And a watermark a region persisted names an object at or below the newest object holding entries that any later recovery of the prefix indexes: the entry it names was durable and indexed when the watermark was persisted, as described under *Acknowledgement*; no durable boundary passes the newest object holding entries, since a batch carries at most the sequence after the last indexed object and a start object carries the boundary recovery found, so collection keeps that object and recovery indexes it on the chain of the tip. The segment of release records counts as entries: it never holds the reclaim boundary, so an object holding only release records can be the one that collection keeps while it deletes every older object. Objects without segments, start objects and the like, do not move it. `LogStore::check_region_history(provider, entry_id)` therefore reports the history of the provider's region as missing when recovery found no object under the prefix, or when `entry_id` names an object above the newest object holding entries that recovery indexed, unless the catalog holds the region's entries through `entry_id`, as it does for a region written since the store opened, or the region's history starts in the store: Mito calls `LogStore::start_region_history` when it creates a region, before it persists the region's manifest, and an open that accepted a missing history records the region the same way, in memory, so the region reopens on the same store without any entry and is counted once. Both methods default to accepting and to doing nothing, so Raft Engine and Kafka are unchanged. Mito calls it before it replays an existing region from its persisted state, on open, on catch-up and when a create finds the region already present, with the larger of the manifest's `flushed_entry_id` and `truncated_entry_id`; a region whose options skip the WAL keeps no history there and is not checked, nor is a region with the noop provider. A missing history fails the open, and such a create, which does not fall back to creating the region over its manifest, with an `InvalidArguments` error that names the region, the prefix, the configured storage provider with its scheme, bucket and root, and the two ways forward below; in standalone a region that fails to open stops startup. The check runs before Mito calls `obsolete` with the watermark, so the sequence floor never hides a missing history.
|
||||
|
||||
@@ -180,7 +186,7 @@ Mito maps `WalOptions::ObjectStore { prefix }` to `Provider::object_store_provid
|
||||
|
||||
The scalar options are validated before any store or engine exists: the prefix must be non-empty, relative and free of empty or `..` components; `flush_interval` at least 10 ms; `max_batch_bytes`, `max_unpersisted_bytes` and `max_unpersisted_age` positive. `storage_provider` is resolved later, once the object store manager has been built and before the log store and the Mito engine are: empty selects the default store, otherwise the name must match a configured provider. Failures in both stages are `InvalidArguments` naming the field, and both happen before any WAL object is touched. The datanode requires a node id to derive the node prefix it opens the store under, and the standalone bootstrap derives the same prefix for the WAL options it allocates.
|
||||
|
||||
`DatanodeBuilder` keeps the store handle from the moment it is created and stops it if a later build step fails. On success the handle moves into `Datanode`, whose shutdown stops the store after the region server. Shutdown of the datanode and of the standalone instance is best-effort and ordered: every step runs, the first error is returned, so a failing region engine does not leave the WAL actor alive.
|
||||
`DatanodeBuilder` keeps the store handle from the moment it is created and stops it if a later build step fails. On success the handle moves into `Datanode`, whose shutdown stops the store before the region server, so pending WAL durability waits settle before regions close. Shutdown of the datanode and of the standalone instance is best-effort and ordered: every step runs, the first error is returned, so a failing region engine does not leave the WAL actor alive.
|
||||
|
||||
## Configuration
|
||||
|
||||
@@ -340,9 +346,9 @@ Simpler catalog, but every region then produces its own timer-driven object, so
|
||||
|
||||
- Write latency under the `durable` mode is the time until the batch seals (up to `flush_interval`, 100 ms by default), plus waiting for every earlier object, plus one PUT. A serial writer waits for the next seal, so its extra latency over Raft Engine is the interval minus the base insert cost modulo the interval, and concurrency does not close the gap: measured within one session on a laptop it was about 23% of throughput at concurrency 1 and about 28% at concurrency 8, and on S3 against Raft Engine on a local NVMe store the `durable` mode reached 31% of Raft Engine's throughput at concurrency 1 and 54% at concurrency 8, a serial writer being bound to one batch per interval, while the `enqueued` mode matched it, see *Write path measurements* and *Cloud write path measurements*.
|
||||
- Every object costs a request. Timer-triggered sealing creates at most one object per interval per node, ten per second at the default; the `enqueued` mode can seal earlier when the unpersisted backlog reaches a threshold, and the batch seals on size only when the admitted bytes reach `max_batch_bytes` before the next tick. Under sustained load on S3 the timer ceiling was reached, about 600 creates per minute per node, about $0.18 per node-hour at the S3 standard list price.
|
||||
- Garbage collection keeps every object at or above the reclaim boundary, so a region that is written but rarely flushed, or never flushed, holds the boundary at its first object and keeps every later object the prefix shares with other regions; recovery time grows with the number of retained objects. A prefix that receives no appends cannot persist a higher boundary, so an idle prefix is collected only after its next object; a release seals that object itself.
|
||||
- Garbage collection keeps every object at or above the reclaim boundary, so a region that is written but rarely flushed, or never flushed, holds the boundary at its first object and keeps every later object the prefix shares with other regions; recovery time grows with the number of retained objects. An idle prefix advances its durable boundary when another object is sealed. A permanent release seals immediately; a pending bounded release lets a timer tick seal a release-only object even without appends.
|
||||
- A dropped region stays unreleased, and holds the reclaim boundary for good, after a crash between the deletion of its table's metadata and a durable release record, or after a crash that follows a failed release before any later create succeeds; `indexed_objects` then only grows. The first window is a gap of the drop procedure for every WAL provider, issue #9577. See *Entry ids*.
|
||||
- A release costs one object of its own and waits for every object sealed before it, in the `enqueued` mode as well, so dropping a region waits for the uploads ahead of its release record; when they fail, or the store is stopped or poisoned, the drop succeeds all the same and logs the failure; a stopped or poisoned store leaves the region unreleased.
|
||||
- A permanent release costs one object of its own and waits for every object sealed before it, in the `enqueued` mode as well, so dropping a region waits for the uploads ahead of its release record; when they fail, or the store is stopped or poisoned, the drop succeeds all the same and logs the failure; a stopped or poisoned store leaves the region unreleased.
|
||||
- Every open of the store writes one start object without segments, one extra PUT per open, and every object carries a 54-byte header. Orphans, the objects of failed batches that were stored anyway, hold storage together with the rows Mito wrote again after those failures until garbage collection deletes them.
|
||||
- Object-sequence-major entry ids consume 20 bits per object for positions, which caps a region at about a million entries per object; the batch seals when the cap is reached. Sequence numbers are 44 bits wide as a result, enough for one object per second for half a million years.
|
||||
|
||||
|
||||
@@ -0,0 +1,547 @@
|
||||
---
|
||||
Feature Name: Object Store Metadata Backend — Authority and Leader Election
|
||||
Tracking Issue: TBD
|
||||
Date: 2026-11-10
|
||||
Author: Alorun
|
||||
Status: Draft for discussion
|
||||
---
|
||||
|
||||
# Summary
|
||||
Add an object-store-backed authority and leader election mechanism to GreptimeDB's Metasrv. Strongly consistent single-object reads and atomic conditional replacements maintain one fixed **Authority Head**, stored as versioned JSON in `head.json`. Its contents record the elected owner, logical epoch, diagnostic lease deadline, and write sequence. OpenDAL `Metadata` from the same object version supplies the condition for `if_not_changed(&metadata)`. Every metadata write that changes authoritative state must pass through this Head. The Head has three responsibilities:
|
||||
|
||||
- It identifies the elected owner and supplies a routing hint; the owner may already have stepped down locally.
|
||||
- It carries the fencing epoch that invalidates an old Leader.
|
||||
- It provides the single serialization point for later metadata commits.
|
||||
|
||||
This RFC defines the Authority and Leader Election contract for the first phase. A separate batching RFC will define metadata commit semantics; it will be added later. Storage layout and read semantics will be specified separately and will reuse the Head defined here.
|
||||
|
||||
# Motivation
|
||||
Metasrv currently uses etcd, MySQL, or PostgreSQL as the metadata authority and leader-election backend. The data path already relies on object storage, so a bucket-backed deployment still needs an independently operated metadata service. Replacing the metadata service with object storage is not a simple key-value translation. The current metadata workflow depends on several properties:
|
||||
|
||||
- A write must be serialized with other related writes.
|
||||
- A Leader that has lost its term must not commit later.
|
||||
- A failed request must not be reported as rejected while its outcome is unknown.
|
||||
- A new Leader must be able to take over after the previous Leader fails.
|
||||
|
||||
The central design choice is to make the Leader the single writer of authoritative metadata. Conditional object versions reject stale updates, and the epoch fences stale terms. With this backend, every authoritative metadata write is routed through the Leader, so failover pauses metadata writes. Renewal costs and failover estimates are below; the full storage requirements are in *Object-store semantics*.
|
||||
|
||||
# Goals
|
||||
|
||||
- Elect exactly one effective Leader among concurrently starting nodes.
|
||||
- Allow a surviving node to take over after the previous Leader expires.
|
||||
- Prevent an old Leader from modifying the Head after a takeover.
|
||||
- Anchor leases to the store's modification timestamp, with a bounded candidate clock offset.
|
||||
- Handle uncertain conditional writes without blindly retrying them.
|
||||
- Serialize Head mutations on each node so renewal and commit do not race locally.
|
||||
- Preserve the existing Metasrv `Election` trait where possible.
|
||||
- Provide a stable authority interface for the later phase-one RFCs.
|
||||
- Reuse the existing OpenDAL object-store abstraction without extending OpenDAL.
|
||||
- Make the design testable against MinIO and the cloud object stores in scope.
|
||||
|
||||
# Non-goals
|
||||
|
||||
- The batching and immutable batch format.
|
||||
- Transaction commit semantics and commit-tail comparisons.
|
||||
- B-link Tree nodes, manifests, splitting, and the read path.
|
||||
- Checkpointing, garbage collection, and materialization.
|
||||
- Quorum replication and follower-local consistent reads.
|
||||
- A migration path from etcd, MySQL, or PostgreSQL.
|
||||
- Running the new backend and an existing backend at the same time.
|
||||
- Changing the persisted format of existing metadata keys.
|
||||
- Supporting standalone Metasrv through this election mechanism.
|
||||
|
||||
Keeping a KV service would retain the independent service dependency, while a routing-only Head would still need another component for fencing and commit serialization. The WAL-style alternative advances history by conditionally creating monotonically named immutable objects and needs rules for discovering the latest valid record and handling concurrent publication. This RFC renews a fixed Head so `owner`, `epoch`, and store-side `last_modified` can be read from one version, requiring atomic replacement conditioned on the version read.
|
||||
|
||||
# Phase boundary
|
||||
The first phase is divided into three related RFCs:
|
||||
|
||||
| RFC | Responsibility | Relation to the Head |
|
||||
| --- | --- | --- |
|
||||
| Authority and election | Leader, epoch, lease, fencing | Defines and owns the Head authority |
|
||||
| Batching and immutable batch | Batch construction and commit | Publishes committed batches through the Head |
|
||||
| B-link Tree layout | Nodes, manifests, and reads | Publishes checkpoint roots through the Head |
|
||||
|
||||
This RFC defines the shared authority contract. It does not implement the `KvBackend` write methods because their visibility semantics belong to the future batching RFC. Later RFCs may extend the Head payload with planned fields such as:
|
||||
|
||||
- `committed_sequence`
|
||||
- `last_batch`
|
||||
- `checkpoint_root`
|
||||
|
||||
The election fields and their meanings are fixed by this RFC.
|
||||
|
||||
# Renewal costs and failover estimates
|
||||
|
||||
Renewal shares the serialized Head writer with later metadata commits. Each renewal requires a conditional replacement and enough time to obtain coherent response metadata or resolve an uncertain result. Renewal priority and request latency must leave sufficient time within the local lease; commit throughput and batching requirements belong to the future batching RFC.
|
||||
|
||||
Failover time includes the remaining store-side lease, the clock guard, the campaign interval with jitter, and the storage requests needed to read and replace the Head. A ten-second lease alone is not a ten-second failover bound. Storage outages or a delayed write that advances `last_modified` can delay takeover further.
|
||||
|
||||
# Design overview
|
||||
The design separates three questions:
|
||||
|
||||
- **Who may write?** The current epoch, Head ownership, active local Leader state, and local deadline decide this.
|
||||
- **When is a write visible?** The Head commit performed by the batching layer decides this.
|
||||
- **Where does data live?** Immutable batches and B-link Tree objects decide this.
|
||||
|
||||
The Authority Head is rewritten in place. Every mutation checks a confirmed Head state and passes its corresponding OpenDAL `Metadata` to `if_not_changed`.
|
||||
The high-level sequence is:
|
||||
|
||||
1. An operator explicitly initializes an empty Head in a new namespace.
|
||||
2. Nodes register themselves as candidates.
|
||||
3. Candidates read the Head and campaign when the lease is absent or expired.
|
||||
4. Exactly one candidate conditionally replaces the previously read Head version.
|
||||
5. The winner becomes Leader and receives the new epoch as its fencing token.
|
||||
6. The Leader renews the Head through the same serialized writer used by commits.
|
||||
7. Renewal failure follows the local retirement transition in *Renewal*; uncertain results follow *Outcomes*.
|
||||
8. Candidates continue campaigning under the takeover rules.
|
||||
|
||||
The election decision is made against the Head state. Candidate listing is never used to decide who may write.
|
||||
|
||||
# Authority Head
|
||||
|
||||
## Object path
|
||||
The Head uses a fixed object path:
|
||||
|
||||
```text
|
||||
<root>/<store_key_prefix>/authority/head.json
|
||||
```
|
||||
|
||||
`root` comes from the selected storage configuration. When clusters share a root, each must explicitly set a non-empty, unique, and stable `store_key_prefix`. An empty prefix is permitted only when the cluster exclusively owns that root. If two clusters resolve to the same Head path, either may take over the other's Head after lease expiry, and later commits may enter the same chain. First-phase isolation relies on deployment owners assigning paths correctly, using the existing configuration without a separate cluster identifier or Authority prefix option.
|
||||
|
||||
Paths in this RFC include the storage root for clarity; calls to the opened operator use relative paths and do not add the root again. The Head path is reserved for Authority updates.
|
||||
|
||||
## Payload
|
||||
The first phase fixes the following logical payload:
|
||||
|
||||
```rust
|
||||
struct AuthorityHead {
|
||||
format_version: u32,
|
||||
owner: Option<NodeIdentity>,
|
||||
epoch: u64,
|
||||
lease_deadline_ms: u64,
|
||||
write_seq: u64,
|
||||
}
|
||||
|
||||
struct NodeIdentity {
|
||||
addr: String,
|
||||
incarnation_id: Uuid,
|
||||
}
|
||||
```
|
||||
|
||||
The initial Head has `owner = null`, `epoch = 0`, and `write_seq = 0`:
|
||||
|
||||
```json
|
||||
{
|
||||
"format_version": 1,
|
||||
"owner": null,
|
||||
"epoch": 0,
|
||||
"lease_deadline_ms": 0,
|
||||
"write_seq": 0
|
||||
}
|
||||
```
|
||||
|
||||
A version-1 Head after takeover contains a non-empty owner:
|
||||
|
||||
```json
|
||||
{
|
||||
"format_version": 1,
|
||||
"owner": {
|
||||
"addr": "127.0.0.1:3002",
|
||||
"incarnation_id": "550e8400-e29b-41d4-a716-446655440000"
|
||||
},
|
||||
"epoch": 1,
|
||||
"lease_deadline_ms": 1794528010000,
|
||||
"write_seq": 1
|
||||
}
|
||||
```
|
||||
|
||||
`addr` is the Metasrv gRPC address. `incarnation_id` is a new UUID generated once at each process start, stable for that process's lifetime, and serialized as a canonical hyphenated UUID string. Ownership checks compare both fields, so restarting at the same address does not inherit a term. `lease_deadline_ms` is diagnostic only. Every successful Head mutation increments `write_seq`; both `epoch` and `write_seq` use checked increments and reject overflow without writing.
|
||||
|
||||
## Encoding
|
||||
Serialize the Head to `head.json` with `serde_json` and top-level `format_version: 1`; v1 readers ignore unknown fields in both Head and nested `NodeIdentity`, while validating required fields and types (`owner` must be present even when `null`). Only optional fields that old readers can ignore and old writers can discard on rewrite without affecting correctness may be added to v1. Adding required fields or changing ownership, lease, fencing, commit visibility, or other protocol semantics requires a higher `format_version`; malformed JSON and unsupported versions are rejected.
|
||||
|
||||
# Object-store semantics
|
||||
|
||||
## Object-store capabilities
|
||||
|
||||
Admission requires strong single-object read-after-write consistency and atomic replacement conditioned on the version that was read. Head contents and the complete OpenDAL `Metadata`, including the condition's version identifier and `last_modified`, must describe the same object version. Separate metadata and content requests must be conditionally bound or retried to obtain a coherent state. Reads must not regress to superseded versions. Listing consistency is not required for election or commit decisions.
|
||||
|
||||
| Capability | Purpose |
|
||||
| --- | --- |
|
||||
| Strong single-object read | Read the Authority Head and resolve uncertain writes |
|
||||
| `if_not_exists(true)` | Initialize the Authority Head |
|
||||
| `if_not_changed(&metadata)` backed by atomic replacement | Takeover, renewal, resignation, and later commits |
|
||||
| Backend condition identifier in `Metadata` | Identify the version used for replacement and read-back comparison |
|
||||
| `last_modified` | Determine lease expiration |
|
||||
| Unconditional write | Register candidate nodes |
|
||||
| Object listing | Discover candidate nodes |
|
||||
| Object deletion | Clean up temporary probes; candidate cleanup additionally requires a safe conditional delete |
|
||||
|
||||
First-phase qualification covers S3-compatible backends, including MinIO, Azure Blob, and GCS. Each actual endpoint must pass the startup probe through the production Head read/write path and configured OpenDAL layers. S3 and Azure use ETag conditions; GCS uses the generation exposed as `Metadata::version()`. GCS must pass real-endpoint generation-path tests before it is enabled; that validation has not been performed for this RFC revision.
|
||||
|
||||
Alibaba OSS server-side `PutObject` rejects `If-Match` and `If-None-Match` with `NotImplemented` (`0017-00000245`); see [Alibaba Cloud's documentation](https://www.alibabacloud.com/help/en/oss/user-guide/0017-00000245). OSS is therefore not supported by the current Head protocol, which requires atomic replacement conditioned on the version read. The local filesystem and other backends without the same atomic condition, coherent metadata, or strong-read guarantees are also excluded; declared flags or read-then-unconditional-write emulation do not satisfy admission.
|
||||
|
||||
The current OpenDAL write interfaces for HDFS and MySQL also lack the required conditional replacement; the MySQL restriction applies to the adapter. HDFS `append` only appends bytes and cannot replace this version-checked Head update: using it would require a separate election protocol, and append support varies by backend.
|
||||
|
||||
GreptimeDB already provides object-store access through OpenDAL. The Metasrv adapter owns JSON encoding, coherent Head reads, conditional-write handling, election, fencing, candidate registration, and capability validation. The functional probe verifies the endpoint and layers against the same admission contract.
|
||||
|
||||
## Deployment requirements
|
||||
|
||||
The bucket is the storage container holding the Head object; on Azure Blob the corresponding resource is a container. The epoch is a logical term stored inside the Head, independent of bucket configuration or object-version IDs. All nodes must use the same selected store, root, and `store_key_prefix`.
|
||||
|
||||
The Authority prefix must be excluded from lifecycle expiration and storage-class transition rules. Administrative deletion, rollback to an older version, or replacement outside this protocol can destroy the authority history and requires operator recovery.
|
||||
|
||||
In a versioned S3 bucket, `If-None-Match: *` can succeed when the current version is a delete marker, even if older Head versions exist. A successful conditional create therefore does not prove that the namespace has never been initialized. See the [S3 conditional-write behavior](https://docs.aws.amazon.com/AmazonS3/latest/userguide/conditional-writes.html#conditional-write-behavior). Explicit initialization is restricted to a namespace the operator has established is new.
|
||||
|
||||
## Conditional writes
|
||||
|
||||
The design uses two conditional write forms:
|
||||
|
||||
| Operation | Condition | Purpose |
|
||||
| --- | --- | --- |
|
||||
| Create if absent | `write_with(...).if_not_exists(true)` | Initialize the Head and immutable objects |
|
||||
| Replace if unchanged | `write_with(...).if_not_changed(&metadata)` | Takeover, renewal, resignation, and later commits |
|
||||
|
||||
Use the `Metadata` paired with the decision's Head contents for every takeover, renewal, and resignation. OpenDAL lowers `if_not_changed` to a supported native version-match condition, or an ETag match when that is the supported primitive. The condition must be atomic with publication, including final multipart or staged-upload completion. A `stat` followed by an unconditional write is not acceptable. Operators or layers that ignore conditions are rejected, and transparent retries must not replay Head mutations. Storage branches use OpenDAL `ErrorKind`.
|
||||
|
||||
## Object version
|
||||
|
||||
Preserve the complete OpenDAL `Metadata` associated with the observed Head path and contents. The identifier selected for conditional writes is opaque: compare it for equality during read-back, without interpreting or ordering it. In OpenDAL 0.59.4, S3 and Azure select `Metadata::etag()`, while GCS selects the object generation in `Metadata::version()`. These physical identifiers differ from the logical epoch; renewal keeps the epoch while changing the conditional version.
|
||||
|
||||
For S3, retain ETags exactly as returned, including surrounding quotes, when OpenDAL passes them to `If-Match`. Writing identical contents may reuse an ETag, so incrementing `write_seq` must change the Head contents on every mutation. Bucket version IDs are not substituted for the ETag condition. Versioned-bucket delete-marker behavior is covered in *Deployment requirements*.
|
||||
|
||||
## Store timestamp and lease
|
||||
|
||||
Candidates compare their wall clocks with `last_modified` from the Head's OpenDAL `Metadata`, using the complete rule in *Expiration test*. Deployments must keep candidate-to-store clock offsets within the stated bound. The Leader uses a monotonic clock for its local deadline, as specified in *Renewal*. The diagnostic `lease_deadline_ms` written by a node is never a lease authority.
|
||||
|
||||
## Capability probe
|
||||
|
||||
After opening the selected storage and applying its configured layers, and before campaigning, check admission status and the declared primitives: `write_with_if_not_exists` plus `write_with_if_version_match` or `write_with_if_match` with a usable metadata identifier. `if_not_changed` has no independent capability flag. The provider's configuration name is not its backend type. Then issue real requests against a unique temporary key under the same `probes/` naming convention as the object-store WAL:
|
||||
|
||||
```text
|
||||
<root>/<store_key_prefix>/probes/<uuid>.json
|
||||
```
|
||||
|
||||
1. Create distinct contents with `if_not_exists(true)`. Read them through the production Head read path; require coherent contents, a usable conditional version identifier, and non-empty `last_modified` in the returned `Metadata`.
|
||||
2. Repeat the conditional create on the same key with different contents. Accept `ConditionNotMatch` or `AlreadyExists`, then read back and verify the original contents and conditional identifier are unchanged.
|
||||
3. Replace it with different contents using `if_not_changed(¤t_metadata)`. Require success and read back coherent new contents and metadata, with a changed conditional identifier and available `last_modified`.
|
||||
4. Attempt another replacement with the old metadata. Require `ConditionNotMatch`, then read back and verify the latest contents and identifier are unchanged.
|
||||
|
||||
Probe payloads use the version-1 Head codec, with distinct contents produced through `write_seq`. The probe uses the production Head read/write path and OpenDAL layers; for GCS it must exercise generation-based conditions. Ignored conditions, missing capabilities, incoherent or incomplete metadata, or an unresolved result fail startup. Also require unconditional writes, listing, and probe deletion. Clean up the temporary object on both success and failure, and report cleanup failures. Probe keys are isolated from `authority/` and candidate records; a probe must never create or modify the Head. Flags alone cannot prove these semantics.
|
||||
|
||||
# Initialization
|
||||
Head creation is an explicit operator operation for a new namespace. Add a planned Metasrv subcommand following the existing `greptime metasrv <subcommand> --config-file` CLI style:
|
||||
|
||||
```sh
|
||||
greptime metasrv init --config-file metasrv.toml
|
||||
```
|
||||
|
||||
This proposed command opens the configured store, runs the isolated capability probe, and creates the version-1 empty Head with `if_not_exists(true)`. It does not campaign. Concurrent initializers that receive `ConditionNotMatch` or `AlreadyExists` read and validate the existing Head and report it as already initialized; they never reset its epoch or contents. Other conflicts require read-back and re-evaluation. An uncertain create is read back without blindly resending it. Creation and takeover remain separate operations:
|
||||
|
||||
| Property | Initialization | Takeover |
|
||||
| --- | --- | --- |
|
||||
| Owner | Empty | Current candidate |
|
||||
| Epoch | `0` | Previous epoch plus one |
|
||||
| Condition | Object absent | Metadata from the previously read Head version |
|
||||
| Lease | Not established | Established by this write |
|
||||
|
||||
The initial empty Head has no lease. Normal `greptime metasrv start --config-file metasrv.toml` requires an existing, valid Head. If the Head is missing at startup or runtime, stop election and writes and report an explicit error naming its path: `Authority Head is missing; operator recovery is required`. Do not invoke initialization as a fallback.
|
||||
|
||||
Recovery requires fencing or stopping existing writers, checking the configured store and namespace, and inspecting retained object versions or backups for the last valid Head. Restore the authority history and its referenced metadata from a consistent recovery point before restarting nodes. A missing current object, including an S3 delete marker, is insufficient evidence of a new namespace. If history cannot be recovered, any destructive reset is a separate recovery decision outside this initialization command.
|
||||
|
||||
# Leader election
|
||||
|
||||
## Takeover
|
||||
A candidate repeatedly attempts takeover:
|
||||
|
||||
```text
|
||||
read Head
|
||||
if owner is empty or lease is expired:
|
||||
write owner = candidate
|
||||
write epoch = old_epoch + 1
|
||||
write_seq = old_write_seq + 1
|
||||
replace using if_not_changed(&metadata) from that Head read
|
||||
else:
|
||||
wait with jitter
|
||||
```
|
||||
|
||||
The lease check and the conditional replacement belong to one authority operation. If two candidates use metadata from the same Head version, only one replacement succeeds, and the epoch increases exactly once. The loser rereads and re-evaluates. Candidate listing is never a vote or quorum. A takeover increments the epoch even after resignation; epoch zero represents an initialized Head with no election term.
|
||||
|
||||
The attempt has a provisional monotonic deadline anchored to its send time plus the lease duration. It grants leadership only when its result is confirmed before that deadline. Uncertain takeover and recovery from a retired term follow *Outcomes*; a late result cannot activate an expired attempt.
|
||||
|
||||
## Expiration test
|
||||
A Head with no owner can be taken over immediately. Otherwise, a candidate considers its lease expired only when:
|
||||
|
||||
```text
|
||||
wall_now > last_modified + lease_duration + clock_guard
|
||||
clock_guard = max_clock_skew + timestamp_resolution
|
||||
```
|
||||
|
||||
`last_modified` comes from the same `Metadata` as the Head version used for the decision. `wall_now` is the candidate's local wall clock in the store timestamp's time domain. The initial internal allowances are one second for the maximum candidate-to-store clock offset and one second for timestamp resolution. Deployments must keep clock offsets within that bound; the lease timing guarantee does not hold outside it. The resolution allowance must cover the supported backend's timestamp precision, verified during implementation.
|
||||
|
||||
This expiration rule determines when takeover is permitted. Routing uses a separate, earlier cutoff defined in *Existing Election integration*. CAS arbitrates competing updates to the same Head version. If renewal replaces that version first, the candidate must reread and repeat the expiration check. If takeover wins, the old Leader's conditional update fails. CAS does not replace the clock assumptions or validate a candidate's expiration calculation.
|
||||
|
||||
## Renewal
|
||||
Use the independent object-store election constant `OBJECT_STORE_META_LEASE_SECS: u64 = 10`, allowing time for storage requests and result read-back without changing existing KV election leases. Default renewal runs at half this lease, every five seconds, through the shared Head writer. Renewal keeps `owner` and `epoch` unchanged and increments `write_seq`. A successful PUT refreshes the store-side `last_modified`. Sample the monotonic clock when sending the request and calculate the proposed deadline:
|
||||
|
||||
```text
|
||||
proposed_deadline = sent_at + lease_duration
|
||||
```
|
||||
|
||||
While the request is pending, retain the existing local deadline. Install the proposed deadline only on a successful renewal response received before that deadline, while local leadership remains active and this node still owns the term. Anchoring at send time avoids counting response latency as additional lease time.
|
||||
|
||||
On the first renewal failure or unknown result, immediately clear the local Leader flag, stop admitting new Leader writes, retire the local term, and emit one `StepDown`. Existing event handlers close heartbeat streams and stop or switch background tasks. Read-back may continue within the original deadline solely to determine whether the PUT applied. Late confirmation and service recovery follow *Outcomes*.
|
||||
|
||||
Reaching the local deadline also retires an active term; repeated failures or deadline expiry after an earlier `StepDown` do not emit it again. The future batching RFC will define whether later batch commits also count as local lease renewal.
|
||||
|
||||
## Resignation
|
||||
A Leader stops admitting new writes when it begins resignation, clears `owner`, retains the epoch, and increments `write_seq` through a fenced Head update. Confirmed resignation ends the local term. An uncertain result follows the same read-back and deadline rules as other mutations. The next takeover increments the epoch and starts a new term.
|
||||
|
||||
# Fencing and comparison
|
||||
|
||||
## Fencing token
|
||||
A Leader receives the current epoch as its fencing token:
|
||||
|
||||
```rust
|
||||
struct FencingToken {
|
||||
epoch: u64,
|
||||
}
|
||||
```
|
||||
|
||||
The token carries the logical term. The conditional version identifier in `Metadata` can change during renewal without changing the term or a queued commit's business state. Later commit callers also supply a business precondition, such as the committed tail against which a batch was prepared.
|
||||
|
||||
## Version and term checks
|
||||
|
||||
Every successful Head mutation changes its contents and conditional version. Takeover also changes the owner and epoch, invalidating the old writer's metadata condition and logical token. Before a fenced update:
|
||||
|
||||
1. Obtain coherent Head contents and their complete `Metadata`, by reading them or using the writer's latest confirmed state.
|
||||
2. Check that the token epoch equals the Head epoch.
|
||||
3. Check that the owner is this node's process identity, local Leader state is active, the term has not been retired, and the local deadline has not passed.
|
||||
4. Check the caller's business precondition.
|
||||
5. Apply the mutation with `if_not_changed(&state.metadata)` for that checked state.
|
||||
|
||||
A failed condition requires Head read-back and re-evaluation of the term, owner, deadline, and applicable preconditions, or recovery if the Head is missing, as specified in *Error handling*. An old-epoch operation is rejected even with fresh metadata. A stale metadata condition is rejected by the store even if the caller has not observed the new epoch. All authoritative publication passes through these checks.
|
||||
|
||||
# Head write serialization
|
||||
Each node uses one writer to serialize all Head updates. Renewal may take priority over queued operations so a busy queue does not starve the lease. Subsequent operations recheck the confirmed Head and metadata, local leadership, deadline, and business preconditions. Renewal alone does not require rebuilding a prepared batch; a moved commit tail does. An unknown outcome pauses subsequent updates. Renewal failures follow *Renewal*, and queued operations for a retired term remain rejected under *Outcomes*. Entry points are defined in *Authority interface*.
|
||||
|
||||
# Uncertain writes
|
||||
|
||||
## Problem
|
||||
A conditional write can apply before its response is lost, or can remain in flight and apply after the client has timed out. A client timeout does not cancel server-side execution. The protocol preserves the distinction between a Head mutation's outcome, current ownership, and a historical client transaction's outcome.
|
||||
|
||||
## Read-back procedure
|
||||
After a timeout or a write error that may follow persistence, pause new Head updates and apply the transition in *Renewal* when appropriate. Read the Head with backoff within the original local deadline solely to resolve the PUT outcome; the unresolved request does not extend that deadline. A takeover attempt uses its provisional deadline. Never blindly resend the original write.
|
||||
|
||||
Compare the read-back identifier selected by the backend for conditional writes with the pre-write identifier, then confirm application only from evidence unique to this operation. Check the complete expected state, including epoch, `write_seq`, and process identity where applicable. An owner address, diagnostic deadline, or empty owner alone is insufficient. A later Head may no longer contain enough evidence to establish an overwritten mutation's history.
|
||||
|
||||
## Outcomes
|
||||
|
||||
| Read-back result | Interpretation |
|
||||
| --- | --- |
|
||||
| Conditional version identifier unchanged, before or after client timeout | Still unknown; the original request may apply later |
|
||||
| Evidence uniquely identifies this mutation | Confirmed applied; service recovery is handled separately below |
|
||||
| Higher epoch or changed owner | Immediately abandon the current term; the original outcome remains unknown without independent evidence |
|
||||
| Conditional version identifier changed without unique evidence | Still unknown; the mutation may have applied and been superseded |
|
||||
| Read-back fails | Retry read-back with backoff within the original deadline |
|
||||
| Original local deadline reached before confirmation | Retire the term if still active, without duplicating `StepDown`, and preserve the operation result as unknown |
|
||||
|
||||
A late success response or successful read-back can establish only that the PUT applied. It cannot extend or reactivate a retired term, even before the original deadline, and queued writes for that term remain rejected. Restoring Leader services and background tasks requires winning a higher epoch through normal takeover and emitting `Elected`. If a late PUT refreshes `last_modified`, candidates use that new timestamp in the unchanged expiration rule.
|
||||
|
||||
Once a legal takeover replaces the observed version, a delayed request with the old metadata condition cannot modify the Head. This fences future execution without proving whether it applied earlier. Historical commit outcomes need independent evidence, such as operation IDs and durable records in the published batch chain, to be defined by the future batching RFC.
|
||||
|
||||
# Candidate registration
|
||||
Candidate registration is separate from the Authority Head. Each node owns one object:
|
||||
|
||||
```text
|
||||
<root>/<store_key_prefix>/candidates/<encoded-node-address>.json
|
||||
```
|
||||
|
||||
The JSON record contains the existing `MetasrvNodeInfo` and a unique refresh identifier. The existing candidate methods and their return types remain unchanged; callers receive `MetasrvNodeInfo`. A node unconditionally overwrites its own path so a restart at the same address can replace the previous record. Refresh runs at an internal interval and retries temporary errors with backoff until stopped. Each refresh attempt uses a fresh identifier, ensuring distinguishable contents and versions even when the node information is unchanged.
|
||||
|
||||
Freshness is judged from the store's `last_modified` and the internal candidate TTL. `all_candidates()` lists records and filters stale entries. Candidate records serve display and peer discovery only; they never decide takeover, epoch assignment, fencing, or commit ordering. Duplicate addresses remain a configuration error; process identities must remain distinct for Authority ownership.
|
||||
|
||||
Periodically clean up stale candidate records using an atomic conditional delete bound to the same version whose timestamp was checked. A refresh after the scan must cause the stale delete to fail and preserve the refreshed record. An unconditional delete after a freshness check is unsafe. On S3, identical-content refreshes could reuse an ETag, which is why refresh identifiers must change. Verify each backend's conditional-delete semantics, including versioned buckets, during implementation. Where safe deletion is unavailable, retain filtering and defer deletion to offline cleanup with refreshers stopped.
|
||||
|
||||
# Authority interface
|
||||
The authority exposes a small interface to the election and later metadata layers:
|
||||
|
||||
```rust
|
||||
trait Authority {
|
||||
async fn head(&self) -> Result<AuthorityState, AuthorityError>;
|
||||
async fn takeover(&self) -> Result<AuthorityState, AuthorityError>;
|
||||
async fn mutate(
|
||||
&self,
|
||||
token: &FencingToken,
|
||||
precondition: Precondition,
|
||||
mutation: Mutation,
|
||||
) -> Result<AuthorityState, AuthorityError>;
|
||||
}
|
||||
```
|
||||
|
||||
All update entry points use the same local writer:
|
||||
|
||||
| Entry point | Requirement | Effect |
|
||||
| --- | --- | --- |
|
||||
| `takeover()` | Empty owner or expired lease | Establish ownership and increment epoch and write sequence |
|
||||
| `mutate(..., Mutation::Renew)` | Current token, owner, active local leadership, and local deadline | Refresh the lease and increment write sequence |
|
||||
| `mutate(..., Mutation::Resign)` | Current token, owner, active local leadership, and local deadline | Clear owner and increment write sequence |
|
||||
|
||||
Takeover creates the first token of a term and is not a `Mutation` variant. Later RFCs may add `Commit` with a commit-tail precondition and `PublishCheckpoint` through the same writer.
|
||||
|
||||
`AuthorityState` contains:
|
||||
|
||||
```rust
|
||||
struct AuthorityState {
|
||||
head: AuthorityHead,
|
||||
metadata: opendal::Metadata,
|
||||
}
|
||||
```
|
||||
|
||||
`head()` returns contents and complete metadata from one coherent object version. Every update entry point uses that metadata with `if_not_changed`; lease formulas use its `last_modified`. An active writer may use its latest confirmed state for the next conditional update. Result resolution follows *Outcomes*. Followers and leader discovery read the Head from the store.
|
||||
|
||||
# Existing Election integration
|
||||
Keep the existing `Election` trait and routing flow. `campaign()` maintains the term using *Renewal*, and result resolution and service recovery follow *Outcomes*. `is_leader()` is local state that can lag the store. Request admission checks it, the active term, and the local deadline; Head updates also enforce fencing and preconditions.
|
||||
|
||||
Confirmed ownership loss, reset, and resignation retire an active term through the same existing event handlers. Remember retired terms locally even while the Head still names this node. `Elected` and `StepDown` occur only on actual transitions, and the infancy flag remains one-shot. Standalone Metasrv does not use this backend.
|
||||
|
||||
## Routing hints
|
||||
|
||||
`leader()` reads the Head and returns an owner address that the caller may try to contact. `LeaderValue` continues to carry the gRPC address. Return `ElectionNoLeader` when the owner is empty, the routing deadline has been reached, or this node knows the observed term has retired. The caller stops routing the current write request on this error.
|
||||
|
||||
Followers use a separate, conservative wall-clock routing deadline:
|
||||
|
||||
```text
|
||||
routing_guard = max_clock_skew + timestamp_resolution
|
||||
route_deadline = last_modified + lease_duration - routing_guard
|
||||
return a hint only if wall_now < route_deadline
|
||||
```
|
||||
|
||||
The clock and precision allowances shorten the hint's lifetime; takeover still adds `clock_guard` under *Expiration test*. Sample `wall_now` after reading the Head, so read latency consumes the routing window rather than extending it from response receipt. With the proposed ten-second lease and two-second allowances, a Head last modified at second zero stops yielding hints at second eight, while takeover is permitted only after second twelve. A lookup at second eleven returns `ElectionNoLeader` while candidates still wait.
|
||||
|
||||
A delayed PUT may place `last_modified` later than the owner's local send time. An owner may also step down early without changing the Head. Followers that do not know this may return its address within the routing window, and forwarding delay can further age the hint. The receiving node must check active local leadership, the current term, and its local deadline and reject writes for a retired or expired term. The first phase uses Head-based hints without an owner-confirmation RPC in `leader()`; an address is not proof that the receiver will accept a write.
|
||||
|
||||
# Configuration
|
||||
Add `BackendImpl::ExperimentalObjectStore`, serialized as `experimental_object_store`, to the existing Metasrv backend selection. Extend Metasrv options with the shared storage configuration and `storage_provider`, following the object-store WAL's provider resolution:
|
||||
|
||||
```toml
|
||||
backend = "experimental_object_store"
|
||||
store_key_prefix = "cluster-a"
|
||||
# Empty selects the default store configured in [storage].
|
||||
storage_provider = ""
|
||||
|
||||
[storage]
|
||||
type = "S3"
|
||||
bucket = "example-metasrv-bucket"
|
||||
root = "metasrv"
|
||||
```
|
||||
|
||||
An empty `storage_provider` selects the default `[storage]` store. A non-empty value is matched case-insensitively to the configured names in `[storage]` and `[[storage.providers]]`, using the same rule as `wal_object_store` in `src/datanode/src/datanode.rs` and `ObjectStoreManager::find`. Unknown names fail configuration validation. Validate the resolved backend type and operator capabilities, rather than comparing the provider name with `s3` or `azblob`.
|
||||
|
||||
For this example, the Head is `metasrv/cluster-a/authority/head.json`, candidates are under `metasrv/cluster-a/candidates/`, and probes are under `metasrv/cluster-a/probes/`. `store_key_prefix` is the only cluster namespace setting; its shared-root isolation rules are defined in *Object path*.
|
||||
|
||||
Election timings follow the repository's internal-constant convention. `OBJECT_STORE_META_LEASE_SECS` and its half-lease renewal interval are defined in *Renewal*, independently of existing KV election timing. Campaigning uses a 500 ms interval with jitter. Clock allowances remain in *Expiration test*. Candidate TTL and refresh reuse the existing 600-second lease and half-lease refresh interval. These are internal constants, not additional configuration options.
|
||||
|
||||
# Error handling
|
||||
Storage branches use OpenDAL `ErrorKind` and its retry metadata. Renewal failures first follow *Renewal*; unknown results and service recovery follow *Outcomes*:
|
||||
|
||||
| OpenDAL result | Action |
|
||||
| --- | --- |
|
||||
| `ConditionNotMatch` | Read the Head; if present, recheck the term, owner, deadline, and operation preconditions against the new state; if missing, stop election and writes and enter operator recovery |
|
||||
| `Conflict` | Read back and re-evaluate contention; retryability alone does not justify replaying the mutation |
|
||||
| `NotFound` on a Head read | Stop and enter operator recovery; never initialize automatically |
|
||||
| `Unexpected` or a temporary write error where persistence is uncertain | Pause updates and use the uncertain-write procedure |
|
||||
| Temporary read-back failure | Retry the read with backoff within the original local deadline |
|
||||
| `Unsupported`, `ConfigInvalid`, or `PermissionDenied` | Report the capability, configuration, or permission failure; fail startup or the operation |
|
||||
|
||||
A client timeout follows the uncertain-write procedure; it is not a separate OpenDAL error kind. A missing target during conditional replacement is a failed condition, not proof that a new Head should be created: only the follow-up read establishes absence. Business-precondition failures return the corresponding conflict for the caller to rebuild and re-evaluate. Preserve unresolved operations as unknown at the API boundary, rather than inviting duplicate execution through an ordinary rejection.
|
||||
|
||||
# Metrics and observability
|
||||
Existing backend-labelled Metasrv metrics cover ordinary request and transaction latency. Add Head write latency and outcome, conditional-write conflicts, uncertain writes and read-back attempts, takeover count and current epoch, renewal failures, late successes, forced step-downs, observed timestamp skew, and stale candidate and cleanup-failure counts. These distinguish storage latency, clock-bound violations, lease churn, and candidate accumulation. Clock-skew metrics do not remove the deployment's bounded-clock requirement.
|
||||
|
||||
# Compatibility and backup
|
||||
The Authority Head is a persisted JSON format covered by the repository compatibility framework. Freeze both version-1 examples, including the non-empty `NodeIdentity`, and verify deterministic `serde_json` encoding and decoding under the rules in [Encoding](#encoding).
|
||||
|
||||
A consistent backup contains the Head and, once later RFCs add them, the published batch chain reachable from `last_batch` and the required tree objects. Candidate records and probes are excluded. The Head and referenced metadata must come from one consistent recovery point. Restoring a backup is an operator recovery action with existing writers fenced, not initialization of an empty Head.
|
||||
|
||||
# Failure scenarios
|
||||
|
||||
This table defines the expected outcomes. The validation plan references scenario IDs instead of repeating them; retirement and service recovery use the contracts in *Renewal* and *Outcomes*.
|
||||
|
||||
| ID | Scenario | Expected behavior |
|
||||
| --- | --- | --- |
|
||||
| F1 | Concurrent initialization in a new namespace | One create succeeds; other initializers validate the existing Head without resetting it |
|
||||
| F2 | Two candidates take over from the same observed version | Exactly one wins and the epoch increases once |
|
||||
| F3 | Leader stops renewing | A candidate takes over after the guarded expiration of the latest store timestamp |
|
||||
| F4 | First renewal failure or unknown result | Perform the immediate local retirement and service shutdown defined in *Renewal* |
|
||||
| F5 | Old Leader uses stale metadata or an old epoch | The store rejects the stale condition; logical checks reject the old epoch even with fresh metadata |
|
||||
| F6 | Renewal races with takeover on the same version | Exactly one conditional replacement succeeds |
|
||||
| F7 | A write applies but its response is lost | Unique read-back evidence confirms application; otherwise preserve the unknown result |
|
||||
| F8 | A timed-out renewal applies or is confirmed later | Apply *Outcomes* even before the original deadline; candidates honor any refreshed store timestamp |
|
||||
| F9 | The former Leader wins a higher epoch | Service recovery follows *Outcomes* through the existing event handlers |
|
||||
| F10 | Routing has expired while takeover is not yet permitted | Return `ElectionNoLeader` and stop routing the current write request |
|
||||
| F11 | A routing hint names a node that stepped down early | An uninformed follower may return the hint before its cutoff; the receiver rejects the write, and a node aware of retirement returns `ElectionNoLeader` |
|
||||
| F12 | Takeover precedes a delayed old-term request | The old metadata condition cannot replace the new Head |
|
||||
| F13 | Head is missing at startup or runtime, including behind an S3 delete marker | Stop election and writes and require operator recovery; never initialize automatically |
|
||||
| F14 | Head is deleted between observation and conditional replacement | `ConditionNotMatch` triggers read-back: recheck term, owner, and preconditions if present, or follow F13 if missing |
|
||||
| F15 | Candidate refresh fails temporarily or a node restarts | Refresh retries with backoff; records become stale or are replaced by distinguishable refreshes |
|
||||
| F16 | Candidate refresh races with stale cleanup | Safe conditional deletion preserves the refreshed record; otherwise use the offline-cleanup fallback |
|
||||
| F17 | Multipart or staged publication uses stale metadata | Final publication rejects the condition and leaves the current Head unchanged |
|
||||
| F18 | Leader resigns | Owner becomes empty; the next takeover starts a higher epoch |
|
||||
| F19 | Startup probe encounters ignored conditions or missing metadata/capabilities | Fail startup, clean up the unique probe key, and never modify the Head |
|
||||
| F20 | A process restarts at the same address | Its new incarnation does not inherit the previous process's ownership |
|
||||
|
||||
# Validation plan
|
||||
|
||||
## Format and deterministic protocol tests
|
||||
|
||||
Freeze both version-1 JSON examples and cover deterministic serialization, required fields (including `owner`, `addr`, and `incarnation_id`), UUID encoding and validation, malformed JSON, invalid types, and unsupported versions. Add checked-overflow cases for both counters. Use injected wall and monotonic clocks and coherent mock `Metadata`; in-memory timestamps do not qualify a backend's real semantics.
|
||||
|
||||
Add three explicit compatibility cases:
|
||||
|
||||
- A v1 reader accepts an otherwise valid Head with an unknown top-level field and decodes the known fields unchanged.
|
||||
- A v1 reader accepts an unknown field inside a non-empty `owner` and decodes its `NodeIdentity` unchanged.
|
||||
- A v1 reader rejects a Head with `format_version: 2` even when the rest of its body follows the v1 structure.
|
||||
|
||||
Unit and in-process tests cover the following scenarios, using the outcomes in [Failure scenarios](#failure-scenarios):
|
||||
|
||||
| Scenarios | Test-layer-specific checks |
|
||||
| --- | --- |
|
||||
| F1, F19 | Exercise both `ConditionNotMatch` and `AlreadyExists` on repeated create; inject ignored conditions, incomplete or mismatched metadata, and probe cleanup failures. Check path isolation under `probes/` |
|
||||
| F2, F5, F6, F18, F20 | Synchronize candidates on one snapshot; test stale metadata separately from a stale epoch with current metadata. Reuse an address with a new UUID, and keep each process UUID stable across operations |
|
||||
| F3, F4, F9–F11 | Inject exact routing/takeover cutoffs, clock offsets, and Head-read delay. Observe leadership flags, event counts, heartbeat closure, and background-task callbacks through the existing handlers |
|
||||
| F13, F14 | Delete between read and replacement; drive both present and missing follow-up reads and inspect the re-evaluated term, owner, and operation preconditions |
|
||||
| F15, F16 | Keep node information unchanged across refreshes, advance refresh identifiers, pause cleanup after its scan, and inject transient refresh errors |
|
||||
|
||||
Also check writer serialization, renewal priority over queued operations, queue rejection after retirement, and business-precondition re-evaluation against confirmed metadata. Mock both native version-match and ETag-match lowering, including unusable condition metadata; do not add an `if_not_changed` capability flag.
|
||||
|
||||
## Failure injection
|
||||
|
||||
Cover F4, F7–F9, and F12 by controlling persistence and response delivery independently: lose a response after persistence, hold a request until after client timeout, return successful read-back before and after the original deadline, and release an old request after takeover. Pause processes and interleave queued operations. Record the original deadline and event-handler ordering to check the referenced outcomes without relying on sleeps or eventual flags alone. Include late successful takeover confirmation against its provisional deadline.
|
||||
|
||||
## Real-backend qualification
|
||||
|
||||
Qualify S3-compatible endpoints including MinIO, Azure Blob, and GCS through the production Head read/write path and configured OpenDAL layers. Run the scenario groups below with real requests; mock tests alone do not enable a backend.
|
||||
|
||||
- **F2, F5, F6, F17, F19:** verify coherent contents, conditional identifier, and `last_modified` from one version. Test current and stale metadata at the actual publication point, including forced S3 multipart completion and Azure block-list publication. Check completed-write visibility, timestamp precision, and that retry layers do not replay unresolved Head writes.
|
||||
- **GCS qualification for F2, F5, F6, F17, F19:** use a real endpoint to verify `Metadata::version()` contains the observed generation and `if_not_changed` selects the generation condition, including any staged publication path. Apply the same admission criteria as other backends. **Status: not yet tested for this RFC revision; enable only after these tests pass.**
|
||||
- **F1, F13, F14, F19:** verify repeated-create error normalization and read-back. A missing conditional-replacement target must map to `ConditionNotMatch`; only a subsequent Head read determines absence. In a versioned S3 bucket, test a delete marker on a disposable key and inspect retained history. Verify S3 ETag quotes survive round trips unchanged.
|
||||
- **F15, F16:** check candidate listing metadata and each backend's actual conditional-delete capability and behavior, including versioned storage and refresh/delete interleavings.
|
||||
- **F4, F7–F12:** repeat fault-injection schedules with real request delays, routing cutoffs, and event handlers. Measure renewal request and read-back latency under queued load to validate the margin provided by the ten-second lease and five-second renewal interval.
|
||||
|
||||
Future OSS support requires evaluating a separate election protocol, such as one based on immutable records.
|
||||
|
||||
# Implementation plan
|
||||
The work is split into reviewable changes:
|
||||
|
||||
- Add Authority types, persisted process identities, versioned JSON encoding, and both compatibility fixtures.
|
||||
- Add capability-based backend admission and the isolated `probes/` runtime checks, including GCS generation-path qualification before enablement.
|
||||
- Add coherent Head/Metadata reads, `if_not_changed` mutations, explicit initialization CLI, and missing-Head recovery errors.
|
||||
- Add takeover, epoch fencing, the independent `OBJECT_STORE_META_LEASE_SECS` constant, renewal, local deadlines, and resignation. Validate request and read-back timing margins at the five-second renewal interval within the ten-second lease.
|
||||
- Add the single-writer task and uncertain-write read-back.
|
||||
- Add retrying candidate refresh, safe stale cleanup, and the existing `Election` integration.
|
||||
- Add backend selection and storage options, metrics, and real-backend qualification with failure injection.
|
||||
|
||||
The future batching RFC adds commit-tail mutations without changing the election contract. The B-link Tree RFC adds checkpoint publication through the same writer.
|
||||
|
||||
# Future work
|
||||
The future batching RFC will define immutable batches, operation identifiers, commit-tail preconditions, and client-visible commit confirmation. The B-link Tree RFC will define nodes, manifests, checkpoint roots, and read semantics. A later phase may add checkpoint garbage collection, quorum replication, and follower-local consistent reads.
|
||||
@@ -13962,7 +13962,7 @@
|
||||
"uid": "${metrics}"
|
||||
},
|
||||
"editorMode": "code",
|
||||
"expr": "sum by (result) (\n changes(greptime_region_balancer_actions_total[$__rate_interval])\n)",
|
||||
"expr": "sum by (result) (\n increase(greptime_region_balancer_actions_total[$__rate_interval])\n)",
|
||||
"hide": false,
|
||||
"instant": false,
|
||||
"legendFormat": "{{result}}",
|
||||
@@ -14064,7 +14064,7 @@
|
||||
"uid": "${metrics}"
|
||||
},
|
||||
"editorMode": "code",
|
||||
"expr": "sum by (gate, reason) (changes(greptime_region_balancer_gate_stop_total[$__rate_interval]))",
|
||||
"expr": "sum by (gate, reason) (increase(greptime_region_balancer_gate_stop_total[$__rate_interval]))",
|
||||
"hide": false,
|
||||
"instant": false,
|
||||
"legendFormat": "{{gate}} / {{reason}}",
|
||||
@@ -14399,7 +14399,7 @@
|
||||
"uid": "${metrics}"
|
||||
},
|
||||
"editorMode": "code",
|
||||
"expr": "sum by (result) (changes(greptime_auto_repartition_actions_total[$__rate_interval]))",
|
||||
"expr": "sum by (result) (increase(greptime_auto_repartition_actions_total[$__rate_interval]))",
|
||||
"hide": false,
|
||||
"instant": false,
|
||||
"legendFormat": "{{result}}",
|
||||
@@ -14415,7 +14415,7 @@
|
||||
"type": "prometheus",
|
||||
"uid": "${metrics}"
|
||||
},
|
||||
"description": "Auto repartition gate stop count by gate and reason",
|
||||
"description": "Repartition gate stop increments. Baseline failures show detailed reasons when available; otherwise the aggregate invalid_baseline series is retained. Fallback is matched per source before aggregation to avoid double counting across mixed versions.",
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"color": {
|
||||
@@ -14501,12 +14501,25 @@
|
||||
"uid": "${metrics}"
|
||||
},
|
||||
"editorMode": "code",
|
||||
"expr": "sum by (gate, reason) (changes(greptime_auto_repartition_gate_stop_total[$__rate_interval]))",
|
||||
"expr": "sum by (gate, reason) (\n increase(greptime_auto_repartition_gate_stop_total{reason!=\"invalid_baseline\"}[$__rate_interval])\n or\n (increase(greptime_auto_repartition_gate_stop_total{reason=\"invalid_baseline\"}[$__rate_interval])\n unless ignoring (gate, reason)\n increase(greptime_auto_repartition_invalid_baseline_total[$__rate_interval]))\n)",
|
||||
"hide": false,
|
||||
"instant": false,
|
||||
"legendFormat": "{{gate}} / {{reason}}",
|
||||
"range": true,
|
||||
"refId": "A"
|
||||
},
|
||||
{
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "${metrics}"
|
||||
},
|
||||
"editorMode": "code",
|
||||
"expr": "sum by (reason) (increase(greptime_auto_repartition_invalid_baseline_total[$__rate_interval]))",
|
||||
"hide": false,
|
||||
"instant": false,
|
||||
"legendFormat": "baseline / {{reason}}",
|
||||
"range": true,
|
||||
"refId": "B"
|
||||
}
|
||||
],
|
||||
"title": "Auto Repartition Gate Stops",
|
||||
|
||||
@@ -241,14 +241,20 @@ ORDER BY data_size DESC;` | `piechart` | Distribution of leader regions and data
|
||||
| Title | Query | Type | Description | Datasource | Unit | Legend Format |
|
||||
| --- | --- | --- | --- | --- | --- | --- |
|
||||
| Region Balancer Actions | `sum by (result) (
|
||||
changes(greptime_region_balancer_actions_total[$__rate_interval])
|
||||
increase(greptime_region_balancer_actions_total[$__rate_interval])
|
||||
)` | `timeseries` | Region balancer action count | `prometheus` | `short` | `{{result}}` |
|
||||
| Region Balancer Gate Stops | `sum by (gate, reason) (changes(greptime_region_balancer_gate_stop_total[$__rate_interval]))` | `timeseries` | Region balancer gate stop count by gate and reason | `prometheus` | `short` | `{{gate}} / {{reason}}` |
|
||||
| Region Balancer Gate Stops | `sum by (gate, reason) (increase(greptime_region_balancer_gate_stop_total[$__rate_interval]))` | `timeseries` | Region balancer gate stop count by gate and reason | `prometheus` | `short` | `{{gate}} / {{reason}}` |
|
||||
| Region Balancer Datanodes | `sum by (state) (greptime_region_balancer_datanodes)` | `stat` | Region balancer datanode count by state | `prometheus` | `short` | `{{state}}` |
|
||||
| Region Balancer Regions | `sum by (state) (greptime_region_balancer_regions)` | `stat` | Region balancer region count by state | `prometheus` | `short` | `{{state}}` |
|
||||
| Region Balancer Datanode Stability | `sum by (state) (greptime_region_balancer_datanode_stability)` | `stat` | Region balancer datanode stability statistics by state | `prometheus` | `binBps` | `{{state}}` |
|
||||
| Auto Repartition Actions | `sum by (result) (changes(greptime_auto_repartition_actions_total[$__rate_interval]))` | `timeseries` | Auto repartition action count by result | `prometheus` | `short` | `{{result}}` |
|
||||
| Auto Repartition Gate Stops | `sum by (gate, reason) (changes(greptime_auto_repartition_gate_stop_total[$__rate_interval]))` | `timeseries` | Auto repartition gate stop count by gate and reason | `prometheus` | `short` | `{{gate}} / {{reason}}` |
|
||||
| Auto Repartition Actions | `sum by (result) (increase(greptime_auto_repartition_actions_total[$__rate_interval]))` | `timeseries` | Auto repartition action count by result | `prometheus` | `short` | `{{result}}` |
|
||||
| Auto Repartition Gate Stops | `sum by (gate, reason) (
|
||||
increase(greptime_auto_repartition_gate_stop_total{reason!="invalid_baseline"}[$__rate_interval])
|
||||
or
|
||||
(increase(greptime_auto_repartition_gate_stop_total{reason="invalid_baseline"}[$__rate_interval])
|
||||
unless ignoring (gate, reason)
|
||||
increase(greptime_auto_repartition_invalid_baseline_total[$__rate_interval]))
|
||||
)`<br/>`sum by (reason) (increase(greptime_auto_repartition_invalid_baseline_total[$__rate_interval]))` | `timeseries` | Repartition gate stop increments. Baseline failures show detailed reasons when available; otherwise the aggregate invalid_baseline series is retained. Fallback is matched per source before aggregation to avoid double counting across mixed versions. | `prometheus` | `short` | `{{gate}} / {{reason}}` |
|
||||
| Auto Repartition Sampling P99 | `histogram_quantile(0.99, sum by (le, stage) (rate(greptime_auto_repartition_sampling_elapsed_bucket[$__rate_interval])))` | `timeseries` | Auto repartition sampling elapsed time by stage | `prometheus` | `s` | `{{stage}}` |
|
||||
| Auto Repartition Executor P99 | `histogram_quantile(0.99, sum by (le, stage) (rate(greptime_auto_repartition_executor_elapsed_bucket[$__rate_interval])))` | `timeseries` | Auto repartition executor elapsed time by stage | `prometheus` | `s` | `{{stage}}` |
|
||||
# Object Store
|
||||
|
||||
@@ -1904,7 +1904,7 @@ groups:
|
||||
queries:
|
||||
- expr: |-
|
||||
sum by (result) (
|
||||
changes(greptime_region_balancer_actions_total[$__rate_interval])
|
||||
increase(greptime_region_balancer_actions_total[$__rate_interval])
|
||||
)
|
||||
datasource:
|
||||
type: prometheus
|
||||
@@ -1915,7 +1915,7 @@ groups:
|
||||
description: Region balancer gate stop count by gate and reason
|
||||
unit: short
|
||||
queries:
|
||||
- expr: sum by (gate, reason) (changes(greptime_region_balancer_gate_stop_total[$__rate_interval]))
|
||||
- expr: sum by (gate, reason) (increase(greptime_region_balancer_gate_stop_total[$__rate_interval]))
|
||||
datasource:
|
||||
type: prometheus
|
||||
uid: ${metrics}
|
||||
@@ -1955,21 +1955,33 @@ groups:
|
||||
description: Auto repartition action count by result
|
||||
unit: short
|
||||
queries:
|
||||
- expr: sum by (result) (changes(greptime_auto_repartition_actions_total[$__rate_interval]))
|
||||
- expr: sum by (result) (increase(greptime_auto_repartition_actions_total[$__rate_interval]))
|
||||
datasource:
|
||||
type: prometheus
|
||||
uid: ${metrics}
|
||||
legendFormat: '{{result}}'
|
||||
- title: Auto Repartition Gate Stops
|
||||
type: timeseries
|
||||
description: Auto repartition gate stop count by gate and reason
|
||||
description: Repartition gate stop increments. Baseline failures show detailed reasons when available; otherwise the aggregate invalid_baseline series is retained. Fallback is matched per source before aggregation to avoid double counting across mixed versions.
|
||||
unit: short
|
||||
queries:
|
||||
- expr: sum by (gate, reason) (changes(greptime_auto_repartition_gate_stop_total[$__rate_interval]))
|
||||
- expr: |-
|
||||
sum by (gate, reason) (
|
||||
increase(greptime_auto_repartition_gate_stop_total{reason!="invalid_baseline"}[$__rate_interval])
|
||||
or
|
||||
(increase(greptime_auto_repartition_gate_stop_total{reason="invalid_baseline"}[$__rate_interval])
|
||||
unless ignoring (gate, reason)
|
||||
increase(greptime_auto_repartition_invalid_baseline_total[$__rate_interval]))
|
||||
)
|
||||
datasource:
|
||||
type: prometheus
|
||||
uid: ${metrics}
|
||||
legendFormat: '{{gate}} / {{reason}}'
|
||||
- expr: sum by (reason) (increase(greptime_auto_repartition_invalid_baseline_total[$__rate_interval]))
|
||||
datasource:
|
||||
type: prometheus
|
||||
uid: ${metrics}
|
||||
legendFormat: baseline / {{reason}}
|
||||
- title: Auto Repartition Sampling P99
|
||||
type: timeseries
|
||||
description: Auto repartition sampling elapsed time by stage
|
||||
|
||||
@@ -13962,7 +13962,7 @@
|
||||
"uid": "${metrics}"
|
||||
},
|
||||
"editorMode": "code",
|
||||
"expr": "sum by (result) (\n changes(greptime_region_balancer_actions_total[$__rate_interval])\n)",
|
||||
"expr": "sum by (result) (\n increase(greptime_region_balancer_actions_total[$__rate_interval])\n)",
|
||||
"hide": false,
|
||||
"instant": false,
|
||||
"legendFormat": "{{result}}",
|
||||
@@ -14064,7 +14064,7 @@
|
||||
"uid": "${metrics}"
|
||||
},
|
||||
"editorMode": "code",
|
||||
"expr": "sum by (gate, reason) (changes(greptime_region_balancer_gate_stop_total[$__rate_interval]))",
|
||||
"expr": "sum by (gate, reason) (increase(greptime_region_balancer_gate_stop_total[$__rate_interval]))",
|
||||
"hide": false,
|
||||
"instant": false,
|
||||
"legendFormat": "{{gate}} / {{reason}}",
|
||||
@@ -14399,7 +14399,7 @@
|
||||
"uid": "${metrics}"
|
||||
},
|
||||
"editorMode": "code",
|
||||
"expr": "sum by (result) (changes(greptime_auto_repartition_actions_total[$__rate_interval]))",
|
||||
"expr": "sum by (result) (increase(greptime_auto_repartition_actions_total[$__rate_interval]))",
|
||||
"hide": false,
|
||||
"instant": false,
|
||||
"legendFormat": "{{result}}",
|
||||
@@ -14415,7 +14415,7 @@
|
||||
"type": "prometheus",
|
||||
"uid": "${metrics}"
|
||||
},
|
||||
"description": "Auto repartition gate stop count by gate and reason",
|
||||
"description": "Repartition gate stop increments. Baseline failures show detailed reasons when available; otherwise the aggregate invalid_baseline series is retained. Fallback is matched per source before aggregation to avoid double counting across mixed versions.",
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"color": {
|
||||
@@ -14501,12 +14501,25 @@
|
||||
"uid": "${metrics}"
|
||||
},
|
||||
"editorMode": "code",
|
||||
"expr": "sum by (gate, reason) (changes(greptime_auto_repartition_gate_stop_total[$__rate_interval]))",
|
||||
"expr": "sum by (gate, reason) (\n increase(greptime_auto_repartition_gate_stop_total{reason!=\"invalid_baseline\"}[$__rate_interval])\n or\n (increase(greptime_auto_repartition_gate_stop_total{reason=\"invalid_baseline\"}[$__rate_interval])\n unless ignoring (gate, reason)\n increase(greptime_auto_repartition_invalid_baseline_total[$__rate_interval]))\n)",
|
||||
"hide": false,
|
||||
"instant": false,
|
||||
"legendFormat": "{{gate}} / {{reason}}",
|
||||
"range": true,
|
||||
"refId": "A"
|
||||
},
|
||||
{
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "${metrics}"
|
||||
},
|
||||
"editorMode": "code",
|
||||
"expr": "sum by (reason) (increase(greptime_auto_repartition_invalid_baseline_total[$__rate_interval]))",
|
||||
"hide": false,
|
||||
"instant": false,
|
||||
"legendFormat": "baseline / {{reason}}",
|
||||
"range": true,
|
||||
"refId": "B"
|
||||
}
|
||||
],
|
||||
"title": "Auto Repartition Gate Stops",
|
||||
|
||||
@@ -241,14 +241,20 @@ ORDER BY data_size DESC;` | `piechart` | Distribution of leader regions and data
|
||||
| Title | Query | Type | Description | Datasource | Unit | Legend Format |
|
||||
| --- | --- | --- | --- | --- | --- | --- |
|
||||
| Region Balancer Actions | `sum by (result) (
|
||||
changes(greptime_region_balancer_actions_total[$__rate_interval])
|
||||
increase(greptime_region_balancer_actions_total[$__rate_interval])
|
||||
)` | `timeseries` | Region balancer action count | `prometheus` | `short` | `{{result}}` |
|
||||
| Region Balancer Gate Stops | `sum by (gate, reason) (changes(greptime_region_balancer_gate_stop_total[$__rate_interval]))` | `timeseries` | Region balancer gate stop count by gate and reason | `prometheus` | `short` | `{{gate}} / {{reason}}` |
|
||||
| Region Balancer Gate Stops | `sum by (gate, reason) (increase(greptime_region_balancer_gate_stop_total[$__rate_interval]))` | `timeseries` | Region balancer gate stop count by gate and reason | `prometheus` | `short` | `{{gate}} / {{reason}}` |
|
||||
| Region Balancer Datanodes | `sum by (state) (greptime_region_balancer_datanodes)` | `stat` | Region balancer datanode count by state | `prometheus` | `short` | `{{state}}` |
|
||||
| Region Balancer Regions | `sum by (state) (greptime_region_balancer_regions)` | `stat` | Region balancer region count by state | `prometheus` | `short` | `{{state}}` |
|
||||
| Region Balancer Datanode Stability | `sum by (state) (greptime_region_balancer_datanode_stability)` | `stat` | Region balancer datanode stability statistics by state | `prometheus` | `binBps` | `{{state}}` |
|
||||
| Auto Repartition Actions | `sum by (result) (changes(greptime_auto_repartition_actions_total[$__rate_interval]))` | `timeseries` | Auto repartition action count by result | `prometheus` | `short` | `{{result}}` |
|
||||
| Auto Repartition Gate Stops | `sum by (gate, reason) (changes(greptime_auto_repartition_gate_stop_total[$__rate_interval]))` | `timeseries` | Auto repartition gate stop count by gate and reason | `prometheus` | `short` | `{{gate}} / {{reason}}` |
|
||||
| Auto Repartition Actions | `sum by (result) (increase(greptime_auto_repartition_actions_total[$__rate_interval]))` | `timeseries` | Auto repartition action count by result | `prometheus` | `short` | `{{result}}` |
|
||||
| Auto Repartition Gate Stops | `sum by (gate, reason) (
|
||||
increase(greptime_auto_repartition_gate_stop_total{reason!="invalid_baseline"}[$__rate_interval])
|
||||
or
|
||||
(increase(greptime_auto_repartition_gate_stop_total{reason="invalid_baseline"}[$__rate_interval])
|
||||
unless ignoring (gate, reason)
|
||||
increase(greptime_auto_repartition_invalid_baseline_total[$__rate_interval]))
|
||||
)`<br/>`sum by (reason) (increase(greptime_auto_repartition_invalid_baseline_total[$__rate_interval]))` | `timeseries` | Repartition gate stop increments. Baseline failures show detailed reasons when available; otherwise the aggregate invalid_baseline series is retained. Fallback is matched per source before aggregation to avoid double counting across mixed versions. | `prometheus` | `short` | `{{gate}} / {{reason}}` |
|
||||
| Auto Repartition Sampling P99 | `histogram_quantile(0.99, sum by (le, stage) (rate(greptime_auto_repartition_sampling_elapsed_bucket[$__rate_interval])))` | `timeseries` | Auto repartition sampling elapsed time by stage | `prometheus` | `s` | `{{stage}}` |
|
||||
| Auto Repartition Executor P99 | `histogram_quantile(0.99, sum by (le, stage) (rate(greptime_auto_repartition_executor_elapsed_bucket[$__rate_interval])))` | `timeseries` | Auto repartition executor elapsed time by stage | `prometheus` | `s` | `{{stage}}` |
|
||||
# Object Store
|
||||
|
||||
@@ -1904,7 +1904,7 @@ groups:
|
||||
queries:
|
||||
- expr: |-
|
||||
sum by (result) (
|
||||
changes(greptime_region_balancer_actions_total[$__rate_interval])
|
||||
increase(greptime_region_balancer_actions_total[$__rate_interval])
|
||||
)
|
||||
datasource:
|
||||
type: prometheus
|
||||
@@ -1915,7 +1915,7 @@ groups:
|
||||
description: Region balancer gate stop count by gate and reason
|
||||
unit: short
|
||||
queries:
|
||||
- expr: sum by (gate, reason) (changes(greptime_region_balancer_gate_stop_total[$__rate_interval]))
|
||||
- expr: sum by (gate, reason) (increase(greptime_region_balancer_gate_stop_total[$__rate_interval]))
|
||||
datasource:
|
||||
type: prometheus
|
||||
uid: ${metrics}
|
||||
@@ -1955,21 +1955,33 @@ groups:
|
||||
description: Auto repartition action count by result
|
||||
unit: short
|
||||
queries:
|
||||
- expr: sum by (result) (changes(greptime_auto_repartition_actions_total[$__rate_interval]))
|
||||
- expr: sum by (result) (increase(greptime_auto_repartition_actions_total[$__rate_interval]))
|
||||
datasource:
|
||||
type: prometheus
|
||||
uid: ${metrics}
|
||||
legendFormat: '{{result}}'
|
||||
- title: Auto Repartition Gate Stops
|
||||
type: timeseries
|
||||
description: Auto repartition gate stop count by gate and reason
|
||||
description: Repartition gate stop increments. Baseline failures show detailed reasons when available; otherwise the aggregate invalid_baseline series is retained. Fallback is matched per source before aggregation to avoid double counting across mixed versions.
|
||||
unit: short
|
||||
queries:
|
||||
- expr: sum by (gate, reason) (changes(greptime_auto_repartition_gate_stop_total[$__rate_interval]))
|
||||
- expr: |-
|
||||
sum by (gate, reason) (
|
||||
increase(greptime_auto_repartition_gate_stop_total{reason!="invalid_baseline"}[$__rate_interval])
|
||||
or
|
||||
(increase(greptime_auto_repartition_gate_stop_total{reason="invalid_baseline"}[$__rate_interval])
|
||||
unless ignoring (gate, reason)
|
||||
increase(greptime_auto_repartition_invalid_baseline_total[$__rate_interval]))
|
||||
)
|
||||
datasource:
|
||||
type: prometheus
|
||||
uid: ${metrics}
|
||||
legendFormat: '{{gate}} / {{reason}}'
|
||||
- expr: sum by (reason) (increase(greptime_auto_repartition_invalid_baseline_total[$__rate_interval]))
|
||||
datasource:
|
||||
type: prometheus
|
||||
uid: ${metrics}
|
||||
legendFormat: baseline / {{reason}}
|
||||
- title: Auto Repartition Sampling P99
|
||||
type: timeseries
|
||||
description: Auto repartition sampling elapsed time by stage
|
||||
|
||||
@@ -15,6 +15,7 @@ headerPath = "licenses/enterprise-header.txt"
|
||||
# with the "# enterprise" block in `licenserc.toml`'s `excludes` — both are
|
||||
# enforced by `make check-enterprise-license`.
|
||||
includes = [
|
||||
"src/datatypes/src/schema/sketch.rs",
|
||||
"src/common/meta/src/rpc/ddl/trigger.rs",
|
||||
"src/operator/src/expr_helper/trigger.rs",
|
||||
"src/sql/src/statements/alter/trigger.rs",
|
||||
@@ -25,6 +26,16 @@ includes = [
|
||||
"src/sql/src/parsers/create_parser/trigger.rs",
|
||||
"src/sql/src/parsers/show_parser/trigger.rs",
|
||||
"src/mito2/src/extension.rs",
|
||||
"src/mito2/src/engine/table_compaction.rs",
|
||||
"src/mito2/src/engine/table_compaction/output.rs",
|
||||
"src/mito2/src/engine/table_compaction/tests.rs",
|
||||
"src/mito2/src/worker/handle_table_compaction.rs",
|
||||
"src/mito2/src/compaction/multi_region.rs",
|
||||
"src/mito2/src/compaction/multi_region/source.rs",
|
||||
"src/mito2/src/compaction/multi_region/memory.rs",
|
||||
"src/mito2/src/compaction/multi_region/worker.rs",
|
||||
"src/mito2/src/compaction/multi_region/writer.rs",
|
||||
"src/mito2/src/compaction/multi_region/tests.rs",
|
||||
"src/common/function/src/admin/purge_table.rs",
|
||||
"src/catalog/src/system_schema/information_schema/recycle_bin.rs",
|
||||
"src/common/meta/src/ddl/purge_dropped_table.rs",
|
||||
|
||||
@@ -31,6 +31,7 @@ excludes = [
|
||||
# Keep this list in sync with that file's `includes`; enforced by
|
||||
# `make check-enterprise-license`.
|
||||
# enterprise:start
|
||||
"src/datatypes/src/schema/sketch.rs",
|
||||
"src/common/meta/src/rpc/ddl/trigger.rs",
|
||||
"src/operator/src/expr_helper/trigger.rs",
|
||||
"src/sql/src/statements/alter/trigger.rs",
|
||||
@@ -41,6 +42,16 @@ excludes = [
|
||||
"src/sql/src/parsers/create_parser/trigger.rs",
|
||||
"src/sql/src/parsers/show_parser/trigger.rs",
|
||||
"src/mito2/src/extension.rs",
|
||||
"src/mito2/src/engine/table_compaction.rs",
|
||||
"src/mito2/src/engine/table_compaction/output.rs",
|
||||
"src/mito2/src/engine/table_compaction/tests.rs",
|
||||
"src/mito2/src/worker/handle_table_compaction.rs",
|
||||
"src/mito2/src/compaction/multi_region.rs",
|
||||
"src/mito2/src/compaction/multi_region/source.rs",
|
||||
"src/mito2/src/compaction/multi_region/memory.rs",
|
||||
"src/mito2/src/compaction/multi_region/worker.rs",
|
||||
"src/mito2/src/compaction/multi_region/writer.rs",
|
||||
"src/mito2/src/compaction/multi_region/tests.rs",
|
||||
"src/common/function/src/admin/purge_table.rs",
|
||||
"src/catalog/src/system_schema/information_schema/recycle_bin.rs",
|
||||
"src/common/meta/src/ddl/purge_dropped_table.rs",
|
||||
|
||||
@@ -1,10 +0,0 @@
|
||||
Auto-merging src/flow/src/batching_mode/frontend_client.rs
|
||||
Auto-merging src/flow/src/lib.rs
|
||||
CONFLICT (content): Merge conflict in src/flow/src/lib.rs
|
||||
Auto-merging src/flow/src/server.rs
|
||||
CONFLICT (content): Merge conflict in src/flow/src/server.rs
|
||||
Auto-merging src/operator/src/statement/ddl.rs
|
||||
Recorded preimage for 'src/flow/src/lib.rs'
|
||||
Recorded preimage for 'src/flow/src/server.rs'
|
||||
Automatic merge failed; fix conflicts and then commit the result.
|
||||
exit=1
|
||||
@@ -27,7 +27,7 @@ function retry_fetch() {
|
||||
local filename=$2
|
||||
local auth_args=()
|
||||
|
||||
if [[ -n "$DASHBOARD_GITHUB_TOKEN" ]]; then
|
||||
if [[ -n "$DASHBOARD_GITHUB_TOKEN" && "$url" == https://github.com/* ]]; then
|
||||
auth_args=(
|
||||
-H "Authorization: Bearer ${DASHBOARD_GITHUB_TOKEN}"
|
||||
-H "Accept: application/octet-stream"
|
||||
|
||||
@@ -280,6 +280,52 @@ pub fn as_skipping_index_type(skipping_index_type: PbSkippingIndexType) -> Skipp
|
||||
}
|
||||
}
|
||||
|
||||
/// Converts fulltext options for a JSON2 type hint to the wire representation.
|
||||
pub fn json_fulltext_options_to_proto(
|
||||
options: FulltextOptions,
|
||||
) -> crate::v1::JsonFulltextIndexOptions {
|
||||
crate::v1::JsonFulltextIndexOptions {
|
||||
analyzer: match options.analyzer {
|
||||
FulltextAnalyzer::English => Analyzer::English.into(),
|
||||
FulltextAnalyzer::Chinese => Analyzer::Chinese.into(),
|
||||
},
|
||||
case_sensitive: options.case_sensitive,
|
||||
backend: match options.backend {
|
||||
FulltextBackend::Bloom => PbFulltextBackend::Bloom.into(),
|
||||
FulltextBackend::Tantivy => PbFulltextBackend::Tantivy.into(),
|
||||
},
|
||||
granularity: options.granularity,
|
||||
false_positive_rate: options.false_positive_rate(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Validates fulltext options received for a JSON2 type hint.
|
||||
/// The presence of these options enables the fulltext index.
|
||||
pub fn json_fulltext_options_from_proto(
|
||||
options: crate::v1::JsonFulltextIndexOptions,
|
||||
) -> datatypes::error::Result<FulltextOptions> {
|
||||
let analyzer = Analyzer::try_from(options.analyzer).map_err(|_| {
|
||||
datatypes::error::InvalidFulltextOptionSnafu {
|
||||
msg: format!("Unknown fulltext analyzer: {}", options.analyzer),
|
||||
}
|
||||
.build()
|
||||
})?;
|
||||
let backend = PbFulltextBackend::try_from(options.backend).map_err(|_| {
|
||||
datatypes::error::InvalidFulltextOptionSnafu {
|
||||
msg: format!("Unknown fulltext backend: {}", options.backend),
|
||||
}
|
||||
.build()
|
||||
})?;
|
||||
FulltextOptions::new(
|
||||
true,
|
||||
as_fulltext_option_analyzer(analyzer),
|
||||
options.case_sensitive,
|
||||
as_fulltext_option_backend(backend),
|
||||
options.granularity,
|
||||
options.false_positive_rate,
|
||||
)
|
||||
}
|
||||
|
||||
/// Validates skipping options received for a JSON2 type hint.
|
||||
pub fn json_skipping_options_from_proto(
|
||||
options: crate::v1::JsonSkippingIndexOptions,
|
||||
@@ -299,7 +345,6 @@ pub fn json_skipping_options_from_proto(
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
|
||||
use common_base::readable_size::ReadableSize;
|
||||
use datatypes::data_type::ConcreteDataType;
|
||||
use datatypes::schema::{CompressionOptions, FulltextAnalyzer, FulltextBackend};
|
||||
@@ -307,6 +352,26 @@ mod tests {
|
||||
use super::*;
|
||||
use crate::v1::ColumnDataType;
|
||||
|
||||
#[test]
|
||||
fn json_fulltext_options_roundtrip() {
|
||||
for backend in [FulltextBackend::Bloom, FulltextBackend::Tantivy] {
|
||||
let options =
|
||||
FulltextOptions::new(true, FulltextAnalyzer::Chinese, true, backend, 8, 0.05)
|
||||
.unwrap();
|
||||
let wire = json_fulltext_options_to_proto(options.clone());
|
||||
assert_eq!(options, json_fulltext_options_from_proto(wire).unwrap());
|
||||
let mut invalid = wire;
|
||||
invalid.backend = 99;
|
||||
assert!(json_fulltext_options_from_proto(invalid).is_err());
|
||||
let mut invalid = wire;
|
||||
invalid.analyzer = 99;
|
||||
assert!(json_fulltext_options_from_proto(invalid).is_err());
|
||||
let mut invalid = wire;
|
||||
invalid.granularity = 0;
|
||||
assert!(json_fulltext_options_from_proto(invalid).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_try_as_column_schema() {
|
||||
let column_def = ColumnDef {
|
||||
|
||||
+122
-7
@@ -14,10 +14,11 @@
|
||||
|
||||
use std::sync::{Arc, LazyLock};
|
||||
|
||||
use common_base::secrets::SecretString;
|
||||
use common_base::secrets::{ExposeSecret, SecretString};
|
||||
use digest::Digest;
|
||||
use hmac::{Hmac, Mac};
|
||||
use pbkdf2::pbkdf2_hmac;
|
||||
use serde::Serializer;
|
||||
use sha1::Sha1;
|
||||
use sha2::Sha256;
|
||||
use snafu::{OptionExt, ensure};
|
||||
@@ -39,6 +40,9 @@ pub const MAX_PBKDF2_SHA256_ITERATIONS: u32 = 1_000_000;
|
||||
pub const MAX_PBKDF2_SHA256_SALT_LEN: usize = 1024;
|
||||
pub const PG_SCRAM_SHA256_KEY_LEN: usize = 32;
|
||||
|
||||
/// Placeholder used when rendering potentially secret user-provider options.
|
||||
pub(crate) const REDACTED_USER_PROVIDER_OPTION: &str = "[REDACTED]";
|
||||
|
||||
type HmacSha256 = Hmac<Sha256>;
|
||||
|
||||
/// Process-wide secret used to derive a stable mock salt for unknown users, so
|
||||
@@ -52,8 +56,8 @@ pub fn userinfo_by_name(username: Option<String>) -> UserInfoRef {
|
||||
}
|
||||
|
||||
pub fn user_provider_from_option(opt: &str) -> Result<UserProviderRef> {
|
||||
let (name, content) = opt.split_once(':').with_context(|| InvalidConfigSnafu {
|
||||
value: opt.to_string(),
|
||||
let (name, content) = opt.split_once(':').context(InvalidConfigSnafu {
|
||||
value: REDACTED_USER_PROVIDER_OPTION,
|
||||
msg: "UserProviderOption must be in format `<option>:<value>`",
|
||||
})?;
|
||||
match name {
|
||||
@@ -66,16 +70,57 @@ pub fn user_provider_from_option(opt: &str) -> Result<UserProviderRef> {
|
||||
WatchFileUserProvider::new(content).map(|p| Arc::new(p) as UserProviderRef)
|
||||
}
|
||||
_ => InvalidConfigSnafu {
|
||||
value: name.to_string(),
|
||||
value: REDACTED_USER_PROVIDER_OPTION,
|
||||
msg: "Invalid UserProviderOption",
|
||||
}
|
||||
.fail(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Serializes a `user_provider` option, exposing only known file-based forms.
|
||||
///
|
||||
/// The option is held as a [`SecretString`] so `Debug` and the default
|
||||
/// serializer never print it. This serializer exposes the value only to keep
|
||||
/// provider names and file paths visible for those forms in configuration dumps
|
||||
/// such as the `/config` endpoint.
|
||||
pub fn serialize_user_provider_option<S>(
|
||||
value: &Option<SecretString>,
|
||||
serializer: S,
|
||||
) -> std::result::Result<S::Ok, S::Error>
|
||||
where
|
||||
S: Serializer,
|
||||
{
|
||||
match value {
|
||||
Some(value) => {
|
||||
serializer.serialize_some(&redact_user_provider_option(value.expose_secret()))
|
||||
}
|
||||
None => serializer.serialize_none(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Redacts user-provider options except known file-based forms with nonempty paths.
|
||||
///
|
||||
/// Only `static_user_provider:file:<path>` and `watch_file_user_provider:<path>`
|
||||
/// are returned unchanged. Inline credentials, unknown providers and malformed
|
||||
/// options are replaced entirely with a placeholder.
|
||||
pub fn redact_user_provider_option(value: &str) -> String {
|
||||
let is_file_provider = match value.split_once(':') {
|
||||
Some((STATIC_USER_PROVIDER, content)) => content
|
||||
.strip_prefix("file:")
|
||||
.is_some_and(|path| !path.is_empty()),
|
||||
Some((WATCH_FILE_USER_PROVIDER, path)) => !path.is_empty(),
|
||||
_ => false,
|
||||
};
|
||||
if is_file_provider {
|
||||
value.to_string()
|
||||
} else {
|
||||
REDACTED_USER_PROVIDER_OPTION.to_string()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn static_user_provider_from_option(opt: &str) -> Result<StaticUserProvider> {
|
||||
let (name, content) = opt.split_once(':').with_context(|| InvalidConfigSnafu {
|
||||
value: opt.to_string(),
|
||||
let (name, content) = opt.split_once(':').context(InvalidConfigSnafu {
|
||||
value: REDACTED_USER_PROVIDER_OPTION,
|
||||
msg: "UserProviderOption must be in format `<option>:<value>`",
|
||||
})?;
|
||||
match name {
|
||||
@@ -84,7 +129,7 @@ pub fn static_user_provider_from_option(opt: &str) -> Result<StaticUserProvider>
|
||||
Ok(provider)
|
||||
}
|
||||
_ => InvalidConfigSnafu {
|
||||
value: name.to_string(),
|
||||
value: REDACTED_USER_PROVIDER_OPTION,
|
||||
msg: format!("Invalid UserProviderOption, expect only {STATIC_USER_PROVIDER}"),
|
||||
}
|
||||
.fail(),
|
||||
@@ -527,6 +572,7 @@ fn double_sha1(data: &[u8]) -> Vec<u8> {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::error::Error;
|
||||
|
||||
fn mysql_native_password_auth_data(password: &[u8], salt: &[u8]) -> Vec<u8> {
|
||||
let hash_stage_1 = sha1_one(password);
|
||||
@@ -651,6 +697,75 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_redact_user_provider_option() {
|
||||
for option in [
|
||||
"static_user_provider:file:/etc/greptimedb/users",
|
||||
"watch_file_user_provider:/etc/greptimedb/users",
|
||||
"static_user_provider:file:users.txt",
|
||||
"watch_file_user_provider:users.txt",
|
||||
] {
|
||||
assert_eq!(redact_user_provider_option(option), option);
|
||||
}
|
||||
|
||||
for option in [
|
||||
"",
|
||||
"secret",
|
||||
"alice=secret",
|
||||
"static_user_provider",
|
||||
"static_user_provider:",
|
||||
"static_user_provider:file",
|
||||
"static_user_provider:file:",
|
||||
"static_user_provider:filex:/etc/greptimedb/users",
|
||||
"static_user_provider:cmd:alice=secret,bob=pbkdf2_sha256:4096:aa:bb",
|
||||
"static_user_provider:cmd:alice",
|
||||
"static_user_provider:cmd:alice:secret",
|
||||
"static_user_provider:cmd:alice=plain:prefix,secret-tail",
|
||||
"static_user_provider:cmdx:alice=secret",
|
||||
"watch_file_user_provider",
|
||||
"watch_file_user_provider:",
|
||||
"ldap_user_provider:/etc/greptimedb/ldap.toml",
|
||||
"unknown_user_provider:cmd:alice=secret",
|
||||
] {
|
||||
assert_eq!(redact_user_provider_option(option), "[REDACTED]");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_user_provider_errors_redact_credentials() {
|
||||
for option in [
|
||||
"secret",
|
||||
"alice=secret",
|
||||
"alice=secret,bob=other_secret",
|
||||
"alice=secret:cmd:alice=secret",
|
||||
"static_user_provider:alice=secret",
|
||||
"static_user_provider:alice=secret:cmd",
|
||||
"static_user_provider:cmdx:alice=secret",
|
||||
"unknown_user_provider:cmd:alice=secret",
|
||||
"static_user_provider:cmd:alice:invalid=secret",
|
||||
"static_user_provider:cmd:alice=secret=tail",
|
||||
"static_user_provider:cmd:alice=pbkdf2_sha256:secret",
|
||||
"static_user_provider:cmd:alice=mysql_native_password:secret",
|
||||
"static_user_provider:cmd:alice=pg_scram_sha256:secret",
|
||||
"static_user_provider:cmd:bob=secret,alice=pbkdf2_sha256:secret",
|
||||
"static_user_provider:cmd:alice:secret",
|
||||
"static_user_provider:cmd:alice=plain:prefix,secret-tail",
|
||||
"static_user_provider:cmd:watch_file_user_provider:secret",
|
||||
] {
|
||||
for error in [
|
||||
user_provider_from_option(option).err().unwrap(),
|
||||
static_user_provider_from_option(option).err().unwrap(),
|
||||
] {
|
||||
assert!(!error.to_string().contains("secret"));
|
||||
assert!(!format!("{error:?}").contains("secret"));
|
||||
let Error::InvalidConfig { value, .. } = error else {
|
||||
panic!("Expected an invalid config error");
|
||||
};
|
||||
assert_eq!(value, "[REDACTED]");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_mock_verifier_is_stable_per_username() {
|
||||
let alice = PgScramSha256Verifier::mock_for_unknown_user(b"alice");
|
||||
|
||||
+3
-2
@@ -27,8 +27,9 @@ pub use common::{
|
||||
PG_SCRAM_SHA256_KEY_LEN, Password, PgScramSha256Verifier, auth_mysql, auth_mysql_with_verifier,
|
||||
format_mysql_native_password_verifier, format_pbkdf2_sha256_password_verifier,
|
||||
format_pg_scram_sha256_password_verifier, mysql_native_password_hash,
|
||||
parse_pg_scram_sha256_password_verifier, static_user_provider_from_option,
|
||||
user_provider_from_option, userinfo_by_name, validate_mysql_native_password_verifier,
|
||||
parse_pg_scram_sha256_password_verifier, redact_user_provider_option,
|
||||
serialize_user_provider_option, static_user_provider_from_option, user_provider_from_option,
|
||||
userinfo_by_name, validate_mysql_native_password_verifier,
|
||||
};
|
||||
pub use permission::{
|
||||
ALL_ACTIONS, AccessMode, DASHBOARD_DELETE, DASHBOARD_QUERY, DASHBOARD_SAVE,
|
||||
|
||||
@@ -34,6 +34,9 @@ pub struct PermissionTableTarget {
|
||||
pub catalog: String,
|
||||
pub schema: String,
|
||||
pub table: String,
|
||||
/// Set from catalog metadata, never from a client-supplied table name.
|
||||
/// Physical metric tables contain data belonging to multiple logical tables.
|
||||
pub is_physical_metric_table: bool,
|
||||
}
|
||||
|
||||
impl PermissionTableTarget {
|
||||
@@ -47,8 +50,15 @@ impl PermissionTableTarget {
|
||||
catalog: catalog.into(),
|
||||
schema: schema.into(),
|
||||
table: table.into(),
|
||||
is_physical_metric_table: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Sets whether catalog metadata identifies this target as a physical metric table.
|
||||
pub fn with_physical_metric_table(mut self, is_physical_metric_table: bool) -> Self {
|
||||
self.is_physical_metric_table = is_physical_metric_table;
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
/// The result of resolving every table target in a permission request.
|
||||
@@ -183,6 +193,11 @@ pub enum PermissionReq<'a> {
|
||||
GrpcRequest(&'a Request),
|
||||
SqlStatement(&'a Statement),
|
||||
Action(PermissionAction),
|
||||
/// Enumerates a schema's metadata without accessing any table data.
|
||||
SchemaRead {
|
||||
catalog: &'a str,
|
||||
schema: &'a str,
|
||||
},
|
||||
BulkInsert {
|
||||
catalog: &'a str,
|
||||
schema: &'a str,
|
||||
@@ -199,6 +214,7 @@ impl<'a> PermissionReq<'a> {
|
||||
}
|
||||
PermissionReq::SqlStatement(stmt) => stmt.is_readonly(),
|
||||
PermissionReq::Action(action) => action.access_mode() == AccessMode::Read,
|
||||
PermissionReq::SchemaRead { .. } => true,
|
||||
|
||||
PermissionReq::GrpcRequest(_) | PermissionReq::BulkInsert { .. } => false,
|
||||
}
|
||||
@@ -241,6 +257,17 @@ pub trait PermissionChecker: Send + Sync {
|
||||
true
|
||||
}
|
||||
|
||||
/// Extracts user-visible gRPC targets before the frontend classifies them
|
||||
/// using catalog metadata. Unrecognized requests must fail closed.
|
||||
fn grpc_table_targets(
|
||||
&self,
|
||||
_request: &Request,
|
||||
_catalog: &str,
|
||||
_schema: &str,
|
||||
) -> PermissionTableTargets {
|
||||
PermissionTableTargets::Unresolved
|
||||
}
|
||||
|
||||
/// Checks the operation privilege and its resolved user-visible table targets.
|
||||
///
|
||||
/// [`PermissionTableTargets::Resolved`] with an empty vector still requires
|
||||
@@ -296,6 +323,18 @@ impl PermissionChecker for Option<&PermissionCheckerRef> {
|
||||
}
|
||||
}
|
||||
|
||||
fn grpc_table_targets(
|
||||
&self,
|
||||
request: &Request,
|
||||
catalog: &str,
|
||||
schema: &str,
|
||||
) -> PermissionTableTargets {
|
||||
match self {
|
||||
Some(checker) => checker.grpc_table_targets(request, catalog, schema),
|
||||
None => PermissionTableTargets::Unresolved,
|
||||
}
|
||||
}
|
||||
|
||||
fn check_permission_with_table_targets(
|
||||
&self,
|
||||
user_info: UserInfoRef,
|
||||
@@ -386,6 +425,20 @@ mod tests {
|
||||
Ok(PermissionResp::Reject)
|
||||
}
|
||||
|
||||
fn grpc_table_targets(
|
||||
&self,
|
||||
request: &Request,
|
||||
catalog: &str,
|
||||
schema: &str,
|
||||
) -> PermissionTableTargets {
|
||||
match request {
|
||||
Request::RowInserts(requests) => {
|
||||
PermissionTableTargets::from_row_insert_requests(catalog, schema, requests)
|
||||
}
|
||||
_ => PermissionTableTargets::Unresolved,
|
||||
}
|
||||
}
|
||||
|
||||
fn check_permission_with_table_targets(
|
||||
&self,
|
||||
_user_info: UserInfoRef,
|
||||
@@ -600,8 +653,8 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn test_table_target_permission_forwarding() {
|
||||
let checker: PermissionCheckerRef = Arc::new(TargetAwarePermissionChecker);
|
||||
let checker = Some(&checker);
|
||||
let inner_checker: PermissionCheckerRef = Arc::new(TargetAwarePermissionChecker);
|
||||
let checker = Some(&inner_checker);
|
||||
assert!(checker.uses_table_targets());
|
||||
|
||||
let allowed = checker
|
||||
@@ -658,6 +711,25 @@ mod tests {
|
||||
|
||||
let no_checker: Option<&PermissionCheckerRef> = None;
|
||||
assert!(!no_checker.uses_table_targets());
|
||||
for request in [
|
||||
Request::RowInserts(RowInsertRequests {
|
||||
inserts: vec![api::v1::RowInsertRequest {
|
||||
table_name: "allowed".to_string(),
|
||||
..Default::default()
|
||||
}],
|
||||
}),
|
||||
Request::RowInserts(RowInsertRequests::default()),
|
||||
Request::Query(api::v1::QueryRequest::default()),
|
||||
] {
|
||||
assert_eq!(
|
||||
inner_checker.grpc_table_targets(&request, "catalog", "schema"),
|
||||
checker.grpc_table_targets(&request, "catalog", "schema"),
|
||||
);
|
||||
assert_eq!(
|
||||
PermissionTableTargets::Unresolved,
|
||||
no_checker.grpc_table_targets(&request, "catalog", "schema"),
|
||||
);
|
||||
}
|
||||
let allowed = no_checker
|
||||
.check_permission_with_table_targets(
|
||||
crate::userinfo_by_name(None),
|
||||
|
||||
@@ -15,6 +15,7 @@
|
||||
use async_trait::async_trait;
|
||||
use snafu::OptionExt;
|
||||
|
||||
use crate::common::REDACTED_USER_PROVIDER_OPTION;
|
||||
use crate::error::{InvalidConfigSnafu, Result};
|
||||
use crate::user_provider::{
|
||||
PgAuthInfo, UserInfoMap, authenticate_with_credential, load_credential_from_file,
|
||||
@@ -31,7 +32,7 @@ pub struct StaticUserProvider {
|
||||
impl StaticUserProvider {
|
||||
pub(crate) fn new(value: &str) -> Result<Self> {
|
||||
let (mode, content) = value.split_once(':').context(InvalidConfigSnafu {
|
||||
value: value.to_string(),
|
||||
value: REDACTED_USER_PROVIDER_OPTION,
|
||||
msg: "StaticUserProviderOption must be in format `<option>:<value>`",
|
||||
})?;
|
||||
match mode {
|
||||
@@ -43,7 +44,7 @@ impl StaticUserProvider {
|
||||
.split(',')
|
||||
.map(|kv| {
|
||||
parse_credential_line(kv).context(InvalidConfigSnafu {
|
||||
value: kv.to_string(),
|
||||
value: REDACTED_USER_PROVIDER_OPTION,
|
||||
msg: "StaticUserProviderOption cmd values must be in format `user=pwd[,user=pwd]`",
|
||||
})
|
||||
})
|
||||
@@ -53,7 +54,7 @@ impl StaticUserProvider {
|
||||
StaticUserProvider { users }
|
||||
}),
|
||||
_ => InvalidConfigSnafu {
|
||||
value: mode.to_string(),
|
||||
value: REDACTED_USER_PROVIDER_OPTION,
|
||||
msg: "StaticUserProviderOption must be in format `file:<path>` or `cmd:<values>`",
|
||||
}
|
||||
.fail(),
|
||||
|
||||
@@ -291,8 +291,9 @@ pub enum Error {
|
||||
location: Location,
|
||||
},
|
||||
|
||||
#[snafu(display("Failed to handle query"))]
|
||||
#[snafu(display("Failed to handle query, addr: {}", addr))]
|
||||
HandleQuery {
|
||||
addr: String,
|
||||
source: common_meta::error::Error,
|
||||
#[snafu(implicit)]
|
||||
location: Location,
|
||||
|
||||
@@ -25,11 +25,15 @@ use common_meta::rpc::procedure;
|
||||
use common_procedure::{ProcedureInfo, ProcedureState};
|
||||
use common_query::request::QueryRequest;
|
||||
use common_recordbatch::adapter::{AsyncRecordBatchStreamAdapter, DfRecordBatchStreamAdapter};
|
||||
use common_recordbatch::filter::MetadataFilter;
|
||||
use common_recordbatch::util::{ChainedRecordBatchStream, LimitedRecordBatchStream};
|
||||
use common_recordbatch::{DfSendableRecordBatchStream, SendableRecordBatchStream};
|
||||
use datafusion::common::Result;
|
||||
use common_recordbatch::{
|
||||
DfSendableRecordBatchStream, EmptyRecordBatchStream, SendableRecordBatchStream,
|
||||
};
|
||||
use datafusion::common::tree_node::TreeNodeRecursion;
|
||||
use datafusion::common::{Result, ScalarValue};
|
||||
use datafusion::execution::TaskContext;
|
||||
use datafusion::logical_expr::LogicalPlan;
|
||||
use datafusion::physical_expr::{EquivalenceProperties, Partitioning, PhysicalExpr};
|
||||
use datafusion::physical_plan::execution_plan::{Boundedness, EmissionType};
|
||||
use datafusion::physical_plan::{DisplayAs, DisplayFormatType, ExecutionPlan, PlanProperties};
|
||||
@@ -38,10 +42,13 @@ use datatypes::schema::SchemaRef;
|
||||
use futures_util::future::try_join_all;
|
||||
use meta_client::MetaClientRef;
|
||||
use snafu::ResultExt;
|
||||
use store_api::compaction_task;
|
||||
use store_api::storage::RegionId;
|
||||
|
||||
use crate::error;
|
||||
use crate::information_schema::{DatanodeInspectRequest, InformationExtension};
|
||||
use crate::information_schema::{
|
||||
DatanodeInspectKind, DatanodeInspectRequest, InformationExtension,
|
||||
};
|
||||
|
||||
pub struct DistributedInformationExtension {
|
||||
meta_client: MetaClientRef,
|
||||
@@ -60,18 +67,53 @@ impl DistributedInformationExtension {
|
||||
meta_client: MetaClientRef,
|
||||
datanode_manager: DatanodeManagerRef,
|
||||
request: DatanodeInspectRequest,
|
||||
) -> std::result::Result<SendableRecordBatchStream, crate::error::Error> {
|
||||
) -> crate::error::Result<SendableRecordBatchStream> {
|
||||
let nodes = meta_client
|
||||
.list_nodes(Some(Role::Datanode))
|
||||
.await
|
||||
.map_err(BoxedError::new)
|
||||
.context(crate::error::ListNodesSnafu)?;
|
||||
Self::inspect_nodes(datanode_manager, request, nodes).await
|
||||
}
|
||||
|
||||
/// Executes inspection against discovered nodes after applying safe node pruning.
|
||||
async fn inspect_nodes(
|
||||
datanode_manager: DatanodeManagerRef,
|
||||
request: DatanodeInspectRequest,
|
||||
nodes: Vec<NodeInfo>,
|
||||
) -> crate::error::Result<SendableRecordBatchStream> {
|
||||
let nodes = prune_compaction_nodes(&request, nodes);
|
||||
let limit = request.scan.limit;
|
||||
let plan = request
|
||||
.build_plan()
|
||||
.context(crate::error::DatafusionSnafu)?;
|
||||
let stream = Self::inspect_query_nodes(datanode_manager, plan, nodes).await?;
|
||||
match limit {
|
||||
Some(limit) => Ok(Box::pin(LimitedRecordBatchStream::new(stream, limit))),
|
||||
None => Ok(stream),
|
||||
}
|
||||
}
|
||||
|
||||
async fn inspect_query_stream(
|
||||
meta_client: MetaClientRef,
|
||||
datanode_manager: DatanodeManagerRef,
|
||||
plan: LogicalPlan,
|
||||
) -> crate::error::Result<SendableRecordBatchStream> {
|
||||
let nodes = meta_client
|
||||
.list_nodes(Some(Role::Datanode))
|
||||
.await
|
||||
.map_err(BoxedError::new)
|
||||
.context(crate::error::ListNodesSnafu)?;
|
||||
Self::inspect_query_nodes(datanode_manager, plan, nodes).await
|
||||
}
|
||||
|
||||
/// Shares query dispatch and empty-stream schema handling for scans and query plans.
|
||||
async fn inspect_query_nodes(
|
||||
datanode_manager: DatanodeManagerRef,
|
||||
plan: LogicalPlan,
|
||||
nodes: Vec<NodeInfo>,
|
||||
) -> crate::error::Result<SendableRecordBatchStream> {
|
||||
let schema = inspection_query_schema(&plan)?;
|
||||
let streams = try_join_all(nodes.into_iter().map(|node| {
|
||||
let datanode_manager = datanode_manager.clone();
|
||||
let plan = plan.clone();
|
||||
@@ -84,25 +126,62 @@ impl DistributedInformationExtension {
|
||||
header: None,
|
||||
})
|
||||
.await
|
||||
.context(crate::error::HandleQuerySnafu)
|
||||
.context(crate::error::HandleQuerySnafu {
|
||||
addr: node.peer.addr,
|
||||
})
|
||||
}
|
||||
}))
|
||||
.await?;
|
||||
|
||||
let chained =
|
||||
ChainedRecordBatchStream::new(streams).context(crate::error::CreateRecordBatchSnafu)?;
|
||||
match limit {
|
||||
Some(limit) => Ok(Box::pin(LimitedRecordBatchStream::new(
|
||||
Box::pin(chained),
|
||||
limit,
|
||||
))),
|
||||
None => Ok(Box::pin(chained)),
|
||||
}
|
||||
chain_inspection_streams(streams, schema)
|
||||
}
|
||||
}
|
||||
|
||||
fn inspection_query_schema(plan: &LogicalPlan) -> crate::error::Result<SchemaRef> {
|
||||
datatypes::schema::Schema::try_from(plan.schema().clone())
|
||||
.map(Arc::new)
|
||||
.map_err(|error| datafusion::common::DataFusionError::External(Box::new(error)))
|
||||
.context(crate::error::DatafusionSnafu)
|
||||
}
|
||||
|
||||
fn chain_inspection_streams(
|
||||
streams: Vec<SendableRecordBatchStream>,
|
||||
schema: SchemaRef,
|
||||
) -> crate::error::Result<SendableRecordBatchStream> {
|
||||
if streams.is_empty() {
|
||||
return Ok(Box::pin(EmptyRecordBatchStream::new(schema)));
|
||||
}
|
||||
Ok(Box::pin(
|
||||
ChainedRecordBatchStream::new(streams).context(crate::error::CreateRecordBatchSnafu)?,
|
||||
))
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
enum InspectPlan {
|
||||
Scan(DatanodeInspectRequest),
|
||||
Query(LogicalPlan),
|
||||
}
|
||||
|
||||
/// Prunes reporting nodes only for live compaction inspection. Region routes cannot
|
||||
/// locate tasks left on a former owner, so only known node IDs can exclude nodes.
|
||||
fn prune_compaction_nodes(request: &DatanodeInspectRequest, nodes: Vec<NodeInfo>) -> Vec<NodeInfo> {
|
||||
if request.kind != DatanodeInspectKind::CompactionTasks {
|
||||
return nodes;
|
||||
}
|
||||
let filter = MetadataFilter::new(&request.scan.filters);
|
||||
nodes
|
||||
.into_iter()
|
||||
.filter(|node| {
|
||||
filter.matches(|name| {
|
||||
(name == compaction_task::NODE_ID)
|
||||
.then_some(ScalarValue::UInt64(Some(node.peer.id)))
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
struct DistributedInspectExec {
|
||||
request: DatanodeInspectRequest,
|
||||
plan: InspectPlan,
|
||||
meta_client: MetaClientRef,
|
||||
datanode_manager: DatanodeManagerRef,
|
||||
schema: SchemaRef,
|
||||
@@ -113,7 +192,7 @@ struct DistributedInspectExec {
|
||||
impl std::fmt::Debug for DistributedInspectExec {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("DistributedInspectExec")
|
||||
.field("request", &self.request)
|
||||
.field("plan", &self.plan)
|
||||
.field("schema", &self.schema)
|
||||
.finish_non_exhaustive()
|
||||
}
|
||||
@@ -125,6 +204,20 @@ impl DistributedInspectExec {
|
||||
schema: SchemaRef,
|
||||
meta_client: MetaClientRef,
|
||||
datanode_manager: DatanodeManagerRef,
|
||||
) -> Self {
|
||||
Self::with_plan(
|
||||
InspectPlan::Scan(request),
|
||||
schema,
|
||||
meta_client,
|
||||
datanode_manager,
|
||||
)
|
||||
}
|
||||
|
||||
fn with_plan(
|
||||
plan: InspectPlan,
|
||||
schema: SchemaRef,
|
||||
meta_client: MetaClientRef,
|
||||
datanode_manager: DatanodeManagerRef,
|
||||
) -> Self {
|
||||
let arrow_schema = schema.arrow_schema().clone();
|
||||
let properties = Arc::new(PlanProperties::new(
|
||||
@@ -134,7 +227,7 @@ impl DistributedInspectExec {
|
||||
Boundedness::Bounded,
|
||||
));
|
||||
Self {
|
||||
request,
|
||||
plan,
|
||||
meta_client,
|
||||
datanode_manager,
|
||||
schema,
|
||||
@@ -146,11 +239,19 @@ impl DistributedInspectExec {
|
||||
|
||||
impl DisplayAs for DistributedInspectExec {
|
||||
fn fmt_as(&self, _t: DisplayFormatType, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(
|
||||
f,
|
||||
"DistributedInspectExec: kind={:?}, scan={}, schema={:?}",
|
||||
self.request.kind, self.request.scan, self.arrow_schema
|
||||
)
|
||||
match &self.plan {
|
||||
InspectPlan::Scan(request) => write!(
|
||||
f,
|
||||
"DistributedInspectExec: kind={:?}, scan={}, schema={:?}",
|
||||
request.kind, request.scan, self.arrow_schema
|
||||
),
|
||||
InspectPlan::Query(plan) => write!(
|
||||
f,
|
||||
"DistributedInspectExec: query={}, schema={:?}",
|
||||
plan.display_indent(),
|
||||
self.arrow_schema
|
||||
),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -205,15 +306,27 @@ impl ExecutionPlan for DistributedInspectExec {
|
||||
|
||||
let meta_client = self.meta_client.clone();
|
||||
let datanode_manager = self.datanode_manager.clone();
|
||||
let request = self.request.clone();
|
||||
let plan = self.plan.clone();
|
||||
let schema = self.schema.clone();
|
||||
let future = async move {
|
||||
DistributedInformationExtension::inspect_datanode_stream(
|
||||
meta_client,
|
||||
datanode_manager,
|
||||
request,
|
||||
)
|
||||
.await
|
||||
match plan {
|
||||
InspectPlan::Scan(request) => {
|
||||
DistributedInformationExtension::inspect_datanode_stream(
|
||||
meta_client,
|
||||
datanode_manager,
|
||||
request,
|
||||
)
|
||||
.await
|
||||
}
|
||||
InspectPlan::Query(plan) => {
|
||||
DistributedInformationExtension::inspect_query_stream(
|
||||
meta_client,
|
||||
datanode_manager,
|
||||
plan,
|
||||
)
|
||||
.await
|
||||
}
|
||||
}
|
||||
.map_err(BoxedError::new)
|
||||
.context(common_recordbatch::error::ExternalSnafu)
|
||||
};
|
||||
@@ -297,6 +410,23 @@ impl InformationExtension for DistributedInformationExtension {
|
||||
.await
|
||||
}
|
||||
|
||||
fn supports_inspect_query_plan(&self) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
fn inspect_datanode_query_plan(
|
||||
&self,
|
||||
plan: LogicalPlan,
|
||||
) -> crate::error::Result<Option<Arc<dyn ExecutionPlan>>> {
|
||||
let schema = inspection_query_schema(&plan)?;
|
||||
Ok(Some(Arc::new(DistributedInspectExec::with_plan(
|
||||
InspectPlan::Query(plan),
|
||||
schema,
|
||||
self.meta_client.clone(),
|
||||
self.datanode_manager.clone(),
|
||||
))))
|
||||
}
|
||||
|
||||
fn inspect_datanode_plan(
|
||||
&self,
|
||||
request: DatanodeInspectRequest,
|
||||
@@ -316,21 +446,198 @@ mod tests {
|
||||
use common_meta::node_manager::{DatanodeManager, DatanodeRef};
|
||||
use common_meta::peer::Peer;
|
||||
use datafusion::common::tree_node::TreeNode;
|
||||
use datafusion::logical_expr::LogicalPlan;
|
||||
use datafusion::datasource::empty::EmptyTable;
|
||||
use datafusion::logical_expr::{Expr, LogicalPlan};
|
||||
use datafusion::physical_plan::sorts::sort::SortExec;
|
||||
use datafusion::prelude::SessionContext;
|
||||
use datatypes::arrow::datatypes::DataType;
|
||||
use meta_client::client::MetaClientBuilder;
|
||||
use store_api::sst_entry::ManifestSstEntry;
|
||||
use store_api::storage::ScanRequest;
|
||||
|
||||
use store_api::compaction_task::CompactionTaskEntry;
|
||||
|
||||
use super::*;
|
||||
use crate::information_schema::DatanodeInspectKind;
|
||||
|
||||
struct UnusedDatanodeManager;
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl DatanodeManager for UnusedDatanodeManager {
|
||||
async fn datanode(&self, _node: &Peer) -> DatanodeRef {
|
||||
panic!("plan tests must not contact datanodes")
|
||||
panic!("this test must not contact datanodes")
|
||||
}
|
||||
}
|
||||
|
||||
fn inspection_nodes() -> Vec<NodeInfo> {
|
||||
[1, 2, 3]
|
||||
.into_iter()
|
||||
.map(|id| NodeInfo {
|
||||
peer: Peer::new(id, format!("datanode-{id}:3001")),
|
||||
last_activity_ts: 0,
|
||||
status: common_meta::cluster::NodeStatus::Standalone,
|
||||
version: String::new(),
|
||||
git_commit: String::new(),
|
||||
start_time_ms: 0,
|
||||
total_cpu_millicores: 0,
|
||||
total_memory_bytes: 0,
|
||||
cpu_usage_millicores: 0,
|
||||
memory_usage_bytes: 0,
|
||||
hostname: String::new(),
|
||||
env_vars: Default::default(),
|
||||
schedulable: None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Uses the default optimizer to produce the predicates seen by inspection scans.
|
||||
async fn compaction_sql_filters(predicate: Option<&str>) -> Vec<Expr> {
|
||||
let ctx = SessionContext::new();
|
||||
ctx.register_table(
|
||||
"compaction_tasks",
|
||||
Arc::new(EmptyTable::new(
|
||||
CompactionTaskEntry::schema().arrow_schema().clone(),
|
||||
)),
|
||||
)
|
||||
.unwrap();
|
||||
let mut sql = "SELECT * FROM compaction_tasks".to_string();
|
||||
if let Some(predicate) = predicate {
|
||||
sql.push_str(" WHERE ");
|
||||
sql.push_str(predicate);
|
||||
}
|
||||
let plan = ctx.sql(&sql).await.unwrap().into_optimized_plan().unwrap();
|
||||
let mut filters = Vec::new();
|
||||
plan.apply(|plan| {
|
||||
match plan {
|
||||
LogicalPlan::Filter(filter) => filters.push(filter.predicate.clone()),
|
||||
LogicalPlan::TableScan(scan) => filters.extend(scan.filters.iter().cloned()),
|
||||
_ => {}
|
||||
}
|
||||
Ok(TreeNodeRecursion::Continue)
|
||||
})
|
||||
.unwrap();
|
||||
filters
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_compaction_node_pruning() {
|
||||
for (predicate, expected, expect_cast) in [
|
||||
(Some("node_id = 2"), vec![2], false),
|
||||
(Some("node_id != 2"), vec![1, 3], false),
|
||||
(Some("node_id > 2"), vec![3], false),
|
||||
(Some("node_id >= 2"), vec![2, 3], false),
|
||||
(Some("node_id < 2"), vec![1], false),
|
||||
(Some("node_id <= 2"), vec![1, 2], false),
|
||||
(Some("2 = node_id"), vec![2], false),
|
||||
(Some("2 < node_id"), vec![3], false),
|
||||
(None, vec![1, 2, 3], false),
|
||||
(Some("state = 'running'"), vec![1, 2, 3], false),
|
||||
(Some("node_id = 2 OR table_id = 42"), vec![1, 2, 3], false),
|
||||
(Some("node_id = 2 AND state = 'running'"), vec![2], false),
|
||||
] {
|
||||
let filters = compaction_sql_filters(predicate).await;
|
||||
let mut has_cast = false;
|
||||
for filter in &filters {
|
||||
filter
|
||||
.apply(|expr| {
|
||||
has_cast |= matches!(expr, Expr::Cast(cast) if cast.field.data_type() == &DataType::Decimal128(20, 0)
|
||||
&& matches!(cast.expr.as_ref(), Expr::Column(_)));
|
||||
Ok(TreeNodeRecursion::Continue)
|
||||
})
|
||||
.unwrap();
|
||||
}
|
||||
assert_eq!(has_cast, expect_cast, "optimized predicate: {predicate:?}");
|
||||
let request = DatanodeInspectRequest {
|
||||
kind: DatanodeInspectKind::CompactionTasks,
|
||||
scan: ScanRequest {
|
||||
filters,
|
||||
..Default::default()
|
||||
},
|
||||
};
|
||||
let actual: Vec<_> = prune_compaction_nodes(&request, inspection_nodes())
|
||||
.into_iter()
|
||||
.map(|node| node.peer.id)
|
||||
.collect();
|
||||
assert_eq!(
|
||||
actual, expected,
|
||||
"{predicate:?}: {:?}",
|
||||
request.scan.filters
|
||||
);
|
||||
}
|
||||
let filters = compaction_sql_filters(Some("node_id = 99")).await;
|
||||
for kind in [
|
||||
DatanodeInspectKind::SstManifest,
|
||||
DatanodeInspectKind::SstStorage,
|
||||
DatanodeInspectKind::SstIndexMeta,
|
||||
DatanodeInspectKind::RegionInfo,
|
||||
] {
|
||||
let request = DatanodeInspectRequest {
|
||||
kind,
|
||||
scan: ScanRequest {
|
||||
filters: filters.clone(),
|
||||
..Default::default()
|
||||
},
|
||||
};
|
||||
let actual: Vec<_> = prune_compaction_nodes(&request, inspection_nodes())
|
||||
.into_iter()
|
||||
.map(|node| node.peer.id)
|
||||
.collect();
|
||||
assert_eq!(actual, vec![1, 2, 3]);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_compaction_empty_nodes_preserve_projected_schema() {
|
||||
let filters = compaction_sql_filters(Some("node_id = 99")).await;
|
||||
for nodes in [vec![], inspection_nodes()] {
|
||||
for (projection, expected) in [
|
||||
(
|
||||
vec![3, 0, 2],
|
||||
vec![
|
||||
("node_id", DataType::UInt64, true),
|
||||
("task_id", DataType::Utf8, false),
|
||||
("table_id", DataType::UInt32, false),
|
||||
],
|
||||
),
|
||||
(vec![], vec![]),
|
||||
] {
|
||||
let request = DatanodeInspectRequest {
|
||||
kind: DatanodeInspectKind::CompactionTasks,
|
||||
scan: ScanRequest {
|
||||
projection: Some(projection),
|
||||
filters: filters.clone(),
|
||||
..Default::default()
|
||||
},
|
||||
};
|
||||
// Panics if the production dispatch path contacts any excluded node.
|
||||
let stream = DistributedInformationExtension::inspect_nodes(
|
||||
Arc::new(UnusedDatanodeManager),
|
||||
request,
|
||||
nodes.clone(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let batches = common_recordbatch::RecordBatches::try_collect(stream)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
batches.iter().map(|batch| batch.num_rows()).sum::<usize>(),
|
||||
0
|
||||
);
|
||||
let schema = batches.schema();
|
||||
let actual: Vec<_> = schema
|
||||
.arrow_schema()
|
||||
.fields()
|
||||
.iter()
|
||||
.map(|field| {
|
||||
(
|
||||
field.name().as_str(),
|
||||
field.data_type().clone(),
|
||||
field.is_nullable(),
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(actual, expected);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -383,6 +690,55 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_inspection_query_plan_is_lazy_and_preserves_schema() {
|
||||
let ctx = datafusion::prelude::SessionContext::new();
|
||||
let remote = ctx
|
||||
.sql("SELECT count(*), sum(value) FROM (VALUES (1), (2)) AS t(value)")
|
||||
.await
|
||||
.unwrap()
|
||||
.into_unoptimized_plan();
|
||||
let extension = DistributedInformationExtension::new(
|
||||
Arc::new(MetaClientBuilder::new(0, api::v1::meta::Role::Frontend).build()),
|
||||
Arc::new(UnusedDatanodeManager),
|
||||
);
|
||||
assert!(extension.supports_inspect_query_plan());
|
||||
let exec = extension
|
||||
.inspect_datanode_query_plan(remote.clone())
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(exec.schema(), remote.schema().inner().clone());
|
||||
let inspect = exec.downcast_ref::<DistributedInspectExec>().unwrap();
|
||||
let InspectPlan::Query(plan) = &inspect.plan else {
|
||||
panic!("expected inspection query")
|
||||
};
|
||||
assert_eq!(plan, &remote);
|
||||
assert!(exec.children().is_empty());
|
||||
// Creating or dropping an unpolled execution must not contact metadata or datanodes.
|
||||
for _ in 0..2 {
|
||||
let stream = exec.execute(0, ctx.task_ctx()).unwrap();
|
||||
assert_eq!(stream.schema(), exec.schema());
|
||||
drop(stream);
|
||||
}
|
||||
assert!(exec.execute(1, ctx.task_ctx()).is_err());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_empty_inspection_query_stream_keeps_output_schema() {
|
||||
use futures_util::StreamExt;
|
||||
|
||||
let ctx = datafusion::prelude::SessionContext::new();
|
||||
let remote = ctx
|
||||
.sql("SELECT count(*), sum(value) FROM (VALUES (1)) AS t(value)")
|
||||
.await
|
||||
.unwrap()
|
||||
.into_unoptimized_plan();
|
||||
let schema = inspection_query_schema(&remote).unwrap();
|
||||
let mut stream = chain_inspection_streams(vec![], schema.clone()).unwrap();
|
||||
assert_eq!(stream.schema(), schema);
|
||||
assert!(stream.next().await.is_none());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_sql_manifest_sort_stays_on_frontend() {
|
||||
let ctx = datafusion::prelude::SessionContext::new();
|
||||
@@ -408,8 +764,11 @@ mod tests {
|
||||
if let Some(scan) = plan.downcast_ref::<DistributedInspectExec>() {
|
||||
found_scan = true;
|
||||
// All matching rows must reach the frontend global sort.
|
||||
assert_eq!(scan.request.scan.limit, None);
|
||||
let remote = scan.request.clone().build_plan().unwrap();
|
||||
let InspectPlan::Scan(request) = &scan.plan else {
|
||||
panic!("expected scan plan")
|
||||
};
|
||||
assert_eq!(request.scan.limit, None);
|
||||
let remote = request.clone().build_plan().unwrap();
|
||||
remote.apply(|node| {
|
||||
assert!(!matches!(
|
||||
node,
|
||||
|
||||
@@ -41,8 +41,14 @@ pub type ProcessManagerRef = Arc<ProcessManager>;
|
||||
|
||||
/// Query process manager.
|
||||
pub struct ProcessManager {
|
||||
/// Local frontend server address,
|
||||
server_addr: String,
|
||||
/// Address this frontend advertises to the cluster.
|
||||
///
|
||||
/// It is the heartbeat peer address, which is also the only address other
|
||||
/// frontends use to reach this node's process management service. The same
|
||||
/// value identifies processes owned by this frontend and routes kill
|
||||
/// requests, so discovery addresses and process addresses share one
|
||||
/// namespace.
|
||||
peer_addr: String,
|
||||
/// Next process id for local queries.
|
||||
next_id: AtomicU32,
|
||||
/// Running process per catalog.
|
||||
@@ -79,11 +85,15 @@ impl Display for QueryStatement {
|
||||
}
|
||||
|
||||
impl ProcessManager {
|
||||
/// Create a [ProcessManager] instance with server address and kv client.
|
||||
pub fn new(server_addr: String, meta_client: Option<MetaClientRef>) -> Self {
|
||||
/// Creates a [ProcessManager] for the frontend identified by `peer_addr`.
|
||||
///
|
||||
/// `peer_addr` must be the address the frontend advertises to metasrv, not
|
||||
/// its public gRPC address: discovered peers are matched by that address to
|
||||
/// exclude this node from remote listings and to route kill requests.
|
||||
pub fn new(peer_addr: String, meta_client: Option<MetaClientRef>) -> Self {
|
||||
let frontend_selector = meta_client.map(MetaClientSelector::new);
|
||||
Self {
|
||||
server_addr,
|
||||
peer_addr,
|
||||
next_id: Default::default(),
|
||||
catalogs: Default::default(),
|
||||
frontend_selector,
|
||||
@@ -111,7 +121,7 @@ impl ProcessManager {
|
||||
query,
|
||||
start_timestamp: current_time_millis(),
|
||||
client,
|
||||
frontend: self.server_addr.clone(),
|
||||
frontend: self.peer_addr.clone(),
|
||||
};
|
||||
let cancellation_handle = Arc::new(CancellationHandle::default());
|
||||
let cancellable_process = CancellableProcess::new(cancellation_handle.clone(), process);
|
||||
@@ -168,6 +178,10 @@ impl ProcessManager {
|
||||
|
||||
/// Lists running processes from every selected frontend and the local registry.
|
||||
///
|
||||
/// The local frontend is excluded from the remote selection by its advertised
|
||||
/// peer address, which is what [`MetaClientSelector`] discovers. Its processes
|
||||
/// are appended from the local registry exactly once.
|
||||
///
|
||||
/// Returns an error if a remote frontend cannot provide its process list.
|
||||
pub async fn list_all_processes(
|
||||
&self,
|
||||
@@ -176,7 +190,7 @@ impl ProcessManager {
|
||||
let mut processes = vec![];
|
||||
if let Some(remote_frontend_selector) = self.frontend_selector.as_ref() {
|
||||
let frontends = remote_frontend_selector
|
||||
.select(|peer| peer.addr != self.server_addr)
|
||||
.select(|peer| peer.addr != self.peer_addr)
|
||||
.await
|
||||
.context(error::InvokeFrontendSnafu)?;
|
||||
for mut f in frontends {
|
||||
@@ -194,29 +208,32 @@ impl ProcessManager {
|
||||
}
|
||||
|
||||
/// Kills query with provided catalog and id.
|
||||
///
|
||||
/// `peer_addr` is the frontend address from the process id, which is the
|
||||
/// advertised peer address of the frontend that owns the process.
|
||||
pub async fn kill_process(
|
||||
&self,
|
||||
server_addr: String,
|
||||
peer_addr: String,
|
||||
catalog: String,
|
||||
id: ProcessId,
|
||||
) -> error::Result<bool> {
|
||||
if server_addr == self.server_addr {
|
||||
if peer_addr == self.peer_addr {
|
||||
self.kill_local_process(catalog, id).await
|
||||
} else {
|
||||
let mut nodes = self
|
||||
.frontend_selector
|
||||
.as_ref()
|
||||
.context(error::MetaClientMissingSnafu)?
|
||||
.select(|peer| peer.addr == server_addr)
|
||||
.select(|peer| peer.addr == peer_addr)
|
||||
.await
|
||||
.context(error::InvokeFrontendSnafu)?;
|
||||
ensure!(
|
||||
!nodes.is_empty(),
|
||||
error::FrontendNotFoundSnafu { addr: server_addr }
|
||||
error::FrontendNotFoundSnafu { addr: peer_addr }
|
||||
);
|
||||
|
||||
let request = KillProcessRequest {
|
||||
server_addr,
|
||||
server_addr: peer_addr,
|
||||
catalog,
|
||||
process_id: id,
|
||||
};
|
||||
|
||||
@@ -14,6 +14,7 @@
|
||||
|
||||
mod cluster_info;
|
||||
pub mod columns;
|
||||
mod compaction_tasks;
|
||||
pub mod flow_statistics;
|
||||
pub mod flows;
|
||||
mod information_memory_table;
|
||||
@@ -58,6 +59,7 @@ use lazy_static::lazy_static;
|
||||
use paste::paste;
|
||||
use process_list::InformationSchemaProcessList;
|
||||
use region_info::InformationSchemaRegionInfo;
|
||||
use store_api::compaction_task::CompactionTaskEntry;
|
||||
use store_api::metric_engine_consts::{
|
||||
MEMTABLE_PARTITION_TREE_PRIMARY_KEY_ENCODING, PRIMARY_KEY_ENCODING,
|
||||
};
|
||||
@@ -74,6 +76,7 @@ use crate::CatalogManager;
|
||||
use crate::error::Error;
|
||||
use crate::process_manager::ProcessManagerRef;
|
||||
use crate::system_schema::information_schema::cluster_info::InformationSchemaClusterInfo;
|
||||
use crate::system_schema::information_schema::compaction_tasks::InformationSchemaCompactionTasks;
|
||||
use crate::system_schema::information_schema::flow_statistics::InformationSchemaFlowStatistics;
|
||||
use crate::system_schema::information_schema::flows::InformationSchemaFlows;
|
||||
use crate::system_schema::information_schema::information_memory_table::get_schema_columns;
|
||||
@@ -312,6 +315,9 @@ impl InformationSchemaProvider {
|
||||
self.catalog_manager.clone(),
|
||||
),
|
||||
) as _),
|
||||
COMPACTION_TASKS => Some(Arc::new(InformationSchemaCompactionTasks::new(
|
||||
self.catalog_manager.clone(),
|
||||
)) as _),
|
||||
REGION_INFO => Some(Arc::new(InformationSchemaRegionInfo::new(
|
||||
self.catalog_manager.clone(),
|
||||
)) as _),
|
||||
@@ -382,6 +388,7 @@ impl InformationSchemaProvider {
|
||||
CLUSTER_INFO,
|
||||
PROCEDURE_INFO,
|
||||
REGION_STATISTICS,
|
||||
COMPACTION_TASKS,
|
||||
REGION_INFO,
|
||||
SSTS_MANIFEST,
|
||||
SSTS_STORAGE,
|
||||
@@ -466,6 +473,21 @@ pub trait InformationExtension {
|
||||
request: DatanodeInspectRequest,
|
||||
) -> std::result::Result<SendableRecordBatchStream, Self::Error>;
|
||||
|
||||
/// Whether this extension can execute an inspection query on every datanode.
|
||||
fn supports_inspect_query_plan(&self) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
/// Builds a plan that executes an inspection query independently on each datanode.
|
||||
/// The caller supplies a plan over reserved inspection tables and retains any
|
||||
/// required global aggregation. The returned schema is the query output schema.
|
||||
fn inspect_datanode_query_plan(
|
||||
&self,
|
||||
_plan: LogicalPlan,
|
||||
) -> std::result::Result<Option<Arc<dyn ExecutionPlan>>, Self::Error> {
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
/// Builds a physical plan for datanode inspect if the extension can expose
|
||||
/// the distributed fan-in semantics to DataFusion.
|
||||
fn inspect_datanode_plan(
|
||||
@@ -491,6 +513,8 @@ pub struct DatanodeInspectRequest {
|
||||
/// The kind of the datanode inspect request.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum DatanodeInspectKind {
|
||||
/// Live compaction cycles.
|
||||
CompactionTasks,
|
||||
/// List SST entries recorded in manifest
|
||||
SstManifest,
|
||||
/// List SST entries discovered in storage layer
|
||||
@@ -505,6 +529,7 @@ impl DatanodeInspectRequest {
|
||||
/// Builds a logical plan for the datanode inspect request.
|
||||
pub fn build_plan(self) -> std::result::Result<LogicalPlan, DataFusionError> {
|
||||
match self.kind {
|
||||
DatanodeInspectKind::CompactionTasks => CompactionTaskEntry::build_plan(self.scan),
|
||||
DatanodeInspectKind::SstManifest => ManifestSstEntry::build_plan(self.scan),
|
||||
DatanodeInspectKind::SstStorage => StorageSstEntry::build_plan(self.scan),
|
||||
DatanodeInspectKind::SstIndexMeta => PuffinIndexMetaEntry::build_plan(self.scan),
|
||||
@@ -689,11 +714,11 @@ mod tests {
|
||||
// An extension replacing a built-in supplies the replacement table's scope.
|
||||
let provider = provider.with_extra_table_factories(factories.clone());
|
||||
let expected_count =
|
||||
44 + usize::from(with_process_manager) + usize::from(cfg!(feature = "enterprise"))
|
||||
45 + usize::from(with_process_manager) + usize::from(cfg!(feature = "enterprise"))
|
||||
- if catalog == DEFAULT_CATALOG_NAME {
|
||||
0
|
||||
} else {
|
||||
8
|
||||
9
|
||||
};
|
||||
assert_eq!(provider.tables().len(), expected_count);
|
||||
for (name, table) in provider.tables() {
|
||||
@@ -809,6 +834,29 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_compaction_tasks_build_plan() {
|
||||
let request = DatanodeInspectRequest {
|
||||
kind: DatanodeInspectKind::CompactionTasks,
|
||||
scan: ScanRequest {
|
||||
projection: Some(vec![0]),
|
||||
filters: vec![
|
||||
datafusion::logical_expr::col("state")
|
||||
.eq(datafusion::logical_expr::lit("running")),
|
||||
],
|
||||
limit: Some(1),
|
||||
..Default::default()
|
||||
},
|
||||
};
|
||||
let plan = request.build_plan().unwrap();
|
||||
assert_eq!(plan.schema().fields().len(), 1);
|
||||
assert!(
|
||||
plan.display_indent()
|
||||
.to_string()
|
||||
.contains("__compaction_tasks")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_datanode_inspect_region_info_build_plan() {
|
||||
let plan = DatanodeInspectRequest {
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
// Copyright 2023 Greptime Team
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
use std::sync::{Arc, Weak};
|
||||
|
||||
use common_catalog::consts::INFORMATION_SCHEMA_COMPACTION_TASKS_TABLE_ID;
|
||||
use common_error::ext::BoxedError;
|
||||
use common_recordbatch::SendableRecordBatchStream;
|
||||
use common_recordbatch::adapter::AsyncRecordBatchStreamAdapter;
|
||||
use datafusion::physical_plan::ExecutionPlan;
|
||||
use datatypes::schema::SchemaRef;
|
||||
use snafu::ResultExt;
|
||||
use store_api::compaction_task::CompactionTaskEntry;
|
||||
use store_api::storage::{ScanRequest, TableId};
|
||||
|
||||
use crate::CatalogManager;
|
||||
use crate::error::Result;
|
||||
use crate::information_schema::{
|
||||
COMPACTION_TASKS, DatanodeInspectKind, InformationSchemaTableScope, InformationTable,
|
||||
};
|
||||
use crate::system_schema::SystemTable;
|
||||
use crate::system_schema::utils;
|
||||
|
||||
/// Information schema table for live compaction tasks.
|
||||
pub struct InformationSchemaCompactionTasks {
|
||||
schema: SchemaRef,
|
||||
catalog_manager: Weak<dyn CatalogManager>,
|
||||
}
|
||||
|
||||
impl InformationSchemaCompactionTasks {
|
||||
pub(crate) fn new(catalog_manager: Weak<dyn CatalogManager>) -> Self {
|
||||
Self {
|
||||
schema: CompactionTaskEntry::schema(),
|
||||
catalog_manager,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl InformationTable for InformationSchemaCompactionTasks {
|
||||
fn scope(&self) -> InformationSchemaTableScope {
|
||||
InformationSchemaTableScope::Global
|
||||
}
|
||||
}
|
||||
|
||||
impl SystemTable for InformationSchemaCompactionTasks {
|
||||
fn table_id(&self) -> TableId {
|
||||
INFORMATION_SCHEMA_COMPACTION_TASKS_TABLE_ID
|
||||
}
|
||||
|
||||
fn table_name(&self) -> &'static str {
|
||||
COMPACTION_TASKS
|
||||
}
|
||||
|
||||
fn schema(&self) -> SchemaRef {
|
||||
self.schema.clone()
|
||||
}
|
||||
|
||||
fn to_stream(&self, request: ScanRequest) -> Result<SendableRecordBatchStream> {
|
||||
let schema = utils::projected_schema(&self.schema, &request)?;
|
||||
|
||||
let info_ext = utils::information_extension(&self.catalog_manager)?;
|
||||
let req =
|
||||
utils::inspect_request(DatanodeInspectKind::CompactionTasks, &self.schema, request)?;
|
||||
|
||||
let future = async move {
|
||||
info_ext
|
||||
.inspect_datanode(req)
|
||||
.await
|
||||
.map_err(BoxedError::new)
|
||||
.context(common_recordbatch::error::ExternalSnafu)
|
||||
};
|
||||
Ok(Box::pin(AsyncRecordBatchStreamAdapter::new(
|
||||
schema,
|
||||
Box::pin(future),
|
||||
)))
|
||||
}
|
||||
|
||||
fn scan_plan(&self, request: ScanRequest) -> Result<Option<Arc<dyn ExecutionPlan>>> {
|
||||
utils::inspect_plan(
|
||||
&self.catalog_manager,
|
||||
DatanodeInspectKind::CompactionTasks,
|
||||
&self.schema,
|
||||
request,
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -75,7 +75,12 @@ const INIT_CAPACITY: usize = 42;
|
||||
/// - `query_scanned_bytes`: The total bytes scanned by queries since region opened.
|
||||
/// - `memtable_size`: The memtable size in bytes.
|
||||
/// - `disk_size`: The approximate disk size in bytes.
|
||||
/// - `manifest_size`: The manifest size in bytes.
|
||||
/// - `manifest_size`: Stored bytes of the latest observed checkpoint and subsequent
|
||||
/// deltas (compressed when enabled), excluding staging and `_last_checkpoint`.
|
||||
/// Older files retained on disk, including failed deletions, are not counted.
|
||||
/// Followers update this estimate on sync; metadata read failures can leave it stale.
|
||||
/// Promotion does not refresh it, so an incomplete estimate can persist without
|
||||
/// further syncs or checkpoints.
|
||||
/// - `sst_size`: The sst data files size in bytes.
|
||||
/// - `index_size`: The sst index files size in bytes.
|
||||
/// - `engine`: The engine type.
|
||||
|
||||
@@ -28,38 +28,14 @@ use store_api::sst_entry::{ManifestSstEntry, PuffinIndexMetaEntry, StorageSstEnt
|
||||
use store_api::storage::{ScanRequest, TableId};
|
||||
|
||||
use crate::CatalogManager;
|
||||
use crate::error::{ProjectSchemaSnafu, Result};
|
||||
use crate::error::Result;
|
||||
use crate::information_schema::{
|
||||
DatanodeInspectKind, DatanodeInspectRequest, InformationSchemaTableScope, InformationTable,
|
||||
SSTS_INDEX_META, SSTS_MANIFEST, SSTS_STORAGE,
|
||||
DatanodeInspectKind, InformationSchemaTableScope, InformationTable, SSTS_INDEX_META,
|
||||
SSTS_MANIFEST, SSTS_STORAGE,
|
||||
};
|
||||
use crate::system_schema::SystemTable;
|
||||
use crate::system_schema::utils;
|
||||
|
||||
fn projected_schema(schema: &SchemaRef, request: &ScanRequest) -> Result<SchemaRef> {
|
||||
if let Some(p) = request.projection.as_deref() {
|
||||
Ok(Arc::new(schema.try_project(p).context(ProjectSchemaSnafu)?))
|
||||
} else {
|
||||
Ok(schema.clone())
|
||||
}
|
||||
}
|
||||
|
||||
fn inspect_plan(
|
||||
catalog_manager: &Weak<dyn CatalogManager>,
|
||||
kind: DatanodeInspectKind,
|
||||
schema: &SchemaRef,
|
||||
request: ScanRequest,
|
||||
) -> Result<Option<Arc<dyn ExecutionPlan>>> {
|
||||
let projected_schema = projected_schema(schema, &request)?;
|
||||
let info_ext = utils::information_extension(catalog_manager)?;
|
||||
let req = DatanodeInspectRequest {
|
||||
kind,
|
||||
scan: request,
|
||||
};
|
||||
|
||||
info_ext.inspect_datanode_plan(req, projected_schema)
|
||||
}
|
||||
|
||||
/// Information schema table for sst manifest.
|
||||
pub struct InformationSchemaSstsManifest {
|
||||
schema: SchemaRef,
|
||||
@@ -95,12 +71,9 @@ impl SystemTable for InformationSchemaSstsManifest {
|
||||
}
|
||||
|
||||
fn to_stream(&self, request: ScanRequest) -> Result<SendableRecordBatchStream> {
|
||||
let schema = projected_schema(&self.schema, &request)?;
|
||||
let schema = utils::projected_schema(&self.schema, &request)?;
|
||||
let info_ext = utils::information_extension(&self.catalog_manager)?;
|
||||
let req = DatanodeInspectRequest {
|
||||
kind: DatanodeInspectKind::SstManifest,
|
||||
scan: request,
|
||||
};
|
||||
let req = utils::inspect_request(DatanodeInspectKind::SstManifest, &self.schema, request)?;
|
||||
|
||||
let future = async move {
|
||||
info_ext
|
||||
@@ -116,7 +89,7 @@ impl SystemTable for InformationSchemaSstsManifest {
|
||||
}
|
||||
|
||||
fn scan_plan(&self, request: ScanRequest) -> Result<Option<Arc<dyn ExecutionPlan>>> {
|
||||
inspect_plan(
|
||||
utils::inspect_plan(
|
||||
&self.catalog_manager,
|
||||
DatanodeInspectKind::SstManifest,
|
||||
&self.schema,
|
||||
@@ -160,13 +133,10 @@ impl SystemTable for InformationSchemaSstsStorage {
|
||||
}
|
||||
|
||||
fn to_stream(&self, request: ScanRequest) -> Result<SendableRecordBatchStream> {
|
||||
let schema = projected_schema(&self.schema, &request)?;
|
||||
let schema = utils::projected_schema(&self.schema, &request)?;
|
||||
|
||||
let info_ext = utils::information_extension(&self.catalog_manager)?;
|
||||
let req = DatanodeInspectRequest {
|
||||
kind: DatanodeInspectKind::SstStorage,
|
||||
scan: request,
|
||||
};
|
||||
let req = utils::inspect_request(DatanodeInspectKind::SstStorage, &self.schema, request)?;
|
||||
|
||||
let future = async move {
|
||||
info_ext
|
||||
@@ -182,7 +152,7 @@ impl SystemTable for InformationSchemaSstsStorage {
|
||||
}
|
||||
|
||||
fn scan_plan(&self, request: ScanRequest) -> Result<Option<Arc<dyn ExecutionPlan>>> {
|
||||
inspect_plan(
|
||||
utils::inspect_plan(
|
||||
&self.catalog_manager,
|
||||
DatanodeInspectKind::SstStorage,
|
||||
&self.schema,
|
||||
@@ -226,13 +196,10 @@ impl SystemTable for InformationSchemaSstsIndexMeta {
|
||||
}
|
||||
|
||||
fn to_stream(&self, request: ScanRequest) -> Result<SendableRecordBatchStream> {
|
||||
let schema = projected_schema(&self.schema, &request)?;
|
||||
let schema = utils::projected_schema(&self.schema, &request)?;
|
||||
|
||||
let info_ext = utils::information_extension(&self.catalog_manager)?;
|
||||
let req = DatanodeInspectRequest {
|
||||
kind: DatanodeInspectKind::SstIndexMeta,
|
||||
scan: request,
|
||||
};
|
||||
let req = utils::inspect_request(DatanodeInspectKind::SstIndexMeta, &self.schema, request)?;
|
||||
|
||||
let future = async move {
|
||||
info_ext
|
||||
@@ -248,7 +215,7 @@ impl SystemTable for InformationSchemaSstsIndexMeta {
|
||||
}
|
||||
|
||||
fn scan_plan(&self, request: ScanRequest) -> Result<Option<Arc<dyn ExecutionPlan>>> {
|
||||
inspect_plan(
|
||||
utils::inspect_plan(
|
||||
&self.catalog_manager,
|
||||
DatanodeInspectKind::SstIndexMeta,
|
||||
&self.schema,
|
||||
@@ -259,6 +226,7 @@ impl SystemTable for InformationSchemaSstsIndexMeta {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::information_schema::DatanodeInspectRequest;
|
||||
use cache::{build_fundamental_cache_registry, with_default_composite_cache_registry};
|
||||
use common_catalog::consts::{DEFAULT_CATALOG_NAME, INFORMATION_SCHEMA_NAME};
|
||||
use common_meta::cache::{CacheRegistryBuilder, LayeredCacheRegistryBuilder};
|
||||
@@ -317,6 +285,63 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_inspect_request_keeps_unsafe_filters_on_frontend() {
|
||||
use datafusion::arrow::datatypes::{DataType, TimeUnit};
|
||||
use datafusion::logical_expr::expr::Cast;
|
||||
use datafusion::logical_expr::{Expr, col, lit};
|
||||
|
||||
for (kind, schema) in [
|
||||
(
|
||||
DatanodeInspectKind::CompactionTasks,
|
||||
store_api::compaction_task::CompactionTaskEntry::schema(),
|
||||
),
|
||||
(DatanodeInspectKind::SstManifest, ManifestSstEntry::schema()),
|
||||
(DatanodeInspectKind::SstStorage, StorageSstEntry::schema()),
|
||||
(
|
||||
DatanodeInspectKind::SstIndexMeta,
|
||||
PuffinIndexMetaEntry::schema(),
|
||||
),
|
||||
] {
|
||||
let safe = col(&schema.column_schemas()[0].name).is_not_null();
|
||||
let scan = ScanRequest {
|
||||
projection: Some(vec![0]),
|
||||
filters: vec![safe.clone()],
|
||||
limit: Some(1),
|
||||
..Default::default()
|
||||
};
|
||||
assert_eq!(
|
||||
utils::inspect_request(kind, &schema, scan.clone()).unwrap(),
|
||||
DatanodeInspectRequest {
|
||||
kind,
|
||||
scan: scan.clone()
|
||||
}
|
||||
);
|
||||
for unsafe_filter in [
|
||||
Expr::Cast(Cast::new(
|
||||
Box::new(lit(0_i64)),
|
||||
DataType::Timestamp(TimeUnit::Nanosecond, Some("+08:00".into())),
|
||||
))
|
||||
.is_not_null(),
|
||||
Expr::Cast(Cast::new(Box::new(lit(1_i64)), DataType::Decimal32(9, 0)))
|
||||
.is_not_null(),
|
||||
col("missing_column").is_null(),
|
||||
] {
|
||||
let mut input = scan.clone();
|
||||
input.filters.push(unsafe_filter);
|
||||
let mut expected = scan.clone();
|
||||
expected.limit = None;
|
||||
assert_eq!(
|
||||
utils::inspect_request(kind, &schema, input).unwrap(),
|
||||
DatanodeInspectRequest {
|
||||
kind,
|
||||
scan: expected
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn ssts_manifest_uses_information_extension_scan_plan() {
|
||||
let backend = Arc::new(MemoryKvBackend::default());
|
||||
|
||||
@@ -60,3 +60,6 @@ pub const USER_PRIVILEGES: &str = "user_privileges";
|
||||
/// MySQL's session list. GreptimeDB reports its own sessions through [`PROCESS_LIST`];
|
||||
/// this table only exists so MySQL tooling finds the name and column shape it expects.
|
||||
pub const PROCESSLIST: &str = "processlist";
|
||||
|
||||
/// Live compaction tasks.
|
||||
pub const COMPACTION_TASKS: &str = "compaction_tasks";
|
||||
|
||||
@@ -12,18 +12,82 @@
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
use std::sync::Weak;
|
||||
pub mod tables;
|
||||
|
||||
use std::sync::{Arc, Weak};
|
||||
|
||||
use common_meta::key::TableMetadataManagerRef;
|
||||
use snafu::OptionExt;
|
||||
use common_query::logical_plan::is_lossless_substrait_type;
|
||||
use datafusion::common::DFSchema;
|
||||
use datafusion::common::tree_node::{TreeNode, TreeNodeRecursion};
|
||||
use datafusion::logical_expr::ExprSchemable;
|
||||
use datafusion::physical_plan::ExecutionPlan;
|
||||
use datatypes::schema::SchemaRef;
|
||||
use snafu::{OptionExt, ResultExt};
|
||||
use store_api::storage::ScanRequest;
|
||||
|
||||
use crate::CatalogManager;
|
||||
use crate::error::{GetInformationExtensionSnafu, Result, UpgradeWeakCatalogManagerRefSnafu};
|
||||
use crate::information_schema::InformationExtensionRef;
|
||||
use crate::error::{
|
||||
GetInformationExtensionSnafu, ProjectSchemaSnafu, Result, UpgradeWeakCatalogManagerRefSnafu,
|
||||
};
|
||||
use crate::information_schema::{
|
||||
DatanodeInspectKind, DatanodeInspectRequest, InformationExtensionRef,
|
||||
};
|
||||
use crate::kvbackend::KvBackendCatalogManager;
|
||||
use crate::system_schema::semantic_graph::EntityGraphProviderRef;
|
||||
|
||||
pub mod tables;
|
||||
/// Projects an inspection table schema according to the scan request.
|
||||
pub(crate) fn projected_schema(schema: &SchemaRef, request: &ScanRequest) -> Result<SchemaRef> {
|
||||
if let Some(p) = request.projection.as_deref() {
|
||||
Ok(Arc::new(schema.try_project(p).context(ProjectSchemaSnafu)?))
|
||||
} else {
|
||||
Ok(schema.clone())
|
||||
}
|
||||
}
|
||||
|
||||
/// Builds a datanode inspection plan with the requested output schema.
|
||||
pub(crate) fn inspect_plan(
|
||||
catalog_manager: &Weak<dyn CatalogManager>,
|
||||
kind: DatanodeInspectKind,
|
||||
schema: &SchemaRef,
|
||||
request: ScanRequest,
|
||||
) -> Result<Option<Arc<dyn ExecutionPlan>>> {
|
||||
let projected_schema = projected_schema(schema, &request)?;
|
||||
let info_ext = information_extension(catalog_manager)?;
|
||||
let req = inspect_request(kind, schema, request)?;
|
||||
|
||||
info_ext.inspect_datanode_plan(req, projected_schema)
|
||||
}
|
||||
|
||||
/// System table predicates are inexact: the frontend keeps a residual filter. Dropping
|
||||
/// an unsafe remote filter preserves correctness only if no remote limit truncates it.
|
||||
pub(crate) fn inspect_request(
|
||||
kind: DatanodeInspectKind,
|
||||
schema: &SchemaRef,
|
||||
mut scan: ScanRequest,
|
||||
) -> Result<DatanodeInspectRequest> {
|
||||
let schema =
|
||||
DFSchema::try_from(schema.arrow_schema().clone()).context(crate::error::DatafusionSnafu)?;
|
||||
let filter_count = scan.filters.len();
|
||||
scan.filters.retain(|filter| {
|
||||
let mut supported = true;
|
||||
let visited = filter.apply(|expr| {
|
||||
if !expr
|
||||
.get_type(&schema)
|
||||
.is_ok_and(|data_type| is_lossless_substrait_type(&data_type))
|
||||
{
|
||||
supported = false;
|
||||
return Ok(TreeNodeRecursion::Stop);
|
||||
}
|
||||
Ok(TreeNodeRecursion::Continue)
|
||||
});
|
||||
visited.is_ok() && supported
|
||||
});
|
||||
if scan.filters.len() != filter_count {
|
||||
scan.limit = None;
|
||||
}
|
||||
Ok(DatanodeInspectRequest { kind, scan })
|
||||
}
|
||||
|
||||
/// Try to get the entity-graph provider from a `[CatalogManager]` weak reference.
|
||||
/// Returns `None` when the manager is not the kv-backed one or the provider has
|
||||
|
||||
@@ -21,6 +21,8 @@ use async_trait::async_trait;
|
||||
use clap::Parser;
|
||||
use common_error::ext::BoxedError;
|
||||
use common_meta::key::{TableMetadataManager, TableMetadataManagerRef};
|
||||
#[cfg(any(feature = "pg_kvbackend", feature = "mysql_kvbackend"))]
|
||||
use common_meta::kv_backend::KvBackendRef;
|
||||
use common_meta::kv_backend::etcd::EtcdStore;
|
||||
use common_meta::kv_backend::memory::MemoryKvBackend;
|
||||
#[cfg(feature = "mysql_kvbackend")]
|
||||
@@ -86,7 +88,7 @@ impl BenchTableMetadataCommand {
|
||||
};
|
||||
|
||||
#[cfg(feature = "pg_kvbackend")]
|
||||
let kv_backend = if let Some(postgres_addr) = &self.postgres_addr {
|
||||
let kv_backend: KvBackendRef = if let Some(postgres_addr) = &self.postgres_addr {
|
||||
info!("Using postgres as kv backend");
|
||||
PgStore::with_url(postgres_addr, "greptime_metakv", 128)
|
||||
.await
|
||||
@@ -96,7 +98,7 @@ impl BenchTableMetadataCommand {
|
||||
};
|
||||
|
||||
#[cfg(feature = "mysql_kvbackend")]
|
||||
let kv_backend = if let Some(mysql_addr) = &self.mysql_addr {
|
||||
let kv_backend: KvBackendRef = if let Some(mysql_addr) = &self.mysql_addr {
|
||||
info!("Using mysql as kv backend");
|
||||
MySqlStore::with_url(mysql_addr, "greptime_metakv", 128)
|
||||
.await
|
||||
|
||||
@@ -209,7 +209,7 @@ wrap_with_clap_prefix! {
|
||||
#[doc = "The endpoint of the object store."]
|
||||
endpoint: String = Default::default(),
|
||||
#[doc = "The SAS token of the object store."]
|
||||
sas_token: Option<String>,
|
||||
sas_token: Option<SecretString>,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -151,7 +151,7 @@ impl StoreConfig {
|
||||
&self.sanitize_store_addrs(),
|
||||
self.backend
|
||||
);
|
||||
let kvbackend = match self.backend {
|
||||
let kvbackend: Result<KvBackendRef, BoxedError> = match self.backend {
|
||||
BackendImpl::EtcdStore => {
|
||||
let tls_config = self.tls_config();
|
||||
let etcd_client = create_etcd_client_with_tls(
|
||||
|
||||
@@ -368,7 +368,7 @@ fn build_gcs_connection(
|
||||
fn build_azblob_connection(storage: &ObjectStoreConfig) -> (String, Vec<Option<String>>) {
|
||||
let account_name = expose_optional_secret(&storage.azblob.azblob_account_name);
|
||||
let account_key = expose_optional_secret(&storage.azblob.azblob_account_key);
|
||||
let sas_token = storage.azblob.azblob_sas_token.clone();
|
||||
let sas_token = expose_optional_secret(&storage.azblob.azblob_sas_token);
|
||||
|
||||
let mut options = Vec::new();
|
||||
if let Some(account_name) = &account_name {
|
||||
@@ -390,7 +390,7 @@ fn build_azblob_connection(storage: &ObjectStoreConfig) -> (String, Vec<Option<S
|
||||
));
|
||||
}
|
||||
|
||||
let secrets = vec![account_name, account_key, sas_token];
|
||||
let secrets = vec![sas_token, account_name, account_key];
|
||||
let connection = if options.is_empty() {
|
||||
String::new()
|
||||
} else {
|
||||
@@ -405,16 +405,18 @@ fn expose_optional_secret(secret: &Option<SecretString>) -> Option<String> {
|
||||
|
||||
fn mask_secrets(sql: &str, secrets: &[Option<String>]) -> String {
|
||||
let mut masked = sql.to_string();
|
||||
let mut secrets: Vec<_> = secrets
|
||||
.iter()
|
||||
.flatten()
|
||||
.filter(|secret| !secret.is_empty())
|
||||
.collect();
|
||||
secrets.sort_by_key(|secret| std::cmp::Reverse(secret.len()));
|
||||
for secret in secrets {
|
||||
if let Some(secret) = secret
|
||||
&& !secret.is_empty()
|
||||
{
|
||||
let escaped = escape_sql_literal(secret);
|
||||
if escaped != *secret {
|
||||
masked = masked.replace(&escaped, "[REDACTED]");
|
||||
}
|
||||
masked = masked.replace(secret, "[REDACTED]");
|
||||
let escaped = escape_sql_literal(secret);
|
||||
if escaped != *secret {
|
||||
masked = masked.replace(&escaped, "[REDACTED]");
|
||||
}
|
||||
masked = masked.replace(secret, "[REDACTED]");
|
||||
}
|
||||
masked
|
||||
}
|
||||
@@ -518,9 +520,9 @@ mod tests {
|
||||
fn test_build_azblob_connection_redacts_sas_token() {
|
||||
let storage = ObjectStoreConfig {
|
||||
azblob: PrefixedAzblobConnection {
|
||||
azblob_account_name: Some(SecretString::from("account".to_string())),
|
||||
azblob_account_key: Some(SecretString::from("key".to_string())),
|
||||
azblob_sas_token: Some("sig=secret-token".to_string()),
|
||||
azblob_account_name: Some(SecretString::from("sig".to_string())),
|
||||
azblob_account_key: Some(SecretString::from("prefix_sig_CANARY_KEY".to_string())),
|
||||
azblob_sas_token: Some("sv=2024-11-04&sig=CANARY_SIGNATURE".to_string().into()),
|
||||
..Default::default()
|
||||
},
|
||||
..Default::default()
|
||||
@@ -529,16 +531,18 @@ mod tests {
|
||||
let (connection, secrets) = build_azblob_connection(&storage);
|
||||
let masked = mask_secrets(&connection, &secrets);
|
||||
|
||||
assert!(connection.contains("SAS_TOKEN='sig=secret-token'"));
|
||||
assert!(connection.contains("SAS_TOKEN='sv=2024-11-04&sig=CANARY_SIGNATURE'"));
|
||||
assert!(masked.contains("SAS_TOKEN='[REDACTED]'"));
|
||||
assert!(!masked.contains("sig=secret-token"));
|
||||
assert!(!masked.contains("CANARY_SIGNATURE"));
|
||||
assert!(masked.contains("ACCOUNT_KEY='[REDACTED]'"));
|
||||
assert!(!masked.contains("CANARY_KEY"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_mask_secrets_redacts_sql_escaped_literals() {
|
||||
let sql =
|
||||
"COPY DATABASE \"greptime\".\"public\" TO 's3://bucket' CONNECTION (SECRET='ab''cd');";
|
||||
let masked = mask_secrets(sql, &[Some("ab'cd".to_string())]);
|
||||
let masked = mask_secrets(sql, &[Some("ab".to_string()), Some("ab'cd".to_string())]);
|
||||
|
||||
assert!(!masked.contains("ab'cd"));
|
||||
assert!(!masked.contains("ab''cd"));
|
||||
|
||||
@@ -41,10 +41,10 @@ fn format_root_path(root: &str) -> String {
|
||||
|
||||
/// Helper function to mask multiple secrets in a string.
|
||||
fn mask_secrets(mut sql: String, secrets: &[&str]) -> String {
|
||||
let mut secrets: Vec<_> = secrets.iter().filter(|secret| !secret.is_empty()).collect();
|
||||
secrets.sort_by_key(|secret| std::cmp::Reverse(secret.len()));
|
||||
for secret in secrets {
|
||||
if !secret.is_empty() {
|
||||
sql = sql.replace(secret, "[REDACTED]");
|
||||
}
|
||||
sql = sql.replace(*secret, "[REDACTED]");
|
||||
}
|
||||
sql
|
||||
}
|
||||
@@ -293,7 +293,7 @@ impl StorageExport for AzblobBackend {
|
||||
];
|
||||
|
||||
if let Some(sas_token) = &self.config.azblob_sas_token {
|
||||
connection_options.push(format!("SAS_TOKEN='{}'", sas_token));
|
||||
connection_options.push(format!("SAS_TOKEN='{}'", sas_token.expose_secret()));
|
||||
}
|
||||
|
||||
let connection_str = format!(" CONNECTION ({})", connection_options.join(", "));
|
||||
@@ -313,6 +313,7 @@ impl StorageExport for AzblobBackend {
|
||||
mask_secrets(
|
||||
sql.to_string(),
|
||||
&[
|
||||
expose_optional_secret(&self.config.azblob_sas_token),
|
||||
expose_optional_secret(&self.config.azblob_account_name),
|
||||
expose_optional_secret(&self.config.azblob_account_key),
|
||||
],
|
||||
@@ -367,3 +368,27 @@ impl StorageType {
|
||||
!matches!(self, StorageType::Fs(_))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_azblob_export_masks_sas_token() {
|
||||
let backend = AzblobBackend {
|
||||
config: PrefixedAzblobConnection {
|
||||
azblob_account_name: Some("sig".to_string().into()),
|
||||
azblob_account_key: Some("prefix_sig_CANARY_KEY".to_string().into()),
|
||||
azblob_sas_token: Some("sig=secret-token".to_string().into()),
|
||||
..Default::default()
|
||||
},
|
||||
};
|
||||
let (_, connection) = backend.get_storage_path("greptime", "public");
|
||||
assert!(connection.contains("SAS_TOKEN='sig=secret-token'"));
|
||||
let masked = backend.mask_sensitive_info(&connection);
|
||||
assert!(masked.contains("SAS_TOKEN='[REDACTED]'"));
|
||||
assert!(masked.contains("ACCOUNT_KEY='[REDACTED]'"));
|
||||
assert!(!masked.contains("CANARY_KEY"));
|
||||
assert!(!masked.contains("sig=secret-token"));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -42,7 +42,7 @@ pub enum Error {
|
||||
location: Location,
|
||||
},
|
||||
|
||||
#[snafu(display("Failed to do Flight get, code: {}", tonic_code))]
|
||||
#[snafu(display("Failed to do Flight get, addr: {}, code: {}", addr, tonic_code))]
|
||||
FlightGet {
|
||||
addr: String,
|
||||
tonic_code: Code,
|
||||
|
||||
@@ -626,6 +626,44 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_cancel_compaction_through_handle() {
|
||||
let server = RegionTestServer::start().await;
|
||||
let requester = server.create_requester(ChannelConfig::default(), false, false);
|
||||
let request = RegionRequest {
|
||||
header: Some(RegionRequestHeader::default()),
|
||||
body: Some(region_request::Body::CancelCompaction(
|
||||
api::v1::region::CancelCompactionRequest {
|
||||
region_id: 42,
|
||||
task_id: "cycle-id".into(),
|
||||
},
|
||||
)),
|
||||
};
|
||||
for affected_rows in [0, 1] {
|
||||
let mut response = build_response(StatusCode::Success);
|
||||
response.affected_rows = affected_rows;
|
||||
server
|
||||
.service
|
||||
.responses
|
||||
.lock()
|
||||
.unwrap()
|
||||
.push_back(Ok(response));
|
||||
assert_eq!(
|
||||
requester
|
||||
.handle(request.clone())
|
||||
.await
|
||||
.unwrap()
|
||||
.affected_rows,
|
||||
affected_rows as usize
|
||||
);
|
||||
}
|
||||
let requests = server.service.requests.lock().unwrap();
|
||||
assert_eq!(requests.len(), 2);
|
||||
for (actual, _, _) in requests.iter() {
|
||||
assert_eq!(actual.body, request.body);
|
||||
}
|
||||
}
|
||||
|
||||
fn build_insert_request() -> RegionRequest {
|
||||
RegionRequest {
|
||||
header: Some(RegionRequestHeader {
|
||||
|
||||
@@ -34,7 +34,7 @@ use mito2::config::IndexConfig;
|
||||
use mito2::manifest::action::{RegionCheckpoint, RegionManifest, RemovedFilesRecord};
|
||||
use mito2::memtable::sort_primary_key_record_batch;
|
||||
use mito2::read::FlatSource;
|
||||
use mito2::sst::file::{FileMeta, RegionFileId};
|
||||
use mito2::sst::file::{FileMeta, FileMetaRef, RegionFileId};
|
||||
use mito2::sst::index::{Indexer, IndexerBuilder};
|
||||
use mito2::sst::parquet::writer::ParquetWriter;
|
||||
use mito2::sst::parquet::{SstInfo, WriteOptions};
|
||||
@@ -490,7 +490,7 @@ pub(super) async fn run_direct_sst(args: DirectArgs) {
|
||||
remap_sst_file(&obj_store_dir, &table_dir, region_id, info.file_id, file_id);
|
||||
files.insert(
|
||||
file_id,
|
||||
file_meta_from_sst_info(&info, region_id, file_id, sequence),
|
||||
FileMetaRef::from(file_meta_from_sst_info(&info, region_id, file_id, sequence)),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -512,6 +512,8 @@ pub(super) async fn run_direct_sst(args: DirectArgs) {
|
||||
compaction_time_window: None,
|
||||
sst_format: format,
|
||||
append_mode: table.append_mode,
|
||||
pending_tails: Default::default(),
|
||||
handoff_floors: Default::default(),
|
||||
};
|
||||
let checkpoint = RegionCheckpoint {
|
||||
last_version: args.checkpoint_version,
|
||||
|
||||
@@ -203,6 +203,7 @@ impl ObjbenchCommand {
|
||||
max_sequence: None,
|
||||
sst_write_format: FormatType::PrimaryKey,
|
||||
index_options: Default::default(),
|
||||
index_build_inputs: None,
|
||||
index_config: mito_engine_config.index.clone(),
|
||||
inverted_index_config: MitoConfig::default().inverted_index,
|
||||
fulltext_index_config,
|
||||
|
||||
@@ -713,7 +713,6 @@ async fn run_direct_iteration(
|
||||
file_path.clone(),
|
||||
object_store.clone(),
|
||||
CacheStrategy::Disabled,
|
||||
row_group_idx,
|
||||
None,
|
||||
);
|
||||
let mut stream = build_sst_parquet_record_batch_stream(
|
||||
|
||||
@@ -20,6 +20,7 @@ use mito2::manifest::action::{RegionEdit, RegionMetaAction, RegionMetaActionList
|
||||
use mito2::manifest::manager::{RegionManifestManager, RegionManifestOptions};
|
||||
use mito2::region::ManifestStats;
|
||||
use mito2::sst::file::RegionFileId;
|
||||
use mito2::sst::file_metadata::FileMetadataInterner;
|
||||
use mito2::sst::location::{region_dir_from_table_dir, sst_file_path};
|
||||
use object_store::ObjectStore;
|
||||
use parquet::file::FOOTER_SIZE;
|
||||
@@ -94,11 +95,16 @@ impl SstReplaceCommand {
|
||||
.unwrap_or_else(|| vec![PathType::Bare, PathType::Data, PathType::Metadata]);
|
||||
let mut found = None;
|
||||
let mut existing_manifests = Vec::new();
|
||||
let file_metadata_interner = FileMetadataInterner::new();
|
||||
for candidate in candidates {
|
||||
let stats = ManifestStats::default();
|
||||
let region_dir = region_dir_from_table_dir(&self.table_dir, region_id, candidate);
|
||||
let manifest_opts =
|
||||
RegionManifestOptions::new(&mito_config, ®ion_dir, &object_store);
|
||||
let manifest_opts = RegionManifestOptions::new(
|
||||
&mito_config,
|
||||
®ion_dir,
|
||||
&object_store,
|
||||
file_metadata_interner.clone(),
|
||||
);
|
||||
let Some(manifest_manager) = RegionManifestManager::open(manifest_opts, &stats)
|
||||
.await
|
||||
.map_err(|e| {
|
||||
@@ -161,7 +167,7 @@ impl SstReplaceCommand {
|
||||
let new_num_row_groups = parquet_meta.num_row_groups() as u64;
|
||||
validate_replacement(&old_file, new_num_rows, new_num_row_groups)?;
|
||||
|
||||
let mut new_file = old_file.clone();
|
||||
let mut new_file = old_file.as_ref().clone();
|
||||
new_file.file_size = new_file_size;
|
||||
new_file.num_rows = new_num_rows;
|
||||
new_file.num_row_groups = new_num_row_groups;
|
||||
@@ -208,6 +214,7 @@ impl SstReplaceCommand {
|
||||
flushed_entry_id: None,
|
||||
flushed_sequence: None,
|
||||
committed_sequence: None,
|
||||
wal_recovery: Default::default(),
|
||||
};
|
||||
let version = manifest_manager
|
||||
.update(
|
||||
|
||||
@@ -85,6 +85,13 @@ pub enum Error {
|
||||
source: datanode::error::Error,
|
||||
},
|
||||
|
||||
#[snafu(display("Failed to close the metadata kv backend"))]
|
||||
CloseMetadataKvBackend {
|
||||
#[snafu(implicit)]
|
||||
location: Location,
|
||||
source: common_meta::error::Error,
|
||||
},
|
||||
|
||||
#[snafu(display("Failed to start flownode"))]
|
||||
StartFlownode {
|
||||
#[snafu(implicit)]
|
||||
@@ -333,6 +340,7 @@ impl ErrorExt for Error {
|
||||
Error::StartDatanode { source, .. } => source.status_code(),
|
||||
Error::StartFrontend { source, .. } => source.status_code(),
|
||||
Error::ShutdownDatanode { source, .. } => source.status_code(),
|
||||
Error::CloseMetadataKvBackend { source, .. } => source.status_code(),
|
||||
Error::ShutdownFrontend { source, .. } => source.status_code(),
|
||||
Error::StartMetaServer { source, .. } => source.status_code(),
|
||||
Error::ShutdownMetaServer { source, .. } => source.status_code(),
|
||||
|
||||
+18
-19
@@ -27,10 +27,10 @@ use catalog::kvbackend::{
|
||||
CachedKvBackendBuilder, CatalogManagerConfiguratorRef, KvBackendCatalogManagerBuilder,
|
||||
new_read_only_meta_kv_backend,
|
||||
};
|
||||
use catalog::process_manager::ProcessManager;
|
||||
use clap::Parser;
|
||||
use client::client_manager::NodeClients;
|
||||
use common_base::Plugins;
|
||||
use common_base::secrets::SecretString;
|
||||
use common_config::{Configurable, DEFAULT_DATA_HOME};
|
||||
use common_error::ext::BoxedError;
|
||||
use common_meta::cache::{CacheRegistryBuilder, LayeredCacheRegistryBuilder};
|
||||
@@ -52,7 +52,6 @@ use plugins::frontend::context::{
|
||||
CatalogManagerConfigureContext, DistributedCatalogManagerConfigureContext,
|
||||
};
|
||||
use plugins::options::PluginOptionsDeserializerImpl;
|
||||
use servers::addrs;
|
||||
use servers::grpc::GrpcOptions;
|
||||
use servers::tls::{TlsMode, TlsOption, merge_tls_option};
|
||||
use snafu::{OptionExt, ResultExt};
|
||||
@@ -237,7 +236,7 @@ pub struct StartCommand {
|
||||
#[clap(long)]
|
||||
tls_watch: bool,
|
||||
#[clap(long)]
|
||||
user_provider: Option<String>,
|
||||
user_provider: Option<SecretString>,
|
||||
#[clap(long)]
|
||||
disable_dashboard: Option<bool>,
|
||||
#[clap(long, default_value = "GREPTIMEDB_FRONTEND")]
|
||||
@@ -488,10 +487,7 @@ impl StartCommand {
|
||||
));
|
||||
plugins.insert::<InformationExtensionRef>(information_extension.clone());
|
||||
|
||||
let process_manager = Arc::new(ProcessManager::new(
|
||||
addrs::resolve_addr(&opts.grpc.bind_addr, Some(&opts.grpc.server_addr)),
|
||||
Some(meta_client.clone()),
|
||||
));
|
||||
let process_manager = opts.create_process_manager(Some(meta_client.clone()));
|
||||
|
||||
let builder = KvBackendCatalogManagerBuilder::new(
|
||||
information_extension,
|
||||
@@ -652,7 +648,6 @@ mod tests {
|
||||
use common_config::ENV_VAR_SEP;
|
||||
use common_test_util::temp_dir::create_named_temp_file;
|
||||
use servers::grpc::GrpcOptions;
|
||||
use servers::http::HttpOptions;
|
||||
|
||||
use super::*;
|
||||
use crate::options::GlobalOptions;
|
||||
@@ -839,16 +834,20 @@ mod tests {
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_try_from_start_command_to_anymap() {
|
||||
let fe_opts = frontend::frontend::FrontendOptions {
|
||||
http: HttpOptions {
|
||||
disable_dashboard: false,
|
||||
..Default::default()
|
||||
},
|
||||
meta_client: Some(MetaClientOptions::default()),
|
||||
user_provider: Some("static_user_provider:cmd:test=test".to_string()),
|
||||
..Default::default()
|
||||
};
|
||||
async fn test_user_provider_cli_redacts_passwords() {
|
||||
let command = StartCommand::try_parse_from([
|
||||
"frontend",
|
||||
"--user-provider",
|
||||
"static_user_provider:cmd:test=cli-secret",
|
||||
])
|
||||
.unwrap();
|
||||
let debug = format!("{command:#?}");
|
||||
assert!(!debug.contains("cli-secret"));
|
||||
assert!(debug.contains("[REDACTED]"));
|
||||
|
||||
let mut fe_opts = command.load_options(&Default::default()).unwrap().component;
|
||||
// Downstream frontend plugins require a meta client outside standalone mode.
|
||||
fe_opts.meta_client = Some(MetaClientOptions::default());
|
||||
|
||||
let mut plugins = Plugins::new();
|
||||
plugins::setup_frontend_plugins_pre_build(&mut plugins, &[], &fe_opts, None)
|
||||
@@ -859,7 +858,7 @@ mod tests {
|
||||
let result = provider
|
||||
.authenticate(
|
||||
Identity::UserId("test", None),
|
||||
Password::PlainText("test".to_string().into()),
|
||||
Password::PlainText("cli-secret".to_string().into()),
|
||||
)
|
||||
.await;
|
||||
let _ = result.unwrap();
|
||||
|
||||
+59
-20
@@ -26,6 +26,7 @@ use catalog::kvbackend::{CatalogManagerConfiguratorRef, KvBackendCatalogManagerB
|
||||
use catalog::process_manager::ProcessManager;
|
||||
use clap::Parser;
|
||||
use common_base::Plugins;
|
||||
use common_base::secrets::SecretString;
|
||||
use common_catalog::consts::{MIN_USER_FLOW_ID, MIN_USER_TABLE_ID};
|
||||
use common_config::{Configurable, metadata_store_dir};
|
||||
use common_datasource::object_store::{LocalFileAccess, configured_local_path};
|
||||
@@ -38,7 +39,7 @@ use common_meta::ddl::{DdlContext, NoopRegionFailureDetectorControl};
|
||||
use common_meta::ddl_manager::{DdlManager, DdlManagerConfiguratorRef, DdlManagerRef};
|
||||
use common_meta::key::flow::FlowMetadataManager;
|
||||
use common_meta::key::{TableMetadataManager, TableMetadataManagerRef};
|
||||
use common_meta::kv_backend::KvBackendRef;
|
||||
use common_meta::kv_backend::{ClosableKvBackendRef, KvBackendRef};
|
||||
use common_meta::node_manager::{FlownodeRef, NodeManagerRef};
|
||||
use common_meta::procedure_executor::{LocalProcedureExecutor, ProcedureExecutorRef};
|
||||
use common_meta::region_keeper::MemoryRegionKeeper;
|
||||
@@ -224,6 +225,8 @@ pub struct Instance {
|
||||
procedure_manager: ProcedureManagerRef,
|
||||
leader_services_controller: Box<dyn StandaloneLeaderServicesController>,
|
||||
leader_services_context: LeaderServicesContext,
|
||||
/// Closed last on shutdown, see [ClosableKvBackend](common_meta::kv_backend::ClosableKvBackend).
|
||||
metadata_kv_backend: ClosableKvBackendRef,
|
||||
// Keep the logging guard to prevent the worker from being dropped.
|
||||
_guard: Vec<WorkerGuard>,
|
||||
}
|
||||
@@ -278,7 +281,7 @@ impl App for Instance {
|
||||
/// ones; the first error is returned and the rest are logged.
|
||||
async fn stop(&mut self) -> Result<()> {
|
||||
let mut first_error = None;
|
||||
let mut record = |result: Result<()>| {
|
||||
let mut record_shutdown_error = |result: Result<()>| {
|
||||
if let Err(err) = result {
|
||||
if first_error.is_none() {
|
||||
first_error = Some(err);
|
||||
@@ -288,14 +291,14 @@ impl App for Instance {
|
||||
}
|
||||
};
|
||||
|
||||
record(
|
||||
record_shutdown_error(
|
||||
self.frontend
|
||||
.shutdown()
|
||||
.await
|
||||
.context(error::ShutdownFrontendSnafu),
|
||||
);
|
||||
|
||||
record(
|
||||
record_shutdown_error(
|
||||
self.leader_services_controller
|
||||
.stop(
|
||||
self.procedure_manager.clone(),
|
||||
@@ -304,20 +307,28 @@ impl App for Instance {
|
||||
.await,
|
||||
);
|
||||
|
||||
record(
|
||||
record_shutdown_error(
|
||||
self.datanode
|
||||
.shutdown()
|
||||
.await
|
||||
.context(error::ShutdownDatanodeSnafu),
|
||||
);
|
||||
|
||||
record(
|
||||
record_shutdown_error(
|
||||
self.flownode
|
||||
.shutdown()
|
||||
.await
|
||||
.context(error::ShutdownFlownodeSnafu),
|
||||
);
|
||||
|
||||
// Close the metadata after attempting to stop all components.
|
||||
record_shutdown_error(
|
||||
self.metadata_kv_backend
|
||||
.close()
|
||||
.await
|
||||
.context(error::CloseMetadataKvBackendSnafu),
|
||||
);
|
||||
|
||||
info!("Datanode instance stopped.");
|
||||
|
||||
first_error.map_or(Ok(()), Err)
|
||||
@@ -351,7 +362,7 @@ pub struct StartCommand {
|
||||
#[clap(long)]
|
||||
tls_watch: bool,
|
||||
#[clap(long)]
|
||||
user_provider: Option<String>,
|
||||
user_provider: Option<SecretString>,
|
||||
#[clap(long, default_value = "GREPTIMEDB_STANDALONE")]
|
||||
pub env_prefix: String,
|
||||
/// The working home directory of this standalone instance.
|
||||
@@ -542,10 +553,11 @@ impl StartCommand {
|
||||
.context(OtherSnafu)?;
|
||||
|
||||
let metadata_dir = metadata_store_dir(data_home);
|
||||
let kv_backend = creator
|
||||
let metadata_kv_backend = creator
|
||||
.metadata_kv_backend_creator
|
||||
.create(metadata_dir, &opts)
|
||||
.await?;
|
||||
let kv_backend: KvBackendRef = metadata_kv_backend.clone();
|
||||
let (procedure_manager, event_recorder_handle) =
|
||||
standalone::build_procedure_manager(kv_backend.clone(), opts.procedure);
|
||||
|
||||
@@ -789,6 +801,7 @@ impl StartCommand {
|
||||
procedure_manager,
|
||||
leader_services_controller: creator.leader_services_controller,
|
||||
leader_services_context,
|
||||
metadata_kv_backend,
|
||||
_guard: vec![],
|
||||
};
|
||||
let result = InstanceCreatorResult {
|
||||
@@ -847,15 +860,25 @@ impl NodeManagerCreator for DefaultNodeManagerCreator {
|
||||
/// configuration types.
|
||||
#[async_trait]
|
||||
pub trait MetadataKvBackendCreator: Send + Sync {
|
||||
async fn create(&self, metadata_dir: String, opts: &StandaloneOptions) -> Result<KvBackendRef>;
|
||||
/// Standalone closes the backend on shutdown, so wrappers must forward
|
||||
/// [close](common_meta::kv_backend::ClosableKvBackend::close) to the backend they wrap.
|
||||
async fn create(
|
||||
&self,
|
||||
metadata_dir: String,
|
||||
opts: &StandaloneOptions,
|
||||
) -> Result<ClosableKvBackendRef>;
|
||||
}
|
||||
|
||||
pub struct DefaultMetadataKvBackendCreator;
|
||||
|
||||
#[async_trait]
|
||||
impl MetadataKvBackendCreator for DefaultMetadataKvBackendCreator {
|
||||
async fn create(&self, metadata_dir: String, opts: &StandaloneOptions) -> Result<KvBackendRef> {
|
||||
standalone::build_metadata_kvbackend(metadata_dir, opts.metadata_store)
|
||||
async fn create(
|
||||
&self,
|
||||
metadata_dir: String,
|
||||
opts: &StandaloneOptions,
|
||||
) -> Result<ClosableKvBackendRef> {
|
||||
standalone::open_metadata_kvbackend(metadata_dir, opts.metadata_store)
|
||||
.context(error::BuildMetadataKvbackendSnafu)
|
||||
}
|
||||
}
|
||||
@@ -1097,7 +1120,6 @@ mod tests {
|
||||
use common_test_util::temp_dir::{create_named_temp_file, create_temp_dir};
|
||||
use common_wal::config::object_store::ObjectStoreWalConfig;
|
||||
use common_wal::options::{ObjectStoreWalOptions, WalOptions};
|
||||
use frontend::frontend::FrontendOptions;
|
||||
use object_store::config::{FileConfig, GcsConfig};
|
||||
use servers::grpc::GrpcOptions;
|
||||
use servers::server::ServerHandlers;
|
||||
@@ -1161,6 +1183,7 @@ mod tests {
|
||||
opts.storage.data_home = data_home.path().to_str().unwrap().to_string();
|
||||
let creator = InstanceCreator::default()
|
||||
.with_leader_services_controller(Box::new(FailingLeaderServices));
|
||||
let metadata_dir = metadata_store_dir(&opts.storage.data_home);
|
||||
let (mut instance, _) = StartCommand::build_with(opts, vec![], creator)
|
||||
.await
|
||||
.unwrap();
|
||||
@@ -1181,6 +1204,11 @@ mod tests {
|
||||
log_store.append_batch(vec![]).await,
|
||||
Err(log_store::error::Error::ObjectStoreWalStopped { .. })
|
||||
));
|
||||
// The metadata backend was closed although earlier steps failed: raft-engine locks its
|
||||
// directory while open, so reopening it only succeeds once it was released.
|
||||
let metadata =
|
||||
standalone::open_metadata_kvbackend(metadata_dir, Default::default()).unwrap();
|
||||
metadata.close().await.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
@@ -1289,11 +1317,22 @@ mod tests {
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_try_from_start_command_to_anymap() {
|
||||
let fe_opts = FrontendOptions {
|
||||
user_provider: Some("static_user_provider:cmd:test=test".to_string()),
|
||||
..Default::default()
|
||||
};
|
||||
async fn test_user_provider_cli_redacts_passwords() {
|
||||
let command = StartCommand::try_parse_from([
|
||||
"standalone",
|
||||
"--user-provider",
|
||||
"static_user_provider:cmd:test=cli-secret",
|
||||
])
|
||||
.unwrap();
|
||||
let debug = format!("{command:#?}");
|
||||
assert!(!debug.contains("cli-secret"));
|
||||
assert!(debug.contains("[REDACTED]"));
|
||||
|
||||
let fe_opts = command
|
||||
.load_options(&Default::default())
|
||||
.unwrap()
|
||||
.component
|
||||
.frontend_options();
|
||||
|
||||
let mut plugins = Plugins::new();
|
||||
plugins.insert(StandaloneFlag);
|
||||
@@ -1305,7 +1344,7 @@ mod tests {
|
||||
let result = provider
|
||||
.authenticate(
|
||||
Identity::UserId("test", None),
|
||||
Password::PlainText("test".to_string().into()),
|
||||
Password::PlainText("cli-secret".to_string().into()),
|
||||
)
|
||||
.await;
|
||||
let _ = result.unwrap();
|
||||
@@ -1374,7 +1413,7 @@ mod tests {
|
||||
write!(file, "{}", toml_str).unwrap();
|
||||
let cmd = StartCommand {
|
||||
config_file: Some(file.path().to_str().unwrap().to_string()),
|
||||
user_provider: Some("static_user_provider:cmd:test=test".to_string()),
|
||||
user_provider: Some("static_user_provider:cmd:test=test".to_string().into()),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
@@ -1437,7 +1476,7 @@ mod tests {
|
||||
#[test]
|
||||
fn test_load_log_options_from_cli() {
|
||||
let cmd = StartCommand {
|
||||
user_provider: Some("static_user_provider:cmd:test=test".to_string()),
|
||||
user_provider: Some("static_user_provider:cmd:test=test".to_string().into()),
|
||||
mysql_addr: Some("127.0.0.1:4002".to_string()),
|
||||
postgres_addr: Some("127.0.0.1:4003".to_string()),
|
||||
..Default::default()
|
||||
|
||||
@@ -19,6 +19,7 @@ use std::time::Duration;
|
||||
use cmd::options::GreptimeOptions;
|
||||
use common_base::memory_limit::MemoryLimit;
|
||||
use common_base::readable_size::ReadableSize;
|
||||
use common_base::secrets::ExposeSecret;
|
||||
use common_config::{Configurable, DEFAULT_DATA_HOME, ENV_VAR_SEP};
|
||||
use common_options::datanode::{ClientOptions, DatanodeClientOptions};
|
||||
use common_runtime::global::RuntimeOptions;
|
||||
@@ -621,6 +622,7 @@ where
|
||||
"storage.access_key_secret",
|
||||
"storage.account_name",
|
||||
"storage.account_key",
|
||||
"storage.sas_token",
|
||||
"storage.credential_path",
|
||||
"storage.credential",
|
||||
"region_engine.mito.inverted_index.intermediate_path",
|
||||
@@ -802,17 +804,54 @@ fn test_load_standalone_user_provider_from_config() {
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(
|
||||
options.component.user_provider.as_deref(),
|
||||
options
|
||||
.component
|
||||
.user_provider
|
||||
.as_ref()
|
||||
.map(|value| value.expose_secret().as_str()),
|
||||
Some(user_provider)
|
||||
);
|
||||
|
||||
let frontend_options = options.component.frontend_options();
|
||||
assert_eq!(
|
||||
frontend_options.user_provider.as_deref(),
|
||||
frontend_options
|
||||
.user_provider
|
||||
.as_ref()
|
||||
.map(|value| value.expose_secret().as_str()),
|
||||
Some(user_provider)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_load_standalone_user_provider_cmd_from_config_is_redacted_in_config_dump() {
|
||||
let config = tempfile::NamedTempFile::new().unwrap();
|
||||
let user_provider = "static_user_provider:cmd:alice=secret";
|
||||
std::fs::write(
|
||||
config.path(),
|
||||
format!("user_provider = \"{user_provider}\"\n"),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let options =
|
||||
GreptimeOptions::<StandaloneOptions>::load_layered_options(config.path().to_str(), "")
|
||||
.unwrap();
|
||||
|
||||
// Loading keeps the original value for authentication...
|
||||
assert_eq!(
|
||||
options
|
||||
.component
|
||||
.user_provider
|
||||
.as_ref()
|
||||
.map(|value| value.expose_secret().as_str()),
|
||||
Some(user_provider)
|
||||
);
|
||||
|
||||
// ...while a config dump (e.g. `/config`) only exposes the redacted form.
|
||||
let serialized = options.to_toml().unwrap();
|
||||
assert!(serialized.contains("user_provider = \"[REDACTED]\""));
|
||||
assert!(!serialized.contains("secret"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_load_heartbeat_env_vars_from_env() {
|
||||
let env_prefix = "HEARTBEAT_ENV_VARS_UT";
|
||||
|
||||
Vendored
+1
-1
@@ -11,7 +11,7 @@ workspace = true
|
||||
bytes.workspace = true
|
||||
common-base.workspace = true
|
||||
futures.workspace = true
|
||||
moka = { workspace = true, features = ["future"] }
|
||||
moka = { workspace = true, features = ["future", "sync"] }
|
||||
prometheus.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
|
||||
Vendored
+26
-7
@@ -15,6 +15,7 @@
|
||||
use std::borrow::Borrow;
|
||||
use std::hash::Hash;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use crate::metrics::{CacheMetrics, CacheSizeMetric, CacheSizeRegistration};
|
||||
|
||||
@@ -76,14 +77,32 @@ where
|
||||
W: Fn(&K, &V) -> u32 + Send + Sync + 'static,
|
||||
L: Fn(Arc<K>, V, RemovalCause) + Send + Sync + 'static,
|
||||
{
|
||||
Self::new_with_ttl(name, capacity, weigher, listener, None)
|
||||
}
|
||||
|
||||
/// Creates a cache with an optional write-based expiration time.
|
||||
pub fn new_with_ttl<W, L>(
|
||||
name: &str,
|
||||
capacity: u64,
|
||||
weigher: W,
|
||||
listener: L,
|
||||
ttl: Option<Duration>,
|
||||
) -> Self
|
||||
where
|
||||
W: Fn(&K, &V) -> u32 + Send + Sync + 'static,
|
||||
L: Fn(Arc<K>, V, RemovalCause) + Send + Sync + 'static,
|
||||
{
|
||||
let mut builder = 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()));
|
||||
if let Some(ttl) = ttl {
|
||||
builder = builder.time_to_live(ttl);
|
||||
}
|
||||
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(),
|
||||
inner: builder.build(),
|
||||
capacity,
|
||||
size_registration: None,
|
||||
metrics: None,
|
||||
|
||||
Vendored
+3
-1
@@ -12,12 +12,14 @@
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
//! Shared memory cache primitives with native asynchronous load deduplication.
|
||||
//! Shared memory caches.
|
||||
|
||||
mod cache;
|
||||
mod sync_cache;
|
||||
|
||||
pub mod metrics;
|
||||
pub mod page;
|
||||
pub mod paged;
|
||||
|
||||
pub use cache::{Cache, RemovalCause};
|
||||
pub use sync_cache::SyncCache;
|
||||
|
||||
Vendored
+15
-1
@@ -25,6 +25,7 @@ use std::num::NonZeroU64;
|
||||
use std::ops::Range;
|
||||
use std::sync::Arc;
|
||||
use std::task::Poll;
|
||||
use std::time::Duration;
|
||||
|
||||
use bytes::{Bytes, BytesMut};
|
||||
use common_base::range_read::RangeReader;
|
||||
@@ -88,15 +89,28 @@ impl<K: Hash + Eq + Clone + Send + Sync + 'static> PagedCache<K> {
|
||||
page_size: u64,
|
||||
weigher: impl Fn(&(K, u64), &Bytes) -> u32 + Send + Sync + 'static,
|
||||
observer: PageCacheObserver,
|
||||
) -> Self {
|
||||
Self::new_with_ttl(name, capacity, page_size, weigher, observer, None)
|
||||
}
|
||||
|
||||
/// Creates a page cache with optional expiration measured from insertion.
|
||||
pub fn new_with_ttl(
|
||||
name: &str,
|
||||
capacity: u64,
|
||||
page_size: u64,
|
||||
weigher: impl Fn(&(K, u64), &Bytes) -> u32 + Send + Sync + 'static,
|
||||
observer: PageCacheObserver,
|
||||
ttl: Option<Duration>,
|
||||
) -> Self {
|
||||
let events = observer.events.clone();
|
||||
let mut cache = Cache::new(
|
||||
let mut cache = Cache::new_with_ttl(
|
||||
name,
|
||||
capacity,
|
||||
move |key, value: &Arc<CachedPage>| weigher(key, &value.bytes),
|
||||
move |_, _, cause| {
|
||||
events(PageEvent::Evicted { cause });
|
||||
},
|
||||
ttl,
|
||||
)
|
||||
.with_size_metric(observer.bytes.clone());
|
||||
if let Some(metrics) = &observer.loads {
|
||||
|
||||
Vendored
+111
@@ -0,0 +1,111 @@
|
||||
// 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::RemovalCause;
|
||||
|
||||
/// A weighted completed-value cache for synchronous callers.
|
||||
///
|
||||
/// Uses the same backend and removal causes as [`crate::Cache`]. Callers can
|
||||
/// serialize publication and invalidation with their own lock without awaiting
|
||||
/// under that lock. Values should be inexpensive to clone, such as `Arc<T>`.
|
||||
#[derive(Clone)]
|
||||
pub struct SyncCache<K, V> {
|
||||
inner: moka::sync::Cache<K, V>,
|
||||
}
|
||||
|
||||
impl<K, V> SyncCache<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::sync::Cache::builder()
|
||||
.name(name)
|
||||
.max_capacity(capacity)
|
||||
.weigher(weigher)
|
||||
.eviction_listener(move |key, value, cause| listener(key, value, cause.into()))
|
||||
.build(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Gets a completed value without starting a load.
|
||||
pub fn get<Q>(&self, key: &Q) -> Option<V>
|
||||
where
|
||||
K: Borrow<Q>,
|
||||
Q: Hash + Eq + ?Sized,
|
||||
{
|
||||
self.inner.get(key)
|
||||
}
|
||||
|
||||
/// Submits a completed value to the cache's admission and eviction policy.
|
||||
/// Insertion does not guarantee retention.
|
||||
pub fn insert(&self, key: K, value: V) {
|
||||
self.inner.insert(key, value);
|
||||
}
|
||||
|
||||
/// Applies pending admission, eviction, and accounting work.
|
||||
pub fn run_pending_tasks(&self) {
|
||||
self.inner.run_pending_tasks();
|
||||
}
|
||||
|
||||
/// Invalidates a completed entry. Concurrent producers are fenced by the caller.
|
||||
pub fn invalidate<Q>(&self, key: &Q)
|
||||
where
|
||||
K: Borrow<Q>,
|
||||
Q: Hash + Eq + ?Sized,
|
||||
{
|
||||
self.inner.invalidate(key);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::sync::Mutex;
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_borrowed_lookup_and_invalidation() {
|
||||
let removed = Arc::new(Mutex::new(Vec::new()));
|
||||
let events = removed.clone();
|
||||
let cache = SyncCache::new(
|
||||
"test",
|
||||
1024,
|
||||
|_: &String, _: &Arc<usize>| 1,
|
||||
move |key, value, cause| events.lock().unwrap().push((key, value, cause)),
|
||||
);
|
||||
let value = Arc::new(7);
|
||||
cache.insert("a".to_string(), value.clone());
|
||||
cache.insert("b".to_string(), Arc::new(9));
|
||||
assert!(Arc::ptr_eq(&cache.get("a").unwrap(), &value));
|
||||
cache.invalidate("a");
|
||||
assert!(cache.get("a").is_none());
|
||||
assert_eq!(*cache.get("b").unwrap(), 9);
|
||||
cache.run_pending_tasks();
|
||||
assert_eq!(
|
||||
*removed.lock().unwrap(),
|
||||
vec![(Arc::new("a".to_string()), value, RemovalCause::Explicit)]
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -128,6 +128,8 @@ pub const INFORMATION_SCHEMA_PLUGINS_TABLE_ID: u32 = 47;
|
||||
pub const INFORMATION_SCHEMA_USER_PRIVILEGES_TABLE_ID: u32 = 48;
|
||||
/// id for information_schema.PROCESSLIST (for mysql)
|
||||
pub const INFORMATION_SCHEMA_PROCESSLIST_TABLE_ID: u32 = 49;
|
||||
/// Id for information_schema.compaction_tasks.
|
||||
pub const INFORMATION_SCHEMA_COMPACTION_TASKS_TABLE_ID: u32 = 50;
|
||||
|
||||
// ----- End of information_schema tables -----
|
||||
|
||||
@@ -224,6 +226,8 @@ pub const SPAN_KIND_SERVER: &str = "SPAN_KIND_SERVER";
|
||||
pub const SPAN_STATUS_ERROR: &str = "STATUS_CODE_ERROR";
|
||||
pub const TRACE_TABLE_NAME: &str = "opentelemetry_traces";
|
||||
pub const TRACE_TABLE_NAME_SESSION_KEY: &str = "trace_table_name";
|
||||
/// Shared exemplar destination within each source metric's schema.
|
||||
pub const METRICS_EXEMPLARS_TABLE: &str = concatcp!(DEFAULT_CATALOG_NAME, "_metrics_exemplars");
|
||||
// ---- End of special table and fields ----
|
||||
|
||||
/// Generate the trace services table name from the trace table name by adding `_services` suffix.
|
||||
|
||||
@@ -16,6 +16,7 @@ use std::fmt::Display;
|
||||
use std::io;
|
||||
use std::str::FromStr;
|
||||
|
||||
use async_compression::Level;
|
||||
use async_compression::tokio::bufread::{BzDecoder, GzipDecoder, XzDecoder, ZstdDecoder};
|
||||
use async_compression::tokio::write;
|
||||
use bytes::Bytes;
|
||||
@@ -88,6 +89,15 @@ impl CompressionType {
|
||||
Self::Uncompressed => "",
|
||||
}
|
||||
}
|
||||
|
||||
/// Encodes `content` as a gzip stream at level 0, which stores it without compression.
|
||||
pub async fn encode_gzip_stored(content: &[u8]) -> io::Result<Vec<u8>> {
|
||||
let mut buffer = Vec::with_capacity(content.len());
|
||||
let mut encoder = write::GzipEncoder::with_quality(&mut buffer, Level::Precise(0));
|
||||
encoder.write_all(content).await?;
|
||||
encoder.shutdown().await?;
|
||||
Ok(buffer)
|
||||
}
|
||||
}
|
||||
|
||||
macro_rules! impl_compression_type {
|
||||
|
||||
@@ -20,6 +20,7 @@ api.workspace = true
|
||||
arrow.workspace = true
|
||||
arrow-schema.workspace = true
|
||||
async-trait.workspace = true
|
||||
auth.workspace = true
|
||||
bincode = "=1.3.3"
|
||||
catalog.workspace = true
|
||||
common-base.workspace = true
|
||||
@@ -52,6 +53,7 @@ mito-codec.workspace = true
|
||||
nalgebra.workspace = true
|
||||
num-traits = "0.2"
|
||||
paste.workspace = true
|
||||
partition.workspace = true
|
||||
regex.workspace = true
|
||||
reqwest = { workspace = true, optional = true }
|
||||
s2 = { version = "0.0.12", optional = true }
|
||||
|
||||
@@ -13,6 +13,7 @@
|
||||
// limitations under the License.
|
||||
|
||||
mod build_index_table;
|
||||
mod cancel_region_compaction;
|
||||
mod discard_unflushed_data;
|
||||
mod flush_compact_region;
|
||||
mod flush_compact_table;
|
||||
@@ -35,6 +36,7 @@ use reconcile_database::ReconcileDatabaseFunction;
|
||||
use reconcile_table::ReconcileTableFunction;
|
||||
|
||||
use crate::admin::build_index_table::{BuildIndexFunction, BuildSeriesIndexFunction};
|
||||
use crate::admin::cancel_region_compaction::CancelRegionCompactionFunction;
|
||||
use crate::admin::discard_unflushed_data::DiscardUnflushedDataFunction;
|
||||
use crate::flush_flow::FlushFlowFunction;
|
||||
use crate::function_registry::FunctionRegistry;
|
||||
@@ -48,6 +50,7 @@ impl AdminFunction {
|
||||
registry.register(MigrateRegionFunction::factory());
|
||||
registry.register(FlushRegionFunction::factory());
|
||||
registry.register(CompactRegionFunction::factory());
|
||||
registry.register(CancelRegionCompactionFunction::factory());
|
||||
registry.register(FlushTableFunction::factory());
|
||||
registry.register(CompactTableFunction::factory());
|
||||
registry.register(GcRegionsFunction::factory());
|
||||
|
||||
@@ -0,0 +1,210 @@
|
||||
// Copyright 2023 Greptime Team
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
use arrow::datatypes::DataType as ArrowDataType;
|
||||
use common_macro::admin_fn;
|
||||
use common_query::error::{
|
||||
InvalidFuncArgsSnafu, MissingTableMutationHandlerSnafu, Result, UnsupportedInputDataTypeSnafu,
|
||||
};
|
||||
use datafusion_expr::Signature;
|
||||
use datatypes::data_type::DataType;
|
||||
use datatypes::prelude::{ConcreteDataType, Value, ValueRef};
|
||||
use session::context::QueryContextRef;
|
||||
use snafu::ensure;
|
||||
use store_api::storage::RegionId;
|
||||
|
||||
use crate::handlers::TableMutationHandlerRef;
|
||||
use crate::helper;
|
||||
|
||||
/// Cancels the region compaction identified by `(region_id, task_id)`.
|
||||
/// Returns one when cancellation is issued or already pending, and zero when absent.
|
||||
#[admin_fn(
|
||||
name = CancelRegionCompactionFunction,
|
||||
display_name = cancel_region_compaction,
|
||||
sig_fn = signature,
|
||||
ret = uint64
|
||||
)]
|
||||
pub(crate) async fn cancel_region_compaction(
|
||||
table_mutation_handler: &TableMutationHandlerRef,
|
||||
query_ctx: &QueryContextRef,
|
||||
params: &[ValueRef<'_>],
|
||||
) -> Result<Value> {
|
||||
ensure!(
|
||||
params.len() == 2,
|
||||
InvalidFuncArgsSnafu {
|
||||
err_msg: format!(
|
||||
"cancel_region_compaction expects 2 arguments, received {}",
|
||||
params.len()
|
||||
),
|
||||
}
|
||||
);
|
||||
let Some(region_id) = helper::cast_u64(¶ms[0])? else {
|
||||
return UnsupportedInputDataTypeSnafu {
|
||||
function: "cancel_region_compaction",
|
||||
datatypes: params
|
||||
.iter()
|
||||
.map(|value| value.data_type())
|
||||
.collect::<Vec<_>>(),
|
||||
}
|
||||
.fail();
|
||||
};
|
||||
let ValueRef::String(task_id) = params[1] else {
|
||||
return InvalidFuncArgsSnafu {
|
||||
err_msg: "task_id must be a non-empty string",
|
||||
}
|
||||
.fail();
|
||||
};
|
||||
ensure!(
|
||||
!task_id.trim().is_empty(),
|
||||
InvalidFuncArgsSnafu {
|
||||
err_msg: "task_id must be a non-empty string"
|
||||
}
|
||||
);
|
||||
let affected_rows = table_mutation_handler
|
||||
.cancel_region_compaction(
|
||||
RegionId::from_u64(region_id),
|
||||
task_id.to_string(),
|
||||
query_ctx.clone(),
|
||||
)
|
||||
.await?;
|
||||
Ok(Value::from(affected_rows as u64))
|
||||
}
|
||||
|
||||
fn signature() -> Signature {
|
||||
// Matches COMPACT_REGION: primitive numerics without Decimal or Float16 overloads.
|
||||
helper::one_of_sigs2(
|
||||
ConcreteDataType::numerics()
|
||||
.into_iter()
|
||||
.map(|data_type| data_type.as_arrow_type())
|
||||
.collect(),
|
||||
vec![ArrowDataType::Utf8],
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::sync::Arc;
|
||||
|
||||
use arrow::datatypes::Field;
|
||||
use datafusion_common::ScalarValue;
|
||||
use datafusion_expr::{ColumnarValue, ScalarFunctionArgs};
|
||||
|
||||
use super::*;
|
||||
use crate::function::FunctionContext;
|
||||
use crate::function_registry;
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_cancel_region_compaction_arguments() {
|
||||
let ctx = FunctionContext::mock();
|
||||
let handler = ctx.state.table_mutation_handler.as_ref().unwrap();
|
||||
for params in [
|
||||
vec![],
|
||||
vec![ValueRef::UInt64(42)],
|
||||
vec![
|
||||
ValueRef::UInt64(42),
|
||||
ValueRef::String("task"),
|
||||
ValueRef::Null,
|
||||
],
|
||||
vec![ValueRef::Null, ValueRef::String("task")],
|
||||
vec![ValueRef::UInt64(42), ValueRef::Null],
|
||||
vec![ValueRef::UInt64(42), ValueRef::UInt64(1)],
|
||||
vec![ValueRef::UInt64(42), ValueRef::String(" \t")],
|
||||
] {
|
||||
assert!(
|
||||
cancel_region_compaction(handler, &ctx.query_ctx, ¶ms)
|
||||
.await
|
||||
.is_err(),
|
||||
"{params:?}"
|
||||
);
|
||||
}
|
||||
let error = cancel_region_compaction(
|
||||
handler,
|
||||
&ctx.query_ctx,
|
||||
&[ValueRef::Null, ValueRef::String("cycle-id")],
|
||||
)
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert!(matches!(
|
||||
error,
|
||||
common_query::error::Error::UnsupportedInputDataType { .. }
|
||||
));
|
||||
assert_eq!(
|
||||
cancel_region_compaction(
|
||||
handler,
|
||||
&ctx.query_ctx,
|
||||
&[ValueRef::UInt64(u64::MAX), ValueRef::String("cycle-id")]
|
||||
)
|
||||
.await
|
||||
.unwrap(),
|
||||
Value::UInt64(42)
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_cancel_region_compaction_async_function() {
|
||||
let factory = function_registry::FUNCTION_REGISTRY
|
||||
.get_function("cancel_region_compaction")
|
||||
.unwrap();
|
||||
for (ctx, has_handler) in [
|
||||
(FunctionContext::mock(), true),
|
||||
(FunctionContext::default(), false),
|
||||
] {
|
||||
let function = factory.provide(ctx);
|
||||
let result = function
|
||||
.as_async()
|
||||
.unwrap()
|
||||
.invoke_async_with_args(ScalarFunctionArgs {
|
||||
args: vec![
|
||||
ColumnarValue::Scalar(ScalarValue::UInt64(Some(u64::MAX))),
|
||||
ColumnarValue::Scalar(ScalarValue::Utf8(Some("cycle-id".into()))),
|
||||
],
|
||||
arg_fields: vec![
|
||||
Arc::new(Field::new("region_id", ArrowDataType::UInt64, false)),
|
||||
Arc::new(Field::new("task_id", ArrowDataType::Utf8, false)),
|
||||
],
|
||||
return_field: Arc::new(Field::new("result", ArrowDataType::UInt64, false)),
|
||||
number_rows: 1,
|
||||
config_options: Default::default(),
|
||||
})
|
||||
.await;
|
||||
if has_handler {
|
||||
let ColumnarValue::Array(array) = result.unwrap() else {
|
||||
panic!("expected array output");
|
||||
};
|
||||
assert_eq!(
|
||||
ScalarValue::try_from_array(&array, 0).unwrap(),
|
||||
ScalarValue::UInt64(Some(42))
|
||||
);
|
||||
} else {
|
||||
assert!(
|
||||
result
|
||||
.unwrap_err()
|
||||
.to_string()
|
||||
.contains("Missing TableMutationHandler")
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_cancel_region_compaction_registration_and_signature() {
|
||||
let factory = function_registry::FUNCTION_REGISTRY
|
||||
.get_function("cancel_region_compaction")
|
||||
.unwrap();
|
||||
let function = factory.provide(FunctionContext::mock());
|
||||
assert_eq!(function.name(), "cancel_region_compaction");
|
||||
assert_eq!(function.return_type(&[]).unwrap(), ArrowDataType::UInt64);
|
||||
assert_eq!(function.signature(), &signature());
|
||||
}
|
||||
}
|
||||
@@ -768,4 +768,63 @@ mod tests {
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_flush_table_requires_admin_privilege() {
|
||||
use auth::{
|
||||
DefaultPermissionChecker, Identity, Password, PermissionCheckerRef, UserProvider,
|
||||
static_user_provider_from_option,
|
||||
};
|
||||
use common_base::Plugins;
|
||||
use common_error::status_code::StatusCode;
|
||||
|
||||
async fn user(username: &str, mode: &str) -> auth::UserInfoRef {
|
||||
let provider = static_user_provider_from_option(&format!(
|
||||
"static_user_provider:cmd:{username}:{mode}={username}_pwd"
|
||||
))
|
||||
.unwrap();
|
||||
provider
|
||||
.authenticate(
|
||||
Identity::UserId(username, None),
|
||||
Password::PlainText(format!("{username}_pwd").into()),
|
||||
)
|
||||
.await
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
let plugins = Plugins::new();
|
||||
plugins.insert::<PermissionCheckerRef>(DefaultPermissionChecker::arc());
|
||||
|
||||
let func_args = || datafusion::logical_expr::ScalarFunctionArgs {
|
||||
args: vec![ColumnarValue::Array(Arc::new(StringArray::from(vec![
|
||||
"test",
|
||||
])))],
|
||||
arg_fields: vec![Arc::new(Field::new("arg_0", DataType::Utf8, false))],
|
||||
return_field: Arc::new(Field::new("result", DataType::UInt64, true)),
|
||||
number_rows: 1,
|
||||
config_options: Arc::new(datafusion_common::config::ConfigOptions::default()),
|
||||
};
|
||||
|
||||
let factory: ScalarFunctionFactory = FlushTableFunction::factory().into();
|
||||
|
||||
let func_ctx =
|
||||
crate::permission::test_function_context(plugins.clone(), user("ro_user", "ro").await);
|
||||
let provider = factory.provide(func_ctx);
|
||||
let f = provider.as_async().unwrap();
|
||||
let error = f.invoke_async_with_args(func_args()).await.unwrap_err();
|
||||
assert_eq!(
|
||||
StatusCode::PermissionDenied,
|
||||
common_query::error::datafusion_status_code::<common_query::error::Error>(&error, None)
|
||||
);
|
||||
|
||||
let func_ctx =
|
||||
crate::permission::test_function_context(plugins, user("rw_user", "rw").await);
|
||||
let provider = factory.provide(func_ctx);
|
||||
let f = provider.as_async().unwrap();
|
||||
let error = f.invoke_async_with_args(func_args()).await.unwrap_err();
|
||||
assert_ne!(
|
||||
StatusCode::PermissionDenied,
|
||||
common_query::error::datafusion_status_code::<common_query::error::Error>(&error, None)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -36,6 +36,10 @@ use crate::scalars::avg_calc::AvgCalcFunction;
|
||||
use crate::scalars::date::DateFunction;
|
||||
use crate::scalars::expression::ExpressionFunction;
|
||||
use crate::scalars::hll_count::HllCalcFunction;
|
||||
use crate::scalars::iceberg_hash::{
|
||||
IcebergHashBoundsFunction, IcebergHashBreakpointsFunction, IcebergHashFunction,
|
||||
IcebergHashRangesSqlFunction,
|
||||
};
|
||||
use crate::scalars::ip::IpFunctions;
|
||||
use crate::scalars::json::JsonFunction;
|
||||
use crate::scalars::matches::MatchesFunction;
|
||||
@@ -226,6 +230,12 @@ pub static FUNCTION_REGISTRY: LazyLock<Arc<FunctionRegistry>> = LazyLock::new(||
|
||||
WelfordStddevFunction::register(&function_registry);
|
||||
DecodePrimaryKeyFunction::register(&function_registry);
|
||||
|
||||
// Hash used by `iceberg_hash` partition rules, plus its breakpoint helpers.
|
||||
IcebergHashFunction::register(&function_registry);
|
||||
IcebergHashBoundsFunction::register(&function_registry);
|
||||
IcebergHashBreakpointsFunction::register(&function_registry);
|
||||
IcebergHashRangesSqlFunction::register(&function_registry);
|
||||
|
||||
// Full text search function
|
||||
MatchesFunction::register(&function_registry);
|
||||
MatchesTermFunction::register(&function_registry);
|
||||
|
||||
@@ -70,6 +70,14 @@ pub trait TableMutationHandler: Send + Sync {
|
||||
ctx: QueryContextRef,
|
||||
) -> Result<AffectedRows>;
|
||||
|
||||
/// Cancels one identified compaction task on a table region.
|
||||
async fn cancel_region_compaction(
|
||||
&self,
|
||||
region_id: RegionId,
|
||||
task_id: String,
|
||||
ctx: QueryContextRef,
|
||||
) -> Result<AffectedRows>;
|
||||
|
||||
/// Discard all unflushed data from a table region.
|
||||
async fn discard_unflushed_data(
|
||||
&self,
|
||||
|
||||
@@ -15,6 +15,7 @@
|
||||
mod admin;
|
||||
mod flush_flow;
|
||||
mod macros;
|
||||
mod permission;
|
||||
mod system;
|
||||
mod uddsketch_compat;
|
||||
|
||||
@@ -27,3 +28,7 @@ pub mod helper;
|
||||
pub mod scalars;
|
||||
pub mod state;
|
||||
pub mod utils;
|
||||
|
||||
// Public for `admin_fn` expansions in downstream crates; the module stays private.
|
||||
#[doc(hidden)]
|
||||
pub use permission::ensure_admin_privilege;
|
||||
|
||||
@@ -0,0 +1,141 @@
|
||||
// Copyright 2023 Greptime Team
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
use auth::{PermissionChecker, PermissionCheckerRef, PermissionReq, PermissionResp};
|
||||
use common_error::ext::BoxedError;
|
||||
use common_query::error::PermissionDeniedSnafu;
|
||||
use datafusion_common::DataFusionError;
|
||||
use sql::ast::{FunctionArguments, Ident, ObjectName};
|
||||
use sql::statements::admin::Admin;
|
||||
use sql::statements::statement::Statement;
|
||||
|
||||
use crate::function::FunctionContext;
|
||||
|
||||
/// Checks ADMIN statement privileges for an `admin_fn`-generated UDF.
|
||||
pub fn ensure_admin_privilege(
|
||||
func_ctx: &FunctionContext,
|
||||
fn_name: &str,
|
||||
) -> datafusion_common::Result<()> {
|
||||
// Database-less MySQL sessions have no authorized default scope. Admin targets
|
||||
// are runtime function arguments, so frontend relation checks cannot authorize
|
||||
// them, even when qualified. Require database selection before invoking a handler.
|
||||
if func_ctx.query_ctx.channel() == session::context::Channel::Mysql
|
||||
&& func_ctx.query_ctx.current_schema().is_empty()
|
||||
{
|
||||
return Err(DataFusionError::External(Box::new(BoxedError::new(
|
||||
session::SessionError::NoDatabaseSelected {},
|
||||
))));
|
||||
}
|
||||
|
||||
let admin_stmt = Statement::Admin(Admin::Func(sql::ast::Function {
|
||||
name: ObjectName::from(vec![Ident::new(fn_name)]),
|
||||
uses_odbc_syntax: false,
|
||||
parameters: FunctionArguments::None,
|
||||
args: FunctionArguments::None,
|
||||
filter: None,
|
||||
null_treatment: None,
|
||||
over: None,
|
||||
within_group: vec![],
|
||||
}));
|
||||
|
||||
let checker = func_ctx.state.plugins.get::<PermissionCheckerRef>();
|
||||
match checker.as_ref().check_permission_with_context(
|
||||
func_ctx.query_ctx.current_user(),
|
||||
PermissionReq::SqlStatement(&admin_stmt),
|
||||
Some(&func_ctx.query_ctx.current_schema()),
|
||||
) {
|
||||
Ok(PermissionResp::Allow) => Ok(()),
|
||||
Ok(PermissionResp::Reject) | Err(_) => {
|
||||
let err = PermissionDeniedSnafu {
|
||||
err_msg: format!(
|
||||
"Executing the admin function '{fn_name}' requires the privileges of an ADMIN statement"
|
||||
),
|
||||
}
|
||||
.build();
|
||||
Err(DataFusionError::External(Box::new(BoxedError::new(err))))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) fn test_function_context(
|
||||
plugins: common_base::Plugins,
|
||||
user: auth::UserInfoRef,
|
||||
) -> FunctionContext {
|
||||
let query_ctx = session::context::QueryContext::arc();
|
||||
query_ctx.set_current_user(user);
|
||||
FunctionContext {
|
||||
query_ctx,
|
||||
state: std::sync::Arc::new(crate::state::FunctionState {
|
||||
plugins,
|
||||
..Default::default()
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use auth::{
|
||||
DefaultPermissionChecker, Identity, Password, PermissionCheckerRef, UserProvider,
|
||||
static_user_provider_from_option,
|
||||
};
|
||||
use common_base::Plugins;
|
||||
use common_error::status_code::StatusCode;
|
||||
|
||||
use super::*;
|
||||
|
||||
async fn user(username: &str, mode: &str) -> auth::UserInfoRef {
|
||||
let provider = static_user_provider_from_option(&format!(
|
||||
"static_user_provider:cmd:{username}:{mode}={username}_pwd"
|
||||
))
|
||||
.unwrap();
|
||||
provider
|
||||
.authenticate(
|
||||
Identity::UserId(username, None),
|
||||
Password::PlainText(format!("{username}_pwd").into()),
|
||||
)
|
||||
.await
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
fn denied_status(error: &DataFusionError) -> StatusCode {
|
||||
common_query::error::datafusion_status_code::<common_query::error::Error>(error, None)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_admin_privilege_without_checker_allows() {
|
||||
let func_ctx = test_function_context(Plugins::default(), user("anyone", "ro").await);
|
||||
ensure_admin_privilege(&func_ctx, "flush_table").unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_admin_privilege_readonly_user_denied() {
|
||||
let plugins = Plugins::new();
|
||||
plugins.insert::<PermissionCheckerRef>(DefaultPermissionChecker::arc());
|
||||
let func_ctx = test_function_context(plugins, user("ro_user", "ro").await);
|
||||
|
||||
let error = ensure_admin_privilege(&func_ctx, "flush_table")
|
||||
.expect_err("read-only user must be denied");
|
||||
assert_eq!(StatusCode::PermissionDenied, denied_status(&error));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_admin_privilege_readwrite_user_allowed() {
|
||||
let plugins = Plugins::new();
|
||||
plugins.insert::<PermissionCheckerRef>(DefaultPermissionChecker::arc());
|
||||
let func_ctx = test_function_context(plugins, user("rw_user", "rw").await);
|
||||
|
||||
ensure_admin_privilege(&func_ctx, "flush_table").unwrap();
|
||||
}
|
||||
}
|
||||
@@ -29,6 +29,7 @@ pub mod vector;
|
||||
|
||||
pub(crate) mod avg_calc;
|
||||
pub(crate) mod hll_count;
|
||||
pub(crate) mod iceberg_hash;
|
||||
pub mod ip;
|
||||
#[cfg(test)]
|
||||
pub(crate) mod test;
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -23,7 +23,7 @@ use datafusion::common::{DFSchema, Result as DfResult};
|
||||
use datafusion::execution::SessionStateBuilder;
|
||||
use datafusion::logical_expr::{self, ColumnarValue, Expr, Volatility};
|
||||
use datafusion::physical_planner::{DefaultPhysicalPlanner, PhysicalPlanner};
|
||||
use datafusion_common::DataFusionError;
|
||||
use datafusion_common::{DataFusionError, ScalarValue};
|
||||
use datafusion_expr::physical_planning_context::PhysicalPlanningContext;
|
||||
use datafusion_expr::{ScalarFunctionArgs, Signature};
|
||||
use datatypes::arrow::array::RecordBatch;
|
||||
@@ -101,14 +101,19 @@ impl Function for MatchesFunction {
|
||||
|
||||
impl MatchesFunction {
|
||||
fn eval(&self, data_array: ArrayRef, pattern: &str) -> DfResult<ColumnarValue> {
|
||||
let data_type = data_array.data_type();
|
||||
if !data_type.is_string() {
|
||||
return Err(DataFusionError::Execution(format!(
|
||||
"unsupported datatype {data_type}"
|
||||
)));
|
||||
}
|
||||
let col_name = "data";
|
||||
let parser_context = ParserContext::default();
|
||||
let raw_ast = parser_context.parse_pattern(pattern)?;
|
||||
let ast = raw_ast.transform_ast()?;
|
||||
|
||||
let like_expr = ast.into_like_expr(col_name);
|
||||
|
||||
let input_schema = Self::input_schema();
|
||||
let like_expr = ast.into_like_expr(col_name, data_type);
|
||||
let input_schema = Self::input_schema(data_type);
|
||||
let session_state = SessionStateBuilder::new().with_default_features().build();
|
||||
let planner = DefaultPhysicalPlanner::default();
|
||||
let physical_expr = planner.create_physical_expr(
|
||||
@@ -119,7 +124,7 @@ impl MatchesFunction {
|
||||
)?;
|
||||
|
||||
let arrow_schema = Arc::new(input_schema.as_arrow().clone());
|
||||
let input_record_batch = RecordBatch::try_new(arrow_schema, vec![data_array]).unwrap();
|
||||
let input_record_batch = RecordBatch::try_new(arrow_schema, vec![data_array])?;
|
||||
|
||||
let num_rows = input_record_batch.num_rows();
|
||||
let result = physical_expr.evaluate(&input_record_batch)?;
|
||||
@@ -128,9 +133,9 @@ impl MatchesFunction {
|
||||
Ok(ColumnarValue::Array(Arc::new(result_array)))
|
||||
}
|
||||
|
||||
fn input_schema() -> DFSchema {
|
||||
fn input_schema(data_type: &DataType) -> DFSchema {
|
||||
DFSchema::from_unqualified_fields(
|
||||
[Arc::new(Field::new("data", DataType::Utf8, true))].into(),
|
||||
[Arc::new(Field::new("data", data_type.clone(), true))].into(),
|
||||
HashMap::new(),
|
||||
)
|
||||
.unwrap()
|
||||
@@ -165,10 +170,10 @@ enum BinaryOp {
|
||||
}
|
||||
|
||||
impl PatternAst {
|
||||
fn into_like_expr(self, column: &str) -> Expr {
|
||||
fn into_like_expr(self, column: &str, data_type: &DataType) -> Expr {
|
||||
match self {
|
||||
PatternAst::Literal { op, pattern } => {
|
||||
let expr = Self::convert_literal(column, &pattern);
|
||||
let expr = Self::convert_literal(column, &pattern, data_type);
|
||||
match op {
|
||||
UnaryOp::Must => expr,
|
||||
UnaryOp::Optional => expr,
|
||||
@@ -181,7 +186,7 @@ impl PatternAst {
|
||||
}
|
||||
let exprs = children
|
||||
.into_iter()
|
||||
.map(|child| child.into_like_expr(column));
|
||||
.map(|child| child.into_like_expr(column, data_type));
|
||||
// safety: children is not empty
|
||||
match op {
|
||||
BinaryOp::And => exprs.reduce(Expr::and).unwrap(),
|
||||
@@ -189,7 +194,7 @@ impl PatternAst {
|
||||
}
|
||||
}
|
||||
PatternAst::Group { op, child } => {
|
||||
let child = child.into_like_expr(column);
|
||||
let child = child.into_like_expr(column, data_type);
|
||||
match op {
|
||||
UnaryOp::Must => child,
|
||||
UnaryOp::Optional => child,
|
||||
@@ -199,11 +204,14 @@ impl PatternAst {
|
||||
}
|
||||
}
|
||||
|
||||
fn convert_literal(column: &str, pattern: &str) -> Expr {
|
||||
logical_expr::col(column).like(logical_expr::lit(format!(
|
||||
"%{}%",
|
||||
crate::utils::escape_like_pattern(pattern)
|
||||
)))
|
||||
fn convert_literal(column: &str, pattern: &str, data_type: &DataType) -> Expr {
|
||||
let pattern = Some(format!("%{}%", crate::utils::escape_like_pattern(pattern)));
|
||||
let pattern = match data_type {
|
||||
DataType::Utf8View => ScalarValue::Utf8View(pattern),
|
||||
DataType::LargeUtf8 => ScalarValue::LargeUtf8(pattern),
|
||||
_ => ScalarValue::Utf8(pattern),
|
||||
};
|
||||
logical_expr::col(column).like(Expr::Literal(pattern, None))
|
||||
}
|
||||
|
||||
/// Transform this AST with preset rules to make it correct.
|
||||
@@ -836,7 +844,6 @@ impl Tokenizer {
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use datafusion::arrow::array::StringArray;
|
||||
use datafusion_common::ScalarValue;
|
||||
use datafusion_common::config::ConfigOptions;
|
||||
|
||||
use super::*;
|
||||
@@ -1294,6 +1301,32 @@ mod test {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn evaluate_matches_string_layouts() {
|
||||
let input: ArrayRef = Arc::new(StringArray::from(vec![
|
||||
Some("error timeout"),
|
||||
Some("healthy"),
|
||||
None,
|
||||
]));
|
||||
let function = MatchesFunction::default();
|
||||
for data_type in [DataType::Utf8, DataType::LargeUtf8, DataType::Utf8View] {
|
||||
let input = datatypes::arrow::compute::cast(&input, &data_type).unwrap();
|
||||
for (pattern, expected) in [
|
||||
("error", vec![Some(true), Some(false), None]),
|
||||
("error AND timeout", vec![Some(true), Some(false), None]),
|
||||
("error OR healthy", vec![Some(true), Some(true), None]),
|
||||
] {
|
||||
let expected: ArrayRef = Arc::new(BooleanArray::from(expected));
|
||||
let actual = function
|
||||
.eval(input.clone(), pattern)
|
||||
.unwrap()
|
||||
.to_array(3)
|
||||
.unwrap();
|
||||
assert_eq!(expected.as_ref(), actual.as_ref(), "{data_type}, {pattern}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn evaluate_matches() {
|
||||
let input_data = vec![
|
||||
|
||||
@@ -35,7 +35,13 @@ impl Debug for ScalarUdf {
|
||||
|
||||
impl PartialEq for ScalarUdf {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.function.signature() == other.function.signature()
|
||||
// Identity first: many unrelated functions share one signature (for
|
||||
// example `Signature::any(1, Immutable)`), and DataFusion compares
|
||||
// expressions (and therefore `ScalarUDF`s) structurally, so matching on
|
||||
// the signature alone makes different functions interchangeable and
|
||||
// corrupts planning (see `rebase_expr`).
|
||||
self.function.name() == other.function.name()
|
||||
&& self.function.signature() == other.function.signature()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -43,7 +49,8 @@ impl Eq for ScalarUdf {}
|
||||
|
||||
impl Hash for ScalarUdf {
|
||||
fn hash<H: Hasher>(&self, state: &mut H) {
|
||||
self.function.signature().hash(state)
|
||||
self.function.name().hash(state);
|
||||
self.function.signature().hash(state);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -43,7 +43,9 @@ pub fn binlit_as_veclit(bytes: &[u8]) -> Result<Cow<'_, [f32]>> {
|
||||
.fail();
|
||||
}
|
||||
|
||||
if cfg!(target_endian = "little") {
|
||||
if cfg!(target_endian = "little") && bytes.as_ptr().align_offset(align_of::<f32>()) == 0 {
|
||||
// The length is a multiple of four, the pointer is aligned, and every f32 bit
|
||||
// pattern is valid. The borrowed slice cannot outlive the input bytes.
|
||||
Ok(unsafe {
|
||||
let vec = std::slice::from_raw_parts(
|
||||
bytes.as_ptr() as *const f32,
|
||||
@@ -123,6 +125,29 @@ mod tests {
|
||||
assert!(result.is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_binlit_as_veclit_alignment() {
|
||||
#[repr(align(4))]
|
||||
struct Aligned([u8; 16]);
|
||||
let mut storage = Aligned([0; 16]);
|
||||
let values = [1.25, -2.5, 3.0];
|
||||
let bytes = veclit_to_binlit(&values);
|
||||
for offset in 0..4 {
|
||||
storage.0[offset..offset + bytes.len()].copy_from_slice(&bytes);
|
||||
let result = binlit_as_veclit(&storage.0[offset..offset + bytes.len()]).unwrap();
|
||||
assert_eq!(result.as_ref(), values);
|
||||
assert_eq!(
|
||||
matches!(result, Cow::Borrowed(_)),
|
||||
cfg!(target_endian = "little") && offset == 0
|
||||
);
|
||||
assert!(
|
||||
binlit_as_veclit(&storage.0[offset..offset])
|
||||
.unwrap()
|
||||
.is_empty()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_binlit_as_veclit() {
|
||||
let vec = &[1.0, 2.0, 3.0];
|
||||
|
||||
@@ -199,6 +199,15 @@ impl FunctionState {
|
||||
Ok(ROWS)
|
||||
}
|
||||
|
||||
async fn cancel_region_compaction(
|
||||
&self,
|
||||
_region_id: RegionId,
|
||||
_task_id: String,
|
||||
_ctx: QueryContextRef,
|
||||
) -> Result<AffectedRows> {
|
||||
Ok(ROWS)
|
||||
}
|
||||
|
||||
async fn discard_unflushed_data(
|
||||
&self,
|
||||
_region_id: RegionId,
|
||||
|
||||
@@ -59,7 +59,9 @@ macro_rules! impl_current_schema_function {
|
||||
let func_ctx = find_function_context(&args)?;
|
||||
let db = func_ctx.query_ctx.current_schema();
|
||||
|
||||
Ok(ColumnarValue::Scalar(ScalarValue::Utf8View(Some(db))))
|
||||
Ok(ColumnarValue::Scalar(ScalarValue::Utf8View(
|
||||
(!db.is_empty()).then_some(db),
|
||||
)))
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user