mirror of
https://github.com/GreptimeTeam/greptimedb.git
synced 2026-11-28 05:34:02 +00:00
Merge remote-tracking branch 'upstream/main' into feat/flow-memory-scope
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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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 \
|
||||
|
||||
@@ -103,3 +103,16 @@ test('script tests gate expensive Rust and Checks jobs', () => {
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test('platform compilation runs only on schedule or manual dispatch', () => {
|
||||
const workflow = readFileSync(resolve(workflows, 'rust.yml'), 'utf8');
|
||||
for (const job of ['check-windows', 'check-riscv64']) {
|
||||
for (const event of ['pull_request', 'merge_group']) {
|
||||
assert.equal(enabled(job, { workflow, event, action: 'opened' }), false, job);
|
||||
}
|
||||
for (const event of ['schedule', 'workflow_dispatch']) {
|
||||
assert.equal(enabled(job, { workflow, event }), true, job);
|
||||
assert.equal(enabled(job, { workflow, event, repository: 'fork/greptimedb' }), false, job);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
@@ -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
|
||||
@@ -33,7 +34,7 @@ jobs:
|
||||
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
|
||||
|
||||
@@ -62,6 +62,7 @@ a module map, read/write paths, change-coupling points, and gotchas:
|
||||
- [`src/servers/AGENTS.md`](src/servers/AGENTS.md)
|
||||
- [`src/operator/AGENTS.md`](src/operator/AGENTS.md)
|
||||
- [`src/mito2/AGENTS.md`](src/mito2/AGENTS.md)
|
||||
- [`src/promql/AGENTS.md`](src/promql/AGENTS.md)
|
||||
- [`src/metric-engine/AGENTS.md`](src/metric-engine/AGENTS.md)
|
||||
- [`src/flow/AGENTS.md`](src/flow/AGENTS.md)
|
||||
- [`src/frontend/AGENTS.md`](src/frontend/AGENTS.md)
|
||||
|
||||
Generated
+106
-37
@@ -2261,6 +2261,15 @@ version = "0.5.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0c9ea0ac24bc397ab3c98583a3c9ba74fa56b09a4449bbe172b9b1ddb016027a"
|
||||
|
||||
[[package]]
|
||||
name = "cobs"
|
||||
version = "0.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0fa961b519f0b462e3a3b4a34b64d119eeaca1d59af726fe450bbba07a9fc0a1"
|
||||
dependencies = [
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "codespan-reporting"
|
||||
version = "0.12.0"
|
||||
@@ -2535,6 +2544,7 @@ dependencies = [
|
||||
"mito-codec",
|
||||
"nalgebra",
|
||||
"num-traits",
|
||||
"partition",
|
||||
"paste",
|
||||
"pretty_assertions",
|
||||
"regex",
|
||||
@@ -2813,6 +2823,7 @@ dependencies = [
|
||||
"common-time",
|
||||
"datafusion",
|
||||
"datafusion-common",
|
||||
"datafusion-datasource",
|
||||
"datafusion-expr",
|
||||
"datafusion-proto",
|
||||
"datatypes",
|
||||
@@ -2929,6 +2940,7 @@ dependencies = [
|
||||
"backtrace",
|
||||
"common-base",
|
||||
"common-error",
|
||||
"common-macro",
|
||||
"common-version",
|
||||
"console-subscriber",
|
||||
"greptime-proto",
|
||||
@@ -2943,6 +2955,7 @@ dependencies = [
|
||||
"prometheus 0.14.0",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"snafu 0.8.6",
|
||||
"tempfile",
|
||||
"tokio",
|
||||
"tracing",
|
||||
@@ -3770,7 +3783,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",
|
||||
@@ -3822,7 +3835,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",
|
||||
@@ -3846,7 +3859,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",
|
||||
@@ -3869,7 +3882,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",
|
||||
@@ -3895,7 +3908,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",
|
||||
@@ -3905,7 +3918,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",
|
||||
@@ -3941,7 +3954,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",
|
||||
@@ -3965,7 +3978,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",
|
||||
@@ -3988,7 +4001,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",
|
||||
@@ -4011,7 +4024,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",
|
||||
@@ -4043,12 +4056,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",
|
||||
@@ -4073,7 +4086,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",
|
||||
@@ -4097,7 +4110,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",
|
||||
@@ -4108,7 +4121,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",
|
||||
@@ -4139,7 +4152,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",
|
||||
@@ -4159,7 +4172,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",
|
||||
@@ -4170,7 +4183,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",
|
||||
@@ -4194,7 +4207,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",
|
||||
@@ -4209,7 +4222,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",
|
||||
@@ -4225,7 +4238,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",
|
||||
@@ -4234,7 +4247,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",
|
||||
@@ -4244,7 +4257,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",
|
||||
@@ -4292,7 +4305,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",
|
||||
@@ -4315,7 +4328,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",
|
||||
@@ -4329,7 +4342,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",
|
||||
@@ -4346,7 +4359,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",
|
||||
@@ -4365,7 +4378,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",
|
||||
@@ -4402,7 +4415,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",
|
||||
@@ -4428,7 +4441,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",
|
||||
@@ -4438,7 +4451,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",
|
||||
@@ -4448,7 +4461,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",
|
||||
@@ -4463,7 +4476,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",
|
||||
@@ -4477,7 +4490,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",
|
||||
@@ -4496,7 +4509,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",
|
||||
@@ -4609,6 +4622,7 @@ dependencies = [
|
||||
"jsonb",
|
||||
"num",
|
||||
"num-traits",
|
||||
"once_cell",
|
||||
"ordered-float 4.6.0",
|
||||
"parquet-variant",
|
||||
"parquet-variant-compute",
|
||||
@@ -5079,6 +5093,18 @@ dependencies = [
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "embedded-io"
|
||||
version = "0.4.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ef1a6892d9eef45c8fa6b9e0086428a2cca8491aca8f787c534a3d6d0bcb3ced"
|
||||
|
||||
[[package]]
|
||||
name = "embedded-io"
|
||||
version = "0.6.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "edd0f118536f44f5ccd48bcb8b111bdc3de888b58c74639dfb034a357d0f206d"
|
||||
|
||||
[[package]]
|
||||
name = "ena"
|
||||
version = "0.14.3"
|
||||
@@ -6158,7 +6184,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "greptime-proto"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/GreptimeTeam/greptime-proto.git?rev=1a30dcbfc215923ed8de0e80d8d9dbe1fc7917b6#1a30dcbfc215923ed8de0e80d8d9dbe1fc7917b6"
|
||||
source = "git+https://github.com/GreptimeTeam/greptime-proto.git?rev=c46f7ee9c82ff90f5762ae192fcf8bb2b0d6046f#c46f7ee9c82ff90f5762ae192fcf8bb2b0d6046f"
|
||||
dependencies = [
|
||||
"prost 0.14.1",
|
||||
"prost-types 0.14.1",
|
||||
@@ -7245,6 +7271,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"
|
||||
@@ -7584,7 +7621,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",
|
||||
@@ -8698,6 +8735,7 @@ dependencies = [
|
||||
"object-store",
|
||||
"partition",
|
||||
"prometheus 0.14.0",
|
||||
"rstest",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"smallvec",
|
||||
@@ -8833,6 +8871,7 @@ dependencies = [
|
||||
"humantime",
|
||||
"humantime-serde",
|
||||
"index",
|
||||
"intern-arc",
|
||||
"itertools 0.14.0",
|
||||
"lazy_static",
|
||||
"log-store",
|
||||
@@ -8864,6 +8903,7 @@ dependencies = [
|
||||
"tokio-util",
|
||||
"toml 0.8.23",
|
||||
"tracing",
|
||||
"twox-hash",
|
||||
"uuid",
|
||||
"winner_tree",
|
||||
"zstd",
|
||||
@@ -9729,6 +9769,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"
|
||||
@@ -11189,6 +11232,18 @@ dependencies = [
|
||||
"portable-atomic",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "postcard"
|
||||
version = "1.1.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6764c3b5dd454e283a30e6dfe78e9b31096d9e32036b5d1eaac7a6119ccb9a24"
|
||||
dependencies = [
|
||||
"cobs",
|
||||
"embedded-io 0.4.0",
|
||||
"embedded-io 0.6.1",
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "postgres-protocol"
|
||||
version = "0.6.12"
|
||||
@@ -11487,12 +11542,14 @@ name = "promql"
|
||||
version = "1.4.0-alpha.0"
|
||||
dependencies = [
|
||||
"ahash 0.8.12",
|
||||
"api",
|
||||
"async-trait",
|
||||
"bytemuck",
|
||||
"common-error",
|
||||
"common-macro",
|
||||
"common-query",
|
||||
"common-recordbatch",
|
||||
"common-runtime",
|
||||
"common-telemetry",
|
||||
"criterion 0.7.0",
|
||||
"datafusion",
|
||||
@@ -11502,10 +11559,19 @@ dependencies = [
|
||||
"futures",
|
||||
"greptime-proto",
|
||||
"lazy_static",
|
||||
"mito-codec",
|
||||
"postcard",
|
||||
"prometheus 0.14.0",
|
||||
"prost 0.14.1",
|
||||
"rand 0.9.4",
|
||||
"regex",
|
||||
"serde",
|
||||
"snafu 0.8.6",
|
||||
"stacker",
|
||||
"store-api",
|
||||
"table",
|
||||
"tokio",
|
||||
"twox-hash",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -13759,6 +13825,7 @@ dependencies = [
|
||||
"local-ip-address",
|
||||
"log-query",
|
||||
"loki-proto",
|
||||
"lz4_flex 0.14.0",
|
||||
"meter-core",
|
||||
"meter-macros",
|
||||
"metric-engine",
|
||||
@@ -14982,6 +15049,7 @@ dependencies = [
|
||||
"promql",
|
||||
"prost 0.14.1",
|
||||
"snafu 0.8.6",
|
||||
"tokio",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -15497,6 +15565,7 @@ dependencies = [
|
||||
"paste",
|
||||
"pipeline",
|
||||
"plugins",
|
||||
"promql",
|
||||
"prost 0.14.1",
|
||||
"query",
|
||||
"rand 0.9.4",
|
||||
|
||||
+24
-18
@@ -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 = "1a30dcbfc215923ed8de0e80d8d9dbe1fc7917b6" }
|
||||
greptime-proto = { git = "https://github.com/GreptimeTeam/greptime-proto.git", rev = "c46f7ee9c82ff90f5762ae192fcf8bb2b0d6046f" }
|
||||
hdfs-native = "0.14.6"
|
||||
hex = "0.4"
|
||||
hostname = "0.4.0"
|
||||
@@ -175,13 +175,16 @@ 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"
|
||||
local-ip-address = "0.6"
|
||||
loki-proto = { git = "https://github.com/GreptimeTeam/loki-proto.git", rev = "f69c8924c4babe516373e26a4118be82d976629c" }
|
||||
# Keep in sync with Arrow IPC's decoder; COPY bounds its output before Arrow decoding.
|
||||
lz4_flex = { version = "=0.14.0", default-features = false, features = ["frame", "std"] }
|
||||
meter-core = { git = "https://github.com/GreptimeTeam/greptime-meter.git", rev = "f743c3a5fe8c1f57363eac5866c356b7d91f9b39" }
|
||||
mockall = "0.13"
|
||||
moka = "0.12"
|
||||
@@ -214,6 +217,7 @@ parquet-variant-json = "=59.2.0"
|
||||
paste = "1.0"
|
||||
percent-encoding = "2.3"
|
||||
pin-project = "1.0"
|
||||
postcard = { version = "1.1.3", default-features = false, features = ["alloc", "use-std"] }
|
||||
pretty_assertions = "1.4.0"
|
||||
prometheus = { version = "0.14", features = ["process"] }
|
||||
promql-parser = { version = "0.10.0", features = ["ser"] }
|
||||
@@ -261,6 +265,7 @@ sqlx = { version = "0.9", default-features = false, features = [
|
||||
"tls-rustls-aws-lc-rs",
|
||||
"rust_decimal",
|
||||
] }
|
||||
stacker = "0.1.25"
|
||||
stringprep = "0.1"
|
||||
strum = { version = "0.27", features = ["derive"] }
|
||||
sysinfo = "0.33"
|
||||
@@ -282,6 +287,7 @@ tracing = "0.1"
|
||||
tracing-appender = "0.2"
|
||||
tracing-opentelemetry = "0.33.0"
|
||||
tracing-subscriber = { version = "0.3", features = ["env-filter", "json", "fmt"] }
|
||||
twox-hash = { version = "2.1", default-features = false, features = ["xxhash64"] }
|
||||
typetag = "0.2"
|
||||
uddsketch-rs = "0.1.0"
|
||||
uuid = { version = "1.17", features = ["serde", "v4", "v7", "fast-rng"] }
|
||||
@@ -371,22 +377,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" }
|
||||
|
||||
+18
-12
@@ -13,11 +13,12 @@
|
||||
| Key | Type | Default | Descriptions |
|
||||
| --- | -----| ------- | ----------- |
|
||||
| `default_timezone` | String | Unset | The default timezone of the server. |
|
||||
| `default_column_prefix` | String | Unset | The default column prefix for auto-created time index, value, and native histogram columns.<br/>Legacy OTLP summary columns keep their historical `greptime_` prefix. |
|
||||
| `default_column_prefix` | String | Unset | The default column prefix for auto-created time index, value, native histogram, and exemplar-label columns.<br/>Legacy OTLP summary columns keep their historical `greptime_` prefix. |
|
||||
| `auto_create_table` | Bool | `true` | Server-side global switch for auto table creation on write.<br/>When `false`, a missing table is never auto-created even if the request sets the `auto_create_table` hint to `true`. Default: `true`. |
|
||||
| `auto_create_physical_table_timestamp_unit` | String | Unset | Time index unit for physical metric tables created by auto table creation<br/>(Prometheus remote write, OTLP metrics, and other metric-engine ingestion).<br/>New logical tables created under such a physical table inherit its unit.<br/>Options: "Second", "Millisecond" (default), "Microsecond", "Nanosecond". |
|
||||
| `user_provider` | String | Unset | The user provider for authentication.<br/>Examples: "static_user_provider:file:/path/to/users", "static_user_provider:cmd:greptime_user=greptime_pwd"<br/>Password verifier formats: "plain:<password>", "pbkdf2_sha256:<iterations>:<hex_salt>:<hex_hash>",<br/>"mysql_native_password:<hex_sha1_sha1_password>",<br/>"pg_scram_sha256:<iterations>:<hex_salt>:<hex_stored_key>:<hex_server_key>"<br/>"pbkdf2_sha256" and "pg_scram_sha256" protect passwords at rest, but such users cannot log in over MySQL:<br/>`static_user_provider` and `watch_file_user_provider` only negotiate `mysql_native_password`, which cannot verify these formats.<br/>"mysql_native_password" is MySQL-specific and cannot authenticate over PostgreSQL at all.<br/>PostgreSQL SCRAM only covers "plain" and "pg_scram_sha256" users; if any user is "pbkdf2_sha256" or<br/>"mysql_native_password", PostgreSQL falls back to cleartext password auth for every user.<br/>For "pg_scram_sha256" users, keep the default iteration count (4096) and salt length (16): both are<br/>observable in the SCRAM server-first message, and non-default values weaken resistance to username<br/>enumeration. |
|
||||
| `max_in_flight_write_bytes` | String | 0 | Maximum total memory for all concurrent write request bodies and messages (HTTP, gRPC, Flight).<br/>Set to 0 to disable the limit. Default: "0" (unlimited) |
|
||||
| `write_bytes_exhausted_policy` | String | `wait` | Policy when write bytes quota is exhausted.<br/>Options: "wait" (default, 10s timeout), "wait(<duration>)" (e.g., "wait(30s)"), "fail" |
|
||||
| `max_in_flight_write_bytes` | String | 0 | Shared quota for concurrent write request bodies and messages (HTTP, gRPC, Flight)<br/>plus retained decoder memory and estimated PB-to-Arrow conversion memory for ordinary-table batching.<br/>A batch must fit together with its request's existing reservations; only additional memory is acquired.<br/>Set to 0 to disable the limit. Default: "0" (unlimited) |
|
||||
| `write_bytes_exhausted_policy` | String | `wait` | Policy when write bytes quota is exhausted.<br/>Options: "wait" (default, 10s timeout), "wait(<duration>)" (e.g., "wait(30s)"), "fail"<br/>Table-batch conversion never waits for additional memory. Under a wait policy,<br/>temporary contention returns a retryable error; requests that cannot fit are rejected. |
|
||||
| `init_regions_in_background` | Bool | `false` | Initialize all regions in the background during the startup.<br/>By default, it provides services after all regions have been initialized. |
|
||||
| `init_regions_parallelism` | Integer | `16` | Parallelism of initializing regions. |
|
||||
| `max_concurrent_queries` | Integer | `0` | The maximum concurrent region-read streams. Zero means unlimited.<br/>A single query can consume multiple permits. |
|
||||
@@ -143,6 +144,7 @@
|
||||
| `procedure.retry_delay` | String | `500ms` | Initial retry delay of procedures, increases exponentially |
|
||||
| `procedure.max_running_procedures` | Integer | `128` | Max running procedures.<br/>The maximum number of procedures that can be running at the same time.<br/>If the number of running procedures exceeds this limit, the procedure will be rejected. |
|
||||
| `query` | -- | -- | The query engine options. |
|
||||
| `query.experimental_native_promql` | Bool | `false` | Enable experimental native PromQL execution for compatible queries.<br/>This is the engine-wide default: a session<br/>SET query.experimental_native_promql = true or a per-request<br/>query.experimental_native_promql option overrides it, in that order.<br/>Default: false |
|
||||
| `query.parallelism` | Integer | `0` | Parallelism of the query engine.<br/>Default to 0, which means the number of CPU cores. |
|
||||
| `query.memory_pool_size` | String | 0 | Memory pool size for query execution operators (aggregation, sorting, join,<br/>and internal series merges during table scans).<br/>Supports absolute size (e.g., "2GB", "4GB") or percentage of system memory (e.g., "20%").<br/>Setting it to 0 disables the limit. Defaults to 0 (unlimited); this example sets it to `50%`.<br/>When this limit is reached, queries will fail with ResourceExhausted error.<br/>Projected Parquet row groups and streamed scan batches use scan_memory_limit separately. |
|
||||
| `query.experimental_memory_pool_policy` | String | `greedy` | Experimental memory pool allocation policy:<br/>- "greedy" (default): first-come-first-served allocation; preserves current behavior.<br/>- "fair": divides available memory among spillable operators and may spill earlier.<br/>Only effective when `memory_pool_size` is bounded (>0). |
|
||||
@@ -185,6 +187,7 @@
|
||||
| `region_engine.mito.manifest_checkpoint_distance` | Integer | `10` | Number of meta action updated to trigger a new checkpoint for the manifest. |
|
||||
| `region_engine.mito.compress_manifest` | Bool | `false` | Whether to compress manifest and checkpoint file by gzip (default false). |
|
||||
| `region_engine.mito.experimental_enable_series_index` | Bool | `false` | Under development; do not enable. Whether to enable series indexes.<br/>Indexes are stored on the local filesystem under `{data_home}/series_index`. |
|
||||
| `region_engine.mito.experimental_series_index_format` | String | `legacy` | Under development. Select legacy Parquet indexes or paired columnar series and samples. |
|
||||
| `region_engine.mito.experimental_series_index_max_size` | String | `5GiB` | Approximate series and range index size limit in open regions, shared across workers.<br/>Workers periodically refresh usage and skip maintenance when full. In-flight reconciliation<br/>can exceed the limit. Closed-region files, temporary output, catalogs, and old snapshots<br/>retained by readers are not counted.<br/>Minimum: 1KiB. Takes effect on restart. |
|
||||
| `region_engine.mito.experimental_enable_range_index` | Bool | `false` | Whether to build and query range indexes when series indexes are enabled.<br/>Obsolete range-index metadata and files are still cleaned up when disabled. |
|
||||
| `region_engine.mito.experimental_series_index_maintenance_interval` | String | `5m` | Interval between series-index maintenance runs. Zero uses the default of 5 min. |
|
||||
@@ -259,7 +262,7 @@
|
||||
| `logging.enable_file_logging` | Bool | `true` | Whether to write logs to files in `dir`. |
|
||||
| `logging.log_format` | String | `text` | The log format. Can be `text`/`json`. |
|
||||
| `logging.max_log_files` | Integer | `720` | The maximum amount of log files. |
|
||||
| `logging.max_log_dir_size` | String | `0B` | The maximum total size of managed log files in `dir`.<br/>Old closed log files are removed before writing when necessary. Active files may exceed it. Set to `0B` to disable. |
|
||||
| `logging.max_log_dir_size` | String | `0B` | The maximum total size of managed log files in `dir`.<br/>Old closed log files are removed before writing when necessary. Active files may exceed it. Set to `0B` to disable.<br/>Requires symbolic links in the log directory; initialization fails if they cannot be created.<br/>On Windows, enable Developer Mode or leave this at `0B`. |
|
||||
| `logging.enable_per_region_metrics` | Bool | `false` | Whether to enable per-region metrics.<br/>Default to false. |
|
||||
| `logging.otlp_export_protocol` | String | `http` | The OTLP tracing export protocol. Can be `grpc`/`http`. |
|
||||
| `logging.otlp_headers` | -- | -- | Additional OTLP headers, only valid when using OTLP http |
|
||||
@@ -291,11 +294,12 @@
|
||||
| Key | Type | Default | Descriptions |
|
||||
| --- | -----| ------- | ----------- |
|
||||
| `default_timezone` | String | Unset | The default timezone of the server. |
|
||||
| `default_column_prefix` | String | Unset | The default column prefix for auto-created time index, value, and native histogram columns.<br/>Legacy OTLP summary columns keep their historical `greptime_` prefix. |
|
||||
| `default_column_prefix` | String | Unset | The default column prefix for auto-created time index, value, native histogram, and exemplar-label columns.<br/>Legacy OTLP summary columns keep their historical `greptime_` prefix. |
|
||||
| `auto_create_table` | Bool | `true` | Server-side global switch for auto table creation on write.<br/>When `false`, a missing table is never auto-created even if the request sets the `auto_create_table` hint to `true`. Default: `true`. |
|
||||
| `auto_create_physical_table_timestamp_unit` | String | Unset | Time index unit for physical metric tables created by auto table creation<br/>(Prometheus remote write, OTLP metrics, and other metric-engine ingestion).<br/>New logical tables created under such a physical table inherit its unit.<br/>Options: "Second", "Millisecond" (default), "Microsecond", "Nanosecond". |
|
||||
| `user_provider` | String | Unset | The user provider for authentication.<br/>Examples: "static_user_provider:file:/path/to/users", "static_user_provider:cmd:greptime_user=greptime_pwd"<br/>Password verifier formats: "plain:<password>", "pbkdf2_sha256:<iterations>:<hex_salt>:<hex_hash>",<br/>"mysql_native_password:<hex_sha1_sha1_password>",<br/>"pg_scram_sha256:<iterations>:<hex_salt>:<hex_stored_key>:<hex_server_key>"<br/>"pbkdf2_sha256" and "pg_scram_sha256" protect passwords at rest, but such users cannot log in over MySQL:<br/>`static_user_provider` and `watch_file_user_provider` only negotiate `mysql_native_password`, which cannot verify these formats.<br/>"mysql_native_password" is MySQL-specific and cannot authenticate over PostgreSQL at all.<br/>PostgreSQL SCRAM only covers "plain" and "pg_scram_sha256" users; if any user is "pbkdf2_sha256" or<br/>"mysql_native_password", PostgreSQL falls back to cleartext password auth for every user.<br/>For "pg_scram_sha256" users, keep the default iteration count (4096) and salt length (16): both are<br/>observable in the SCRAM server-first message, and non-default values weaken resistance to username<br/>enumeration. |
|
||||
| `max_in_flight_write_bytes` | String | 0 | Maximum total memory for all concurrent write request bodies and messages (HTTP, gRPC, Flight).<br/>Set to 0 to disable the limit. Default: "0" (unlimited) |
|
||||
| `write_bytes_exhausted_policy` | String | `wait` | Policy when write bytes quota is exhausted.<br/>Options: "wait" (default, 10s timeout), "wait(<duration>)" (e.g., "wait(30s)"), "fail" |
|
||||
| `max_in_flight_write_bytes` | String | 0 | Shared quota for concurrent write request bodies and messages (HTTP, gRPC, Flight)<br/>plus retained decoder memory and estimated PB-to-Arrow conversion memory for ordinary-table batching.<br/>A batch must fit together with its request's existing reservations; only additional memory is acquired.<br/>Set to 0 to disable the limit. Default: "0" (unlimited) |
|
||||
| `write_bytes_exhausted_policy` | String | `wait` | Policy when write bytes quota is exhausted.<br/>Options: "wait" (default, 10s timeout), "wait(<duration>)" (e.g., "wait(30s)"), "fail"<br/>Table-batch conversion never waits for additional memory. Under a wait policy,<br/>temporary contention returns a retryable error; requests that cannot fit are rejected. |
|
||||
| `runtime` | -- | -- | The runtime options. |
|
||||
| `runtime.global_rt_size` | Integer | Auto | The number of threads to execute the runtime for global read operations.<br/>Defaults to max(num_cpus, 2). |
|
||||
| `runtime.compact_rt_size` | Integer | Auto | The number of threads to execute compact operations.<br/>Defaults to max(num_cpus / 2, 2). |
|
||||
@@ -392,6 +396,7 @@
|
||||
| `meta_client.metadata_cache_ttl` | String | `10m` | TTL of the metadata cache. |
|
||||
| `meta_client.metadata_cache_tti` | String | `5m` | -- |
|
||||
| `query` | -- | -- | The query engine options. |
|
||||
| `query.experimental_native_promql` | Bool | `false` | Enable experimental native PromQL execution for compatible standalone queries.<br/>Requires in-process region transport. This is the engine-wide default: a<br/>session SET query.experimental_native_promql = true or a per-request<br/>query.experimental_native_promql option overrides it, in that order.<br/>Default: false |
|
||||
| `query.parallelism` | Integer | `0` | Parallelism of the query engine.<br/>Default to 0, which means the number of CPU cores. |
|
||||
| `query.allow_query_fallback` | Bool | `false` | Whether to allow query fallback when push down optimize fails.<br/>Default to false, meaning when push down optimize failed, return error msg |
|
||||
| `query.memory_pool_size` | String | 0 | Memory pool size for query execution operators (aggregation, sorting, join).<br/>Supports absolute size (e.g., "4GB", "8GB") or percentage of system memory (e.g., "30%").<br/>Setting it to 0 disables the limit. Defaults to 0 (unlimited); this example sets it to `50%`.<br/>When this limit is reached, queries will fail with ResourceExhausted error.<br/>This pool applies to operators on this frontend. Datanodes use their own query<br/>pools for local operators and internal series merges during table scans. |
|
||||
@@ -420,7 +425,7 @@
|
||||
| `logging.enable_file_logging` | Bool | `true` | Whether to write logs to files in `dir`. |
|
||||
| `logging.log_format` | String | `text` | The log format. Can be `text`/`json`. |
|
||||
| `logging.max_log_files` | Integer | `720` | The maximum amount of log files. |
|
||||
| `logging.max_log_dir_size` | String | `0B` | The maximum total size of managed log files in `dir`.<br/>Old closed log files are removed before writing when necessary. Active files may exceed it. Set to `0B` to disable. |
|
||||
| `logging.max_log_dir_size` | String | `0B` | The maximum total size of managed log files in `dir`.<br/>Old closed log files are removed before writing when necessary. Active files may exceed it. Set to `0B` to disable.<br/>Requires symbolic links in the log directory; initialization fails if they cannot be created.<br/>On Windows, enable Developer Mode or leave this at `0B`. |
|
||||
| `logging.enable_per_region_metrics` | Bool | `false` | Whether to enable per-region metrics.<br/>Default to false. |
|
||||
| `logging.otlp_export_protocol` | String | `http` | The OTLP tracing export protocol. Can be `grpc`/`http`. |
|
||||
| `logging.otlp_headers` | -- | -- | Additional OTLP headers, only valid when using OTLP http |
|
||||
@@ -539,7 +544,7 @@
|
||||
| `logging.enable_file_logging` | Bool | `true` | Whether to write logs to files in `dir`. |
|
||||
| `logging.log_format` | String | `text` | The log format. Can be `text`/`json`. |
|
||||
| `logging.max_log_files` | Integer | `720` | The maximum amount of log files. |
|
||||
| `logging.max_log_dir_size` | String | `0B` | The maximum total size of managed log files in `dir`.<br/>Old closed log files are removed before writing when necessary. Active files may exceed it. Set to `0B` to disable. |
|
||||
| `logging.max_log_dir_size` | String | `0B` | The maximum total size of managed log files in `dir`.<br/>Old closed log files are removed before writing when necessary. Active files may exceed it. Set to `0B` to disable.<br/>Requires symbolic links in the log directory; initialization fails if they cannot be created.<br/>On Windows, enable Developer Mode or leave this at `0B`. |
|
||||
| `logging.otlp_export_protocol` | String | `http` | The OTLP tracing export protocol. Can be `grpc`/`http`. |
|
||||
| `logging.otlp_headers` | -- | -- | Additional OTLP headers, only valid when using OTLP http |
|
||||
| `logging.tracing_sample_ratio` | -- | Unset | The percentage of tracing will be sampled and exported.<br/>Valid range `[0, 1]`, 1 means all traces are sampled, 0 means all traces are not sampled, the default value is 1.<br/>ratio > 1 are treated as 1. Fractions < 0 are treated as 0 |
|
||||
@@ -555,7 +560,7 @@
|
||||
| Key | Type | Default | Descriptions |
|
||||
| --- | -----| ------- | ----------- |
|
||||
| `node_id` | Integer | Unset | The datanode identifier and should be unique in the cluster. |
|
||||
| `default_column_prefix` | String | Unset | The default column prefix for auto-created time index, value, and native histogram columns.<br/>Legacy OTLP summary columns keep their historical `greptime_` prefix. |
|
||||
| `default_column_prefix` | String | Unset | The default column prefix for auto-created time index, value, native histogram, and exemplar-label columns.<br/>Legacy OTLP summary columns keep their historical `greptime_` prefix. |
|
||||
| `require_lease_before_startup` | Bool | `false` | Start services after regions have obtained leases.<br/>It will block the datanode start if it can't receive leases in the heartbeat from metasrv. |
|
||||
| `init_regions_in_background` | Bool | `false` | Initialize all regions in the background during the startup.<br/>By default, it provides services after all regions have been initialized. |
|
||||
| `init_regions_parallelism` | Integer | `16` | Parallelism of initializing regions. |
|
||||
@@ -668,6 +673,7 @@
|
||||
| `region_engine.mito.experimental_manifest_keep_removed_file_ttl` | String | `1h` | How long to keep removed files in the `removed_files` field of manifest<br/>after they are removed from manifest.<br/>files will only be removed from `removed_files` field<br/>if both `keep_removed_file_count` and `keep_removed_file_ttl` is reached. |
|
||||
| `region_engine.mito.compress_manifest` | Bool | `false` | Whether to compress manifest and checkpoint file by gzip (default false). |
|
||||
| `region_engine.mito.experimental_enable_series_index` | Bool | `false` | Under development; do not enable. Whether to enable series indexes.<br/>Indexes are stored on the local filesystem under `{data_home}/series_index`. |
|
||||
| `region_engine.mito.experimental_series_index_format` | String | `legacy` | Under development. Select legacy Parquet indexes or paired columnar series and samples. |
|
||||
| `region_engine.mito.experimental_series_index_max_size` | String | `5GiB` | Approximate series and range index size limit in open regions, shared across workers.<br/>Workers periodically refresh usage and skip maintenance when full. In-flight reconciliation<br/>can exceed the limit. Closed-region files, temporary output, catalogs, and old snapshots<br/>retained by readers are not counted.<br/>Minimum: 1KiB. Takes effect on restart. |
|
||||
| `region_engine.mito.experimental_enable_range_index` | Bool | `false` | Whether to build and query range indexes when series indexes are enabled.<br/>Obsolete range-index metadata and files are still cleaned up when disabled. |
|
||||
| `region_engine.mito.experimental_series_index_maintenance_interval` | String | `5m` | Interval between series-index maintenance runs. Zero uses the default of 5 min. |
|
||||
@@ -746,7 +752,7 @@
|
||||
| `logging.enable_file_logging` | Bool | `true` | Whether to write logs to files in `dir`. |
|
||||
| `logging.log_format` | String | `text` | The log format. Can be `text`/`json`. |
|
||||
| `logging.max_log_files` | Integer | `720` | The maximum amount of log files. |
|
||||
| `logging.max_log_dir_size` | String | `0B` | The maximum total size of managed log files in `dir`.<br/>Old closed log files are removed before writing when necessary. Active files may exceed it. Set to `0B` to disable. |
|
||||
| `logging.max_log_dir_size` | String | `0B` | The maximum total size of managed log files in `dir`.<br/>Old closed log files are removed before writing when necessary. Active files may exceed it. Set to `0B` to disable.<br/>Requires symbolic links in the log directory; initialization fails if they cannot be created.<br/>On Windows, enable Developer Mode or leave this at `0B`. |
|
||||
| `logging.otlp_export_protocol` | String | `http` | The OTLP tracing export protocol. Can be `grpc`/`http`. |
|
||||
| `logging.otlp_headers` | -- | -- | Additional OTLP headers, only valid when using OTLP http |
|
||||
| `logging.tracing_sample_ratio` | -- | Unset | The percentage of tracing will be sampled and exported.<br/>Valid range `[0, 1]`, 1 means all traces are sampled, 0 means all traces are not sampled, the default value is 1.<br/>ratio > 1 are treated as 1. Fractions < 0 are treated as 0 |
|
||||
@@ -807,7 +813,7 @@
|
||||
| `logging.enable_file_logging` | Bool | `true` | Whether to write logs to files in `dir`. |
|
||||
| `logging.log_format` | String | `text` | The log format. Can be `text`/`json`. |
|
||||
| `logging.max_log_files` | Integer | `720` | The maximum amount of log files. |
|
||||
| `logging.max_log_dir_size` | String | `0B` | The maximum total size of managed log files in `dir`.<br/>Old closed log files are removed before writing when necessary. Active files may exceed it. Set to `0B` to disable. |
|
||||
| `logging.max_log_dir_size` | String | `0B` | The maximum total size of managed log files in `dir`.<br/>Old closed log files are removed before writing when necessary. Active files may exceed it. Set to `0B` to disable.<br/>Requires symbolic links in the log directory; initialization fails if they cannot be created.<br/>On Windows, enable Developer Mode or leave this at `0B`. |
|
||||
| `logging.otlp_export_protocol` | String | `http` | The OTLP tracing export protocol. Can be `grpc`/`http`. |
|
||||
| `logging.otlp_headers` | -- | -- | Additional OTLP headers, only valid when using OTLP http |
|
||||
| `logging.tracing_sample_ratio` | -- | Unset | The percentage of tracing will be sampled and exported.<br/>Valid range `[0, 1]`, 1 means all traces are sampled, 0 means all traces are not sampled, the default value is 1.<br/>ratio > 1 are treated as 1. Fractions < 0 are treated as 0 |
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
## @toml2docs:none-default
|
||||
node_id = 42
|
||||
|
||||
## The default column prefix for auto-created time index, value, and native histogram columns.
|
||||
## The default column prefix for auto-created time index, value, native histogram, and exemplar-label columns.
|
||||
## Legacy OTLP summary columns keep their historical `greptime_` prefix.
|
||||
## @toml2docs:none-default
|
||||
default_column_prefix = "greptime"
|
||||
@@ -333,6 +333,7 @@ overwrite_entry_start_id = false
|
||||
|
||||
## The query engine options.
|
||||
[query]
|
||||
|
||||
## Parallelism of the query engine.
|
||||
## Default to 0, which means the number of CPU cores.
|
||||
parallelism = 0
|
||||
@@ -557,6 +558,9 @@ compress_manifest = false
|
||||
## Indexes are stored on the local filesystem under `{data_home}/series_index`.
|
||||
#+ experimental_enable_series_index = false
|
||||
|
||||
## Under development. Select legacy Parquet indexes or paired columnar series and samples.
|
||||
#+ experimental_series_index_format = "legacy"
|
||||
|
||||
## Approximate series and range index size limit in open regions, shared across workers.
|
||||
## Workers periodically refresh usage and skip maintenance when full. In-flight reconciliation
|
||||
## can exceed the limit. Closed-region files, temporary output, catalogs, and old snapshots
|
||||
@@ -906,6 +910,8 @@ max_log_files = 720
|
||||
|
||||
## The maximum total size of managed log files in `dir`.
|
||||
## Old closed log files are removed before writing when necessary. Active files may exceed it. Set to `0B` to disable.
|
||||
## Requires symbolic links in the log directory; initialization fails if they cannot be created.
|
||||
## On Windows, enable Developer Mode or leave this at `0B`.
|
||||
max_log_dir_size = "0B"
|
||||
|
||||
## The OTLP tracing export protocol. Can be `grpc`/`http`.
|
||||
|
||||
@@ -126,6 +126,8 @@ max_log_files = 720
|
||||
|
||||
## The maximum total size of managed log files in `dir`.
|
||||
## Old closed log files are removed before writing when necessary. Active files may exceed it. Set to `0B` to disable.
|
||||
## Requires symbolic links in the log directory; initialization fails if they cannot be created.
|
||||
## On Windows, enable Developer Mode or leave this at `0B`.
|
||||
max_log_dir_size = "0B"
|
||||
|
||||
## The OTLP tracing export protocol. Can be `grpc`/`http`.
|
||||
@@ -151,6 +153,7 @@ default_ratio = 1.0
|
||||
#+ tokio_console_addr = "127.0.0.1"
|
||||
|
||||
[query]
|
||||
|
||||
## Parallelism of the query engine for query sent by flownode.
|
||||
## Default to 1, so it won't use too much cpu or memory
|
||||
parallelism = 1
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
## @toml2docs:none-default
|
||||
default_timezone = "UTC"
|
||||
|
||||
## The default column prefix for auto-created time index, value, and native histogram columns.
|
||||
## The default column prefix for auto-created time index, value, native histogram, and exemplar-label columns.
|
||||
## Legacy OTLP summary columns keep their historical `greptime_` prefix.
|
||||
## @toml2docs:none-default
|
||||
default_column_prefix = "greptime"
|
||||
@@ -11,6 +11,13 @@ default_column_prefix = "greptime"
|
||||
## When `false`, a missing table is never auto-created even if the request sets the `auto_create_table` hint to `true`. Default: `true`.
|
||||
#+ auto_create_table = true
|
||||
|
||||
## Time index unit for physical metric tables created by auto table creation
|
||||
## (Prometheus remote write, OTLP metrics, and other metric-engine ingestion).
|
||||
## New logical tables created under such a physical table inherit its unit.
|
||||
## Options: "Second", "Millisecond" (default), "Microsecond", "Nanosecond".
|
||||
## @toml2docs:none-default
|
||||
#+ auto_create_physical_table_timestamp_unit = "Millisecond"
|
||||
|
||||
## The user provider for authentication.
|
||||
## Examples: "static_user_provider:file:/path/to/users", "static_user_provider:cmd:greptime_user=greptime_pwd"
|
||||
## Password verifier formats: "plain:<password>", "pbkdf2_sha256:<iterations>:<hex_salt>:<hex_hash>",
|
||||
@@ -27,13 +34,17 @@ default_column_prefix = "greptime"
|
||||
## @toml2docs:none-default
|
||||
#+ user_provider = "static_user_provider:file:/path/to/users"
|
||||
|
||||
## Maximum total memory for all concurrent write request bodies and messages (HTTP, gRPC, Flight).
|
||||
## Shared quota for concurrent write request bodies and messages (HTTP, gRPC, Flight)
|
||||
## plus retained decoder memory and estimated PB-to-Arrow conversion memory for ordinary-table batching.
|
||||
## A batch must fit together with its request's existing reservations; only additional memory is acquired.
|
||||
## Set to 0 to disable the limit. Default: "0" (unlimited)
|
||||
## @toml2docs:none-default="0"
|
||||
#+ max_in_flight_write_bytes = "1GB"
|
||||
|
||||
## Policy when write bytes quota is exhausted.
|
||||
## Options: "wait" (default, 10s timeout), "wait(<duration>)" (e.g., "wait(30s)"), "fail"
|
||||
## Table-batch conversion never waits for additional memory. Under a wait policy,
|
||||
## temporary contention returns a retryable error; requests that cannot fit are rejected.
|
||||
#+ write_bytes_exhausted_policy = "wait"
|
||||
|
||||
## The runtime options.
|
||||
@@ -359,6 +370,13 @@ metadata_cache_tti = "5m"
|
||||
|
||||
## The query engine options.
|
||||
[query]
|
||||
|
||||
## Enable experimental native PromQL execution for compatible standalone queries.
|
||||
## Requires in-process region transport. This is the engine-wide default: a
|
||||
## session SET query.experimental_native_promql = true or a per-request
|
||||
## query.experimental_native_promql option overrides it, in that order.
|
||||
## Default: false
|
||||
#+ experimental_native_promql = false
|
||||
## Parallelism of the query engine.
|
||||
## Default to 0, which means the number of CPU cores.
|
||||
parallelism = 0
|
||||
@@ -453,6 +471,8 @@ max_log_files = 720
|
||||
|
||||
## The maximum total size of managed log files in `dir`.
|
||||
## Old closed log files are removed before writing when necessary. Active files may exceed it. Set to `0B` to disable.
|
||||
## Requires symbolic links in the log directory; initialization fails if they cannot be created.
|
||||
## On Windows, enable Developer Mode or leave this at `0B`.
|
||||
max_log_dir_size = "0B"
|
||||
|
||||
## Whether to enable per-region metrics.
|
||||
|
||||
@@ -392,6 +392,8 @@ max_log_files = 720
|
||||
|
||||
## The maximum total size of managed log files in `dir`.
|
||||
## Old closed log files are removed before writing when necessary. Active files may exceed it. Set to `0B` to disable.
|
||||
## Requires symbolic links in the log directory; initialization fails if they cannot be created.
|
||||
## On Windows, enable Developer Mode or leave this at `0B`.
|
||||
max_log_dir_size = "0B"
|
||||
|
||||
## The OTLP tracing export protocol. Can be `grpc`/`http`.
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
## @toml2docs:none-default
|
||||
default_timezone = "UTC"
|
||||
|
||||
## The default column prefix for auto-created time index, value, and native histogram columns.
|
||||
## The default column prefix for auto-created time index, value, native histogram, and exemplar-label columns.
|
||||
## Legacy OTLP summary columns keep their historical `greptime_` prefix.
|
||||
## @toml2docs:none-default
|
||||
default_column_prefix = "greptime"
|
||||
@@ -11,6 +11,13 @@ default_column_prefix = "greptime"
|
||||
## When `false`, a missing table is never auto-created even if the request sets the `auto_create_table` hint to `true`. Default: `true`.
|
||||
#+ auto_create_table = true
|
||||
|
||||
## Time index unit for physical metric tables created by auto table creation
|
||||
## (Prometheus remote write, OTLP metrics, and other metric-engine ingestion).
|
||||
## New logical tables created under such a physical table inherit its unit.
|
||||
## Options: "Second", "Millisecond" (default), "Microsecond", "Nanosecond".
|
||||
## @toml2docs:none-default
|
||||
#+ auto_create_physical_table_timestamp_unit = "Millisecond"
|
||||
|
||||
## The user provider for authentication.
|
||||
## Examples: "static_user_provider:file:/path/to/users", "static_user_provider:cmd:greptime_user=greptime_pwd"
|
||||
## Password verifier formats: "plain:<password>", "pbkdf2_sha256:<iterations>:<hex_salt>:<hex_hash>",
|
||||
@@ -27,13 +34,17 @@ default_column_prefix = "greptime"
|
||||
## @toml2docs:none-default
|
||||
#+ user_provider = "static_user_provider:file:/path/to/users"
|
||||
|
||||
## Maximum total memory for all concurrent write request bodies and messages (HTTP, gRPC, Flight).
|
||||
## Shared quota for concurrent write request bodies and messages (HTTP, gRPC, Flight)
|
||||
## plus retained decoder memory and estimated PB-to-Arrow conversion memory for ordinary-table batching.
|
||||
## A batch must fit together with its request's existing reservations; only additional memory is acquired.
|
||||
## Set to 0 to disable the limit. Default: "0" (unlimited)
|
||||
## @toml2docs:none-default="0"
|
||||
#+ max_in_flight_write_bytes = "1GB"
|
||||
|
||||
## Policy when write bytes quota is exhausted.
|
||||
## Options: "wait" (default, 10s timeout), "wait(<duration>)" (e.g., "wait(30s)"), "fail"
|
||||
## Table-batch conversion never waits for additional memory. Under a wait policy,
|
||||
## temporary contention returns a retryable error; requests that cannot fit are rejected.
|
||||
#+ write_bytes_exhausted_policy = "wait"
|
||||
|
||||
## Initialize all regions in the background during the startup.
|
||||
@@ -552,6 +563,13 @@ max_running_procedures = 128
|
||||
|
||||
## The query engine options.
|
||||
[query]
|
||||
|
||||
## Enable experimental native PromQL execution for compatible queries.
|
||||
## This is the engine-wide default: a session
|
||||
## SET query.experimental_native_promql = true or a per-request
|
||||
## query.experimental_native_promql option overrides it, in that order.
|
||||
## Default: false
|
||||
#+ experimental_native_promql = false
|
||||
## Parallelism of the query engine.
|
||||
## Default to 0, which means the number of CPU cores.
|
||||
parallelism = 0
|
||||
@@ -772,6 +790,9 @@ compress_manifest = false
|
||||
## Indexes are stored on the local filesystem under `{data_home}/series_index`.
|
||||
#+ experimental_enable_series_index = false
|
||||
|
||||
## Under development. Select legacy Parquet indexes or paired columnar series and samples.
|
||||
#+ experimental_series_index_format = "legacy"
|
||||
|
||||
## Approximate series and range index size limit in open regions, shared across workers.
|
||||
## Workers periodically refresh usage and skip maintenance when full. In-flight reconciliation
|
||||
## can exceed the limit. Closed-region files, temporary output, catalogs, and old snapshots
|
||||
@@ -1099,6 +1120,8 @@ max_log_files = 720
|
||||
|
||||
## The maximum total size of managed log files in `dir`.
|
||||
## Old closed log files are removed before writing when necessary. Active files may exceed it. Set to `0B` to disable.
|
||||
## Requires symbolic links in the log directory; initialization fails if they cannot be created.
|
||||
## On Windows, enable Developer Mode or leave this at `0B`.
|
||||
max_log_dir_size = "0B"
|
||||
|
||||
## Whether to enable per-region metrics.
|
||||
|
||||
@@ -0,0 +1,586 @@
|
||||
# Mito columnar samples format
|
||||
|
||||
This document specifies the version 1 on-disk layout, encodings, ordering rules,
|
||||
and validation limits for samples artifacts. The version number stays 1: the
|
||||
exact-identity change is enforced by the mandatory `identity_encoding` manifest
|
||||
discriminator, not by a version bump.
|
||||
|
||||
Every block names the exact series identity (the canonical sparse primary key), which
|
||||
the part stores once per series in its [key area](#key-area), followed by that copy's
|
||||
checksum.
|
||||
An artifact written before exact identity has the same version number and recorded
|
||||
only `(table_id, tsid)`, a hash; it can be structurally valid and perfectly ordered
|
||||
while two distinct series were merged. Nothing in such an artifact proves
|
||||
otherwise, so a manifest without the `identity_encoding` discriminator is
|
||||
rejected, and its artifact rebuilt from SSTs; there is no dual reader. The same
|
||||
applies to an artifact of the earlier layout of this format, whose keys sat inside
|
||||
the block descriptors: its `identity_encoding` value is the older
|
||||
`exact-sparse-key`, so it is refused when the manifest is opened rather than when a
|
||||
part is first read. It shares artifact conventions with
|
||||
[Mito columnar series format](mito-series.md).
|
||||
|
||||
Samples store nullable Float64 fields, timestamps, sequences, and operation types
|
||||
in single-series blocks bounded by rows and decoded bytes.
|
||||
|
||||
## Artifact manifest
|
||||
|
||||
The catalog identifier is `columnar-samples`. Its file and manifest version is 1,
|
||||
independent of the series format's version and both formats' codec identifiers.
|
||||
Existing `parquet` and `columnar-series` identifiers keep their meaning.
|
||||
|
||||
An artifact is derived either from one immutable source SST (legacy) or from
|
||||
a bounded group of snapshot SSTs contributing to one UTC day. It owns
|
||||
these objects:
|
||||
|
||||
```text
|
||||
<region_id>/samples/<generation>/manifest.json
|
||||
<region_id>/samples/<generation>/part-0.samples
|
||||
<region_id>/samples/<generation>/part-1.samples
|
||||
...
|
||||
```
|
||||
|
||||
Daily catalog entries add `source_file_ids` (the complete, sorted source SST
|
||||
set) and `window` (signed UTC day number since the Unix epoch). Missing fields
|
||||
retain legacy whole-SST semantics. The catalog key and manifest owner ID for a
|
||||
daily artifact are its unique generation ID, not an individual source SST.
|
||||
Each source group is merged once and rows are routed to nonempty days; sequence numbers, deletion markers,
|
||||
and duplicate versions are preserved. Blocks and parts retain their existing
|
||||
size bounds. An SST crossing midnight contributes to multiple artifacts.
|
||||
|
||||
Publication uses the existing atomic samples catalog, which also commits series
|
||||
and range indexes. Readers pin each generation once. A grouped artifact is
|
||||
ineligible if any source SST is absent from the query's data snapshot; exact
|
||||
sequence-range or SST-sequence-pruned scans fall back to the existing path.
|
||||
Maintenance retains complete visible groups and groups only uncovered sources,
|
||||
with at most 64 sources per merge. One anchor entry per group records `source_windows`, the
|
||||
actual populated days for every source in its group. Other daily entries share
|
||||
the same ordered source set without repeating the coverage map. Coverage checks use this
|
||||
record rather than enumerating the timestamp span. Earlier daily entries without
|
||||
this record require rebuilding. Publication commits all days together; retired
|
||||
objects remain pinned until readers release them. Source Parquet SSTs are unchanged.
|
||||
|
||||
The source file ID and generation use existing `FileId` serialization. The
|
||||
generation is unique for each build. A manifest contains:
|
||||
|
||||
| Field | Meaning |
|
||||
| --- | --- |
|
||||
| `format` | String `columnar-samples` |
|
||||
| `version` | Integer 1 |
|
||||
| `identity_encoding` | String `exact-sparse-key-area`; required, never defaulted. It names the identity *and* the layout that stores it, so `exact-sparse-key` (keys inline in the block descriptors) is different and not readable |
|
||||
| `region_id` | Physical region ID, u64 |
|
||||
| `source_file_id` | Artifact owner ID matching `SamplesEntry.file_id`; the SST ID for legacy artifacts, or the generation ID for daily artifacts |
|
||||
| `generation` | `FileId` matching the catalog artifact generation |
|
||||
| `timestamp` | Object with `column_id`, `name`, and `unit` |
|
||||
| `fields` | Ordered objects with `column_id`, `name`, `type`, and `nullable` |
|
||||
| `files` | Ordered part descriptors, defined below |
|
||||
|
||||
The timestamp's ID is u32, its name is the region's time-index name, and its unit
|
||||
is one of `second`, `millisecond`, `microsecond`, or `nanosecond`. Values are
|
||||
signed i64 counts since the Unix epoch in that unit. There is no dataset-relative
|
||||
origin, unit conversion, or timezone in the file. The timestamp is non-null.
|
||||
|
||||
The field list records the build-time region field schema in metadata order.
|
||||
Require 1..=1,024 fields, each with `type = "float64"` and `nullable = true`.
|
||||
A non-nullable source Float64 field is represented by this same nullable logical
|
||||
type with no null values. Sparse logical-table fields may be entirely null.
|
||||
Timestamp and field IDs must be distinct. All output names must be unique,
|
||||
including the internal names below. Tags are not sample fields and are not stored here.
|
||||
|
||||
The stored logical Arrow schema is `__table_id: UInt32`, `__tsid: UInt64`, the
|
||||
timestamp column with its recorded unit, `__sequence: UInt64`, `__op_type: UInt8`,
|
||||
then nullable Float64 fields in manifest order, and finally
|
||||
`__primary_key: Binary` naming the exact key of the block that produced each row.
|
||||
The five internal columns and `__primary_key` are non-null; value fields stay
|
||||
nullable, as the manifest declares them. `__table_id`/`__tsid` are the coarse,
|
||||
hash-based prefix of that key. Tag columns are not stored; the exact key is the
|
||||
identity. A reader returns that key once per output batch — each block belongs to
|
||||
exactly one series — instead of materializing the column per row, and rejects a
|
||||
request that projects it.
|
||||
|
||||
Each `files` entry contains `part_id: u32`, `file_size: u64`, `num_rows: u64`,
|
||||
`num_blocks: u64`, `first`, `last`, `min_timestamp: i64`, and `max_timestamp: i64`.
|
||||
`first` and `last` are inclusive `{ table_id: u32, tsid: u64 }` bounds. Time bounds
|
||||
are the minimum and maximum over **all** blocks in the part, not just its first
|
||||
and last rows. Every part is nonempty. Part IDs start at zero, increase by one,
|
||||
and derive `part-<part_id>.samples` names with decimal IDs and no leading zeros.
|
||||
No object path is stored in a part descriptor.
|
||||
|
||||
Parts follow input order. Adjacent identifier ranges satisfy
|
||||
`previous.last <= next.first`; equality is allowed because a series can continue
|
||||
in another part. The shared boundary series can also have equal timestamps on
|
||||
both sides. These ranges are **not disjoint**, unlike the series-index format.
|
||||
Readers consider every matching part rather than choosing a unique owner.
|
||||
|
||||
`ArtifactMetadata.objects` records the manifest and every part as `{ path, file_size }`;
|
||||
the artifact's `file_size` is their checked sum. An empty artifact has an empty
|
||||
file list and no part files. The manifest is at most 64 MiB.
|
||||
|
||||
Region, source SST, and generation must match the catalog entry. The artifact
|
||||
object list must contain exactly the derived manifest and part paths, without
|
||||
duplicates, extra objects, or inconsistent size totals. Part order comes from
|
||||
the manifest.
|
||||
|
||||
## Part file
|
||||
|
||||
```text
|
||||
┌──────────────────────────────────────────────┐
|
||||
│ Header 16 bytes │
|
||||
├──────────────────────────────────────────────┤
|
||||
│ Independently encoded/compressed chunks │
|
||||
│ Block 0: time, sequence, operation, fields │
|
||||
│ Block 1: ... │
|
||||
├──────────────────────────────────────────────┤ ← payload_end
|
||||
│ Key area: one exact series key per series, │
|
||||
│ back to back, not page bounded │
|
||||
├──────────────────────────────────────────────┤ ← key_end
|
||||
│ Leaf pages (one is the root at depth 1) │
|
||||
│ Optional internal root (depth 2) │
|
||||
├──────────────────────────────────────────────┤
|
||||
│ Trailer 120 bytes │
|
||||
└──────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
All fixed-width numbers are little-endian, without alignment padding. Byte ranges
|
||||
are half-open; offsets are absolute from the start of the part. Parse each field
|
||||
explicitly. Rust struct layout, enum order, and `usize` are not wire contracts.
|
||||
Reserved fields must be zero, and decoded structures must have no trailing bytes.
|
||||
|
||||
### Header
|
||||
|
||||
| Field | Bytes | Value |
|
||||
| --- | ---: | --- |
|
||||
| Magic | 8 | ASCII `GTSAMPLE` |
|
||||
| File version | 4 | 1 |
|
||||
| Reserved | 4 | Zero |
|
||||
|
||||
### Column payloads and row semantics
|
||||
|
||||
Each block contains exactly one series and names it by that series' exact canonical
|
||||
sparse primary key, which is stored once per series in the part's [key area](#key-area)
|
||||
and referenced by the block descriptor. The key is the SST's own encoding of
|
||||
`(table_id, tsid, label column-id/value pairs sorted by name, non-null only)`, and
|
||||
`(table_id, tsid)` is only its order-preserving prefix. Two distinct series may
|
||||
share a prefix. Timestamp, sequence, operation type, and each present value field
|
||||
are independent chunks; their references are in the metadata, not inline headers.
|
||||
Emit chunks in that order, with value fields following manifest order.
|
||||
|
||||
Rows preserve delete markers, duplicate timestamps, and equal-key ties, including
|
||||
conflicting values at the same sequence. The format does not encode a deduplicated
|
||||
or snapshot-filtered view.
|
||||
|
||||
Block keys are nondecreasing in byte-lexicographic order, timestamps are
|
||||
nondecreasing within one exact key, and sequences are nonincreasing within equal
|
||||
timestamps, including across parts. A change of exact key restarts timestamps and
|
||||
ordinals, even when the coarse `(table_id, tsid)` prefix is unchanged. Equal
|
||||
ordering keys retain input order; operation type is not a sorting key. The key area
|
||||
follows the same order, one copy per series. Block keys never decrease, so a key that
|
||||
is read must not sort before the key read before it; a repeated key must continue its
|
||||
timestamps and ordinals rather than restart them. Because key bytes are read lazily,
|
||||
the descriptor-only checks use the `(table_id, tsid)` prefix and the order, disjointness,
|
||||
and reuse of key references inside one part, and only the keys a request actually loads
|
||||
are checked for byte order and continuation.
|
||||
|
||||
Blocks split on an identity change or before the next row would exceed a packing
|
||||
limit. There is no hourly split and no padding of short blocks. The default row
|
||||
limit is 8,192, also the version-1 reader maximum; a writer may choose a smaller
|
||||
positive limit without changing the version. With `F` manifest fields and `N`
|
||||
rows, the decoded accounting size is:
|
||||
|
||||
```text
|
||||
N * (8 timestamp + 8 sequence + 1 operation + 8 * F values)
|
||||
+ F * ceil(N / 8) validity bytes
|
||||
```
|
||||
|
||||
Require this to be at most 262,144 bytes. Count all manifest fields, including
|
||||
omitted/all-null fields, and reserve validity bytes even for all-valid fields.
|
||||
This is a bound on decoded column buffers, not total allocator usage or RSS.
|
||||
The effective row cap is the largest integer satisfying both limits: 8,192 for
|
||||
one field and 31 for 1,024 fields. Encoded buffers and metadata have separate
|
||||
bounds below. Increasing the reader maximum requires an explicit compatibility
|
||||
decision; it is not merely a writer option in this version.
|
||||
|
||||
### Payload reference
|
||||
|
||||
Every stored column and metadata page uses the same 32-byte reference layout as
|
||||
the series format:
|
||||
|
||||
| Field | Bytes | Meaning |
|
||||
| --- | ---: | --- |
|
||||
| Offset | 8 | Absolute location of stored bytes |
|
||||
| Stored length | 4 | Bytes to fetch |
|
||||
| Decoded length | 4 | Bytes after decompression, before column/page decoding |
|
||||
| Checksum | 8 | XXH64 of stored bytes, seed zero |
|
||||
| Encoding ID | 2 | Sample column or metadata encoding, according to context |
|
||||
| Compression ID | 2 | Compression of the encoded bytes |
|
||||
| Reserved | 4 | Zero |
|
||||
|
||||
Lengths are nonzero. Check `offset + stored_length` for u64 overflow before
|
||||
checking the enclosing area. u32 payload lengths do not limit the part or its
|
||||
offsets to 4 GiB. Verify the checksum before decompression; require exactly the
|
||||
declared decoded length, with bounded output even if a codec frame claims more.
|
||||
Checksums detect accidental corruption, not malicious modification.
|
||||
|
||||
### Key area
|
||||
|
||||
The exact series keys occupy their own region between the column payloads and the
|
||||
metadata pages: `[payload_end, key_end)`. Keys are written back to back with no
|
||||
padding and no alignment, in block order, and every block of one series shares one
|
||||
copy of that series' key. The area therefore holds exactly one key per distinct
|
||||
series of the part, ordered by exact key. A descriptor's key reference is unique per
|
||||
series, ordered, and disjoint from every other series' copy, which is why an equal
|
||||
reference means "the same exact series" without reading the bytes.
|
||||
|
||||
A key's length is bounded by the part, not by a page or a chunk. Version 1 puts no
|
||||
page inside the key area, so one key may be far longer than the 65,536-byte page
|
||||
limit; the `u32` length in a descriptor is validated against `key_end`, so a
|
||||
corrupt length can never address bytes outside the part.
|
||||
|
||||
Each copy is `[key bytes][checksum]`, where the checksum is the u64 XXH64 of those
|
||||
key bytes with seed zero, stored little-endian. A reference's `length` counts the key
|
||||
bytes only, so the checksum is always the eight bytes after `offset + length` and is
|
||||
never part of what the reference names. There is no per-key compression and no other
|
||||
framing: the key bytes between them are stored exactly as the SST encodes them, and
|
||||
their own primary-key framing (a fixed reserved prefix plus dense or sparse label
|
||||
encoding) is what decodes them. The checksum is what protects them. A key previously
|
||||
sat inside a metadata page, whose stored bytes the page reference already checksummed;
|
||||
without a per-key checksum, flipping one label byte would keep the framing and the
|
||||
`(table_id, tsid)` prefix valid and silently attribute the block's rows to another
|
||||
series.
|
||||
|
||||
Reading stays lazy. A reader reads only the byte ranges of the keys of the blocks a
|
||||
request selects, at most once per series, and validates a fetched key's checksum, its
|
||||
framing, and its `(table_id, tsid)` prefix against the descriptor that referenced it. A
|
||||
reference is rejected as soon as its descriptor is decoded — before any row is emitted
|
||||
— when it starts before `payload_end`, when `offset + length + 8` exceeds `key_end`,
|
||||
when the length is zero, or when two consecutive descriptors of one part that do not
|
||||
name one series overlap.
|
||||
|
||||
A key reference is an offset into one part's key area, so the references of two parts
|
||||
are unrelated numbers and are never compared. Whether one exact series continues in
|
||||
another part is decided on the exact key bytes: the last key a request loaded from one
|
||||
part is compared with the first it loads from the next, and an equal key must continue
|
||||
timestamps and ordinals, while a greater key starts a new series at ordinal zero.
|
||||
|
||||
Because keys are only read for blocks a request selects, this content check covers the
|
||||
keys actually loaded: unvisited ranges are validated structurally, not by content. It
|
||||
is chained, though, so a selection that skips a block, a page, or a whole part cannot
|
||||
hide the two keys around the gap: the check compares each loaded key with the previous
|
||||
loaded key, not with the previous traversed block. Loaded keys must be nondecreasing.
|
||||
Within one exact key the ordinal must strictly increase, and only immediately adjacent
|
||||
blocks of that same key require it to be exactly one greater; a different key starts a
|
||||
new series at ordinal zero, so no ordering between the two series' ordinals is required.
|
||||
|
||||
### Metadata pages
|
||||
|
||||
A leaf describes blocks. An internal page references leaves. The root is either
|
||||
the only leaf (depth 1) or an internal page (depth 2). Other depths are unsupported
|
||||
in version 1; roll parts before a third level would be needed.
|
||||
|
||||
As in the series format, the entire page, including its kind and count, is encoded
|
||||
and independently compressed. The reference in the parent or trailer supplies
|
||||
its storage location, lengths, checksum, and codecs. There is no separate stored
|
||||
page header. Decoded pages begin with `kind: u32` and `entry_count: u64`:
|
||||
|
||||
```text
|
||||
Leaf (kind 0): Internal root (kind 1):
|
||||
kind u32 kind u32
|
||||
entry_count u64 entry_count u64
|
||||
block descriptor 0 page reference 0 72 bytes
|
||||
... ...
|
||||
block descriptor N-1 page reference N-1 72 bytes
|
||||
```
|
||||
|
||||
Pages are nonempty and limited to 65,536 decoded bytes, including the 12-byte
|
||||
prefix. Descriptors never straddle pages, and every descriptor is fixed-width because
|
||||
the key it names is not stored in it. The writer requires the 12-byte leaf prefix and
|
||||
one descriptor to fit in a configured page, which for the 1,024-field maximum is
|
||||
`12 + 56 + 44 * 1,027 = 45,256` decoded bytes. The page limit is a bound on
|
||||
descriptors only: it no longer bounds the length of a series key.
|
||||
|
||||
#### Block descriptor
|
||||
|
||||
| Field | Bytes | Meaning |
|
||||
| --- | ---: | --- |
|
||||
| Table ID | 4 | Coarse prefix of the constant key in this block |
|
||||
| TSID | 8 | Coarse prefix of the constant key in this block |
|
||||
| Key offset | 8 | Absolute offset of the block's exact key in the part's key area |
|
||||
| Key length | 4 | Nonzero; the key's `(table_id, tsid)` prefix must equal the two fields above |
|
||||
| Minimum timestamp | 8 | Signed i64, first row's timestamp |
|
||||
| Maximum timestamp | 8 | Signed i64, last row's timestamp |
|
||||
| Block ordinal | 8 | Per-identifier ordinal across the artifact |
|
||||
| Row count | 4 | Nonzero, subject to decoded-block limits |
|
||||
| Column count | 4 | Number of following column descriptors |
|
||||
| Column descriptors | 44 each | Defined below |
|
||||
|
||||
The fixed prefix is 56 bytes and does not depend on the key: `4 table ID + 8 TSID +
|
||||
8 key offset + 4 key length + 8 minimum timestamp + 8 maximum timestamp + 8 ordinal +
|
||||
4 row count + 4 column count`. Ordinals start at zero for each exact key and increase
|
||||
by one across block and part boundaries while that key continues. Blocks sort by exact
|
||||
key. Adjacent blocks of the same exact key share one key reference and satisfy
|
||||
`previous.max_timestamp <= next.min_timestamp`; equality is permitted. Blocks of
|
||||
different keys have no timestamp relation at all, and a new series' key copy starts at
|
||||
or after the end of the previous copy.
|
||||
|
||||
Each column descriptor is:
|
||||
|
||||
| Field | Bytes | Meaning |
|
||||
| --- | ---: | --- |
|
||||
| Role | 4 | 1 timestamp, 2 sequence, 3 operation type, 4 value field |
|
||||
| Column ID | 4 | Timestamp/field physical ID; zero for sequence/operation |
|
||||
| Payload reference | 32 | Independently stored chunk |
|
||||
| Null count | 4 | Number of null rows |
|
||||
|
||||
Role and column ID together identify a chunk. The role namespace avoids reserving
|
||||
physical field IDs for internal columns. Time, sequence, and operation descriptors
|
||||
are mandatory, appear first in that order, and have zero null counts. Value
|
||||
descriptors follow manifest order with no repeated or unknown IDs. A value with
|
||||
all rows null is omitted and synthesized as null by the reader; present value
|
||||
chunks have `null_count < row_count`. No value statistics are stored.
|
||||
|
||||
A block with `P` present fields has `C = 3 + P` chunks and a descriptor of
|
||||
`56 + 44 * C` bytes, whatever its key's length. For one present field that is
|
||||
`56 + 44 * 4 = 232` bytes; at the 1,024-field maximum it is `56 + 44 * 1,027 = 45,244`
|
||||
bytes, and the 12-byte leaf prefix makes that `45,256`. Key length is therefore not
|
||||
part of any page budget: a part whose exact key is far longer than a page produces the
|
||||
same descriptors, and the earlier `base + key_length` ceiling — 65,344 bytes with no
|
||||
value field, 65,300 with one, and 20,288 at the 1,024-field maximum — no longer
|
||||
exists. All chunks are physically ordered and disjoint in the column area, across
|
||||
blocks as well as within a block, and the key area follows the column area. There is no
|
||||
inline block header or block-wide compression.
|
||||
|
||||
#### Page reference and time bounds
|
||||
|
||||
Samples extend the series format's reference with two timestamp bounds:
|
||||
|
||||
| Field | Bytes | Meaning |
|
||||
| --- | ---: | --- |
|
||||
| First table ID; first TSID | 4 + 8 | Inclusive first identifier |
|
||||
| Last table ID; last TSID | 4 + 8 | Inclusive last identifier |
|
||||
| Minimum timestamp | 8 | Minimum over all descendant blocks |
|
||||
| Maximum timestamp | 8 | Maximum over all descendant blocks |
|
||||
| Payload reference | 32 | Location and codecs of the child page |
|
||||
|
||||
The reference is 72 bytes. Compare identifiers as integer pairs, not as serialized
|
||||
little-endian bytes. Time bounds use the manifest unit. The time range is an
|
||||
envelope over all identifiers in the page; it need not describe the first or last
|
||||
identifier alone. This can admit extra reads, but cannot exclude matching rows.
|
||||
Every part/page identifier interval requires `first <= last`, and all part/page/
|
||||
block time intervals require `min_timestamp <= max_timestamp`, even when pruning
|
||||
would skip their payloads.
|
||||
|
||||
Child pages follow block order. Their identifier bounds may touch at a shared
|
||||
series, just like part bounds. Do not require strict disjointness or use an
|
||||
exclusive next-child lower bound. Validate each loaded page's derived identifier
|
||||
and time bounds against its reference. At depth 2 all children must be leaves;
|
||||
reject an internal child. Child byte ranges are ordered, disjoint, within the
|
||||
metadata area, and precede the parent. The root ends immediately before the trailer.
|
||||
|
||||
An internal root has `12 + 72 * N` decoded bytes, so it holds at most
|
||||
`floor((65536 - 12) / 72) = 910` leaf references. The writer must account for the
|
||||
next descriptor's leaf placement before writing its block. If the descriptor
|
||||
would require a 911th leaf, finish this part and start the block in a new part.
|
||||
|
||||
#### Navigation and equal-timestamp example
|
||||
|
||||
For a requested qualified identity and optional half-open interval `[start, end)`,
|
||||
select every part/page whose identifier interval contains the identity and whose
|
||||
time envelope overlaps the request:
|
||||
|
||||
```text
|
||||
(start is absent || max_timestamp >= start)
|
||||
&& (end is absent || min_timestamp < end)
|
||||
```
|
||||
|
||||
For multiple selected identities, intersect the ordered ID set with the inclusive
|
||||
identifier range. A table restriction also intersects this selection. Visit each
|
||||
selected page once per request. Apply the same overlap test to leaf blocks, then
|
||||
filter decoded timestamps exactly. Metadata bounds are conservative candidates.
|
||||
No predecessor-only or unique-child lookup is used: a shared identity or timestamp
|
||||
can require several adjacent children, and even several parts.
|
||||
|
||||
```text
|
||||
Part 0, depth 2:
|
||||
Root R
|
||||
├─ Leaf A: IDs [(7,42),(7,42)], times [0,100]
|
||||
│ block ordinal 0: (7,42), times [0,100]
|
||||
└─ Leaf B: IDs [(7,42),(7,43)], times [0,200]
|
||||
block ordinal 1: (7,42), times [100,200]
|
||||
block ordinal 0: (7,43), times [0,50]
|
||||
|
||||
Part 1:
|
||||
Leaf/root C: IDs [(7,43),(7,43)], times [50,80]
|
||||
block ordinal 1: (7,43), times [50,80]
|
||||
```
|
||||
|
||||
For `(7,42)` and `[100,101)`, visit both A and B, keeping all rows at timestamp
|
||||
100 from blocks 0 and 1. Do not decode `(7,43)` payloads. For `(7,43)` and
|
||||
`[50,51)`, visit B and part 1's C: both may contain rows at 50. A `[51,60)` request
|
||||
for `(7,43)` can skip B's `(7,43)` block even though B's time envelope overlaps.
|
||||
For `(7,42)` and `[90,95)`, A is still visited although its block starts before
|
||||
the requested interval. Global time envelopes must not be computed from just
|
||||
the first and last blocks: B's range is `[0,200]`, not `[100,50]`.
|
||||
|
||||
The series-index format has no sample timestamps or time bounds.
|
||||
|
||||
### Trailer
|
||||
|
||||
| Field | Bytes | Meaning |
|
||||
| --- | ---: | --- |
|
||||
| Root page reference | 72 | Inclusive ID/time bounds and payload reference |
|
||||
| Index depth | 4 | 1 or 2 |
|
||||
| File version | 4 | 1 |
|
||||
| File length | 8 | Includes header and trailer |
|
||||
| `payload_end` | 8 | End of column area, start of key area |
|
||||
| `key_end` | 8 | End of key area, start of metadata area |
|
||||
| Magic | 8 | ASCII `GTSAMPLE` |
|
||||
| Trailer checksum | 8 | XXH64 of the preceding 112 trailer bytes (the 104-byte body and the magic), seed zero |
|
||||
|
||||
The trailer is 120 bytes. Locate it using the recorded object size without a stat
|
||||
request. Validate the checksum, magic, version, length, depth, area boundaries,
|
||||
root bounds against the manifest part descriptor, and root end position before
|
||||
traversal. Column references must lie in `[16, payload_end)`; key references must lie
|
||||
in `[payload_end, key_end)`; page references lie in `[key_end, file_length - 120)`.
|
||||
The header and trailer versions must agree.
|
||||
|
||||
## Encodings and compression
|
||||
|
||||
Sample column encoding IDs below are distinct from series column encoding IDs,
|
||||
even where their numeric values coincide. Metadata and compression have separate
|
||||
namespaces as well. Never reuse an assigned ID with a different meaning.
|
||||
|
||||
| Namespace | ID | Meaning |
|
||||
| --- | ---: | --- |
|
||||
| Column encoding | 1 | Timestamp constant step |
|
||||
| Column encoding | 2 | Timestamp delta-of-delta |
|
||||
| Column encoding | 3 | Constant sequence |
|
||||
| Column encoding | 4 | Sequence delta |
|
||||
| Column encoding | 5 | Nullable Float64 XOR |
|
||||
| Column encoding | 6 | Constant operation type |
|
||||
| Column encoding | 7 | Raw operation types |
|
||||
| Metadata encoding | 1 | Leaf/internal page layout above |
|
||||
| Compression | 0 | Raw encoded bytes |
|
||||
| Compression | 1 | Zstd frame |
|
||||
|
||||
Encode first, then compress each chunk/page independently. The default writer
|
||||
tries Zstd level 3 and chooses it only if strictly smaller than the raw encoded
|
||||
bytes. Compression 0 requires equal stored and
|
||||
decoded lengths. Compression level is a writer choice; decoding information is
|
||||
in the frame.
|
||||
|
||||
Unsigned varints use base-128/LEB128: seven data bits per byte and a high
|
||||
continuation bit. Writers emit the shortest representation. Readers reject
|
||||
truncation, more than ten bytes, a tenth byte greater than 1, and trailing bytes
|
||||
after the expected values. ZigZag maps signed i64 `x` to
|
||||
`((x as u64) << 1) ^ ((x >> 63) as u64)` and reverses that mapping on decode.
|
||||
All wrapping arithmetic below is modulo 2^64, not signed overflowing arithmetic.
|
||||
|
||||
### Timestamp encodings 1 and 2
|
||||
|
||||
Encoding 1 contains `first: i64` and `step: i64`, exactly 16 bytes. Use it when
|
||||
every adjacent difference is the same nonnegative, representable i64. A singleton
|
||||
uses step zero. Reconstruct by checked addition; reject overflow. Zero step is
|
||||
valid for repeated timestamps.
|
||||
|
||||
Encoding 2 contains the first i64, followed for two or more rows by the first
|
||||
delta as a ZigZag varint, then ZigZag varints of differences between deltas.
|
||||
Compute deltas and delta differences with wrapping arithmetic; reconstruct in
|
||||
the same way. This permits differences across the full signed timestamp range.
|
||||
After either decoding, require nondecreasing signed timestamps and exact agreement
|
||||
of first/last values with the descriptor. Consume exactly the recorded row count.
|
||||
Use encoding 1 when applicable, otherwise encoding 2.
|
||||
|
||||
### Sequence encodings 3 and 4
|
||||
|
||||
Encoding 3 contains one u64, repeated for all rows. Encoding 4 contains the first
|
||||
u64 followed by each wrapping u64 difference from its predecessor, reinterpreted
|
||||
as i64 and written as a ZigZag varint. Decode with wrapping addition. Use 3 if
|
||||
all sequences are equal, otherwise 4. Preserve all u64 bit patterns. Sequence
|
||||
need not be monotonic across different timestamps; equal-timestamp runs retain
|
||||
the input's nonincreasing order.
|
||||
|
||||
### Nullable Float64 encoding 5
|
||||
|
||||
```text
|
||||
validity_kind <u8> # 0 = all valid, 1 = bitmap
|
||||
validity <ceil(row_count/8) bytes> # only for kind 1
|
||||
first_non_null_bits <u64>
|
||||
xor_deltas <one uvarint per remaining non-null value>
|
||||
```
|
||||
|
||||
Bitmap bit `i % 8` in byte `i / 8` is one for a present value; unused high bits of
|
||||
the final byte are zero. Kind 0 has no bitmap and requires zero null count. Kind
|
||||
1 requires `0 < null_count < row_count` and an exactly matching count of unset
|
||||
in-range bits. All-null columns have no descriptor or payload, so every stored
|
||||
Float64 chunk contains at least one non-null value.
|
||||
|
||||
Process non-null values in row order. Write the first IEEE-754 bit pattern as
|
||||
u64, then varints of XOR with the previous **non-null** bit pattern. Nulls do not
|
||||
reset that previous value. Decode exactly `row_count - null_count` values and
|
||||
scatter according to validity. Preserve all bits, including signed zero, NaN
|
||||
payloads, infinities, and subnormals. Null and NaN are distinct. The unspecified
|
||||
value-buffer bits behind nulls are not part of the logical preservation contract.
|
||||
|
||||
### Operation encodings 6 and 7
|
||||
|
||||
Operation values are u8: 0 delete, 1 put, matching Mito's current `OpType` values.
|
||||
Unknown operation values fail decoding. Encoding 6 stores one byte repeated for
|
||||
the whole block; encoding 7 stores exactly one byte per row. Use 6 when all values
|
||||
are equal, otherwise 7. Neither encoding filters delete rows or discards their
|
||||
field values.
|
||||
|
||||
### Limits and evolution
|
||||
|
||||
An individual chunk has at most 1 MiB of encoded bytes after decompression and
|
||||
1 MiB plus 64 KiB of stored bytes. Pages have at most 65,536 decoded and 131,072
|
||||
stored bytes. Series keys are stored in the key area rather than in a page or a
|
||||
chunk, so a key's length is bounded by the part and by its `u32` reference length,
|
||||
not by `PAGE_LIMIT`; a key longer than a page is a supported part of this version. Bound sizes before allocating, fetching, or decompressing. Validate
|
||||
counts against enclosing bytes before allocating descriptor vectors; row counts
|
||||
must also satisfy the decoded-block formula. Null output materialization remains
|
||||
subject to the same block bound even when chunks are omitted.
|
||||
|
||||
Unknown file versions, depths, reserved fields, roles, or metadata codecs fail
|
||||
open/read explicitly. Column role must agree with its encoding: time 1/2,
|
||||
sequence 3/4, Float64 5, operation 6/7. An unknown column encoding or compression
|
||||
can be skipped if its chunk is not needed, but attempting to decode it returns
|
||||
an unsupported-codec error. Known encodings assigned to a different role are
|
||||
invalid metadata, even for an unprojected column. Unknown fields or malformed
|
||||
references must not be interpreted as omitted all-null columns.
|
||||
|
||||
New column encodings or compression methods receive new IDs. Structural changes,
|
||||
changed field meanings, or incompatible limits require a new version. Deeper
|
||||
metadata trees require an explicit reader-support and rollout decision; an
|
||||
unchanged layout alone does not make them readable by version-1 implementations.
|
||||
|
||||
The local cache root contains a layout-version marker. Startup clears the entire
|
||||
series-index cache when this marker is absent or incompatible, then rebuilds
|
||||
artifacts through existing maintenance. Source SST identity remains in metadata.
|
||||
|
||||
### Local cache rollout
|
||||
|
||||
Daily consolidation is the only layout the opt-in columnar samples backend
|
||||
writes, including manual reconciliation. Legacy-format defaults are unchanged. A day may
|
||||
contain several generations with disjoint source sets (at most 64 SSTs per merge),
|
||||
and each generation may contain multiple bounded part files. Source Parquet files
|
||||
are never rewritten.
|
||||
|
||||
This branch has no deployments, so the local series-index cache token is pinned to
|
||||
`1`: a cache written by any other build is discarded on startup and rebuilt from
|
||||
the SSTs before regions open, and ordinary SST reads remain available meanwhile.
|
||||
That is the only cache migration this layout has. An artifact written by an earlier
|
||||
build of this branch — keys inside the block descriptors, a key area without stored
|
||||
checksums, a 112-byte trailer without `key_end` — carries a different
|
||||
`identity_encoding` value, `exact-sparse-key` instead of `exact-sparse-key-area`, so
|
||||
it is refused when its manifest is opened. Maintenance treats that refusal as "not
|
||||
reusable" and rebuilds the artifact, so an old artifact is never marked reusable and
|
||||
then fails on the first part read. A part reached without that check would also be
|
||||
rejected: the reader locates a trailer from the recorded object size, reads the last
|
||||
120 bytes of such a part, and refuses the shifted frame instead of decoding it.
|
||||
Allow for rebuild time and I/O in either direction; do not reuse daily catalogs with
|
||||
an older reader outside this startup check. Existing per-SST catalog entries remain
|
||||
readable by the new reader.
|
||||
|
||||
A prepared scan uses a grouped artifact only when all of its sources belong to
|
||||
that scan's assignment or were excluded solely by its time filter. Partial coverage
|
||||
or a stale source set selects the
|
||||
ordinary SST path until reconciliation supplies complete valid coverage.
|
||||
@@ -0,0 +1,416 @@
|
||||
# Mito columnar series format
|
||||
|
||||
This document specifies the version 1 on-disk layout, encodings, ordering rules,
|
||||
and validation limits for series-index artifacts. The version number stays 1: the
|
||||
exact-identity change is enforced by the mandatory `identity_encoding` manifest
|
||||
discriminator, not by a version bump.
|
||||
|
||||
Rows are keyed by the exact series identity. A row is one distinct canonical
|
||||
sparse primary key, so two series that share `(table_id, tsid)` are two rows with
|
||||
their own labels. An artifact written before exact identity has the same version
|
||||
number and may contain an already merged row that cannot be told apart from a
|
||||
complete one; nothing else in the artifact distinguishes them. A manifest that
|
||||
does not carry `identity_encoding` is therefore rejected, and its artifact rebuilt
|
||||
from SSTs; there is no dual reader. For samples, see
|
||||
[Mito columnar samples format](mito-samples.md).
|
||||
|
||||
## Artifact manifest
|
||||
|
||||
The catalog format identifier is `columnar-series`. Its wire version is separate
|
||||
from that identifier and from all column-encoding and compression identifiers.
|
||||
Legacy catalog entries and the `parquet` identifier keep their existing meaning.
|
||||
|
||||
One immutable artifact owns the following objects under a unique generation:
|
||||
|
||||
```text
|
||||
<region_id>/series/<index_uuid>/manifest.json
|
||||
<region_id>/series/<index_uuid>/part-0.series
|
||||
<region_id>/series/<index_uuid>/part-1.series
|
||||
...
|
||||
```
|
||||
|
||||
`manifest.json` contains these fields:
|
||||
|
||||
| Field | Meaning |
|
||||
| --- | --- |
|
||||
| `format` | String `columnar-series` |
|
||||
| `version` | Integer 1 |
|
||||
| `identity_encoding` | String `exact-sparse-key`; required, never defaulted, and the only thing that separates exact-identity artifacts from older ones |
|
||||
| `region_id` | Physical region ID |
|
||||
| `generation` | Index UUID, using the existing `FileId` serialization |
|
||||
| `tags` | Ordered objects with `column_id` and `name`; all are nullable UTF-8 |
|
||||
| `coverage` | Existing `SeriesIndexEntry` representation, with `artifact` omitted and `file_size` zero |
|
||||
| `files` | Ordered objects with `part_id`, `file_size`, `num_series`, `first`, and `last` |
|
||||
|
||||
`part_id` is an unsigned 32-bit integer, starting at zero and increasing by one
|
||||
in file order. The object name is derived as `part-<part_id>.series`, using the
|
||||
decimal ID without leading zeros, under the artifact's generation prefix. No
|
||||
path is stored in a file entry. `first` and `last` are inclusive identifiers,
|
||||
represented as objects with `table_id` and `tsid`. Ranges are strictly ordered
|
||||
and disjoint. Coverage and generation must match the catalog entry.
|
||||
|
||||
The tag list records the schema at build time, including tags currently absent
|
||||
from some logical tables. The logical Arrow schema is `__table_id`, `__tsid`,
|
||||
`__series_row_count`, followed by stored tags in manifest order. It has no
|
||||
timestamp columns and is separate from the existing Parquet index schema.
|
||||
|
||||
`ArtifactMetadata.objects` lists the manifest and every part as `{ path, file_size }`
|
||||
objects. The artifact-level `file_size` is their total stored size; the manifest
|
||||
does not store its own size. Object paths derive from the generation and part IDs.
|
||||
Part order comes from the manifest. An empty artifact has an empty file list and
|
||||
no part files.
|
||||
|
||||
## Part file
|
||||
|
||||
```text
|
||||
┌──────────────────────────────────────────────┐
|
||||
│ Header 16 bytes │
|
||||
├──────────────────────────────────────────────┤
|
||||
│ Independently encoded/compressed columns │
|
||||
│ Block 0: TSIDs, counts, tags │
|
||||
│ Block 1: ... │
|
||||
├──────────────────────────────────────────────┤ ← payload_end
|
||||
│ Leaf pages (one is the root at depth 1) │
|
||||
│ Optional internal root (depth 2) │
|
||||
├──────────────────────────────────────────────┤
|
||||
│ Trailer 96 bytes │
|
||||
└──────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
All fixed-width integers are little-endian. Offsets are absolute from the start
|
||||
of the part; ranges are half-open. There is
|
||||
no alignment padding. A string is `length <u64>` followed by that many UTF-8
|
||||
bytes. Parse fields explicitly; Rust struct layout, `usize`, and enum declaration
|
||||
order are not wire contracts. Reject trailing bytes in decoded structures.
|
||||
|
||||
### Header
|
||||
|
||||
| Field | Bytes | Value |
|
||||
| --- | ---: | --- |
|
||||
| Magic | 8 | ASCII `GTSERIES` |
|
||||
| File version | 4 | 1 |
|
||||
| Reserved | 4 | Zero |
|
||||
|
||||
### Column payloads
|
||||
|
||||
An artifact indexes the series in one Mito series-index bucket. Authoritative
|
||||
data remains in Parquet SSTs; these indexes can be rebuilt. Each record contains:
|
||||
|
||||
| Logical column | Type | Storage |
|
||||
| --- | --- | --- |
|
||||
| `__table_id` | UInt32 | One constant in each block descriptor |
|
||||
| `__tsid` | UInt64 | Independently encoded column chunk |
|
||||
| `__series_row_count` | UInt64 | Independently encoded column chunk |
|
||||
| Tag columns | Nullable UTF-8 | Independent dictionary/code chunks |
|
||||
|
||||
Group records from one table into a block, using a writer row limit that defaults
|
||||
to 8,192. This is a packing choice, not a wire-format limit: every block records
|
||||
its actual number of series. A writer can use another limit without changing
|
||||
the file version, provided the encoded counts and payload sizes remain supported.
|
||||
Readers must not assume that blocks contain 8,192 rows. Write each stored column
|
||||
as an independent encoded and compressed chunk, then continue with the next
|
||||
block. Chunks have no inline header: their locations, lengths, codecs, and
|
||||
checksums are recorded in the later [metadata pages](#metadata-pages).
|
||||
|
||||
`(__table_id, __tsid)` is the coarse, hash-based prefix of the identity, not the
|
||||
identity. Equal TSIDs in different tables are distinct, and different label sets
|
||||
inside one table may hash to the same TSID. Records are ordered by the canonical
|
||||
sparse key, which groups equal prefixes together, and a record repeats only for
|
||||
the same exact key. The block's `first`/`last` identifier bounds stay coarse, so
|
||||
they overlap for colliding series and only ever over-select.
|
||||
|
||||
There is no stored `__primary_key` column: identity is reconstructed by encoding
|
||||
the record's own tags in the artifact order, which reproduces the SST key.
|
||||
|
||||
The row count records input rows aggregated for each identifier. Tags are constant
|
||||
for that identifier under the uniqueness assumption. The count is not necessarily
|
||||
the query-visible row count after deduplication or snapshot filtering.
|
||||
|
||||
No per-series or per-block timestamps or timestamp unit are stored. Time coverage
|
||||
is recorded only in the catalog bucket. Tags named `job` and `instance` are
|
||||
ordinary tag columns, not dedicated identifier components.
|
||||
|
||||
#### Integer encoding 1
|
||||
|
||||
Start each chunk with `previous = 0`. For each value, compute wrapping u64
|
||||
subtraction from the previous value, reinterpret the result as i64,
|
||||
ZigZag-encode it, and write an unsigned base-128 varint. The previous value
|
||||
becomes the current value. Decoding
|
||||
uses wrapping addition after reversing ZigZag. This preserves all UInt64 values,
|
||||
including differences beyond the signed range.
|
||||
|
||||
A varint has seven low data bits per byte and the high continuation bit. It is
|
||||
at most ten bytes; the tenth byte can contain only bit zero and cannot continue.
|
||||
The writer uses the shortest representation. Decode exactly the block's number
|
||||
of series and reject truncation, overflow, and trailing bytes. TSID values must
|
||||
be strictly increasing and agree with the descriptor's first/last values.
|
||||
|
||||
#### Dictionary encoding 2
|
||||
|
||||
```text
|
||||
dictionary_byte_length <uvarint>
|
||||
dictionary:
|
||||
entry_count <u64>
|
||||
repeated entries:
|
||||
present <u8> # 0 = null, 1 = UTF-8 string
|
||||
string <length + bytes> # only if present = 1
|
||||
row_codes <one uvarint per series>
|
||||
```
|
||||
|
||||
Entry zero is null; remaining entries are distinct non-null strings in
|
||||
first-occurrence order. Null cannot occur at another entry. The empty string is
|
||||
a non-null entry with zero bytes. Dictionary length includes its count and entry
|
||||
framing. Codes must be in range; the dictionary and code streams must each be
|
||||
consumed exactly.
|
||||
|
||||
### Metadata pages
|
||||
|
||||
The metadata is a tree that maps identifier ranges to column locations:
|
||||
|
||||
- A **leaf page** describes data blocks and where their column chunks are stored.
|
||||
- An **internal page** points to other metadata pages, with an identifier range
|
||||
for each child so the reader can skip unrelated children.
|
||||
- The **root page** is the tree's entrypoint, referenced by the trailer. It is
|
||||
either a leaf or an internal page; there is no separate root page encoding.
|
||||
|
||||
Version 1 supports depths 1 and 2 only; internal pages cannot occur below the root.
|
||||
|
||||
Each page is encoded and compressed independently. The diagrams below show its
|
||||
**decoded bytes**. The stored bytes are the compressed form of that entire page;
|
||||
the kind and entry count are inside the compressed payload. The parent's page
|
||||
reference supplies the location, lengths, checksum, and codecs needed to read it.
|
||||
For the root, that reference is in the trailer.
|
||||
|
||||
#### Leaf page
|
||||
|
||||
A leaf uses kind 0. Its entry count is the number of block descriptors, not the
|
||||
number of series. Block descriptors have variable length because their column
|
||||
names and label statistics have variable length.
|
||||
|
||||
```text
|
||||
┌───────────────────────────────────────────────────────┐
|
||||
│ kind = 0 u32 │
|
||||
│ entry_count = N u64 │
|
||||
├───────────────────────────────────────────────────────┤
|
||||
│ Block descriptor 0 │
|
||||
│ table_id u32 │
|
||||
│ first_tsid, last_tsid 2 × u64│
|
||||
│ num_series, num_columns 2 × u32│
|
||||
│ Column descriptor 0 │
|
||||
│ name string │
|
||||
│ payload reference 32 bytes │──→ column chunk
|
||||
│ null_count, statistics_kind 2 × u32│ in payload area
|
||||
│ optional label min/max strings │
|
||||
│ ... │
|
||||
│ Column descriptor num_columns - 1 │
|
||||
├───────────────────────────────────────────────────────┤
|
||||
│ ... │
|
||||
│ Block descriptor N - 1 │
|
||||
└───────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
The leaf contains locations and statistics, not the column values themselves.
|
||||
Its table ID supplies the constant `__table_id` value for each series in a block.
|
||||
The exact descriptor fields are specified under [Block descriptor](#block-descriptor).
|
||||
|
||||
#### Internal page
|
||||
|
||||
An internal page uses kind 1. Its entry count is the number of child metadata
|
||||
pages. Each entry is a fixed-size 56-byte page reference:
|
||||
|
||||
```text
|
||||
┌───────────────────────────────────────────────────────┐
|
||||
│ kind = 1 u32 │
|
||||
│ entry_count = N u64 │
|
||||
├───────────────────────────────────────────────────────┤
|
||||
│ Child page reference 0 56 bytes │
|
||||
│ first = (table_id, tsid) 12 bytes │
|
||||
│ last = (table_id, tsid) 12 bytes │
|
||||
│ payload reference 32 bytes │──→ child page
|
||||
├───────────────────────────────────────────────────────┤
|
||||
│ ... │
|
||||
│ Child page reference N - 1 56 bytes │
|
||||
└───────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
An internal page's decoded size is `12 + N × 56` bytes. It is always the root and all its children are leaves. An internal page has no
|
||||
block descriptors or column data. At the 65,536-byte page limit, the root holds
|
||||
at most `floor((65536 - 12) / 56) = 1170` leaf references.
|
||||
|
||||
#### Root page and traversal example
|
||||
|
||||
If all block descriptors fit in one leaf, that leaf is also the root and the
|
||||
trailer records depth 1. Otherwise the root is an internal page and the trailer
|
||||
records depth 2: root → leaves. Other depths are invalid in version 1.
|
||||
|
||||
For example, four data blocks can be indexed by two leaves and an internal root.
|
||||
The ranges below are inclusive `(table_id, tsid)` bounds; they do not imply that
|
||||
every ID between the endpoints exists.
|
||||
|
||||
```text
|
||||
Trailer: depth = 2
|
||||
root reference: [(7,10), (7,49)]
|
||||
│
|
||||
▼
|
||||
Root R: internal page, kind = 1, entry_count = 2
|
||||
├─ reference [(7,10), (7,29)] ──→ Leaf A: kind = 0, entry_count = 2
|
||||
│ ├─ Block 0: table 7, TSIDs [10,19]
|
||||
│ └─ Block 1: table 7, TSIDs [20,29]
|
||||
└─ reference [(7,30), (7,49)] ──→ Leaf B: kind = 0, entry_count = 2
|
||||
├─ Block 2: table 7, TSIDs [30,39]
|
||||
└─ Block 3: table 7, TSIDs [40,49]
|
||||
|
||||
Physical order, from payload_end to end of part:
|
||||
[compressed Leaf A] [compressed Leaf B] [compressed Root R] [Trailer]
|
||||
```
|
||||
|
||||
To find `(7,35)`, read the trailer and Root R, then follow only the reference to
|
||||
Leaf B. Its Block 2 descriptor locates the TSID and requested label/count chunks
|
||||
in the earlier column payload area. Decode the TSID chunk to find the exact row;
|
||||
metadata bounds only identify a candidate block. Leaf A and Block 3's payloads
|
||||
are not needed.
|
||||
|
||||
The root's own bounds and storage reference live in the trailer; its page bytes
|
||||
have exactly the leaf or internal layout above. At depth 2 the writer emits all
|
||||
leaves and then the internal root. At depth 1 it emits only the single leaf.
|
||||
|
||||
#### Page ordering and size limits
|
||||
|
||||
Pages are nonempty. A leaf's bounds are its first/last block bounds; an internal
|
||||
page's bounds are its first/last child bounds. Child key ranges are strictly
|
||||
ordered and disjoint, as are block ranges. Children physically precede their
|
||||
parent and their stored ranges do not overlap. Columns within a leaf are likewise
|
||||
physically ordered and non-overlapping.
|
||||
|
||||
Pages target 65,536 decoded bytes including the 12-byte prefix. A descriptor
|
||||
never straddles pages. A descriptor larger than the target gets its own leaf,
|
||||
capped at 8 MiB including framing; a larger descriptor fails the build. Internal
|
||||
pages never exceed 65,536 decoded bytes. Stored pages are capped at 8 MiB plus
|
||||
64 KiB. Readers validate sizes and counts before allocating or decompressing.
|
||||
|
||||
#### Payload reference
|
||||
|
||||
Every column chunk and metadata page has this 32-byte reference:
|
||||
|
||||
| Field | Bytes | Meaning |
|
||||
| --- | ---: | --- |
|
||||
| Offset | 8 | Absolute location of stored bytes |
|
||||
| Stored length | 4 | Bytes to fetch |
|
||||
| Decoded length | 4 | Bytes after decompression, before decoding |
|
||||
| Checksum | 8 | XXH64 of stored bytes, seed zero |
|
||||
| Encoding ID | 2 | Column or metadata encoding, according to context |
|
||||
| Compression ID | 2 | Compression of the encoded payload |
|
||||
| Reserved | 4 | Zero |
|
||||
|
||||
The offset is u64, so a payload can start beyond the 4 GiB boundary. The two u32
|
||||
lengths limit a single stored or decoded payload to at most `2^32 - 1` bytes;
|
||||
they do not limit the whole part to 4 GiB. File length and `payload_end` are also
|
||||
u64. This version keeps u32 payload lengths because chunks and pages have much
|
||||
smaller bounded sizes. Check `offset + stored_length` in u64 with overflow
|
||||
handling, and validate decoded sizes before converting to allocation sizes.
|
||||
|
||||
The checksum is verified before decompression. Decompression must produce exactly
|
||||
the declared length. Encoding and compression are independent: encode first,
|
||||
compress second. Compression parameters needed for decoding must be in the codec
|
||||
frame; the Zstd level is a writer choice, not a decoding requirement.
|
||||
|
||||
#### Page reference
|
||||
|
||||
A page reference is 56 bytes: `first table ID <u32>`, `first TSID <u64>`,
|
||||
`last table ID <u32>`, `last TSID <u64>`, then a 32-byte payload reference.
|
||||
Bounds are inclusive. Compare identifiers as integer pairs, not by the byte
|
||||
ordering of their little-endian representation.
|
||||
|
||||
#### Block descriptor
|
||||
|
||||
A block contains series from one table; its actual row count is recorded below.
|
||||
The writer defaults to 8,192 series per block. A table boundary ends the current
|
||||
block without necessarily ending the part. The decoded block descriptor has the
|
||||
following fields in order:
|
||||
|
||||
| Field | Encoding |
|
||||
| --- | --- |
|
||||
| Table ID | u32 |
|
||||
| First and last TSID | u64 each, inclusive |
|
||||
| Number of series | u32, nonzero |
|
||||
| Number of stored columns | u32 |
|
||||
| Column descriptors | Repeated in logical-schema order, excluding table ID |
|
||||
|
||||
Each column descriptor contains `name <string>`, `payload <32-byte reference>`,
|
||||
`null_count <u32>`, and `statistics_kind <u32>`. Statistics kind 0 has no extra
|
||||
fields; kind 1 adds minimum and maximum non-null strings, in that order. Only
|
||||
tag columns use kind 1. String bounds use UTF-8 byte lexicographic order.
|
||||
|
||||
TSID and row count are mandatory, non-null columns. An all-null tag column can
|
||||
be omitted; its logical values are all null
|
||||
and its inferred null count equals the number of series. A present tag chunk
|
||||
has string bounds if it contains any non-null values. Null and the empty string
|
||||
are distinct. Names must be unique and belong to the manifest schema.
|
||||
|
||||
### Trailer
|
||||
|
||||
| Field | Bytes | Meaning |
|
||||
| --- | ---: | --- |
|
||||
| Root page reference | 56 | Root bounds and payload location/codecs |
|
||||
| Index depth | 4 | Leaf-only index = 1 |
|
||||
| File version | 4 | 1 |
|
||||
| File length | 8 | Includes header and trailer |
|
||||
| `payload_end` | 8 | End of column area, start of metadata area |
|
||||
| Magic | 8 | ASCII `GTSERIES` |
|
||||
| Trailer checksum | 8 | XXH64 of the preceding 88 trailer bytes, seed zero |
|
||||
|
||||
The root ends immediately before the trailer. Supported depths are 1 and 2. Page ranges
|
||||
lie in the metadata area; column ranges lie between the header and `payload_end`.
|
||||
Checksums detect accidental corruption; they do not authenticate data.
|
||||
|
||||
## Codec selection and evolution
|
||||
|
||||
Encoding IDs have separate column and metadata namespaces. IDs are explicitly
|
||||
assigned and never reused. Version 1 supports:
|
||||
|
||||
| Namespace | ID | Meaning |
|
||||
| --- | ---: | --- |
|
||||
| Column encoding | 1 | Wrapping delta, ZigZag, unsigned varint integer stream |
|
||||
| Column encoding | 2 | Nullable UTF-8 dictionary and unsigned varint codes |
|
||||
| Metadata encoding | 1 | Block descriptors / page references defined above |
|
||||
| Compression | 0 | None; stored length equals decoded length |
|
||||
| Compression | 1 | Zstd frame |
|
||||
|
||||
Compression 0 stores encoded bytes without compression. Compression 1 stores
|
||||
a Zstd frame; its level does not affect the decoding contract.
|
||||
|
||||
Changing the writer's block row limit (for example, from 8,192 to 16,384) requires
|
||||
no codec ID, trailer extension, or file-version change: the block descriptor
|
||||
already supplies the actual row count. The same applies to part rollover choices.
|
||||
These choices remain subject to field-width and reader resource limits. They
|
||||
are distinct from changing the serialized structure of a descriptor or trailer.
|
||||
|
||||
A new encoding gets a new ID and its own documented payload interpretation;
|
||||
it can coexist with older encodings in the same file. A codec can define its
|
||||
own payload prefix for parameters. A new compression method likewise receives
|
||||
a new ID. Neither change requires rewriting the outer layout. Changing the outer structures or the meaning of an existing field
|
||||
requires a new file version. Reserved fields must remain zero in version 1.
|
||||
|
||||
Unknown versions, reserved bits, or metadata codecs fail open/read explicitly.
|
||||
An unknown column codec may be skipped when its column is neither projected nor
|
||||
needed for filtering; attempting to read it returns an unsupported-codec error.
|
||||
It must never be interpreted as null or silently decoded with a default codec.
|
||||
|
||||
## Format limits
|
||||
|
||||
Version 1 permits metadata depths 1 and 2 only. At most 1,170 leaf references
|
||||
fit in the root; an artifact may use additional parts when that limit is reached.
|
||||
Part size and block packing choices do not alter the wire layout.
|
||||
|
||||
An individual column chunk is capped at 64 MiB decoded and 64 MiB plus 1 MiB
|
||||
stored. A block contains at most 8,388,608 series. The manifest is at most 64 MiB.
|
||||
Offsets, lengths, and counts must fit their enclosing areas without arithmetic
|
||||
overflow. Counts must not imply allocations larger than the enclosing decoded
|
||||
payload permits.
|
||||
|
||||
## Local cache compatibility
|
||||
|
||||
The local series-index cache has a root `version` marker independent of this
|
||||
format version. Before workers start, a missing or incompatible marker causes
|
||||
the entire derived cache (including samples, ranges, and catalogs) to be reset.
|
||||
Matching-version restarts preserve the cache.
|
||||
@@ -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.
|
||||
|
||||
@@ -168,10 +174,51 @@ To move the WAL to another location, stop the instance, copy every object under
|
||||
|
||||
The check does not catch every change of location. A location whose prefix already holds objects passes a region that never flushed, and a region whose watermark names an object at or below the newest object holding entries there, whatever history those objects hold. A refused start on an empty prefix leaves its start object behind when the process ends before the delete completes or when the delete fails, which is logged; the next start then finds a prefix with only start objects and passes a region that never flushed, while it still refuses every region whose watermark names an object. The same holds when the store created a region before the refusal. When it admitted an append or a release before the refusal, as it can when regions open while the instance already serves, the store withdraws nothing and the prefix keeps an object holding entries, which may already have collected the start object; the next start then also passes every region whose watermark names an object at or below that one.
|
||||
|
||||
**Metrics.** The store exports metrics under `greptime_logstore_object_store_wal_`. The write path reports `seal_to_durable_seconds`, the time from sealing a batch until its object is durable, `append_ack_seconds`, the time an append waits for its acknowledgement in the `durable` mode, `object_bytes` and `object_entries`, the size and the entry count of every object sealed, and `created_objects_total`, the creates that succeeded, an identical retry included; a create is counted and timed whether or not its batch is still there to be indexed, since an object a poisoned store gave up on is as durable as any other. `indexed_objects` and `indexed_bytes` are the objects and the bytes the catalog holds, set by a recovery that succeeded and moved by every object indexed or unindexed afterwards, so a collection takes the object it deleted off both, and a recovery that is abandoned publishes neither. A recovery that succeeds reports `recovery_seconds` and the objects it read footers from in `recovered_objects_total`, both of the same recoveries, so one that is abandoned at a fetch or rejected by the catalog contributes to neither; a read stream reports `read_seconds` once it has been read to its end, and one that fails or is dropped part way reports nothing. The failure paths are counted: `create_conflicts_total` for a create that found a conflicting object, `create_failures_total` for one the object store did not confirm, `poisoned_total` for a store that recorded a terminal error, `skipped_segments_total` for a segment a read skipped, `missing_history_accepted_total` for a region that `accept_missing_history` let open without its history, and `stalled_appends_total` with `stalled_append_seconds` for an append held back because the sealed batches were full, in either mode, or by the `enqueued` backlog thresholds, timed until it is admitted or refused, a stop, a terminal error, a failing store or the teardown of the actor releasing it included. The gauge `failing` counts the stores whose backlog the object store refuses with an error that requires intervention, and `rejected_appends_total` the appends and releases such a store rejected; the attempts of a failing store are counted in `create_failures_total`. The delete counters of a collection and the release record counter are described under *Entry ids*. The histogram buckets are chosen for the default flush interval of 100 ms and the default `max_batch_bytes` of 8 MiB.
|
||||
**Metrics.** The store exports metrics under `greptime_logstore_object_store_wal_`. The write path reports `seal_to_durable_seconds`, the time from sealing a batch until its object is durable, `append_ack_seconds`, the time an append waits for its acknowledgement in the `durable` mode, `object_bytes` and `object_entries`, the size and the entry count of every object sealed, and `created_objects_total`, the creates that succeeded, an identical retry included; a create is counted and timed whether or not its batch is still there to be indexed, since an object a poisoned store gave up on is as durable as any other. `indexed_objects` and `indexed_bytes` are the objects and the bytes the catalog holds, set by a recovery that succeeded and moved by every object indexed or unindexed afterwards, so a collection takes the object it deleted off both, and a recovery that is abandoned publishes neither. A recovery that succeeds reports `recovery_seconds` and the objects it read footers from in `recovered_objects_total`, both of the same recoveries, so one that is abandoned at a fetch or rejected by the catalog contributes to neither; a read stream reports `read_seconds` once it has been read to its end, and one that fails or is dropped part way reports nothing. The failure paths are counted: `create_conflicts_total` for a create that found a conflicting object, `create_failures_total` for one the object store did not confirm, `poisoned_total` for a store that recorded a terminal error, `skipped_segments_total` for a segment a read skipped, `missing_history_accepted_total` for a region that `accept_missing_history` let open without its history, and `stalled_appends_total` with `stalled_append_seconds` for an append held back because the sealed batches were full, in either mode, or by the `enqueued` backlog thresholds, timed until it is admitted or refused, a stop, a terminal error, a failing store or the teardown of the actor releasing it included. The gauge `failing` counts the stores whose backlog the object store refuses with an error that requires intervention, and `rejected_appends_total` the appends and releases such a store rejected; the attempts of a failing store are counted in `create_failures_total`. The gauge `io_permission_unavailable` counts live stores observed without permission to initiate object-store I/O, including idle stores and those awaiting their first grant. Each store is counted once while permission is unavailable and removed from the count when permission returns or its actor exits; the gauge measures permission availability, not backlog size. The delete counters of a collection and the release record counter are described under *Entry ids*. The histogram buckets are chosen for the default flush interval of 100 ms and the default `max_batch_bytes` of 8 MiB.
|
||||
|
||||
A `testing` cargo feature exposes hooks to wait for admitted appends, to seal the open batch, to hold and release creates and to make creates fail, so engine tests can flush deterministically and observe entries that are admitted but not durable.
|
||||
|
||||
### Node lease and recovery fencing
|
||||
|
||||
A metasrv-controlled datanode accepts object-store WAL only when its plugins
|
||||
contain `EnableObjectStoreWal`; OSS does not register this marker. The builder
|
||||
installs an I/O permit backed by Mito's node lease before opening regions. The
|
||||
permit exposes only whether new object-store I/O is allowed; the WAL does not
|
||||
own deadlines or heartbeat renewal. Standalone installs no permit. The node
|
||||
prefix retains the fixed `epochs/0` directory across restarts, independently of
|
||||
the heartbeat node epoch and the store epoch in object headers. Metasrv
|
||||
configuration, failover integration and Enterprise registration remain separate
|
||||
prerequisites for enabling the distributed WAL.
|
||||
Startup's initial object and its withdrawal after a missing-history failure are
|
||||
exempt so startup does not depend on a heartbeat that has not started yet.
|
||||
|
||||
Every new upload, including a retry or release-only object, and every collection
|
||||
delete checks the permit immediately before issuance. Issued operations may
|
||||
finish, including their transport retries. The flush timer checks expiry and
|
||||
renewal without sealing while expired. Expiry fails durable open and unindexed
|
||||
batches with a retryable error, ignores their late upload results and never
|
||||
reuses their ids. Enqueued batches already acknowledged remain pending until
|
||||
renewal. Release records remain available for a later batch, while their current
|
||||
waiters fail. An admission that would wait for upload capacity fails immediately
|
||||
while expired; ordinary admissions continue to rely on the region write lease.
|
||||
|
||||
The datanode keeps the heartbeat running until the object-store WAL stops, then
|
||||
closes the heartbeat and regions. If the lease expires during shutdown, the WAL
|
||||
drops its unindexed backlog without waiting for uploads, and still waits for
|
||||
issued deletes. Expiry is checked on the next flush timer tick, including during
|
||||
shutdown, so detection can take one configured flush interval plus actor
|
||||
scheduling delay. Dropping acknowledged enqueued entries has crash semantics.
|
||||
|
||||
Recovery still selects the latest complete chain, but before writing its initial
|
||||
object checks that the selected tip carries the maximum epoch among all listed
|
||||
headers. Falling back to an older epoch fails without modifying storage, with
|
||||
the skipped epochs, object counts and sequence ranges in the error. Explicit
|
||||
`accept_missing_history` permits this fallback only as an operator recovery:
|
||||
previous writers must have exited and acknowledged unflushed data may be lost.
|
||||
The new initial object's epoch exceeds every listed epoch. An incomplete branch
|
||||
within the selected epoch does not trigger this rejection. Remote readers always
|
||||
reject an older-epoch fallback, independent of this setting.
|
||||
|
||||
## Mito integration
|
||||
|
||||
Mito maps `WalOptions::ObjectStore { prefix }` to `Provider::object_store_provider(region_id, prefix)`; resolving object store options against a Raft Engine or Kafka log store reports the existing incompatible-provider error. Reads go through the region-scoped reader used for Kafka, so a namespace shared by many regions never leaks entries across regions even if a log store returned them. Object store regions are opened individually rather than grouped by topic. After replay, `topic_latest_entry_id` follows the existing remote-WAL rule: it is taken from the store's latest entry id only when the region's memtables are empty, otherwise it stays at the replay start, because that value feeds pruning and must never advance past unflushed data. Before a flush, a full truncate or a discard of unflushed data publishes a manifest watermark, Mito waits on the durability barrier described under *Acknowledgement*; with the `durable` mode and with every other provider the wait returns at once. When Mito drops a region it calls `release_region` after `obsolete`, as described under *Entry ids*; the default of that method does nothing, so the other providers handle a dropped region as before. Neither a release nor an `obsolete` of an object store region that fails, the latter for instance on a store that the release of another region poisoned, fails the drop, since nothing sends the drop of a removed region again and a caller that drops several regions, such as the metric engine with its data and metadata regions, would leave the others undone: the region's runtime state is cleaned up and its files are scheduled for deletion as for any drop, and the failure is logged; an `obsolete` that fails for another provider fails the drop as before. A store that is neither stopped nor poisoned keeps the record and writes it with its next object; a stopped or poisoned store keeps none, and the region stays unreleased after a restart. The store carries the record in a later object, as described under *Entry ids*; a crash before any later create succeeds loses it, and the dropped region's segments then hold the reclaim boundary after the restart. Before Mito replays an existing region on open, on catch-up or for a create that finds the region present, it runs the history check described under *Log store*.
|
||||
@@ -180,7 +227,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
|
||||
|
||||
@@ -265,7 +312,7 @@ The reference implementation was validated on the following evidence; the tests
|
||||
- Object store access: an unwritable store; a listing, a trailer fetch, a footer fetch, a segment fetch and a delete that fail; a delete that fails and is retried by the next collection; an object collected between the listing and its fetch, below and at the tip's reclaim boundary; an object store that answers slowly.
|
||||
- Store state: an object the catalog rejects, per-region entry id exhaustion, the catalog refusing a next sequence past the maximum, every stop path with several creates in flight that succeed, fail transiently or conflict after stop began, a stop with a delete in flight, an append held back by full sealed batches, and the appends the backlog thresholds were holding back released by admission, by a stop, by a terminal error and by the teardown of the actor.
|
||||
- Pipelined uploader: concurrent creates acknowledged in sequence order, every sealed batch linked to its pipeline predecessor, the open batch sealing at the threshold while creates are in flight, a transient failure failing every batch that is not indexed, created ones included, a permanent failure poisoning the store.
|
||||
- Chain recovery: a linear chain, orphans below and above the tip, a broken tip falling back to the latest complete object, a late object of an earlier epoch next to the chain of a later one, a missing predecessor, objects present without a complete chain, orphans raising the next sequence, and the start object on an empty prefix and meeting objects of an earlier and of a later epoch.
|
||||
- Chain recovery: a linear chain, orphans below and above the tip, an incomplete branch within the selected epoch, rejection of an older-epoch fallback before any mutation and its explicit acceptance with `accept_missing_history`, a late object of an earlier epoch next to the chain of a later one, a missing predecessor, objects present without a complete chain, orphans raising the next sequence, and the start object on an empty prefix and meeting objects of an earlier and of a later epoch.
|
||||
|
||||
### What the evidence does not cover
|
||||
|
||||
@@ -340,9 +387,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.
|
||||
@@ -26,6 +26,10 @@ 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",
|
||||
|
||||
@@ -42,6 +42,10 @@ 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",
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -12,6 +12,7 @@
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
use futures::TryStreamExt;
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
|
||||
@@ -74,6 +75,21 @@ impl DfTableSourceProvider {
|
||||
&self.query_ctx
|
||||
}
|
||||
|
||||
/// The logical metric tables of `schema`: the metric engine's own tables, not their physical
|
||||
/// backing. A selector that names no metric is answered by enumerating these.
|
||||
pub async fn logical_metric_tables(&self, schema: &str) -> Result<Vec<TableRef>> {
|
||||
self.catalog_manager
|
||||
.tables(&self.default_catalog, schema, Some(&self.query_ctx))
|
||||
.try_filter(|table| {
|
||||
std::future::ready(
|
||||
table.table_info().meta.engine == common_catalog::consts::METRIC_ENGINE
|
||||
&& !table.table_info().is_physical_table(),
|
||||
)
|
||||
})
|
||||
.try_collect()
|
||||
.await
|
||||
}
|
||||
|
||||
pub fn resolve_table_ref(&self, table_ref: TableReference) -> Result<ResolvedTableReference> {
|
||||
if self.disallow_cross_catalog_query {
|
||||
match &table_ref {
|
||||
|
||||
@@ -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"));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1632,10 +1632,15 @@ mod tests {
|
||||
assert_eq!(batch.num_rows(), 1);
|
||||
|
||||
let err = record_batch_stream.next().await.unwrap().unwrap_err();
|
||||
assert_eq!("External error", err.to_string());
|
||||
// The failure keeps its message: a client reading the error learns what went wrong, not
|
||||
// just that a stream failed.
|
||||
assert!(
|
||||
format!("{err:?}").contains("Invalid terminal metrics message"),
|
||||
"unexpected error: {err:?}"
|
||||
err.to_string().starts_with("External error: "),
|
||||
"unexpected error: {err}"
|
||||
);
|
||||
assert!(
|
||||
err.to_string().contains("Invalid terminal metrics message"),
|
||||
"unexpected error: {err}"
|
||||
);
|
||||
assert!(record_batch_stream.next().await.is_none());
|
||||
assert!(terminal_metrics.is_ready());
|
||||
|
||||
@@ -355,10 +355,15 @@ fn flight_stream_error(addr: &str, error: error::Error) -> error::Error {
|
||||
);
|
||||
}
|
||||
|
||||
error::Error::FlightGet {
|
||||
// The failure's own sentence travels with it: a region read crosses a process boundary, and
|
||||
// the message is the only thing that says what the region refused.
|
||||
let message = error.to_string();
|
||||
error::Error::FlightStream {
|
||||
addr: addr.to_string(),
|
||||
tonic_code,
|
||||
message,
|
||||
source: BoxedError::new(error),
|
||||
location: snafu::location!(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1205,7 +1210,7 @@ mod tests {
|
||||
|
||||
assert!(matches!(
|
||||
error,
|
||||
error::Error::FlightGet {
|
||||
error::Error::FlightStream {
|
||||
addr,
|
||||
tonic_code: tonic::Code::Unavailable,
|
||||
..
|
||||
@@ -1226,7 +1231,7 @@ mod tests {
|
||||
|
||||
assert!(matches!(
|
||||
error,
|
||||
error::Error::FlightGet {
|
||||
error::Error::FlightStream {
|
||||
addr,
|
||||
tonic_code: tonic::Code::Unknown,
|
||||
..
|
||||
@@ -1795,10 +1800,15 @@ mod tests {
|
||||
.unwrap();
|
||||
|
||||
let err = recordbatches.next().await.unwrap().unwrap_err();
|
||||
assert_eq!("External error", err.to_string());
|
||||
// The failure keeps its message: a client reading the error learns what went wrong, not
|
||||
// just that a stream failed.
|
||||
assert!(
|
||||
format!("{err:?}").contains("boom after metrics"),
|
||||
"unexpected error: {err:?}"
|
||||
err.to_string().starts_with("External error: "),
|
||||
"unexpected error: {err}"
|
||||
);
|
||||
assert!(
|
||||
err.to_string().contains("boom after metrics"),
|
||||
"unexpected error: {err}"
|
||||
);
|
||||
assert!(recordbatches.next().await.is_none());
|
||||
}
|
||||
|
||||
@@ -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,
|
||||
|
||||
+2
-1
@@ -77,7 +77,8 @@ impl Command {
|
||||
&TracingOptions::default(),
|
||||
None,
|
||||
None,
|
||||
);
|
||||
)
|
||||
.context(crate::error::InitLoggingSnafu)?;
|
||||
|
||||
let tool = self.cmd.build().await.context(error::BuildCliSnafu)?;
|
||||
let instance = Instance {
|
||||
|
||||
@@ -67,7 +67,8 @@ impl InstanceBuilder {
|
||||
&dn_opts.tracing,
|
||||
dn_opts.node_id.map(|x| x.to_string()),
|
||||
None,
|
||||
);
|
||||
)
|
||||
.context(crate::error::InitLoggingSnafu)?;
|
||||
|
||||
common_runtime::init_datanode_runtimes(&opts.runtime);
|
||||
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -47,7 +47,7 @@ use mito2::sst::file_ref::FileReferenceManager;
|
||||
use moka::future::CacheBuilder;
|
||||
use object_store::manager::ObjectStoreManager;
|
||||
use object_store::util::normalize_dir;
|
||||
use query::optimizer::parallelize_scan::ParallelizeScan;
|
||||
use query::optimizer::parallelize_scan::assign_partition_ranges;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use snafu::{OptionExt, ResultExt};
|
||||
use sqlparser::ast::ExprWithAlias as SqlExprWithAlias;
|
||||
@@ -995,8 +995,7 @@ impl ScanbenchCommand {
|
||||
let all_ranges: Vec<_> = original_partitions.into_iter().flatten().collect();
|
||||
|
||||
// Distribute ranges across partitions
|
||||
let mut partitions =
|
||||
ParallelizeScan::assign_partition_range(all_ranges, self.parallelism);
|
||||
let mut partitions = assign_partition_ranges(all_ranges, self.parallelism);
|
||||
|
||||
// Sort ranges within each partition by start time ascending
|
||||
for partition in &mut partitions {
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -23,6 +23,13 @@ use snafu::{Location, Snafu};
|
||||
#[snafu(visibility(pub))]
|
||||
#[stack_trace_debug]
|
||||
pub enum Error {
|
||||
#[snafu(display("Failed to initialize logging"))]
|
||||
InitLogging {
|
||||
#[snafu(implicit)]
|
||||
location: Location,
|
||||
source: common_telemetry::logging::InitLoggingError,
|
||||
},
|
||||
|
||||
#[snafu(display("Failed to install ring crypto provider: {}", msg))]
|
||||
InitTlsProvider {
|
||||
#[snafu(implicit)]
|
||||
@@ -85,6 +92,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)]
|
||||
@@ -330,9 +344,11 @@ pub type Result<T> = std::result::Result<T, Error>;
|
||||
impl ErrorExt for Error {
|
||||
fn status_code(&self) -> StatusCode {
|
||||
match self {
|
||||
Error::InitLogging { source, .. } => source.status_code(),
|
||||
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(),
|
||||
|
||||
@@ -251,7 +251,8 @@ impl StartCommand {
|
||||
&opts.component.tracing,
|
||||
opts.component.node_id.map(|x| x.to_string()),
|
||||
None,
|
||||
);
|
||||
)
|
||||
.context(crate::error::InitLoggingSnafu)?;
|
||||
|
||||
common_runtime::init_global_runtimes(&opts.runtime);
|
||||
|
||||
|
||||
@@ -384,7 +384,8 @@ impl StartCommand {
|
||||
&opts.component.tracing,
|
||||
opts.component.node_id.clone(),
|
||||
Some(&opts.component.slow_query),
|
||||
);
|
||||
)
|
||||
.context(crate::error::InitLoggingSnafu)?;
|
||||
|
||||
common_runtime::init_global_runtimes(&opts.runtime);
|
||||
|
||||
@@ -464,7 +465,9 @@ impl StartCommand {
|
||||
)
|
||||
.context(error::BuildCacheRegistrySnafu)?;
|
||||
|
||||
if let Some(plugin_cache_builder) = plugins::frontend::configure_cache_registry(&plugins) {
|
||||
if let Some(plugin_cache_builder) =
|
||||
plugins::frontend::configure_cache_registry(&plugins, cached_meta_backend.clone())
|
||||
{
|
||||
layered_cache_builder =
|
||||
layered_cache_builder.add_cache_registry(plugin_cache_builder.build());
|
||||
}
|
||||
|
||||
@@ -324,7 +324,8 @@ impl StartCommand {
|
||||
&opts.component.tracing,
|
||||
None,
|
||||
None,
|
||||
);
|
||||
)
|
||||
.context(crate::error::InitLoggingSnafu)?;
|
||||
|
||||
common_runtime::init_global_runtimes(&opts.runtime);
|
||||
|
||||
|
||||
+43
-14
@@ -39,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;
|
||||
@@ -54,7 +54,7 @@ use common_telemetry::{info, warn};
|
||||
use common_time::timezone::set_default_timezone;
|
||||
use common_version::{short_version, verbose_version};
|
||||
use common_wal::config::DatanodeWalConfig;
|
||||
use common_wal::config::object_store::STANDALONE_GENERATION;
|
||||
use common_wal::config::object_store::FIXED_DIRECTORY_GENERATION;
|
||||
use datanode::config::{DatanodeOptions, StorageConfig};
|
||||
use datanode::datanode::{Datanode, DatanodeBuilder};
|
||||
use datanode::region_server::RegionServer;
|
||||
@@ -98,7 +98,7 @@ pub async fn build_standalone_wal_provider(
|
||||
) -> Result<WalProvider> {
|
||||
match wal {
|
||||
DatanodeWalConfig::ObjectStore(config) => Ok(WalProvider::ObjectStore {
|
||||
prefix: config.node_prefix(node_id.unwrap_or(0), STANDALONE_GENERATION),
|
||||
prefix: config.node_prefix(node_id.unwrap_or(0), FIXED_DIRECTORY_GENERATION),
|
||||
}),
|
||||
DatanodeWalConfig::RaftEngine(_)
|
||||
| DatanodeWalConfig::Kafka(_)
|
||||
@@ -225,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>,
|
||||
}
|
||||
@@ -279,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);
|
||||
@@ -289,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(),
|
||||
@@ -305,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)
|
||||
@@ -488,7 +498,8 @@ impl StartCommand {
|
||||
&opts.component.tracing,
|
||||
None,
|
||||
Some(&opts.component.slow_query),
|
||||
);
|
||||
)
|
||||
.context(crate::error::InitLoggingSnafu)?;
|
||||
|
||||
common_runtime::init_standalone_runtimes(&opts.runtime);
|
||||
|
||||
@@ -543,10 +554,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);
|
||||
|
||||
@@ -790,6 +802,7 @@ impl StartCommand {
|
||||
procedure_manager,
|
||||
leader_services_controller: creator.leader_services_controller,
|
||||
leader_services_context,
|
||||
metadata_kv_backend,
|
||||
_guard: vec![],
|
||||
};
|
||||
let result = InstanceCreatorResult {
|
||||
@@ -848,15 +861,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)
|
||||
}
|
||||
}
|
||||
@@ -1161,6 +1184,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 +1205,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]
|
||||
@@ -1192,7 +1221,7 @@ mod tests {
|
||||
..Default::default()
|
||||
};
|
||||
// The regions persist the node prefix the datanode runs its store under.
|
||||
let node_prefix = config.node_prefix(0, STANDALONE_GENERATION);
|
||||
let node_prefix = config.node_prefix(0, FIXED_DIRECTORY_GENERATION);
|
||||
assert_eq!(node_prefix, "cluster-a/wal/datanodes/0/epochs/0");
|
||||
let provider = build_standalone_wal_provider(
|
||||
&DatanodeWalConfig::ObjectStore(config),
|
||||
|
||||
@@ -25,6 +25,7 @@ use common_options::datanode::{ClientOptions, DatanodeClientOptions};
|
||||
use common_runtime::global::RuntimeOptions;
|
||||
use common_telemetry::logging::{DEFAULT_LOGGING_DIR, DEFAULT_OTLP_HTTP_ENDPOINT, LoggingOptions};
|
||||
use common_test_util::temp_dir::create_named_temp_file;
|
||||
use common_time::timestamp::TimeUnit;
|
||||
use common_wal::config::DatanodeWalConfig;
|
||||
use common_wal::config::raft_engine::RaftEngineConfig;
|
||||
use datanode::config::{DatanodeOptions, RegionEngineConfig, StorageConfig};
|
||||
@@ -249,6 +250,7 @@ fn test_load_frontend_example_config() {
|
||||
default_timezone: Some("UTC".to_string()),
|
||||
default_column_prefix: Some("greptime".to_string()),
|
||||
auto_create_table: true,
|
||||
auto_create_physical_table_timestamp_unit: TimeUnit::Millisecond,
|
||||
meta_client: Some(MetaClientOptions {
|
||||
metasrv_addrs: vec!["127.0.0.1:3002".to_string()],
|
||||
timeout: Duration::from_secs(3),
|
||||
@@ -430,6 +432,7 @@ fn test_load_standalone_example_config() {
|
||||
default_timezone: Some("UTC".to_string()),
|
||||
default_column_prefix: Some("greptime".to_string()),
|
||||
auto_create_table: true,
|
||||
auto_create_physical_table_timestamp_unit: TimeUnit::Millisecond,
|
||||
wal: DatanodeWalConfig::RaftEngine(RaftEngineConfig {
|
||||
dir: Some(format!("{}/{}", DEFAULT_DATA_HOME, WAL_DIR)),
|
||||
sync_period: Some(Duration::from_secs(5)),
|
||||
@@ -622,6 +625,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",
|
||||
|
||||
@@ -104,6 +104,8 @@ where
|
||||
#[derive(Copy, Clone, Debug)]
|
||||
pub struct Cancelled;
|
||||
|
||||
impl std::error::Error for Cancelled {}
|
||||
|
||||
impl Display for Cancelled {
|
||||
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
|
||||
write!(f, "Future has been cancelled")
|
||||
|
||||
Vendored
+1
-1
@@ -12,7 +12,7 @@
|
||||
// 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;
|
||||
|
||||
@@ -53,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 }
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -27,6 +27,17 @@ 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,
|
||||
|
||||
@@ -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
@@ -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];
|
||||
|
||||
@@ -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),
|
||||
)))
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
@@ -90,7 +90,9 @@ impl Function for CurrentSchemaFunction {
|
||||
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),
|
||||
)))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -158,11 +160,15 @@ impl Function for CurrentSchemasFunction {
|
||||
&self,
|
||||
args: ScalarFunctionArgs,
|
||||
) -> datafusion_common::Result<ColumnarValue> {
|
||||
let func_ctx = find_function_context(&args)?;
|
||||
let schema = func_ctx.query_ctx.current_schema();
|
||||
let args = ColumnarValue::values_to_arrays(&args.args)?;
|
||||
let input = as_boolean_array(&args[0]);
|
||||
|
||||
// Create a UTF8 array with a single value
|
||||
let mut values = vec!["public"];
|
||||
let mut values = Vec::new();
|
||||
if !schema.is_empty() {
|
||||
values.push(schema.as_str());
|
||||
}
|
||||
// include implicit schemas
|
||||
if input.value(0) {
|
||||
values.push(INFORMATION_SCHEMA_NAME);
|
||||
|
||||
@@ -27,6 +27,10 @@ and durable DDL procedures. Metasrv process and service wiring live in
|
||||
invalidation.
|
||||
- Procedure changes must preserve persisted state and `TYPE_NAME`; new
|
||||
procedures need loader registration in `src/common/meta/src/ddl_manager.rs`.
|
||||
- Database drops persist bounded logical-table batches before deleting metadata.
|
||||
Replays must finish cache invalidation even after table-name keys are gone;
|
||||
physical-region removal follows the logical phase. Keep the legacy single-table
|
||||
executor readable for in-flight procedures from older versions.
|
||||
- Marker-style table options that no region consumes (`greptime.semantic.*`,
|
||||
`repartition.column.hint`) go through `AnnotationFamily` in
|
||||
`src/table/src/requests.rs` — classification, validation, logical-table
|
||||
|
||||
@@ -173,6 +173,10 @@ where
|
||||
let key = NodeAddressKey::with_flownode(*node_id);
|
||||
self.invalidate_key(&key.to_bytes()).await;
|
||||
}
|
||||
#[cfg(feature = "enterprise")]
|
||||
CacheIdent::TriggerId(_) => {
|
||||
// Trigger keys are owned by enterprise cache invalidators.
|
||||
}
|
||||
CacheIdent::User(_) => {
|
||||
// User cache invalidation is handled by external
|
||||
// CacheInvalidator implementations.
|
||||
|
||||
@@ -24,7 +24,7 @@ use common_procedure::{Context, EventContext, EventTrigger, LockKey, Procedure,
|
||||
use common_telemetry::{debug, error, info, warn};
|
||||
pub use executor::make_alter_region_request;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use snafu::{ResultExt, ensure};
|
||||
use snafu::ResultExt;
|
||||
use store_api::metadata::ColumnMetadata;
|
||||
use store_api::metric_engine_consts::ALTER_PHYSICAL_EXTENSION_KEY;
|
||||
use strum::AsRefStr;
|
||||
@@ -40,7 +40,7 @@ use crate::ddl::event::table::{
|
||||
TableDdlEvent, TableDdlEventType, TableDdlLocator, alter_table_kind_name,
|
||||
};
|
||||
use crate::ddl::utils::{extract_column_metadatas, map_to_procedure_error, sync_follower_regions};
|
||||
use crate::error::{self, Result};
|
||||
use crate::error::Result;
|
||||
use crate::instruction::CacheIdent;
|
||||
use crate::key::DeserializedValueWithBytes;
|
||||
use crate::key::table_info::TableInfoValue;
|
||||
@@ -67,7 +67,7 @@ fn build_validator_from_alter_table_data<'a>(
|
||||
.iter()
|
||||
.map(|task| &task.alter_table)
|
||||
.collect::<Vec<_>>();
|
||||
AlterLogicalTableValidator::new(physical_table_id, alters)
|
||||
AlterLogicalTableValidator::new(physical_table_id, alters, &data.logical_table_ids)
|
||||
}
|
||||
|
||||
/// Builds the executor from the [`AlterTablesData`].
|
||||
@@ -149,26 +149,6 @@ impl AlterLogicalTablesProcedure {
|
||||
);
|
||||
}
|
||||
|
||||
// Locks are fixed at submission. A logical table that resolves to an
|
||||
// id outside the locked set here was dropped and recreated in between,
|
||||
// so this procedure holds no lock for it. Procedures restored from
|
||||
// pre-upgrade state have no recorded ids and keep the old behavior.
|
||||
if !self.data.logical_table_ids.is_empty() {
|
||||
for value in &table_info_values {
|
||||
let table_id = value.get_inner_ref().table_info.ident.table_id;
|
||||
ensure!(
|
||||
self.data.logical_table_ids.contains(&table_id),
|
||||
error::UnexpectedSnafu {
|
||||
err_msg: format!(
|
||||
"logical table {} (id {table_id}) is not covered by the \
|
||||
procedure locks; retry the statement",
|
||||
value.get_inner_ref().table_info.name
|
||||
),
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Updates the procedure state.
|
||||
retain_unskipped(&mut self.data.tasks, &skip_alter);
|
||||
self.data.physical_table_info = Some(physical_table_info);
|
||||
|
||||
@@ -26,7 +26,7 @@ use crate::ddl::utils::table_info::{
|
||||
};
|
||||
use crate::error::{
|
||||
AlterLogicalTablesInvalidArgumentsSnafu, Result, TableInfoNotFoundSnafu,
|
||||
TableRouteNotFoundSnafu,
|
||||
TableRouteNotFoundSnafu, UnexpectedSnafu,
|
||||
};
|
||||
use crate::key::table_info::TableInfoValue;
|
||||
use crate::key::table_route::{PhysicalTableRouteValue, TableRouteManager, TableRouteValue};
|
||||
@@ -36,13 +36,19 @@ use crate::key::{DeserializedValueWithBytes, TableMetadataManagerRef};
|
||||
pub struct AlterLogicalTableValidator<'a> {
|
||||
physical_table_id: TableId,
|
||||
alters: Vec<&'a AlterTableExpr>,
|
||||
expected_table_ids: &'a [TableId],
|
||||
}
|
||||
|
||||
impl<'a> AlterLogicalTableValidator<'a> {
|
||||
pub fn new(physical_table_id: TableId, alters: Vec<&'a AlterTableExpr>) -> Self {
|
||||
pub fn new(
|
||||
physical_table_id: TableId,
|
||||
alters: Vec<&'a AlterTableExpr>,
|
||||
expected_table_ids: &'a [TableId],
|
||||
) -> Self {
|
||||
Self {
|
||||
physical_table_id,
|
||||
alters,
|
||||
expected_table_ids,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -187,6 +193,14 @@ impl<'a> AlterLogicalTableValidator<'a> {
|
||||
let table_ids =
|
||||
get_all_table_ids_by_names(table_metadata_manager.table_name_manager(), &table_names)
|
||||
.await?;
|
||||
// Check before skipping completed ALTERs, while the procedure holds the pinned ID locks.
|
||||
// Old persisted procedures have no pinned IDs and retain their previous behavior.
|
||||
ensure!(
|
||||
self.expected_table_ids.is_empty() || self.expected_table_ids == table_ids,
|
||||
UnexpectedSnafu {
|
||||
err_msg: "logical tables changed and are not covered by the procedure locks; retry the statement",
|
||||
}
|
||||
);
|
||||
let mut table_info_values = get_all_table_info_values_by_table_ids(
|
||||
table_metadata_manager.table_info_manager(),
|
||||
&table_ids,
|
||||
|
||||
@@ -97,7 +97,7 @@ impl CreateLogicalTablesProcedure {
|
||||
self.check_input_tasks()?;
|
||||
// Sets physical region numbers
|
||||
self.fill_physical_table_info().await?;
|
||||
// Add partition columns from physical table to logical table schemas
|
||||
// Add the physical table's user partition columns to logical table schemas.
|
||||
self.merge_partition_columns_into_logical_tables()?;
|
||||
// Checks if the tables exist
|
||||
self.check_tables_already_exist().await?;
|
||||
@@ -325,6 +325,10 @@ pub struct CreateTablesData {
|
||||
physical_table_id: TableId,
|
||||
physical_region_numbers: Vec<RegionNumber>,
|
||||
physical_columns: Vec<ColumnMetadata>,
|
||||
/// Partition column names of the physical table.
|
||||
///
|
||||
/// Procedures persisted before engine identity columns were filtered may store them
|
||||
/// here, so the merge re-checks the names instead of trusting this list.
|
||||
physical_partition_columns: Vec<String>,
|
||||
}
|
||||
|
||||
|
||||
@@ -18,6 +18,7 @@ use std::sync::Arc;
|
||||
use datatypes::prelude::ConcreteDataType;
|
||||
use datatypes::schema::{ColumnSchema, Schema};
|
||||
use snafu::OptionExt;
|
||||
use store_api::metric_engine_consts::is_metric_engine_internal_column;
|
||||
|
||||
use crate::ddl::create_logical_tables::CreateLogicalTablesProcedure;
|
||||
use crate::error::Result;
|
||||
@@ -82,6 +83,14 @@ impl CreateLogicalTablesProcedure {
|
||||
|
||||
// Add missing partition columns
|
||||
for partition_column in partition_columns {
|
||||
// The engine owns its identity columns: they are derived from the logical
|
||||
// table at write time, so a logical schema must never declare them. Older
|
||||
// procedures may have persisted an unfiltered partition column list, hence
|
||||
// filtering here rather than only while collecting it.
|
||||
if is_metric_engine_internal_column(partition_column) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if !existing_column_names.contains(partition_column) {
|
||||
let new_column_index = column_schemas.len() + new_columns.len();
|
||||
|
||||
|
||||
@@ -26,7 +26,7 @@ use common_procedure::{
|
||||
Context as ProcedureContext, EventContext, EventTrigger, LockKey, Procedure,
|
||||
Result as ProcedureResult, Status,
|
||||
};
|
||||
use futures::stream::BoxStream;
|
||||
use futures::stream::{BoxStream, Peekable};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use snafu::ResultExt;
|
||||
use tonic::async_trait;
|
||||
@@ -54,12 +54,14 @@ pub(crate) enum DropTableTarget {
|
||||
Physical,
|
||||
}
|
||||
|
||||
type TableStream = Peekable<BoxStream<'static, Result<(String, TableNameValue)>>>;
|
||||
|
||||
/// Context of [DropDatabaseProcedure] execution.
|
||||
pub(crate) struct DropDatabaseContext {
|
||||
catalog: String,
|
||||
schema: String,
|
||||
drop_if_exists: bool,
|
||||
tables: Option<BoxStream<'static, Result<(String, TableNameValue)>>>,
|
||||
tables: Option<TableStream>,
|
||||
retrying: bool,
|
||||
}
|
||||
|
||||
|
||||
@@ -13,21 +13,24 @@
|
||||
// limitations under the License.
|
||||
|
||||
use std::any::Any;
|
||||
use std::collections::HashSet;
|
||||
use std::pin::Pin;
|
||||
|
||||
use common_base::readable_size::ReadableSize;
|
||||
use common_catalog::format_full_table_name;
|
||||
use common_procedure::Status;
|
||||
use futures::TryStreamExt;
|
||||
use futures::{StreamExt, TryStreamExt};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use snafu::OptionExt;
|
||||
use snafu::{OptionExt, ensure};
|
||||
use table::metadata::{TableId, TableType};
|
||||
use table::table_name::TableName;
|
||||
|
||||
use crate::cache_invalidator::Context;
|
||||
use crate::ddl::DdlContext;
|
||||
use crate::ddl::drop_database::executor::DropDatabaseExecutor;
|
||||
use crate::ddl::drop_database::executor::{DropDatabaseBatchExecutor, DropDatabaseExecutor};
|
||||
use crate::ddl::drop_database::metadata::DropDatabaseRemoveMetadata;
|
||||
use crate::ddl::drop_database::{DropDatabaseContext, DropTableTarget, State};
|
||||
use crate::error::{Result, TableInfoNotFoundSnafu};
|
||||
use crate::error::{Result, TableInfoNotFoundSnafu, UnexpectedSnafu};
|
||||
use crate::instruction::CacheIdent;
|
||||
use crate::key::table_route::TableRouteValue;
|
||||
|
||||
@@ -42,6 +45,123 @@ impl DropDatabaseCursor {
|
||||
Self { target }
|
||||
}
|
||||
|
||||
/// Collects a bounded page without mutating metadata. Only the executor's batch is durable.
|
||||
async fn collect_logical_tables(
|
||||
&mut self,
|
||||
ddl_ctx: &DdlContext,
|
||||
ctx: &mut DropDatabaseContext,
|
||||
) -> Result<(Box<dyn State>, Status)> {
|
||||
let page = Self::collect_page(ctx).await?;
|
||||
if page.is_empty() {
|
||||
return self.handle_reach_end(ctx);
|
||||
}
|
||||
let tables = Self::logical_tables(ddl_ctx, ctx, page).await?;
|
||||
if tables.is_empty() {
|
||||
return Ok((Box::new(Self::new(self.target)), Status::executing(false)));
|
||||
}
|
||||
Ok((
|
||||
Box::new(DropDatabaseBatchExecutor { tables }),
|
||||
Status::executing(true),
|
||||
))
|
||||
}
|
||||
|
||||
// Leave headroom below etcd's default 1.5 MiB request limit.
|
||||
const MAX_BATCH_BYTES: usize = ReadableSize::mb(1).as_bytes() as usize;
|
||||
|
||||
fn estimated_table_bytes(catalog: &str, schema: &str, name: &str) -> usize {
|
||||
// A control byte can expand to 6 JSON bytes, then 7 inside ProcedureMessage's
|
||||
// JSON string. Round up to 8x and allow 128 bytes for fixed per-table JSON/key overhead.
|
||||
128 + 8 * (catalog.len() + schema.len() + name.len())
|
||||
}
|
||||
|
||||
async fn collect_page(ctx: &mut DropDatabaseContext) -> Result<Vec<(String, TableId)>> {
|
||||
let mut page = Vec::new();
|
||||
let mut bytes: usize = 0;
|
||||
let tables = ctx.tables.as_mut().unwrap();
|
||||
loop {
|
||||
match Pin::new(&mut *tables).peek().await {
|
||||
Some(Ok((name, _))) => {
|
||||
let size = Self::estimated_table_bytes(&ctx.catalog, &ctx.schema, name);
|
||||
if !page.is_empty() && bytes.saturating_add(size) > Self::MAX_BATCH_BYTES {
|
||||
break;
|
||||
}
|
||||
// A single oversized name must still make progress. Procedure storage
|
||||
// already splits oversized values; never strand an existing table here.
|
||||
bytes = bytes.saturating_add(size);
|
||||
}
|
||||
Some(Err(_)) => {} // Consume below to propagate the owned error.
|
||||
None => break,
|
||||
}
|
||||
let (name, value) = tables.try_next().await?.unwrap();
|
||||
page.push((name, value.table_id()));
|
||||
}
|
||||
Ok(page)
|
||||
}
|
||||
|
||||
async fn logical_tables(
|
||||
ddl_ctx: &DdlContext,
|
||||
ctx: &mut DropDatabaseContext,
|
||||
page: Vec<(String, TableId)>,
|
||||
) -> Result<Vec<(TableId, TableName)>> {
|
||||
let manager = &ddl_ctx.table_metadata_manager;
|
||||
let ids = page.iter().map(|(_, id)| *id).collect::<Vec<_>>();
|
||||
let infos = manager.table_info_manager().batch_get(&ids).await?;
|
||||
let routes = manager
|
||||
.table_route_manager()
|
||||
.table_route_storage()
|
||||
.batch_get(&ids)
|
||||
.await?;
|
||||
let physical_ids = routes
|
||||
.iter()
|
||||
.filter_map(|route| match route {
|
||||
Some(TableRouteValue::Logical(route)) => Some(route.physical_table_id()),
|
||||
_ => None,
|
||||
})
|
||||
.collect::<HashSet<_>>()
|
||||
.into_iter()
|
||||
.collect::<Vec<_>>();
|
||||
let physical_infos = manager
|
||||
.table_info_manager()
|
||||
.batch_get(&physical_ids)
|
||||
.await?;
|
||||
let mut tables = Vec::new();
|
||||
for ((name, id), route) in page.into_iter().zip(routes) {
|
||||
let info = infos.get(&id).with_context(|| TableInfoNotFoundSnafu {
|
||||
table: format_full_table_name(&ctx.catalog, &ctx.schema, &name),
|
||||
})?;
|
||||
if info.table_info.table_type == TableType::View {
|
||||
// Views are handled in the physical phase so collecting a batch has no side effects.
|
||||
continue;
|
||||
}
|
||||
if let Some(TableRouteValue::Logical(route)) = route {
|
||||
let physical = physical_infos
|
||||
.get(&route.physical_table_id())
|
||||
.with_context(|| TableInfoNotFoundSnafu {
|
||||
table: route.physical_table_id().to_string(),
|
||||
})?;
|
||||
// Metadata-only deletion is safe only when the backing table is dropped with us.
|
||||
ensure!(
|
||||
physical.table_info.catalog_name == ctx.catalog
|
||||
&& physical.table_info.schema_name == ctx.schema,
|
||||
UnexpectedSnafu {
|
||||
err_msg: format!(
|
||||
"Logical table {} references physical table {} (id {}) outside the dropped database",
|
||||
format_full_table_name(&ctx.catalog, &ctx.schema, &name),
|
||||
format_full_table_name(
|
||||
&physical.table_info.catalog_name,
|
||||
&physical.table_info.schema_name,
|
||||
&physical.table_info.name,
|
||||
),
|
||||
route.physical_table_id(),
|
||||
),
|
||||
}
|
||||
);
|
||||
tables.push((id, TableName::new(&ctx.catalog, &ctx.schema, name)));
|
||||
}
|
||||
}
|
||||
Ok(tables)
|
||||
}
|
||||
|
||||
fn handle_reach_end(
|
||||
&mut self,
|
||||
ctx: &mut DropDatabaseContext,
|
||||
@@ -62,32 +182,12 @@ impl DropDatabaseCursor {
|
||||
|
||||
async fn handle_table(
|
||||
&mut self,
|
||||
ddl_ctx: &DdlContext,
|
||||
ctx: &mut DropDatabaseContext,
|
||||
table_name: String,
|
||||
table_id: TableId,
|
||||
table_route_value: TableRouteValue,
|
||||
) -> Result<(Box<dyn State>, Status)> {
|
||||
match (self.target, table_route_value) {
|
||||
(DropTableTarget::Logical, TableRouteValue::Logical(route)) => {
|
||||
let physical_table_id = route.physical_table_id();
|
||||
|
||||
let (_, table_route) = ddl_ctx
|
||||
.table_metadata_manager
|
||||
.table_route_manager()
|
||||
.get_physical_table_route(physical_table_id)
|
||||
.await?;
|
||||
Ok((
|
||||
Box::new(DropDatabaseExecutor::new(
|
||||
table_id,
|
||||
table_id,
|
||||
TableName::new(&ctx.catalog, &ctx.schema, &table_name),
|
||||
table_route.region_routes,
|
||||
self.target,
|
||||
)),
|
||||
Status::executing(true),
|
||||
))
|
||||
}
|
||||
(DropTableTarget::Physical, TableRouteValue::Physical(table_route)) => Ok((
|
||||
Box::new(DropDatabaseExecutor::new(
|
||||
table_id,
|
||||
@@ -104,7 +204,6 @@ impl DropDatabaseCursor {
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
async fn handle_view(
|
||||
&self,
|
||||
ddl_ctx: &DdlContext,
|
||||
@@ -148,50 +247,61 @@ impl State for DropDatabaseCursor {
|
||||
ddl_ctx: &DdlContext,
|
||||
ctx: &mut DropDatabaseContext,
|
||||
) -> Result<(Box<dyn State>, Status)> {
|
||||
if ctx.tables.as_deref().is_none() {
|
||||
if ctx.tables.is_none() {
|
||||
let tables = ddl_ctx
|
||||
.table_metadata_manager
|
||||
.table_name_manager()
|
||||
.tables(&ctx.catalog, &ctx.schema);
|
||||
ctx.tables = Some(tables);
|
||||
ctx.tables = Some(tables.peekable());
|
||||
}
|
||||
// Safety: must exist
|
||||
match ctx.tables.as_mut().unwrap().try_next().await? {
|
||||
Some((table_name, table_name_value)) => {
|
||||
let table_id = table_name_value.table_id();
|
||||
let result = async {
|
||||
if self.target == DropTableTarget::Logical {
|
||||
return self.collect_logical_tables(ddl_ctx, ctx).await;
|
||||
}
|
||||
// Safety: must exist
|
||||
match ctx.tables.as_mut().unwrap().try_next().await? {
|
||||
Some((table_name, table_name_value)) => {
|
||||
let table_id = table_name_value.table_id();
|
||||
|
||||
let table_info_value = ddl_ctx
|
||||
.table_metadata_manager
|
||||
.table_info_manager()
|
||||
.get(table_id)
|
||||
.await?
|
||||
.with_context(|| TableInfoNotFoundSnafu {
|
||||
table: format_full_table_name(&ctx.catalog, &ctx.schema, &table_name),
|
||||
})?;
|
||||
let table_info_value = ddl_ctx
|
||||
.table_metadata_manager
|
||||
.table_info_manager()
|
||||
.get(table_id)
|
||||
.await?
|
||||
.with_context(|| TableInfoNotFoundSnafu {
|
||||
table: format_full_table_name(&ctx.catalog, &ctx.schema, &table_name),
|
||||
})?;
|
||||
|
||||
if table_info_value.table_info.table_type == TableType::View {
|
||||
return self.handle_view(ddl_ctx, ctx, table_name, table_id).await;
|
||||
}
|
||||
if table_info_value.table_info.table_type == TableType::View {
|
||||
return self.handle_view(ddl_ctx, ctx, table_name, table_id).await;
|
||||
}
|
||||
|
||||
match ddl_ctx
|
||||
.table_metadata_manager
|
||||
.table_route_manager()
|
||||
.table_route_storage()
|
||||
.get(table_id)
|
||||
.await?
|
||||
{
|
||||
Some(table_route_value) => {
|
||||
self.handle_table(ddl_ctx, ctx, table_name, table_id, table_route_value)
|
||||
.await
|
||||
match ddl_ctx
|
||||
.table_metadata_manager
|
||||
.table_route_manager()
|
||||
.table_route_storage()
|
||||
.get(table_id)
|
||||
.await?
|
||||
{
|
||||
Some(table_route_value) => {
|
||||
self.handle_table(ctx, table_name, table_id, table_route_value)
|
||||
.await
|
||||
}
|
||||
None => Ok((
|
||||
Box::new(DropDatabaseCursor::new(self.target)),
|
||||
Status::executing(false),
|
||||
)),
|
||||
}
|
||||
None => Ok((
|
||||
Box::new(DropDatabaseCursor::new(self.target)),
|
||||
Status::executing(false),
|
||||
)),
|
||||
}
|
||||
None => self.handle_reach_end(ctx),
|
||||
}
|
||||
None => self.handle_reach_end(ctx),
|
||||
}
|
||||
.await;
|
||||
if result.is_err() {
|
||||
// The entry was consumed but no deletion plan was persisted. Rescan on retry.
|
||||
ctx.tables.take();
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
fn as_any(&self) -> &dyn Any {
|
||||
@@ -206,12 +316,163 @@ mod tests {
|
||||
use common_catalog::consts::{DEFAULT_CATALOG_NAME, DEFAULT_SCHEMA_NAME};
|
||||
|
||||
use crate::ddl::drop_database::cursor::DropDatabaseCursor;
|
||||
use crate::ddl::drop_database::executor::DropDatabaseExecutor;
|
||||
use crate::ddl::drop_database::executor::{DropDatabaseBatchExecutor, DropDatabaseExecutor};
|
||||
use crate::ddl::drop_database::metadata::DropDatabaseRemoveMetadata;
|
||||
use crate::ddl::drop_database::{DropDatabaseContext, DropTableTarget, State};
|
||||
use crate::ddl::test_util::{create_logical_table, create_physical_table};
|
||||
use crate::test_util::{MockDatanodeManager, new_ddl_context};
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_cursor_read_failure_rescans() {
|
||||
use crate::key::table_name::TableNameValue;
|
||||
use futures::StreamExt;
|
||||
for target in [DropTableTarget::Logical, DropTableTarget::Physical] {
|
||||
let ddl = new_ddl_context(Arc::new(MockDatanodeManager::new(())));
|
||||
let physical = create_physical_table(&ddl, "physical").await;
|
||||
let mut ctx = DropDatabaseContext {
|
||||
catalog: DEFAULT_CATALOG_NAME.into(),
|
||||
schema: DEFAULT_SCHEMA_NAME.into(),
|
||||
drop_if_exists: false,
|
||||
retrying: false,
|
||||
tables: Some(
|
||||
futures::stream::iter(vec![Ok(("missing".into(), TableNameValue::new(99999)))])
|
||||
.boxed()
|
||||
.peekable(),
|
||||
),
|
||||
};
|
||||
let mut cursor = DropDatabaseCursor::new(target);
|
||||
assert!(cursor.next(&ddl, &mut ctx).await.is_err());
|
||||
assert!(ctx.tables.is_none());
|
||||
let (state, _) = cursor.next(&ddl, &mut ctx).await.unwrap();
|
||||
if target == DropTableTarget::Physical {
|
||||
assert!(state.as_any().is::<DropDatabaseExecutor>());
|
||||
} else {
|
||||
assert!(state.as_any().is::<DropDatabaseCursor>());
|
||||
}
|
||||
assert!(
|
||||
ddl.table_metadata_manager
|
||||
.table_info_manager()
|
||||
.get(physical)
|
||||
.await
|
||||
.unwrap()
|
||||
.is_some()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_collect_page_oversized_singleton_makes_progress() {
|
||||
use crate::key::table_name::TableNameValue;
|
||||
use futures::StreamExt;
|
||||
let mut ctx = DropDatabaseContext {
|
||||
catalog: DEFAULT_CATALOG_NAME.into(),
|
||||
schema: DEFAULT_SCHEMA_NAME.into(),
|
||||
drop_if_exists: false,
|
||||
retrying: false,
|
||||
tables: Some(
|
||||
futures::stream::iter(vec![
|
||||
Ok((
|
||||
"x".repeat(DropDatabaseCursor::MAX_BATCH_BYTES),
|
||||
TableNameValue::new(1),
|
||||
)),
|
||||
Ok(("small".into(), TableNameValue::new(2))),
|
||||
])
|
||||
.boxed()
|
||||
.peekable(),
|
||||
),
|
||||
};
|
||||
let page = DropDatabaseCursor::collect_page(&mut ctx).await.unwrap();
|
||||
assert_eq!(page.len(), 1);
|
||||
assert_eq!(page[0].1, 1);
|
||||
assert_eq!(
|
||||
DropDatabaseCursor::collect_page(&mut ctx).await.unwrap(),
|
||||
vec![("small".into(), 2)]
|
||||
);
|
||||
assert!(
|
||||
DropDatabaseCursor::collect_page(&mut ctx)
|
||||
.await
|
||||
.unwrap()
|
||||
.is_empty()
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_collect_page_limits_and_request_headroom() {
|
||||
use common_procedure::store::ProcedureMessage;
|
||||
use futures::StreamExt;
|
||||
use table::table_name::TableName;
|
||||
|
||||
use crate::ddl::drop_database::DropDatabaseProcedure;
|
||||
use crate::key::TableMetadataManager;
|
||||
use crate::key::table_name::TableNameValue;
|
||||
for name in [
|
||||
"short".to_string(),
|
||||
"x".repeat(64 * 1024),
|
||||
"\"\\\n\u{0001}中文".repeat(4096),
|
||||
] {
|
||||
let ddl = new_ddl_context(Arc::new(MockDatanodeManager::new(())));
|
||||
let count = if name.len() < 1024 { 5000 } else { 65 };
|
||||
let entries = (0..count)
|
||||
.map(|id| Ok((name.clone(), TableNameValue::new(id))))
|
||||
.collect::<Vec<_>>();
|
||||
let mut ctx = DropDatabaseContext {
|
||||
catalog: DEFAULT_CATALOG_NAME.into(),
|
||||
schema: DEFAULT_SCHEMA_NAME.into(),
|
||||
drop_if_exists: false,
|
||||
tables: Some(futures::stream::iter(entries).boxed().peekable()),
|
||||
retrying: false,
|
||||
};
|
||||
let mut collected = Vec::new();
|
||||
loop {
|
||||
let page = DropDatabaseCursor::collect_page(&mut ctx).await.unwrap();
|
||||
if page.is_empty() {
|
||||
break;
|
||||
}
|
||||
let estimated = page
|
||||
.iter()
|
||||
.map(|(name, _)| {
|
||||
DropDatabaseCursor::estimated_table_bytes(&ctx.catalog, &ctx.schema, name)
|
||||
})
|
||||
.sum::<usize>();
|
||||
assert!(estimated <= DropDatabaseCursor::MAX_BATCH_BYTES);
|
||||
let tables = page
|
||||
.iter()
|
||||
.map(|(name, id)| (*id, TableName::new(&ctx.catalog, &ctx.schema, name)))
|
||||
.collect::<Vec<_>>();
|
||||
// Each delete has one bytes field nested in two messages. Allow
|
||||
// 32 bytes per key for tags and length varints, plus a txn envelope.
|
||||
let delete_bytes = 64
|
||||
+ tables
|
||||
.iter()
|
||||
.flat_map(|(id, name)| TableMetadataManager::table_identity_keys(*id, name))
|
||||
.map(|key| key.len() + 32)
|
||||
.sum::<usize>();
|
||||
assert!(delete_bytes <= estimated);
|
||||
let mut procedure = DropDatabaseProcedure::new(
|
||||
ctx.catalog.clone(),
|
||||
ctx.schema.clone(),
|
||||
false,
|
||||
ddl.clone(),
|
||||
);
|
||||
procedure.state = Box::new(DropDatabaseBatchExecutor { tables });
|
||||
let message = ProcedureMessage {
|
||||
type_name: DropDatabaseProcedure::TYPE_NAME.into(),
|
||||
data: common_procedure::Procedure::dump(&procedure).unwrap(),
|
||||
parent_id: None,
|
||||
subprocedure_recovery: common_procedure::SubprocedureRecovery::Discard,
|
||||
step: u32::MAX,
|
||||
error: None,
|
||||
context: Default::default(),
|
||||
};
|
||||
let serialized = serde_json::to_vec(&message).unwrap();
|
||||
assert!(serialized.len() <= estimated);
|
||||
assert!(serialized.len() + 512 * 1024 < 1536 * 1024);
|
||||
collected.extend(page.into_iter().map(|(_, id)| id));
|
||||
}
|
||||
assert_eq!(collected, (0..count).collect::<Vec<_>>());
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_next_without_logical_tables() {
|
||||
let node_manager = Arc::new(MockDatanodeManager::new(()));
|
||||
@@ -267,16 +528,10 @@ mod tests {
|
||||
assert!(status.need_persist());
|
||||
let executor = state
|
||||
.as_any()
|
||||
.downcast_ref::<DropDatabaseExecutor>()
|
||||
.downcast_ref::<DropDatabaseBatchExecutor>()
|
||||
.unwrap();
|
||||
let (_, table_route) = ddl_context
|
||||
.table_metadata_manager
|
||||
.table_route_manager()
|
||||
.get_physical_table_route(physical_table_id)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(table_route.region_routes, executor.physical_region_routes);
|
||||
assert_eq!(executor.target, DropTableTarget::Logical);
|
||||
assert_eq!(executor.tables.len(), 1);
|
||||
assert_eq!(executor.tables[0].1.table_name, "metric_0");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
|
||||
@@ -21,12 +21,14 @@ use snafu::OptionExt;
|
||||
use table::metadata::TableId;
|
||||
use table::table_name::TableName;
|
||||
|
||||
use crate::cache_invalidator::Context;
|
||||
use crate::ddl::DdlContext;
|
||||
use crate::ddl::drop_database::cursor::DropDatabaseCursor;
|
||||
use crate::ddl::drop_database::{DropDatabaseContext, DropTableTarget, State};
|
||||
use crate::ddl::drop_table::executor::DropTableExecutor;
|
||||
use crate::ddl::utils::get_region_wal_options;
|
||||
use crate::error::{self, Result};
|
||||
use crate::instruction::CacheIdent;
|
||||
use crate::key::table_route::TableRouteValue;
|
||||
use crate::region_keeper::OperatingRegionGuard;
|
||||
use crate::rpc::router::{RegionRoute, operating_leader_region_roles};
|
||||
@@ -140,7 +142,7 @@ impl State for DropDatabaseExecutor {
|
||||
&ddl_ctx.leader_region_registry,
|
||||
&self.physical_region_routes,
|
||||
true,
|
||||
false,
|
||||
self.target == DropTableTarget::Physical,
|
||||
false,
|
||||
)
|
||||
.await?;
|
||||
@@ -157,6 +159,54 @@ impl State for DropDatabaseExecutor {
|
||||
}
|
||||
}
|
||||
|
||||
/// A durable logical-table deletion batch. Physical regions are removed in the next phase.
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub(crate) struct DropDatabaseBatchExecutor {
|
||||
pub(crate) tables: Vec<(TableId, TableName)>,
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
#[typetag::serde]
|
||||
impl State for DropDatabaseBatchExecutor {
|
||||
async fn next(
|
||||
&mut self,
|
||||
ddl_ctx: &DdlContext,
|
||||
_ctx: &mut DropDatabaseContext,
|
||||
) -> Result<(Box<dyn State>, Status)> {
|
||||
ddl_ctx
|
||||
.table_metadata_manager
|
||||
.destroy_logical_tables_metadata(&self.tables)
|
||||
.await?;
|
||||
let idents = self
|
||||
.tables
|
||||
.iter()
|
||||
.flat_map(|(id, name)| {
|
||||
[
|
||||
CacheIdent::TableId(*id),
|
||||
CacheIdent::TableName(name.clone()),
|
||||
]
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
ddl_ctx
|
||||
.cache_invalidator
|
||||
.invalidate(
|
||||
&Context {
|
||||
subject: Some("Invalidate logical tables by dropping database".to_string()),
|
||||
},
|
||||
&idents,
|
||||
)
|
||||
.await?;
|
||||
Ok((
|
||||
Box::new(DropDatabaseCursor::new(DropTableTarget::Logical)),
|
||||
Status::executing(false),
|
||||
))
|
||||
}
|
||||
|
||||
fn as_any(&self) -> &dyn Any {
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::collections::HashSet;
|
||||
@@ -448,10 +498,13 @@ mod tests {
|
||||
|
||||
state.recover(&ddl_context).unwrap();
|
||||
|
||||
let roles = ddl_context
|
||||
let operating_regions = ddl_context
|
||||
.memory_region_keeper
|
||||
.extract_operating_region_roles(7, &HashSet::from([region_id]));
|
||||
assert_eq!(roles.get(®ion_id), Some(&RegionRole::DowngradingLeader));
|
||||
.extract_operating_regions(7, &HashSet::from([region_id]));
|
||||
assert_eq!(
|
||||
operating_regions.get(®ion_id).map(|region| region.role),
|
||||
Some(RegionRole::DowngradingLeader)
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
|
||||
@@ -713,21 +713,27 @@ async fn test_on_prepare_rejects_table_outside_locked_set() {
|
||||
let phy_id = create_physical_table(&ddl_context, "phy").await;
|
||||
create_logical_table(ddl_context.clone(), phy_id, "table1").await;
|
||||
|
||||
let tasks = vec![make_alter_logical_table_add_column_task(
|
||||
None,
|
||||
"table1",
|
||||
vec!["column1".to_string()],
|
||||
)];
|
||||
|
||||
// The table resolved at prepare time is not in the locked set, as if it
|
||||
// had been dropped and recreated after submission.
|
||||
let stale_locked_id = phy_id + 1000;
|
||||
let mut procedure =
|
||||
AlterLogicalTablesProcedure::new(tasks, phy_id, vec![stale_locked_id], ddl_context);
|
||||
let err = procedure.on_prepare().await.unwrap_err();
|
||||
assert!(
|
||||
err.to_string()
|
||||
.contains("not covered by the procedure locks"),
|
||||
"{err}"
|
||||
);
|
||||
// A completed ADD must also reject rebinding, even when no schema changes are needed.
|
||||
for column in ["column1", "host"] {
|
||||
let tasks = vec![make_alter_logical_table_add_column_task(
|
||||
None,
|
||||
"table1",
|
||||
vec![column.into()],
|
||||
)];
|
||||
let mut procedure = AlterLogicalTablesProcedure::new(
|
||||
tasks,
|
||||
phy_id,
|
||||
vec![stale_locked_id],
|
||||
ddl_context.clone(),
|
||||
);
|
||||
let err = procedure.on_prepare().await.unwrap_err();
|
||||
assert!(
|
||||
err.to_string()
|
||||
.contains("not covered by the procedure locks"),
|
||||
"{err}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -23,11 +23,17 @@ use common_error::ext::ErrorExt;
|
||||
use common_error::status_code::StatusCode;
|
||||
use common_procedure::{Context as ProcedureContext, Procedure, ProcedureId, Status};
|
||||
use common_procedure_test::MockContextProvider;
|
||||
use datatypes::prelude::ConcreteDataType;
|
||||
use datatypes::schema::{ColumnSchema, Schema};
|
||||
use store_api::metadata::ColumnMetadata;
|
||||
use store_api::metric_engine_consts::{ALTER_PHYSICAL_EXTENSION_KEY, MANIFEST_INFO_EXTENSION_KEY};
|
||||
use store_api::metric_engine_consts::{
|
||||
ALTER_PHYSICAL_EXTENSION_KEY, DATA_SCHEMA_TABLE_ID_COLUMN_NAME, MANIFEST_INFO_EXTENSION_KEY,
|
||||
is_metric_engine_internal_column,
|
||||
};
|
||||
use store_api::region_engine::RegionManifestInfo;
|
||||
use store_api::storage::RegionId;
|
||||
use store_api::storage::consts::ReservedColumnId;
|
||||
use table::metadata::TableInfo;
|
||||
use tokio::sync::mpsc;
|
||||
|
||||
use crate::ddl::TableMetadata;
|
||||
@@ -566,3 +572,136 @@ async fn test_on_submit_create_request() {
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
/// Appends a column to the table schema and returns its index.
|
||||
fn push_column(
|
||||
table_info: &mut TableInfo,
|
||||
name: &str,
|
||||
data_type: ConcreteDataType,
|
||||
is_nullable: bool,
|
||||
) -> usize {
|
||||
let mut columns = table_info.meta.schema.column_schemas().to_vec();
|
||||
columns.push(ColumnSchema::new(name, data_type, is_nullable));
|
||||
table_info.meta.schema = Arc::new(Schema::new(columns));
|
||||
table_info.meta.schema.column_schemas().len() - 1
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_on_prepare_skips_internal_partition_columns() {
|
||||
let (tx, mut rx) = mpsc::channel(8);
|
||||
let node_manager = Arc::new(MockDatanodeManager::new(DatanodeWatcher::new(tx)));
|
||||
let ddl_context = new_ddl_context(node_manager);
|
||||
|
||||
// The physical table owns the engine identity column and has been repartitioned by
|
||||
// both it and a user tag that no logical table declares.
|
||||
let mut create_physical_table_task = test_create_physical_table_task("phy_table");
|
||||
let table_id_column_index = push_column(
|
||||
&mut create_physical_table_task.table_info,
|
||||
DATA_SCHEMA_TABLE_ID_COLUMN_NAME,
|
||||
ConcreteDataType::uint32_datatype(),
|
||||
false,
|
||||
);
|
||||
let extra_tag_column_index = push_column(
|
||||
&mut create_physical_table_task.table_info,
|
||||
"extra_tag",
|
||||
ConcreteDataType::string_datatype(),
|
||||
true,
|
||||
);
|
||||
create_physical_table_task
|
||||
.table_info
|
||||
.meta
|
||||
.partition_key_indices = vec![extra_tag_column_index, table_id_column_index];
|
||||
|
||||
let TableMetadata {
|
||||
table_id,
|
||||
table_route,
|
||||
..
|
||||
} = ddl_context
|
||||
.table_metadata_allocator
|
||||
.create(&create_physical_table_task)
|
||||
.await
|
||||
.unwrap();
|
||||
create_physical_table_task.set_table_id(table_id);
|
||||
create_physical_table_metadata(
|
||||
&ddl_context,
|
||||
create_physical_table_task.table_info.clone(),
|
||||
TableRouteValue::Physical(table_route),
|
||||
)
|
||||
.await;
|
||||
|
||||
let mut procedure = CreateLogicalTablesProcedure::new(
|
||||
vec![test_create_logical_table_task("foo")],
|
||||
table_id,
|
||||
ddl_context.clone(),
|
||||
);
|
||||
let status = procedure.on_prepare().await.unwrap();
|
||||
assert_matches!(
|
||||
status,
|
||||
Status::Executing {
|
||||
persist: true,
|
||||
clean_poisons: false
|
||||
}
|
||||
);
|
||||
|
||||
let ctx = ProcedureContext {
|
||||
procedure_id: ProcedureId::random(),
|
||||
provider: Arc::new(MockContextProvider::default()),
|
||||
event_context: None,
|
||||
};
|
||||
procedure.execute(&ctx).await.unwrap();
|
||||
let status = procedure.execute(&ctx).await.unwrap();
|
||||
let table_ids = status.downcast_output_ref::<Vec<u32>>().unwrap().clone();
|
||||
|
||||
// The engine rejects a request that occupies a reserved identity column.
|
||||
let mut creates = None;
|
||||
while let Ok((_, request)) = rx.try_recv() {
|
||||
if let Some(region_request::Body::Creates(body)) = request.body {
|
||||
creates = Some(body);
|
||||
}
|
||||
}
|
||||
let creates = creates.unwrap();
|
||||
assert_eq!(creates.requests.len(), 1);
|
||||
let requested_columns = creates.requests[0]
|
||||
.column_defs
|
||||
.iter()
|
||||
.map(|def| def.column_def.as_ref().unwrap().name.as_str())
|
||||
.collect::<Vec<_>>();
|
||||
assert!(
|
||||
!requested_columns
|
||||
.iter()
|
||||
.any(|name| is_metric_engine_internal_column(name)),
|
||||
"logical region request must not occupy internal columns: {requested_columns:?}"
|
||||
);
|
||||
assert!(requested_columns.contains(&"extra_tag"));
|
||||
|
||||
let logical_table_info = get_raw_table_info(&ddl_context, table_ids[0]).await;
|
||||
let column_names = logical_table_info
|
||||
.meta
|
||||
.schema
|
||||
.column_schemas()
|
||||
.iter()
|
||||
.map(|column| column.name.as_str())
|
||||
.collect::<Vec<_>>();
|
||||
assert!(
|
||||
!column_names.contains(&DATA_SCHEMA_TABLE_ID_COLUMN_NAME),
|
||||
"internal identity column must not be merged into the logical schema: {column_names:?}"
|
||||
);
|
||||
assert!(column_names.contains(&"extra_tag"));
|
||||
|
||||
// The user partition column is still merged as a nullable string tag of the primary key.
|
||||
let extra_tag_index = logical_table_info
|
||||
.meta
|
||||
.schema
|
||||
.column_index_by_name("extra_tag")
|
||||
.unwrap();
|
||||
assert!(
|
||||
logical_table_info
|
||||
.meta
|
||||
.primary_key_indices
|
||||
.contains(&extra_tag_index),
|
||||
"merged partition column must be part of the primary key"
|
||||
);
|
||||
let extra_tag = &logical_table_info.meta.schema.column_schemas()[extra_tag_index];
|
||||
assert_eq!(extra_tag.data_type, ConcreteDataType::string_datatype());
|
||||
assert!(extra_tag.is_nullable());
|
||||
}
|
||||
|
||||
@@ -382,10 +382,13 @@ async fn test_memory_region_keeper_guard_dropped_on_procedure_done() {
|
||||
.memory_region_keeper
|
||||
.contains(datanode_id, region_id)
|
||||
);
|
||||
let roles = ddl_context
|
||||
let operating_regions = ddl_context
|
||||
.memory_region_keeper
|
||||
.extract_operating_region_roles(datanode_id, &HashSet::from([region_id]));
|
||||
assert_eq!(roles.get(®ion_id), Some(&RegionRole::Leader));
|
||||
.extract_operating_regions(datanode_id, &HashSet::from([region_id]));
|
||||
assert_eq!(
|
||||
operating_regions.get(®ion_id).map(|region| region.role),
|
||||
Some(RegionRole::Leader)
|
||||
);
|
||||
|
||||
execute_procedure_until_done(&mut procedure).await;
|
||||
|
||||
|
||||
@@ -22,7 +22,7 @@ use common_procedure_test::{
|
||||
use futures::TryStreamExt;
|
||||
|
||||
use crate::ddl::drop_database::DropDatabaseProcedure;
|
||||
use crate::ddl::drop_database::executor::DropDatabaseExecutor;
|
||||
use crate::ddl::drop_database::executor::{DropDatabaseBatchExecutor, DropDatabaseExecutor};
|
||||
use crate::ddl::test_util::datanode_handler::{NaiveDatanodeHandler, RetryErrorDatanodeHandler};
|
||||
use crate::ddl::test_util::{create_logical_table, create_physical_table};
|
||||
use crate::key::schema_name::SchemaNameKey;
|
||||
@@ -151,24 +151,15 @@ async fn test_drop_database_recover() {
|
||||
ddl_context.clone(),
|
||||
);
|
||||
let num_operating_regions = 1;
|
||||
// Before dropping the logical table
|
||||
// Recover the persisted logical batch before its metadata is removed.
|
||||
execute_procedure_until(&mut procedure, |p| {
|
||||
p.state()
|
||||
.as_any()
|
||||
.downcast_ref::<DropDatabaseExecutor>()
|
||||
.is_some()
|
||||
p.state().as_any().is::<DropDatabaseBatchExecutor>()
|
||||
})
|
||||
.await;
|
||||
// Dump data
|
||||
let data = procedure.dump().unwrap();
|
||||
assert_eq!(ddl_context.memory_region_keeper.len(), 0);
|
||||
let mut procedure = DropDatabaseProcedure::from_json(&data, ddl_context.clone()).unwrap();
|
||||
procedure.recover().unwrap();
|
||||
assert_eq!(
|
||||
ddl_context.memory_region_keeper.len(),
|
||||
num_operating_regions
|
||||
);
|
||||
ddl_context.memory_region_keeper.clear();
|
||||
assert_eq!(ddl_context.memory_region_keeper.len(), 0);
|
||||
// Before dropping the physical table
|
||||
execute_procedure_until(&mut procedure, |p| {
|
||||
p.state()
|
||||
@@ -197,3 +188,304 @@ async fn test_drop_database_recover() {
|
||||
.unwrap();
|
||||
assert!(tables.is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_drop_database_batches_recover_after_metadata_deletion() {
|
||||
use crate::ddl::test_util::datanode_handler::DatanodeWatcher;
|
||||
use api::v1::region::region_request::Body;
|
||||
use store_api::storage::RegionId;
|
||||
|
||||
// A full batch, multiple batches, and a trailing partial batch.
|
||||
for (count, name_padding, expected_batches) in
|
||||
[(0, 0, 0), (1, 0, 1), (64, 0, 1), (129, 0, 1), (20, 8192, 2)]
|
||||
{
|
||||
let (tx, mut rx) = tokio::sync::mpsc::channel(16);
|
||||
let ddl = new_ddl_context(Arc::new(MockDatanodeManager::new(DatanodeWatcher::new(tx))));
|
||||
ddl.table_metadata_manager
|
||||
.schema_manager()
|
||||
.create(
|
||||
SchemaNameKey::new(DEFAULT_CATALOG_NAME, DEFAULT_SCHEMA_NAME),
|
||||
None,
|
||||
false,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let physical = create_physical_table(&ddl, "z_physical").await;
|
||||
let mut ids = Vec::new();
|
||||
for i in 0..count {
|
||||
create_logical_table(
|
||||
ddl.clone(),
|
||||
physical,
|
||||
&format!("logical_{i:04}{}", "x".repeat(name_padding)),
|
||||
)
|
||||
.await;
|
||||
}
|
||||
let mut procedure = DropDatabaseProcedure::new(
|
||||
DEFAULT_CATALOG_NAME.into(),
|
||||
DEFAULT_SCHEMA_NAME.into(),
|
||||
false,
|
||||
ddl.clone(),
|
||||
);
|
||||
let ctx = ProcedureContext {
|
||||
procedure_id: ProcedureId::random(),
|
||||
provider: Arc::new(MockContextProvider::default()),
|
||||
event_context: None,
|
||||
};
|
||||
let mut batches = 0;
|
||||
loop {
|
||||
if let Some(batch) = procedure
|
||||
.state()
|
||||
.as_any()
|
||||
.downcast_ref::<DropDatabaseBatchExecutor>()
|
||||
{
|
||||
ids.extend(batch.tables.iter().map(|(id, _)| *id));
|
||||
// Crash after keys are gone but before cache invalidation and cursor advancement.
|
||||
let dump = procedure.dump().unwrap();
|
||||
ddl.table_metadata_manager
|
||||
.destroy_logical_tables_metadata(&batch.tables)
|
||||
.await
|
||||
.unwrap();
|
||||
procedure = DropDatabaseProcedure::from_json(&dump, ddl.clone()).unwrap();
|
||||
procedure.recover().unwrap();
|
||||
batches += 1;
|
||||
}
|
||||
if procedure.execute(&ctx).await.unwrap().is_done() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
assert_eq!(ids.len(), count);
|
||||
assert_eq!(batches, expected_batches);
|
||||
let (_, request) = rx.try_recv().unwrap();
|
||||
let Some(Body::Drop(drop)) = request.body else {
|
||||
panic!("expected physical drop")
|
||||
};
|
||||
assert_eq!(RegionId::from_u64(drop.region_id).table_id(), physical);
|
||||
assert!(drop.force);
|
||||
assert!(
|
||||
rx.try_recv().is_err(),
|
||||
"logical tables must not send region RPCs"
|
||||
);
|
||||
assert!(
|
||||
ddl.table_metadata_manager
|
||||
.table_info_manager()
|
||||
.batch_get(&ids)
|
||||
.await
|
||||
.unwrap()
|
||||
.is_empty()
|
||||
);
|
||||
assert!(
|
||||
ddl.table_metadata_manager
|
||||
.table_name_manager()
|
||||
.tables(DEFAULT_CATALOG_NAME, DEFAULT_SCHEMA_NAME)
|
||||
.try_collect::<Vec<_>>()
|
||||
.await
|
||||
.unwrap()
|
||||
.is_empty()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_drop_database_legacy_state_fixture() {
|
||||
let ddl = new_ddl_context(Arc::new(MockDatanodeManager::new(NaiveDatanodeHandler)));
|
||||
// Single-table executor state from f8d8fe1071, before logical-table batching.
|
||||
let fixture = r#"{
|
||||
"catalog": "greptime",
|
||||
"schema": "public",
|
||||
"drop_if_exists": false,
|
||||
"state": {
|
||||
"drop_database_state": "DropDatabaseExecutor",
|
||||
"table_id": 1025,
|
||||
"physical_table_id": 1025,
|
||||
"table_name": {
|
||||
"catalog_name": "greptime",
|
||||
"schema_name": "public",
|
||||
"table_name": "logical"
|
||||
},
|
||||
"physical_region_routes": [],
|
||||
"target": "Logical"
|
||||
}
|
||||
}"#;
|
||||
let mut procedure = DropDatabaseProcedure::from_json(fixture, ddl).unwrap();
|
||||
procedure.recover().unwrap();
|
||||
assert!(procedure.state().as_any().is::<DropDatabaseExecutor>());
|
||||
assert_eq!(
|
||||
serde_json::from_str::<serde_json::Value>(fixture).unwrap(),
|
||||
serde_json::from_str::<serde_json::Value>(&procedure.dump().unwrap()).unwrap()
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_drop_database_batch_cache_failure_recovery() {
|
||||
use crate::cache_invalidator::{CacheInvalidator, Context};
|
||||
use crate::instruction::CacheIdent;
|
||||
use std::sync::Mutex;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
|
||||
struct FailingInvalidator {
|
||||
fail: AtomicBool,
|
||||
calls: Mutex<Vec<Vec<CacheIdent>>>,
|
||||
}
|
||||
#[async_trait::async_trait]
|
||||
impl CacheInvalidator for FailingInvalidator {
|
||||
async fn invalidate(&self, _: &Context, caches: &[CacheIdent]) -> crate::error::Result<()> {
|
||||
self.calls.lock().unwrap().push(caches.to_vec());
|
||||
if self.fail.swap(false, Ordering::Relaxed) {
|
||||
return crate::error::UnexpectedSnafu {
|
||||
err_msg: "injected cache failure",
|
||||
}
|
||||
.fail();
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn invalidate_all(&self) -> crate::error::Result<()> {
|
||||
// This test invalidator owns only call records, not cached metadata.
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
let invalidator = Arc::new(FailingInvalidator {
|
||||
fail: AtomicBool::new(false),
|
||||
calls: Mutex::new(Vec::new()),
|
||||
});
|
||||
let mut ddl = new_ddl_context(Arc::new(MockDatanodeManager::new(NaiveDatanodeHandler)));
|
||||
ddl.cache_invalidator = invalidator.clone();
|
||||
ddl.table_metadata_manager
|
||||
.schema_manager()
|
||||
.create(
|
||||
SchemaNameKey::new(DEFAULT_CATALOG_NAME, DEFAULT_SCHEMA_NAME),
|
||||
None,
|
||||
false,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let physical = create_physical_table(&ddl, "physical").await;
|
||||
create_logical_table(ddl.clone(), physical, "logical").await;
|
||||
let mut procedure = DropDatabaseProcedure::new(
|
||||
DEFAULT_CATALOG_NAME.into(),
|
||||
DEFAULT_SCHEMA_NAME.into(),
|
||||
false,
|
||||
ddl.clone(),
|
||||
);
|
||||
execute_procedure_until(&mut procedure, |p| {
|
||||
p.state().as_any().is::<DropDatabaseBatchExecutor>()
|
||||
})
|
||||
.await;
|
||||
let dump = procedure.dump().unwrap();
|
||||
invalidator.calls.lock().unwrap().clear();
|
||||
invalidator.fail.store(true, Ordering::Relaxed);
|
||||
let ctx = ProcedureContext {
|
||||
procedure_id: ProcedureId::random(),
|
||||
provider: Arc::new(MockContextProvider::default()),
|
||||
event_context: None,
|
||||
};
|
||||
assert!(procedure.execute(&ctx).await.is_err());
|
||||
assert_eq!(procedure.dump().unwrap(), dump);
|
||||
let mut restored = DropDatabaseProcedure::from_json(&dump, ddl).unwrap();
|
||||
restored.recover().unwrap();
|
||||
restored.execute(&ctx).await.unwrap();
|
||||
let calls = invalidator.calls.lock().unwrap();
|
||||
assert_eq!(calls.len(), 2);
|
||||
assert_eq!(calls[0], calls[1]);
|
||||
assert_eq!(calls[0].len(), 2);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_drop_database_mixed_table_order_and_recovery() {
|
||||
use crate::ddl::test_util::create_table::test_create_table_task;
|
||||
use crate::ddl::tests::create_view::{test_create_view_task, test_table_names};
|
||||
use crate::key::table_route::TableRouteValue;
|
||||
use itertools::Itertools;
|
||||
use std::collections::HashMap;
|
||||
|
||||
// Every relative ordering of metric physical, logical, mito and view names.
|
||||
for names in ["a", "b", "c", "d"].into_iter().permutations(4) {
|
||||
for recover in [false, true] {
|
||||
let ddl = new_ddl_context(Arc::new(MockDatanodeManager::new(NaiveDatanodeHandler)));
|
||||
let manager = &ddl.table_metadata_manager;
|
||||
manager
|
||||
.schema_manager()
|
||||
.create(
|
||||
SchemaNameKey::new(DEFAULT_CATALOG_NAME, DEFAULT_SCHEMA_NAME),
|
||||
None,
|
||||
false,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let physical = create_physical_table(&ddl, names[0]).await;
|
||||
let logical = create_logical_table(ddl.clone(), physical, names[1]).await;
|
||||
let mito = test_create_table_task(names[2], 20000);
|
||||
manager
|
||||
.create_table_metadata(
|
||||
mito.table_info,
|
||||
TableRouteValue::physical(vec![]),
|
||||
HashMap::new(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let mut view = test_create_view_task(names[3]);
|
||||
view.view_info.ident.table_id = 20001;
|
||||
manager
|
||||
.create_view_metadata(
|
||||
view.view_info,
|
||||
view.create_view.logical_plan,
|
||||
test_table_names(),
|
||||
vec![],
|
||||
vec![],
|
||||
"definition".into(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let mut procedure = DropDatabaseProcedure::new(
|
||||
DEFAULT_CATALOG_NAME.into(),
|
||||
DEFAULT_SCHEMA_NAME.into(),
|
||||
false,
|
||||
ddl.clone(),
|
||||
);
|
||||
let ctx = ProcedureContext {
|
||||
procedure_id: ProcedureId::random(),
|
||||
provider: Arc::new(MockContextProvider::default()),
|
||||
event_context: None,
|
||||
};
|
||||
let mut done = false;
|
||||
for _ in 0..40 {
|
||||
let status = procedure.execute(&ctx).await.unwrap();
|
||||
if status.is_done() {
|
||||
done = true;
|
||||
break;
|
||||
}
|
||||
if recover && status.need_persist() {
|
||||
let dump = procedure.dump().unwrap();
|
||||
drop(procedure);
|
||||
procedure = DropDatabaseProcedure::from_json(&dump, ddl.clone()).unwrap();
|
||||
procedure.recover().unwrap();
|
||||
}
|
||||
}
|
||||
assert!(done, "{names:?}, recovery={recover}");
|
||||
assert!(
|
||||
manager
|
||||
.table_name_manager()
|
||||
.tables(DEFAULT_CATALOG_NAME, DEFAULT_SCHEMA_NAME)
|
||||
.try_collect::<Vec<_>>()
|
||||
.await
|
||||
.unwrap()
|
||||
.is_empty()
|
||||
);
|
||||
assert!(
|
||||
manager
|
||||
.table_info_manager()
|
||||
.batch_get(&[physical, logical, 20000, 20001])
|
||||
.await
|
||||
.unwrap()
|
||||
.is_empty()
|
||||
);
|
||||
assert!(
|
||||
manager
|
||||
.view_info_manager()
|
||||
.get(20001)
|
||||
.await
|
||||
.unwrap()
|
||||
.is_none()
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2782,10 +2782,13 @@ async fn test_memory_region_keeper_guard_dropped_on_procedure_done() {
|
||||
.memory_region_keeper
|
||||
.contains(datanode_id, region_id)
|
||||
);
|
||||
let roles = ddl_context
|
||||
let operating_regions = ddl_context
|
||||
.memory_region_keeper
|
||||
.extract_operating_region_roles(datanode_id, &HashSet::from([region_id]));
|
||||
assert_eq!(roles.get(®ion_id), Some(&RegionRole::Leader));
|
||||
.extract_operating_regions(datanode_id, &HashSet::from([region_id]));
|
||||
assert_eq!(
|
||||
operating_regions.get(®ion_id).map(|region| region.role),
|
||||
Some(RegionRole::Leader)
|
||||
);
|
||||
|
||||
execute_procedure_until_done(&mut procedure).await;
|
||||
|
||||
|
||||
@@ -625,13 +625,22 @@ impl DdlManager {
|
||||
&self,
|
||||
alter_table_tasks: Vec<AlterTableTask>,
|
||||
physical_table_id: TableId,
|
||||
expected_table_ids: Option<Vec<TableId>>,
|
||||
procedure_context: ProcedureContext,
|
||||
) -> Result<(ProcedureId, Option<Output>)> {
|
||||
let context = self.create_context();
|
||||
|
||||
// Resolve the logical table ids up front: procedure locks are fixed
|
||||
// at submission, so `lock_key` cannot derive them during `Prepare`.
|
||||
let logical_table_ids = {
|
||||
let logical_table_ids = if let Some(ids) = expected_table_ids {
|
||||
ensure!(
|
||||
ids.len() == alter_table_tasks.len(),
|
||||
error::AlterLogicalTablesInvalidArgumentsSnafu {
|
||||
err_msg: "Expected one pinned table ID per logical ALTER task",
|
||||
}
|
||||
);
|
||||
ids
|
||||
} else {
|
||||
let table_refs = alter_table_tasks
|
||||
.iter()
|
||||
.map(|task| task.table_ref())
|
||||
@@ -1043,8 +1052,13 @@ impl DdlManager {
|
||||
.await
|
||||
}
|
||||
AlterLogicalTables(alter_table_tasks) => {
|
||||
handle_alter_logical_table_tasks(self, alter_table_tasks, procedure_context)
|
||||
.await
|
||||
handle_alter_logical_table_tasks(
|
||||
self,
|
||||
alter_table_tasks,
|
||||
query_context,
|
||||
procedure_context,
|
||||
)
|
||||
.await
|
||||
}
|
||||
DropLogicalTables(_) => todo!(),
|
||||
CreateDatabase(create_database_task) => {
|
||||
@@ -1598,6 +1612,7 @@ async fn handle_create_trigger_task(
|
||||
async fn handle_alter_logical_table_tasks(
|
||||
ddl_manager: &DdlManager,
|
||||
alter_table_tasks: Vec<AlterTableTask>,
|
||||
query_context: QueryContext,
|
||||
procedure_context: ProcedureContext,
|
||||
) -> Result<SubmitDdlTaskResponse> {
|
||||
ensure!(
|
||||
@@ -1616,9 +1631,15 @@ async fn handle_alter_logical_table_tasks(
|
||||
let physical_table_id =
|
||||
utils::get_physical_table_id(ddl_manager.table_metadata_manager(), first_table).await?;
|
||||
let num_logical_tables = alter_table_tasks.len();
|
||||
let expected_table_ids = query_context.pinned_logical_table_ids()?;
|
||||
|
||||
let (id, _) = ddl_manager
|
||||
.submit_alter_logical_table_tasks(alter_table_tasks, physical_table_id, procedure_context)
|
||||
.submit_alter_logical_table_tasks(
|
||||
alter_table_tasks,
|
||||
physical_table_id,
|
||||
expected_table_ids,
|
||||
procedure_context,
|
||||
)
|
||||
.await?;
|
||||
|
||||
info!(
|
||||
@@ -2061,6 +2082,59 @@ mod tests {
|
||||
)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_alter_logical_tables_preserves_caller_pinned_ids() {
|
||||
use crate::ddl::test_util::alter_table::TestAlterTableExprBuilder;
|
||||
use crate::ddl::test_util::{create_logical_table, create_physical_table};
|
||||
use crate::rpc::ddl::ALTER_LOGICAL_TABLE_IDS_EXTENSION_KEY;
|
||||
|
||||
let manager = build_soft_drop_test_ddl_manager();
|
||||
manager.register_loaders().unwrap();
|
||||
manager.procedure_manager.start().await.unwrap();
|
||||
let context = manager.create_context();
|
||||
let physical_id = create_physical_table(&context, "physical").await;
|
||||
let logical_id = create_logical_table(context, physical_id, "logical").await;
|
||||
let expr: api::v1::AlterTableExpr = TestAlterTableExprBuilder::default()
|
||||
.table_name("logical")
|
||||
.add_columns(vec![api::v1::ColumnDef {
|
||||
name: "host".into(),
|
||||
data_type: api::v1::ColumnDataType::String as i32,
|
||||
semantic_type: api::v1::SemanticType::Tag as i32,
|
||||
is_nullable: true,
|
||||
..Default::default()
|
||||
}])
|
||||
.add_if_not_exists(true)
|
||||
.build()
|
||||
.unwrap()
|
||||
.into();
|
||||
for (ids, succeeds) in [
|
||||
(Some((logical_id + 1000).to_string()), false),
|
||||
(Some(format!("{logical_id},{logical_id}")), false),
|
||||
(Some(logical_id.to_string()), true),
|
||||
(None, true),
|
||||
] {
|
||||
let mut context = QueryContext::default();
|
||||
if let Some(ids) = ids {
|
||||
context
|
||||
.extensions
|
||||
.insert(ALTER_LOGICAL_TABLE_IDS_EXTENSION_KEY.into(), ids);
|
||||
}
|
||||
let result = manager
|
||||
.submit_ddl_task(
|
||||
ExecutorContext {
|
||||
query_context: Some(context),
|
||||
..Default::default()
|
||||
},
|
||||
SubmitDdlTaskRequest::new(DdlTask::new_alter_logical_tables(vec![
|
||||
expr.clone(),
|
||||
])),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(result.is_ok(), succeeds, "{result:?}");
|
||||
}
|
||||
manager.procedure_manager.stop().await.unwrap();
|
||||
}
|
||||
|
||||
#[cfg(feature = "enterprise")]
|
||||
#[tokio::test]
|
||||
async fn test_reserved_sequence_range_is_rejected_before_custom_handler() {
|
||||
|
||||
@@ -388,6 +388,9 @@ pub struct UpgradeRegion {
|
||||
pub replay_entry_id: Option<u64>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub metadata_replay_entry_id: Option<u64>,
|
||||
/// The candidate lease id of the migration's registration of this target region.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub candidate_lease_id: Option<u64>,
|
||||
}
|
||||
|
||||
impl UpgradeRegion {
|
||||
@@ -408,6 +411,9 @@ impl UpgradeRegion {
|
||||
/// The identifier of cache.
|
||||
pub enum CacheIdent {
|
||||
FlowId(FlowId),
|
||||
/// Indicates a change of trigger metadata; invalidated by enterprise plugins.
|
||||
#[cfg(feature = "enterprise")]
|
||||
TriggerId(u64),
|
||||
/// Indicate change of address of flownode.
|
||||
FlowNodeAddressChange(u64),
|
||||
FlowName(FlowName),
|
||||
@@ -1559,6 +1565,7 @@ mod tests {
|
||||
location_id: None,
|
||||
replay_entry_id: None,
|
||||
metadata_replay_entry_id: None,
|
||||
candidate_lease_id: None,
|
||||
}]);
|
||||
|
||||
let serialized = serde_json::to_string(&upgrade_region).unwrap();
|
||||
@@ -1656,10 +1663,27 @@ mod tests {
|
||||
location_id: None,
|
||||
replay_entry_id: None,
|
||||
metadata_replay_entry_id: None,
|
||||
candidate_lease_id: None,
|
||||
}]);
|
||||
assert_eq!(upgrade_region_instruction, upgrade_region);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_upgrade_region_candidate_lease_id_json() {
|
||||
let upgrade_region = UpgradeRegion {
|
||||
region_id: RegionId::new(1024, 1),
|
||||
replay_timeout: Duration::from_millis(1000),
|
||||
candidate_lease_id: Some(7),
|
||||
..Default::default()
|
||||
};
|
||||
let json = serde_json::to_value(&upgrade_region).unwrap();
|
||||
assert_eq!(json["candidate_lease_id"], 7);
|
||||
assert_eq!(
|
||||
serde_json::from_value::<UpgradeRegion>(json).unwrap(),
|
||||
upgrade_region
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_deserialize_instruction_reply() {
|
||||
// legacy close region reply
|
||||
|
||||
+118
-13
@@ -994,6 +994,26 @@ impl TableMetadataManager {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
const TABLE_IDENTITY_KEYS: usize = 4;
|
||||
|
||||
/// Keys shared by physical and logical tables, independent of region placement.
|
||||
pub(crate) fn table_identity_keys(
|
||||
table_id: TableId,
|
||||
table_name: &TableName,
|
||||
) -> [Vec<u8>; Self::TABLE_IDENTITY_KEYS] {
|
||||
[
|
||||
TableNameKey::new(
|
||||
&table_name.catalog_name,
|
||||
&table_name.schema_name,
|
||||
&table_name.table_name,
|
||||
)
|
||||
.to_bytes(),
|
||||
TableInfoKey::new(table_id).to_bytes(),
|
||||
TableRouteKey::new(table_id).to_bytes(),
|
||||
TableRepartKey::new(table_id).to_bytes(),
|
||||
]
|
||||
}
|
||||
|
||||
fn table_metadata_keys(
|
||||
&self,
|
||||
table_id: TableId,
|
||||
@@ -1009,15 +1029,7 @@ impl TableMetadataManager {
|
||||
} else {
|
||||
vec![]
|
||||
};
|
||||
let mut keys = Vec::with_capacity(3 + datanode_ids.len());
|
||||
let table_name = TableNameKey::new(
|
||||
&table_name.catalog_name,
|
||||
&table_name.schema_name,
|
||||
&table_name.table_name,
|
||||
);
|
||||
let table_info_key = TableInfoKey::new(table_id);
|
||||
let table_route_key = TableRouteKey::new(table_id);
|
||||
let table_repart_key = TableRepartKey::new(table_id);
|
||||
let mut keys = Vec::from(Self::table_identity_keys(table_id, table_name));
|
||||
let datanode_table_keys = datanode_ids
|
||||
.into_iter()
|
||||
.map(|datanode_id| DatanodeTableKey::new(datanode_id, table_id))
|
||||
@@ -1029,10 +1041,6 @@ impl TableMetadataManager {
|
||||
.iter()
|
||||
.map(|(region_id, topic)| TopicRegionKey::new(*region_id, topic))
|
||||
.collect::<Vec<_>>();
|
||||
keys.push(table_name.to_bytes());
|
||||
keys.push(table_info_key.to_bytes());
|
||||
keys.push(table_route_key.to_bytes());
|
||||
keys.push(table_repart_key.to_bytes());
|
||||
for key in &datanode_table_keys {
|
||||
keys.push(key.to_bytes());
|
||||
}
|
||||
@@ -1321,6 +1329,30 @@ impl TableMetadataManager {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Permanently deletes a batch of logical tables. The caller holds their schema write lock
|
||||
/// and persists the deletion plan before calling, since backend requests may partially succeed.
|
||||
pub(crate) async fn destroy_logical_tables_metadata(
|
||||
&self,
|
||||
tables: &[(TableId, TableName)],
|
||||
) -> Result<()> {
|
||||
let max_ops = self.kv_backend.max_txn_ops().max(1);
|
||||
let tables_per_request = (max_ops / Self::TABLE_IDENTITY_KEYS).max(1);
|
||||
// Keep a table's keys together whenever they fit in one backend request. A backend
|
||||
// limit smaller than a single table still requires splitting, as with single-table drop.
|
||||
for tables in tables.chunks(tables_per_request) {
|
||||
let keys = tables
|
||||
.iter()
|
||||
.flat_map(|(id, name)| Self::table_identity_keys(*id, name))
|
||||
.collect::<Vec<_>>();
|
||||
for keys in keys.chunks(max_ops) {
|
||||
self.kv_backend
|
||||
.batch_delete(BatchDeleteRequest::new().with_keys(keys.to_vec()))
|
||||
.await?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Rebuilds dropped table metadata from tombstoned keys.
|
||||
async fn get_dropped_table_metadata<T>(
|
||||
&self,
|
||||
@@ -3094,6 +3126,79 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_destroy_logical_tables_metadata_limits_and_partial_failure() {
|
||||
use crate::kv_backend::test_util::MockKvBackendBuilder;
|
||||
use crate::rpc::store::{BatchDeleteRequest, BatchDeleteResponse};
|
||||
use std::sync::Mutex;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
for limit in [1, 3, 127, 128, 129] {
|
||||
let tables = (0..65)
|
||||
.map(|id| {
|
||||
(
|
||||
id,
|
||||
TableName::new("greptime", "public", format!("logical_{id}")),
|
||||
)
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
let remaining = Arc::new(Mutex::new(
|
||||
tables
|
||||
.iter()
|
||||
.flat_map(|(id, name)| TableMetadataManager::table_identity_keys(*id, name))
|
||||
.collect::<HashSet<_>>(),
|
||||
));
|
||||
let requests = Arc::new(AtomicUsize::new(0));
|
||||
let backend = MockKvBackendBuilder::default()
|
||||
.max_txn_ops(limit)
|
||||
.batch_delete_fn({
|
||||
let remaining = remaining.clone();
|
||||
let requests = requests.clone();
|
||||
Arc::new(move |req: BatchDeleteRequest| {
|
||||
assert!(!req.keys.is_empty());
|
||||
assert!(req.keys.len() <= limit);
|
||||
if limit >= 4 {
|
||||
assert_eq!(req.keys.len() % 4, 0, "single-table keys stay together");
|
||||
}
|
||||
for key in &req.keys {
|
||||
remaining.lock().unwrap().remove(key);
|
||||
}
|
||||
// Simulate a response lost after the second chunk committed.
|
||||
if requests.fetch_add(1, Ordering::Relaxed) == 1 {
|
||||
return crate::error::UnexpectedSnafu {
|
||||
err_msg: "injected lost response",
|
||||
}
|
||||
.fail();
|
||||
}
|
||||
Ok(BatchDeleteResponse::default())
|
||||
})
|
||||
})
|
||||
.build()
|
||||
.unwrap();
|
||||
let manager = TableMetadataManager::new(Arc::new(backend));
|
||||
assert!(
|
||||
manager
|
||||
.destroy_logical_tables_metadata(&tables)
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
assert!(!remaining.lock().unwrap().is_empty());
|
||||
manager
|
||||
.destroy_logical_tables_metadata(&tables)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(remaining.lock().unwrap().is_empty());
|
||||
assert_eq!(
|
||||
requests.load(Ordering::Relaxed),
|
||||
2 + if limit < 4 {
|
||||
65_usize * 4_usize.div_ceil(limit)
|
||||
} else {
|
||||
65_usize.div_ceil(limit / 4)
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_destroy_table_metadata() {
|
||||
let mem_kv = Arc::new(MemoryKvBackend::default());
|
||||
|
||||
@@ -41,6 +41,20 @@ pub mod txn;
|
||||
pub mod util;
|
||||
pub type KvBackendRef<E = Error> = Arc<dyn KvBackend<Error = E> + Send + Sync>;
|
||||
|
||||
/// A [KvBackend] holding resources that must be released explicitly on shutdown, because
|
||||
/// components sharing it may keep it alive until the process exits.
|
||||
///
|
||||
/// Wrappers of a closable backend must forward [ClosableKvBackend::close] to it.
|
||||
#[async_trait]
|
||||
pub trait ClosableKvBackend: KvBackend<Error = Error> {
|
||||
/// Releases the backend's resources; any later use fails.
|
||||
/// May wait for in-flight operations to release their resources, so callers must
|
||||
/// stop consumers first. Closing is terminal, not a pause for role transitions.
|
||||
async fn close(&self) -> Result<(), Error>;
|
||||
}
|
||||
|
||||
pub type ClosableKvBackendRef = Arc<dyn ClosableKvBackend + Send + Sync>;
|
||||
|
||||
#[cfg(any(feature = "pg_kvbackend", feature = "mysql_kvbackend"))]
|
||||
// The default meta table name, default is "greptime_metakv".
|
||||
pub const DEFAULT_META_TABLE_NAME: &str = "greptime_metakv";
|
||||
|
||||
@@ -26,7 +26,7 @@ use crate::error::{Error, RdsTransactionRetryFailedSnafu, Result, UnexpectedSnaf
|
||||
use crate::kv_backend::txn::{
|
||||
Compare, Txn as KvTxn, TxnOp, TxnOpResponse, TxnResponse as KvTxnResponse,
|
||||
};
|
||||
use crate::kv_backend::{KvBackend, TxnService};
|
||||
use crate::kv_backend::{ClosableKvBackend, KvBackend, TxnService};
|
||||
use crate::metrics::METRIC_META_TXN_REQUEST;
|
||||
use crate::rpc::KeyValue;
|
||||
use crate::rpc::store::{
|
||||
@@ -121,6 +121,11 @@ pub trait Transaction<'a>: Send + Sync {
|
||||
/// Factory for creating default and transaction query executors.
|
||||
#[async_trait::async_trait]
|
||||
pub trait ExecutorFactory<T: Executor>: Send + Sync {
|
||||
/// Closes the connection pool to new acquisitions. This affects all shared pool handles.
|
||||
/// MySQL waits for checked-out connections to be returned; PostgreSQL allows them to
|
||||
/// finish and releases them when returned. Stop consumers before closing the backend.
|
||||
async fn close(&self);
|
||||
|
||||
async fn default_executor(&self) -> Result<T>;
|
||||
|
||||
async fn txn_executor<'a>(&self, default_executor: &'a mut T) -> Result<T::Transaction<'a>>;
|
||||
@@ -585,6 +590,20 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl<T, S, R> ClosableKvBackend for RdsStore<T, S, R>
|
||||
where
|
||||
R: 'static,
|
||||
Self: KvQueryExecutor<T> + Send + Sync,
|
||||
T: Executor + 'static,
|
||||
S: ExecutorFactory<T> + 'static,
|
||||
{
|
||||
async fn close(&self) -> Result<()> {
|
||||
self.executor_factory.close().await;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Checks if the transaction operations are the same type.
|
||||
fn check_txn_ops(txn_ops: &[TxnOp]) -> Result<bool> {
|
||||
if txn_ops.is_empty() {
|
||||
|
||||
@@ -27,7 +27,7 @@ use strum::AsRefStr;
|
||||
use crate::error::{
|
||||
CreateMySqlPoolSnafu, MySqlExecutionSnafu, MySqlTransactionSnafu, Result, UnexpectedSnafu,
|
||||
};
|
||||
use crate::kv_backend::KvBackendRef;
|
||||
use crate::kv_backend::ClosableKvBackendRef;
|
||||
use crate::kv_backend::rds::{
|
||||
Executor, ExecutorFactory, ExecutorImpl, KvQueryExecutor, RDS_STORE_OP_BATCH_DELETE,
|
||||
RDS_STORE_OP_BATCH_GET, RDS_STORE_OP_BATCH_PUT, RDS_STORE_OP_RANGE_DELETE,
|
||||
@@ -348,6 +348,10 @@ pub struct MySqlExecutorFactory {
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl ExecutorFactory<MySqlClient> for MySqlExecutorFactory {
|
||||
async fn close(&self) {
|
||||
self.pool.close().await;
|
||||
}
|
||||
|
||||
async fn default_executor(&self) -> Result<MySqlClient> {
|
||||
Ok(self.pool.clone())
|
||||
}
|
||||
@@ -631,8 +635,12 @@ impl MySqlStore {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Create [MySqlStore] impl of [KvBackendRef] from url.
|
||||
pub async fn with_url(url: &str, table_name: &str, max_txn_ops: usize) -> Result<KvBackendRef> {
|
||||
/// Create [MySqlStore] impl of [ClosableKvBackendRef] from url.
|
||||
pub async fn with_url(
|
||||
url: &str,
|
||||
table_name: &str,
|
||||
max_txn_ops: usize,
|
||||
) -> Result<ClosableKvBackendRef> {
|
||||
ensure_rustls_crypto_provider_installed()?;
|
||||
let pool = MySqlPool::connect(url)
|
||||
.await
|
||||
@@ -640,12 +648,12 @@ impl MySqlStore {
|
||||
Self::with_mysql_pool(pool, table_name, max_txn_ops).await
|
||||
}
|
||||
|
||||
/// Create [MySqlStore] impl of [KvBackendRef] from [sqlx::Pool<MySql>].
|
||||
/// Create [MySqlStore] impl of [ClosableKvBackendRef] from [sqlx::Pool<MySql>].
|
||||
pub async fn with_mysql_pool(
|
||||
pool: Pool<MySql>,
|
||||
table_name: &str,
|
||||
max_txn_ops: usize,
|
||||
) -> Result<KvBackendRef> {
|
||||
) -> Result<ClosableKvBackendRef> {
|
||||
// This step ensures the mysql metadata backend is ready to use.
|
||||
// We check if greptime_metakv table exists, and we will create a new table
|
||||
// if it does not exist.
|
||||
@@ -690,6 +698,61 @@ mod tests {
|
||||
use crate::rpc::store::{PutRequest, RangeRequest};
|
||||
use crate::test_util::test_certs_dir;
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_close_backend() {
|
||||
let pool =
|
||||
sqlx::mysql::MySqlPoolOptions::new().connect_lazy_with(MySqlConnectOptions::new());
|
||||
let backend: ClosableKvBackendRef = Arc::new(MySqlStore {
|
||||
max_txn_ops: 128,
|
||||
txn_retry_count: RDS_STORE_TXN_RETRY_COUNT,
|
||||
executor_factory: MySqlExecutorFactory {
|
||||
pool: Arc::new(pool.clone()),
|
||||
},
|
||||
sql_template_set: MySqlTemplateFactory::new("close_test").build(),
|
||||
_phantom: PhantomData,
|
||||
});
|
||||
let shared_backend = backend.clone();
|
||||
assert!(!pool.is_closed());
|
||||
backend.close().await.unwrap();
|
||||
assert!(pool.is_closed());
|
||||
shared_backend.close().await.unwrap();
|
||||
assert!(matches!(pool.acquire().await, Err(sqlx::Error::PoolClosed)));
|
||||
let result = tokio::time::timeout(
|
||||
std::time::Duration::from_secs(1),
|
||||
shared_backend.put(crate::rpc::store::PutRequest {
|
||||
key: b"key".to_vec(),
|
||||
value: b"value".to_vec(),
|
||||
prev_kv: false,
|
||||
}),
|
||||
)
|
||||
.await
|
||||
.expect("closed backend must reject writes promptly");
|
||||
assert!(result.is_err());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_close_backend_waits_for_checked_out_connection() {
|
||||
maybe_skip_mysql_integration_test!();
|
||||
let pool = mysql_pool().await.unwrap();
|
||||
let table = new_test_table_name("close_held");
|
||||
let backend = MySqlStore::with_mysql_pool(pool.clone(), &table, 128)
|
||||
.await
|
||||
.unwrap();
|
||||
let connection = pool.acquire().await.unwrap();
|
||||
let close = backend.close();
|
||||
tokio::pin!(close);
|
||||
|
||||
assert!(futures::poll!(close.as_mut()).is_pending());
|
||||
assert!(pool.is_closed());
|
||||
assert!(matches!(pool.acquire().await, Err(sqlx::Error::PoolClosed)));
|
||||
drop(connection);
|
||||
tokio::time::timeout(std::time::Duration::from_secs(5), close)
|
||||
.await
|
||||
.expect("close must finish after the connection is returned")
|
||||
.unwrap();
|
||||
backend.close().await.unwrap();
|
||||
}
|
||||
|
||||
fn new_test_table_name(prefix: &str) -> String {
|
||||
let uuid = Uuid::new_v4().simple().to_string();
|
||||
let max_prefix_len = 63usize.saturating_sub(uuid.len() + 1);
|
||||
|
||||
@@ -36,7 +36,7 @@ use crate::error::{
|
||||
CreatePostgresPoolSnafu, GetPostgresConnectionSnafu, LoadTlsCertificateSnafu,
|
||||
PostgresExecutionSnafu, PostgresTlsConfigSnafu, PostgresTransactionSnafu, Result,
|
||||
};
|
||||
use crate::kv_backend::KvBackendRef;
|
||||
use crate::kv_backend::ClosableKvBackendRef;
|
||||
use crate::kv_backend::rds::{
|
||||
Executor, ExecutorFactory, ExecutorImpl, KvQueryExecutor, RDS_STORE_OP_BATCH_DELETE,
|
||||
RDS_STORE_OP_BATCH_GET, RDS_STORE_OP_BATCH_PUT, RDS_STORE_OP_RANGE_DELETE,
|
||||
@@ -389,6 +389,10 @@ impl PgExecutorFactory {
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl ExecutorFactory<PgClient> for PgExecutorFactory {
|
||||
async fn close(&self) {
|
||||
self.pool.close();
|
||||
}
|
||||
|
||||
async fn default_executor(&self) -> Result<PgClient> {
|
||||
self.client().await
|
||||
}
|
||||
@@ -808,7 +812,7 @@ impl KvQueryExecutor<PgClient> for PgStore {
|
||||
}
|
||||
|
||||
impl PgStore {
|
||||
/// Create [PgStore] impl of [KvBackendRef] from url with optional TLS support.
|
||||
/// Create [PgStore] impl of [ClosableKvBackendRef] from url with optional TLS support.
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
@@ -821,7 +825,7 @@ impl PgStore {
|
||||
table_name: &str,
|
||||
max_txn_ops: usize,
|
||||
tls_config: Option<TlsOption>,
|
||||
) -> Result<KvBackendRef> {
|
||||
) -> Result<ClosableKvBackendRef> {
|
||||
let mut cfg = Config::new();
|
||||
cfg.url = Some(url.to_string());
|
||||
|
||||
@@ -853,19 +857,23 @@ impl PgStore {
|
||||
Self::with_pg_pool(pool, None, table_name, max_txn_ops, false).await
|
||||
}
|
||||
|
||||
/// Create [PgStore] impl of [KvBackendRef] from url (backward compatibility).
|
||||
pub async fn with_url(url: &str, table_name: &str, max_txn_ops: usize) -> Result<KvBackendRef> {
|
||||
/// Create [PgStore] impl of [ClosableKvBackendRef] from url without TLS.
|
||||
pub async fn with_url(
|
||||
url: &str,
|
||||
table_name: &str,
|
||||
max_txn_ops: usize,
|
||||
) -> Result<ClosableKvBackendRef> {
|
||||
Self::with_url_and_tls(url, table_name, max_txn_ops, None).await
|
||||
}
|
||||
|
||||
/// Create [PgStore] impl of [KvBackendRef] from [deadpool_postgres::Pool] with optional schema.
|
||||
/// Create [PgStore] impl of [ClosableKvBackendRef] from [deadpool_postgres::Pool] with optional schema.
|
||||
pub async fn with_pg_pool(
|
||||
pool: Pool,
|
||||
schema_name: Option<&str>,
|
||||
table_name: &str,
|
||||
max_txn_ops: usize,
|
||||
auto_create_schema: bool,
|
||||
) -> Result<KvBackendRef> {
|
||||
) -> Result<ClosableKvBackendRef> {
|
||||
// Ensure the postgres metadata backend is ready to use.
|
||||
let client = match pool.get().await {
|
||||
Ok(client) => client,
|
||||
@@ -925,6 +933,68 @@ mod tests {
|
||||
use crate::test_util::test_certs_dir;
|
||||
use crate::{maybe_skip_postgres_integration_test, maybe_skip_postgres15_integration_test};
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_close_backend() {
|
||||
let mut config = Config::new();
|
||||
config.host = Some("localhost".to_string());
|
||||
config.user = Some("test".to_string());
|
||||
config.dbname = Some("test".to_string());
|
||||
let pool = config.create_pool(Some(Runtime::Tokio1), NoTls).unwrap();
|
||||
let backend: ClosableKvBackendRef = Arc::new(PgStore {
|
||||
max_txn_ops: 128,
|
||||
txn_retry_count: RDS_STORE_TXN_RETRY_COUNT,
|
||||
executor_factory: PgExecutorFactory { pool: pool.clone() },
|
||||
sql_template_set: PgSqlTemplateFactory::new(None, "close_test").build(),
|
||||
_phantom: PhantomData,
|
||||
});
|
||||
let shared_backend = backend.clone();
|
||||
assert!(!pool.is_closed());
|
||||
backend.close().await.unwrap();
|
||||
assert!(pool.is_closed());
|
||||
shared_backend.close().await.unwrap();
|
||||
assert!(matches!(
|
||||
pool.get().await,
|
||||
Err(deadpool::managed::PoolError::Closed)
|
||||
));
|
||||
let result = tokio::time::timeout(
|
||||
std::time::Duration::from_secs(1),
|
||||
shared_backend.put(crate::rpc::store::PutRequest {
|
||||
key: b"key".to_vec(),
|
||||
value: b"value".to_vec(),
|
||||
prev_kv: false,
|
||||
}),
|
||||
)
|
||||
.await
|
||||
.expect("closed backend must reject writes promptly");
|
||||
assert!(result.is_err());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_close_backend_with_checked_out_connection() {
|
||||
maybe_skip_postgres_integration_test!();
|
||||
let mut config = Config::new();
|
||||
config.url = Some(std::env::var("GT_POSTGRES_ENDPOINTS").unwrap());
|
||||
let pool = config.create_pool(Some(Runtime::Tokio1), NoTls).unwrap();
|
||||
let backend = PgStore::with_pg_pool(pool.clone(), None, "close_held", 128, false)
|
||||
.await
|
||||
.unwrap();
|
||||
let connection = pool.get().await.unwrap();
|
||||
|
||||
tokio::time::timeout(std::time::Duration::from_secs(5), backend.close())
|
||||
.await
|
||||
.expect("PostgreSQL close does not wait for checked-out connections")
|
||||
.unwrap();
|
||||
assert!(pool.is_closed());
|
||||
assert!(matches!(
|
||||
pool.get().await,
|
||||
Err(deadpool::managed::PoolError::Closed)
|
||||
));
|
||||
// Existing executors can finish even though new acquisitions are rejected.
|
||||
connection.simple_query("SELECT 1").await.unwrap();
|
||||
drop(connection);
|
||||
backend.close().await.unwrap();
|
||||
}
|
||||
|
||||
async fn build_pg_kv_backend(table_name: &str) -> Option<PgStore> {
|
||||
let endpoints = std::env::var("GT_POSTGRES_ENDPOINTS").unwrap_or_default();
|
||||
if endpoints.is_empty() {
|
||||
|
||||
@@ -22,8 +22,8 @@ use crate::error::Result;
|
||||
use crate::kv_backend::txn::{Txn, TxnResponse};
|
||||
use crate::kv_backend::{
|
||||
BatchDeleteRequest, BatchDeleteResponse, BatchGetRequest, BatchGetResponse, BatchPutRequest,
|
||||
BatchPutResponse, DeleteRangeRequest, DeleteRangeResponse, KvBackend, PutRequest, PutResponse,
|
||||
RangeRequest, RangeResponse, TxnService,
|
||||
BatchPutResponse, DeleteRangeRequest, DeleteRangeResponse, KvBackend, KvBackendRef, PutRequest,
|
||||
PutResponse, RangeRequest, RangeResponse, TxnService,
|
||||
};
|
||||
|
||||
pub type MockFn<Req, Resp> = Arc<dyn Fn(Req) -> Result<Resp> + Send + Sync>;
|
||||
@@ -133,3 +133,60 @@ impl KvBackend for MockKvBackend {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A [KvBackend] that runs `before_txn` before each transaction of `inner`.
|
||||
pub struct TxnObservingKvBackend {
|
||||
/// The kv backend every request is forwarded to.
|
||||
pub inner: KvBackendRef,
|
||||
/// Runs before each transaction is forwarded to `inner`.
|
||||
pub before_txn: Box<dyn Fn() + Send + Sync>,
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl TxnService for TxnObservingKvBackend {
|
||||
type Error = crate::error::Error;
|
||||
|
||||
async fn txn(&self, txn: Txn) -> Result<TxnResponse> {
|
||||
(self.before_txn)();
|
||||
self.inner.txn(txn).await
|
||||
}
|
||||
|
||||
fn max_txn_ops(&self) -> usize {
|
||||
self.inner.max_txn_ops()
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl KvBackend for TxnObservingKvBackend {
|
||||
fn name(&self) -> &str {
|
||||
self.inner.name()
|
||||
}
|
||||
|
||||
fn as_any(&self) -> &dyn Any {
|
||||
self
|
||||
}
|
||||
|
||||
async fn range(&self, req: RangeRequest) -> Result<RangeResponse> {
|
||||
self.inner.range(req).await
|
||||
}
|
||||
|
||||
async fn put(&self, req: PutRequest) -> Result<PutResponse> {
|
||||
self.inner.put(req).await
|
||||
}
|
||||
|
||||
async fn batch_put(&self, req: BatchPutRequest) -> Result<BatchPutResponse> {
|
||||
self.inner.batch_put(req).await
|
||||
}
|
||||
|
||||
async fn batch_get(&self, req: BatchGetRequest) -> Result<BatchGetResponse> {
|
||||
self.inner.batch_get(req).await
|
||||
}
|
||||
|
||||
async fn delete_range(&self, req: DeleteRangeRequest) -> Result<DeleteRangeResponse> {
|
||||
self.inner.delete_range(req).await
|
||||
}
|
||||
|
||||
async fn batch_delete(&self, req: BatchDeleteRequest) -> Result<BatchDeleteResponse> {
|
||||
self.inner.batch_delete(req).await
|
||||
}
|
||||
}
|
||||
|
||||
@@ -21,12 +21,25 @@ use store_api::storage::RegionId;
|
||||
|
||||
use crate::DatanodeId;
|
||||
|
||||
/// An operating region on a datanode.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct OperatingRegion {
|
||||
/// The role of a lease granted because of this registration, when the region route grants
|
||||
/// none.
|
||||
pub role: RegionRole,
|
||||
/// The random non-zero id of a region migration's registration of its target region. A lease
|
||||
/// granted because of this registration carries it while the table route exists. `None` for
|
||||
/// other operations.
|
||||
pub candidate_lease_id: Option<u64>,
|
||||
}
|
||||
|
||||
/// Tracks the operating(i.e., creating, opening, dropping) regions.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct OperatingRegionGuard {
|
||||
datanode_id: DatanodeId,
|
||||
region_id: RegionId,
|
||||
inner: Arc<RwLock<HashMap<(DatanodeId, RegionId), RegionRole>>>,
|
||||
candidate_lease_id: Option<u64>,
|
||||
inner: Arc<RwLock<HashMap<(DatanodeId, RegionId), OperatingRegion>>>,
|
||||
}
|
||||
|
||||
impl Drop for OperatingRegionGuard {
|
||||
@@ -41,6 +54,11 @@ impl OperatingRegionGuard {
|
||||
pub fn info(&self) -> (DatanodeId, RegionId) {
|
||||
(self.datanode_id, self.region_id)
|
||||
}
|
||||
|
||||
/// Returns the candidate lease id of a region migration's target region registration.
|
||||
pub fn candidate_lease_id(&self) -> Option<u64> {
|
||||
self.candidate_lease_id
|
||||
}
|
||||
}
|
||||
|
||||
pub type MemoryRegionKeeperRef = Arc<MemoryRegionKeeper>;
|
||||
@@ -52,7 +70,7 @@ pub type MemoryRegionKeeperRef = Arc<MemoryRegionKeeper>;
|
||||
/// - Tracks the deleting regions after the corresponding metadata is deleted.
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct MemoryRegionKeeper {
|
||||
inner: Arc<RwLock<HashMap<(DatanodeId, RegionId), RegionRole>>>,
|
||||
inner: Arc<RwLock<HashMap<(DatanodeId, RegionId), OperatingRegion>>>,
|
||||
}
|
||||
|
||||
impl MemoryRegionKeeper {
|
||||
@@ -67,19 +85,32 @@ impl MemoryRegionKeeper {
|
||||
region_id: RegionId,
|
||||
role: RegionRole,
|
||||
) -> Option<OperatingRegionGuard> {
|
||||
let mut inner = self.inner.write().unwrap();
|
||||
self.register(
|
||||
datanode_id,
|
||||
region_id,
|
||||
OperatingRegion {
|
||||
role,
|
||||
candidate_lease_id: None,
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
match inner.entry((datanode_id, region_id)) {
|
||||
Entry::Occupied(_) => None,
|
||||
Entry::Vacant(vacant_entry) => {
|
||||
vacant_entry.insert(role);
|
||||
Some(OperatingRegionGuard {
|
||||
datanode_id,
|
||||
region_id,
|
||||
inner: self.inner.clone(),
|
||||
})
|
||||
}
|
||||
}
|
||||
/// Registers the target region of a region migration as a follower with a new random
|
||||
/// candidate lease id. Returns [OperatingRegionGuard] if Region(`region_id`) on
|
||||
/// Peer(`datanode_id`) does not exist.
|
||||
pub fn register_candidate_region(
|
||||
&self,
|
||||
datanode_id: DatanodeId,
|
||||
region_id: RegionId,
|
||||
) -> Option<OperatingRegionGuard> {
|
||||
self.register(
|
||||
datanode_id,
|
||||
region_id,
|
||||
OperatingRegion {
|
||||
role: RegionRole::Follower,
|
||||
candidate_lease_id: Some(new_candidate_lease_id(rand::random)),
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
/// Returns true if the keeper contains a (`datanoe_id`, `region_id`) tuple.
|
||||
@@ -88,19 +119,19 @@ impl MemoryRegionKeeper {
|
||||
inner.contains_key(&(datanode_id, region_id))
|
||||
}
|
||||
|
||||
/// Extracts all operating regions with roles from `region_ids`.
|
||||
pub fn extract_operating_region_roles(
|
||||
/// Extracts all operating regions from `region_ids`.
|
||||
pub fn extract_operating_regions(
|
||||
&self,
|
||||
datanode_id: DatanodeId,
|
||||
region_ids: &HashSet<RegionId>,
|
||||
) -> HashMap<RegionId, RegionRole> {
|
||||
) -> HashMap<RegionId, OperatingRegion> {
|
||||
let inner = self.inner.read().unwrap();
|
||||
region_ids
|
||||
.iter()
|
||||
.filter_map(|region_id| {
|
||||
inner
|
||||
.get(&(datanode_id, *region_id))
|
||||
.map(|role| (*region_id, *role))
|
||||
.map(|region| (*region_id, *region))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
@@ -121,6 +152,38 @@ impl MemoryRegionKeeper {
|
||||
let mut inner = self.inner.write().unwrap();
|
||||
inner.clear();
|
||||
}
|
||||
|
||||
fn register(
|
||||
&self,
|
||||
datanode_id: DatanodeId,
|
||||
region_id: RegionId,
|
||||
operating_region: OperatingRegion,
|
||||
) -> Option<OperatingRegionGuard> {
|
||||
let mut inner = self.inner.write().unwrap();
|
||||
|
||||
match inner.entry((datanode_id, region_id)) {
|
||||
Entry::Occupied(_) => None,
|
||||
Entry::Vacant(vacant_entry) => {
|
||||
vacant_entry.insert(operating_region);
|
||||
Some(OperatingRegionGuard {
|
||||
datanode_id,
|
||||
region_id,
|
||||
candidate_lease_id: operating_region.candidate_lease_id,
|
||||
inner: self.inner.clone(),
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the first non-zero value of `random`, since 0 means no candidate lease id on the wire.
|
||||
fn new_candidate_lease_id(mut random: impl FnMut() -> u64) -> u64 {
|
||||
loop {
|
||||
let candidate_lease_id = random();
|
||||
if candidate_lease_id != 0 {
|
||||
return candidate_lease_id;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -130,7 +193,7 @@ mod tests {
|
||||
use store_api::region_engine::RegionRole;
|
||||
use store_api::storage::RegionId;
|
||||
|
||||
use crate::region_keeper::MemoryRegionKeeper;
|
||||
use crate::region_keeper::{MemoryRegionKeeper, OperatingRegion, new_candidate_lease_id};
|
||||
|
||||
#[test]
|
||||
fn test_opening_region_keeper() {
|
||||
@@ -153,7 +216,7 @@ mod tests {
|
||||
RegionId::from_u64(2),
|
||||
RegionId::from_u64(3),
|
||||
]);
|
||||
let output = keeper.extract_operating_region_roles(1, ®ions);
|
||||
let output = keeper.extract_operating_regions(1, ®ions);
|
||||
assert_eq!(output.len(), 2);
|
||||
|
||||
assert!(output.contains_key(&RegionId::from_u64(1)));
|
||||
@@ -165,12 +228,24 @@ mod tests {
|
||||
RegionId::from_u64(2),
|
||||
RegionId::from_u64(3),
|
||||
]);
|
||||
let output = keeper.extract_operating_region_roles(1, ®ions);
|
||||
let output = keeper.extract_operating_regions(1, ®ions);
|
||||
assert_eq!(
|
||||
output,
|
||||
HashMap::from([
|
||||
(RegionId::from_u64(1), RegionRole::Leader),
|
||||
(RegionId::from_u64(2), RegionRole::Follower),
|
||||
(
|
||||
RegionId::from_u64(1),
|
||||
OperatingRegion {
|
||||
role: RegionRole::Leader,
|
||||
candidate_lease_id: None,
|
||||
}
|
||||
),
|
||||
(
|
||||
RegionId::from_u64(2),
|
||||
OperatingRegion {
|
||||
role: RegionRole::Follower,
|
||||
candidate_lease_id: None,
|
||||
}
|
||||
),
|
||||
])
|
||||
);
|
||||
assert_eq!(keeper.len(), 2);
|
||||
@@ -182,4 +257,42 @@ mod tests {
|
||||
drop(guard2);
|
||||
assert!(keeper.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_register_candidate_region_uses_new_candidate_lease_id() {
|
||||
let keeper = MemoryRegionKeeper::new();
|
||||
let region_id = RegionId::from_u64(1);
|
||||
let regions = HashSet::from([region_id]);
|
||||
|
||||
let guard = keeper
|
||||
.register_with_role(1, region_id, RegionRole::Follower)
|
||||
.unwrap();
|
||||
assert_eq!(guard.candidate_lease_id(), None);
|
||||
assert_eq!(
|
||||
keeper.extract_operating_regions(1, ®ions)[®ion_id].candidate_lease_id,
|
||||
None
|
||||
);
|
||||
drop(guard);
|
||||
|
||||
let guard = keeper.register_candidate_region(1, region_id).unwrap();
|
||||
let first = guard.candidate_lease_id().unwrap();
|
||||
assert!(keeper.register_candidate_region(1, region_id).is_none());
|
||||
assert_eq!(
|
||||
keeper.extract_operating_regions(1, ®ions)[®ion_id],
|
||||
OperatingRegion {
|
||||
role: RegionRole::Follower,
|
||||
candidate_lease_id: Some(first),
|
||||
}
|
||||
);
|
||||
drop(guard);
|
||||
|
||||
let guard = keeper.register_candidate_region(1, region_id).unwrap();
|
||||
assert_ne!(guard.candidate_lease_id().unwrap(), first);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_new_candidate_lease_id_skips_zero() {
|
||||
let mut values = [0, 0, 7].into_iter();
|
||||
assert_eq!(new_candidate_lease_id(|| values.next().unwrap()), 7);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -68,6 +68,8 @@ use crate::key::table_name::{TableNameKey, TableNameManager};
|
||||
|
||||
/// Reserved query-context extension key for the frontend peer address that submitted a DDL request.
|
||||
pub const ORIGIN_FRONTEND_ADDR_EXTENSION_KEY: &str = "__greptime_origin_frontend.addr";
|
||||
/// Ordered source table IDs pinned by the caller of an automatic logical-table ALTER.
|
||||
pub const ALTER_LOGICAL_TABLE_IDS_EXTENSION_KEY: &str = "__greptime_alter_logical_tables.ids";
|
||||
/// Reserved query-context extension key for the authenticated database creator.
|
||||
pub const CREATE_DATABASE_CREATOR_EXTENSION_KEY: &str = "__greptime_create_database.creator";
|
||||
/// Internal gRPC metadata key for the authenticated database creator.
|
||||
@@ -1707,6 +1709,24 @@ impl QueryContext {
|
||||
&self.extensions
|
||||
}
|
||||
|
||||
pub(crate) fn pinned_logical_table_ids(&self) -> Result<Option<Vec<TableId>>> {
|
||||
self.extensions
|
||||
.get(ALTER_LOGICAL_TABLE_IDS_EXTENSION_KEY)
|
||||
.map(|ids| {
|
||||
ids.split(',')
|
||||
.map(|id| {
|
||||
id.parse::<TableId>().map_err(|error| {
|
||||
error::AlterLogicalTablesInvalidArgumentsSnafu {
|
||||
err_msg: format!("Invalid pinned logical table ID: {error}"),
|
||||
}
|
||||
.build()
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
})
|
||||
.transpose()
|
||||
}
|
||||
|
||||
/// Get the channel
|
||||
pub fn channel(&self) -> u8 {
|
||||
self.channel
|
||||
@@ -1891,6 +1911,32 @@ mod tests {
|
||||
|
||||
use super::{AlterTableTask, CreateTableTask, *};
|
||||
|
||||
#[test]
|
||||
fn test_pinned_logical_table_ids_wire_compatibility() {
|
||||
let legacy = include_bytes!(
|
||||
"../../../../../tests/compatibility/wire/read_preference/legacy_query_context.pb"
|
||||
);
|
||||
let mut context = QueryContext::from(PbQueryContext::decode(legacy.as_slice()).unwrap());
|
||||
assert_eq!(context.pinned_logical_table_ids().unwrap(), None);
|
||||
context.extensions.insert(
|
||||
"__greptime_alter_logical_tables.ids".into(),
|
||||
"1025,1024".into(),
|
||||
);
|
||||
let wire = PbQueryContext::from(context.clone()).encode_to_vec();
|
||||
let decoded = QueryContext::from(PbQueryContext::decode(wire.as_slice()).unwrap());
|
||||
assert_eq!(decoded, context);
|
||||
assert_eq!(
|
||||
decoded.pinned_logical_table_ids().unwrap(),
|
||||
Some(vec![1025, 1024])
|
||||
);
|
||||
for invalid in ["", "1024,", "1024,no", "-1", "4294967296"] {
|
||||
context
|
||||
.extensions
|
||||
.insert(ALTER_LOGICAL_TABLE_IDS_EXTENSION_KEY.into(), invalid.into());
|
||||
assert!(context.pinned_logical_table_ids().is_err(), "{invalid}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_ddl_timeout_secs() {
|
||||
assert_eq!(ddl_timeout_secs(Duration::ZERO), 0);
|
||||
|
||||
@@ -5,7 +5,10 @@ edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[features]
|
||||
testing = []
|
||||
# `datafusion-datasource` is only needed by `testing`, which builds the real hash-join
|
||||
# fixtures. `futures-util` stays a regular dependency here because the series-frame API
|
||||
# exposes `futures_util::Stream` in its public signatures.
|
||||
testing = ["dep:datafusion-datasource"]
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -22,9 +25,11 @@ common-recordbatch.workspace = true
|
||||
common-time.workspace = true
|
||||
datafusion.workspace = true
|
||||
datafusion-common.workspace = true
|
||||
datafusion-datasource = { workspace = true, optional = true }
|
||||
datafusion-expr.workspace = true
|
||||
datafusion-proto.workspace = true
|
||||
datatypes.workspace = true
|
||||
futures-util.workspace = true
|
||||
once_cell.workspace = true
|
||||
prost.workspace = true
|
||||
serde.workspace = true
|
||||
@@ -33,12 +38,13 @@ snafu.workspace = true
|
||||
sqlparser.workspace = true
|
||||
sqlparser_derive = "0.1"
|
||||
store-api.workspace = true
|
||||
tokio.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
common-base.workspace = true
|
||||
futures-util.workspace = true
|
||||
datafusion-datasource.workspace = true
|
||||
serde_json.workspace = true
|
||||
tokio.workspace = true
|
||||
tokio = { workspace = true, features = ["test-util"] }
|
||||
|
||||
[package.metadata.cargo-shear]
|
||||
# `sqlparser` is required by `sqlparser_derive`: the generated code references
|
||||
|
||||
@@ -218,6 +218,27 @@ pub enum Error {
|
||||
#[snafu(implicit)]
|
||||
location: Location,
|
||||
},
|
||||
|
||||
#[snafu(display(
|
||||
"Remote dynamic filter predicate cannot be represented on the wire: {}",
|
||||
reason
|
||||
))]
|
||||
DynFilterUnsupported {
|
||||
reason: String,
|
||||
#[snafu(implicit)]
|
||||
location: Location,
|
||||
},
|
||||
}
|
||||
|
||||
impl Error {
|
||||
/// Whether the error reports a dynamic filter predicate with no wire form.
|
||||
///
|
||||
/// Initial capture omits the refused snapshot; ongoing fanout sends an explicit
|
||||
/// `true` reset to invalidate any stale region-side predicate. Neither path fails
|
||||
/// the query.
|
||||
pub fn is_dyn_filter_unsupported(&self) -> bool {
|
||||
matches!(self, Error::DynFilterUnsupported { .. })
|
||||
}
|
||||
}
|
||||
|
||||
pub type Result<T> = std::result::Result<T, Error>;
|
||||
@@ -250,6 +271,9 @@ impl ErrorExt for Error {
|
||||
| Error::InvalidColumnPrefix { .. } => StatusCode::InvalidArguments,
|
||||
|
||||
Error::DynFilterPayloadTooLarge { .. } => StatusCode::PlanQuery,
|
||||
// An unrepresentable dynamic predicate is a transport limitation, not a
|
||||
// server failure: callers omit the initial snapshot or reset the remote predicate.
|
||||
Error::DynFilterUnsupported { .. } => StatusCode::Unsupported,
|
||||
|
||||
Error::ConvertDfRecordBatchStream { source, .. } => source.status_code(),
|
||||
|
||||
@@ -394,6 +418,15 @@ mod tests {
|
||||
StatusCode::PlanQuery
|
||||
);
|
||||
|
||||
let unsupported_error = DataFusionError::External(Box::new(Error::DynFilterUnsupported {
|
||||
reason: "no wire form".to_string(),
|
||||
location: Location::default(),
|
||||
}));
|
||||
assert_eq!(
|
||||
datafusion_status_code::<Error>(&unsupported_error, Some(StatusCode::Internal)),
|
||||
StatusCode::Unsupported
|
||||
);
|
||||
|
||||
let boundary_error =
|
||||
DataFusionError::Shared(Arc::new(DataFusionError::External(Box::new(
|
||||
BoxedError::new(common_recordbatch::error::Error::PhysicalExpr {
|
||||
|
||||
@@ -20,6 +20,7 @@ pub mod prelude;
|
||||
pub mod prometheus;
|
||||
pub mod promql_annotations;
|
||||
pub mod request;
|
||||
pub mod series_frame;
|
||||
pub mod stream;
|
||||
#[cfg(any(test, feature = "testing"))]
|
||||
pub mod test_util;
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -30,6 +30,9 @@ static GREPTIME_VALUE_CELL: OnceCell<String> = OnceCell::new();
|
||||
/// Default native histogram column name.
|
||||
static GREPTIME_NATIVE_HISTOGRAM_CELL: OnceCell<String> = OnceCell::new();
|
||||
|
||||
/// Default exemplar labels column name.
|
||||
static GREPTIME_EXEMPLAR_LABELS_CELL: OnceCell<String> = OnceCell::new();
|
||||
|
||||
pub fn set_default_prefix(prefix: Option<&str>) -> Result<()> {
|
||||
// Strip surrounding double quotes as a defensive measure against upstream
|
||||
// sources (scripts, CI, template engines, incorrect shell escaping) that may
|
||||
@@ -46,12 +49,14 @@ pub fn set_default_prefix(prefix: Option<&str>) -> Result<()> {
|
||||
GREPTIME_TIMESTAMP_CELL.get_or_init(|| GREPTIME_TIMESTAMP.to_string());
|
||||
GREPTIME_VALUE_CELL.get_or_init(|| GREPTIME_VALUE.to_string());
|
||||
GREPTIME_NATIVE_HISTOGRAM_CELL.get_or_init(|| NATIVE_HISTOGRAM_FIELD.to_string());
|
||||
GREPTIME_EXEMPLAR_LABELS_CELL.get_or_init(|| GREPTIME_EXEMPLAR_LABELS.to_string());
|
||||
}
|
||||
Some(s) if s.trim().is_empty() => {
|
||||
// use "" to disable prefix
|
||||
GREPTIME_TIMESTAMP_CELL.get_or_init(|| "timestamp".to_string());
|
||||
GREPTIME_VALUE_CELL.get_or_init(|| "value".to_string());
|
||||
GREPTIME_NATIVE_HISTOGRAM_CELL.get_or_init(|| "native_histogram".to_string());
|
||||
GREPTIME_EXEMPLAR_LABELS_CELL.get_or_init(|| "exemplar_labels".to_string());
|
||||
}
|
||||
Some(x) => {
|
||||
ensure!(
|
||||
@@ -61,6 +66,7 @@ pub fn set_default_prefix(prefix: Option<&str>) -> Result<()> {
|
||||
GREPTIME_TIMESTAMP_CELL.get_or_init(|| format!("{}_timestamp", x));
|
||||
GREPTIME_VALUE_CELL.get_or_init(|| format!("{}_value", x));
|
||||
GREPTIME_NATIVE_HISTOGRAM_CELL.get_or_init(|| format!("{}_native_histogram", x));
|
||||
GREPTIME_EXEMPLAR_LABELS_CELL.get_or_init(|| format!("{}_exemplar_labels", x));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
@@ -87,6 +93,14 @@ pub fn greptime_native_histogram() -> &'static str {
|
||||
.map_or(NATIVE_HISTOGRAM_FIELD, String::as_str)
|
||||
}
|
||||
|
||||
/// Returns the configured exemplar labels column name, or `greptime_exemplar_labels` if not set.
|
||||
#[inline]
|
||||
pub fn greptime_exemplar_labels() -> &'static str {
|
||||
GREPTIME_EXEMPLAR_LABELS_CELL
|
||||
.get()
|
||||
.map_or(GREPTIME_EXEMPLAR_LABELS, String::as_str)
|
||||
}
|
||||
|
||||
/// Default timestamp column name constant for backward compatibility.
|
||||
const GREPTIME_TIMESTAMP: &str = "greptime_timestamp";
|
||||
/// Default value column name constant for backward compatibility.
|
||||
@@ -94,7 +108,7 @@ const GREPTIME_VALUE: &str = "greptime_value";
|
||||
/// Query-visible source metric name stored in the exemplar table.
|
||||
pub const EXEMPLAR_METRIC_COLUMN: &str = "greptime_metric";
|
||||
/// JSON2 object containing exemplar-owned labels.
|
||||
pub const EXEMPLAR_LABELS_COLUMN: &str = "exemplar_labels";
|
||||
const GREPTIME_EXEMPLAR_LABELS: &str = "greptime_exemplar_labels";
|
||||
/// Stored series label that opts ordinary float samples into raw-delta math.
|
||||
pub const OTLP_AGGREGATION_TEMPORALITY_LABEL: &str = "otlp_aggregation_temporality";
|
||||
/// Authoritative raw-delta value for [`OTLP_AGGREGATION_TEMPORALITY_LABEL`].
|
||||
@@ -115,6 +129,7 @@ mod tests {
|
||||
assert_eq!(greptime_timestamp(), "greptime_timestamp");
|
||||
assert_eq!(greptime_value(), "greptime_value");
|
||||
assert_eq!(greptime_native_histogram(), "greptime_native_histogram");
|
||||
assert_eq!(greptime_exemplar_labels(), "greptime_exemplar_labels");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -123,6 +138,7 @@ mod tests {
|
||||
assert_eq!(greptime_timestamp(), "timestamp");
|
||||
assert_eq!(greptime_value(), "value");
|
||||
assert_eq!(greptime_native_histogram(), "native_histogram");
|
||||
assert_eq!(greptime_exemplar_labels(), "exemplar_labels");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -132,6 +148,7 @@ mod tests {
|
||||
assert_eq!(greptime_timestamp(), "timestamp");
|
||||
assert_eq!(greptime_value(), "value");
|
||||
assert_eq!(greptime_native_histogram(), "native_histogram");
|
||||
assert_eq!(greptime_exemplar_labels(), "exemplar_labels");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -140,6 +157,7 @@ mod tests {
|
||||
assert_eq!(greptime_timestamp(), "mydb_timestamp");
|
||||
assert_eq!(greptime_value(), "mydb_value");
|
||||
assert_eq!(greptime_native_histogram(), "mydb_native_histogram");
|
||||
assert_eq!(greptime_exemplar_labels(), "mydb_exemplar_labels");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -113,17 +113,6 @@ pub fn promql_annotation_collector(query_id: &str) -> PromqlAnnotationCollector
|
||||
collector
|
||||
}
|
||||
|
||||
pub fn get_promql_annotation_collector(query_id: &str) -> Option<PromqlAnnotationCollector> {
|
||||
let mut registry = PROMQL_ANNOTATION_REGISTRY
|
||||
.lock()
|
||||
.expect("promql annotation registry poisoned");
|
||||
registry.retain(|_, collector| collector.strong_count() > 0);
|
||||
registry
|
||||
.get(query_id)
|
||||
.and_then(Weak::upgrade)
|
||||
.map(|inner| PromqlAnnotationCollector { inner })
|
||||
}
|
||||
|
||||
fn append_unique(target: &mut Vec<String>, values: impl Iterator<Item = String>) {
|
||||
let mut seen = target.iter().cloned().collect::<BTreeSet<_>>();
|
||||
for value in values {
|
||||
@@ -156,15 +145,30 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn registry_prunes_dead_collectors() {
|
||||
let key = "registry_prunes_dead_collectors";
|
||||
fn collector_is_shared_while_a_strong_reference_lives() {
|
||||
let key = "collector_is_shared_while_a_strong_reference_lives";
|
||||
let first = promql_annotation_collector(key);
|
||||
first.record_warning("shared");
|
||||
let second = promql_annotation_collector(key);
|
||||
|
||||
let mut warnings = vec![];
|
||||
let mut infos = vec![];
|
||||
second.append_to(&mut warnings, &mut infos);
|
||||
assert_eq!(warnings, vec!["shared"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_dropped_collector_is_not_reused() {
|
||||
let key = "a_dropped_collector_is_not_reused";
|
||||
{
|
||||
let collector = promql_annotation_collector(key);
|
||||
assert!(get_promql_annotation_collector(key).is_some());
|
||||
drop(collector);
|
||||
let stale = promql_annotation_collector(key);
|
||||
stale.record_warning("stale");
|
||||
}
|
||||
|
||||
assert!(get_promql_annotation_collector(key).is_none());
|
||||
assert!(!PROMQL_ANNOTATION_REGISTRY.lock().unwrap().contains_key(key));
|
||||
let current = promql_annotation_collector(key);
|
||||
let mut warnings = vec![];
|
||||
let mut infos = vec![];
|
||||
current.append_to(&mut warnings, &mut infos);
|
||||
assert!(warnings.is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
+1949
-84
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,194 @@
|
||||
// Copyright 2023 Greptime Team
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
//! Test-only helpers that produce *real* DataFusion dynamic filters.
|
||||
//!
|
||||
//! A `HashTableLookupExpr` built by hand always has `build_lease = None`, so it cannot
|
||||
//! prove that build-side membership recovery works. These helpers run an actual
|
||||
//! `HashJoinExec`, which publishes lookups backed by real build leases, and return the
|
||||
//! code of the dynamic filter it produced.
|
||||
//!
|
||||
//! The helpers live behind `test`/the `testing` feature so both `common-query` and the
|
||||
//! distributed-plan tests can exercise the same fixture.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use datafusion::arrow::array::{ArrayRef, StringArray};
|
||||
use datafusion::arrow::datatypes::{DataType, Field, Schema};
|
||||
use datafusion::arrow::record_batch::RecordBatch;
|
||||
use datafusion::execution::TaskContext;
|
||||
use datafusion::execution::config::SessionConfig;
|
||||
use datafusion::execution::session_state::SessionStateBuilder;
|
||||
use datafusion::physical_expr::expressions::{Column, DynamicFilterPhysicalExpr, lit};
|
||||
use datafusion::physical_plan::filter::FilterExec;
|
||||
use datafusion::physical_plan::joins::{HashJoinExec, PartitionMode};
|
||||
use datafusion::physical_plan::repartition::RepartitionExec;
|
||||
use datafusion::physical_plan::{ExecutionPlan, Partitioning, PhysicalExpr};
|
||||
use datafusion_common::config::ConfigOptions;
|
||||
use datafusion_common::{JoinType, NullEquality};
|
||||
use datafusion_datasource::memory::MemorySourceConfig;
|
||||
use futures_util::TryStreamExt;
|
||||
|
||||
/// A real hash-join dynamic filter and the probe schema it is bound to.
|
||||
pub struct RealDynFilter {
|
||||
/// The predicate DataFusion published for the join's probe side.
|
||||
pub expr: Arc<dyn PhysicalExpr>,
|
||||
/// Schema of the probe side the predicate applies to.
|
||||
pub probe_schema: Arc<Schema>,
|
||||
}
|
||||
|
||||
/// Schema with a single nullable column.
|
||||
pub fn one_column_schema(name: &str, data_type: DataType) -> Arc<Schema> {
|
||||
Arc::new(Schema::new(vec![Field::new(name, data_type, true)]))
|
||||
}
|
||||
|
||||
/// Turns one column vector per partition into one `RecordBatch` per partition.
|
||||
pub fn partitions(schema: &Arc<Schema>, columns: Vec<Vec<ArrayRef>>) -> Vec<Vec<RecordBatch>> {
|
||||
columns
|
||||
.into_iter()
|
||||
.map(|columns| vec![RecordBatch::try_new(Arc::clone(schema), columns).unwrap()])
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// A column reference by name and index.
|
||||
pub fn key(name: &str, index: usize) -> Arc<dyn PhysicalExpr> {
|
||||
Arc::new(Column::new(name, index))
|
||||
}
|
||||
|
||||
/// A `Utf8` array.
|
||||
pub fn utf8(values: &[&str]) -> ArrayRef {
|
||||
Arc::new(StringArray::from(values.to_vec()))
|
||||
}
|
||||
|
||||
/// Runs a real `HashJoinExec` and returns the dynamic filter it published.
|
||||
///
|
||||
/// The join is forced onto the `Map` pushdown strategy (the only strategy that
|
||||
/// produces a runtime lookup) by setting the `IN`-list pushdown limit to zero, and
|
||||
/// both children are hash-partitioned on the complete join-key vector, which is what
|
||||
/// DataFusion requires before it publishes a partitioned dynamic filter.
|
||||
pub async fn run_real_hash_join(
|
||||
partition_count: usize,
|
||||
left_schema: Arc<Schema>,
|
||||
right_schema: Arc<Schema>,
|
||||
build_partitions: Vec<Vec<RecordBatch>>,
|
||||
probe_partitions: Vec<Vec<RecordBatch>>,
|
||||
on: Vec<(Arc<dyn PhysicalExpr>, Arc<dyn PhysicalExpr>)>,
|
||||
) -> RealDynFilter {
|
||||
assert!(partition_count >= 1);
|
||||
|
||||
let left_scan: Arc<dyn ExecutionPlan> =
|
||||
MemorySourceConfig::try_new_exec(&build_partitions, Arc::clone(&left_schema), None)
|
||||
.unwrap();
|
||||
let right_scan: Arc<dyn ExecutionPlan> =
|
||||
MemorySourceConfig::try_new_exec(&probe_partitions, Arc::clone(&right_schema), None)
|
||||
.unwrap();
|
||||
|
||||
let (left, right_scan) = if partition_count > 1 {
|
||||
// Hash on the complete join-key vector on both sides, like the real plan does.
|
||||
let left_partitioning = Partitioning::Hash(
|
||||
on.iter().map(|(build, _)| Arc::clone(build)).collect(),
|
||||
partition_count,
|
||||
);
|
||||
let right_partitioning = Partitioning::Hash(
|
||||
on.iter().map(|(_, probe)| Arc::clone(probe)).collect(),
|
||||
partition_count,
|
||||
);
|
||||
(
|
||||
Arc::new(RepartitionExec::try_new(left_scan, left_partitioning).unwrap())
|
||||
as Arc<dyn ExecutionPlan>,
|
||||
Arc::new(RepartitionExec::try_new(right_scan, right_partitioning).unwrap())
|
||||
as Arc<dyn ExecutionPlan>,
|
||||
)
|
||||
} else {
|
||||
(left_scan, right_scan)
|
||||
};
|
||||
|
||||
let probe_filter = Arc::new(DynamicFilterPhysicalExpr::new(
|
||||
on.iter().map(|(_, probe)| Arc::clone(probe)).collect(),
|
||||
lit(true),
|
||||
));
|
||||
let dyn_filter: Arc<dyn PhysicalExpr> = Arc::clone(&probe_filter) as _;
|
||||
// The probe subtree must reference the produced filter, otherwise the join never
|
||||
// publishes it.
|
||||
let right: Arc<dyn ExecutionPlan> =
|
||||
Arc::new(FilterExec::try_new(Arc::clone(&dyn_filter), right_scan).unwrap());
|
||||
|
||||
let join = HashJoinExec::try_new(
|
||||
left,
|
||||
right,
|
||||
on,
|
||||
None,
|
||||
&JoinType::Inner,
|
||||
None,
|
||||
PartitionMode::Partitioned,
|
||||
NullEquality::NullEqualsNothing,
|
||||
false,
|
||||
)
|
||||
.unwrap()
|
||||
.with_dynamic_filter_expr(Arc::clone(&probe_filter))
|
||||
.unwrap();
|
||||
let join: Arc<dyn ExecutionPlan> = Arc::new(join);
|
||||
|
||||
let mut options = ConfigOptions::default();
|
||||
options.optimizer.hash_join_inlist_pushdown_max_size = 0;
|
||||
let session_config = SessionConfig::from(options);
|
||||
let state = SessionStateBuilder::new()
|
||||
.with_config(session_config)
|
||||
.with_default_features()
|
||||
.build();
|
||||
let task_ctx = Arc::new(TaskContext::from(&state));
|
||||
|
||||
// Every build partition must report before the filter is finalized, so all
|
||||
// partition streams have to make progress concurrently.
|
||||
let streams = (0..partition_count)
|
||||
.map(|partition| {
|
||||
let join = Arc::clone(&join);
|
||||
let task_ctx = Arc::clone(&task_ctx);
|
||||
async move {
|
||||
let stream = join.execute(partition, task_ctx).unwrap();
|
||||
stream.try_collect::<Vec<_>>().await.unwrap();
|
||||
}
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
futures_util::future::join_all(streams).await;
|
||||
|
||||
RealDynFilter {
|
||||
expr: probe_filter.current().unwrap(),
|
||||
probe_schema: right_schema,
|
||||
}
|
||||
}
|
||||
|
||||
/// Build and probe batches for a `Utf8` join over distinct keys.
|
||||
///
|
||||
/// Both sides start as one partition; the fixture hash-repartitions them so every hash
|
||||
/// partition holds rows and DataFusion produces one filter branch per partition. Also
|
||||
/// returns every distinct key.
|
||||
pub fn utf8_join(
|
||||
partition_count: usize,
|
||||
) -> (Vec<Vec<RecordBatch>>, Vec<Vec<RecordBatch>>, Vec<String>) {
|
||||
let schema = one_column_schema("trace_id", DataType::Utf8);
|
||||
let values = (0..partition_count * 8)
|
||||
.map(|i| format!("trace-{i:02}"))
|
||||
.collect::<Vec<_>>();
|
||||
let borrowed = values.iter().map(String::as_str).collect::<Vec<_>>();
|
||||
let build = partitions(&schema, vec![vec![utf8(&borrowed)]]);
|
||||
// Probe rows include every member plus keys that belong to no build side.
|
||||
let mut probe_values = borrowed.clone();
|
||||
let misses = (0..partition_count * 4)
|
||||
.map(|i| format!("miss-{i:02}"))
|
||||
.collect::<Vec<_>>();
|
||||
probe_values.extend(misses.iter().map(String::as_str));
|
||||
let probe = partitions(&schema, vec![vec![utf8(&probe_values)]]);
|
||||
(build, probe, values)
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,498 @@
|
||||
// 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::pin::Pin;
|
||||
use std::sync::Arc;
|
||||
use std::task::{Context, Poll};
|
||||
|
||||
use common_error::ext::BoxedError;
|
||||
use datatypes::arrow::array::{Array, Float64Array, UInt32Array};
|
||||
use datatypes::arrow::buffer::{Buffer, ScalarBuffer};
|
||||
use datatypes::series::SeriesOrdering;
|
||||
use datatypes::series::histogram::{BucketSideView, CounterResetHint, HistogramBatchBuilder};
|
||||
use datatypes::series::raw::{RawSeriesChunk, RawTimestamps};
|
||||
use datatypes::series::samples::{
|
||||
DenseSamplesRef, FieldSpec, HistogramSamples, SampleRef, Samples, SeriesFields, SeriesSchema,
|
||||
};
|
||||
use datatypes::series::{Label, SeriesLabels};
|
||||
use futures_util::{Stream, StreamExt};
|
||||
use store_api::region_engine::{RawLabelSource, RawSeriesStream, SendableRawSeriesStream};
|
||||
|
||||
use super::super::{pack_raw_series, unpack_raw_series};
|
||||
|
||||
struct RawFixture {
|
||||
schema: Arc<SeriesSchema>,
|
||||
binding: RawLabelSource,
|
||||
chunk: Option<RawSeriesChunk>,
|
||||
}
|
||||
|
||||
impl Stream for RawFixture {
|
||||
type Item = Result<RawSeriesChunk, BoxedError>;
|
||||
|
||||
fn poll_next(mut self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Option<Self::Item>> {
|
||||
Poll::Ready(self.chunk.take().map(Ok))
|
||||
}
|
||||
}
|
||||
|
||||
impl RawSeriesStream for RawFixture {
|
||||
fn schema(&self) -> &Arc<SeriesSchema> {
|
||||
&self.schema
|
||||
}
|
||||
|
||||
fn label_source(&self) -> &RawLabelSource {
|
||||
&self.binding
|
||||
}
|
||||
|
||||
fn ordering(&self) -> SeriesOrdering {
|
||||
SeriesOrdering::Contiguous
|
||||
}
|
||||
}
|
||||
|
||||
fn histogram_batch() -> Arc<datatypes::series::histogram::HistogramBatch> {
|
||||
let custom = [1.5, 4.5];
|
||||
let positive_offsets = [1];
|
||||
let positive_lengths = [2];
|
||||
let positive_buckets = [3.25, 7.5];
|
||||
let negative_offsets = [-2];
|
||||
let negative_lengths = [1];
|
||||
let negative_buckets = [0.75];
|
||||
let mut builder = HistogramBatchBuilder::new();
|
||||
for (sum, start_timestamp) in [(10.5, Some(-123)), (-9.5, Some(456)), (7.25, None)] {
|
||||
builder
|
||||
.push(datatypes::series::histogram::HistogramView {
|
||||
schema: -7,
|
||||
zero_threshold: 0.125,
|
||||
sum,
|
||||
count: 17.25,
|
||||
zero_count: 2.5,
|
||||
reset_hint: CounterResetHint::Unrecognized(37),
|
||||
start_timestamp,
|
||||
custom_values: &custom,
|
||||
positive: BucketSideView {
|
||||
span_offsets: &positive_offsets,
|
||||
span_lengths: &positive_lengths,
|
||||
buckets: &positive_buckets,
|
||||
},
|
||||
negative: BucketSideView {
|
||||
span_offsets: &negative_offsets,
|
||||
span_lengths: &negative_lengths,
|
||||
buckets: &negative_buckets,
|
||||
},
|
||||
})
|
||||
.unwrap();
|
||||
}
|
||||
builder.finish().unwrap()
|
||||
}
|
||||
|
||||
fn assert_histogram(
|
||||
view: datatypes::series::histogram::HistogramView<'_>,
|
||||
sum: f64,
|
||||
start: Option<i64>,
|
||||
) {
|
||||
assert_eq!(view.schema, -7);
|
||||
assert_eq!(view.zero_threshold, 0.125);
|
||||
assert_eq!(view.sum.to_bits(), sum.to_bits());
|
||||
assert_eq!(view.count, 17.25);
|
||||
assert_eq!(view.zero_count, 2.5);
|
||||
assert_eq!(view.reset_hint, CounterResetHint::Unrecognized(37));
|
||||
assert_eq!(view.start_timestamp, start);
|
||||
assert_eq!(view.custom_values, [1.5, 4.5]);
|
||||
assert_eq!(view.positive.span_offsets, [1]);
|
||||
assert_eq!(view.positive.span_lengths, [2]);
|
||||
assert_eq!(view.positive.buckets, [3.25, 7.5]);
|
||||
assert_eq!(view.negative.span_offsets, [-2]);
|
||||
assert_eq!(view.negative.span_lengths, [1]);
|
||||
assert_eq!(view.negative.buckets, [0.75]);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn streaming_round_trip_preserves_sliced_multifield_payload_and_owners() {
|
||||
let schema = Arc::new(SeriesSchema {
|
||||
fields: vec!["float", "histogram", "mixed"]
|
||||
.into_iter()
|
||||
.map(|name| FieldSpec {
|
||||
name: Arc::from(name),
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.into(),
|
||||
eval_grid: None,
|
||||
});
|
||||
let time_owner = ScalarBuffer::from(vec![0, 11, 22, 33, 44]);
|
||||
let times = RawTimestamps::try_new(time_owner.slice(1, 3)).unwrap();
|
||||
let float_owner = Float64Array::from(vec![
|
||||
Some(90.0),
|
||||
None,
|
||||
Some(f64::from_bits(0x7ff8_0000_0000_0042)),
|
||||
Some(-0.0),
|
||||
Some(80.0),
|
||||
]);
|
||||
let float_a = float_owner.slice(1, 2);
|
||||
let float_b = float_owner.slice(3, 1);
|
||||
let floats = Samples::try_from_chunks(vec![
|
||||
Samples::from_float(float_a.clone()),
|
||||
Samples::from_float(float_b.clone()),
|
||||
])
|
||||
.unwrap();
|
||||
|
||||
let table_owner = histogram_batch();
|
||||
let table_weak = Arc::downgrade(&table_owner);
|
||||
let source_table = table_owner.as_arrow().clone();
|
||||
let sliced_table = Arc::new(
|
||||
datatypes::series::histogram::HistogramBatch::try_from_arrow(source_table.slice(1, 2))
|
||||
.unwrap(),
|
||||
);
|
||||
let sliced_weak = Arc::downgrade(&sliced_table);
|
||||
let index_owner = UInt32Array::from(vec![Some(2), Some(0), Some(1), Some(0), Some(1)]);
|
||||
let indices = index_owner.slice(1, 3);
|
||||
let hist = Samples::try_from_histogram(indices.clone(), sliced_table.clone()).unwrap();
|
||||
let mixed_float_owner = Float64Array::from(vec![Some(1.25), None, None]);
|
||||
let mixed_index_owner = UInt32Array::from(vec![None, Some(0), None]);
|
||||
let mixed = Samples::try_from_mixed(
|
||||
mixed_float_owner.clone(),
|
||||
HistogramSamples::try_new(mixed_index_owner.clone(), sliced_table.clone()).unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
let chunk = RawSeriesChunk::try_new(
|
||||
&schema,
|
||||
Buffer::from(vec![0xaa_u8, 0x10, 0xbb]),
|
||||
Some(
|
||||
SeriesLabels::try_new(
|
||||
Some(Arc::from("cpu")),
|
||||
vec![Label {
|
||||
name: Arc::from("host"),
|
||||
value: Arc::from("a"),
|
||||
}],
|
||||
)
|
||||
.unwrap(),
|
||||
),
|
||||
times,
|
||||
SeriesFields::try_from_vec(vec![floats, hist, mixed]).unwrap(),
|
||||
true,
|
||||
)
|
||||
.unwrap();
|
||||
let input_times_ptr = chunk.time.as_buffer().as_ptr();
|
||||
let input_float_ptr = float_a.values().as_ptr();
|
||||
let input_hist_indices_ptr = indices.values().as_ptr();
|
||||
let input_mixed_float_ptr = mixed_float_owner.values().as_ptr();
|
||||
let input_mixed_indices_ptr = mixed_index_owner.values().as_ptr();
|
||||
|
||||
let input: SendableRawSeriesStream = Box::pin(RawFixture {
|
||||
schema: schema.clone(),
|
||||
binding: RawLabelSource::Explicit,
|
||||
chunk: Some(chunk),
|
||||
});
|
||||
let frames = pack_raw_series(input).unwrap();
|
||||
let mut decoded = unpack_raw_series(frames, Some(schema)).unwrap();
|
||||
let mut output = Vec::new();
|
||||
while let Some(item) = decoded.next().await {
|
||||
output.push(item.unwrap());
|
||||
}
|
||||
assert_eq!(
|
||||
output.len(),
|
||||
2,
|
||||
"one bounded batch still decodes one chunk per union-of-segment row"
|
||||
);
|
||||
assert_eq!(output[0].time.len(), 2);
|
||||
assert!(
|
||||
!output[0].is_last,
|
||||
"a chunk that stops at the field segment boundary is not final"
|
||||
);
|
||||
assert_eq!(output[1].time.len(), 1);
|
||||
assert!(output[1].is_last);
|
||||
assert_eq!(
|
||||
output[0].fields.get(0).unwrap().segments().len(),
|
||||
1,
|
||||
"the decoded chunk is dense again after the frame round trip"
|
||||
);
|
||||
|
||||
// The batch now holds both rows, so its per-row Arrow constituents are concatenated: multi-row
|
||||
// values are copied rather than aliasing the source slices. Multi-row copying is expected and
|
||||
// does not change contents, offsets, or owner cleanup; only genuinely single-row frames keep
|
||||
// the buffers by pointer (see the single-row zero-copy test below).
|
||||
let DenseSamplesRef::Float(decoded_float) = output[0].fields.get(0).unwrap().dense().unwrap()
|
||||
else {
|
||||
panic!("expected float")
|
||||
};
|
||||
assert_ne!(
|
||||
decoded_float.values().as_ptr(),
|
||||
input_float_ptr,
|
||||
"multi-row concatenation copies float values"
|
||||
);
|
||||
assert_eq!(decoded_float.len(), 2);
|
||||
assert!(!decoded_float.is_valid(0));
|
||||
assert_eq!(
|
||||
decoded_float.value(1).to_bits(),
|
||||
f64::from_bits(0x7ff8_0000_0000_0042).to_bits()
|
||||
);
|
||||
let DenseSamplesRef::Histogram(decoded_hist) =
|
||||
output[0].fields.get(1).unwrap().dense().unwrap()
|
||||
else {
|
||||
panic!("expected histogram")
|
||||
};
|
||||
assert_ne!(
|
||||
decoded_hist.indices().values().as_ptr(),
|
||||
input_hist_indices_ptr,
|
||||
"multi-row concatenation copies histogram indices"
|
||||
);
|
||||
assert!(
|
||||
!decoded_hist
|
||||
.batch()
|
||||
.as_arrow()
|
||||
.to_data()
|
||||
.ptr_eq(&sliced_table.as_arrow().to_data()),
|
||||
"multi-row concatenation copies the histogram table"
|
||||
);
|
||||
let DenseSamplesRef::Mixed(decoded_mixed) = output[0].fields.get(2).unwrap().dense().unwrap()
|
||||
else {
|
||||
panic!("expected mixed")
|
||||
};
|
||||
assert_ne!(
|
||||
decoded_mixed.floats().values().as_ptr(),
|
||||
input_mixed_float_ptr
|
||||
);
|
||||
assert_ne!(
|
||||
decoded_mixed.histograms().indices().values().as_ptr(),
|
||||
input_mixed_indices_ptr
|
||||
);
|
||||
assert!(
|
||||
!decoded_mixed
|
||||
.histograms()
|
||||
.batch()
|
||||
.as_arrow()
|
||||
.to_data()
|
||||
.ptr_eq(&sliced_table.as_arrow().to_data()),
|
||||
"multi-row concatenation copies the mixed histogram table"
|
||||
);
|
||||
let first_times = output[0].time.as_buffer();
|
||||
assert_ne!(
|
||||
first_times.as_ptr(),
|
||||
input_times_ptr,
|
||||
"multi-row concatenation copies timestamps"
|
||||
);
|
||||
assert_eq!(&first_times[..], &[11_i64, 22]);
|
||||
|
||||
drop(decoded);
|
||||
drop(time_owner);
|
||||
drop(float_owner);
|
||||
drop(float_a);
|
||||
drop(float_b);
|
||||
drop(index_owner);
|
||||
drop(indices);
|
||||
drop(mixed_float_owner);
|
||||
drop(mixed_index_owner);
|
||||
drop(source_table);
|
||||
drop(table_owner);
|
||||
drop(sliced_table);
|
||||
assert!(table_weak.upgrade().is_none());
|
||||
assert!(sliced_weak.upgrade().is_none());
|
||||
|
||||
let expected_histograms = [(-9.5, Some(456)), (7.25, None), (-9.5, Some(456))];
|
||||
let mut times_seen = Vec::new();
|
||||
let mut float_seen = Vec::new();
|
||||
let mut histogram_seen = Vec::new();
|
||||
let mut mixed_seen = Vec::new();
|
||||
for chunk in &output {
|
||||
assert_eq!(chunk.primary_key.as_slice(), [0xaa, 0x10, 0xbb]);
|
||||
assert_eq!(chunk.metric.as_ref().unwrap().name(), Some("cpu"));
|
||||
assert_eq!(chunk.metric.as_ref().unwrap().get("host"), Some("a"));
|
||||
// Only the row that ends the chunk in the source stream is final.
|
||||
assert_eq!(chunk.is_last, times_seen.len() + chunk.time.len() == 3);
|
||||
for i in 0..chunk.time.len() {
|
||||
let position = times_seen.len();
|
||||
times_seen.push(chunk.time.timestamp(i).unwrap());
|
||||
match chunk.fields.get(0).unwrap().sample(i) {
|
||||
SampleRef::Float(value) => float_seen.push(Some(value.to_bits())),
|
||||
SampleRef::Missing => float_seen.push(None),
|
||||
SampleRef::Histogram(_) => panic!("expected float field"),
|
||||
}
|
||||
let SampleRef::Histogram(value) = chunk.fields.get(1).unwrap().sample(i) else {
|
||||
panic!("expected histogram")
|
||||
};
|
||||
let (sum, start) = expected_histograms[position];
|
||||
assert_histogram(value, sum, start);
|
||||
histogram_seen.push(value.sum);
|
||||
match (position, chunk.fields.get(2).unwrap().sample(i)) {
|
||||
(0, SampleRef::Float(value)) => mixed_seen.push(Some(value.to_bits())),
|
||||
(1, SampleRef::Histogram(value)) => {
|
||||
assert_histogram(value, -9.5, Some(456));
|
||||
mixed_seen.push(None);
|
||||
}
|
||||
(2, SampleRef::Missing) => mixed_seen.push(None),
|
||||
_ => panic!("mixed payload variant did not match expected position {position}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
assert_eq!(times_seen, [11, 22, 33]);
|
||||
assert_eq!(
|
||||
float_seen,
|
||||
[
|
||||
None,
|
||||
Some(f64::from_bits(0x7ff8_0000_0000_0042).to_bits()),
|
||||
Some((-0.0_f64).to_bits())
|
||||
]
|
||||
);
|
||||
assert_eq!(histogram_seen, [-9.5, 7.25, -9.5]);
|
||||
assert_eq!(mixed_seen, [Some(1.25_f64.to_bits()), None, None]);
|
||||
}
|
||||
|
||||
/// One row of one sample, with payload arrays as nonzero-offset slices of larger owners: the
|
||||
/// decoded chunk keeps the float and time buffers by pointer, and values stay readable and bit-exact
|
||||
/// after every source owner is dropped.
|
||||
#[tokio::test]
|
||||
async fn single_row_sliced_payload_keeps_zero_copy_buffers_and_releases_owners() {
|
||||
let schema = Arc::new(SeriesSchema {
|
||||
fields: vec!["float", "histogram", "mixed"]
|
||||
.into_iter()
|
||||
.map(|name| FieldSpec {
|
||||
name: Arc::from(name),
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.into(),
|
||||
eval_grid: None,
|
||||
});
|
||||
let metric = SeriesLabels::try_new(
|
||||
Some(Arc::from("cpu")),
|
||||
vec![Label {
|
||||
name: Arc::from("host"),
|
||||
value: Arc::from("a"),
|
||||
}],
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let time_owner = ScalarBuffer::from(vec![0_i64, 11, 22]);
|
||||
let times = RawTimestamps::try_new(time_owner.slice(1, 1)).unwrap();
|
||||
let float_owner = Float64Array::from(vec![
|
||||
Some(90.0),
|
||||
Some(f64::from_bits(0x7ff8_0000_0000_0042)),
|
||||
]);
|
||||
let float = float_owner.slice(1, 1);
|
||||
let table_owner = histogram_batch();
|
||||
let table_weak = Arc::downgrade(&table_owner);
|
||||
let source_table = table_owner.as_arrow().clone();
|
||||
let sliced_table = Arc::new(
|
||||
datatypes::series::histogram::HistogramBatch::try_from_arrow(source_table.slice(1, 1))
|
||||
.unwrap(),
|
||||
);
|
||||
let sliced_weak = Arc::downgrade(&sliced_table);
|
||||
let index_owner = UInt32Array::from(vec![Some(3), Some(0)]);
|
||||
let indices = index_owner.slice(1, 1);
|
||||
let hist = Samples::try_from_histogram(indices.clone(), sliced_table.clone()).unwrap();
|
||||
let mixed_float_owner = Float64Array::from(vec![Some(0.0), None]);
|
||||
let mixed_floats = mixed_float_owner.slice(1, 1);
|
||||
let mixed_index_owner = UInt32Array::from(vec![None, Some(0)]);
|
||||
let mixed_indices = mixed_index_owner.slice(1, 1);
|
||||
let mixed = Samples::try_from_mixed(
|
||||
mixed_floats.clone(),
|
||||
HistogramSamples::try_new(mixed_indices.clone(), sliced_table.clone()).unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
let chunk = RawSeriesChunk::try_new(
|
||||
&schema,
|
||||
Buffer::from(vec![0xaa_u8, 0x10, 0xbb]),
|
||||
Some(metric),
|
||||
times,
|
||||
SeriesFields::try_from_vec(vec![Samples::from_float(float.clone()), hist, mixed]).unwrap(),
|
||||
true,
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let input_times_ptr = chunk.time.as_buffer().as_ptr();
|
||||
let input_float_ptr = float.values().as_ptr();
|
||||
let input_mixed_float_ptr = mixed_floats.values().as_ptr();
|
||||
|
||||
let input: SendableRawSeriesStream = Box::pin(RawFixture {
|
||||
schema: schema.clone(),
|
||||
binding: RawLabelSource::Explicit,
|
||||
chunk: Some(chunk),
|
||||
});
|
||||
let frames = pack_raw_series(input).unwrap();
|
||||
let mut decoded = unpack_raw_series(frames, Some(schema)).unwrap();
|
||||
let mut output = Vec::new();
|
||||
while let Some(item) = decoded.next().await {
|
||||
output.push(item.unwrap());
|
||||
}
|
||||
assert_eq!(output.len(), 1, "one sample packs as one row");
|
||||
assert_eq!(output[0].time.len(), 1);
|
||||
assert!(output[0].is_last);
|
||||
|
||||
let DenseSamplesRef::Float(decoded_float) = output[0].fields.get(0).unwrap().dense().unwrap()
|
||||
else {
|
||||
panic!("expected float")
|
||||
};
|
||||
assert_eq!(decoded_float.values().as_ptr(), input_float_ptr);
|
||||
let DenseSamplesRef::Histogram(decoded_hist) =
|
||||
output[0].fields.get(1).unwrap().dense().unwrap()
|
||||
else {
|
||||
panic!("expected histogram")
|
||||
};
|
||||
assert!(decoded_hist.indices().is_valid(0));
|
||||
assert_eq!(decoded_hist.indices().value(0), 0);
|
||||
assert_histogram(decoded_hist.batch().view(0).unwrap(), -9.5, Some(456));
|
||||
let DenseSamplesRef::Mixed(decoded_mixed) = output[0].fields.get(2).unwrap().dense().unwrap()
|
||||
else {
|
||||
panic!("expected mixed")
|
||||
};
|
||||
assert_eq!(
|
||||
decoded_mixed.floats().values().as_ptr(),
|
||||
input_mixed_float_ptr
|
||||
);
|
||||
assert!(decoded_mixed.floats().is_null(0));
|
||||
assert!(decoded_mixed.histograms().indices().is_valid(0));
|
||||
assert_eq!(decoded_mixed.histograms().indices().value(0), 0);
|
||||
assert_histogram(
|
||||
decoded_mixed.histograms().batch().view(0).unwrap(),
|
||||
-9.5,
|
||||
Some(456),
|
||||
);
|
||||
assert_eq!(output[0].time.as_buffer().as_ptr(), input_times_ptr);
|
||||
|
||||
// The decoded chunk owns the slices, so the source owners can go while the values remain
|
||||
// valid and bit-exact.
|
||||
drop(decoded);
|
||||
drop(time_owner);
|
||||
drop(float_owner);
|
||||
drop(float);
|
||||
drop(index_owner);
|
||||
drop(indices);
|
||||
drop(mixed_float_owner);
|
||||
drop(mixed_floats);
|
||||
drop(mixed_index_owner);
|
||||
drop(mixed_indices);
|
||||
drop(source_table);
|
||||
drop(table_owner);
|
||||
drop(sliced_table);
|
||||
assert!(table_weak.upgrade().is_none());
|
||||
assert!(sliced_weak.upgrade().is_none());
|
||||
|
||||
let chunk = &output[0];
|
||||
assert_eq!(chunk.primary_key.as_slice(), [0xaa, 0x10, 0xbb]);
|
||||
assert_eq!(chunk.metric.as_ref().unwrap().name(), Some("cpu"));
|
||||
assert_eq!(chunk.metric.as_ref().unwrap().get("host"), Some("a"));
|
||||
assert_eq!(chunk.time.timestamp(0), Some(11));
|
||||
match chunk.fields.get(0).unwrap().sample(0) {
|
||||
SampleRef::Float(value) => assert_eq!(
|
||||
value.to_bits(),
|
||||
f64::from_bits(0x7ff8_0000_0000_0042).to_bits()
|
||||
),
|
||||
SampleRef::Missing | SampleRef::Histogram(_) => panic!("expected float field"),
|
||||
}
|
||||
let SampleRef::Histogram(value) = chunk.fields.get(1).unwrap().sample(0) else {
|
||||
panic!("expected histogram")
|
||||
};
|
||||
assert_histogram(value, -9.5, Some(456));
|
||||
let SampleRef::Histogram(value) = chunk.fields.get(2).unwrap().sample(0) else {
|
||||
panic!("expected mixed histogram")
|
||||
};
|
||||
assert_histogram(value, -9.5, Some(456));
|
||||
}
|
||||
@@ -0,0 +1,412 @@
|
||||
// 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::io::Cursor;
|
||||
use std::sync::Arc;
|
||||
|
||||
use common_error::ext::BoxedError;
|
||||
use common_recordbatch::DfSendableRecordBatchStream;
|
||||
use datatypes::arrow::compute::concat_batches;
|
||||
use datatypes::arrow::ipc::{reader::StreamReader, writer::StreamWriter};
|
||||
use datatypes::arrow::record_batch::RecordBatch;
|
||||
use datatypes::series::aggregate_state::{
|
||||
AggregateStateKind, AggregateStateSchema, AggregateStateValues, StateComponent, StatePayload,
|
||||
StateSeries,
|
||||
};
|
||||
use datatypes::series::frame::{FrameLabelMode, StateFrameRow};
|
||||
use datatypes::series::samples::{FieldSpec, SeriesSchema};
|
||||
use datatypes::series::time::{GridSpan, TimeAxis};
|
||||
use datatypes::series::{Label, SeriesLabels};
|
||||
use futures_util::StreamExt;
|
||||
|
||||
use super::super::{
|
||||
SendableStateSeriesStream, pack_aggregate_state, pack_evaluated_series, unpack_aggregate_state,
|
||||
unpack_evaluated_series,
|
||||
};
|
||||
use super::{df_source, evaluated_grid, evaluated_schema};
|
||||
|
||||
fn group() -> SeriesLabels {
|
||||
SeriesLabels::try_new(
|
||||
Some(Arc::from("cpu")),
|
||||
vec![Label {
|
||||
name: Arc::from("host"),
|
||||
value: Arc::from("a"),
|
||||
}],
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
fn state_schema(kind: AggregateStateKind) -> Arc<AggregateStateSchema> {
|
||||
let components = match kind {
|
||||
AggregateStateKind::Group => vec![],
|
||||
AggregateStateKind::Sum => vec![StateComponent::Value, StateComponent::Compensation],
|
||||
AggregateStateKind::Count => vec![StateComponent::Count],
|
||||
AggregateStateKind::Avg => vec![
|
||||
StateComponent::Value,
|
||||
StateComponent::Mean,
|
||||
StateComponent::Compensation,
|
||||
StateComponent::Count,
|
||||
StateComponent::IncrementalMean,
|
||||
],
|
||||
AggregateStateKind::Min | AggregateStateKind::Max => vec![StateComponent::Value],
|
||||
AggregateStateKind::Stddev | AggregateStateKind::Stdvar => vec![
|
||||
StateComponent::Value,
|
||||
StateComponent::Mean,
|
||||
StateComponent::Count,
|
||||
],
|
||||
AggregateStateKind::HistogramSum => vec![
|
||||
StateComponent::HistogramValue,
|
||||
StateComponent::HistogramCompensation,
|
||||
StateComponent::Poisoned,
|
||||
StateComponent::IncompatibleLayout,
|
||||
StateComponent::CustomBoundsReconciled,
|
||||
StateComponent::CounterResetSeen,
|
||||
StateComponent::NotCounterResetSeen,
|
||||
],
|
||||
AggregateStateKind::HistogramAvg => vec![
|
||||
StateComponent::HistogramValue,
|
||||
StateComponent::HistogramCompensation,
|
||||
StateComponent::Count,
|
||||
StateComponent::IncrementalMean,
|
||||
StateComponent::Poisoned,
|
||||
StateComponent::IncompatibleLayout,
|
||||
StateComponent::CustomBoundsReconciled,
|
||||
StateComponent::CounterResetSeen,
|
||||
StateComponent::NotCounterResetSeen,
|
||||
],
|
||||
};
|
||||
Arc::new(AggregateStateSchema::try_new(kind, components).unwrap())
|
||||
}
|
||||
|
||||
fn series_schema(fields: &[&str]) -> Arc<SeriesSchema> {
|
||||
Arc::new(SeriesSchema {
|
||||
fields: fields
|
||||
.iter()
|
||||
.map(|name| FieldSpec {
|
||||
name: Arc::from(*name),
|
||||
})
|
||||
.collect(),
|
||||
eval_grid: Some(evaluated_grid()),
|
||||
})
|
||||
}
|
||||
|
||||
fn wrong_grid_schema() -> Arc<SeriesSchema> {
|
||||
Arc::new(SeriesSchema {
|
||||
fields: vec![FieldSpec {
|
||||
name: Arc::from("a"),
|
||||
}]
|
||||
.into(),
|
||||
eval_grid: Some(Arc::new(
|
||||
datatypes::series::time::EvalGrid::try_new(
|
||||
datatypes::series::time::GridSpec::try_new(1, 1000, 512).unwrap(),
|
||||
)
|
||||
.unwrap(),
|
||||
)),
|
||||
})
|
||||
}
|
||||
|
||||
fn input(fields: Vec<Vec<Option<StatePayload>>>) -> (StateSeries, bool) {
|
||||
let time = TimeAxis::from_grid_spans(evaluated_grid(), vec![GridSpan::new(1, 3)]).unwrap();
|
||||
(
|
||||
StateSeries {
|
||||
metric: group(),
|
||||
time,
|
||||
states: fields,
|
||||
},
|
||||
true,
|
||||
)
|
||||
}
|
||||
|
||||
fn source(items: Vec<(StateSeries, bool)>) -> SendableStateSeriesStream {
|
||||
Box::pin(futures_util::stream::iter(
|
||||
items.into_iter().map(Ok::<_, BoxedError>),
|
||||
))
|
||||
}
|
||||
|
||||
async fn packed(
|
||||
rows: Vec<(StateSeries, bool)>,
|
||||
state: Arc<AggregateStateSchema>,
|
||||
schema: Arc<SeriesSchema>,
|
||||
) -> Vec<RecordBatch> {
|
||||
let mut stream = pack_aggregate_state(source(rows), state, schema).unwrap();
|
||||
let mut batches = Vec::new();
|
||||
while let Some(batch) = stream.next().await {
|
||||
batches.push(batch.unwrap());
|
||||
}
|
||||
batches
|
||||
}
|
||||
|
||||
fn unpack_source(
|
||||
batches: Vec<RecordBatch>,
|
||||
schema: Arc<datatypes::arrow::datatypes::Schema>,
|
||||
) -> DfSendableRecordBatchStream {
|
||||
df_source(batches, schema).0
|
||||
}
|
||||
|
||||
async fn rows(
|
||||
batches: Vec<RecordBatch>,
|
||||
state: Option<Arc<AggregateStateSchema>>,
|
||||
schema: Option<Arc<SeriesSchema>>,
|
||||
) -> Vec<StateFrameRow> {
|
||||
let frame = batches
|
||||
.first()
|
||||
.map(|batch| batch.schema())
|
||||
.unwrap_or_else(|| {
|
||||
datatypes::series::frame::aggregate_state_frame_schema(
|
||||
state.as_ref().unwrap(),
|
||||
schema.as_ref().unwrap(),
|
||||
FrameLabelMode::Explicit,
|
||||
)
|
||||
.unwrap()
|
||||
});
|
||||
let mut stream = unpack_aggregate_state(unpack_source(batches, frame), state, schema).unwrap();
|
||||
let mut rows = Vec::new();
|
||||
while let Some(row) = stream.next().await {
|
||||
rows.push(row.unwrap());
|
||||
}
|
||||
rows
|
||||
}
|
||||
|
||||
fn values(value: f64) -> Option<StatePayload> {
|
||||
Some(StatePayload::Float(AggregateStateValues {
|
||||
value,
|
||||
compensation: value / 10.0,
|
||||
..Default::default()
|
||||
}))
|
||||
}
|
||||
|
||||
fn assert_state_row(row: &StateFrameRow, expected: &[f64], last: bool) {
|
||||
assert_eq!(row.metric(), &group());
|
||||
assert!(row.is_last() == last);
|
||||
assert_eq!(
|
||||
row.time()
|
||||
.positions()
|
||||
.map(|(position, _)| position)
|
||||
.collect::<Vec<_>>(),
|
||||
vec![1, 2, 3]
|
||||
);
|
||||
let fields = row.fields().unwrap();
|
||||
for (position, value) in expected.iter().enumerate() {
|
||||
assert!(fields.is_present(0, position).unwrap());
|
||||
assert_eq!(
|
||||
fields
|
||||
.field_values(0, StateComponent::Value)
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
.value(position),
|
||||
*value
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn assert_group_row(row: &StateFrameRow, last: bool) {
|
||||
assert_eq!(row.metric(), &group());
|
||||
assert_eq!(row.is_last(), last);
|
||||
assert_eq!(
|
||||
row.time()
|
||||
.positions()
|
||||
.map(|(position, _)| position)
|
||||
.collect::<Vec<_>>(),
|
||||
vec![1, 2, 3]
|
||||
);
|
||||
let fields = row.fields().unwrap();
|
||||
for field in 0..fields.len() {
|
||||
for position in 0..3 {
|
||||
assert!(fields.is_present(field, position).unwrap());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn aggregate_state_roundtrip_preserves_components_and_group_rows() {
|
||||
let sum = state_schema(AggregateStateKind::Sum);
|
||||
let schema = series_schema(&["a"]);
|
||||
let input_rows = vec![input(vec![vec![values(1.0), values(2.0), values(3.0)]])];
|
||||
let batches = packed(input_rows, sum.clone(), schema.clone()).await;
|
||||
let decoded = rows(batches, Some(sum), Some(schema)).await;
|
||||
assert_eq!(decoded.len(), 1);
|
||||
assert_state_row(&decoded[0], &[1.0, 2.0, 3.0], true);
|
||||
|
||||
let group_state = state_schema(AggregateStateKind::Group);
|
||||
let group_schema = series_schema(&["a"]);
|
||||
let group_batches = packed(
|
||||
vec![input(vec![vec![values(0.0), values(0.0), values(0.0)]])],
|
||||
group_state.clone(),
|
||||
group_schema.clone(),
|
||||
)
|
||||
.await;
|
||||
let group_rows = rows(group_batches, Some(group_state), Some(group_schema)).await;
|
||||
assert_eq!(group_rows.len(), 1);
|
||||
assert_group_row(&group_rows[0], true);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn group_presence_is_per_field() {
|
||||
let state = state_schema(AggregateStateKind::Group);
|
||||
let schema = series_schema(&["a", "b"]);
|
||||
let batches = packed(
|
||||
vec![input(vec![
|
||||
vec![values(0.0), None, values(0.0)],
|
||||
vec![None, values(0.0), None],
|
||||
])],
|
||||
state.clone(),
|
||||
schema.clone(),
|
||||
)
|
||||
.await;
|
||||
let decoded = rows(batches, Some(state), Some(schema)).await;
|
||||
let fields = decoded[0].fields().unwrap();
|
||||
assert_eq!(
|
||||
(0..3)
|
||||
.map(|i| fields.is_present(0, i).unwrap())
|
||||
.collect::<Vec<_>>(),
|
||||
vec![true, false, true]
|
||||
);
|
||||
assert_eq!(
|
||||
(0..3)
|
||||
.map(|i| fields.is_present(1, i).unwrap())
|
||||
.collect::<Vec<_>>(),
|
||||
vec![false, true, false]
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn aggregate_state_ipc_concat_roundtrip() {
|
||||
let state = state_schema(AggregateStateKind::Sum);
|
||||
let schema = series_schema(&["a"]);
|
||||
let batches = packed(
|
||||
vec![input(vec![vec![values(1.0), values(2.0), values(3.0)]])],
|
||||
state.clone(),
|
||||
schema.clone(),
|
||||
)
|
||||
.await;
|
||||
let expected = rows(batches.clone(), Some(state.clone()), Some(schema.clone())).await;
|
||||
let mut bytes = Cursor::new(Vec::new());
|
||||
{
|
||||
let mut writer = StreamWriter::try_new(&mut bytes, batches[0].schema().as_ref()).unwrap();
|
||||
for batch in &batches {
|
||||
writer.write(batch).unwrap();
|
||||
}
|
||||
writer.finish().unwrap();
|
||||
}
|
||||
bytes.set_position(0);
|
||||
let reader = StreamReader::try_new(bytes, None).unwrap();
|
||||
let read = reader.map(Result::unwrap).collect::<Vec<_>>();
|
||||
let concatenated = concat_batches(&batches[0].schema(), &read).unwrap();
|
||||
let decoded = rows(vec![concatenated], Some(state), Some(schema)).await;
|
||||
assert_eq!(decoded.len(), expected.len());
|
||||
assert_state_row(&decoded[0], &[1.0, 2.0, 3.0], true);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn aggregate_state_refusals_name_mismatched_parts() {
|
||||
let state = state_schema(AggregateStateKind::Sum);
|
||||
let schema = series_schema(&["a"]);
|
||||
let batches = packed(
|
||||
vec![input(vec![vec![values(1.0), values(2.0), values(3.0)]])],
|
||||
state.clone(),
|
||||
schema.clone(),
|
||||
)
|
||||
.await;
|
||||
for (expected, expected_schema, part) in [
|
||||
(
|
||||
Some(state_schema(AggregateStateKind::Count)),
|
||||
Some(schema.clone()),
|
||||
"kind",
|
||||
),
|
||||
(
|
||||
Some(Arc::new(AggregateStateSchema {
|
||||
kind: AggregateStateKind::Sum,
|
||||
components: vec![StateComponent::Compensation, StateComponent::Value].into(),
|
||||
})),
|
||||
Some(schema.clone()),
|
||||
"components",
|
||||
),
|
||||
(Some(state.clone()), Some(wrong_grid_schema()), "grid"),
|
||||
(
|
||||
Some(state.clone()),
|
||||
Some(series_schema(&["a", "b"])),
|
||||
"fields",
|
||||
),
|
||||
] {
|
||||
let frame = batches[0].schema();
|
||||
let (source, _, _) = df_source(batches.clone(), frame);
|
||||
let error = unpack_aggregate_state(source, expected, expected_schema)
|
||||
.err()
|
||||
.unwrap()
|
||||
.to_string();
|
||||
assert!(
|
||||
error.to_lowercase().contains(part),
|
||||
"{error} did not name {part}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn aggregate_state_rejects_evaluated_and_evaluated_rejects_state() {
|
||||
let state = state_schema(AggregateStateKind::Sum);
|
||||
let schema = series_schema(&["a"]);
|
||||
let batches = packed(
|
||||
vec![input(vec![vec![values(1.0), values(2.0), values(3.0)]])],
|
||||
state,
|
||||
schema,
|
||||
)
|
||||
.await;
|
||||
let eval =
|
||||
pack_evaluated_series(Box::pin(futures_util::stream::empty()), evaluated_schema()).unwrap();
|
||||
let frame = eval.schema();
|
||||
let (source, _, _) = df_source(vec![], frame.clone());
|
||||
assert!(
|
||||
unpack_aggregate_state(source, None, None)
|
||||
.err()
|
||||
.unwrap()
|
||||
.to_string()
|
||||
.contains("evaluated")
|
||||
);
|
||||
let (source, _, _) = df_source(batches.clone(), batches[0].schema());
|
||||
assert!(
|
||||
unpack_evaluated_series(source, None)
|
||||
.err()
|
||||
.unwrap()
|
||||
.to_string()
|
||||
.contains("aggregate_state")
|
||||
);
|
||||
let eval =
|
||||
pack_evaluated_series(Box::pin(futures_util::stream::empty()), evaluated_schema()).unwrap();
|
||||
let frame = eval.schema();
|
||||
let (source, _, _) = df_source(vec![], frame);
|
||||
assert!(
|
||||
unpack_aggregate_state(source, None, None)
|
||||
.err()
|
||||
.unwrap()
|
||||
.to_string()
|
||||
.contains("evaluated")
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn aggregate_state_empty_stream_terminates() {
|
||||
let state = state_schema(AggregateStateKind::Sum);
|
||||
let schema = series_schema(&["a"]);
|
||||
let batches = packed(vec![], state.clone(), schema.clone()).await;
|
||||
assert!(batches.is_empty());
|
||||
let frame = datatypes::series::frame::aggregate_state_frame_schema(
|
||||
&state,
|
||||
&schema,
|
||||
datatypes::series::frame::FrameLabelMode::Explicit,
|
||||
)
|
||||
.unwrap();
|
||||
let (source, _, _) = df_source(vec![], frame);
|
||||
let mut decoded = unpack_aggregate_state(source, Some(state), Some(schema)).unwrap();
|
||||
assert!(decoded.next().await.is_none());
|
||||
}
|
||||
@@ -17,11 +17,12 @@ use std::future::Future;
|
||||
use std::marker::PhantomData;
|
||||
use std::pin::Pin;
|
||||
use std::str::FromStr;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::task::{Context, Poll};
|
||||
|
||||
use common_base::readable_size::ReadableSize;
|
||||
use common_error::ext::BoxedError;
|
||||
use common_telemetry::tracing::{Span, info_span};
|
||||
use common_time::util::format_nanoseconds_human_readable;
|
||||
use datafusion::arrow::compute::cast;
|
||||
@@ -32,7 +33,7 @@ use datafusion::logical_expr::Expr;
|
||||
use datafusion::logical_expr::physical_planning_context::PhysicalPlanningContext;
|
||||
use datafusion::logical_expr::utils::conjunction;
|
||||
use datafusion::physical_expr::create_physical_expr;
|
||||
use datafusion::physical_plan::metrics::{BaselineMetrics, MetricValue};
|
||||
use datafusion::physical_plan::metrics::{BaselineMetrics, CustomMetricValue, MetricValue};
|
||||
use datafusion::physical_plan::{
|
||||
DisplayFormatType, ExecutionPlan, ExecutionPlanVisitor, PhysicalExpr,
|
||||
RecordBatchStream as DfRecordBatchStream, accept,
|
||||
@@ -55,6 +56,7 @@ use crate::{
|
||||
};
|
||||
|
||||
const REGION_SCAN_EXEC_NAME: &str = "RegionScanExec";
|
||||
pub const SERIES_SCAN_EXEC_NAME: &str = "SeriesScanExec";
|
||||
|
||||
type FutureStream =
|
||||
Pin<Box<dyn std::future::Future<Output = Result<SendableRecordBatchStream>> + Send>>;
|
||||
@@ -205,7 +207,9 @@ impl Stream for DfRecordBatchStreamAdapter {
|
||||
Poll::Pending => Poll::Pending,
|
||||
Poll::Ready(Some(recordbatch)) => match recordbatch {
|
||||
Ok(recordbatch) => Poll::Ready(Some(Ok(recordbatch.into_df_record_batch()))),
|
||||
Err(e) => Poll::Ready(Some(Err(DataFusionError::External(Box::new(e))))),
|
||||
Err(e) => Poll::Ready(Some(Err(DataFusionError::External(Box::new(
|
||||
BoxedError::new(e),
|
||||
))))),
|
||||
},
|
||||
Poll::Ready(None) => Poll::Ready(None),
|
||||
}
|
||||
@@ -377,12 +381,16 @@ impl RecordBatchStreamAdapter {
|
||||
}
|
||||
}
|
||||
|
||||
fn is_region_scan_name(name: &str) -> bool {
|
||||
name == REGION_SCAN_EXEC_NAME || name == SERIES_SCAN_EXEC_NAME
|
||||
}
|
||||
|
||||
/// Extracts total `output_bytes` from region scan plan nodes.
|
||||
pub fn region_scan_output_bytes(metrics: &RecordBatchMetrics) -> usize {
|
||||
metrics
|
||||
.plan_metrics
|
||||
.iter()
|
||||
.filter(|pm| pm.plan_name == REGION_SCAN_EXEC_NAME)
|
||||
.filter(|pm| is_region_scan_name(&pm.plan_name))
|
||||
.flat_map(|pm| &pm.metrics)
|
||||
.filter_map(|(name, value)| (name == "output_bytes").then_some(*value))
|
||||
.sum()
|
||||
@@ -434,7 +442,7 @@ fn collect_lightweight_query_load_metrics_inner(
|
||||
level: usize,
|
||||
record_batch_metrics: &mut RecordBatchMetrics,
|
||||
) {
|
||||
let is_region_scan = df_plan.name() == REGION_SCAN_EXEC_NAME;
|
||||
let is_region_scan = is_region_scan_name(df_plan.name());
|
||||
let mut region_scan_output_bytes = None;
|
||||
|
||||
if let Some(metrics) = df_plan.metrics() {
|
||||
@@ -462,6 +470,7 @@ fn collect_lightweight_query_load_metrics_inner(
|
||||
plan_name: df_plan.name().to_string(),
|
||||
level,
|
||||
metrics: vec![("output_bytes".to_string(), output_bytes)],
|
||||
native: None,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -580,6 +589,7 @@ impl ExecutionPlanVisitor for MetricCollector {
|
||||
plan_name: plan.name().to_string(),
|
||||
level: self.current_level,
|
||||
metrics: vec![],
|
||||
native: None,
|
||||
});
|
||||
self.current_level += 1;
|
||||
return Ok(true);
|
||||
@@ -595,8 +605,20 @@ impl ExecutionPlanVisitor for MetricCollector {
|
||||
plan_name: plan.name().to_string(),
|
||||
level: self.current_level,
|
||||
metrics: Vec::with_capacity(metric.iter().size_hint().0),
|
||||
native: None,
|
||||
};
|
||||
for m in metric.iter() {
|
||||
// An operator that runs nodes inside itself registers the tree as one of its metric
|
||||
// values. It travels here, where a plain value cannot: the tree is structure, not a
|
||||
// figure, so it is reported apart from the flat list instead of being flattened into it.
|
||||
if let MetricValue::Custom { name, value } = m.value()
|
||||
&& name.as_ref() == NATIVE_TREE_METRIC
|
||||
{
|
||||
if let Some(tree) = value.as_any().downcast_ref::<NativeTreeMetric>() {
|
||||
plan_metric.native = Some(tree.report());
|
||||
}
|
||||
continue;
|
||||
}
|
||||
plan_metric
|
||||
.metrics
|
||||
.push((m.value().name().to_string(), m.value().as_usize()));
|
||||
@@ -686,45 +708,59 @@ pub struct RegionWatermarkEntry {
|
||||
}
|
||||
|
||||
/// Determines if a metric name represents a time measurement that should be formatted.
|
||||
fn is_time_metric(metric_name: &str) -> bool {
|
||||
pub fn is_time_metric(metric_name: &str) -> bool {
|
||||
metric_name.contains("elapsed") || metric_name.contains("time") || metric_name.contains("cost")
|
||||
}
|
||||
|
||||
/// Determines if a metric name represents a bytes measurement that should be formatted.
|
||||
fn is_bytes_metric(metric_name: &str) -> bool {
|
||||
pub fn is_bytes_metric(metric_name: &str) -> bool {
|
||||
metric_name.contains("bytes") || metric_name.contains("mem")
|
||||
}
|
||||
|
||||
fn format_bytes_human_readable(bytes: usize) -> String {
|
||||
/// Renders `bytes` the way a plan line reports a memory figure.
|
||||
pub fn format_bytes_human_readable(bytes: usize) -> String {
|
||||
format!("{}", ReadableSize(bytes as u64))
|
||||
}
|
||||
|
||||
/// Renders one metric as `label: value`, the way every `ANALYZE` line reports it.
|
||||
///
|
||||
/// A time is a readable duration, a byte count a readable size, and anything else a plain integer.
|
||||
/// This is the one formatter for a plan line, so a node rendered by its own operator and a node
|
||||
/// rendered by the collector read alike.
|
||||
pub fn format_metric(label: &str, value: usize) -> String {
|
||||
if is_time_metric(label) {
|
||||
format!("{}: {}", label, format_nanoseconds_human_readable(value))
|
||||
} else if is_bytes_metric(label) {
|
||||
format!("{}: {}", label, format_bytes_human_readable(value))
|
||||
} else {
|
||||
format!("{}: {}", label, value)
|
||||
}
|
||||
}
|
||||
|
||||
/// Only display `plan_metrics` with indent ` ` (2 spaces).
|
||||
///
|
||||
/// An operator's own figures go at the end of its own line, which is the line that names it. An
|
||||
/// operator whose line continues - one that renders the nodes it runs below itself - therefore
|
||||
/// keeps those figures rather than receiving every figure of the subtree it drew, and the lines it
|
||||
/// drew keep the figures and the indentation they were rendered with, shifted to sit under it.
|
||||
impl Display for RecordBatchMetrics {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
for metric in &self.plan_metrics {
|
||||
let indent = metric.level * 2;
|
||||
let mut lines = metric.plan.trim_end().lines();
|
||||
write!(
|
||||
f,
|
||||
"{:indent$}{} metrics=[",
|
||||
" ",
|
||||
metric.plan.trim_end(),
|
||||
indent = metric.level * 2,
|
||||
lines.next().unwrap_or_default(),
|
||||
)?;
|
||||
for (label, value) in &metric.metrics {
|
||||
if is_time_metric(label) {
|
||||
write!(
|
||||
f,
|
||||
"{}: {}, ",
|
||||
label,
|
||||
format_nanoseconds_human_readable(*value),
|
||||
)?;
|
||||
} else if is_bytes_metric(label) {
|
||||
write!(f, "{}: {}, ", label, format_bytes_human_readable(*value),)?;
|
||||
} else {
|
||||
write!(f, "{}: {}, ", label, value)?;
|
||||
}
|
||||
write!(f, "{}, ", format_metric(label, *value))?;
|
||||
}
|
||||
writeln!(f, "]")?;
|
||||
for line in lines {
|
||||
writeln!(f, "{:indent$}{line}", " ")?;
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
@@ -743,6 +779,131 @@ pub struct PlanMetrics {
|
||||
/// An ordered key-value list of metrics.
|
||||
/// Key is metric label and value is metric value.
|
||||
pub metrics: Vec<(String, usize)>,
|
||||
/// The tree of nodes an operator runs inside itself, when it runs one.
|
||||
///
|
||||
/// Such an operator reports its own figures through `metrics` and each node it runs through
|
||||
/// this: they are not the same operator, so they are not the same entry. Absent for every other
|
||||
/// operator, and for a record written before this field existed.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub native: Option<NativeTreeMetrics>,
|
||||
}
|
||||
|
||||
/// One node of a tree an operator runs inside itself, with the figures that node recorded.
|
||||
///
|
||||
/// The shape is the plan line's own: the node's line without figures, the figures, and the nodes
|
||||
/// that consume its output, in the order the operator feeds them.
|
||||
#[derive(serde::Serialize, serde::Deserialize, Default, Debug, Clone, PartialEq, Eq)]
|
||||
pub struct NativeTreeMetrics {
|
||||
/// The node's line without figures, as `<kind>: <what it computes>`.
|
||||
pub line: String,
|
||||
/// An ordered key-value list of the figures this node recorded.
|
||||
#[serde(default)]
|
||||
pub metrics: Vec<(String, usize)>,
|
||||
/// The nodes that consume this one's output.
|
||||
#[serde(default)]
|
||||
pub children: Vec<NativeTreeMetrics>,
|
||||
}
|
||||
|
||||
/// Builds the tree a reader sees, when it asks for it.
|
||||
type NativeTreeReader = Arc<dyn Fn() -> NativeTreeMetrics + Send + Sync>;
|
||||
|
||||
/// The tree an operator runs, registered as one of that operator's metrics.
|
||||
///
|
||||
/// It is a metric value so it travels with the operator's own figures through the same collection
|
||||
/// and the same record: a plan's figures are only final once it ran, which is when `ANALYZE` reads
|
||||
/// them, so what is registered is how to read the tree rather than a copy of it.
|
||||
pub struct NativeTreeMetric {
|
||||
/// Reads the tree as it is now. `None` for a value created to accumulate a combination.
|
||||
reader: Option<NativeTreeReader>,
|
||||
/// A report this value took over while combining with another, which wins over `reader`.
|
||||
adopted: Mutex<Option<NativeTreeMetrics>>,
|
||||
}
|
||||
|
||||
/// The name an operator registers its tree under.
|
||||
///
|
||||
/// It carries the same `native.` prefix as the per-node figures so a reader that lists an
|
||||
/// operator's own figures leaves it out.
|
||||
pub const NATIVE_TREE_METRIC: &str = "native.tree";
|
||||
|
||||
impl NativeTreeMetric {
|
||||
/// Registers `reader` as the way to read the tree when it is asked for.
|
||||
pub fn new(reader: impl Fn() -> NativeTreeMetrics + Send + Sync + 'static) -> Self {
|
||||
Self {
|
||||
reader: Some(Arc::new(reader)),
|
||||
adopted: Mutex::new(None),
|
||||
}
|
||||
}
|
||||
|
||||
/// The tree with the figures it has now.
|
||||
pub fn report(&self) -> NativeTreeMetrics {
|
||||
if let Some(adopted) = self
|
||||
.adopted
|
||||
.lock()
|
||||
.unwrap_or_else(|poisoned| poisoned.into_inner())
|
||||
.clone()
|
||||
{
|
||||
return adopted;
|
||||
}
|
||||
self.reader
|
||||
.as_ref()
|
||||
.map_or_else(NativeTreeMetrics::default, |reader| reader())
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Display for NativeTreeMetric {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(f, "a tree of {} nodes", self.report().node_count())
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for NativeTreeMetric {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("NativeTreeMetric").finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
impl NativeTreeMetrics {
|
||||
/// How many nodes this node and everything below it cover.
|
||||
pub fn node_count(&self) -> usize {
|
||||
1 + self
|
||||
.children
|
||||
.iter()
|
||||
.map(NativeTreeMetrics::node_count)
|
||||
.sum::<usize>()
|
||||
}
|
||||
}
|
||||
|
||||
impl CustomMetricValue for NativeTreeMetric {
|
||||
/// A value to accumulate a combination into: it holds nothing until it combines with one.
|
||||
fn new_empty(&self) -> Arc<dyn CustomMetricValue> {
|
||||
Arc::new(Self {
|
||||
reader: None,
|
||||
adopted: Mutex::new(None),
|
||||
})
|
||||
}
|
||||
|
||||
/// Combining takes the report of `other`, because one operator registers one tree: what a
|
||||
/// combination of two registrations would mean is not defined, and cannot happen today.
|
||||
fn aggregate(&self, other: Arc<dyn CustomMetricValue + 'static>) {
|
||||
let Some(other) = other.as_any().downcast_ref::<Self>() else {
|
||||
return;
|
||||
};
|
||||
*self
|
||||
.adopted
|
||||
.lock()
|
||||
.unwrap_or_else(|poisoned| poisoned.into_inner()) = Some(other.report());
|
||||
}
|
||||
|
||||
fn as_any(&self) -> &dyn std::any::Any {
|
||||
self
|
||||
}
|
||||
|
||||
fn is_eq(&self, other: &Arc<dyn CustomMetricValue>) -> bool {
|
||||
other
|
||||
.as_any()
|
||||
.downcast_ref::<Self>()
|
||||
.is_some_and(|other| other.report() == self.report())
|
||||
}
|
||||
}
|
||||
|
||||
enum AsyncRecordBatchStreamAdapterState {
|
||||
@@ -937,9 +1098,10 @@ fn convert_map_to_json_binary(
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use std::collections::VecDeque;
|
||||
use std::time::Duration;
|
||||
|
||||
use common_error::ext::BoxedError;
|
||||
use common_error::ext::{ErrorExt, PlainError};
|
||||
use common_error::mock::MockError;
|
||||
use common_error::status_code::StatusCode;
|
||||
use datafusion::execution::TaskContext;
|
||||
@@ -959,14 +1121,15 @@ mod test {
|
||||
use snafu::IntoError;
|
||||
|
||||
use super::*;
|
||||
use crate::RecordBatches;
|
||||
use crate::error::Error;
|
||||
use crate::{RecordBatchStreamWrapper, RecordBatches};
|
||||
|
||||
#[derive(Debug)]
|
||||
struct TestMetricsExec {
|
||||
properties: Arc<PlanProperties>,
|
||||
metrics: ExecutionPlanMetricsSet,
|
||||
format_plan: bool,
|
||||
plan_name: &'static str,
|
||||
}
|
||||
|
||||
impl TestMetricsExec {
|
||||
@@ -975,17 +1138,23 @@ mod test {
|
||||
}
|
||||
|
||||
fn new_without_plan_formatting(schema: DfSchemaRef) -> Self {
|
||||
Self::with_output_bytes_and_formatting(schema, &[24], false)
|
||||
Self::with_output_bytes_and_formatting(schema, &[24], false, REGION_SCAN_EXEC_NAME)
|
||||
}
|
||||
|
||||
fn with_output_bytes(schema: DfSchemaRef, output_bytes_by_partition: &[usize]) -> Self {
|
||||
Self::with_output_bytes_and_formatting(schema, output_bytes_by_partition, true)
|
||||
Self::with_output_bytes_and_formatting(
|
||||
schema,
|
||||
output_bytes_by_partition,
|
||||
true,
|
||||
REGION_SCAN_EXEC_NAME,
|
||||
)
|
||||
}
|
||||
|
||||
fn with_output_bytes_and_formatting(
|
||||
schema: DfSchemaRef,
|
||||
output_bytes_by_partition: &[usize],
|
||||
format_plan: bool,
|
||||
plan_name: &'static str,
|
||||
) -> Self {
|
||||
let metrics = ExecutionPlanMetricsSet::new();
|
||||
let elapsed_compute = MetricBuilder::new(&metrics).elapsed_compute(0);
|
||||
@@ -1004,6 +1173,7 @@ mod test {
|
||||
)),
|
||||
metrics,
|
||||
format_plan,
|
||||
plan_name,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1014,7 +1184,7 @@ mod test {
|
||||
self.format_plan,
|
||||
"non-verbose lightweight partial metrics must not format the plan"
|
||||
);
|
||||
write!(f, "RegionScanExec")?;
|
||||
write!(f, "{}", self.plan_name)?;
|
||||
if matches!(t, DisplayFormatType::Verbose) {
|
||||
write!(f, ": files=[file-1.parquet]")?;
|
||||
}
|
||||
@@ -1024,7 +1194,7 @@ mod test {
|
||||
|
||||
impl ExecutionPlan for TestMetricsExec {
|
||||
fn name(&self) -> &str {
|
||||
REGION_SCAN_EXEC_NAME
|
||||
self.plan_name
|
||||
}
|
||||
|
||||
fn properties(&self) -> &Arc<PlanProperties> {
|
||||
@@ -1064,6 +1234,29 @@ mod test {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_lightweight_query_load_metrics_sums_series_scan_output_bytes() {
|
||||
let schema = Arc::new(Schema::new(vec![ColumnSchema::new(
|
||||
"a",
|
||||
ConcreteDataType::int32_datatype(),
|
||||
false,
|
||||
)]));
|
||||
let plan = TestMetricsExec::with_output_bytes_and_formatting(
|
||||
schema.arrow_schema().clone(),
|
||||
&[24, 18],
|
||||
true,
|
||||
SERIES_SCAN_EXEC_NAME,
|
||||
);
|
||||
|
||||
let metrics = collect_lightweight_query_load_metrics(&plan, Some(42));
|
||||
|
||||
assert_eq!(region_scan_output_bytes(&metrics), 42);
|
||||
assert_eq!(metrics.plan_metrics[0].plan_name, SERIES_SCAN_EXEC_NAME);
|
||||
|
||||
let full_metrics = collect_full_metrics(&plan, false, Some(42));
|
||||
assert_eq!(region_scan_output_bytes(&full_metrics), 42);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_lightweight_query_load_metrics_sums_region_scan_output_bytes() {
|
||||
let schema = Arc::new(Schema::new(vec![ColumnSchema::new(
|
||||
@@ -1195,6 +1388,7 @@ mod test {
|
||||
plan_name: REGION_SCAN_EXEC_NAME.to_string(),
|
||||
level: 0,
|
||||
metrics: vec![("output_bytes".to_string(), 2)],
|
||||
native: None,
|
||||
}],
|
||||
..Default::default()
|
||||
};
|
||||
@@ -1313,6 +1507,171 @@ mod test {
|
||||
);
|
||||
}
|
||||
|
||||
/// Invariant: both stream adapters must forward the original error as a
|
||||
/// typed `BoxedError` inside `DataFusionError::External`, so downstream
|
||||
/// status code recovery (the `Error::PollStream` arm of `Error::status_code`)
|
||||
/// keeps the original status code.
|
||||
#[test]
|
||||
fn test_df_record_batch_stream_adapter_preserves_typed_errors() {
|
||||
fn chain_has_marker(err: &(dyn std::error::Error + 'static), marker: &str) -> bool {
|
||||
let mut current = Some(err);
|
||||
while let Some(error) = current {
|
||||
if error.to_string().contains(marker) {
|
||||
return true;
|
||||
}
|
||||
current = error.source();
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
fn assert_typed_external(
|
||||
df_error: &DataFusionError,
|
||||
expected: StatusCode,
|
||||
context: &str,
|
||||
marker: &str,
|
||||
) {
|
||||
let DataFusionError::External(payload) = df_error else {
|
||||
panic!("{context}: expected DataFusionError::External, got {df_error:?}");
|
||||
};
|
||||
let Some(boxed) = payload.downcast_ref::<BoxedError>() else {
|
||||
panic!("{context}: external payload lost its typed BoxedError: {payload:?}");
|
||||
};
|
||||
assert_eq!(
|
||||
boxed.status_code(),
|
||||
expected,
|
||||
"{context}: original status code lost"
|
||||
);
|
||||
assert!(
|
||||
chain_has_marker(boxed, marker),
|
||||
"{context}: original error lost from the source chain: {payload:?}"
|
||||
);
|
||||
}
|
||||
|
||||
let schema = Arc::new(Schema::new(vec![ColumnSchema::new(
|
||||
"a",
|
||||
ConcreteDataType::int32_datatype(),
|
||||
false,
|
||||
)]));
|
||||
let batch = RecordBatch::new(
|
||||
schema.clone(),
|
||||
vec![Arc::new(Int32Vector::from_slice([1])) as _],
|
||||
)
|
||||
.unwrap();
|
||||
let expected_df_batch = batch.clone().into_df_record_batch();
|
||||
|
||||
// A stream is consumed once, so every adapter under test gets its own
|
||||
// fresh equivalent stream. Sequence: Pending -> batch -> typed error -> EOF.
|
||||
let make_stream = |marker: &str, status: StatusCode| -> SendableRecordBatchStream {
|
||||
let typed_error = error::ExternalSnafu
|
||||
.into_error(BoxedError::new(PlainError::new(marker.to_string(), status)));
|
||||
let mut items: VecDeque<Poll<Option<Result<RecordBatch>>>> = VecDeque::from([
|
||||
Poll::Pending,
|
||||
Poll::Ready(Some(Ok(batch.clone()))),
|
||||
Poll::Ready(Some(Err(typed_error))),
|
||||
Poll::Ready(None),
|
||||
]);
|
||||
Box::pin(RecordBatchStreamWrapper::new(
|
||||
schema.clone(),
|
||||
futures::stream::poll_fn(move |_| items.pop_front().unwrap_or(Poll::Ready(None))),
|
||||
))
|
||||
};
|
||||
|
||||
let waker = futures::task::noop_waker_ref();
|
||||
let mut cx = Context::from_waker(waker);
|
||||
|
||||
for status in [
|
||||
StatusCode::InvalidArguments,
|
||||
StatusCode::Internal,
|
||||
StatusCode::Unknown,
|
||||
StatusCode::RequestOutdated,
|
||||
] {
|
||||
// Unique per case, so a match proves the *original* error survived.
|
||||
let marker = format!("df-record-batch-stream-adapter-typed-error-marker-{status}");
|
||||
|
||||
// Greptime -> DataFusion forward adapter.
|
||||
let mut df_adapter = DfRecordBatchStreamAdapter::new(make_stream(&marker, status));
|
||||
assert_eq!(df_adapter.schema(), schema.arrow_schema().clone());
|
||||
assert!(
|
||||
matches!(Pin::new(&mut df_adapter).poll_next(&mut cx), Poll::Pending),
|
||||
"Pending must be preserved"
|
||||
);
|
||||
let Poll::Ready(Some(Ok(df_batch))) = Pin::new(&mut df_adapter).poll_next(&mut cx)
|
||||
else {
|
||||
panic!("expected the forwarded batch");
|
||||
};
|
||||
assert_eq!(df_batch.schema(), schema.arrow_schema().clone());
|
||||
assert_eq!(df_batch, expected_df_batch);
|
||||
let Poll::Ready(Some(Err(df_error))) = Pin::new(&mut df_adapter).poll_next(&mut cx)
|
||||
else {
|
||||
panic!("expected the forwarded error");
|
||||
};
|
||||
assert_typed_external(
|
||||
&df_error,
|
||||
status,
|
||||
&format!("forward adapter, status {status}"),
|
||||
&marker,
|
||||
);
|
||||
assert!(
|
||||
matches!(
|
||||
Pin::new(&mut df_adapter).poll_next(&mut cx),
|
||||
Poll::Ready(None)
|
||||
),
|
||||
"EOF must be preserved"
|
||||
);
|
||||
|
||||
// DataFusion -> Greptime adapter over another fresh equivalent
|
||||
// stream: Pending, batch, schema and EOF stay unchanged, and the
|
||||
// error is reported exactly once.
|
||||
let df_stream: DfSendableRecordBatchStream = Box::pin(DfRecordBatchStreamAdapter::new(
|
||||
make_stream(&marker, status),
|
||||
));
|
||||
let mut roundtrip = RecordBatchStreamAdapter::try_new(df_stream).unwrap();
|
||||
assert_eq!(roundtrip.schema().arrow_schema(), schema.arrow_schema());
|
||||
assert!(
|
||||
matches!(Pin::new(&mut roundtrip).poll_next(&mut cx), Poll::Pending),
|
||||
"Pending must be preserved"
|
||||
);
|
||||
let Poll::Ready(Some(Ok(roundtrip_batch))) =
|
||||
Pin::new(&mut roundtrip).poll_next(&mut cx)
|
||||
else {
|
||||
panic!("expected the roundtripped batch");
|
||||
};
|
||||
assert_eq!(roundtrip_batch.schema, roundtrip.schema());
|
||||
assert_eq!(roundtrip_batch.df_record_batch(), &expected_df_batch);
|
||||
let Poll::Ready(Some(Err(roundtrip_error))) =
|
||||
Pin::new(&mut roundtrip).poll_next(&mut cx)
|
||||
else {
|
||||
panic!("expected the roundtripped error");
|
||||
};
|
||||
let Error::PollStream {
|
||||
error: df_error, ..
|
||||
} = &roundtrip_error
|
||||
else {
|
||||
panic!("expected a poll stream error, got {roundtrip_error:?}");
|
||||
};
|
||||
assert_eq!(roundtrip_error.status_code(), status);
|
||||
let expected_output = match status {
|
||||
StatusCode::Internal => "Internal error: 1003".to_string(),
|
||||
StatusCode::Unknown => "Internal error: 1000".to_string(),
|
||||
_ => marker.clone(),
|
||||
};
|
||||
assert_eq!(roundtrip_error.output_msg(), expected_output);
|
||||
assert_typed_external(
|
||||
df_error,
|
||||
status,
|
||||
&format!("roundtrip adapter, status {status}"),
|
||||
&marker,
|
||||
);
|
||||
assert!(
|
||||
matches!(
|
||||
Pin::new(&mut roundtrip).poll_next(&mut cx),
|
||||
Poll::Ready(None)
|
||||
),
|
||||
"the roundtrip stream must end after the error"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_convert_map_to_json_binary() {
|
||||
let keys = StringArray::from(vec![Some("a"), Some("b"), Some("c"), Some("x")]);
|
||||
@@ -1399,6 +1758,7 @@ mod test {
|
||||
plan_name: REGION_SCAN_EXEC_NAME.to_string(),
|
||||
level: 0,
|
||||
metrics: vec![("output_bytes".to_string(), 42)],
|
||||
native: None,
|
||||
}],
|
||||
..Default::default()
|
||||
};
|
||||
@@ -1433,6 +1793,7 @@ mod test {
|
||||
plan_name: REGION_SCAN_EXEC_NAME.to_string(),
|
||||
level: 0,
|
||||
metrics: vec![("output_bytes".to_string(), 42)],
|
||||
native: None,
|
||||
}],
|
||||
..Default::default()
|
||||
};
|
||||
@@ -1512,6 +1873,108 @@ mod test {
|
||||
assert_eq!(decoded.region_watermarks, metrics.region_watermarks);
|
||||
}
|
||||
|
||||
fn plan_metrics(level: usize, plan: &str, metrics: &[(&str, usize)]) -> PlanMetrics {
|
||||
PlanMetrics {
|
||||
plan: plan.to_string(),
|
||||
plan_name: "Test".to_string(),
|
||||
level,
|
||||
metrics: metrics
|
||||
.iter()
|
||||
.map(|(label, value)| (label.to_string(), *value))
|
||||
.collect(),
|
||||
native: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// A one-line operator keeps its figures on its line, rendered as before: this is the shape
|
||||
/// every operator other than one that draws a subtree has always had.
|
||||
#[test]
|
||||
fn a_single_line_plan_keeps_its_figures_on_its_line() {
|
||||
let metrics = RecordBatchMetrics {
|
||||
plan_metrics: vec![
|
||||
plan_metrics(0, "CooperativeExec", &[("elapsed_compute", 1_000_000)]),
|
||||
plan_metrics(1, "RegionScanExec", &[("output_bytes", 2048)]),
|
||||
],
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
assert_eq!(
|
||||
metrics.to_string(),
|
||||
" CooperativeExec metrics=[elapsed_compute: 1.0ms, ]\n RegionScanExec metrics=[output_bytes: 2.0KiB, ]\n"
|
||||
);
|
||||
}
|
||||
|
||||
/// An operator that draws nodes below itself keeps its own figures on its own - first - line.
|
||||
/// Its subtree keeps the figures and the indentation it was rendered with, shifted to sit under
|
||||
/// the operator it hangs from.
|
||||
#[test]
|
||||
fn a_multi_line_plan_receives_its_figures_before_the_subtree_it_drew() {
|
||||
let metrics = RecordBatchMetrics {
|
||||
plan_metrics: vec![
|
||||
plan_metrics(
|
||||
1,
|
||||
"FusedSeriesExec: rate(x[5m])\n Window: rate, metrics=[output_values: 3]\n Input: source=0",
|
||||
&[("elapsed_compute", 2_000_000)],
|
||||
),
|
||||
plan_metrics(2, "RegionScanExec", &[("output_bytes", 4096)]),
|
||||
],
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
assert_eq!(
|
||||
metrics.to_string(),
|
||||
concat!(
|
||||
" FusedSeriesExec: rate(x[5m]) metrics=[elapsed_compute: 2.0ms, ]\n",
|
||||
" Window: rate, metrics=[output_values: 3]\n",
|
||||
" Input: source=0\n",
|
||||
" RegionScanExec metrics=[output_bytes: 4.0KiB, ]\n",
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/// A record written before the native tree was carried here still reads, and a record without
|
||||
/// one does not grow a field: the payload is optional on the wire in both directions.
|
||||
#[test]
|
||||
fn a_plan_record_without_a_native_tree_reads_and_writes_no_field() {
|
||||
let older: PlanMetrics = serde_json::from_str(
|
||||
r#"{"plan":"CooperativeExec","plan_name":"CooperativeExec","level":0,"metrics":[]}"#,
|
||||
)
|
||||
.expect("a record written before the field existed reads");
|
||||
|
||||
assert_eq!(older.native, None);
|
||||
let written = serde_json::to_value(&older).unwrap();
|
||||
assert!(written.get("native").is_none());
|
||||
}
|
||||
|
||||
/// A tree crosses the record as structure: each node's line, its own figures, and its children.
|
||||
#[test]
|
||||
fn a_native_tree_round_trips_through_the_record() {
|
||||
let tree = NativeTreeMetrics {
|
||||
line: "Map: abs".to_string(),
|
||||
metrics: vec![("output_values".to_string(), 4)],
|
||||
children: vec![NativeTreeMetrics {
|
||||
line: "Input: raw samples source=0".to_string(),
|
||||
metrics: vec![],
|
||||
children: vec![],
|
||||
}],
|
||||
};
|
||||
let record = RecordBatchMetrics {
|
||||
plan_metrics: vec![PlanMetrics {
|
||||
plan: "FusedSeriesExec: abs(rate(x[5m]))".to_string(),
|
||||
plan_name: "FusedSeriesExec".to_string(),
|
||||
level: 0,
|
||||
metrics: vec![],
|
||||
native: Some(tree.clone()),
|
||||
}],
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let written = serde_json::to_string(&record).unwrap();
|
||||
let read: RecordBatchMetrics = serde_json::from_str(&written).unwrap();
|
||||
|
||||
assert_eq!(read.plan_metrics[0].native, Some(tree));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_recordbatch_metrics_skips_empty_region_watermarks_on_serialize() {
|
||||
let value = serde_json::to_value(RecordBatchMetrics::default()).unwrap();
|
||||
|
||||
@@ -44,7 +44,7 @@ pub enum Error {
|
||||
source: datatypes::error::Error,
|
||||
},
|
||||
|
||||
#[snafu(display("External error"))]
|
||||
#[snafu(display("External error: {source}"))]
|
||||
External {
|
||||
#[snafu(implicit)]
|
||||
location: Location,
|
||||
@@ -314,6 +314,11 @@ mod tests {
|
||||
location: Location::default(),
|
||||
};
|
||||
assert_eq!(error.status_code(), status);
|
||||
let expected_output = match status {
|
||||
StatusCode::Unknown => "Internal error: 1000",
|
||||
_ => "neutral error",
|
||||
};
|
||||
assert!(error.output_msg().contains(expected_output));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -361,6 +366,15 @@ mod tests {
|
||||
location: Location::default(),
|
||||
};
|
||||
assert_eq!(error.status_code(), StatusCode::EngineExecuteQuery);
|
||||
if matches!(
|
||||
&error,
|
||||
Error::PollStream {
|
||||
error: DataFusionError::Internal(_),
|
||||
..
|
||||
}
|
||||
) {
|
||||
assert!(error.output_msg().contains("neutral internal error"));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -25,7 +25,7 @@ use std::sync::Arc;
|
||||
use datafusion::error::Result as DfResult;
|
||||
use datafusion::logical_expr::{Expr, Literal, Operator, utils};
|
||||
use datafusion::physical_plan::PhysicalExpr;
|
||||
use datafusion_common::arrow::array::{ArrayRef, Datum};
|
||||
use datafusion_common::arrow::array::{ArrayRef, Datum, Scalar};
|
||||
use datafusion_common::arrow::buffer::BooleanBuffer;
|
||||
use datafusion_common::cast::{as_boolean_array, as_null_array};
|
||||
use datafusion_common::{DataFusionError, ScalarValue, internal_err};
|
||||
@@ -79,6 +79,7 @@ impl MetadataFilter {
|
||||
|
||||
/// Evaluates supported single-column predicates with precompiled regular expressions.
|
||||
/// Compound predicates preserve SQL null semantics until conversion to a scan mask.
|
||||
/// Float comparisons treat `-0.0` and `+0.0` as equal, as DataFusion does.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct SimpleFilterEvaluator {
|
||||
column_name: String,
|
||||
@@ -104,7 +105,9 @@ impl SimpleFilterEvaluator {
|
||||
Some(Self {
|
||||
column_name,
|
||||
predicate: SimplePredicate::Comparison {
|
||||
literal: value.to_scalar().ok()?,
|
||||
literal: datafusion_common::utils::normalize_float_zero_scalar(value)
|
||||
.to_scalar()
|
||||
.ok()?,
|
||||
op,
|
||||
regex: None,
|
||||
regex_negative: false,
|
||||
@@ -224,11 +227,15 @@ impl SimpleFilterEvaluator {
|
||||
let input = input
|
||||
.to_scalar()
|
||||
.with_context(|_| ToArrowScalarSnafu { v: input.clone() })?;
|
||||
let input = Scalar::new(datafusion_common::utils::normalize_float_zero(
|
||||
&input.into_inner(),
|
||||
));
|
||||
Ok(self.evaluate_datum(&input, 1)?.value(0))
|
||||
}
|
||||
|
||||
pub fn evaluate_array(&self, input: &ArrayRef) -> Result<BooleanBuffer> {
|
||||
self.evaluate_datum(input, input.len())
|
||||
let input = datafusion_common::utils::normalize_float_zero(input);
|
||||
self.evaluate_datum(&input, input.len())
|
||||
}
|
||||
|
||||
pub fn evaluate_vector(&self, input: &VectorRef) -> Result<BooleanBuffer> {
|
||||
|
||||
@@ -98,7 +98,9 @@ impl SimplePredicate {
|
||||
};
|
||||
let (regex, regex_negative) = Self::maybe_build_regex(op, literal).ok()?;
|
||||
Some(Self::Comparison {
|
||||
literal: literal.to_scalar().ok()?,
|
||||
literal: datafusion_common::utils::normalize_float_zero_scalar(literal.clone())
|
||||
.to_scalar()
|
||||
.ok()?,
|
||||
op,
|
||||
regex,
|
||||
regex_negative,
|
||||
@@ -626,6 +628,103 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn float_zero_predicates_match_datafusion() {
|
||||
use datafusion::prelude::SessionContext;
|
||||
use datatypes::arrow::array::{Float32Array, Float64Array, Int32Array};
|
||||
|
||||
let float64: ArrayRef = Arc::new(Float64Array::from(vec![
|
||||
Some(-0.0),
|
||||
Some(0.0),
|
||||
Some(1.0),
|
||||
Some(f64::NAN),
|
||||
None,
|
||||
]));
|
||||
let float32: ArrayRef = Arc::new(Float32Array::from(vec![
|
||||
Some(-0.0),
|
||||
Some(0.0),
|
||||
Some(1.0),
|
||||
Some(f32::NAN),
|
||||
None,
|
||||
]));
|
||||
for input in [float64, float32] {
|
||||
let literal = |v: f64| {
|
||||
if input.data_type() == &DataType::Float32 {
|
||||
lit(v as f32)
|
||||
} else {
|
||||
lit(v)
|
||||
}
|
||||
};
|
||||
let ctx = SessionContext::new();
|
||||
let schema = Arc::new(Schema::new(vec![
|
||||
Field::new("v", input.data_type().clone(), true),
|
||||
Field::new("id", DataType::Int32, false),
|
||||
]));
|
||||
ctx.register_batch(
|
||||
"floats",
|
||||
RecordBatch::try_new(
|
||||
schema,
|
||||
vec![
|
||||
input.clone(),
|
||||
Arc::new(Int32Array::from_iter_values(0..input.len() as i32)),
|
||||
],
|
||||
)
|
||||
.unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
for expr in [
|
||||
col("v").eq(literal(0.0)),
|
||||
col("v").eq(literal(-0.0)),
|
||||
col("v").not_eq(literal(-0.0)),
|
||||
col("v").lt(literal(0.0)),
|
||||
col("v").lt_eq(literal(-0.0)),
|
||||
col("v").gt(literal(-0.0)),
|
||||
col("v").gt_eq(literal(0.0)),
|
||||
literal(0.0).lt_eq(col("v")),
|
||||
col("v").eq(literal(0.0)).or(col("v").eq(literal(1.0))),
|
||||
col("v").eq(literal(f64::NAN)),
|
||||
] {
|
||||
let expected = ctx
|
||||
.table("floats")
|
||||
.await
|
||||
.unwrap()
|
||||
.filter(expr.clone())
|
||||
.unwrap()
|
||||
.collect()
|
||||
.await
|
||||
.unwrap()
|
||||
.iter()
|
||||
.flat_map(|batch| {
|
||||
batch
|
||||
.column_by_name("id")
|
||||
.unwrap()
|
||||
.as_any()
|
||||
.downcast_ref::<Int32Array>()
|
||||
.unwrap()
|
||||
.values()
|
||||
.to_vec()
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
let evaluator = SimpleFilterEvaluator::try_new(&expr).unwrap();
|
||||
let mask = evaluator.evaluate_array(&input).unwrap();
|
||||
let selected = mask
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter_map(|(i, matched)| matched.then_some(i as i32))
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!(selected, expected, "{expr}");
|
||||
for (i, matched) in mask.iter().enumerate() {
|
||||
let scalar = ScalarValue::try_from_array(&input, i).unwrap();
|
||||
assert_eq!(
|
||||
evaluator.evaluate_scalar(&scalar).unwrap(),
|
||||
matched,
|
||||
"{expr}, row={i}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn supported_filter_op() {
|
||||
// equal
|
||||
|
||||
@@ -13,6 +13,7 @@
|
||||
// limitations under the License.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::mem::size_of;
|
||||
use std::slice;
|
||||
use std::sync::Arc;
|
||||
|
||||
@@ -20,7 +21,8 @@ use datafusion::arrow::util::pretty::pretty_format_batches;
|
||||
use datafusion_common::arrow::array::ArrayRef;
|
||||
use datafusion_common::arrow::compute;
|
||||
use datafusion_common::arrow::datatypes::{DataType as ArrowDataType, SchemaRef as ArrowSchemaRef};
|
||||
use datatypes::arrow::array::{Array, AsArray, RecordBatchOptions};
|
||||
use datatypes::arrow::array::{Array, AsArray, OffsetSizeTrait, RecordBatchOptions};
|
||||
use datatypes::arrow::util::bit_util;
|
||||
use datatypes::prelude::DataType;
|
||||
use datatypes::schema::SchemaRef;
|
||||
use datatypes::vectors::{Helper, VectorRef};
|
||||
@@ -270,6 +272,11 @@ impl RecordBatch {
|
||||
/// traversed or accounted. It is not an exact measure of live physical memory. If Arrow cannot
|
||||
/// calculate a slice's size, the full buffer size is used conservatively.
|
||||
///
|
||||
/// Flat columns (fixed-width primitives, timestamps, booleans, and `Utf8`/`LargeUtf8`/
|
||||
/// `Binary`/`LargeBinary`) are measured directly from their typed arrays using Arrow's own
|
||||
/// formula (see [`flat_slice_memory_size`]), so the scan hot path does not materialize an
|
||||
/// `ArrayData` per column per batch. All other types use Arrow's calculation.
|
||||
///
|
||||
/// Mito's current scan paths do not produce top-level View arrays. If they do in the future,
|
||||
/// their out-of-line payload accounting must be reassessed here.
|
||||
pub fn logical_slice_memory_size(&self) -> usize {
|
||||
@@ -277,11 +284,7 @@ impl RecordBatch {
|
||||
.columns()
|
||||
.iter()
|
||||
.fold(0, |total, array| {
|
||||
let array_size = array
|
||||
.to_data()
|
||||
.get_slice_memory_size()
|
||||
.unwrap_or_else(|_| array.get_buffer_memory_size());
|
||||
total.saturating_add(array_size)
|
||||
total.saturating_add(logical_column_memory_size(array))
|
||||
})
|
||||
}
|
||||
|
||||
@@ -331,6 +334,97 @@ impl RecordBatch {
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns Arrow's logical slice memory size of a single column.
|
||||
///
|
||||
/// This is `array.to_data().get_slice_memory_size()`, with the full buffer size as a conservative
|
||||
/// fallback when Arrow cannot calculate the slice size. Flat columns are measured from their typed
|
||||
/// array (see [`flat_slice_memory_size`]) so that no `ArrayData` is materialized for them.
|
||||
fn logical_column_memory_size(array: &dyn Array) -> usize {
|
||||
flat_slice_memory_size(array).unwrap_or_else(|| {
|
||||
array
|
||||
.to_data()
|
||||
.get_slice_memory_size()
|
||||
.unwrap_or_else(|_| array.get_buffer_memory_size())
|
||||
})
|
||||
}
|
||||
|
||||
/// Computes `array.to_data().get_slice_memory_size()` for flat arrays without building the
|
||||
/// `ArrayData`.
|
||||
///
|
||||
/// The formulas mirror Arrow's `ArrayData::get_slice_memory_size` (arrow-data 59.2.0,
|
||||
/// `get_slice_memory_size` in `arrow-data/src/data.rs`):
|
||||
///
|
||||
/// - a fixed-width value buffer costs `len * byte_width`, where the byte width is the one of the
|
||||
/// type's buffer layout, as reported by `DataType::primitive_width`,
|
||||
/// - the value bitmap of a boolean array costs `ceil(len / 8)`,
|
||||
/// - the offsets buffer of a variable-width array holds `len + 1` boundaries and costs
|
||||
/// `(len + 1) * offset_width`,
|
||||
/// - the visible value bytes of a variable-width array cost `offset[len] - offset[0]`,
|
||||
/// - the validity bitmap costs `ceil(len / 8)`, but only if the slice contains a null: converting
|
||||
/// an array to `ArrayData` drops a validity bitmap without any null (`ArrayDataBuilder::build`),
|
||||
/// so Arrow only sees one when `null_count` is non-zero.
|
||||
///
|
||||
/// Returns `None` for data types that are left to Arrow's general computation (nested, view,
|
||||
/// dictionary, union, `FixedSizeBinary`, `Null`, ...) and when the size computation overflows
|
||||
/// `usize`, which Arrow reports as an error. Callers must then fall back to Arrow.
|
||||
fn flat_slice_memory_size(array: &dyn Array) -> Option<usize> {
|
||||
let len = array.len();
|
||||
let validity_size = if array.null_count() != 0 {
|
||||
bit_util::ceil(len, 8)
|
||||
} else {
|
||||
0
|
||||
};
|
||||
|
||||
match array.data_type() {
|
||||
ArrowDataType::Boolean => bit_util::ceil(len, 8).checked_add(validity_size),
|
||||
ArrowDataType::Utf8 => {
|
||||
offset_slice_memory_size(len, array.as_string::<i32>().offsets(), validity_size)
|
||||
}
|
||||
ArrowDataType::LargeUtf8 => {
|
||||
offset_slice_memory_size(len, array.as_string::<i64>().offsets(), validity_size)
|
||||
}
|
||||
ArrowDataType::Binary => {
|
||||
offset_slice_memory_size(len, array.as_binary::<i32>().offsets(), validity_size)
|
||||
}
|
||||
ArrowDataType::LargeBinary => {
|
||||
offset_slice_memory_size(len, array.as_binary::<i64>().offsets(), validity_size)
|
||||
}
|
||||
data_type => data_type
|
||||
.primitive_width()
|
||||
.and_then(|byte_width| fixed_width_slice_memory_size(len, byte_width, validity_size)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns `len * byte_width + validity_size`, or `None` on overflow.
|
||||
#[inline]
|
||||
fn fixed_width_slice_memory_size(
|
||||
len: usize,
|
||||
byte_width: usize,
|
||||
validity_size: usize,
|
||||
) -> Option<usize> {
|
||||
len.checked_mul(byte_width)?.checked_add(validity_size)
|
||||
}
|
||||
|
||||
/// Returns `(len + 1) * offset_width + (offsets[len] - offsets[0]) + validity_size`, or `None` on
|
||||
/// overflow.
|
||||
///
|
||||
/// `offsets` are the offsets of the visible slice, so `offsets[0]` is the first visible byte and
|
||||
/// `offsets[len]` is the end of the last visible value. The offsets buffer size is checked before
|
||||
/// `offsets[len]` is read, so a `len` that cannot come from a valid offsets buffer is reported as
|
||||
/// an overflow instead of panicking.
|
||||
#[inline]
|
||||
fn offset_slice_memory_size<O: OffsetSizeTrait>(
|
||||
len: usize,
|
||||
offsets: &[O],
|
||||
validity_size: usize,
|
||||
) -> Option<usize> {
|
||||
let offsets_size = len.checked_add(1)?.checked_mul(size_of::<O>())?;
|
||||
let values_size = (offsets[len] - offsets[0]).as_usize();
|
||||
offsets_size
|
||||
.checked_add(values_size)?
|
||||
.checked_add(validity_size)
|
||||
}
|
||||
|
||||
impl Serialize for RecordBatch {
|
||||
fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
|
||||
where
|
||||
@@ -375,12 +469,26 @@ pub fn merge_record_batches(schema: SchemaRef, batches: &[RecordBatch]) -> Resul
|
||||
mod tests {
|
||||
use std::sync::Arc;
|
||||
|
||||
use datatypes::arrow::array::{AsArray, StringArray, StringViewArray, UInt32Array};
|
||||
use datatypes::arrow::datatypes::{DataType, Field, Schema as ArrowSchema, UInt32Type};
|
||||
use datatypes::arrow::array::{
|
||||
ArrayRef, AsArray, BinaryArray, BooleanArray, DictionaryArray, FixedSizeBinaryArray,
|
||||
Int32Array, LargeBinaryArray, LargeStringArray, ListArray, PrimitiveArray, StringArray,
|
||||
StringViewArray, TimestampMillisecondArray, UInt32Array,
|
||||
};
|
||||
use datatypes::arrow::buffer::{NullBuffer, ScalarBuffer};
|
||||
use datatypes::arrow::datatypes::{
|
||||
ArrowNativeType, ArrowPrimitiveType, DataType, Date32Type, Date64Type, Decimal128Type,
|
||||
Decimal256Type, DurationMicrosecondType, Field, Float32Type, Float64Type, Int8Type,
|
||||
Int16Type, Int32Type, Int64Type, IntervalDayTimeType, IntervalMonthDayNanoType,
|
||||
IntervalYearMonthType, Schema as ArrowSchema, Time32MillisecondType, Time64NanosecondType,
|
||||
TimestampMicrosecondType, TimestampMillisecondType, TimestampNanosecondType,
|
||||
TimestampSecondType, UInt8Type, UInt16Type, UInt32Type, UInt64Type,
|
||||
};
|
||||
use datatypes::data_type::ConcreteDataType;
|
||||
use datatypes::extension::json::JsonExtensionType;
|
||||
use datatypes::schema::{ColumnSchema, Schema};
|
||||
use datatypes::vectors::{BinaryVector, StringVector, UInt32Vector};
|
||||
use datatypes::vectors::{
|
||||
BinaryVector, BooleanVector, StringVector, UInt32Vector, UInt64Vector,
|
||||
};
|
||||
|
||||
use super::*;
|
||||
|
||||
@@ -558,6 +666,486 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
/// Arrow's own computation for a single array, the reference for the fast path.
|
||||
fn arrow_slice_memory_size(array: &dyn Array) -> usize {
|
||||
array
|
||||
.to_data()
|
||||
.get_slice_memory_size()
|
||||
.unwrap_or_else(|_| array.get_buffer_memory_size())
|
||||
}
|
||||
|
||||
/// Slices probed for every array: the whole array, empty slices at both ends, single element
|
||||
/// slices, a non byte aligned range, and slices that skip a prefix or a suffix.
|
||||
fn probe_ranges(len: usize) -> Vec<(usize, usize)> {
|
||||
if len == 0 {
|
||||
return vec![(0, 0)];
|
||||
}
|
||||
|
||||
let mut ranges = vec![
|
||||
(0, 0),
|
||||
(len, 0),
|
||||
(0, 1),
|
||||
(len - 1, 1),
|
||||
(1, len.saturating_sub(1)),
|
||||
(len / 3, len / 3),
|
||||
];
|
||||
if len >= 8 {
|
||||
ranges.push((3, 5));
|
||||
}
|
||||
ranges
|
||||
}
|
||||
|
||||
/// Asserts the fast path covers `array` and agrees with Arrow's own formula.
|
||||
#[track_caller]
|
||||
fn assert_fast_path_matches_arrow(name: &str, array: &dyn Array) {
|
||||
let expected = arrow_slice_memory_size(array);
|
||||
let Some(actual) = flat_slice_memory_size(array) else {
|
||||
panic!("{name}: fast path must cover {:?}", array.data_type());
|
||||
};
|
||||
|
||||
assert_eq!(
|
||||
expected,
|
||||
actual,
|
||||
"{name}: fast path disagrees with Arrow for {:?} (len {}, null count {})",
|
||||
array.data_type(),
|
||||
array.len(),
|
||||
array.null_count()
|
||||
);
|
||||
assert_eq!(
|
||||
expected,
|
||||
logical_column_memory_size(array),
|
||||
"{name}: column size disagrees with Arrow for {:?}",
|
||||
array.data_type()
|
||||
);
|
||||
}
|
||||
|
||||
/// Asserts the fast path agrees with Arrow for `array` and all probe slices of it.
|
||||
fn assert_fast_path_matches_arrow_on_slices(name: &str, array: &ArrayRef) {
|
||||
assert_fast_path_matches_arrow(name, array.as_ref());
|
||||
|
||||
for (offset, len) in probe_ranges(array.len()) {
|
||||
let slice = array.slice(offset, len);
|
||||
assert_fast_path_matches_arrow(
|
||||
&format!("{name}[{offset}..{}]", offset + len),
|
||||
slice.as_ref(),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns a full array, an array with a few nulls and an all-null array of `len` values.
|
||||
fn primitive_cases<T: ArrowPrimitiveType>(len: usize) -> Vec<ArrayRef> {
|
||||
let values = (0..len)
|
||||
.map(|index| Some(T::Native::usize_as(index)))
|
||||
.collect::<PrimitiveArray<T>>();
|
||||
let with_nulls = (0..len)
|
||||
.map(|index| (index % 3 != 0).then(|| T::Native::usize_as(index)))
|
||||
.collect::<PrimitiveArray<T>>();
|
||||
let all_null = (0..len)
|
||||
.map(|_| None::<T::Native>)
|
||||
.collect::<PrimitiveArray<T>>();
|
||||
|
||||
vec![
|
||||
Arc::new(values) as ArrayRef,
|
||||
Arc::new(with_nulls),
|
||||
Arc::new(all_null),
|
||||
]
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_flat_slice_memory_size_matches_arrow_for_fixed_width_types() {
|
||||
macro_rules! check {
|
||||
($($ty:ty),* $(,)?) => {
|
||||
$(
|
||||
for (index, array) in primitive_cases::<$ty>(13).into_iter().enumerate() {
|
||||
assert_fast_path_matches_arrow_on_slices(
|
||||
&format!("{}-{index}", stringify!($ty)),
|
||||
&array,
|
||||
);
|
||||
}
|
||||
)*
|
||||
};
|
||||
}
|
||||
|
||||
check!(
|
||||
Int8Type,
|
||||
Int16Type,
|
||||
Int32Type,
|
||||
Int64Type,
|
||||
UInt8Type,
|
||||
UInt16Type,
|
||||
UInt32Type,
|
||||
UInt64Type,
|
||||
Float32Type,
|
||||
Float64Type,
|
||||
Date32Type,
|
||||
Date64Type,
|
||||
Time32MillisecondType,
|
||||
Time64NanosecondType,
|
||||
TimestampSecondType,
|
||||
TimestampMillisecondType,
|
||||
TimestampMicrosecondType,
|
||||
TimestampNanosecondType,
|
||||
DurationMicrosecondType,
|
||||
IntervalYearMonthType,
|
||||
IntervalDayTimeType,
|
||||
IntervalMonthDayNanoType,
|
||||
Decimal128Type,
|
||||
Decimal256Type,
|
||||
);
|
||||
|
||||
// Guard against a vacuous differential test: `len` values cost `len * width`, plus one
|
||||
// bitmap byte per 8 values when the array is nullable.
|
||||
let len = 13;
|
||||
let plain = Int32Array::from((0..len as i32).collect::<Vec<_>>());
|
||||
assert_eq!(Some(len * 4), flat_slice_memory_size(&plain));
|
||||
let nullable = Int32Array::from(
|
||||
(0..len)
|
||||
.map(|index| (index % 2 == 0).then_some(index as i32))
|
||||
.collect::<Vec<_>>(),
|
||||
);
|
||||
assert_eq!(
|
||||
Some(len * 4 + bit_util::ceil(len, 8)),
|
||||
flat_slice_memory_size(&nullable)
|
||||
);
|
||||
|
||||
// Timestamps with a timezone share the `Int64` layout.
|
||||
let with_timezone =
|
||||
Arc::new(TimestampMillisecondArray::from(vec![1_i64, 2, 3]).with_timezone_utc())
|
||||
as ArrayRef;
|
||||
assert_fast_path_matches_arrow_on_slices("timestamp-utc", &with_timezone);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_flat_slice_memory_size_matches_arrow_for_byte_arrays() {
|
||||
// Empty, short (inline) and long (out of line) values, plus nulls.
|
||||
let strings: Vec<Option<&str>> = vec![
|
||||
Some(""),
|
||||
Some("a"),
|
||||
Some("greptime"),
|
||||
Some("a value that is much longer than twelve bytes"),
|
||||
None,
|
||||
Some(""),
|
||||
Some("z"),
|
||||
Some("another long value that exceeds the inline limit"),
|
||||
None,
|
||||
];
|
||||
let bytes: Vec<Option<&[u8]>> = strings
|
||||
.iter()
|
||||
.map(|value| value.map(str::as_bytes))
|
||||
.collect();
|
||||
|
||||
let cases: Vec<(&str, ArrayRef)> = vec![
|
||||
("utf8", Arc::new(StringArray::from(strings.clone()))),
|
||||
(
|
||||
"large-utf8",
|
||||
Arc::new(LargeStringArray::from(strings.clone())),
|
||||
),
|
||||
("binary", Arc::new(BinaryArray::from(bytes.clone()))),
|
||||
("large-binary", Arc::new(LargeBinaryArray::from(bytes))),
|
||||
];
|
||||
|
||||
for (name, array) in cases {
|
||||
assert_fast_path_matches_arrow_on_slices(name, &array);
|
||||
|
||||
// `(len + 1) * offset_width + visible value bytes`, plus the validity bitmap.
|
||||
let len = array.len();
|
||||
let offset_width = match array.data_type() {
|
||||
DataType::Utf8 | DataType::Binary => 4,
|
||||
DataType::LargeUtf8 | DataType::LargeBinary => 8,
|
||||
other => panic!("unexpected type {other}"),
|
||||
};
|
||||
let visible: usize = strings.iter().map(|value| value.map_or(0, str::len)).sum();
|
||||
let mut expected = (len + 1) * offset_width + visible;
|
||||
if array.null_count() != 0 {
|
||||
expected += bit_util::ceil(len, 8);
|
||||
}
|
||||
assert_eq!(
|
||||
Some(expected),
|
||||
flat_slice_memory_size(array.as_ref()),
|
||||
"{name}"
|
||||
);
|
||||
}
|
||||
|
||||
// Zero rows keep one offset boundary per array, and nothing else.
|
||||
let empty = Arc::new(StringArray::from(Vec::<Option<&str>>::new())) as ArrayRef;
|
||||
assert_eq!(Some(4), flat_slice_memory_size(empty.as_ref()));
|
||||
assert_eq!(4, arrow_slice_memory_size(empty.as_ref()));
|
||||
assert_fast_path_matches_arrow("utf8-empty", empty.as_ref());
|
||||
|
||||
let empty_large = Arc::new(LargeStringArray::from(Vec::<Option<&str>>::new())) as ArrayRef;
|
||||
assert_eq!(Some(8), flat_slice_memory_size(empty_large.as_ref()));
|
||||
assert_fast_path_matches_arrow("large-utf8-empty", empty_large.as_ref());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_flat_slice_memory_size_matches_arrow_for_boolean_bitmaps() {
|
||||
// Lengths around byte boundaries of the value bitmap.
|
||||
for len in [0_usize, 1, 7, 8, 9, 15, 16, 17, 33] {
|
||||
let plain =
|
||||
BooleanArray::from((0..len).map(|index| index % 3 == 0).collect::<Vec<_>>());
|
||||
let nullable = BooleanArray::from(
|
||||
(0..len)
|
||||
.map(|index| (index % 4 != 0).then_some(index % 3 == 0))
|
||||
.collect::<Vec<_>>(),
|
||||
);
|
||||
let all_null = BooleanArray::from(vec![None::<bool>; len]);
|
||||
|
||||
let cases: Vec<(&str, ArrayRef)> = vec![
|
||||
("plain", Arc::new(plain)),
|
||||
("nullable", Arc::new(nullable)),
|
||||
("all-null", Arc::new(all_null)),
|
||||
];
|
||||
|
||||
for (kind, array) in cases {
|
||||
let name = format!("boolean-{kind}-{len}");
|
||||
assert_fast_path_matches_arrow_on_slices(&name, &array);
|
||||
|
||||
// A value bitmap, plus a validity bitmap when the slice contains a null.
|
||||
let bitmaps = if array.null_count() != 0 { 2 } else { 1 };
|
||||
assert_eq!(
|
||||
Some(bit_util::ceil(len, 8) * bitmaps),
|
||||
flat_slice_memory_size(array.as_ref()),
|
||||
"{name}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_flat_slice_memory_size_ignores_null_free_validity_bitmap() {
|
||||
// A validity bitmap without any null value is free: `ArrayDataBuilder::build` drops it, so
|
||||
// Arrow's formula does not charge for it even though the physical buffer exists.
|
||||
let array = Arc::new(Int32Array::new(
|
||||
ScalarBuffer::from(vec![1_i32, 2, 3, 4, 5]),
|
||||
Some(NullBuffer::new_valid(5)),
|
||||
)) as ArrayRef;
|
||||
|
||||
assert_eq!(0, array.null_count());
|
||||
assert!(array.nulls().is_some());
|
||||
assert_eq!(Some(5 * 4), flat_slice_memory_size(array.as_ref()));
|
||||
assert_fast_path_matches_arrow_on_slices("int32-validity-only", &array);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_flat_slice_memory_size_matches_arrow_for_zero_rows() {
|
||||
let schema = Arc::new(Schema::new(vec![
|
||||
ColumnSchema::new("numbers", ConcreteDataType::uint64_datatype(), true),
|
||||
ColumnSchema::new("flags", ConcreteDataType::boolean_datatype(), true),
|
||||
ColumnSchema::new("strings", ConcreteDataType::string_datatype(), true),
|
||||
ColumnSchema::new("binary", ConcreteDataType::binary_datatype(), true),
|
||||
]));
|
||||
let columns: Vec<VectorRef> = vec![
|
||||
Arc::new(UInt64Vector::from_slice([1_u64, 2, 3])),
|
||||
Arc::new(BooleanVector::from(vec![Some(true), None, Some(false)])),
|
||||
Arc::new(StringVector::from(vec![Some("a"), None, Some("ccc")])),
|
||||
Arc::new(BinaryVector::from(vec![
|
||||
Some(vec![1_u8]),
|
||||
None,
|
||||
Some(vec![2_u8, 3]),
|
||||
])),
|
||||
];
|
||||
let batch = RecordBatch::new(schema, columns).unwrap();
|
||||
let empty = batch.slice(0, 0).unwrap();
|
||||
|
||||
assert_eq!(0, empty.num_rows());
|
||||
for (index, column) in empty.columns().iter().enumerate() {
|
||||
assert_fast_path_matches_arrow(&format!("empty-column-{index}"), column.as_ref());
|
||||
}
|
||||
|
||||
let expected: usize = empty
|
||||
.columns()
|
||||
.iter()
|
||||
.map(|column| arrow_slice_memory_size(column.as_ref()))
|
||||
.sum();
|
||||
assert_eq!(expected, empty.logical_slice_memory_size());
|
||||
// Only the offsets of the string and binary columns survive.
|
||||
assert_eq!(4 + 4, empty.logical_slice_memory_size());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_flat_slice_memory_size_for_many_slices_of_shared_backing() {
|
||||
let schema = Arc::new(Schema::new(vec![
|
||||
ColumnSchema::new("strings", ConcreteDataType::string_datatype(), false),
|
||||
ColumnSchema::new("numbers", ConcreteDataType::uint64_datatype(), false),
|
||||
ColumnSchema::new("flags", ConcreteDataType::boolean_datatype(), false),
|
||||
]));
|
||||
let strings = (0..1024)
|
||||
.map(|value| format!("shared-value-{value}"))
|
||||
.collect::<Vec<_>>();
|
||||
let numbers = (0_u64..1024).collect::<Vec<_>>();
|
||||
let flags = (0..1024).map(|value| value % 3 == 0).collect::<Vec<_>>();
|
||||
let backing = RecordBatch::new(
|
||||
schema,
|
||||
vec![
|
||||
Arc::new(StringVector::from(strings)) as VectorRef,
|
||||
Arc::new(UInt64Vector::from_slice(numbers)),
|
||||
Arc::new(BooleanVector::from(flags)),
|
||||
],
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let slices = (0..128)
|
||||
.map(|index| backing.slice(index * 4, 3).unwrap())
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
for slice in &slices {
|
||||
for column in slice.columns() {
|
||||
assert_fast_path_matches_arrow("shared-backing", column.as_ref());
|
||||
}
|
||||
let expected: usize = slice
|
||||
.columns()
|
||||
.iter()
|
||||
.map(|column| arrow_slice_memory_size(column.as_ref()))
|
||||
.sum();
|
||||
assert_eq!(expected, slice.logical_slice_memory_size());
|
||||
}
|
||||
|
||||
let logical_total = slices
|
||||
.iter()
|
||||
.map(RecordBatch::logical_slice_memory_size)
|
||||
.sum::<usize>();
|
||||
let buffer_total = slices
|
||||
.iter()
|
||||
.map(RecordBatch::buffer_memory_size)
|
||||
.sum::<usize>();
|
||||
assert!(logical_total < buffer_total);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_logical_slice_memory_size_matches_arrow_for_mixed_slices() {
|
||||
let schema = Arc::new(Schema::new(vec![
|
||||
ColumnSchema::new("numbers", ConcreteDataType::uint32_datatype(), false),
|
||||
ColumnSchema::new("flags", ConcreteDataType::boolean_datatype(), true),
|
||||
ColumnSchema::new("strings", ConcreteDataType::string_datatype(), true),
|
||||
ColumnSchema::new("binary", ConcreteDataType::binary_datatype(), true),
|
||||
]));
|
||||
let numbers: Vec<u32> = (0..512).collect();
|
||||
let flags = (0..512)
|
||||
.map(|value| (value % 5 != 0).then_some(value % 3 == 0))
|
||||
.collect::<Vec<_>>();
|
||||
let strings = (0..512)
|
||||
.map(|value| (value % 4 != 0).then(|| format!("value-{value}")))
|
||||
.collect::<Vec<_>>();
|
||||
let binary = (0..512_u32)
|
||||
.map(|value| (value % 4 != 0).then(|| value.to_le_bytes().to_vec()))
|
||||
.collect::<Vec<_>>();
|
||||
let batch = RecordBatch::new(
|
||||
schema,
|
||||
vec![
|
||||
Arc::new(UInt32Vector::from_slice(numbers)) as VectorRef,
|
||||
Arc::new(BooleanVector::from(flags)),
|
||||
Arc::new(StringVector::from(strings)),
|
||||
Arc::new(BinaryVector::from(binary)),
|
||||
],
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
for (offset, len) in [(0, 512), (0, 0), (511, 1), (1, 511), (3, 5), (256, 3)] {
|
||||
let slice = batch.slice(offset, len).unwrap();
|
||||
|
||||
for column in slice.columns() {
|
||||
assert_fast_path_matches_arrow("mixed-slice", column.as_ref());
|
||||
}
|
||||
let expected: usize = slice
|
||||
.columns()
|
||||
.iter()
|
||||
.map(|column| arrow_slice_memory_size(column.as_ref()))
|
||||
.sum();
|
||||
assert_eq!(
|
||||
expected,
|
||||
slice.logical_slice_memory_size(),
|
||||
"slice({offset}, {len})"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_flat_slice_memory_size_declines_on_overflow() {
|
||||
// `len * byte_width` overflows `usize`, Arrow reports an error for it.
|
||||
assert_eq!(
|
||||
None,
|
||||
fixed_width_slice_memory_size(usize::MAX / 8 + 1, 8, 0)
|
||||
);
|
||||
// The validity bitmap pushes the total over the edge.
|
||||
assert_eq!(None, fixed_width_slice_memory_size(usize::MAX, 1, 8));
|
||||
// `(len + 1) * offset_width` overflows `usize`.
|
||||
assert_eq!(
|
||||
None,
|
||||
offset_slice_memory_size::<i32>(usize::MAX, &[0, 0], 0)
|
||||
);
|
||||
// The visible value bytes push the total over the edge.
|
||||
assert_eq!(
|
||||
None,
|
||||
offset_slice_memory_size::<i32>(1, &[0, i32::MAX], usize::MAX)
|
||||
);
|
||||
// In range sizes are still computed: `(len + 1) * 4` offsets plus `offsets[2] - offsets[0]`
|
||||
// visible value bytes.
|
||||
assert_eq!(Some(16), fixed_width_slice_memory_size(2, 8, 0));
|
||||
assert_eq!(
|
||||
Some(3 * 4 + 3),
|
||||
offset_slice_memory_size::<i32>(2, &[7, 9, 10], 0)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_logical_column_memory_size_falls_back_for_other_types() {
|
||||
let view = StringViewArray::from(vec![
|
||||
"a short view",
|
||||
"a much longer string view value that is stored out of line",
|
||||
"",
|
||||
]);
|
||||
let dictionary = DictionaryArray::<Int32Type>::from_iter(vec![
|
||||
Some("first"),
|
||||
None,
|
||||
Some("a longer dictionary value"),
|
||||
]);
|
||||
let list = ListArray::from_iter_primitive::<Int32Type, _, _>(vec![
|
||||
Some(vec![Some(1), Some(2), None]),
|
||||
None,
|
||||
Some(vec![Some(3)]),
|
||||
]);
|
||||
let first: [u8; 3] = [1, 2, 3];
|
||||
let second: [u8; 3] = [4, 5, 6];
|
||||
let fixed_size_binary = FixedSizeBinaryArray::try_from(vec![
|
||||
Some(first.as_slice()),
|
||||
None::<&[u8]>,
|
||||
Some(second.as_slice()),
|
||||
])
|
||||
.unwrap();
|
||||
|
||||
let cases: Vec<(&str, ArrayRef)> = vec![
|
||||
("utf8-view", Arc::new(view)),
|
||||
("dictionary", Arc::new(dictionary)),
|
||||
("list", Arc::new(list)),
|
||||
("fixed-size-binary", Arc::new(fixed_size_binary)),
|
||||
];
|
||||
|
||||
for (name, array) in cases {
|
||||
assert_eq!(
|
||||
None,
|
||||
flat_slice_memory_size(array.as_ref()),
|
||||
"{name}: expected Arrow's fallback for {:?}",
|
||||
array.data_type()
|
||||
);
|
||||
|
||||
for (offset, len) in probe_ranges(array.len()) {
|
||||
let slice = array.slice(offset, len);
|
||||
assert_eq!(
|
||||
None,
|
||||
flat_slice_memory_size(slice.as_ref()),
|
||||
"{name}[{offset}..{}]: expected Arrow's fallback",
|
||||
offset + len
|
||||
);
|
||||
assert_eq!(
|
||||
arrow_slice_memory_size(slice.as_ref()),
|
||||
logical_column_memory_size(slice.as_ref()),
|
||||
"{name}[{offset}..{}]: fallback must match Arrow",
|
||||
offset + len
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_merge_record_batch() {
|
||||
let column_schemas = vec![
|
||||
|
||||
@@ -20,3 +20,6 @@ datafusion-substrait.workspace = true
|
||||
promql.workspace = true
|
||||
prost.workspace = true
|
||||
snafu.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
tokio.workspace = true
|
||||
|
||||
@@ -19,8 +19,8 @@ use datafusion::execution::registry::SerializerRegistry;
|
||||
use datafusion_common::DataFusionError;
|
||||
use datafusion_expr::UserDefinedLogicalNode;
|
||||
use promql::extension_plan::{
|
||||
Absent, EmptyMetric, HistogramFold, InstantManipulate, RangeManipulate, ScalarCalculate,
|
||||
SeriesDivide, SeriesNormalize, UnionDistinctOn,
|
||||
Absent, EmptyMetric, FusedSeries, HistogramFold, InstantManipulate, RangeManipulate,
|
||||
RawSeriesSource, ScalarCalculate, SeriesDivide, SeriesNormalize, UnionDistinctOn,
|
||||
};
|
||||
|
||||
#[derive(Debug)]
|
||||
@@ -31,6 +31,13 @@ impl SerializerRegistry for ExtensionSerializer {
|
||||
/// input plans.
|
||||
fn serialize_logical_plan(&self, node: &dyn UserDefinedLogicalNode) -> Result<Vec<u8>> {
|
||||
match node.name() {
|
||||
name if name == FusedSeries::name() => {
|
||||
let fused = node
|
||||
.as_any()
|
||||
.downcast_ref::<FusedSeries>()
|
||||
.expect("Failed to downcast to FusedSeries");
|
||||
fused.serialize()
|
||||
}
|
||||
name if name == InstantManipulate::name() => {
|
||||
let instant_manipulate = node
|
||||
.as_any()
|
||||
@@ -87,6 +94,13 @@ impl SerializerRegistry for ExtensionSerializer {
|
||||
.expect("Failed to downcast to UnionDistinctOn");
|
||||
Ok(union_distinct_on.serialize())
|
||||
}
|
||||
name if name == RawSeriesSource::name() => {
|
||||
let raw_series_source = node
|
||||
.as_any()
|
||||
.downcast_ref::<RawSeriesSource>()
|
||||
.expect("Failed to downcast to RawSeriesSource");
|
||||
Ok(raw_series_source.serialize())
|
||||
}
|
||||
name if name == EmptyMetric::name() => Err(DataFusionError::Substrait(
|
||||
"EmptyMetric should not be serialized".to_string(),
|
||||
)),
|
||||
@@ -105,6 +119,7 @@ impl SerializerRegistry for ExtensionSerializer {
|
||||
bytes: &[u8],
|
||||
) -> Result<Arc<dyn UserDefinedLogicalNode>> {
|
||||
match name {
|
||||
name if name == FusedSeries::name() => Ok(Arc::new(FusedSeries::deserialize(bytes)?)),
|
||||
name if name == InstantManipulate::name() => {
|
||||
let instant_manipulate = InstantManipulate::deserialize(bytes)?;
|
||||
Ok(Arc::new(instant_manipulate))
|
||||
@@ -137,6 +152,9 @@ impl SerializerRegistry for ExtensionSerializer {
|
||||
let union_distinct_on = UnionDistinctOn::deserialize(bytes)?;
|
||||
Ok(Arc::new(union_distinct_on))
|
||||
}
|
||||
name if name == RawSeriesSource::name() => {
|
||||
Ok(Arc::new(RawSeriesSource::deserialize(bytes)?))
|
||||
}
|
||||
name if name == EmptyMetric::name() => Err(DataFusionError::Substrait(
|
||||
"EmptyMetric should not be deserialized".to_string(),
|
||||
)),
|
||||
@@ -147,3 +165,91 @@ impl SerializerRegistry for ExtensionSerializer {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use datafusion::arrow::datatypes::{DataType, Field, Schema, TimeUnit};
|
||||
use datafusion::datasource::{MemTable, provider_as_source};
|
||||
use datafusion::execution::SessionStateBuilder;
|
||||
use datafusion::logical_expr::{Extension, LogicalPlan, LogicalPlanBuilder, col, lit};
|
||||
use datafusion::prelude::SessionContext;
|
||||
|
||||
use super::*;
|
||||
use crate::{DFLogicalSubstraitConvertor, SubstraitPlan};
|
||||
|
||||
#[tokio::test]
|
||||
async fn raw_series_source_substrait_roundtrip_restores_scan() {
|
||||
let table_name = "raw_source_input";
|
||||
let input_schema = Arc::new(Schema::new(vec![
|
||||
Field::new("z", DataType::Utf8, false),
|
||||
Field::new("value_b", DataType::Float64, false),
|
||||
Field::new("value_a", DataType::Float64, false),
|
||||
Field::new("a", DataType::Utf8, false),
|
||||
Field::new("unused", DataType::Utf8, true),
|
||||
Field::new(
|
||||
"ts",
|
||||
DataType::Timestamp(TimeUnit::Millisecond, None),
|
||||
false,
|
||||
),
|
||||
]));
|
||||
let provider = Arc::new(MemTable::try_new(input_schema, vec![vec![]]).unwrap());
|
||||
let filter = col("raw_source_input.z").eq(lit("web-1"));
|
||||
let input = LogicalPlanBuilder::scan_with_filters(
|
||||
table_name,
|
||||
provider_as_source(provider.clone()),
|
||||
Some(vec![0, 3, 2, 1, 5]),
|
||||
vec![filter],
|
||||
)
|
||||
.unwrap()
|
||||
.build()
|
||||
.unwrap();
|
||||
let LogicalPlan::TableScan(expected_scan) = &input else {
|
||||
panic!("expected table scan");
|
||||
};
|
||||
let expected_projection = expected_scan.projection.clone();
|
||||
let expected_schema = Arc::clone(&expected_scan.projected_schema);
|
||||
let expected_filters = expected_scan.filters.clone();
|
||||
let source = RawSeriesSource::try_new(
|
||||
Arc::from("http_requests_total"),
|
||||
vec!["z".into(), "a".into()],
|
||||
vec!["value_b".into(), "value_a".into()],
|
||||
input,
|
||||
)
|
||||
.unwrap();
|
||||
let expected_source_schema = Arc::clone(source.schema());
|
||||
let plan = LogicalPlan::Extension(Extension {
|
||||
node: Arc::new(source),
|
||||
});
|
||||
let converter = DFLogicalSubstraitConvertor;
|
||||
let bytes = converter.encode(&plan, ExtensionSerializer).unwrap();
|
||||
let state = SessionStateBuilder::new()
|
||||
.with_default_features()
|
||||
.with_serializer_registry(Arc::new(ExtensionSerializer))
|
||||
.build();
|
||||
let context = SessionContext::new_with_state(state);
|
||||
context.register_table(table_name, provider).unwrap();
|
||||
let decoded = converter.decode(bytes, context.state()).await.unwrap();
|
||||
|
||||
let LogicalPlan::Extension(extension) = decoded else {
|
||||
panic!("expected restored RawSeriesSource extension");
|
||||
};
|
||||
let restored = extension
|
||||
.node
|
||||
.as_any()
|
||||
.downcast_ref::<RawSeriesSource>()
|
||||
.expect("expected RawSeriesSource");
|
||||
assert_eq!(restored.metric_name(), "http_requests_total");
|
||||
assert_eq!(restored.tags(), ["z", "a"]);
|
||||
assert_eq!(restored.fields(), ["value_b", "value_a"]);
|
||||
assert_eq!(restored.schema(), &expected_source_schema);
|
||||
let inputs = extension.node.inputs();
|
||||
assert_eq!(inputs.len(), 1);
|
||||
let LogicalPlan::TableScan(scan) = inputs[0] else {
|
||||
panic!("expected restored table scan child, got: {inputs:?}");
|
||||
};
|
||||
assert_eq!(scan.table_name.to_string(), table_name);
|
||||
assert_eq!(scan.projection, expected_projection);
|
||||
assert_eq!(scan.projected_schema, expected_schema);
|
||||
assert_eq!(scan.filters, expected_filters);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,6 +15,7 @@ workspace = true
|
||||
backtrace = "0.3"
|
||||
common-base.workspace = true
|
||||
common-error.workspace = true
|
||||
common-macro.workspace = true
|
||||
common-version.workspace = true
|
||||
console-subscriber = { version = "0.1", optional = true }
|
||||
greptime-proto.workspace = true
|
||||
@@ -31,6 +32,7 @@ parking_lot.workspace = true
|
||||
prometheus.workspace = true
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
snafu.workspace = true
|
||||
tokio.workspace = true
|
||||
tracing = "0.1"
|
||||
tracing-appender.workspace = true
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user