diff --git a/.agents/skills/greptimedb-release-note/SKILL.md b/.agents/skills/greptimedb-release-note/SKILL.md index 026ad90cd8d..461c5149d5a 100644 --- a/.agents/skills/greptimedb-release-note/SKILL.md +++ b/.agents/skills/greptimedb-release-note/SKILL.md @@ -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 `` 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 /release/vX.Y /main) ``` @@ -80,14 +86,14 @@ small Python script is the reliable way — match `pull/)` 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 .. --tag vX.Y.Z -o ... +GITHUB_TOKEN=$(gh auth token) git cliff .. --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 `) — each `* fix: ... (#NN)` line is a picked PR. +(`git log -1 --format=%B `) — 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 '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 ../release/vX.Y`) belong to the next release, even if they are -already merged when you write the note. - The range `..` 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/ --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 | 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 --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: diff --git a/.agents/skills/greptimedb-release/SKILL.md b/.agents/skills/greptimedb-release/SKILL.md index 215493519ec..9efb60e646c 100644 --- a/.agents/skills/greptimedb-release/SKILL.md +++ b/.agents/skills/greptimedb-release/SKILL.md @@ -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 ``. Confirm with the user, then: ``` gh release create vX.Y.Z \ --repo GreptimeTeam/greptimedb \ - --target release/vX.Y \ + --target \ --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 diff --git a/.github/actions/deploy-greptimedb/action.yml b/.github/actions/deploy-greptimedb/action.yml index b18830ef8d7..634cae85dcd 100644 --- a/.github/actions/deploy-greptimedb/action.yml +++ b/.github/actions/deploy-greptimedb/action.yml @@ -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 diff --git a/.github/actions/sqlness-test/action.yml b/.github/actions/sqlness-test/action.yml index 004f2b40b16..255a175f7a0 100644 --- a/.github/actions/sqlness-test/action.yml +++ b/.github/actions/sqlness-test/action.yml @@ -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 diff --git a/.github/scripts/deploy-greptimedb.sh b/.github/scripts/deploy-greptimedb.sh index 92ca440dbd9..9747edc7796 100755 --- a/.github/scripts/deploy-greptimedb.sh +++ b/.github/scripts/deploy-greptimedb.sh @@ -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 \ diff --git a/.github/scripts/heavy-ci-policy.test.cjs b/.github/scripts/heavy-ci-policy.test.cjs index 093ff8c636b..9dfd030796e 100644 --- a/.github/scripts/heavy-ci-policy.test.cjs +++ b/.github/scripts/heavy-ci-policy.test.cjs @@ -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); + } + } +}); diff --git a/.github/workflows/nightly-ci.yml b/.github/workflows/nightly-ci.yml index 2b6862bb827..fe4e89cb59d 100644 --- a/.github/workflows/nightly-ci.yml +++ b/.github/workflows/nightly-ci.yml @@ -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 diff --git a/AGENTS.md b/AGENTS.md index 20b2689a401..4ff990a5542 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -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) diff --git a/Cargo.lock b/Cargo.lock index 373ce2873e9..865c701cafa 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -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", diff --git a/Cargo.toml b/Cargo.toml index 48e39ada226..7400aae11d5 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -164,7 +164,7 @@ fs2 = "0.4" fst = "0.4.7" futures = "0.3" futures-util = "0.3" -greptime-proto = { git = "https://github.com/GreptimeTeam/greptime-proto.git", rev = "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" } diff --git a/config/config.md b/config/config.md index 9bbed619ab3..8f8bddf3c0e 100644 --- a/config/config.md +++ b/config/config.md @@ -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.
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.
Legacy OTLP summary columns keep their historical `greptime_` prefix. | | `auto_create_table` | Bool | `true` | Server-side global switch for auto table creation on write.
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
(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". | | `user_provider` | String | Unset | 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:", "pbkdf2_sha256:::",
"mysql_native_password:",
"pg_scram_sha256::::"
"pbkdf2_sha256" and "pg_scram_sha256" protect passwords at rest, but such users cannot log in over MySQL:
`static_user_provider` and `watch_file_user_provider` only negotiate `mysql_native_password`, which cannot verify these formats.
"mysql_native_password" is MySQL-specific and cannot authenticate over PostgreSQL at all.
PostgreSQL SCRAM only covers "plain" and "pg_scram_sha256" users; if any user is "pbkdf2_sha256" or
"mysql_native_password", PostgreSQL falls back to cleartext password auth for every user.
For "pg_scram_sha256" users, keep the default iteration count (4096) and salt length (16): both are
observable in the SCRAM server-first message, and non-default values weaken resistance to username
enumeration. | -| `max_in_flight_write_bytes` | String | 0 | Maximum total memory for all concurrent write request bodies and messages (HTTP, gRPC, Flight).
Set to 0 to disable the limit. Default: "0" (unlimited) | -| `write_bytes_exhausted_policy` | String | `wait` | Policy when write bytes quota is exhausted.
Options: "wait" (default, 10s timeout), "wait()" (e.g., "wait(30s)"), "fail" | +| `max_in_flight_write_bytes` | String | 0 | 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) | +| `write_bytes_exhausted_policy` | String | `wait` | Policy when write bytes quota is exhausted.
Options: "wait" (default, 10s timeout), "wait()" (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. | | `init_regions_in_background` | Bool | `false` | Initialize all regions in the background during the startup.
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.
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.
The maximum number of procedures that can be running at the same time.
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.
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 | | `query.parallelism` | Integer | `0` | Parallelism of the query engine.
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,
and internal series merges during table scans).
Supports absolute size (e.g., "2GB", "4GB") or percentage of system memory (e.g., "20%").
Setting it to 0 disables the limit. Defaults to 0 (unlimited); this example sets it to `50%`.
When this limit is reached, queries will fail with ResourceExhausted error.
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:
- "greedy" (default): first-come-first-served allocation; preserves current behavior.
- "fair": divides available memory among spillable operators and may spill earlier.
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.
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.
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
retained by readers are not counted.
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.
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`.
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`.
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`. | | `logging.enable_per_region_metrics` | Bool | `false` | Whether to enable per-region metrics.
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.
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.
Legacy OTLP summary columns keep their historical `greptime_` prefix. | | `auto_create_table` | Bool | `true` | Server-side global switch for auto table creation on write.
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
(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". | | `user_provider` | String | Unset | 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:", "pbkdf2_sha256:::",
"mysql_native_password:",
"pg_scram_sha256::::"
"pbkdf2_sha256" and "pg_scram_sha256" protect passwords at rest, but such users cannot log in over MySQL:
`static_user_provider` and `watch_file_user_provider` only negotiate `mysql_native_password`, which cannot verify these formats.
"mysql_native_password" is MySQL-specific and cannot authenticate over PostgreSQL at all.
PostgreSQL SCRAM only covers "plain" and "pg_scram_sha256" users; if any user is "pbkdf2_sha256" or
"mysql_native_password", PostgreSQL falls back to cleartext password auth for every user.
For "pg_scram_sha256" users, keep the default iteration count (4096) and salt length (16): both are
observable in the SCRAM server-first message, and non-default values weaken resistance to username
enumeration. | -| `max_in_flight_write_bytes` | String | 0 | Maximum total memory for all concurrent write request bodies and messages (HTTP, gRPC, Flight).
Set to 0 to disable the limit. Default: "0" (unlimited) | -| `write_bytes_exhausted_policy` | String | `wait` | Policy when write bytes quota is exhausted.
Options: "wait" (default, 10s timeout), "wait()" (e.g., "wait(30s)"), "fail" | +| `max_in_flight_write_bytes` | String | 0 | 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) | +| `write_bytes_exhausted_policy` | String | `wait` | Policy when write bytes quota is exhausted.
Options: "wait" (default, 10s timeout), "wait()" (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. | | `runtime` | -- | -- | The runtime options. | | `runtime.global_rt_size` | Integer | Auto | The number of threads to execute the runtime for global read operations.
Defaults to max(num_cpus, 2). | | `runtime.compact_rt_size` | Integer | Auto | The number of threads to execute compact operations.
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.
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 | | `query.parallelism` | Integer | `0` | Parallelism of the query engine.
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.
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).
Supports absolute size (e.g., "4GB", "8GB") or percentage of system memory (e.g., "30%").
Setting it to 0 disables the limit. Defaults to 0 (unlimited); this example sets it to `50%`.
When this limit is reached, queries will fail with ResourceExhausted error.
This pool applies to operators on this frontend. Datanodes use their own query
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`.
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`.
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`. | | `logging.enable_per_region_metrics` | Bool | `false` | Whether to enable per-region metrics.
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`.
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`.
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`. | | `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.
Valid range `[0, 1]`, 1 means all traces are sampled, 0 means all traces are not sampled, the default value is 1.
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.
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.
Legacy OTLP summary columns keep their historical `greptime_` prefix. | | `require_lease_before_startup` | Bool | `false` | Start services after regions have obtained leases.
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.
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
after they are removed from manifest.
files will only be removed from `removed_files` field
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.
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.
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
retained by readers are not counted.
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.
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`.
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`.
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`. | | `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.
Valid range `[0, 1]`, 1 means all traces are sampled, 0 means all traces are not sampled, the default value is 1.
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`.
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`.
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`. | | `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.
Valid range `[0, 1]`, 1 means all traces are sampled, 0 means all traces are not sampled, the default value is 1.
ratio > 1 are treated as 1. Fractions < 0 are treated as 0 | diff --git a/config/datanode.example.toml b/config/datanode.example.toml index 45f1d93d39a..8ac0308cd1c 100644 --- a/config/datanode.example.toml +++ b/config/datanode.example.toml @@ -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`. diff --git a/config/flownode.example.toml b/config/flownode.example.toml index fab31fed510..837e1b51d9e 100644 --- a/config/flownode.example.toml +++ b/config/flownode.example.toml @@ -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 diff --git a/config/frontend.example.toml b/config/frontend.example.toml index f0c1402327f..72da7dd199b 100644 --- a/config/frontend.example.toml +++ b/config/frontend.example.toml @@ -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:", "pbkdf2_sha256:::", @@ -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()" (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. diff --git a/config/metasrv.example.toml b/config/metasrv.example.toml index fe4c38d02f9..35ba3ae0a98 100644 --- a/config/metasrv.example.toml +++ b/config/metasrv.example.toml @@ -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`. diff --git a/config/standalone.example.toml b/config/standalone.example.toml index 7682e537861..01729fa0d6e 100644 --- a/config/standalone.example.toml +++ b/config/standalone.example.toml @@ -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:", "pbkdf2_sha256:::", @@ -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()" (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. diff --git a/docs/formats/mito-samples.md b/docs/formats/mito-samples.md new file mode 100644 index 00000000000..5008babf5e6 --- /dev/null +++ b/docs/formats/mito-samples.md @@ -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 +/samples//manifest.json +/samples//part-0.samples +/samples//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-.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 # 0 = all valid, 1 = bitmap +validity # only for kind 1 +first_non_null_bits +xor_deltas +``` + +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. diff --git a/docs/formats/mito-series.md b/docs/formats/mito-series.md new file mode 100644 index 00000000000..66ea4bd4017 --- /dev/null +++ b/docs/formats/mito-series.md @@ -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 +/series//manifest.json +/series//part-0.series +/series//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-.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 ` 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 +dictionary: + entry_count + repeated entries: + present # 0 = null, 1 = UTF-8 string + string # only if present = 1 +row_codes +``` + +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 `, `first TSID `, +`last table ID `, `last TSID `, 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 `, `payload <32-byte reference>`, +`null_count `, and `statistics_kind `. 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. diff --git a/docs/rfcs/2026-09-06-object-store-wal.md b/docs/rfcs/2026-09-06-object-store-wal.md index d3e38bb5a26..be152130289 100644 --- a/docs/rfcs/2026-09-06-object-store-wal.md +++ b/docs/rfcs/2026-09-06-object-store-wal.md @@ -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. diff --git a/docs/rfcs/2026-11-10-object-store-metadata-leader-election.md b/docs/rfcs/2026-11-10-object-store-metadata-leader-election.md new file mode 100644 index 00000000000..8d55201c49f --- /dev/null +++ b/docs/rfcs/2026-11-10-object-store-metadata-leader-election.md @@ -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 +//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, + 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 +//probes/.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 --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 +//candidates/.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; + async fn takeover(&self) -> Result; + async fn mutate( + &self, + token: &FencingToken, + precondition: Precondition, + mutation: Mutation, + ) -> Result; +} +``` + +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. diff --git a/licenserc-enterprise.toml b/licenserc-enterprise.toml index 939346f5cba..22b35ded3e8 100644 --- a/licenserc-enterprise.toml +++ b/licenserc-enterprise.toml @@ -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", diff --git a/licenserc.toml b/licenserc.toml index e601ca6f7c1..172a6af5d61 100644 --- a/licenserc.toml +++ b/licenserc.toml @@ -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", diff --git a/merge-main.log b/merge-main.log deleted file mode 100644 index ec2af961861..00000000000 --- a/merge-main.log +++ /dev/null @@ -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 diff --git a/scripts/fetch-dashboard-assets.sh b/scripts/fetch-dashboard-assets.sh index 3ccebb95218..a2055f9033e 100755 --- a/scripts/fetch-dashboard-assets.sh +++ b/scripts/fetch-dashboard-assets.sh @@ -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" diff --git a/src/catalog/src/table_source.rs b/src/catalog/src/table_source.rs index fd78cc2573a..f06fd781f14 100644 --- a/src/catalog/src/table_source.rs +++ b/src/catalog/src/table_source.rs @@ -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> { + 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 { if self.disallow_cross_catalog_query { match &table_ref { diff --git a/src/cli/src/bench.rs b/src/cli/src/bench.rs index eb559316527..14d58738fef 100644 --- a/src/cli/src/bench.rs +++ b/src/cli/src/bench.rs @@ -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 diff --git a/src/cli/src/common/object_store.rs b/src/cli/src/common/object_store.rs index e671e6a534b..dc7e8adcb75 100644 --- a/src/cli/src/common/object_store.rs +++ b/src/cli/src/common/object_store.rs @@ -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, + sas_token: Option, } } diff --git a/src/cli/src/common/store.rs b/src/cli/src/common/store.rs index c3b8e477ed1..17418440b44 100644 --- a/src/cli/src/common/store.rs +++ b/src/cli/src/common/store.rs @@ -151,7 +151,7 @@ impl StoreConfig { &self.sanitize_store_addrs(), self.backend ); - let kvbackend = match self.backend { + let kvbackend: Result = match self.backend { BackendImpl::EtcdStore => { let tls_config = self.tls_config(); let etcd_client = create_etcd_client_with_tls( diff --git a/src/cli/src/data/export_v2/data.rs b/src/cli/src/data/export_v2/data.rs index dac094c0dda..e9242adcdac 100644 --- a/src/cli/src/data/export_v2/data.rs +++ b/src/cli/src/data/export_v2/data.rs @@ -368,7 +368,7 @@ fn build_gcs_connection( fn build_azblob_connection(storage: &ObjectStoreConfig) -> (String, Vec>) { 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 { fn mask_secrets(sql: &str, secrets: &[Option]) -> 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")); diff --git a/src/cli/src/data/storage_export.rs b/src/cli/src/data/storage_export.rs index 01bf252bbf5..c3222630981 100644 --- a/src/cli/src/data/storage_export.rs +++ b/src/cli/src/data/storage_export.rs @@ -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")); + } +} diff --git a/src/client/src/database.rs b/src/client/src/database.rs index de3c722a86a..58171d4d835 100644 --- a/src/client/src/database.rs +++ b/src/client/src/database.rs @@ -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()); diff --git a/src/client/src/region.rs b/src/client/src/region.rs index a70f5b5c766..371370c1918 100644 --- a/src/client/src/region.rs +++ b/src/client/src/region.rs @@ -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()); } diff --git a/src/cmd/src/bin/query_perf_fixture/direct_sst.rs b/src/cmd/src/bin/query_perf_fixture/direct_sst.rs index 0b09d1634ca..ca50192c21d 100644 --- a/src/cmd/src/bin/query_perf_fixture/direct_sst.rs +++ b/src/cmd/src/bin/query_perf_fixture/direct_sst.rs @@ -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, diff --git a/src/cmd/src/cli.rs b/src/cmd/src/cli.rs index 3739d4cc4fc..92aca3a5625 100644 --- a/src/cmd/src/cli.rs +++ b/src/cmd/src/cli.rs @@ -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 { diff --git a/src/cmd/src/datanode/builder.rs b/src/cmd/src/datanode/builder.rs index 6df7ac728e8..fc933a9c5be 100644 --- a/src/cmd/src/datanode/builder.rs +++ b/src/cmd/src/datanode/builder.rs @@ -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); diff --git a/src/cmd/src/datanode/objbench.rs b/src/cmd/src/datanode/objbench.rs index 248acc09bf6..aa26491c351 100644 --- a/src/cmd/src/datanode/objbench.rs +++ b/src/cmd/src/datanode/objbench.rs @@ -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, diff --git a/src/cmd/src/datanode/scanbench.rs b/src/cmd/src/datanode/scanbench.rs index 667a5f54be1..ca7f810d880 100644 --- a/src/cmd/src/datanode/scanbench.rs +++ b/src/cmd/src/datanode/scanbench.rs @@ -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 { diff --git a/src/cmd/src/datanode/sst_replace.rs b/src/cmd/src/datanode/sst_replace.rs index df13fcd6f25..e358c016e34 100644 --- a/src/cmd/src/datanode/sst_replace.rs +++ b/src/cmd/src/datanode/sst_replace.rs @@ -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( diff --git a/src/cmd/src/error.rs b/src/cmd/src/error.rs index 82273c0b67d..84553439ab1 100644 --- a/src/cmd/src/error.rs +++ b/src/cmd/src/error.rs @@ -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 = std::result::Result; 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(), diff --git a/src/cmd/src/flownode.rs b/src/cmd/src/flownode.rs index 0dfcf85e2e7..91faf313dc3 100644 --- a/src/cmd/src/flownode.rs +++ b/src/cmd/src/flownode.rs @@ -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); diff --git a/src/cmd/src/frontend.rs b/src/cmd/src/frontend.rs index b9aa76f0f49..7a430d7619d 100644 --- a/src/cmd/src/frontend.rs +++ b/src/cmd/src/frontend.rs @@ -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()); } diff --git a/src/cmd/src/metasrv.rs b/src/cmd/src/metasrv.rs index 369f5c428d1..7df4b92ab00 100644 --- a/src/cmd/src/metasrv.rs +++ b/src/cmd/src/metasrv.rs @@ -324,7 +324,8 @@ impl StartCommand { &opts.component.tracing, None, None, - ); + ) + .context(crate::error::InitLoggingSnafu)?; common_runtime::init_global_runtimes(&opts.runtime); diff --git a/src/cmd/src/standalone.rs b/src/cmd/src/standalone.rs index 2b07db019ab..934429517f4 100644 --- a/src/cmd/src/standalone.rs +++ b/src/cmd/src/standalone.rs @@ -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 { 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, 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, } @@ -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; + /// 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; } pub struct DefaultMetadataKvBackendCreator; #[async_trait] impl MetadataKvBackendCreator for DefaultMetadataKvBackendCreator { - async fn create(&self, metadata_dir: String, opts: &StandaloneOptions) -> Result { - standalone::build_metadata_kvbackend(metadata_dir, opts.metadata_store) + async fn create( + &self, + metadata_dir: String, + opts: &StandaloneOptions, + ) -> Result { + 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), diff --git a/src/cmd/tests/load_config_test.rs b/src/cmd/tests/load_config_test.rs index 4a393c1d393..4f2a68ba988 100644 --- a/src/cmd/tests/load_config_test.rs +++ b/src/cmd/tests/load_config_test.rs @@ -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", diff --git a/src/common/base/src/cancellation.rs b/src/common/base/src/cancellation.rs index 94aa872834c..d08a1ba7b03 100644 --- a/src/common/base/src/cancellation.rs +++ b/src/common/base/src/cancellation.rs @@ -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") diff --git a/src/common/cache/src/lib.rs b/src/common/cache/src/lib.rs index 7cd68b2c81b..3e4ad6811e4 100644 --- a/src/common/cache/src/lib.rs +++ b/src/common/cache/src/lib.rs @@ -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; diff --git a/src/common/function/Cargo.toml b/src/common/function/Cargo.toml index fbb7c173e76..4fa7eb67860 100644 --- a/src/common/function/Cargo.toml +++ b/src/common/function/Cargo.toml @@ -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 } diff --git a/src/common/function/src/function_registry.rs b/src/common/function/src/function_registry.rs index 8657636fe6b..027a576a51f 100644 --- a/src/common/function/src/function_registry.rs +++ b/src/common/function/src/function_registry.rs @@ -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> = 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); diff --git a/src/common/function/src/permission.rs b/src/common/function/src/permission.rs index 1a8392a0585..f3f5c6731a4 100644 --- a/src/common/function/src/permission.rs +++ b/src/common/function/src/permission.rs @@ -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, diff --git a/src/common/function/src/scalars.rs b/src/common/function/src/scalars.rs index 4bc4c17f5bb..b65fce554d8 100644 --- a/src/common/function/src/scalars.rs +++ b/src/common/function/src/scalars.rs @@ -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; diff --git a/src/common/function/src/scalars/iceberg_hash.rs b/src/common/function/src/scalars/iceberg_hash.rs new file mode 100644 index 00000000000..987b979477b --- /dev/null +++ b/src/common/function/src/scalars/iceberg_hash.rs @@ -0,0 +1,1247 @@ +// 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. + +//! SQL forms of the hash used by `iceberg_hash` partition rules. +//! +//! `iceberg_hash(col)` is the same function partition rules evaluate, exposed so +//! that users can measure a distribution or verify which bucket a value falls +//! into. It must never diverge from the rule form: both are built from +//! [`partition::function::iceberg_hash_udf`]. +//! +//! `iceberg_hash_bounds(n)` prints the breakpoints of an equal-width n-bucket +//! split, ready to paste into `PARTITION ON COLUMNS`. It only formats the +//! numbers; it does not create or change partitions. +//! +//! `iceberg_hash_breakpoints(v1, v2, ...)` hashes the given constant values +//! (any order, all from one hash encoding: strings, or integers) and prints them +//! sorted, for building buckets around known key values instead of around equal +//! widths. +//! +//! `iceberg_hash_ranges_sql(column, n)` renders the whole rule list for +//! `PARTITION ON COLUMNS` from an equal-width split, so it can be pasted +//! without expanding the breakpoints by hand. The column name is quoted, so +//! names that are not plain lowercase identifiers round-trip. + +use std::fmt; + +use datafusion::arrow::array::ArrayRef; +use datafusion::arrow::datatypes::DataType; +use datafusion_common::{DataFusionError, ScalarValue}; +use datafusion_expr::{ColumnarValue, ScalarFunctionArgs, Signature, Volatility}; +use partition::function::{IcebergHash, iceberg_hash_udf}; + +use crate::function::Function; +use crate::function_registry::FunctionRegistry; + +/// `iceberg_hash_bounds` hard limit. Each region carries its own WAL, memtable, +/// manifest and compaction stream, so four-digit bucket counts are already far +/// beyond any practical table. +const MAX_BUCKETS: i64 = 1024; + +/// `iceberg_hash(col)`: registers the UDF partition rules already plan. +/// +/// The raw [`iceberg_hash_udf`] is registered instead of a `Function` wrapper: +/// a wrapper is a different `ScalarUDFImpl` type, and DataFusion compares +/// expressions by concrete type, so `iceberg_hash(host)` from SQL would not +/// compare equal to the expression `Operand::IcebergHash::to_logical_expr` +/// builds. One impl type also keeps a batch from constructing a fresh +/// `ScalarUDF`. +pub(crate) struct IcebergHashFunction; + +impl IcebergHashFunction { + pub fn register(registry: &FunctionRegistry) { + registry.register(iceberg_hash_udf()); + } +} + +/// `iceberg_hash_bounds(n)`: the `n - 1` equal-width breakpoints of the hash +/// space, as comma separated `INT32` literals. +#[derive(Debug)] +pub(crate) struct IcebergHashBoundsFunction { + signature: Signature, +} + +impl Default for IcebergHashBoundsFunction { + fn default() -> Self { + Self { + signature: Signature::any(1, Volatility::Immutable), + } + } +} + +impl IcebergHashBoundsFunction { + pub fn register(registry: &FunctionRegistry) { + registry.register_scalar(Self::default()); + } + + /// Returns the bucket count a constant scalar names, or an error naming + /// the rejected input and the calling function. + fn bucket_count(name: &str, scalar: &ScalarValue) -> datafusion_common::Result { + let count = match scalar { + ScalarValue::Int64(Some(v)) => *v, + ScalarValue::Int32(Some(v)) => i64::from(*v), + ScalarValue::Int16(Some(v)) => i64::from(*v), + ScalarValue::Int8(Some(v)) => i64::from(*v), + ScalarValue::UInt64(Some(v)) => i64::try_from(*v).map_err(|_| { + DataFusionError::Execution(format!("{name} bucket count is too large: {v}")) + })?, + ScalarValue::UInt32(Some(v)) => i64::from(*v), + ScalarValue::UInt16(Some(v)) => i64::from(*v), + ScalarValue::UInt8(Some(v)) => i64::from(*v), + other => { + return Err(DataFusionError::Execution(format!( + "{name} expects an integer bucket count, got {other:?}" + ))); + } + }; + Ok(count) + } + + /// Returns the `n - 1` equal-width breakpoints a constant bucket count + /// names, or an error when the count is not a constant integer in + /// `[2, MAX_BUCKETS]`. Shared with [`IcebergHashRangesSqlFunction`], which + /// passes its own name so errors name the function the user called. + fn breakpoints_of(name: &str, scalar: &ScalarValue) -> datafusion_common::Result> { + equal_split_breakpoints(name, Self::bucket_count(name, scalar)?) + } +} + +impl Function for IcebergHashBoundsFunction { + fn name(&self) -> &str { + "iceberg_hash_bounds" + } + + fn return_type(&self, _input_types: &[DataType]) -> datafusion_common::Result { + Ok(DataType::Utf8) + } + + fn signature(&self) -> &Signature { + &self.signature + } + + fn invoke_with_args( + &self, + args: ScalarFunctionArgs, + ) -> datafusion_common::Result { + let [arg] = args.args.as_slice() else { + return Err(DataFusionError::Execution(format!( + "{} expects one argument, got {}", + self.name(), + args.args.len() + ))); + }; + let value = match arg { + ColumnarValue::Scalar(scalar) => scalar, + ColumnarValue::Array(_) => { + return Err(DataFusionError::Execution(format!( + "{} expects a constant bucket count, not a column", + self.name() + ))); + } + }; + if value.is_null() { + return Ok(ColumnarValue::Scalar(ScalarValue::Utf8(None))); + } + Ok(ColumnarValue::Scalar(ScalarValue::Utf8(Some( + Self::breakpoints_of(self.name(), value)? + .iter() + .map(i32::to_string) + .collect::>() + .join(", "), + )))) + } +} + +impl fmt::Display for IcebergHashBoundsFunction { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("ICEBERG_HASH_BOUNDS") + } +} + +/// `iceberg_hash_breakpoints(v1, v2, ...)`: the sorted, comma separated hash +/// values of the given constant values, as `INT32` literals. +/// +/// The values do not need to be sorted; the output is. Every value must be a +/// constant from one hash encoding, exactly like the values a partition rule +/// compares the hashed column against: all strings, or all integers. Mixing a +/// string with an integer is rejected because the two hash differently, so the +/// result would not describe the target column. +/// +/// NULL values hash to NULL and can never match a comparison bound, so they are +/// rejected rather than silently dropped; an empty argument list is rejected +/// too. +#[derive(Debug)] +pub(crate) struct IcebergHashBreakpointsFunction { + signature: Signature, +} + +impl Default for IcebergHashBreakpointsFunction { + fn default() -> Self { + Self { + signature: Signature::variadic_any(Volatility::Immutable), + } + } +} + +impl IcebergHashBreakpointsFunction { + pub fn register(registry: &FunctionRegistry) { + registry.register_scalar(Self::default()); + } + + /// Hashes the scalar arguments into sorted breakpoints, or an error when + /// the arguments cannot form a usable breakpoint list. + fn breakpoints(&self, args: &ScalarFunctionArgs) -> datafusion_common::Result { + if args.args.is_empty() { + return Err(DataFusionError::Execution(format!( + "{} expects at least one value, got none", + self.name() + ))); + } + let mut domain: Option = None; + let mut scalars: Vec = Vec::with_capacity(args.args.len()); + for (position, arg) in args.args.iter().enumerate() { + let scalar = match arg { + ColumnarValue::Scalar(scalar) => scalar, + ColumnarValue::Array(_) => { + return Err(DataFusionError::Execution(format!( + "{} expects constant values, not a column (argument {})", + self.name(), + position + 1 + ))); + } + }; + let hashed = if scalar.is_null() { + // A NULL hash can never match a comparison bound, so a NULL + // value cannot be a breakpoint. Reject it instead of silently + // dropping it: the user asked for that value's breakpoint. + return Err(DataFusionError::Execution(format!( + "{} cannot use NULL as a breakpoint (argument {}): NULL rows fall in the lowest bucket", + self.name(), + position + 1 + ))); + } else { + let value_domain = HashDomain::of(scalar).ok_or_else(|| { + DataFusionError::Execution(format!( + "{} expects string or integer values, argument {} is {scalar:?}", + self.name(), + position + 1 + )) + })?; + match domain { + Some(expected) if expected != value_domain => { + return Err(DataFusionError::Execution(format!( + "{} expects values with one hash encoding, argument {} is {} but earlier values are {}", + self.name(), + position + 1, + value_domain, + expected + ))); + } + Some(_) => {} + None => domain = Some(value_domain), + } + into_hashed_scalar(self.name(), position + 1, scalar)? + }; + scalars.push(hashed); + } + scalars.sort_unstable(); + scalars.dedup(); + Ok(scalars + .iter() + .map(i32::to_string) + .collect::>() + .join(", ")) + } +} + +impl Function for IcebergHashBreakpointsFunction { + fn name(&self) -> &str { + "iceberg_hash_breakpoints" + } + + fn return_type(&self, _input_types: &[DataType]) -> datafusion_common::Result { + Ok(DataType::Utf8) + } + + fn signature(&self) -> &Signature { + &self.signature + } + + fn invoke_with_args( + &self, + args: ScalarFunctionArgs, + ) -> datafusion_common::Result { + Ok(ColumnarValue::Scalar(ScalarValue::Utf8(Some( + self.breakpoints(&args)?, + )))) + } +} + +impl fmt::Display for IcebergHashBreakpointsFunction { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("ICEBERG_HASH_BREAKPOINTS") + } +} + +/// `iceberg_hash_ranges_sql(column, n)`: the ready-to-paste rule list for +/// `PARTITION ON COLUMNS`, built from an equal-width `n`-bucket split. +/// +/// The first argument is the column name as a constant string, the second the +/// constant bucket count accepted by [`IcebergHashBoundsFunction`]. The output +/// is the complete expression list: `iceberg_hash(c) < b1`, +/// `iceberg_hash(c) >= b1 AND iceberg_hash(c) < b2`, ..., one rule per bucket, +/// with the same breakpoints `iceberg_hash_bounds(n)` prints. +/// +/// It only renders text; it does not create or change any partition. +#[derive(Debug)] +pub(crate) struct IcebergHashRangesSqlFunction { + signature: Signature, +} + +impl Default for IcebergHashRangesSqlFunction { + fn default() -> Self { + Self { + signature: Signature::any(2, Volatility::Immutable), + } + } +} + +impl IcebergHashRangesSqlFunction { + pub fn register(registry: &FunctionRegistry) { + registry.register_scalar(Self::default()); + } + + /// Renders the rule list from the hashed column name and the bucket count. + fn ranges_sql(&self, args: &ScalarFunctionArgs) -> datafusion_common::Result> { + let [column_name, buckets] = args.args.as_slice() else { + return Err(DataFusionError::Execution(format!( + "{} expects (column, buckets), got {} arguments", + self.name(), + args.args.len() + ))); + }; + let (name, buckets) = match (column_name, buckets) { + (ColumnarValue::Scalar(name), ColumnarValue::Scalar(buckets)) => (name, buckets), + (ColumnarValue::Array(_), _) | (_, ColumnarValue::Array(_)) => { + return Err(DataFusionError::Execution(format!( + "{} expects constant arguments (column name, bucket count)", + self.name() + ))); + } + }; + if name.is_null() || buckets.is_null() { + return Ok(None); + } + // Every string representation is a valid column name: a literal is + // `Utf8`, but a user can hand over `Utf8View` explicitly (for example + // `arrow_cast('host', 'Utf8View')`), and `Signature::any` does not + // convert it back. + let column = match name.try_as_str() { + Some(Some(column)) => column, + _ => { + return Err(DataFusionError::Execution(format!( + "{} expects a column name string, got {name:?}", + self.name() + ))); + } + }; + if column.is_empty() { + return Err(DataFusionError::Execution(format!( + "{} expects a non-empty column name", + self.name() + ))); + } + let bounds = IcebergHashBoundsFunction::breakpoints_of(self.name(), buckets)?; + // `column` is a raw name, not SQL text: quote it so names with dashes, + // spaces, dots, quotes or upper case stay a single identifier when the + // rendered rules are pasted into `PARTITION ON COLUMNS`. + let column = quoted_identifier(column); + let mut rules = Vec::with_capacity(bounds.len() + 1); + for (index, bound) in bounds.iter().copied().enumerate() { + if index == 0 { + // First rule: only the upper bound; NULL rows land here. + rules.push(format!("iceberg_hash({column}) < {bound}")); + } else { + let lower = bounds[index - 1]; + rules.push(format!( + "iceberg_hash({column}) >= {lower} AND iceberg_hash({column}) < {bound}" + )); + } + } + // Last rule: only the lower bound. + rules.push(format!( + "iceberg_hash({column}) >= {}", + bounds[bounds.len() - 1] + )); + Ok(Some(rules.join(",\n"))) + } +} + +impl Function for IcebergHashRangesSqlFunction { + fn name(&self) -> &str { + "iceberg_hash_ranges_sql" + } + + fn return_type(&self, _input_types: &[DataType]) -> datafusion_common::Result { + Ok(DataType::Utf8) + } + + fn signature(&self) -> &Signature { + &self.signature + } + + fn invoke_with_args( + &self, + args: ScalarFunctionArgs, + ) -> datafusion_common::Result { + Ok(ColumnarValue::Scalar(ScalarValue::Utf8( + self.ranges_sql(&args)?, + ))) + } +} + +impl fmt::Display for IcebergHashRangesSqlFunction { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("ICEBERG_HASH_RANGES_SQL") + } +} + +/// The hash encoding a constant goes through. Integer widths share one +/// encoding (`INT32`, `UINT8`, ... all hash as Iceberg longs), while strings use +/// their UTF-8 bytes, so mixing the two produces breakpoints that do not +/// describe a single column. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum HashDomain { + String, + Integer, +} + +impl HashDomain { + fn of(scalar: &ScalarValue) -> Option { + match scalar { + ScalarValue::Utf8(_) | ScalarValue::LargeUtf8(_) | ScalarValue::Utf8View(_) => { + Some(Self::String) + } + ScalarValue::Int8(_) + | ScalarValue::Int16(_) + | ScalarValue::Int32(_) + | ScalarValue::Int64(_) + | ScalarValue::UInt8(_) + | ScalarValue::UInt16(_) + | ScalarValue::UInt32(_) + | ScalarValue::UInt64(_) => Some(Self::Integer), + _ => None, + } + } +} + +impl fmt::Display for HashDomain { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::String => f.write_str("string"), + Self::Integer => f.write_str("integer"), + } + } +} + +/// Quotes a column name as a SQL identifier: wrap it in double quotes and +/// double every embedded quote. +fn quoted_identifier(column: &str) -> String { + format!("\"{}\"", column.replace('"', "\"\"")) +} + +/// Hashes one constant by evaluating it through the shared array form, so the +/// value goes through exactly the code a partition rule evaluates. +fn into_hashed_scalar( + name: &str, + position: usize, + scalar: &ScalarValue, +) -> datafusion_common::Result { + let array: ArrayRef = scalar.to_array()?; + // Hash through the array form a partition rule evaluates, one value per row. + let hashed = IcebergHash::evaluate_array(array.as_ref()).map_err(|error| { + DataFusionError::Execution(format!("{name} argument {position}: {error}")) + })?; + let value = ScalarValue::try_from_array(&hashed, 0)?; + match value { + ScalarValue::Int32(Some(hashed)) => Ok(hashed), + ScalarValue::Int32(None) => Err(DataFusionError::Execution(format!( + "{name} argument {position}: NULL hash" + ))), + other => Err(DataFusionError::Execution(format!( + "{name} argument {position}: unexpected hash {other:?}" + ))), + } +} + +/// Returns the `n - 1` equal-width breakpoints of `buckets` over `INT32`, +/// following `bi = i32::MIN + floor(i * 2^32 / n)`. +fn equal_split_breakpoints(name: &str, buckets: i64) -> datafusion_common::Result> { + if !(2..=MAX_BUCKETS).contains(&buckets) { + return Err(DataFusionError::Execution(format!( + "{name} expects a bucket count in [2, {MAX_BUCKETS}], got {buckets}" + ))); + } + + Ok((1..buckets) + .map(|i| { + let offset = ((i as i128) << 32) / buckets as i128; + i32::MIN as i64 + offset as i64 + }) + .map(|bound| bound as i32) + .collect()) +} + +#[cfg(test)] +mod tests { + use std::sync::Arc; + + use datafusion::arrow::array::{Array, AsArray, Int64Array}; + use datafusion::arrow::datatypes::{DataType, Field, Int32Type}; + use datatypes::value::Value; + + use super::*; + use crate::function_registry::FUNCTION_REGISTRY; + + fn invoke( + function: &impl Function, + args: Vec, + rows: usize, + return_type: DataType, + ) -> ColumnarValue { + function + .invoke_with_args(ScalarFunctionArgs { + args, + arg_fields: vec![], + number_rows: rows, + return_field: Arc::new(Field::new("result", return_type, true)), + config_options: Arc::new(Default::default()), + }) + .unwrap() + } + + fn invoke_udf( + udf: &datafusion::logical_expr::ScalarUDF, + args: Vec, + rows: usize, + return_type: DataType, + ) -> ColumnarValue { + udf.invoke_with_args(ScalarFunctionArgs { + args, + arg_fields: vec![], + number_rows: rows, + return_field: Arc::new(Field::new("result", return_type, true)), + config_options: Arc::new(Default::default()), + }) + .unwrap() + } + + fn into_scalar(value: ColumnarValue) -> ScalarValue { + match value { + ColumnarValue::Scalar(scalar) => scalar, + ColumnarValue::Array(_) => panic!("expected a scalar result"), + } + } + + #[test] + fn test_hash_matches_partition_rule() { + let udf = iceberg_hash_udf(); + assert_eq!(udf.name(), "iceberg_hash"); + assert_eq!(udf.return_type(&[DataType::Utf8]).unwrap(), DataType::Int32); + + // Iceberg table spec, appendix B. + let hashed = invoke_udf( + &udf, + vec![ColumnarValue::Scalar(ScalarValue::Utf8(Some( + "iceberg".to_string(), + )))], + 1, + DataType::Int32, + ); + assert_eq!(into_scalar(hashed), ScalarValue::Int32(Some(1210000089))); + + // An untyped NULL reaches the UDF as ScalarValue::Null. + let untyped_null = invoke_udf( + &udf, + vec![ColumnarValue::Scalar(ScalarValue::Null)], + 1, + DataType::Int32, + ); + assert_eq!(into_scalar(untyped_null), ScalarValue::Int32(None)); + + // Integers hash as Iceberg longs, and NULL hashes to NULL. + let array = invoke_udf( + &udf, + vec![ColumnarValue::Array(Arc::new(Int64Array::from(vec![ + Some(34), + None, + ])))], + 2, + DataType::Int32, + ) + .to_array(2) + .unwrap(); + let array = array.as_primitive::(); + assert_eq!(array.value(0), 2017239379); + assert!(array.is_null(1)); + } + + #[test] + fn test_bounds_equal_split() { + let function = IcebergHashBoundsFunction::default(); + assert_eq!(function.name(), "iceberg_hash_bounds"); + assert_eq!( + function.return_type(&[DataType::Int64]).unwrap(), + DataType::Utf8 + ); + + let cases = [ + (2, "0"), + (3, "-715827883, 715827882"), + (4, "-1073741824, 0, 1073741824"), + ( + 8, + "-1610612736, -1073741824, -536870912, 0, 536870912, \ + 1073741824, 1610612736", + ), + ]; + for (buckets, expected) in cases { + let bounds = invoke( + &function, + vec![ColumnarValue::Scalar(ScalarValue::Int64(Some(buckets)))], + 1, + DataType::Utf8, + ); + assert_eq!( + into_scalar(bounds), + ScalarValue::Utf8(Some(expected.to_string())), + "buckets: {buckets}" + ); + } + + // Every integer width is a constant count; small widths must not be + // rejected as non-integer input. + for buckets in [ + ScalarValue::Int8(Some(4)), + ScalarValue::Int16(Some(4)), + ScalarValue::UInt8(Some(4)), + ScalarValue::UInt16(Some(4)), + ScalarValue::UInt32(Some(4)), + ScalarValue::UInt64(Some(4)), + ] { + let label = format!("{buckets:?}"); + let bounds = invoke( + &function, + vec![ColumnarValue::Scalar(buckets)], + 1, + DataType::Utf8, + ); + assert_eq!( + into_scalar(bounds), + ScalarValue::Utf8(Some("-1073741824, 0, 1073741824".to_string())), + "scalar: {label}" + ); + } + } + + #[test] + fn test_breakpoints_sorts_and_dedups() { + let function = IcebergHashBreakpointsFunction::default(); + assert_eq!(function.name(), "iceberg_hash_breakpoints"); + assert_eq!( + function.return_type(&[DataType::Utf8]).unwrap(), + DataType::Utf8 + ); + + // Unsorted strings: 'iceberg', 'a', and 'iceberg' again (dedup). + let bounds = invoke( + &function, + vec![ + ColumnarValue::Scalar(ScalarValue::Utf8(Some("iceberg".to_string()))), + ColumnarValue::Scalar(ScalarValue::Utf8(Some("a".to_string()))), + ColumnarValue::Scalar(ScalarValue::Utf8(Some("iceberg".to_string()))), + ], + 1, + DataType::Utf8, + ); + let iceberg = IcebergHash::evaluate_value(&Value::String("iceberg".into())) + .unwrap() + .as_i64() + .unwrap() as i32; + let a = IcebergHash::evaluate_value(&Value::String("a".into())) + .unwrap() + .as_i64() + .unwrap() as i32; + let expected = match (iceberg, a) { + (min, max) if min < max => format!("{min}, {max}"), + (min, max) => format!("{max}, {min}"), + }; + assert_eq!(into_scalar(bounds), ScalarValue::Utf8(Some(expected))); + + // Integer widths share one encoding, so they mix. + let bounds = invoke( + &function, + vec![ + ColumnarValue::Scalar(ScalarValue::Int64(Some(34))), + ColumnarValue::Scalar(ScalarValue::Int32(Some(-1))), + ColumnarValue::Scalar(ScalarValue::UInt8(Some(0))), + ], + 1, + DataType::Utf8, + ); + assert_eq!( + into_scalar(bounds), + ScalarValue::Utf8(Some(format!( + "{}, {}, {}", + IcebergHash::evaluate_value(&Value::Int32(-1)) + .unwrap() + .as_i64() + .unwrap() as i32, + IcebergHash::evaluate_value(&Value::UInt8(0)) + .unwrap() + .as_i64() + .unwrap() as i32, + IcebergHash::evaluate_value(&Value::Int64(34)) + .unwrap() + .as_i64() + .unwrap() as i32, + ))) + ); + } + + #[test] + fn test_breakpoints_rejects_invalid_input() { + let function = IcebergHashBreakpointsFunction::default(); + let call = |args: Vec| { + function.invoke_with_args(ScalarFunctionArgs { + args, + arg_fields: vec![], + number_rows: 1, + return_field: Arc::new(Field::new("result", DataType::Utf8, true)), + config_options: Arc::new(Default::default()), + }) + }; + + // Empty list cannot form a breakpoint list. + let err = call(vec![]).unwrap_err().to_string(); + assert!(err.contains("at least one value"), "{err}"); + + // NULL can never be a breakpoint: it falls in the lowest bucket. + let err = call(vec![ + ColumnarValue::Scalar(ScalarValue::Utf8(Some("a".to_string()))), + ColumnarValue::Scalar(ScalarValue::Null), + ]) + .unwrap_err() + .to_string(); + assert!(err.contains("cannot use NULL as a breakpoint"), "{err}"); + + // A column cannot be hashed at planning time. + let err = call(vec![ColumnarValue::Array(Arc::new(Int64Array::from( + vec![34_i64], + )))]) + .unwrap_err() + .to_string(); + assert!(err.contains("constant values, not a column"), "{err}"); + + // Unsupported value type is named explicitly. + let err = call(vec![ColumnarValue::Scalar(ScalarValue::Float64(Some(1.0)))]) + .unwrap_err() + .to_string(); + assert!(err.contains("expects string or integer values"), "{err}"); + + // A string and an integer hash through different encodings, so mixing + // them cannot describe one column. + let err = call(vec![ + ColumnarValue::Scalar(ScalarValue::Utf8(Some("iceberg".to_string()))), + ColumnarValue::Scalar(ScalarValue::Int64(Some(34))), + ]) + .unwrap_err() + .to_string(); + assert!( + err.contains("one hash encoding") + && err.contains("argument 2 is integer") + && err.contains("earlier values are string"), + "{err}" + ); + } + + #[test] + fn test_bounds_rejects_invalid_input() { + let function = IcebergHashBoundsFunction::default(); + let call = |arg: ColumnarValue| { + function.invoke_with_args(ScalarFunctionArgs { + args: vec![arg], + arg_fields: vec![], + number_rows: 1, + return_field: Arc::new(Field::new("result", DataType::Utf8, true)), + config_options: Arc::new(Default::default()), + }) + }; + + for buckets in [i64::MIN, -1, 0, 1, MAX_BUCKETS + 1] { + let err = call(ColumnarValue::Scalar(ScalarValue::Int64(Some(buckets)))) + .unwrap_err() + .to_string(); + assert!( + err.contains("bucket count in [2, 1024]"), + "unexpected error for {buckets}: {err}" + ); + } + + let err = call(ColumnarValue::Scalar(ScalarValue::Utf8(Some( + "4".to_string(), + )))) + .unwrap_err() + .to_string(); + assert!(err.contains("integer bucket count"), "{err}"); + + let err = call(ColumnarValue::Array(Arc::new(Int64Array::from(vec![ + 4_i64, + ])))) + .unwrap_err() + .to_string(); + assert!(err.contains("constant bucket count"), "{err}"); + + // A NULL bucket count propagates instead of failing. + let null = call(ColumnarValue::Scalar(ScalarValue::Int64(None))).unwrap(); + assert_eq!(into_scalar(null), ScalarValue::Utf8(None)); + } + + #[test] + fn test_ranges_sql_renders_rule_list() { + let function = IcebergHashRangesSqlFunction::default(); + assert_eq!(function.name(), "iceberg_hash_ranges_sql"); + assert_eq!( + function + .return_type(&[DataType::Utf8, DataType::Int64]) + .unwrap(), + DataType::Utf8 + ); + + let render = |name: &str, buckets: i64| { + let rendered = invoke( + &function, + vec![ + ColumnarValue::Scalar(ScalarValue::Utf8(Some(name.to_string()))), + ColumnarValue::Scalar(ScalarValue::Int64(Some(buckets))), + ], + 1, + DataType::Utf8, + ); + into_scalar(rendered) + }; + + let four_buckets = [ + "iceberg_hash(\"host\") < -1073741824", + "iceberg_hash(\"host\") >= -1073741824 AND iceberg_hash(\"host\") < 0", + "iceberg_hash(\"host\") >= 0 AND iceberg_hash(\"host\") < 1073741824", + "iceberg_hash(\"host\") >= 1073741824", + ] + .join(",\n"); + assert_eq!(render("host", 4), ScalarValue::Utf8(Some(four_buckets))); + assert_eq!( + render("tenant", 2), + ScalarValue::Utf8(Some( + "iceberg_hash(\"tenant\") < 0,\niceberg_hash(\"tenant\") >= 0".to_string() + )) + ); + + // Names that are not plain lowercase identifiers must stay one + // identifier: dashes, spaces and embedded quotes are quoted/escaped. + assert_eq!( + render("host-name", 2), + ScalarValue::Utf8(Some( + "iceberg_hash(\"host-name\") < 0,\niceberg_hash(\"host-name\") >= 0".to_string() + )) + ); + assert_eq!( + render("he\"llo", 2), + ScalarValue::Utf8(Some( + "iceberg_hash(\"he\"\"llo\") < 0,\niceberg_hash(\"he\"\"llo\") >= 0".to_string() + )) + ); + + // A column name can arrive in any Arrow string representation. An + // explicit `Utf8View` (for example from `arrow_cast`) must render + // exactly like a plain literal instead of being rejected as non-string. + for name in [ + ScalarValue::LargeUtf8(Some("host-name".to_string())), + ScalarValue::Utf8View(Some("host-name".to_string())), + ] { + let rendered = invoke( + &function, + vec![ + ColumnarValue::Scalar(name), + ColumnarValue::Scalar(ScalarValue::Int64(Some(2))), + ], + 1, + DataType::Utf8, + ); + assert_eq!( + into_scalar(rendered), + ScalarValue::Utf8(Some( + "iceberg_hash(\"host-name\") < 0,\niceberg_hash(\"host-name\") >= 0" + .to_string() + )) + ); + } + + // A NULL name or bucket count propagates. + let call = |args: Vec| { + let rendered = function + .invoke_with_args(ScalarFunctionArgs { + args, + arg_fields: vec![], + number_rows: 1, + return_field: Arc::new(Field::new("result", DataType::Utf8, true)), + config_options: Arc::new(Default::default()), + }) + .unwrap(); + into_scalar(rendered) + }; + assert_eq!( + call(vec![ + ColumnarValue::Scalar(ScalarValue::Utf8(None)), + ColumnarValue::Scalar(ScalarValue::Int64(Some(4))), + ]), + ScalarValue::Utf8(None) + ); + assert_eq!( + call(vec![ + ColumnarValue::Scalar(ScalarValue::Utf8(Some("host".to_string()))), + ColumnarValue::Scalar(ScalarValue::Int64(None)), + ]), + ScalarValue::Utf8(None) + ); + } + + /// Rendered rules must be valid partition expressions for the quoted + /// column, including names that need quoting. + #[test] + fn test_ranges_sql_output_parses_as_partition_rule() { + use sql::dialect::GreptimeDbDialect; + use sql::parser::{ParseOptions, ParserContext}; + + for column in ["host", "host-name", "HOST", "he\"llo", "a b"] { + let rendered = into_scalar(invoke( + &IcebergHashRangesSqlFunction::default(), + vec![ + ColumnarValue::Scalar(ScalarValue::Utf8(Some(column.to_string()))), + ColumnarValue::Scalar(ScalarValue::Int64(Some(4))), + ], + 1, + DataType::Utf8, + )); + let ScalarValue::Utf8(Some(rules)) = rendered else { + panic!("expected rendered rules for {column}"); + }; + let quoted = quoted_identifier(column); + let ddl = format!( + "CREATE TABLE t ({quoted} STRING, ts TIMESTAMP TIME INDEX, PRIMARY KEY ({quoted})) \ + PARTITION ON COLUMNS ({quoted}) ({rules})" + ); + let statements = ParserContext::create_with_dialect( + &ddl, + &GreptimeDbDialect {}, + ParseOptions::default(), + ) + .unwrap_or_else(|error| { + panic!("generated rules must parse for {column}: {error}\n{ddl}") + }); + assert_eq!(1, statements.len(), "{column}"); + } + } + + #[test] + fn test_ranges_sql_rejects_invalid_input() { + let function = IcebergHashRangesSqlFunction::default(); + let call = |args: Vec| { + function + .invoke_with_args(ScalarFunctionArgs { + args, + arg_fields: vec![], + number_rows: 1, + return_field: Arc::new(Field::new("result", DataType::Utf8, true)), + config_options: Arc::new(Default::default()), + }) + .unwrap_err() + .to_string() + }; + + // Bucket count outside the accepted range names the shared limit and + // the function the user actually called. + let err = call(vec![ + ColumnarValue::Scalar(ScalarValue::Utf8(Some("host".to_string()))), + ColumnarValue::Scalar(ScalarValue::Int64(Some(1))), + ]); + assert!(err.contains("bucket count in [2, 1024]"), "{err}"); + assert!( + err.contains("iceberg_hash_ranges_sql expects"), + "error must name the caller: {err}" + ); + + // Non-integer bucket count names the shared type error. + let err = call(vec![ + ColumnarValue::Scalar(ScalarValue::Utf8(Some("host".to_string()))), + ColumnarValue::Scalar(ScalarValue::Utf8(Some("4".to_string()))), + ]); + assert!(err.contains("integer bucket count"), "{err}"); + assert!( + err.contains("iceberg_hash_ranges_sql expects"), + "error must name the caller: {err}" + ); + + // Non-string column name. + let err = call(vec![ + ColumnarValue::Scalar(ScalarValue::Int64(Some(1))), + ColumnarValue::Scalar(ScalarValue::Int64(Some(4))), + ]); + assert!(err.contains("column name string"), "{err}"); + + // Empty column name. + let err = call(vec![ + ColumnarValue::Scalar(ScalarValue::Utf8(Some(String::new()))), + ColumnarValue::Scalar(ScalarValue::Int64(Some(4))), + ]); + assert!(err.contains("non-empty column name"), "{err}"); + + // Columns cannot be hashed at planning time. + let err = call(vec![ + ColumnarValue::Array(Arc::new(Int64Array::from(vec![1_i64]))), + ColumnarValue::Scalar(ScalarValue::Int64(Some(4))), + ]); + assert!(err.contains("constant arguments"), "{err}"); + + // Wrong arity. + let err = call(vec![ColumnarValue::Scalar(ScalarValue::Int64(Some(4)))]); + assert!(err.contains("expects (column, buckets)"), "{err}"); + } + + /// The SQL function must be the same `ScalarUDFImpl` the partition planner + /// builds, so a query expression compares equal to a rule expression. + #[test] + fn test_registered_hash_matches_partition_rule_expression() { + use datafusion::prelude::col; + + let sql_expr = FUNCTION_REGISTRY + .get_function("iceberg_hash") + .expect("iceberg_hash is registered") + .provide(crate::function::FunctionContext::default()) + .call(vec![col("host")]); + // The exact expression `Operand::IcebergHash` builds while planning a + // partition rule. + let rule_expr = IcebergHash::new("host").to_logical_expr(); + assert_eq!( + rule_expr, sql_expr, + "the registered iceberg_hash must be the UDF partition rules plan" + ); + } + + /// Functions that share a signature must stay distinct `ScalarUDF`s: + /// DataFusion compares expressions structurally, and treating `isnull` and + /// `iceberg_hash` as the same function corrupted `GROUP BY` planning + /// (`rebase_expr` matched `isnull(x)` against the grouped + /// `iceberg_hash(x)`). + #[test] + fn test_same_signature_functions_stay_distinct() { + use std::collections::HashSet; + use std::collections::hash_map::DefaultHasher; + use std::hash::{Hash, Hasher}; + + use datafusion::prelude::col; + + let provide = |name: &str| { + FUNCTION_REGISTRY + .get_function(name) + .unwrap_or_else(|| panic!("{name} is not registered")) + .provide(crate::function::FunctionContext::default()) + }; + let isnull = provide("isnull"); + let hash = provide("iceberg_hash"); + let bounds = provide("iceberg_hash_bounds"); + + // All three share `Signature::any(1, Immutable)` but are not equal. + assert!(isnull != hash); + assert!(isnull != bounds); + assert!(hash != bounds); + assert_ne!( + isnull.call(vec![col("x")]), + hash.call(vec![col("x")]), + "isnull(x) and iceberg_hash(x) must not compare equal" + ); + + let hash_of = |udf: &datafusion::logical_expr::ScalarUDF| { + let mut hasher = DefaultHasher::new(); + udf.hash(&mut hasher); + hasher.finish() + }; + // Equal objects keep hashing equally, so the registry still finds them. + let hash_again = provide("iceberg_hash"); + assert_eq!(hash, hash_again); + assert_eq!(hash_of(&hash), hash_of(&hash_again)); + // Distinct functions remain separable keys in hash-based containers. + let udfs: HashSet<_> = [isnull, hash, bounds].into_iter().collect(); + assert_eq!(3, udfs.len()); + } + + /// `isnull` and `iceberg_hash` share a signature; grouping by one while + /// selecting the other must still plan (regression for the identity bug). + #[tokio::test] + async fn test_group_by_with_same_signature_functions() { + use datafusion::arrow::array::{ArrayRef, Int64Array}; + use datafusion::arrow::record_batch::RecordBatch; + use datafusion::prelude::SessionContext; + + use crate::function::FunctionContext; + + let ctx = SessionContext::new(); + for name in ["isnull", "iceberg_hash"] { + let udf = FUNCTION_REGISTRY + .get_function(name) + .unwrap() + .provide(FunctionContext::default()); + ctx.register_udf(udf); + } + ctx.register_batch( + "t", + RecordBatch::try_from_iter([( + "x", + Arc::new(Int64Array::from(vec![Some(34), None])) as ArrayRef, + )]) + .unwrap(), + ) + .unwrap(); + + for sql in [ + "SELECT isnull(x) FROM t GROUP BY x, iceberg_hash(x)", + "SELECT iceberg_hash(x) FROM t GROUP BY x, isnull(x)", + ] { + let batches = ctx + .sql(sql) + .await + .unwrap_or_else(|error| panic!("{sql} must plan: {error}")) + .collect() + .await + .unwrap_or_else(|error| panic!("{sql} must execute: {error}")); + assert_eq!( + 2, + batches.iter().map(|batch| batch.num_rows()).sum::(), + "{sql}" + ); + } + } + + /// Both functions must resolve and run through a plain SQL session, not just + /// through the [Function] trait. + #[tokio::test] + async fn test_functions_run_through_sql() { + use datafusion::prelude::SessionContext; + + use crate::function::FunctionContext; + + // Register what the registry actually exposes, which also pins the + // `iceberg_hash` registration to the raw partition-rule UDF. + let ctx = SessionContext::new(); + for name in [ + "iceberg_hash", + "iceberg_hash_bounds", + "iceberg_hash_breakpoints", + "iceberg_hash_ranges_sql", + ] { + let udf = FUNCTION_REGISTRY + .get_function(name) + .unwrap_or_else(|| panic!("{name} is not registered")) + .provide(FunctionContext::default()); + ctx.register_udf(udf); + } + + let batches = ctx + .sql( + "SELECT iceberg_hash('iceberg') AS h, iceberg_hash(34) AS i, \ + iceberg_hash(NULL) AS n, iceberg_hash_bounds(4) AS b, \ + iceberg_hash_bounds(CAST(4 AS SMALLINT)) AS sb, \ + iceberg_hash_breakpoints('iceberg', 'a') AS bp, \ + iceberg_hash_ranges_sql('host-name', 2) AS rs, \ + iceberg_hash_ranges_sql(arrow_cast('host-name', 'Utf8View'), 2) AS rsv", + ) + .await + .unwrap() + .collect() + .await + .unwrap(); + assert_eq!(batches.len(), 1); + assert_eq!(batches[0].num_rows(), 1); + assert_eq!( + batches[0].column(0).as_primitive::().value(0), + 1210000089 + ); + assert_eq!( + batches[0].column(1).as_primitive::().value(0), + 2017239379 + ); + assert!(batches[0].column(2).as_primitive::().is_null(0)); + assert_eq!( + batches[0].column(3).as_string::().value(0), + "-1073741824, 0, 1073741824" + ); + assert_eq!( + batches[0].column(4).as_string::().value(0), + "-1073741824, 0, 1073741824" + ); + // Sorted hash values of the two strings, computed by the shared hash. + let iceberg = IcebergHash::evaluate_value(&Value::String("iceberg".into())) + .unwrap() + .as_i64() + .unwrap() as i32; + let a = IcebergHash::evaluate_value(&Value::String("a".into())) + .unwrap() + .as_i64() + .unwrap() as i32; + let expected_breakpoints = if iceberg < a { + format!("{iceberg}, {a}") + } else { + format!("{a}, {iceberg}") + }; + assert_eq!( + batches[0].column(5).as_string::().value(0), + expected_breakpoints + ); + // Ready-to-paste rule list, with the column name quoted. + let rendered_rules = "iceberg_hash(\"host-name\") < 0,\niceberg_hash(\"host-name\") >= 0"; + assert_eq!( + batches[0].column(6).as_string::().value(0), + rendered_rules + ); + // An explicit `Utf8View` column name renders the same rules. + assert_eq!( + batches[0].column(7).as_string::().value(0), + rendered_rules + ); + } + + #[test] + fn test_hash_functions_are_registered() { + for name in [ + "iceberg_hash", + "iceberg_hash_bounds", + "iceberg_hash_breakpoints", + "iceberg_hash_ranges_sql", + ] { + assert!( + FUNCTION_REGISTRY.get_function(name).is_some(), + "{name} is not registered" + ); + } + } +} diff --git a/src/common/function/src/scalars/udf.rs b/src/common/function/src/scalars/udf.rs index 48c59ac230a..151982ef581 100644 --- a/src/common/function/src/scalars/udf.rs +++ b/src/common/function/src/scalars/udf.rs @@ -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(&self, state: &mut H) { - self.function.signature().hash(state) + self.function.name().hash(state); + self.function.signature().hash(state); } } diff --git a/src/common/function/src/scalars/vector/impl_conv.rs b/src/common/function/src/scalars/vector/impl_conv.rs index 00d23cedf7f..d46f2b12606 100644 --- a/src/common/function/src/scalars/vector/impl_conv.rs +++ b/src/common/function/src/scalars/vector/impl_conv.rs @@ -43,7 +43,9 @@ pub fn binlit_as_veclit(bytes: &[u8]) -> Result> { .fail(); } - if cfg!(target_endian = "little") { + if cfg!(target_endian = "little") && bytes.as_ptr().align_offset(align_of::()) == 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]; diff --git a/src/common/function/src/system/database.rs b/src/common/function/src/system/database.rs index 1884c5525f0..b9ad7ab7178 100644 --- a/src/common/function/src/system/database.rs +++ b/src/common/function/src/system/database.rs @@ -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), + ))) } } }; diff --git a/src/common/function/src/system/pg_catalog.rs b/src/common/function/src/system/pg_catalog.rs index 3029361c202..bc311d84164 100644 --- a/src/common/function/src/system/pg_catalog.rs +++ b/src/common/function/src/system/pg_catalog.rs @@ -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 { + 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); diff --git a/src/common/meta/AGENTS.md b/src/common/meta/AGENTS.md index 69d76d3c5ca..1be24b2ee9a 100644 --- a/src/common/meta/AGENTS.md +++ b/src/common/meta/AGENTS.md @@ -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 diff --git a/src/common/meta/src/cache_invalidator.rs b/src/common/meta/src/cache_invalidator.rs index edf84b00b83..5e781e9c7da 100644 --- a/src/common/meta/src/cache_invalidator.rs +++ b/src/common/meta/src/cache_invalidator.rs @@ -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. diff --git a/src/common/meta/src/ddl/alter_logical_tables.rs b/src/common/meta/src/ddl/alter_logical_tables.rs index ccf130cec8c..ac70980329a 100644 --- a/src/common/meta/src/ddl/alter_logical_tables.rs +++ b/src/common/meta/src/ddl/alter_logical_tables.rs @@ -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::>(); - 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); diff --git a/src/common/meta/src/ddl/alter_logical_tables/validator.rs b/src/common/meta/src/ddl/alter_logical_tables/validator.rs index 7e6c130351f..af0c642d919 100644 --- a/src/common/meta/src/ddl/alter_logical_tables/validator.rs +++ b/src/common/meta/src/ddl/alter_logical_tables/validator.rs @@ -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, diff --git a/src/common/meta/src/ddl/create_logical_tables.rs b/src/common/meta/src/ddl/create_logical_tables.rs index 9b231f3c538..1e65a7ef724 100644 --- a/src/common/meta/src/ddl/create_logical_tables.rs +++ b/src/common/meta/src/ddl/create_logical_tables.rs @@ -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, physical_columns: Vec, + /// 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, } diff --git a/src/common/meta/src/ddl/create_logical_tables/metadata.rs b/src/common/meta/src/ddl/create_logical_tables/metadata.rs index 22424668946..da9cbc1708f 100644 --- a/src/common/meta/src/ddl/create_logical_tables/metadata.rs +++ b/src/common/meta/src/ddl/create_logical_tables/metadata.rs @@ -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(); diff --git a/src/common/meta/src/ddl/drop_database.rs b/src/common/meta/src/ddl/drop_database.rs index 5bbd229ec5b..d083d4402b0 100644 --- a/src/common/meta/src/ddl/drop_database.rs +++ b/src/common/meta/src/ddl/drop_database.rs @@ -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>>; + /// Context of [DropDatabaseProcedure] execution. pub(crate) struct DropDatabaseContext { catalog: String, schema: String, drop_if_exists: bool, - tables: Option>>, + tables: Option, retrying: bool, } diff --git a/src/common/meta/src/ddl/drop_database/cursor.rs b/src/common/meta/src/ddl/drop_database/cursor.rs index e060567be58..7e300efde86 100644 --- a/src/common/meta/src/ddl/drop_database/cursor.rs +++ b/src/common/meta/src/ddl/drop_database/cursor.rs @@ -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, 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> { + 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> { + let manager = &ddl_ctx.table_metadata_manager; + let ids = page.iter().map(|(_, id)| *id).collect::>(); + 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::>() + .into_iter() + .collect::>(); + 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, 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, 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::()); + } else { + assert!(state.as_any().is::()); + } + 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::>(); + 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::(); + assert!(estimated <= DropDatabaseCursor::MAX_BATCH_BYTES); + let tables = page + .iter() + .map(|(name, id)| (*id, TableName::new(&ctx.catalog, &ctx.schema, name))) + .collect::>(); + // 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::(); + 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::>()); + } + } + #[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::() + .downcast_ref::() .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] diff --git a/src/common/meta/src/ddl/drop_database/executor.rs b/src/common/meta/src/ddl/drop_database/executor.rs index 1c01060c5ed..84d2eafe5fd 100644 --- a/src/common/meta/src/ddl/drop_database/executor.rs +++ b/src/common/meta/src/ddl/drop_database/executor.rs @@ -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, 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::>(); + 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] diff --git a/src/common/meta/src/ddl/tests/alter_logical_tables.rs b/src/common/meta/src/ddl/tests/alter_logical_tables.rs index 619e02bb9b9..4dd915d1505 100644 --- a/src/common/meta/src/ddl/tests/alter_logical_tables.rs +++ b/src/common/meta/src/ddl/tests/alter_logical_tables.rs @@ -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}" + ); + } } diff --git a/src/common/meta/src/ddl/tests/create_logical_tables.rs b/src/common/meta/src/ddl/tests/create_logical_tables.rs index 89ec486ee03..a74ef63403e 100644 --- a/src/common/meta/src/ddl/tests/create_logical_tables.rs +++ b/src/common/meta/src/ddl/tests/create_logical_tables.rs @@ -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::>().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::>(); + 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::>(); + 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()); +} diff --git a/src/common/meta/src/ddl/tests/create_table.rs b/src/common/meta/src/ddl/tests/create_table.rs index d39346e02da..e1c880fbf32 100644 --- a/src/common/meta/src/ddl/tests/create_table.rs +++ b/src/common/meta/src/ddl/tests/create_table.rs @@ -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; diff --git a/src/common/meta/src/ddl/tests/drop_database.rs b/src/common/meta/src/ddl/tests/drop_database.rs index 05a70962bf0..049eb82e551 100644 --- a/src/common/meta/src/ddl/tests/drop_database.rs +++ b/src/common/meta/src/ddl/tests/drop_database.rs @@ -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::() - .is_some() + p.state().as_any().is::() }) .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::() + { + 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::>() + .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::()); + assert_eq!( + serde_json::from_str::(fixture).unwrap(), + serde_json::from_str::(&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>>, + } + #[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::() + }) + .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::>() + .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() + ); + } + } +} diff --git a/src/common/meta/src/ddl/tests/drop_table.rs b/src/common/meta/src/ddl/tests/drop_table.rs index a278b951dd5..40505c28fa2 100644 --- a/src/common/meta/src/ddl/tests/drop_table.rs +++ b/src/common/meta/src/ddl/tests/drop_table.rs @@ -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; diff --git a/src/common/meta/src/ddl_manager.rs b/src/common/meta/src/ddl_manager.rs index 5078328443d..87a0ddae91b 100644 --- a/src/common/meta/src/ddl_manager.rs +++ b/src/common/meta/src/ddl_manager.rs @@ -625,13 +625,22 @@ impl DdlManager { &self, alter_table_tasks: Vec, physical_table_id: TableId, + expected_table_ids: Option>, procedure_context: ProcedureContext, ) -> Result<(ProcedureId, Option)> { 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, + query_context: QueryContext, procedure_context: ProcedureContext, ) -> Result { 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() { diff --git a/src/common/meta/src/instruction.rs b/src/common/meta/src/instruction.rs index 0291f3a0946..2fba5a24f48 100644 --- a/src/common/meta/src/instruction.rs +++ b/src/common/meta/src/instruction.rs @@ -388,6 +388,9 @@ pub struct UpgradeRegion { pub replay_entry_id: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub metadata_replay_entry_id: Option, + /// 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, } 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::(json).unwrap(), + upgrade_region + ); + } + #[test] fn test_deserialize_instruction_reply() { // legacy close region reply diff --git a/src/common/meta/src/key.rs b/src/common/meta/src/key.rs index 189c427e9ec..61b171b8bfe 100644 --- a/src/common/meta/src/key.rs +++ b/src/common/meta/src/key.rs @@ -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; 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::>(); - 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::>(); + 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( &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::>(); + let remaining = Arc::new(Mutex::new( + tables + .iter() + .flat_map(|(id, name)| TableMetadataManager::table_identity_keys(*id, name)) + .collect::>(), + )); + 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()); diff --git a/src/common/meta/src/kv_backend.rs b/src/common/meta/src/kv_backend.rs index 10e51578505..171241bcd90 100644 --- a/src/common/meta/src/kv_backend.rs +++ b/src/common/meta/src/kv_backend.rs @@ -41,6 +41,20 @@ pub mod txn; pub mod util; pub type KvBackendRef = Arc + 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 { + /// 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; + #[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"; diff --git a/src/common/meta/src/kv_backend/rds.rs b/src/common/meta/src/kv_backend/rds.rs index 1e94741dd8e..cb2dc47ef06 100644 --- a/src/common/meta/src/kv_backend/rds.rs +++ b/src/common/meta/src/kv_backend/rds.rs @@ -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: 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; async fn txn_executor<'a>(&self, default_executor: &'a mut T) -> Result>; @@ -585,6 +590,20 @@ where } } +#[async_trait::async_trait] +impl ClosableKvBackend for RdsStore +where + R: 'static, + Self: KvQueryExecutor + Send + Sync, + T: Executor + 'static, + S: ExecutorFactory + '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 { if txn_ops.is_empty() { diff --git a/src/common/meta/src/kv_backend/rds/mysql.rs b/src/common/meta/src/kv_backend/rds/mysql.rs index c933bb345f6..6c314bc69e4 100644 --- a/src/common/meta/src/kv_backend/rds/mysql.rs +++ b/src/common/meta/src/kv_backend/rds/mysql.rs @@ -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 for MySqlExecutorFactory { + async fn close(&self) { + self.pool.close().await; + } + async fn default_executor(&self) -> Result { 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 { + /// Create [MySqlStore] impl of [ClosableKvBackendRef] from url. + pub async fn with_url( + url: &str, + table_name: &str, + max_txn_ops: usize, + ) -> Result { 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]. + /// Create [MySqlStore] impl of [ClosableKvBackendRef] from [sqlx::Pool]. pub async fn with_mysql_pool( pool: Pool, table_name: &str, max_txn_ops: usize, - ) -> Result { + ) -> Result { // 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); diff --git a/src/common/meta/src/kv_backend/rds/postgres.rs b/src/common/meta/src/kv_backend/rds/postgres.rs index 4a2f8b13564..f48d21a5ab7 100644 --- a/src/common/meta/src/kv_backend/rds/postgres.rs +++ b/src/common/meta/src/kv_backend/rds/postgres.rs @@ -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 for PgExecutorFactory { + async fn close(&self) { + self.pool.close(); + } + async fn default_executor(&self) -> Result { self.client().await } @@ -808,7 +812,7 @@ impl KvQueryExecutor 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, - ) -> Result { + ) -> Result { 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 { + /// Create [PgStore] impl of [ClosableKvBackendRef] from url without TLS. + pub async fn with_url( + url: &str, + table_name: &str, + max_txn_ops: usize, + ) -> Result { 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 { + ) -> Result { // 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 { let endpoints = std::env::var("GT_POSTGRES_ENDPOINTS").unwrap_or_default(); if endpoints.is_empty() { diff --git a/src/common/meta/src/kv_backend/test_util.rs b/src/common/meta/src/kv_backend/test_util.rs index 589c6c699ef..0f19476eced 100644 --- a/src/common/meta/src/kv_backend/test_util.rs +++ b/src/common/meta/src/kv_backend/test_util.rs @@ -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 = Arc Result + 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, +} + +#[async_trait::async_trait] +impl TxnService for TxnObservingKvBackend { + type Error = crate::error::Error; + + async fn txn(&self, txn: Txn) -> Result { + (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 { + self.inner.range(req).await + } + + async fn put(&self, req: PutRequest) -> Result { + self.inner.put(req).await + } + + async fn batch_put(&self, req: BatchPutRequest) -> Result { + self.inner.batch_put(req).await + } + + async fn batch_get(&self, req: BatchGetRequest) -> Result { + self.inner.batch_get(req).await + } + + async fn delete_range(&self, req: DeleteRangeRequest) -> Result { + self.inner.delete_range(req).await + } + + async fn batch_delete(&self, req: BatchDeleteRequest) -> Result { + self.inner.batch_delete(req).await + } +} diff --git a/src/common/meta/src/region_keeper.rs b/src/common/meta/src/region_keeper.rs index aca0b958385..d40e4158ff6 100644 --- a/src/common/meta/src/region_keeper.rs +++ b/src/common/meta/src/region_keeper.rs @@ -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, +} + /// Tracks the operating(i.e., creating, opening, dropping) regions. #[derive(Debug, Clone)] pub struct OperatingRegionGuard { datanode_id: DatanodeId, region_id: RegionId, - inner: Arc>>, + candidate_lease_id: Option, + inner: Arc>>, } 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 { + self.candidate_lease_id + } } pub type MemoryRegionKeeperRef = Arc; @@ -52,7 +70,7 @@ pub type MemoryRegionKeeperRef = Arc; /// - Tracks the deleting regions after the corresponding metadata is deleted. #[derive(Debug, Clone, Default)] pub struct MemoryRegionKeeper { - inner: Arc>>, + inner: Arc>>, } impl MemoryRegionKeeper { @@ -67,19 +85,32 @@ impl MemoryRegionKeeper { region_id: RegionId, role: RegionRole, ) -> Option { - 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 { + 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, - ) -> HashMap { + ) -> HashMap { 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 { + 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); + } } diff --git a/src/common/meta/src/rpc/ddl.rs b/src/common/meta/src/rpc/ddl.rs index 9e88527f935..496060e2f52 100644 --- a/src/common/meta/src/rpc/ddl.rs +++ b/src/common/meta/src/rpc/ddl.rs @@ -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>> { + self.extensions + .get(ALTER_LOGICAL_TABLE_IDS_EXTENSION_KEY) + .map(|ids| { + ids.split(',') + .map(|id| { + id.parse::().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); diff --git a/src/common/query/Cargo.toml b/src/common/query/Cargo.toml index 4acdfafcb6c..97cef47889a 100644 --- a/src/common/query/Cargo.toml +++ b/src/common/query/Cargo.toml @@ -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 diff --git a/src/common/query/src/error.rs b/src/common/query/src/error.rs index 511f0a82db3..f5f880e8ced 100644 --- a/src/common/query/src/error.rs +++ b/src/common/query/src/error.rs @@ -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 = std::result::Result; @@ -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::(&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 { diff --git a/src/common/query/src/lib.rs b/src/common/query/src/lib.rs index c68e4c76470..3e6f625211d 100644 --- a/src/common/query/src/lib.rs +++ b/src/common/query/src/lib.rs @@ -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; diff --git a/src/common/query/src/native_histogram.rs b/src/common/query/src/native_histogram.rs index 38a7895c27a..05527b02cc8 100644 --- a/src/common/query/src/native_histogram.rs +++ b/src/common/query/src/native_histogram.rs @@ -21,12 +21,13 @@ mod encoding; +use std::borrow::Cow; use std::collections::BTreeMap; use std::sync::Arc; use datafusion::arrow::array::{ Array, ArrayRef, Float64Array, Int32Array, Int64Array, ListArray, PrimitiveArray, StructArray, - TimestampMillisecondArray, + TimestampMillisecondArray, UInt32Array, }; use datafusion::arrow::buffer::NullBuffer; use datafusion::arrow::datatypes::{ @@ -35,6 +36,9 @@ use datafusion::arrow::datatypes::{ }; use datafusion_common::{DataFusionError, Result as DfResult}; use datatypes::data_type::{ConcreteDataType, DataType}; +pub use datatypes::series::histogram::CounterResetHint; +use datatypes::series::histogram::{BucketSideView, HistogramBatchBuilder, HistogramView}; +use datatypes::series::samples::Samples; use datatypes::types::{StructField, StructType}; pub use encoding::{ NativeHistogramError, decode_native_histogram_for_remote_read, encode_native_histogram, @@ -175,48 +179,6 @@ pub const CUSTOM_BUCKETS_SCHEMA: i32 = -53; const MIN_EXPONENTIAL_SCHEMA: i32 = -4; const MAX_EXPONENTIAL_SCHEMA: i32 = 8; -/// Information carried by a native histogram about a possible counter reset. -/// -/// The persisted and protobuf representation remains an `i32`. Unrecognized -/// values are retained so data written by a newer producer can still round-trip. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum CounterResetHint { - /// The payload must be inspected to determine whether a reset occurred. - Unknown, - /// This is the first histogram after a counter reset. - CounterReset, - /// No counter reset occurred since the previous histogram. - NotCounterReset, - /// This is a gauge histogram, so counter resets do not apply. - Gauge, - /// A value not understood by this version. - Unrecognized(i32), -} - -impl From for CounterResetHint { - fn from(value: i32) -> Self { - match value { - 0 => Self::Unknown, - 1 => Self::CounterReset, - 2 => Self::NotCounterReset, - 3 => Self::Gauge, - value => Self::Unrecognized(value), - } - } -} - -impl From for i32 { - fn from(value: CounterResetHint) -> Self { - match value { - CounterResetHint::Unknown => 0, - CounterResetHint::CounterReset => 1, - CounterResetHint::NotCounterReset => 2, - CounterResetHint::Gauge => 3, - CounterResetHint::Unrecognized(value) => value, - } - } -} - /// Reset hint indicating that the payload must be inspected. pub const UNKNOWN_COUNTER_RESET_HINT: CounterResetHint = CounterResetHint::Unknown; /// Reset hint indicating the first histogram after a counter reset. @@ -312,6 +274,38 @@ fn format_promql_histogram_float(value: f64) -> String { format!("{mantissa}e{sign}{exponent:0>2}") } +impl NativeHistogram { + /// Appends this histogram, borrowing its bucket and custom-bound slices as input. + /// Span metadata is staged into temporary column vectors; the builder copies all input + /// values into its owned result storage. + pub fn push_to(&self, builder: &mut HistogramBatchBuilder) -> datatypes::Result { + let positive_offsets: Vec<_> = self.positive_spans.iter().map(|span| span.offset).collect(); + let positive_lengths: Vec<_> = self.positive_spans.iter().map(|span| span.length).collect(); + let negative_offsets: Vec<_> = self.negative_spans.iter().map(|span| span.offset).collect(); + let negative_lengths: Vec<_> = self.negative_spans.iter().map(|span| span.length).collect(); + builder.push(HistogramView { + schema: self.schema, + zero_threshold: self.zero_threshold, + sum: self.sum, + count: self.count, + zero_count: self.zero_count, + reset_hint: self.reset_hint, + start_timestamp: self.start_timestamp, + custom_values: &self.custom_values, + positive: BucketSideView { + span_offsets: &positive_offsets, + span_lengths: &positive_lengths, + buckets: &self.positive_buckets, + }, + negative: BucketSideView { + span_offsets: &negative_offsets, + span_lengths: &negative_lengths, + buckets: &self.negative_buckets, + }, + }) + } +} + impl NativeHistogram { fn uses_custom_buckets(&self) -> bool { self.schema == CUSTOM_BUCKETS_SCHEMA @@ -628,18 +622,12 @@ impl NativeHistogram { } fn all_buckets(&self) -> Option> { - let mut buckets = self.side_buckets(false)?; - buckets.reverse(); - if self.zero_count != 0.0 { - buckets.push(Bucket { - lower: -self.zero_threshold, - upper: self.zero_threshold, - count: self.zero_count, - boundary_rule: BoundaryRule::ClosedBoth, - }); - } - buckets.extend(self.side_buckets(true)?); - Some(buckets) + Some(assemble_bucket_sides( + self.side_buckets(false)?, + self.zero_threshold, + self.zero_count, + self.side_buckets(true)?, + )) } fn side_buckets(&self, positive: bool) -> Option> { @@ -649,31 +637,13 @@ impl NativeHistogram { (&self.negative_spans, &self.negative_buckets) }; - let mut result = Vec::with_capacity(counts.len()); - for (idx, count) in side_bucket_indices(spans)?.into_iter().zip(counts) { - let upper = get_bound(idx, self.schema, &self.custom_values)?; - let lower = get_bound(idx.checked_sub(1)?, self.schema, &self.custom_values)?; - if positive { - result.push(Bucket { - lower, - upper, - count: *count, - boundary_rule: if self.uses_custom_buckets() && idx == 0 { - BoundaryRule::ClosedBoth - } else { - BoundaryRule::OpenLeft - }, - }); - } else { - result.push(Bucket { - lower: -upper, - upper: -lower, - count: *count, - boundary_rule: BoundaryRule::OpenRight, - }); - } - } - Some(result) + build_side_buckets( + spans.iter().map(|span| (span.offset, span.length)), + counts, + self.schema, + &self.custom_values, + positive, + ) } /// Estimates the value at quantile `q`. @@ -686,83 +656,15 @@ impl NativeHistogram { /// Estimates the value at quantile `q` and reports the effect of NaN observations. pub fn quantile_with_info(&self, q: f64) -> (f64, Option) { - if q < 0.0 { - return (f64::NEG_INFINITY, None); - } - if q > 1.0 { - return (f64::INFINITY, None); - } - if self.count == 0.0 || q.is_nan() { - return (f64::NAN, None); - } - - let Some(mut buckets) = self.all_buckets() else { - return (f64::NAN, None); - }; - let bucket_total = buckets.iter().map(|bucket| bucket.count).sum::(); - let has_nan_observations = self.sum.is_nan() && bucket_total < self.count; - let info = has_nan_observations.then_some(NativeHistogramQuantileInfo::NaNSkew); - let rank = q * self.count; - let mut count = 0.0; - for bucket in &mut buckets { - if bucket.count == 0.0 { - continue; - } - count += bucket.count; - if count < rank { - continue; - } - - if !self.uses_custom_buckets() && bucket.lower < 0.0 && bucket.upper > 0.0 { - if self.negative_buckets.is_empty() && !self.positive_buckets.is_empty() { - bucket.lower = 0.0; - } else if self.positive_buckets.is_empty() && !self.negative_buckets.is_empty() { - bucket.upper = 0.0; - } - } else if self.uses_custom_buckets() { - if bucket.lower == f64::NEG_INFINITY { - if bucket.upper <= 0.0 { - return (bucket.upper, info); - } - bucket.lower = 0.0; - } else if bucket.upper == f64::INFINITY { - return (bucket.lower, info); - } - } - - let rank_in_bucket = rank - (count - bucket.count); - let fraction = rank_in_bucket / bucket.count; - if self.uses_custom_buckets() || (bucket.lower <= 0.0 && bucket.upper >= 0.0) { - return ( - bucket.lower + (bucket.upper - bucket.lower) * fraction, - info, - ); - } - - let log_lower = bucket.lower.abs().log2(); - let log_upper = bucket.upper.abs().log2(); - if bucket.lower > 0.0 { - return ( - 2.0_f64.powf(log_lower + (log_upper - log_lower) * fraction), - info, - ); - } - return ( - -2.0_f64.powf(log_upper + (log_lower - log_upper) * (1.0 - fraction)), - info, - ); - } - - let info = if self.sum.is_nan() && count < self.count { - Some(if count < rank { - NativeHistogramQuantileInfo::NaNResult - } else { - NativeHistogramQuantileInfo::NaNSkew - }) - } else { - None - }; - (f64::NAN, info) + quantile_from_parts( + q, + self.schema, + self.count, + self.sum, + self.negative_buckets.is_empty(), + self.positive_buckets.is_empty(), + || self.all_buckets(), + ) } /// Estimates the fraction of observations between `lower` and `upper`. @@ -1081,21 +983,223 @@ fn add_reset_hint(left: CounterResetHint, right: CounterResetHint) -> CounterRes } } -fn side_bucket_indices(spans: &[Span]) -> Option> { +/// Estimates a quantile from histogram metadata and a lazily materialized bucket sequence. +/// +/// This is the estimator [`NativeHistogram::quantile_with_info`] and [`quantile_histogram_view`] +/// expose, so it stays for callers of this crate. The PromQL `histogram_quantile` does not use it: +/// that function reads the same histogram through the native kernel in the `promql` crate, which +/// walks the buckets the way Prometheus does -- from the highest bucket down for a quantile above +/// the median -- so one histogram has one answer instead of two that differ in their last places. +/// The exponential boundary below interpolates with `2^x`, which likewise stays only for this +/// estimator; the kernel interpolates with `exp2` over Prometheus's bound table. +fn quantile_from_parts( + q: f64, + schema: i32, + count_total: f64, + sum: f64, + negative_empty: bool, + positive_empty: bool, + buckets: impl FnOnce() -> Option>, +) -> (f64, Option) { + if q < 0.0 { + return (f64::NEG_INFINITY, None); + } + if q > 1.0 { + return (f64::INFINITY, None); + } + if count_total == 0.0 || q.is_nan() { + return (f64::NAN, None); + } + let Some(mut buckets) = buckets() else { + return (f64::NAN, None); + }; + let bucket_total = buckets.iter().map(|bucket| bucket.count).sum::(); + let has_nan_observations = sum.is_nan() && bucket_total < count_total; + let info = has_nan_observations.then_some(NativeHistogramQuantileInfo::NaNSkew); + let rank = q * count_total; + let mut count = 0.0; + for bucket in &mut buckets { + if bucket.count == 0.0 { + continue; + } + count += bucket.count; + if count < rank { + continue; + } + if schema != CUSTOM_BUCKETS_SCHEMA && bucket.lower < 0.0 && bucket.upper > 0.0 { + if negative_empty && !positive_empty { + bucket.lower = 0.0; + } else if positive_empty && !negative_empty { + bucket.upper = 0.0; + } + } else if schema == CUSTOM_BUCKETS_SCHEMA { + if bucket.lower == f64::NEG_INFINITY { + if bucket.upper <= 0.0 { + return (bucket.upper, info); + } + bucket.lower = 0.0; + } else if bucket.upper == f64::INFINITY { + return (bucket.lower, info); + } + } + let rank_in_bucket = rank - (count - bucket.count); + let fraction = rank_in_bucket / bucket.count; + if schema == CUSTOM_BUCKETS_SCHEMA || (bucket.lower <= 0.0 && bucket.upper >= 0.0) { + return ( + bucket.lower + (bucket.upper - bucket.lower) * fraction, + info, + ); + } + let log_lower = bucket.lower.abs().log2(); + let log_upper = bucket.upper.abs().log2(); + if bucket.lower > 0.0 { + return ( + 2.0_f64.powf(log_lower + (log_upper - log_lower) * fraction), + info, + ); + } + return ( + -2.0_f64.powf(log_upper + (log_lower - log_upper) * (1.0 - fraction)), + info, + ); + } + let info = if sum.is_nan() && count < count_total { + Some(if count < rank { + NativeHistogramQuantileInfo::NaNResult + } else { + NativeHistogramQuantileInfo::NaNSkew + }) + } else { + None + }; + (f64::NAN, info) +} + +/// Quantile entrypoint operating directly on the columnar borrowed view. +pub fn quantile_histogram_view( + view: &HistogramView<'_>, + q: f64, +) -> (f64, Option) { + quantile_from_parts( + q, + view.schema, + view.count, + view.sum, + view.negative.buckets.is_empty(), + view.positive.buckets.is_empty(), + || { + Some(assemble_bucket_sides( + build_view_side(view.negative, view.schema, view.custom_values, false)?, + view.zero_threshold, + view.zero_count, + build_view_side(view.positive, view.schema, view.custom_values, true)?, + )) + }, + ) +} + +fn assemble_bucket_sides( + mut negative: Vec, + zero_threshold: f64, + zero_count: f64, + positive: Vec, +) -> Vec { + negative.reverse(); + if zero_count != 0.0 { + negative.push(Bucket { + lower: -zero_threshold, + upper: zero_threshold, + count: zero_count, + boundary_rule: BoundaryRule::ClosedBoth, + }); + } + negative.extend(positive); + negative +} + +fn build_view_side( + side: BucketSideView<'_>, + schema: i32, + custom_values: &[f64], + positive: bool, +) -> Option> { + if side.span_offsets.len() != side.span_lengths.len() { + return None; + } + let mut total = 0usize; + for (span_index, (&offset, &length)) in + side.span_offsets.iter().zip(side.span_lengths).enumerate() + { + if length < 0 || (span_index > 0 && offset < 0) { + return None; + } + total = total.checked_add(length as usize)?; + } + if total != side.buckets.len() { + return None; + } + build_side_buckets( + side.span_offsets + .iter() + .copied() + .zip(side.span_lengths.iter().copied()), + side.buckets, + schema, + custom_values, + positive, + ) +} + +fn build_side_buckets( + spans: impl Iterator, + counts: &[f64], + schema: i32, + custom_values: &[f64], + positive: bool, +) -> Option> { + let indices = bucket_indices(spans)?; + let mut result = Vec::with_capacity(counts.len()); + for (idx, count) in indices.into_iter().zip(counts) { + let upper = get_bound(idx, schema, custom_values)?; + let lower = get_bound(idx.checked_sub(1)?, schema, custom_values)?; + result.push(if positive { + Bucket { + lower, + upper, + count: *count, + boundary_rule: if schema == CUSTOM_BUCKETS_SCHEMA && idx == 0 { + BoundaryRule::ClosedBoth + } else { + BoundaryRule::OpenLeft + }, + } + } else { + Bucket { + lower: -upper, + upper: -lower, + count: *count, + boundary_rule: BoundaryRule::OpenRight, + } + }); + } + Some(result) +} + +fn bucket_indices(spans: impl Iterator) -> Option> { let mut indices = Vec::new(); let mut current_index = 0i32; let mut first = true; - for (span_index, span) in spans.iter().enumerate() { - if span_index > 0 && span.offset < 0 { + for (span_index, (offset, length)) in spans.enumerate() { + if span_index > 0 && offset < 0 { return None; } if first { - current_index = span.offset; + current_index = offset; first = false; } else { - current_index = current_index.checked_add(span.offset)?; + current_index = current_index.checked_add(offset)?; } - for _ in 0..span.length { + for _ in 0..length { indices.push(current_index); current_index = current_index.checked_add(1)?; } @@ -1103,6 +1207,10 @@ fn side_bucket_indices(spans: &[Span]) -> Option> { Some(indices) } +fn side_bucket_indices(spans: &[Span]) -> Option> { + bucket_indices(spans.iter().map(|span| (span.offset, span.length))) +} + fn span_bucket_len(spans: &[Span]) -> Option { spans .iter() @@ -1291,6 +1399,15 @@ pub fn exponential_overflow_bucket_index(schema: i32) -> Option { i32::try_from(last_finite.checked_add(1)?).ok() } +/// The bound of bucket `idx`: a custom bound, an infinity sentinel, or `2^(idx / 2^schema)`. +/// +/// The exponential case computes its bound instead of reading one, while Prometheus reads +/// `ExponentialBounds`: those entries are not all correctly rounded, because a bound becomes a zero +/// threshold that is compared exactly, and a computed one would not compare as the sender's did. +/// So the computed bound here agrees with the table the native histogram kernel uses only to within +/// an ulp. This function keeps serving the renderers and the estimators of this crate's public +/// `NativeHistogram` API (`promql_string`, `estimated_stdvar`, the legacy quantile above, the +/// zero-threshold reconciliation in `add`); the PromQL estimators read the kernel's `bound`. fn get_bound(idx: i32, schema: i32, custom_values: &[f64]) -> Option { if schema == CUSTOM_BUCKETS_SCHEMA { return match idx { @@ -1387,6 +1504,29 @@ where Ok((!values.is_null(row)).then(|| values.value(row))) } +fn borrowed_list<'a, T>( + list: &'a ListArray, + values: &'a PrimitiveArray, + row: usize, + name: &str, +) -> DfResult<&'a [T::Native]> +where + T: ArrowPrimitiveType, +{ + if list.is_null(row) { + return Ok(&[]); + } + let offsets = list.value_offsets(); + let start = offsets[row] as usize; + let end = offsets[row + 1] as usize; + if (start..end).any(|index| values.is_null(index)) { + return Err(DataFusionError::Execution(format!( + "native histogram list field {name} contains null" + ))); + } + Ok(&values.values()[start..end]) +} + fn list_values(array: &StructArray, name: &str, row: usize) -> DfResult> where T: ArrowPrimitiveType, @@ -1453,6 +1593,178 @@ fn check_span_bucket_count(spans: &[Span], buckets: usize, name: &str) -> DfResu Ok(()) } +/// Converts persisted native histograms directly into canonical columnar samples. +/// +/// Bucket and custom-bound values are borrowed from Arrow until copied by the batch builder. +pub fn histogram_samples_from_arrow(array: &StructArray) -> DfResult { + let schema = primitive_child::(array, SCHEMA_FIELD)?; + let threshold = primitive_child::(array, ZERO_THRESHOLD_FIELD)?; + let sum = primitive_child::(array, SUM_FIELD)?; + let hint = primitive_child::(array, RESET_HINT_FIELD)?; + let start = primitive_child::(array, START_TIMESTAMP_FIELD)?; + let custom_list = list_child(array, CUSTOM_VALUES_FIELD)?; + let custom_values = list_primitive::(custom_list, CUSTOM_VALUES_FIELD)?; + let positive_offsets_list = list_child(array, POSITIVE_SPAN_OFFSETS_FIELD)?; + let positive_offsets = + list_primitive::(positive_offsets_list, POSITIVE_SPAN_OFFSETS_FIELD)?; + let positive_lengths_list = list_child(array, POSITIVE_SPAN_LENGTHS_FIELD)?; + let positive_lengths = + list_primitive::(positive_lengths_list, POSITIVE_SPAN_LENGTHS_FIELD)?; + let negative_offsets_list = list_child(array, NEGATIVE_SPAN_OFFSETS_FIELD)?; + let negative_offsets = + list_primitive::(negative_offsets_list, NEGATIVE_SPAN_OFFSETS_FIELD)?; + let negative_lengths_list = list_child(array, NEGATIVE_SPAN_LENGTHS_FIELD)?; + let negative_lengths = + list_primitive::(negative_lengths_list, NEGATIVE_SPAN_LENGTHS_FIELD)?; + let count_f = primitive_child::(array, COUNT_F64_FIELD)?; + let zero_f = primitive_child::(array, ZERO_COUNT_F64_FIELD)?; + let positive_f_list = list_child(array, POSITIVE_BUCKETS_F64_FIELD)?; + let positive_f = list_primitive::(positive_f_list, POSITIVE_BUCKETS_F64_FIELD)?; + let negative_f_list = list_child(array, NEGATIVE_BUCKETS_F64_FIELD)?; + let negative_f = list_primitive::(negative_f_list, NEGATIVE_BUCKETS_F64_FIELD)?; + let count_i = primitive_child::(array, COUNT_I64_FIELD)?; + let zero_i = primitive_child::(array, ZERO_COUNT_I64_FIELD)?; + let positive_i_list = list_child(array, POSITIVE_BUCKETS_I64_FIELD)?; + let positive_i = list_primitive::(positive_i_list, POSITIVE_BUCKETS_I64_FIELD)?; + let negative_i_list = list_child(array, NEGATIVE_BUCKETS_I64_FIELD)?; + let negative_i = list_primitive::(negative_i_list, NEGATIVE_BUCKETS_I64_FIELD)?; + + let mut builder = HistogramBatchBuilder::new(); + let mut indices = Vec::with_capacity(array.len()); + for row in 0..array.len() { + if array.is_null(row) { + indices.push(None); + continue; + } + let required = |values: &dyn Array, name: &str| -> DfResult<()> { + if values.is_null(row) { + Err(DataFusionError::Execution(format!( + "native histogram field {name} is null" + ))) + } else { + Ok(()) + } + }; + required(schema, SCHEMA_FIELD)?; + required(threshold, ZERO_THRESHOLD_FIELD)?; + required(sum, SUM_FIELD)?; + required(hint, RESET_HINT_FIELD)?; + let positive_offsets = borrowed_list( + positive_offsets_list, + positive_offsets, + row, + POSITIVE_SPAN_OFFSETS_FIELD, + )?; + let positive_lengths = borrowed_list( + positive_lengths_list, + positive_lengths, + row, + POSITIVE_SPAN_LENGTHS_FIELD, + )?; + let negative_offsets = borrowed_list( + negative_offsets_list, + negative_offsets, + row, + NEGATIVE_SPAN_OFFSETS_FIELD, + )?; + let negative_lengths = borrowed_list( + negative_lengths_list, + negative_lengths, + row, + NEGATIVE_SPAN_LENGTHS_FIELD, + )?; + let custom = borrowed_list(custom_list, custom_values, row, CUSTOM_VALUES_FIELD)?; + let (count, zero_count, positive_buckets, negative_buckets) = if !count_f.is_null(row) { + ( + count_f.value(row), + if zero_f.is_null(row) { + 0.0 + } else { + zero_f.value(row) + }, + Cow::Borrowed(borrowed_list( + positive_f_list, + positive_f, + row, + POSITIVE_BUCKETS_F64_FIELD, + )?), + Cow::Borrowed(borrowed_list( + negative_f_list, + negative_f, + row, + NEGATIVE_BUCKETS_F64_FIELD, + )?), + ) + } else { + required(count_i, COUNT_I64_FIELD)?; + let p: Vec = + borrowed_list(positive_i_list, positive_i, row, POSITIVE_BUCKETS_I64_FIELD)? + .iter() + .map(|v| *v as f64) + .collect(); + let n: Vec = + borrowed_list(negative_i_list, negative_i, row, NEGATIVE_BUCKETS_I64_FIELD)? + .iter() + .map(|v| *v as f64) + .collect(); + ( + count_i.value(row) as f64, + if zero_i.is_null(row) { + 0.0 + } else { + zero_i.value(row) as f64 + }, + Cow::Owned(p), + Cow::Owned(n), + ) + }; + let index = builder + .push(HistogramView { + schema: schema.value(row), + zero_threshold: threshold.value(row), + sum: sum.value(row), + count, + zero_count, + reset_hint: hint.value(row).into(), + start_timestamp: (!start.is_null(row)).then(|| start.value(row)), + custom_values: custom, + positive: BucketSideView { + span_offsets: positive_offsets, + span_lengths: positive_lengths, + buckets: positive_buckets.as_ref(), + }, + negative: BucketSideView { + span_offsets: negative_offsets, + span_lengths: negative_lengths, + buckets: negative_buckets.as_ref(), + }, + }) + .map_err(|e| DataFusionError::External(Box::new(e)))?; + indices.push(Some(index)); + } + let batch = builder + .finish() + .map_err(|e| DataFusionError::External(Box::new(e)))?; + Samples::try_from_histogram(UInt32Array::from(indices), batch) + .map_err(|e| DataFusionError::External(Box::new(e))) +} + +fn list_primitive<'a, T>(list: &'a ListArray, name: &str) -> DfResult<&'a PrimitiveArray> +where + T: ArrowPrimitiveType, +{ + let values = list.values(); + values + .as_any() + .downcast_ref::>() + .ok_or_else(|| { + DataFusionError::Execution(format!( + "native histogram list field {name} has invalid value type {}", + values.data_type() + )) + }) +} + /// Decodes one native histogram row into the query-time [`NativeHistogram`] model. /// /// A null struct returns `Ok(None)`. Integer payloads are converted to absolute @@ -1711,6 +2023,103 @@ pub fn build_histogram_array(values: &[Option]) -> ArrayRef { #[cfg(test)] mod tests { use super::*; + use datatypes::series::histogram::HistogramBatch; + + #[test] + fn assembles_bucket_sides_in_order_and_preserves_zero_count_semantics() { + let bucket = |lower, upper, count, boundary_rule| Bucket { + lower, + upper, + count, + boundary_rule, + }; + let negative = vec![ + bucket(-3.0, -2.0, 1.0, BoundaryRule::OpenRight), + bucket(-4.0, -3.0, 2.0, BoundaryRule::OpenRight), + ]; + let positive = vec![bucket(2.0, 3.0, 4.0, BoundaryRule::OpenLeft)]; + + for (zero_count, expected) in [ + ( + 5.0, + vec![ + bucket(-4.0, -3.0, 2.0, BoundaryRule::OpenRight), + bucket(-3.0, -2.0, 1.0, BoundaryRule::OpenRight), + bucket(-0.5, 0.5, 5.0, BoundaryRule::ClosedBoth), + bucket(2.0, 3.0, 4.0, BoundaryRule::OpenLeft), + ], + ), + ( + 0.0, + vec![ + bucket(-4.0, -3.0, 2.0, BoundaryRule::OpenRight), + bucket(-3.0, -2.0, 1.0, BoundaryRule::OpenRight), + bucket(2.0, 3.0, 4.0, BoundaryRule::OpenLeft), + ], + ), + ( + -0.0, + vec![ + bucket(-4.0, -3.0, 2.0, BoundaryRule::OpenRight), + bucket(-3.0, -2.0, 1.0, BoundaryRule::OpenRight), + bucket(2.0, 3.0, 4.0, BoundaryRule::OpenLeft), + ], + ), + ] { + assert_eq!( + assemble_bucket_sides(negative.clone(), 0.5, zero_count, positive.clone()), + expected + ); + } + } + + fn assert_histogram_view_eq(view: &HistogramView<'_>, expected: &NativeHistogram) { + assert_eq!(view.schema, expected.schema); + assert_eq!( + view.zero_threshold.to_bits(), + expected.zero_threshold.to_bits() + ); + assert_eq!(view.sum.to_bits(), expected.sum.to_bits()); + assert_eq!(view.count.to_bits(), expected.count.to_bits()); + assert_eq!(view.zero_count.to_bits(), expected.zero_count.to_bits()); + assert_eq!(view.reset_hint, expected.reset_hint); + assert_eq!(view.start_timestamp, expected.start_timestamp); + assert_eq!(view.custom_values.len(), expected.custom_values.len()); + for (actual, expected) in view.custom_values.iter().zip(&expected.custom_values) { + assert_eq!(actual.to_bits(), expected.to_bits()); + } + for (actual, expected_spans, expected_buckets) in [ + ( + &view.positive, + &expected.positive_spans, + &expected.positive_buckets, + ), + ( + &view.negative, + &expected.negative_spans, + &expected.negative_buckets, + ), + ] { + assert_eq!( + actual.span_offsets, + expected_spans + .iter() + .map(|span| span.offset) + .collect::>() + ); + assert_eq!( + actual.span_lengths, + expected_spans + .iter() + .map(|span| span.length) + .collect::>() + ); + assert_eq!(actual.buckets.len(), expected_buckets.len()); + for (actual, expected) in actual.buckets.iter().zip(expected_buckets) { + assert_eq!(actual.to_bits(), expected.to_bits()); + } + } + } fn histogram(positive_spans: Vec, positive_buckets: Vec) -> NativeHistogram { let count = positive_buckets.iter().sum(); @@ -1730,6 +2139,215 @@ mod tests { } } + #[test] + fn borrowed_quantile_matches_owned_through_batch_builder() { + let mut owned = histogram( + vec![Span { + offset: 0, + length: 2, + }], + vec![1.0, 2.0], + ); + owned.count = 5.0; + owned.zero_threshold = 0.5; + owned.zero_count = 1.0; + owned.start_timestamp = Some(123456); + owned.negative_spans = vec![Span { + offset: 0, + length: 1, + }]; + owned.negative_buckets = vec![1.0]; + let mut builder = HistogramBatchBuilder::new(); + assert_eq!(owned.push_to(&mut builder).unwrap(), 0); + let batch = builder.finish().unwrap(); + let view = batch.view(0).unwrap(); + for q in [-0.1, 0.0, 0.1, 0.3, 0.5, 1.0, 1.1, f64::NAN] { + let expected = owned.quantile_with_info(q); + let actual = quantile_histogram_view(&view, q); + assert_eq!(actual.0.to_bits(), expected.0.to_bits()); + assert_eq!(actual.1, expected.1); + } + assert_eq!(view.reset_hint, owned.reset_hint); + assert_eq!(view.start_timestamp, owned.start_timestamp); + assert_eq!(view.count.to_bits(), owned.count.to_bits()); + assert_eq!(view.sum.to_bits(), owned.sum.to_bits()); + } + + #[test] + fn owned_malformed_spans_keep_truncating_behavior() { + let malformed = NativeHistogram { + schema: 0, + zero_threshold: 0.0, + sum: 3.0, + reset_hint: CounterResetHint::Unknown, + start_timestamp: None, + custom_values: Vec::new(), + positive_spans: vec![Span { + offset: 0, + length: 1, + }], + negative_spans: Vec::new(), + count: 3.0, + zero_count: 0.0, + positive_buckets: vec![1.0, 2.0], + negative_buckets: Vec::new(), + }; + assert_eq!(malformed.quantile(0.0), 0.5); + assert_eq!(malformed.fraction(0.0, 1.0), 1.0); + + let negative_length = NativeHistogram { + positive_spans: vec![ + Span { + offset: 0, + length: -1, + }, + Span { + offset: 0, + length: 1, + }, + ], + positive_buckets: vec![1.0], + count: 1.0, + ..histogram(Vec::new(), Vec::new()) + }; + assert_eq!(negative_length.quantile(0.0), 0.5); + } + + #[test] + fn borrowed_custom_quantile_and_nan_info_match_owned() { + let owned = NativeHistogram { + schema: CUSTOM_BUCKETS_SCHEMA, + zero_threshold: 0.0, + sum: f64::NAN, + reset_hint: CounterResetHint::Unrecognized(91), + start_timestamp: Some(987), + custom_values: vec![-1.0, 1.0], + positive_spans: vec![Span { + offset: 0, + length: 3, + }], + negative_spans: Vec::new(), + count: 4.0, + zero_count: 0.0, + positive_buckets: vec![1.0, 1.0, 1.0], + negative_buckets: Vec::new(), + }; + let mut builder = HistogramBatchBuilder::new(); + owned.push_to(&mut builder).unwrap(); + let batch = builder.finish().unwrap(); + let view = batch.view(0).unwrap(); + for q in [0.0, 0.5, 0.99, 1.0] { + let expected = owned.quantile_with_info(q); + let actual = quantile_histogram_view(&view, q); + assert_eq!(actual.0.to_bits(), expected.0.to_bits()); + assert_eq!(actual.1, expected.1); + } + } + + #[test] + fn borrowed_quantile_rejects_malformed_and_overflowing_spans() { + let owned = histogram( + vec![Span { + offset: 0, + length: 1, + }], + vec![1.0], + ); + let mut builder = HistogramBatchBuilder::new(); + owned.push_to(&mut builder).unwrap(); + let batch = builder.finish().unwrap(); + let mut view = batch.view(0).unwrap(); + let malformed = [ + BucketSideView { + span_offsets: &[0], + span_lengths: &[], + buckets: &[1.0], + }, + BucketSideView { + span_offsets: &[i32::MAX], + span_lengths: &[1], + buckets: &[1.0], + }, + BucketSideView { + span_offsets: &[0], + span_lengths: &[-1], + buckets: &[], + }, + BucketSideView { + span_offsets: &[0], + span_lengths: &[2], + buckets: &[1.0], + }, + BucketSideView { + span_offsets: &[0], + span_lengths: &[0], + buckets: &[1.0], + }, + BucketSideView { + span_offsets: &[0, -1], + span_lengths: &[0, 1], + buckets: &[1.0], + }, + BucketSideView { + span_offsets: &[0], + span_lengths: &[i32::MAX], + buckets: &[1.0], + }, + ]; + for side in malformed { + view.positive = side; + let (value, info) = quantile_histogram_view(&view, 0.5); + assert!(value.is_nan()); + assert_eq!(info, None); + } + assert_eq!( + quantile_histogram_view(&view, -1.0), + (f64::NEG_INFINITY, None) + ); + assert_eq!(quantile_histogram_view(&view, 2.0), (f64::INFINITY, None)); + } + + #[test] + fn sliced_histogram_view_remains_valid_after_original_owner_drops() { + let first = histogram( + vec![Span { + offset: 0, + length: 1, + }], + vec![2.0], + ); + let mut second = histogram( + vec![Span { + offset: 1, + length: 1, + }], + vec![4.0], + ); + second.schema = CUSTOM_BUCKETS_SCHEMA; + second.custom_values = vec![10.0]; + second.reset_hint = CounterResetHint::Gauge; + second.start_timestamp = Some(789); + let expected_quantile = second.quantile_with_info(0.5); + let expected_bucket = second.positive_buckets[0]; + let mut builder = HistogramBatchBuilder::new(); + first.push_to(&mut builder).unwrap(); + second.push_to(&mut builder).unwrap(); + let batch = builder.finish().unwrap(); + let sliced = HistogramBatch::try_from_arrow(batch.as_arrow().slice(1, 1)).unwrap(); + drop(batch); + drop(first); + drop(second); + let view = sliced.view(0).unwrap(); + assert_eq!(view.schema, CUSTOM_BUCKETS_SCHEMA); + assert_eq!(view.custom_values, &[10.0]); + assert_eq!(view.positive.span_offsets, &[1]); + assert_eq!(view.positive.span_lengths, &[1]); + assert_eq!(view.positive.buckets, &[expected_bucket]); + assert_eq!(view.reset_hint, CounterResetHint::Gauge); + assert_eq!(view.start_timestamp, Some(789)); + assert_eq!(quantile_histogram_view(&view, 0.5), expected_quantile); + } + #[test] fn promql_string_matches_prometheus_float_format() { assert_eq!(format_promql_histogram_float(0.0001), "0.0001"); @@ -1787,6 +2405,231 @@ mod tests { ); } + #[test] + fn direct_arrow_samples_preserve_payload_and_null_rows() { + let mut expected = histogram( + vec![Span { + offset: 0, + length: 2, + }], + vec![1.0, 3.0], + ); + expected.negative_spans = vec![Span { + offset: -2, + length: 1, + }]; + expected.negative_buckets = vec![7.0]; + expected.schema = 3; + expected.zero_threshold = f64::from_bits(0x3fb9_9999_9999_999a); + expected.sum = f64::from_bits(0x7ff8_0000_0000_0042); + expected.zero_count = -0.0; + expected.custom_values = vec![f64::from_bits(0x3ff0_0000_0000_0001)]; + expected.positive_spans = vec![ + Span { + offset: 2, + length: 1, + }, + Span { + offset: 1, + length: 1, + }, + ]; + expected.positive_buckets = vec![1.0, 3.0]; + expected.reset_hint = CounterResetHint::Unrecognized(42); + expected.start_timestamp = Some(1234); + let array = build_histogram_array(&[Some(expected.clone()), None]); + let array = array.as_any().downcast_ref::().unwrap(); + let samples = histogram_samples_from_arrow(array).unwrap(); + assert_eq!(samples.len(), 2); + let datatypes::series::samples::SampleRef::Histogram(view) = samples.sample(0) else { + panic!("expected histogram sample"); + }; + assert_histogram_view_eq(&view, &expected); + assert!(matches!( + samples.sample(1), + datatypes::series::samples::SampleRef::Missing + )); + } + + #[test] + fn direct_arrow_conversion_handles_sliced_parent_and_owns_result() { + let mut first = histogram( + vec![Span { + offset: 3, + length: 2, + }], + vec![8.0, 9.0], + ); + first.custom_values = vec![4.0]; + first.negative_spans = vec![Span { + offset: 1, + length: 1, + }]; + first.negative_buckets = vec![6.0]; + let mut second = histogram( + vec![Span { + offset: -1, + length: 1, + }], + vec![2.0], + ); + second.negative_spans = vec![Span { + offset: 2, + length: 1, + }]; + second.negative_buckets = vec![3.0]; + second.custom_values = vec![0.5]; + second.start_timestamp = Some(77); + second.reset_hint = CounterResetHint::Unrecognized(99); + second.zero_count = -0.0; + let owner = build_histogram_array(&[Some(first), Some(second.clone())]); + let sliced = owner.slice(1, 1); + let samples = { + let struct_array = sliced.as_any().downcast_ref::().unwrap(); + histogram_samples_from_arrow(struct_array).unwrap() + }; + drop(sliced); + drop(owner); + let datatypes::series::samples::SampleRef::Histogram(view) = samples.sample(0) else { + panic!("expected histogram sample"); + }; + assert_histogram_view_eq(&view, &second); + } + + #[test] + fn direct_arrow_entrypoint_preserves_empty_and_all_null_rows() { + for (values, expected_len) in [(&[][..], 0), (&[None, None][..], 2)] { + let array = build_histogram_array(values); + let array = array.as_any().downcast_ref::().unwrap(); + let samples = histogram_samples_from_arrow(array).unwrap(); + assert_eq!(samples.len(), expected_len); + assert!((0..expected_len).all(|index| matches!( + samples.sample(index), + datatypes::series::samples::SampleRef::Missing + ))); + } + } + + #[test] + fn direct_arrow_integer_buckets_remain_absolute_and_float_family_wins() { + let value = histogram( + vec![Span { + offset: 0, + length: 2, + }], + vec![1.0, 3.0], + ); + let array = build_histogram_array(&[Some(value)]); + let source = array.as_any().downcast_ref::().unwrap(); + let mut columns = source.columns().to_vec(); + let index = |name: &str| { + source + .fields() + .iter() + .position(|f| f.name() == name) + .unwrap() + }; + columns[index(COUNT_F64_FIELD)] = Arc::new(Float64Array::from(vec![None])); + columns[index(COUNT_I64_FIELD)] = Arc::new(Int64Array::from(vec![Some(4)])); + columns[index(POSITIVE_BUCKETS_I64_FIELD)] = + Arc::new(ListArray::from_iter_primitive::([Some( + vec![Some(1), Some(3)], + )])); + let integer = StructArray::new(source.fields().clone(), columns, None); + let samples = histogram_samples_from_arrow(&integer).unwrap(); + assert!( + matches!(samples.sample(0), datatypes::series::samples::SampleRef::Histogram(view) + if view.count == 4.0 && view.positive.buckets == [1.0, 3.0]) + ); + + let mut columns = integer.columns().to_vec(); + columns[index(ZERO_COUNT_I64_FIELD)] = Arc::new(Int64Array::from(vec![None])); + columns[index(ZERO_COUNT_F64_FIELD)] = Arc::new(Float64Array::from(vec![None])); + columns[index(COUNT_F64_FIELD)] = Arc::new(Float64Array::from(vec![None])); + let integer_null_zero = StructArray::new(integer.fields().clone(), columns, None); + let samples = histogram_samples_from_arrow(&integer_null_zero).unwrap(); + assert!( + matches!(samples.sample(0), datatypes::series::samples::SampleRef::Histogram(view) + if view.count == 4.0 && view.zero_count == 0.0 && view.positive.buckets == [1.0, 3.0]) + ); + + let mut columns = integer.columns().to_vec(); + columns[index(ZERO_COUNT_F64_FIELD)] = Arc::new(Float64Array::from(vec![None])); + columns[index(COUNT_F64_FIELD)] = Arc::new(Float64Array::from(vec![Some(5.0)])); + columns[index(POSITIVE_BUCKETS_F64_FIELD)] = + Arc::new(ListArray::from_iter_primitive::([Some( + vec![Some(2.0), Some(4.0)], + )])); + let both_families = StructArray::new(integer.fields().clone(), columns, None); + let samples = histogram_samples_from_arrow(&both_families).unwrap(); + assert!( + matches!(samples.sample(0), datatypes::series::samples::SampleRef::Histogram(view) + if view.count == 5.0 && view.zero_count == 0.0 && view.positive.buckets == [2.0, 4.0]) + ); + } + + #[test] + fn direct_arrow_conversion_rejects_null_required_fields_and_list_items() { + let value = histogram( + vec![Span { + offset: 0, + length: 1, + }], + vec![1.0], + ); + let array = build_histogram_array(&[Some(value)]); + let source = array.as_any().downcast_ref::().unwrap(); + let mut columns = source.columns().to_vec(); + let schema_idx = source + .fields() + .iter() + .position(|f| f.name() == SCHEMA_FIELD) + .unwrap(); + columns[schema_idx] = Arc::new(Int32Array::from(vec![None])); + let malformed_scalar = StructArray::new(source.fields().clone(), columns, None); + assert!(histogram_samples_from_arrow(&malformed_scalar).is_err()); + + let mut columns = source.columns().to_vec(); + let buckets_idx = source + .fields() + .iter() + .position(|f| f.name() == POSITIVE_BUCKETS_F64_FIELD) + .unwrap(); + columns[buckets_idx] = + Arc::new(ListArray::from_iter_primitive::([Some( + vec![None], + )])); + let malformed_item = StructArray::new(source.fields().clone(), columns, None); + assert!(histogram_samples_from_arrow(&malformed_item).is_err()); + + let mut columns = source.columns().to_vec(); + let lengths_idx = source + .fields() + .iter() + .position(|f| f.name() == POSITIVE_SPAN_LENGTHS_FIELD) + .unwrap(); + columns[lengths_idx] = Arc::new(ListArray::from_iter_primitive::([Some( + vec![Some(2)], + )])); + let malformed_spans = StructArray::new(source.fields().clone(), columns, None); + assert!(histogram_samples_from_arrow(&malformed_spans).is_err()); + } + + #[test] + fn datatypes_reset_hints_round_trip_through_native_histogram() { + use datatypes::series::histogram::CounterResetHint as DatatypesCounterResetHint; + + let values = [-1, 0, 1, 2, 3, 77, i32::MIN, i32::MAX]; + for value in values { + let datatypes_hint = DatatypesCounterResetHint::from(value); + let query_hint: CounterResetHint = datatypes_hint; + let mut histogram = histogram(Vec::new(), Vec::new()); + histogram.reset_hint = query_hint; + let datatypes_hint: DatatypesCounterResetHint = histogram.reset_hint; + assert_eq!(i32::from(datatypes_hint), value); + } + } + #[test] fn arrow_round_trip_preserves_unrecognized_reset_hint() { let mut expected = histogram( diff --git a/src/common/query/src/prelude.rs b/src/common/query/src/prelude.rs index 8d950d77096..beafb83f30b 100644 --- a/src/common/query/src/prelude.rs +++ b/src/common/query/src/prelude.rs @@ -30,6 +30,9 @@ static GREPTIME_VALUE_CELL: OnceCell = OnceCell::new(); /// Default native histogram column name. static GREPTIME_NATIVE_HISTOGRAM_CELL: OnceCell = OnceCell::new(); +/// Default exemplar labels column name. +static GREPTIME_EXEMPLAR_LABELS_CELL: OnceCell = 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] diff --git a/src/common/query/src/promql_annotations.rs b/src/common/query/src/promql_annotations.rs index 70f4db0af70..ccb8fd0b3de 100644 --- a/src/common/query/src/promql_annotations.rs +++ b/src/common/query/src/promql_annotations.rs @@ -113,17 +113,6 @@ pub fn promql_annotation_collector(query_id: &str) -> PromqlAnnotationCollector collector } -pub fn get_promql_annotation_collector(query_id: &str) -> Option { - 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, values: impl Iterator) { let mut seen = target.iter().cloned().collect::>(); 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()); } } diff --git a/src/common/query/src/request.rs b/src/common/query/src/request.rs index 86c6758aa25..2d68133d283 100644 --- a/src/common/query/src/request.rs +++ b/src/common/query/src/request.rs @@ -14,17 +14,21 @@ mod base64_serde; mod initial_remote_dyn_filter_reg; +#[cfg(any(test, feature = "testing"))] +pub mod remote_membership_test_support; use std::cell::Cell; use std::sync::Arc; use api::v1::region::RegionRequestHeader; +use datafusion::arrow::array::{Array, ArrayRef, StringArray}; use datafusion::execution::TaskContext; -use datafusion::physical_expr::expressions::{Column, InListExpr, lit}; +use datafusion::physical_expr::expressions::{Column, InListExpr, Literal}; +use datafusion::physical_expr::{conjunction, split_conjunction}; use datafusion::physical_plan::joins::HashTableLookupExpr; use datafusion::physical_plan::{ExecutionPlan, PhysicalExpr}; -use datafusion_common::tree_node::{Transformed, TreeNode, TreeNodeRecursion}; -use datafusion_common::{DataFusionError, Result as DataFusionResult}; +use datafusion_common::tree_node::{TreeNode, TreeNodeRecursion}; +use datafusion_common::{DataFusionError, Result as DataFusionResult, ScalarValue}; use datafusion_expr::LogicalPlan; use datafusion_proto::physical_plan::from_proto::parse_physical_expr; use datafusion_proto::physical_plan::to_proto::{ @@ -34,7 +38,8 @@ use datafusion_proto::physical_plan::{ DefaultPhysicalExtensionCodec, DefaultPhysicalProtoConverter, PhysicalExtensionCodec, PhysicalPlanDecodeContext, PhysicalProtoConverterExtension, }; -use datafusion_proto::protobuf::{PhysicalExprNode, PhysicalPlanNode}; +use datafusion_proto::protobuf::physical_expr_node::ExprType as PhysicalExprNodeType; +use datafusion_proto::protobuf::{PhysicalExprNode, PhysicalInListNode, PhysicalPlanNode}; use prost::Message; use serde::{Deserialize, Serialize}; use snafu::ensure; @@ -45,12 +50,46 @@ pub use self::initial_remote_dyn_filter_reg::{ INITIAL_REMOTE_DYN_FILTER_REGISTRATIONS_EXTENSION_KEY, InitialDynFilterReg, InitialDynFilterRegs, InitialDynFilterSnapshot, }; -use crate::error::{DynFilterPayloadTooLargeSnafu, Error as CommonQueryError}; +use crate::error::{ + DynFilterPayloadTooLargeSnafu, DynFilterUnsupportedSnafu, Error as CommonQueryError, +}; pub const DYN_FILTER_PROTOCOL_VERSION: u32 = 1; /// Shared raw protobuf byte budget for remote dynamic filter payloads. pub const REMOTE_DYN_FILTER_PAYLOAD_MAX_BYTES: usize = 512 * 1024; +/// Smallest number of encoded bytes a single `IN` list literal can take. +/// +/// Every list entry is a `PhysicalExprNode` whose `literal` arm holds the +/// [`ScalarValue`] message itself, so the oneof field tag plus its length prefix are +/// already 2 bytes even for an empty `Utf8` value (whose `ScalarValue` body may encode to +/// nothing at all). Protobuf sizes add up across nesting, so a payload of `B` bytes can +/// never hold more than `B / 2` literals. This is the floor the value bound is derived +/// from; it is not an encoder policy constant. +const MIN_ENCODED_LITERAL_BYTES: usize = 2; + +/// Upper bound on how many `IN` list literals `max_payload_bytes` can hold. +/// +/// The count bound is derived from the transport budget with +/// [`MIN_ENCODED_LITERAL_BYTES`] rather than being an arbitrary cap: a larger budget +/// admits proportionally more build keys, and a small budget refuses the membership +/// before a single literal is built. +fn max_membership_values(max_payload_bytes: usize) -> usize { + max_payload_bytes / MIN_ENCODED_LITERAL_BYTES +} + +/// Frame size reported for a payload refused because it does not fit the budget. +/// +/// A refused payload is never materialized, so there is no measured frame length. The +/// error reports the largest lower bound that is known instead: the price of the literals +/// the refused membership would have written (`lower_bound`), or - when nothing about the +/// shape is known - one byte over the budget. Either way the number is genuinely above +/// `max_payload_bytes`; it is a bound, never a measurement, and it is only used for +/// diagnostics. +fn refused_payload_size(lower_bound: usize, max_payload_bytes: usize) -> usize { + lower_bound.max(max_payload_bytes.saturating_add(1)) +} + /// Serialized predicate payload for remote dynamic filter updates. /// /// The payload is tagged in JSON so receivers can reject unsupported encodings @@ -72,20 +111,98 @@ pub enum DynFilterPayload { impl DynFilterPayload { /// Encodes a DataFusion physical expression into a bounded dynamic filter payload. /// - /// Runtime-only hash lookup predicates are degraded to `true` before encoding so - /// serializable min/max bounds around them can still be shipped to remote scans. - /// If the full serializable predicate is still larger than `max_payload_bytes`, large - /// membership predicates (`IN (...)`) are also degraded to `true` as a bounds-only fallback. + /// # Narrow contract: a key list used as a positive pruning hint + /// + /// A runtime [`HashTableLookupExpr`] is written as the existing + /// `PhysicalInListNode` — `key IN (build key, ...)` — built from the lookup's + /// published build-key list, so no new wire variant is needed. The expression tree + /// around it is preserved node for node: `IS NULL`, `NOT`, `CASE`, `AND`, `OR` and + /// every other parent are serialized as-is, and a `NOT` over a lookup therefore + /// becomes `NOT IN`. + /// + /// The membership is a **hint for pruning only**, not a re-statement of the join + /// semantics. For supported positive pruning, the list preserves actual build-key + /// matches; it is not universal Boolean equivalence. `IN`/`NOT IN` propagate + /// `NULL` while a hash lookup can be definite on a `NULL` probe key, and hash + /// presence can admit collisions, so a predicate that inspects the *negation* of a + /// lookup is not universally equivalent. + /// + /// The conversion is decided by the lookup alone (single-column `Utf8`, non-empty, + /// `NULL`-free build keys — see [`HashTableLookupExpr::build_key_membership`]). + /// Exactly one node changes: every [`HashTableLookupExpr`] is written as its key + /// list, wherever it sits in the tree (`NOT lookup` included, which is why it + /// becomes `NOT IN`). No node is ever replaced by a *weaker stand-in* — in + /// particular never by `true` — and no membership is dropped from inside a + /// predicate: when a lookup cannot be written at all, the whole top-level `AND` + /// conjunct that holds it is dropped (see below) or the payload is rejected. + /// + /// # Top-level conjunctive retention + /// + /// If a lookup has no such key list (accessor limitation) or the serialized predicate + /// does not fit `max_payload_bytes`, [`split_conjunction`] splits the original + /// expression and the whole conjuncts that cannot be shipped are dropped. Dropping an + /// `AND` term can only widen a predicate, so the result never drops a row the producer + /// would keep. Which conjuncts go depends on why the payload was refused: + /// + /// - a lookup has no wire form: only conjuncts holding a [`HashTableLookupExpr`] are + /// dropped. A static [`InListExpr`] is representable, so `lookup AND id IN (...)` + /// keeps the list and stays `id IN (...)`; + /// - the payload is over budget: conjuncts holding a [`HashTableLookupExpr`] *or* an + /// [`InListExpr`] are dropped, because a static `IN` list is the node that usually + /// blows the budget. `bounds AND oversized IN (...)` becomes `bounds`. + /// + /// Either way a conjunct is kept or dropped as a whole: a membership nested inside + /// `NOT`, `CASE` or `OR` drops that entire conjunct instead of being rewritten. + /// Retained conjuncts are encoded again under the same budget, and when the first two + /// rules still leave an over-budget payload the second one is applied as well, so a + /// static `IN` list that is too large for the budget is dropped last. + /// + /// # Encoder-level no-substitution rule + /// + /// This encoder never replaces a node in the producer expression with `true`: it + /// serializes the expression, retries after dropping whole top-level conjuncts under + /// the retention rules above, or returns an error. A caller decides what a refused + /// generation means for its receiver. Initial capture keeps the parent filter local; + /// the long-lived query fanout path + /// (`remote_dyn_filter_registry::fanout_snapshot_for_query`) publishes an explicit + /// `true` reset to invalidate a stale region-side predicate. That reset is not a + /// representation of the refused producer expression. + /// + /// The two refusals stay distinct so callers can tell a shape problem from a size + /// problem: + /// + /// - [`CommonQueryError::DynFilterUnsupported`]: no conjunct can be retained because + /// every one of them holds a lookup with no UTF-8 key list (`NOT lookup`, `CASE` / + /// `OR` over such a membership). The wire has no form for the predicate. + /// - [`CommonQueryError::DynFilterPayloadTooLarge`]: the predicate is representable but + /// does not fit `max_payload_bytes` - either a key list itself exceeds the budget, or + /// the retained conjuncts still do not fit. An over-budget key list is never reported + /// as unsupported; it is a size refusal and uses + /// [`ConjunctRetention::OverBudget`]. + /// + /// These refusals do not fail the query in either caller: initial capture leaves the + /// parent filter local, while fanout sends an explicit `true` reset instead of leaving + /// a stale narrower predicate installed. pub fn from_datafusion_expr( expr: &Arc, max_payload_bytes: usize, ) -> DataFusionResult { - match encode_remote_dyn_filter_expr(expr, max_payload_bytes, false) { + match encode_bounded_physical_expr_to_bytes(expr, max_payload_bytes) { Ok(bytes) => Ok(Self::Datafusion(bytes)), + // The predicate cannot be shipped as it stands: either a lookup has no key + // list, or the frame does not fit the budget. Keep the widest *safe* part of + // the predicate instead of publishing an always-true filter. + Err(CommonQueryError::DynFilterUnsupported { .. }) => retain_membership_free_conjuncts( + expr, + max_payload_bytes, + ConjunctRetention::UnrepresentableLookup, + ), Err(CommonQueryError::DynFilterPayloadTooLarge { .. }) => { - encode_remote_dyn_filter_expr(expr, max_payload_bytes, true) - .map(Self::Datafusion) - .map_err(DataFusionError::from) + retain_membership_free_conjuncts( + expr, + max_payload_bytes, + ConjunctRetention::OverBudget, + ) } Err(error) => Err(DataFusionError::from(error)), } @@ -96,6 +213,22 @@ impl DynFilterPayload { /// The decoded expression is validated to ensure column indexes stay within the receiver-side /// schema, column names are consistent (defensive check), and the payload stays within /// `max_payload_bytes`. + /// + /// # Precondition: pruning only, never row filtering + /// + /// The decoded predicate is only a **pruning hint**. The sole production consumer — + /// `Predicate::dyn_filters` (in the `table` crate) and its pruning path, reached by + /// mito2's row-group pruner — uses it to skip containers whose statistics prove that + /// no row can match, so a predicate that is merely *wider* than the producer's costs + /// nothing but a wasted scan. + /// + /// The payload is not a re-statement of the producer predicate: the membership is the + /// join's build-key list, so `IN`/`NOT IN` `NULL` propagation and hash collisions can + /// make it disagree with a runtime lookup, and the encoder drops whole top-level + /// conjuncts it cannot ship (see [`DynFilterPayload::from_datafusion_expr`]). A + /// consumer that *filters rows* would turn every such widening into lost data, so row + /// filtering must not consume this payload unconditionally: it would need to prove the + /// predicate is equivalent for the rows it drops, which this format does not carry. pub fn decode_datafusion_expr( &self, task_ctx: &TaskContext, @@ -129,6 +262,141 @@ fn encode_physical_expr_to_bytes(expr: &Arc) -> DataFusionResu struct BoundedPhysicalExprEncoder { max_payload_bytes: usize, encoded_bytes: Cell, + /// Set when the encoding aborted on a runtime lookup that has no serializable key + /// list. + /// + /// The abort travels out as an ordinary [`DataFusionError`], which would lose the + /// typed dynamic filter error on the way, so the flag is what lets + /// `encode_bounded_physical_expr_to_bytes` rebuild + /// [`CommonQueryError::DynFilterUnsupported`]. No placeholder is ever encoded in its + /// place. + unsupported: Cell, + /// Set to the reported frame size when the encoding aborted because a build-key + /// membership does not fit `max_payload_bytes`. + /// + /// This is a size refusal, not a shape one, so + /// `encode_bounded_physical_expr_to_bytes` rebuilds + /// [`CommonQueryError::DynFilterPayloadTooLarge`] from it instead of reporting the + /// predicate as having no wire form. + over_budget: Cell>, +} + +impl BoundedPhysicalExprEncoder { + fn new(max_payload_bytes: usize) -> Self { + Self { + max_payload_bytes, + encoded_bytes: Cell::new(0), + unsupported: Cell::new(false), + over_budget: Cell::new(None), + } + } + + /// Charges `proto` (including its encoded children) against the payload budget. + /// + /// The accounting is additive over siblings and exact for the top-level node, so + /// no branch can push the payload over budget unnoticed. + fn finish( + &self, + before_children: usize, + proto: PhysicalExprNode, + ) -> DataFusionResult { + let encoded_bytes = before_children.saturating_add(proto.encoded_len()); + self.encoded_bytes.set(encoded_bytes); + validate_payload_size(encoded_bytes, self.max_payload_bytes) + .map_err(DataFusionError::from)?; + Ok(proto) + } + + /// Encodes a lookup as its build-key membership, charging every list literal and + /// node against the payload budget. + /// + /// The decision only looks at the lookup itself: if DataFusion can hand out the + /// single-column `Utf8` build-key list it is written as `key IN (...)`; otherwise the + /// whole payload aborts. A lookup is a real predicate that DataFusion only degrades to + /// `true` in its own proto encoder, so this transport must not write any substitute for + /// it, and the abort keeps the two reasons apart: no key list at all (unsupported) is + /// not the same thing as a key list that exceeds the budget (too large). + fn membership_to_proto( + &self, + lookup: &HashTableLookupExpr, + codec: &dyn PhysicalExtensionCodec, + ) -> DataFusionResult { + let membership = match RemoteMembership::from_lookup(lookup, self.max_payload_bytes) { + Ok(membership) => membership, + // A lookup without a key list has no wire form at all: that is a shape + // refusal, not a size one. + Err(MembershipRefusal::NoKeyList) => return Err(self.abort_unsupported_lookup()), + // The key list exists but does not fit the budget: report it as a size + // refusal so it is not counted as "no wire form". + Err(MembershipRefusal::OverBudget { build_keys }) => { + return Err(self.abort_over_budget_membership(build_keys)); + } + }; + // The count bound is enforced once more before any literal exists, so a build side + // larger than the budget can hold is never materialized. This cannot fail for any + // other reason here: the accessor already guaranteed a non-empty, `NULL`-free + // `Utf8` list, so a refusal is again a size refusal. + let Some(literals) = utf8_list_literals( + &membership.values, + max_membership_values(self.max_payload_bytes), + ) else { + return Err(self.abort_over_budget_membership(membership.values.len())); + }; + + let before_children = self.encoded_bytes.get(); + let mut list = Vec::with_capacity(literals.len()); + for literal in literals { + list.push(self.physical_expr_to_proto(&literal, codec)?); + } + + // The `InList` proto is built by hand instead of going through the generic + // serializer: that path needs an `InListExpr`, whose only constructors + // (`InListExpr::try_new` / `try_new_from_array`) require an input `Schema` to + // resolve the key expression's data type, and this encoder converts a bare + // expression without one. The key is known to be `Utf8` (see + // `HashTableLookupExpr::build_key_membership`), which is exactly what the list + // below writes, so no type check is lost. + let proto = PhysicalExprNode { + expr_id: None, + expr_type: Some(PhysicalExprNodeType::InList(Box::new(PhysicalInListNode { + expr: Some(Box::new( + self.physical_expr_to_proto(&membership.key, codec)?, + )), + list, + negated: false, + }))), + }; + + self.finish(before_children, proto) + } + + /// Aborts the payload because the wire has no form for `lookup`. + /// + /// The returned error only carries the abort; [`Self::unsupported`] is what the caller + /// reads to rebuild the typed dynamic filter error. + fn abort_unsupported_lookup(&self) -> DataFusionError { + self.unsupported.set(true); + DataFusionError::NotImplemented( + "hash table lookup has no UTF-8 build-key membership to encode".to_string(), + ) + } + + /// Aborts the payload because a build-key membership does not fit `max_payload_bytes`. + /// + /// This is a *size* refusal, never a "no wire form" one, so the caller rebuilds + /// [`CommonQueryError::DynFilterPayloadTooLarge`] from [`Self::over_budget`] instead of + /// [`CommonQueryError::DynFilterUnsupported`]. `build_keys` is the number of build keys + /// the refused list would have written; every one of them costs at least + /// [`MIN_ENCODED_LITERAL_BYTES`], so that product is a real lower bound of the frame. + fn abort_over_budget_membership(&self, build_keys: usize) -> DataFusionError { + self.over_budget.set(Some(refused_payload_size( + build_keys.saturating_mul(MIN_ENCODED_LITERAL_BYTES), + self.max_payload_bytes, + ))); + DataFusionError::NotImplemented( + "hash table lookup build-key membership exceeds the payload budget".to_string(), + ) + } } impl PhysicalProtoConverterExtension for BoundedPhysicalExprEncoder { @@ -162,55 +430,268 @@ impl PhysicalProtoConverterExtension for BoundedPhysicalExprEncoder { expr: &Arc, codec: &dyn PhysicalExtensionCodec, ) -> DataFusionResult { + // A real `HashTableLookupExpr` has no wire form: DataFusion's own + // `try_to_proto` degrades it to `true`. Intercept it so the build-key list can + // be written with the existing `InList` node instead. The decision is made by + // the lookup alone; every other node, including `IS NULL`, `NOT`, `CASE`, + // `AND` and `OR`, is serialized exactly as it is. + if let Some(lookup) = expr.downcast_ref::() { + return self.membership_to_proto(lookup, codec); + } + let before_children = self.encoded_bytes.get(); let proto = serialize_physical_expr_with_converter(expr, codec, self)?; // Replace the children's contribution with the whole subtree, including protobuf framing. // Checking each child stops large IN lists before materializing all their Arrow IPC literals. - let encoded_bytes = before_children.saturating_add(proto.encoded_len()); - self.encoded_bytes.set(encoded_bytes); - validate_payload_size(encoded_bytes, self.max_payload_bytes) - .map_err(DataFusionError::from)?; - Ok(proto) + self.finish(before_children, proto) } } +/// Encodes `expr` for the remote wire under `max_payload_bytes`. +/// +/// Returns the typed [`CommonQueryError::DynFilterUnsupported`] when the predicate holds a +/// lookup whose key list cannot be serialized, and +/// [`CommonQueryError::DynFilterPayloadTooLarge`] when the frame (or a build-key +/// membership) does not fit the budget. The two refusals stay distinct: an over-budget +/// membership is a size refusal and is never reported as a predicate without a wire form. +/// The caller answers both with [`retain_membership_free_conjuncts`]; neither is ever +/// replaced with `true`. fn encode_bounded_physical_expr_to_bytes( expr: &Arc, max_payload_bytes: usize, ) -> Result, CommonQueryError> { let codec = DefaultPhysicalExtensionCodec {}; - let encoder = BoundedPhysicalExprEncoder { - max_payload_bytes, - encoded_bytes: Cell::new(0), - }; + let encoder = BoundedPhysicalExprEncoder::new(max_payload_bytes); let proto = encoder.physical_expr_to_proto(expr, &codec); - // Preserve the size error so the caller can retry with bounds only. + // A build-key membership that exceeds the budget is a size refusal even though the + // frame that would have held it is never materialized. + if let Some(payload_size_bytes) = encoder.over_budget.get() { + return Err(DynFilterPayloadTooLargeSnafu { + payload_size_bytes, + max_payload_bytes, + } + .build()); + } + let unsupported = encoder.unsupported.get(); + // The encoder stops at the node that went over budget, so this reports the size + // error unwrapped instead of the wrapped DataFusion error. validate_payload_size(encoder.encoded_bytes.get(), max_payload_bytes)?; + if unsupported { + return Err(DynFilterUnsupportedSnafu { + reason: "the predicate holds a hash table lookup without a UTF-8 build-key \ + membership", + } + .build()); + } Ok(proto.map_err(CommonQueryError::from)?.encode_to_vec()) } -fn encode_remote_dyn_filter_expr( - expr: &Arc, - max_payload_bytes: usize, - bounds_only: bool, -) -> Result, CommonQueryError> { - let expr = portable_remote_dyn_filter_expr(Arc::clone(expr), bounds_only) - .map_err(CommonQueryError::from)?; - encode_bounded_physical_expr_to_bytes(&expr, max_payload_bytes) +/// Which top-level conjuncts [`retain_membership_free_conjuncts`] has to drop. +#[derive(Clone, Copy, Debug)] +enum ConjunctRetention { + /// The payload holds a [`HashTableLookupExpr`] without a wire form, so such a lookup + /// is the only unshippable node: a static [`InListExpr`] is representable and stays. + UnrepresentableLookup, + /// The payload exceeds its budget. A static [`InListExpr`] is the node most likely to + /// be the oversized one, so it is dropped with the lookups. + OverBudget, } -fn portable_remote_dyn_filter_expr( - expr: Arc, - bounds_only: bool, -) -> DataFusionResult> { - expr.transform_up(|node| { - if node.is::() || (bounds_only && node.is::()) { - Ok(Transformed::yes(lit(true))) - } else { - Ok(Transformed::no(node)) +/// Keeps the top-level conjuncts of a predicate that cannot be shipped as it stands. +/// +/// Dropping an `AND` term can only widen a predicate, so the retained payload still never +/// drops a row the producer would keep. `retention` decides which conjuncts have to go. It +/// only widens as far as it has to: when the narrow retention leaves conjuncts that still do +/// not fit `max_payload_bytes`, the [`InListExpr`]-bearing ones are dropped as well, because +/// a static `IN` list is the node most likely to be the oversized one. +/// +/// The refusal keeps the two reasons apart instead of folding them into "no wire form": +/// nothing retained under [`ConjunctRetention::UnrepresentableLookup`] means the wire +/// really has no form for the predicate +/// ([`CommonQueryError::DynFilterUnsupported`]), while nothing retained under +/// [`ConjunctRetention::OverBudget`] (or a retained payload that still does not fit) is a +/// size refusal ([`CommonQueryError::DynFilterPayloadTooLarge`]). Transport never +/// substitutes `true` for either. +fn retain_membership_free_conjuncts( + expr: &Arc, + max_payload_bytes: usize, + retention: ConjunctRetention, +) -> DataFusionResult { + match encode_retained_conjuncts_to_bytes(expr, max_payload_bytes, retention) { + Ok(Some(bytes)) => Ok(DynFilterPayload::Datafusion(bytes)), + // Nothing could be retained. Which refusal that is depends on *why* the conjuncts + // had to go, and the two must not be mixed up: an over-budget predicate is + // representable, it only does not fit. + Ok(None) => Err(match retention { + ConjunctRetention::UnrepresentableLookup => DynFilterUnsupportedSnafu { + reason: "every top-level conjunct of the predicate holds a hash table \ + lookup without a UTF-8 build-key membership, so the wire has no \ + form for it", + } + .build() + .into(), + ConjunctRetention::OverBudget => DynFilterPayloadTooLargeSnafu { + payload_size_bytes: refused_payload_size(0, max_payload_bytes), + max_payload_bytes, + } + .build() + .into(), + }), + Err(CommonQueryError::DynFilterPayloadTooLarge { .. }) + if matches!(retention, ConjunctRetention::UnrepresentableLookup) => + { + retain_membership_free_conjuncts(expr, max_payload_bytes, ConjunctRetention::OverBudget) } - }) - .map(|transformed| transformed.data) + Err(error) => Err(error.into()), + } +} + +/// Encodes the top-level conjuncts of `expr` that `retention` allows to keep. +/// +/// [`split_conjunction`] hands out the top-level `AND` terms of the original +/// expression; a term is dropped as a whole when its subtree holds a node the retention +/// cannot ship (see [`ConjunctRetention`]). Membership nested inside `NOT`, `CASE` or `OR` +/// therefore drops that whole conjunct instead of being rewritten in place, so the payload +/// only ever loses top-level `AND` terms, which can only widen a predicate. +/// +/// The retained terms are encoded again under the same `max_payload_bytes`, so a caller +/// supplied budget still bounds the frame. Returns `Ok(None)` when no conjunct can be +/// retained; the caller decides which typed refusal that is from `retention`, because an +/// empty retention caused by an unrepresentable lookup is not the same thing as an empty +/// retention caused by the budget. +fn encode_retained_conjuncts_to_bytes( + expr: &Arc, + max_payload_bytes: usize, + retention: ConjunctRetention, +) -> Result>, CommonQueryError> { + let mut retained = Vec::new(); + for conjunct in split_conjunction(expr) { + if !retention.drops_conjunct(conjunct)? { + retained.push(Arc::clone(conjunct)); + } + } + if retained.is_empty() { + return Ok(None); + } + encode_bounded_physical_expr_to_bytes(&conjunction(retained), max_payload_bytes).map(Some) +} + +impl ConjunctRetention { + /// Whether the whole subtree of `expr` holds a node this retention cannot ship. + /// + /// This is a "whole conjunct" test on purpose: a conjunct that reaches such a node + /// anywhere is dropped by the retention instead of being rewritten around it. + fn drops_conjunct(self, expr: &Arc) -> DataFusionResult { + let mut found = false; + expr.apply(|node| { + let unshippable = match self { + Self::UnrepresentableLookup => node.is::(), + Self::OverBudget => node.is::() || node.is::(), + }; + if unshippable { + found = true; + Ok(TreeNodeRecursion::Stop) + } else { + Ok(TreeNodeRecursion::Continue) + } + })?; + Ok(found) + } +} + +/// Build-key list of one hash lookup, written as `probe_key IN (value, ...)`. +/// +/// The membership reuses the existing `PhysicalInListNode`, so no new wire variant +/// and no in-payload version tag are needed, and it is charged against the normal +/// payload budget. Only the build-key list itself is consulted here; the wire form +/// never depends on where the lookup sits in the predicate tree. +struct RemoteMembership { + /// Probe-side key expression, reused as the `InList` operand. + key: Arc, + /// Published build key values, tied to the lookup's build lease. + values: ArrayRef, +} + +impl RemoteMembership { + /// Key-list membership of `lookup`, or the reason it cannot be written. + /// + /// The count bound handed to DataFusion is derived from the byte budget (see + /// [`max_membership_values`]) instead of being a policy constant, and the byte bound + /// is the raw payload budget itself, which every build-key buffer has to fit before it + /// can be written as literals. Both are conservative early guards, not the exact + /// serialized frame length: the encoder still charges every literal against the budget + /// node by node. + /// + /// The accessor keeps the value-level limitations — it returns `None` for lookups + /// without a build lease (e.g. a test-only lookup), composite keys, non-`Utf8` keys + /// (integer/float/decimal/dictionary/unknown), and `NULL`-containing or empty build + /// keys — and [`utf8_list_literals`] re-checks everything it materializes. Those are + /// accessor and materialization limitations, not encoder policy. + /// + /// The accessor folds its shape and size checks into one `None`, so a key list that + /// exists but exceeds the bounds is told apart by asking again with the bounds lifted: + /// only a list that exists at all can be refused for its size, and a size refusal must + /// not be reported as a predicate without a wire form (it is + /// [`CommonQueryError::DynFilterPayloadTooLarge`], not + /// [`CommonQueryError::DynFilterUnsupported`]). + fn from_lookup( + lookup: &HashTableLookupExpr, + max_payload_bytes: usize, + ) -> Result { + match lookup + .build_key_membership(max_membership_values(max_payload_bytes), max_payload_bytes) + { + Some(membership) => Ok(Self { + key: Arc::clone(membership.key()), + values: Arc::clone(membership.values()), + }), + None => Err(match lookup.build_key_membership(usize::MAX, usize::MAX) { + Some(unbounded) => MembershipRefusal::OverBudget { + build_keys: unbounded.values().len(), + }, + None => MembershipRefusal::NoKeyList, + }), + } + } +} + +/// Why a lookup's build-key membership cannot be written as `probe_key IN (...)`. +/// +/// The two reasons are answered differently: [`Self::NoKeyList`] means the wire has no +/// form for the node, while [`Self::OverBudget`] means the membership is real but too +/// large for the payload budget, which the encoder reports as a size refusal. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum MembershipRefusal { + /// The lookup has no single-column `Utf8` build-key list at all: no build lease, + /// composite key, unsupported key type, or an empty / `NULL`-containing build side. + NoKeyList, + /// The build-key list exists but exceeds the caller's bounds. `build_keys` is how many + /// literals it would have written, measured from the unbounded accessor. + OverBudget { build_keys: usize }, +} + +/// Materializes the `IN` list literals for a build-key membership. +/// +/// This is the authoritative value check: the list is only built for a non-empty, +/// `NULL`-free, non-dictionary `Utf8` array of at most `max_values` entries. `max_values` +/// is checked *before* a [`Literal`] is created for every build key, so an over-large +/// build side is refused instead of being materialized and then measured. The caller has +/// already been through [`RemoteMembership::from_lookup`], so a refusal here can only be +/// the count bound and is reported as a size refusal, not as a missing wire form. +fn utf8_list_literals(values: &ArrayRef, max_values: usize) -> Option>> { + let values = values.as_any().downcast_ref::()?; + if values.is_empty() || values.null_count() != 0 || values.len() > max_values { + return None; + } + values + .iter() + .map(|value| { + value.map(|value| { + Arc::new(Literal::new(ScalarValue::Utf8(Some(value.to_owned())))) + as Arc + }) + }) + .collect() } pub(crate) fn decode_physical_expr_from_bytes( @@ -246,6 +727,78 @@ fn validate_payload_size( Ok(()) } +/// Asserts the predicate is reported as having no wire form instead of becoming `true`. +#[cfg(test)] +fn assert_unsupported(error: DataFusionError) { + assert_typed_dyn_filter_error(error, "DynFilterUnsupported", |error| { + matches!(error, CommonQueryError::DynFilterUnsupported { .. }) + }); +} + +/// Asserts the retained payload still exceeds the caller-supplied budget. +#[cfg(test)] +fn assert_too_large(error: DataFusionError) { + assert_typed_dyn_filter_error(error, "DynFilterPayloadTooLarge", |error| { + matches!(error, CommonQueryError::DynFilterPayloadTooLarge { .. }) + }); +} + +#[cfg(test)] +fn assert_typed_dyn_filter_error( + error: DataFusionError, + expected: &str, + matches_error: impl Fn(&CommonQueryError) -> bool, +) { + let DataFusionError::External(error) = error else { + panic!("expected external common query error, got: {error:?}"); + }; + let typed = error + .downcast_ref::() + .unwrap_or_else(|| panic!("expected external {expected}, got: {error:?}")); + assert!(matches_error(typed), "expected {expected}, got: {error:?}"); +} + +/// Whether `error` reports a dynamic filter predicate the wire cannot represent. +/// +/// Transport never rewrites a producer predicate to `true`, so a producer answers this +/// error by not shipping the producer predicate and keeping the query running. Callers +/// that keep a long-lived region-side predicate treat it as an invalidation trigger: the +/// stale predicate is replaced by an explicit `true` reset (see +/// `remote_dyn_filter_registry`), so a producer that later widens its filter cannot be +/// pruned away by it. +pub fn is_dyn_filter_unsupported(error: &DataFusionError) -> bool { + matches!( + error, + DataFusionError::External(source) + if source + .downcast_ref::() + .is_some_and(CommonQueryError::is_dyn_filter_unsupported) + ) +} + +/// Whether `error` reports a dynamic filter payload that exceeded `max_payload_bytes`. +/// +/// This is the other refusal [`DynFilterPayload::from_datafusion_expr`] reports, next to +/// [`is_dyn_filter_unsupported`]: the predicate exists and is representable, but even the +/// retained top-level conjuncts do not fit the budget. It is *not* a "no wire form" case +/// and must not be reported as one. Like the unsupported case it is answered by not +/// shipping the producer predicate (the query keeps running) and never by narrowing or +/// rewriting it; a caller that keeps a long-lived region predicate publishes the explicit +/// `true` reset instead, so a stale, narrower predicate cannot prune rows the producer +/// still keeps. +pub fn is_dyn_filter_payload_too_large(error: &DataFusionError) -> bool { + matches!( + error, + DataFusionError::External(source) + if source + .downcast_ref::() + .is_some_and(|error| matches!( + error, + CommonQueryError::DynFilterPayloadTooLarge { .. } + )) + ) +} + fn validate_supported_payload_expr(expr: &Arc) -> DataFusionResult<()> { expr.apply(|node| { if node.is::() { @@ -352,14 +905,51 @@ pub struct QueryRequest { pub plan: LogicalPlan, } +/// First node of type `T` anywhere in `expr`. +#[cfg(test)] +fn find_expr(expr: &Arc) -> Option> { + let mut found = None; + expr.apply(|node| { + if node.is::() { + found = Some(Arc::clone(node)); + Ok(TreeNodeRecursion::Stop) + } else { + Ok(TreeNodeRecursion::Continue) + } + }) + .unwrap(); + found +} + +/// Whether `expr` holds a node of type `T` anywhere. +#[cfg(test)] +fn has_expr(expr: &Arc) -> bool { + find_expr::(expr).is_some() +} + +/// Encodes `expr` at `max_payload_bytes` and decodes it against `schema`. This is the +/// round trip a receiver performs, so the tests never assert on the encoder alone. +#[cfg(test)] +fn decode( + expr: &Arc, + schema: &Arc, + max_payload_bytes: usize, +) -> Arc { + DynFilterPayload::from_datafusion_expr(expr, max_payload_bytes) + .unwrap() + .decode_datafusion_expr(&TaskContext::default(), schema, max_payload_bytes) + .unwrap() +} + #[cfg(test)] mod tests { use std::sync::Arc; use base64::Engine; use base64::prelude::BASE64_STANDARD; + use datafusion::arrow::array::{ArrayRef, Int32Array, StringArray}; use datafusion::arrow::datatypes::{DataType, Field, Schema}; - use datafusion::physical_expr::expressions::{BinaryExpr, Column, InListExpr, lit}; + use datafusion::physical_expr::expressions::{BinaryExpr, Column, InListExpr, NotExpr, lit}; use datafusion::physical_plan::expressions::col; use datafusion::physical_plan::joins::join_hash_map::JoinHashMapU32; use datafusion::physical_plan::joins::{HashTableLookupExpr, Map, SeededRandomState}; @@ -507,8 +1097,23 @@ mod tests { assert!(matches!(err, DataFusionError::Plan(_))); } + /// A hand-built lookup has no build lease, hence no key list: the wire cannot + /// represent it, so the encoder aborts unless a membership-free conjunct can be kept. + fn unrepresentable_lookup(key: &Arc) -> Arc { + Arc::new(HashTableLookupExpr::new( + vec![Arc::clone(key)], + SeededRandomState::with_seed(0), + Arc::new(Map::HashMap(Box::new(JoinHashMapU32::with_capacity(0)))), + "hash_lookup".to_string(), + None, + )) as Arc + } + #[test] - fn dyn_filter_payload_hash_lookup_fallback_preserves_bounds() { + fn dyn_filter_payload_unconvertible_lookup_keeps_integer_bounds() { + // `bounds AND lookup` where the lookup has no key list: only the + // membership-bearing conjunct is dropped, so the integer bounds still travel as a + // regular payload instead of an always-true filter or an error. let schema = Arc::new(Schema::new(vec![Field::new( "device_id", DataType::Int32, @@ -520,29 +1125,224 @@ mod tests { Operator::GtEq, lit(10i32), )) as Arc; - let lookup = Arc::new(HashTableLookupExpr::new( - vec![Arc::clone(&device_id)], - SeededRandomState::with_seed(0), - Arc::new(Map::HashMap(Box::new(JoinHashMapU32::with_capacity(0)))), - "hash_lookup".to_string(), + let upper_bound = Arc::new(BinaryExpr::new( + Arc::clone(&device_id), + Operator::LtEq, + lit(20i32), + )) as Arc; + let bounds = Arc::new(BinaryExpr::new(lower_bound, Operator::And, upper_bound)) + as Arc; + let expr = Arc::new(BinaryExpr::new( + Arc::clone(&bounds), + Operator::And, + unrepresentable_lookup(&device_id), )) as Arc; - let expr = - Arc::new(BinaryExpr::new(lower_bound, Operator::And, lookup)) as Arc; - let payload = DynFilterPayload::from_datafusion_expr(&expr, 1024).unwrap(); - let decoded = payload - .decode_datafusion_expr(&TaskContext::default(), &schema, 1024) - .unwrap(); + // The predicate itself has no wire form: the lookup has no key list. + assert!(matches!( + encode_bounded_physical_expr_to_bytes(&expr, 1024), + Err(CommonQueryError::DynFilterUnsupported { .. }) + )); - assert!(!contains_expr::(&decoded)); - let decoded_display = decoded.to_string(); - assert!(decoded_display.contains("device_id")); - assert!(decoded_display.contains(">=")); - assert!(!decoded_display.contains("hash_lookup")); + // Keeping the membership-free top-level conjuncts turns it into a normal payload. + let decoded = decode(&expr, &schema, 1024); + let display = decoded.to_string(); + assert!( + display.contains(">= 10"), + "lower bound must survive: {display}" + ); + assert!( + display.contains("<= 20"), + "upper bound must survive: {display}" + ); + assert!(!has_expr::(&decoded), "{display}"); + assert!(!has_expr::(&decoded), "{display}"); + // Both bounds are copied verbatim: no `AND` term was rewritten in place. + assert_eq!( + encode_physical_expr_to_bytes(&decoded).unwrap(), + encode_physical_expr_to_bytes(&bounds).unwrap() + ); } #[test] - fn dyn_filter_payload_oversized_inlist_falls_back_to_bounds() { + fn unrepresentable_lookup_drops_only_the_lookup_conjunct() { + // One unsupported lookup (no key list) between the bounds and a static `IN` list + // that is itself perfectly representable: only the lookup-bearing conjunct is + // dropped, so the list survives as a whole and the payload stays as narrow as the + // wire allows. + let schema = Arc::new(Schema::new(vec![Field::new( + "device_id", + DataType::Int32, + false, + )])); + let device_id = col("device_id", &schema).unwrap(); + let lower_bound = Arc::new(BinaryExpr::new( + Arc::clone(&device_id), + Operator::GtEq, + lit(10i32), + )) as Arc; + let upper_bound = Arc::new(BinaryExpr::new( + Arc::clone(&device_id), + Operator::LtEq, + lit(20i32), + )) as Arc; + let bounds = Arc::new(BinaryExpr::new( + Arc::clone(&lower_bound), + Operator::And, + Arc::clone(&upper_bound), + )) as Arc; + let in_list = Arc::new( + InListExpr::try_new( + Arc::clone(&device_id), + (10..20).map(lit).collect(), + false, + &schema, + ) + .unwrap(), + ) as Arc; + let expr = Arc::new(BinaryExpr::new( + Arc::new(BinaryExpr::new( + Arc::clone(&bounds), + Operator::And, + unrepresentable_lookup(&device_id), + )) as Arc, + Operator::And, + Arc::clone(&in_list), + )) as Arc; + + let decoded = decode(&expr, &schema, REMOTE_DYN_FILTER_PAYLOAD_MAX_BYTES); + let display = decoded.to_string(); + assert!(display.contains(">= 10"), "{display}"); + assert!(display.contains("<= 20"), "{display}"); + assert!(!has_expr::(&decoded), "{display}"); + // The static `IN` list is representable, so it is kept verbatim. + assert!(has_expr::(&decoded), "{display}"); + assert_eq!( + split_conjunction(&decoded).len(), + 3, + "the two bounds and the static `IN` list survive: {display}" + ); + // The retained conjuncts are the original terms verbatim: the list was not + // rewritten, truncated or moved. + let retained_in_list = find_expr::(&decoded).expect("static IN survives"); + let retained_in_list = retained_in_list.downcast_ref::().unwrap(); + assert!(!retained_in_list.negated()); + assert_eq!(retained_in_list.list().len(), 10); + let retained = conjunction(vec![ + Arc::clone(&lower_bound), + Arc::clone(&upper_bound), + in_list, + ]); + assert_eq!( + encode_physical_expr_to_bytes(&decoded).unwrap(), + encode_physical_expr_to_bytes(&retained).unwrap() + ); + } + + #[test] + fn over_budget_membership_drops_the_oversized_in_list_too() { + // The same shape under a budget that only fits the bounds: keeping the + // representative-but-large `IN` list is not enough, so the retention widens once + // more and drops the `InListExpr`-bearing conjuncts as well. + let schema = Arc::new(Schema::new(vec![Field::new( + "device_id", + DataType::Int32, + false, + )])); + let device_id = col("device_id", &schema).unwrap(); + let lower_bound = Arc::new(BinaryExpr::new( + Arc::clone(&device_id), + Operator::GtEq, + lit(10i32), + )) as Arc; + let upper_bound = Arc::new(BinaryExpr::new( + Arc::clone(&device_id), + Operator::LtEq, + lit(20i32), + )) as Arc; + let bounds = Arc::new(BinaryExpr::new( + Arc::clone(&lower_bound), + Operator::And, + Arc::clone(&upper_bound), + )) as Arc; + let in_list = Arc::new( + InListExpr::try_new( + Arc::clone(&device_id), + (10..20).map(lit).collect(), + false, + &schema, + ) + .unwrap(), + ) as Arc; + let expr = Arc::new(BinaryExpr::new( + Arc::new(BinaryExpr::new( + Arc::clone(&bounds), + Operator::And, + unrepresentable_lookup(&device_id), + )) as Arc, + Operator::And, + in_list, + )) as Arc; + + let budget = encode_physical_expr_to_bytes(&bounds).unwrap().len(); + assert!(encode_bounded_physical_expr_to_bytes(&expr, budget).is_err()); + + let decoded = decode(&expr, &schema, budget); + let display = decoded.to_string(); + assert!(display.contains(">= 10"), "{display}"); + assert!(display.contains("<= 20"), "{display}"); + assert!(!has_expr::(&decoded), "{display}"); + assert!(!has_expr::(&decoded), "{display}"); + assert_eq!( + encode_physical_expr_to_bytes(&decoded).unwrap(), + encode_physical_expr_to_bytes(&bounds).unwrap() + ); + } + + #[test] + fn dyn_filter_payload_negated_unconvertible_lookup_is_unsupported() { + // `NOT lookup` is a single top-level conjunct that carries the membership, so + // there is nothing safe to keep. Transport must not encode `NOT true` (or `true`) + // in its place: the predicate is reported as unsupported. + let schema = Arc::new(Schema::new(vec![Field::new( + "device_id", + DataType::Int32, + false, + )])); + let device_id = col("device_id", &schema).unwrap(); + let not_lookup = + Arc::new(NotExpr::new(unrepresentable_lookup(&device_id))) as Arc; + + assert_unsupported(DynFilterPayload::from_datafusion_expr(¬_lookup, 1024).unwrap_err()); + } + + #[test] + fn dyn_filter_payload_membership_under_or_is_unsupported() { + // `bound OR lookup` is a single top-level conjunct that carries the membership: + // rewriting it to `bound OR true` would be nothing but `true`, and keeping only + // the bound would *narrow* the predicate, so it is reported as unsupported. + let schema = Arc::new(Schema::new(vec![Field::new( + "device_id", + DataType::Int32, + false, + )])); + let device_id = col("device_id", &schema).unwrap(); + let lower_bound = Arc::new(BinaryExpr::new( + Arc::clone(&device_id), + Operator::GtEq, + lit(10i32), + )) as Arc; + let expr = Arc::new(BinaryExpr::new( + lower_bound, + Operator::Or, + unrepresentable_lookup(&device_id), + )) as Arc; + + assert_unsupported(DynFilterPayload::from_datafusion_expr(&expr, 1024).unwrap_err()); + } + + #[test] + fn dyn_filter_payload_over_budget_keeps_bounds() { let schema = Arc::new(Schema::new(vec![Field::new( "device_id", DataType::Int32, @@ -559,9 +1359,12 @@ mod tests { Operator::LtEq, lit(8255i32), )) as Arc; - let bounds = Arc::new(BinaryExpr::new(lower_bound, Operator::And, upper_bound)) - as Arc; - let in_list = Arc::new( + let bounds = Arc::new(BinaryExpr::new( + Arc::clone(&lower_bound), + Operator::And, + Arc::clone(&upper_bound), + )) as Arc; + let oversized_in = Arc::new( InListExpr::try_new( Arc::clone(&device_id), (8192..8256).map(lit).collect(), @@ -570,23 +1373,33 @@ mod tests { ) .unwrap(), ) as Arc; - let expr = Arc::new(BinaryExpr::new(Arc::clone(&bounds), Operator::And, in_list)) - as Arc; - let bounds_only = portable_remote_dyn_filter_expr(Arc::clone(&expr), true).unwrap(); - let bounds_only_size = encode_physical_expr_to_bytes(&bounds_only).unwrap().len(); - let full_size = encode_physical_expr_to_bytes(&expr).unwrap().len(); - assert!(full_size > bounds_only_size); + let expr = Arc::new(BinaryExpr::new( + Arc::clone(&bounds), + Operator::And, + oversized_in, + )) as Arc; - let payload = DynFilterPayload::from_datafusion_expr(&expr, bounds_only_size).unwrap(); - let decoded = payload - .decode_datafusion_expr(&TaskContext::default(), &schema, bounds_only_size) - .unwrap(); + // A caller-supplied limit that fits the bounds but not the oversized `IN` list: + // the membership conjunct is dropped and the bounds are encoded under the same + // budget. + let bounds_size = encode_physical_expr_to_bytes(&bounds).unwrap().len(); + assert!(encode_bounded_physical_expr_to_bytes(&expr, bounds_size).is_err()); - assert!(!contains_expr::(&decoded)); - let decoded_display = decoded.to_string(); - assert!(decoded_display.contains("device_id")); - assert!(decoded_display.contains(">=")); - assert!(decoded_display.contains("<=")); + let decoded = decode(&expr, &schema, bounds_size); + let display = decoded.to_string(); + assert!(display.contains(">= 8192"), "{display}"); + assert!(display.contains("<= 8255"), "{display}"); + assert!(!has_expr::(&decoded), "{display}"); + assert_eq!( + encode_physical_expr_to_bytes(&decoded).unwrap(), + encode_physical_expr_to_bytes(&bounds).unwrap() + ); + + // A budget that does not even fit the retained bounds is reported as too large: + // nothing that cannot be shipped may be replaced with `true`. + let true_size = encode_physical_expr_to_bytes(&lit(true)).unwrap().len(); + assert!(true_size < bounds_size); + assert_too_large(DynFilterPayload::from_datafusion_expr(&expr, true_size).unwrap_err()); } #[test] @@ -660,17 +1473,1069 @@ mod tests { )); } - fn contains_expr(expr: &Arc) -> bool { - let mut found = false; + #[test] + fn membership_value_bound_really_bounds_what_the_byte_budget_holds() { + // The count bound has to be *real*, not a restatement of its own formula: a + // payload of `B` bytes can never hold more than `B / MIN_ENCODED_LITERAL_BYTES` + // list literals. Prove it by encoding one literal more than the bound and checking + // that the resulting frame really exceeds `B`. + let budget = 512; + let bound = max_membership_values(budget); + assert!(bound > 1, "the bound must leave room for a real list"); + let schema = Schema::new(vec![Field::new("host", DataType::Utf8, true)]); + let minimal_in_list = |values: usize| { + Arc::new( + InListExpr::try_new( + Arc::new(Column::new("host", 0)), + (0..values).map(|_| lit("")).collect(), + false, + &schema, + ) + .unwrap(), + ) as Arc + }; + + let over_bound = encode_physical_expr_to_bytes(&minimal_in_list(bound + 1)).unwrap(); + assert!( + over_bound.len() > budget, + "{} literals must not fit a {budget}-byte budget, but the frame is {} bytes", + bound + 1, + over_bound.len() + ); + // The same payload is refused by the bounded encoder, so the derived bound and the + // encoder agree on where the budget ends. + assert!(matches!( + encode_bounded_physical_expr_to_bytes(&minimal_in_list(bound + 1), budget), + Err(CommonQueryError::DynFilterPayloadTooLarge { .. }) + )); + // The floor the bound is derived from must hold for the cheapest literal there is. + let cheapest = encode_physical_expr_to_bytes(&lit("")).unwrap().len(); + assert!( + cheapest >= MIN_ENCODED_LITERAL_BYTES, + "floor must hold for the cheapest literal, got {cheapest} bytes" + ); + } + + #[test] + fn utf8_list_literals_is_the_authoritative_value_check() { + let values: ArrayRef = Arc::new(StringArray::from(vec!["a", "b", "c"])); + assert!(utf8_list_literals(&values, 3).is_some()); + // The count is bounded before a single `Literal` is built. + assert!(utf8_list_literals(&values, 2).is_none()); + assert!(utf8_list_literals(&values, 0).is_none()); + // NULL-containing, empty and non-`Utf8` arrays are refused here, not only by the + // `HashTableLookupExpr` accessor. + let with_null: ArrayRef = Arc::new(StringArray::from(vec![Some("a"), None])); + assert!(utf8_list_literals(&with_null, 8).is_none()); + let empty: ArrayRef = Arc::new(StringArray::from(Vec::<&str>::new())); + assert!(utf8_list_literals(&empty, 8).is_none()); + let not_utf8: ArrayRef = Arc::new(Int32Array::from(vec![1, 2])); + assert!(utf8_list_literals(¬_utf8, 8).is_none()); + } +} + +/// Remote dynamic filter membership recovered from *real* DataFusion build leases. +/// +/// The tests above build `HashTableLookupExpr` by hand, which always has +/// `build_lease = None`. These tests run an actual `HashJoinExec` so DataFusion +/// publishes lookups backed by a real build lease, which is the only way to prove that +/// the key list (and the membership-free conjunct retention) actually works. +/// +/// Most remote predicates are checked twice: structurally (what the payload contains) +/// and by **evaluating** the producer predicate and the decoded predicate on the same +/// `NULL`-free rows. Evaluation pins the contract that applies here: the converted +/// membership is the build key list, so on `NULL`-free keys only, the decoded predicate +/// keeps exactly the rows the producer kept. It is a pruning hint, not a universal +/// equivalence — see `not_lookup_becomes_not_in` for the `NULL` caveat. +#[cfg(test)] +mod remote_membership_tests { + use std::collections::BTreeMap; + + use datafusion::arrow::array::{ + ArrayRef, BooleanArray, Float64Array, Int32Array, StringArray, StringDictionaryBuilder, + }; + use datafusion::arrow::datatypes::{DataType, Field, Int32Type, Schema}; + use datafusion::arrow::record_batch::RecordBatch; + use datafusion::physical_expr::expressions::{ + BinaryExpr, CaseExpr, Column, InListExpr, IsNullExpr, Literal, NotExpr, lit, + }; + use datafusion::physical_plan::PhysicalExpr; + use datafusion::physical_plan::joins::{HashExpr, HashTableLookupExpr}; + use datafusion_expr::Operator; + + use super::remote_membership_test_support::{ + RealDynFilter, key, one_column_schema, partitions, run_real_hash_join, utf8, utf8_join, + }; + use super::*; + + fn in_lists(expr: &Arc) -> Vec> { + let mut found = Vec::new(); expr.apply(|node| { - if node.is::() { - found = true; + if node.is::() { + found.push(Arc::clone(node)); + } + Ok(TreeNodeRecursion::Continue) + }) + .unwrap(); + found + } + + fn in_list_values(expr: &Arc) -> Vec { + let in_list = expr.downcast_ref::().unwrap(); + assert!(!in_list.negated()); + in_list + .list() + .iter() + .map(|literal| { + literal + .downcast_ref::() + .unwrap() + .value() + .to_string() + .trim_matches('\'') + .to_string() + }) + .collect() + } + + fn assert_has_bounds(expr: &Arc) { + let display = expr.to_string(); + assert!(display.contains(">="), "missing lower bound: {display}"); + assert!(display.contains("<="), "missing upper bound: {display}"); + } + + fn utf8_batch(schema: &Arc, values: &[&str]) -> RecordBatch { + RecordBatch::try_new(Arc::clone(schema), vec![utf8(values)]).unwrap() + } + + fn selected(expr: &Arc, batch: &RecordBatch) -> Vec { + let array = expr + .evaluate(batch) + .unwrap() + .into_array(batch.num_rows()) + .unwrap(); + let booleans = array.as_any().downcast_ref::().unwrap(); + (0..batch.num_rows()) + .map(|index| booleans.value(index)) + .collect() + } + + /// Widening check: the decoded predicate keeps every row the producer kept. + /// + /// Only used on `NULL`-free rows, where the build-key membership is exact for the + /// converted node. + fn assert_fail_open( + original: &Arc, + decoded: &Arc, + batch: &RecordBatch, + ) -> (Vec, Vec) { + let original_selected = selected(original, batch); + let decoded_selected = selected(decoded, batch); + for (row, (kept, kept_after)) in original_selected + .iter() + .zip(decoded_selected.iter()) + .enumerate() + { + assert!( + kept_after >= kept, + "decoded predicate dropped row {row}: producer={kept} decoded={kept_after} \ + (decoded predicate: {decoded})" + ); + } + (original_selected, decoded_selected) + } + + /// Branch chosen by the CASE routing expression for every row. + fn routed_branch(case: &CaseExpr, batch: &RecordBatch) -> Vec { + let routing = case.expr().expect("hash routing operand"); + let array = routing + .evaluate(batch) + .unwrap() + .into_array(batch.num_rows()) + .unwrap(); + let branches = array + .as_any() + .downcast_ref::() + .unwrap(); + (0..batch.num_rows()) + .map(|index| branches.value(index)) + .collect() + } + + fn hash_seed(expr: &Arc) -> u64 { + let mut seed = None; + expr.apply(|node| { + if let Some(hash) = node.downcast_ref::() { + seed = Some(hash.seed()); Ok(TreeNodeRecursion::Stop) } else { Ok(TreeNodeRecursion::Continue) } }) .unwrap(); - found + seed.expect("hash routing expression") + } + + /// `trace_id` values used to evaluate recovered filters. + fn evaluation_batch(schema: &Arc, values: &[String]) -> RecordBatch { + let borrowed = values.iter().map(String::as_str).collect::>(); + utf8_batch(schema, &borrowed) + } + + /// UTF-8 batch that can contain SQL NULLs, for wrapper semantics. + fn nullable_evaluation_batch(schema: &Arc, values: &[Option]) -> RecordBatch { + let array = StringArray::from(values.to_vec()); + RecordBatch::try_new(Arc::clone(schema), vec![Arc::new(array) as ArrayRef]).unwrap() + } + + #[tokio::test] + async fn membership_round_trips_real_utf8_build_lease() { + let schema = one_column_schema("trace_id", DataType::Utf8); + let (build, probe, values) = utf8_join(1); + let trace_id = key("trace_id", 0); + let filter = run_real_hash_join( + 1, + Arc::clone(&schema), + Arc::clone(&schema), + build, + probe, + vec![(Arc::clone(&trace_id), Arc::clone(&trace_id))], + ) + .await; + + // The producer predicate really holds a runtime-only lookup... + assert!(has_expr::(&filter.expr)); + + // ...and it is serialized as exact build membership, not as `true`. + let decoded = decode( + &filter.expr, + &filter.probe_schema, + REMOTE_DYN_FILTER_PAYLOAD_MAX_BYTES, + ); + assert!(!has_expr::(&decoded)); + let lists = in_lists(&decoded); + assert_eq!(lists.len(), 1, "expected one recovered InList: {decoded}"); + assert_eq!(in_list_values(&lists[0]), values); + assert_has_bounds(&decoded); + + // Members are selected, non-members are not, nothing else changes. + let mut rows = values.clone(); + rows.push("miss-not-a-member".to_string()); + let batch = evaluation_batch(&schema, &rows); + let (original_selected, decoded_selected) = + assert_fail_open(&filter.expr, &decoded, &batch); + for row in 0..values.len() { + assert!(original_selected[row], "member row {row} must be selected"); + assert!(decoded_selected[row], "member row {row} must stay selected"); + } + assert!( + !decoded_selected[values.len()], + "non-member must not be selected" + ); + } + + #[tokio::test] + async fn membership_preserves_three_branch_case_structure() { + let schema = one_column_schema("trace_id", DataType::Utf8); + let (build, probe, values) = utf8_join(3); + let trace_id = key("trace_id", 0); + let filter = run_real_hash_join( + 3, + Arc::clone(&schema), + Arc::clone(&schema), + build, + probe, + vec![(Arc::clone(&trace_id), Arc::clone(&trace_id))], + ) + .await; + + // Three hash-routed partitions produce a three-branch CASE. + let original_case = filter + .expr + .downcast_ref::() + .expect("real three-branch CASE"); + assert_eq!(original_case.when_then_expr().len(), 3); + + let decoded = decode( + &filter.expr, + &filter.probe_schema, + REMOTE_DYN_FILTER_PAYLOAD_MAX_BYTES, + ); + let case = decoded.downcast_ref::().expect("CASE preserved"); + assert_eq!(case.when_then_expr().len(), 3); + assert!(case.else_expr().is_some()); + + // Routing is untouched: same operand expression and same `HashExpr` seed, so + // the receiver selects the same branch for every row. + assert_eq!( + original_case.expr().unwrap().to_string(), + case.expr().unwrap().to_string() + ); + assert_eq!( + hash_seed(original_case.expr().unwrap()), + hash_seed(case.expr().unwrap()) + ); + + // Branch-specific membership: the WHEN literal names the branch, so the values + // recovered for each branch can be checked individually. + let mut branch_values: BTreeMap> = BTreeMap::new(); + for (when, then) in case.when_then_expr() { + let branch = match when.downcast_ref::().unwrap().value() { + ScalarValue::UInt64(Some(branch)) => *branch, + other => panic!("unexpected CASE routing literal: {other:?}"), + }; + let lists = in_lists(then); + assert_eq!(lists.len(), 1, "each branch keeps its membership: {then}"); + let mut branch_list = in_list_values(&lists[0]); + branch_list.sort(); + assert!( + branch_values.insert(branch, branch_list).is_none(), + "branch {branch} appears twice" + ); + assert_has_bounds(then); + } + assert_eq!(branch_values.len(), 3, "three distinct branches"); + + // Every build key is recovered exactly once, in its own branch. + let mut recovered = branch_values + .values() + .flatten() + .cloned() + .collect::>(); + recovered.sort(); + assert_eq!(recovered, values); + + // Evaluation proves branch-specific routing: a row is selected iff its key is in + // the membership of the branch the routing sends it to. + let mut rows = values.clone(); + rows.extend((0..4).map(|i| format!("miss-{i:02}"))); + let batch = evaluation_batch(&schema, &rows); + let (original_selected, decoded_selected) = + assert_fail_open(&filter.expr, &decoded, &batch); + let branches = routed_branch(case, &batch); + for (row, value) in rows.iter().enumerate() { + let branch = branches[row]; + let expected = branch_values + .get(&branch) + .is_some_and(|members| members.binary_search(value).is_ok()); + assert_eq!( + decoded_selected[row], expected, + "row {value} routed to branch {branch} must be selected iff it is a \ + member of that branch's list" + ); + // Build members must keep their decision; misses only ever widen. + if expected { + assert!( + original_selected[row], + "producer must select its own build member {value}" + ); + assert!(decoded_selected[row]); + } + } + assert!( + decoded_selected + .iter() + .filter(|selected| **selected) + .count() + >= values.len(), + "every build member must still be selected" + ); + } + + /// Runs a real one-partition `Utf8` hash join over `key_count` distinct keys. + async fn real_join_with_keys(key_count: usize) -> (Arc, RealDynFilter, Vec) { + let schema = one_column_schema("trace_id", DataType::Utf8); + let trace_id = key("trace_id", 0); + let values = (0..key_count) + .map(|i| format!("trace-{i:04}")) + .collect::>(); + let borrowed = values.iter().map(String::as_str).collect::>(); + let build = partitions(&schema, vec![vec![utf8(&borrowed)]]); + let probe = partitions(&schema, vec![vec![utf8(&borrowed)]]); + let filter = run_real_hash_join( + 1, + Arc::clone(&schema), + Arc::clone(&schema), + build, + probe, + vec![(Arc::clone(&trace_id), Arc::clone(&trace_id))], + ) + .await; + (schema, filter, values) + } + + #[tokio::test] + async fn bounds_survive_unrepresentable_integer_lookup() { + // Integer keys are not a single-column `Utf8` membership, so this real lookup has + // no wire form. Retention keeps the top-level bounds and drops the lookup + // conjunct, so the decoded predicate only ever gets wider. + let schema = one_column_schema("k", DataType::Int32); + let k = key("k", 0); + let filter = run_real_hash_join( + 1, + Arc::clone(&schema), + Arc::clone(&schema), + partitions( + &schema, + vec![vec![Arc::new(Int32Array::from(vec![1, 2, 3])) as ArrayRef]], + ), + partitions( + &schema, + vec![vec![ + Arc::new(Int32Array::from(vec![1, 2, 3, 4, 5, 10])) as ArrayRef + ]], + ), + vec![(Arc::clone(&k), Arc::clone(&k))], + ) + .await; + let lookup = find_expr::(&filter.expr).expect("real lookup"); + + let lower_bound = Arc::new(BinaryExpr::new(Arc::clone(&k), Operator::GtEq, lit(2i32))) + as Arc; + let upper_bound = Arc::new(BinaryExpr::new(Arc::clone(&k), Operator::LtEq, lit(4i32))) + as Arc; + let bounds = Arc::new(BinaryExpr::new(lower_bound, Operator::And, upper_bound)) + as Arc; + let expr = Arc::new(BinaryExpr::new(Arc::clone(&bounds), Operator::And, lookup)) + as Arc; + + let decoded = decode( + &expr, + &filter.probe_schema, + REMOTE_DYN_FILTER_PAYLOAD_MAX_BYTES, + ); + let display = decoded.to_string(); + assert!( + display.contains(">= 2"), + "lower bound must survive: {display}" + ); + assert!( + display.contains("<= 4"), + "upper bound must survive: {display}" + ); + assert!(!has_expr::(&decoded), "{display}"); + assert!(!has_expr::(&decoded), "{display}"); + + // The producer and the decoded predicate agree on every row the producer kept and + // only diverge on the non-member `4`, where the retained payload widens. + let batch = RecordBatch::try_new( + Arc::clone(&schema), + vec![Arc::new(Int32Array::from(vec![1, 2, 3, 4, 5, 10])) as ArrayRef], + ) + .unwrap(); + let (original_selected, decoded_selected) = assert_fail_open(&expr, &decoded, &batch); + assert_eq!( + original_selected, + vec![false, true, true, false, false, false] + ); + assert_eq!( + decoded_selected, + vec![false, true, true, true, false, false] + ); + } + + #[tokio::test] + async fn small_budget_keeps_bounds_and_drops_real_membership() { + // A real `Utf8` lookup next to integer bounds, shipped under a caller-supplied + // limit that fits only the bounds: retention drops the membership conjunct and + // still sends the bounds, which can only widen the producer predicate. + let probe_schema = Arc::new(Schema::new(vec![ + Field::new("trace_id", DataType::Utf8, true), + Field::new("k", DataType::Int32, true), + ])); + let build_schema = one_column_schema("trace_id", DataType::Utf8); + let long = "t".repeat(256); + let values = (0..24) + .map(|i| format!("{long}-{i:02}")) + .collect::>(); + let borrowed = values.iter().map(String::as_str).collect::>(); + let build_key = key("trace_id", 0); + let probe_key = key("trace_id", 0); + let filter = run_real_hash_join( + 1, + Arc::clone(&build_schema), + Arc::clone(&probe_schema), + partitions(&build_schema, vec![vec![utf8(&borrowed)]]), + partitions( + &probe_schema, + vec![vec![ + utf8(&borrowed), + Arc::new(Int32Array::from(vec![0i32; values.len()])) as ArrayRef, + ]], + ), + vec![(Arc::clone(&build_key), Arc::clone(&probe_key))], + ) + .await; + let lookup = find_expr::(&filter.expr).expect("real lookup"); + + let k = key("k", 1); + let lower_bound = Arc::new(BinaryExpr::new(Arc::clone(&k), Operator::GtEq, lit(2i32))) + as Arc; + let upper_bound = Arc::new(BinaryExpr::new(Arc::clone(&k), Operator::LtEq, lit(5i32))) + as Arc; + let bounds = Arc::new(BinaryExpr::new(lower_bound, Operator::And, upper_bound)) + as Arc; + let expr = Arc::new(BinaryExpr::new(Arc::clone(&bounds), Operator::And, lookup)) + as Arc; + + // Only the bounds fit: the membership of 24 long keys is far beyond this budget. + let bounds_size = encode_physical_expr_to_bytes(&bounds).unwrap().len(); + let decoded = decode(&expr, &filter.probe_schema, bounds_size); + let display = decoded.to_string(); + assert!( + display.contains(">= 2"), + "lower bound must survive: {display}" + ); + assert!( + display.contains("<= 5"), + "upper bound must survive: {display}" + ); + assert!(!has_expr::(&decoded), "{display}"); + assert!(!has_expr::(&decoded), "{display}"); + + // Evaluation: a member inside the bounds is kept by both, a member outside the + // bounds is dropped by both, and only the non-member is widened. + let trace_ids = vec![ + values[0].as_str(), + values[1].as_str(), + "miss-not-a-member", + values[2].as_str(), + ]; + let batch = RecordBatch::try_new( + Arc::clone(&probe_schema), + vec![ + utf8(&trace_ids), + Arc::new(Int32Array::from(vec![2i32, 6, 3, 5])) as ArrayRef, + ], + ) + .unwrap(); + let (original_selected, decoded_selected) = assert_fail_open(&expr, &decoded, &batch); + assert_eq!(original_selected, vec![true, false, false, true]); + assert_eq!(decoded_selected, vec![true, false, true, true]); + } + + #[tokio::test] + async fn real_642_key_hash_join_becomes_exact_642_literal_in() { + let (schema, filter, values) = real_join_with_keys(642).await; + assert_eq!(values.len(), 642); + // The producer predicate really holds a runtime-only lookup... + assert!(has_expr::(&filter.expr)); + + // ...and it is written as one literal per build key within the payload budget. + let decoded = decode( + &filter.expr, + &filter.probe_schema, + REMOTE_DYN_FILTER_PAYLOAD_MAX_BYTES, + ); + assert!(!has_expr::(&decoded)); + let lists = in_lists(&decoded); + assert_eq!(lists.len(), 1, "expected one converted InList: {decoded}"); + let mut recovered = in_list_values(&lists[0]); + assert_eq!(recovered.len(), 642, "one literal per build key"); + recovered.sort(); + assert_eq!(recovered, values); + + // The membership selects exactly the build keys. + let mut rows = values.clone(); + rows.push("miss-not-a-member".to_string()); + let batch = evaluation_batch(&schema, &rows); + let (original_selected, decoded_selected) = + assert_fail_open(&filter.expr, &decoded, &batch); + for row in 0..values.len() { + assert!( + original_selected[row], + "build key row {row} must be selected" + ); + assert!( + decoded_selected[row], + "build key row {row} must stay selected" + ); + } + assert!( + !decoded_selected[values.len()], + "non-member must not be selected" + ); + } + + #[tokio::test] + async fn large_build_side_is_refused_before_materializing_literals() { + // A build side far larger than a small budget can hold must be refused by the + // derived count bound *before* the encoder creates one `Literal` per build key. + let (_, filter, values) = real_join_with_keys(1024).await; + let lookup = find_expr::(&filter.expr).expect("real lookup"); + let lookup = lookup.downcast_ref::().unwrap(); + + // DataFusion itself would hand out every build key ... + let unbounded = lookup + .build_key_membership(usize::MAX, usize::MAX) + .expect("the build lease holds the keys"); + assert_eq!(unbounded.values().len(), values.len()); + + // ... but a budget that only fits the producer's own bounds leaves room for a few + // literals, so the count bound derived from it refuses the list outright. + let bounds = conjunction( + split_conjunction(&filter.expr) + .into_iter() + .filter(|conjunct| !has_expr::(conjunct)) + .cloned() + .collect::>(), + ); + let budget = encode_physical_expr_to_bytes(&bounds).unwrap().len(); + assert!( + max_membership_values(budget) < values.len(), + "the derived count bound must stay below the build side size" + ); + // The refusal is reported as a *size* refusal, not as a predicate without a wire + // form: the key list exists, it just does not fit this budget. + assert!( + matches!( + RemoteMembership::from_lookup(lookup, budget), + Err(MembershipRefusal::OverBudget { build_keys }) if build_keys == values.len() + ), + "an over-large build key list must be refused as over budget" + ); + + // Nothing of the 1024-key membership reaches the payload. + let decoded = decode(&filter.expr, &filter.probe_schema, budget); + assert!(!has_expr::(&decoded), "{decoded}"); + assert!(!has_expr::(&decoded), "{decoded}"); + assert_has_bounds(&decoded); + } + + #[tokio::test] + async fn lookup_or_key_is_null_preserves_wrapper_and_becomes_in_list() { + // The `key IS NULL OR ` wrapper of a null-aware join is an ordinary + // node: it stays in the payload and only the lookup inside it is converted. + let (schema, filter, values) = real_join_with_keys(8).await; + let lookup = find_expr::(&filter.expr).expect("real lookup"); + let trace_id = key("trace_id", 0); + let wrapped = Arc::new(BinaryExpr::new( + Arc::clone(&lookup), + Operator::Or, + Arc::new(IsNullExpr::new(Arc::clone(&trace_id))), + )) as Arc; + + let decoded = decode( + &wrapped, + &filter.probe_schema, + REMOTE_DYN_FILTER_PAYLOAD_MAX_BYTES, + ); + let display = decoded.to_string(); + assert!( + display.contains("IS NULL"), + "IS NULL wrapper must survive: {display}" + ); + assert!(!display.contains("hash_lookup"), "{display}"); + let lists = in_lists(&decoded); + assert_eq!(lists.len(), 1, "expected one converted InList: {display}"); + assert_eq!(in_list_values(&lists[0]), values); + + let mut rows = values + .iter() + .map(|value| Some(value.clone())) + .collect::>(); + rows.push(Some("miss-not-a-member".to_string())); + rows.push(None); + let batch = nullable_evaluation_batch(&schema, &rows); + let (original_selected, decoded_selected) = assert_fail_open(&wrapped, &decoded, &batch); + for row in 0..values.len() { + assert!(original_selected[row]); + assert!(decoded_selected[row]); + } + assert!( + original_selected[rows.len() - 1], + "producer `lookup OR key IS NULL` keeps a NULL probe" + ); + assert!( + decoded_selected[rows.len() - 1], + "decoded `IN ... OR key IS NULL` must also keep a NULL probe" + ); + } + + #[tokio::test] + async fn null_build_keys_keep_only_the_safe_bounds() { + // The key-list accessor requires `NULL`-free build keys, so a build side with a + // `NULL` key has no membership. This producer shape is `bounds AND lookup`: the + // bounds DataFusion derived from the non-`NULL` keys are retained, and the lookup + // is dropped instead of the predicate being replaced with `true`. + let schema = one_column_schema("trace_id", DataType::Utf8); + let trace_id = key("trace_id", 0); + let build_values: ArrayRef = Arc::new(StringArray::from(vec![ + Some("trace-a"), + None, + Some("trace-b"), + ])); + let filter = run_real_hash_join( + 1, + Arc::clone(&schema), + Arc::clone(&schema), + partitions(&schema, vec![vec![build_values]]), + partitions(&schema, vec![vec![utf8(&["trace-a", "trace-b", "miss"])]]), + vec![(Arc::clone(&trace_id), Arc::clone(&trace_id))], + ) + .await; + assert!(has_expr::(&filter.expr)); + let producer = filter.expr.to_string(); + assert!(producer.contains(">= trace-a"), "{producer}"); + assert!(producer.contains("<= trace-b"), "{producer}"); + + let decoded = decode( + &filter.expr, + &filter.probe_schema, + REMOTE_DYN_FILTER_PAYLOAD_MAX_BYTES, + ); + let display = decoded.to_string(); + assert!(!has_expr::(&decoded), "{display}"); + assert!(!has_expr::(&decoded), "{display}"); + assert!(display.contains(">= trace-a"), "{display}"); + assert!(display.contains("<= trace-b"), "{display}"); + assert_ne!(display, "true", "transport must not widen to `true`"); + + // The retained conjuncts are the producer bounds verbatim. + let bounds = split_conjunction(&filter.expr) + .into_iter() + .filter(|conjunct| !has_expr::(conjunct)) + .cloned() + .collect::>(); + assert_eq!( + encode_physical_expr_to_bytes(&decoded).unwrap(), + encode_physical_expr_to_bytes(&conjunction(bounds)).unwrap() + ); + + // Widening only: every build key row the producer kept is still kept. + let rows = ["trace-a", "trace-b", "miss"] + .map(ToString::to_string) + .to_vec(); + let batch = evaluation_batch(&schema, &rows); + let (original_selected, decoded_selected) = + assert_fail_open(&filter.expr, &decoded, &batch); + assert_eq!(original_selected, vec![true, true, false]); + assert!(decoded_selected[0], "build key row must stay selected"); + assert!(decoded_selected[1], "build key row must stay selected"); + } + + /// `NOT lookup` becomes `NOT (key IN (...))`. + /// + /// This narrow contract is about **positive pruning**: the membership is the build + /// key list of the join, so converting the node in place structurally preserves the + /// negation instead of substituting `true` into it. It is *not* a claim of + /// universal equivalence with the join: `IN`/`NOT IN` are `NULL`-propagating while + /// a hash lookup can be definite on a `NULL` probe key, so a `NULL` key that the + /// lookup keeps can still be dropped by `NOT IN`. The rows below are non-`NULL`, + /// which is the shape the hint is meant for. + #[tokio::test] + async fn not_lookup_becomes_not_in() { + let (schema, filter, values) = real_join_with_keys(8).await; + let lookup = find_expr::(&filter.expr).expect("real lookup"); + let not_lookup = Arc::new(NotExpr::new(Arc::clone(&lookup))) as Arc; + + let decoded = decode( + ¬_lookup, + &filter.probe_schema, + REMOTE_DYN_FILTER_PAYLOAD_MAX_BYTES, + ); + let display = decoded.to_string(); + assert!( + display.starts_with("NOT "), + "NOT must survive the wire: {display}" + ); + let lists = in_lists(&decoded); + assert_eq!(lists.len(), 1, "expected one converted InList: {display}"); + assert_eq!(in_list_values(&lists[0]), values); + + let mut rows = values.clone(); + rows.push("miss-not-a-member".to_string()); + let batch = evaluation_batch(&schema, &rows); + let (original_selected, decoded_selected) = assert_fail_open(¬_lookup, &decoded, &batch); + assert!(original_selected[..values.len()].iter().all(|kept| !*kept)); + assert!( + original_selected[values.len()], + "producer `NOT lookup` keeps the non-member" + ); + assert!(decoded_selected[..values.len()].iter().all(|kept| !*kept)); + assert!( + decoded_selected[values.len()], + "decoded `NOT IN` keeps the non-member" + ); + } + + #[tokio::test] + async fn unsupported_float_composite_and_dictionary_keys_keep_only_safe_conjuncts() { + // Float64 keys: the key-list accessor only exposes a single `Utf8` column. + let float_schema = one_column_schema("k", DataType::Float64); + let float_on = key("k", 0); + let float_filter = run_real_hash_join( + 2, + Arc::clone(&float_schema), + Arc::clone(&float_schema), + partitions( + &float_schema, + vec![ + vec![Arc::new(Float64Array::from(vec![0.0, -0.0])) as ArrayRef], + vec![Arc::new(Float64Array::from(vec![1.5])) as ArrayRef], + ], + ), + partitions( + &float_schema, + vec![ + vec![Arc::new(Float64Array::from(vec![0.0, 2.5])) as ArrayRef], + vec![Arc::new(Float64Array::from(vec![1.5])) as ArrayRef], + ], + ), + vec![(Arc::clone(&float_on), Arc::clone(&float_on))], + ) + .await; + assert!(has_expr::(&float_filter.expr)); + // The partitioned producer publishes a per-partition `CASE`, so the only + // top-level conjunct carries the membership and there is nothing safe to keep: + // the predicate is reported as unsupported instead of becoming `true`. + assert_unsupported( + DynFilterPayload::from_datafusion_expr( + &float_filter.expr, + REMOTE_DYN_FILTER_PAYLOAD_MAX_BYTES, + ) + .unwrap_err(), + ); + + // Composite (two-column) keys: not a single-column membership. Both columns + // take part in the hash partitioning, exactly like a real two-key join. + let composite_schema = Arc::new(Schema::new(vec![ + Field::new("trace_id", DataType::Utf8, true), + Field::new("host", DataType::Utf8, true), + ])); + let composite_on = vec![ + (key("trace_id", 0), key("trace_id", 0)), + (key("host", 1), key("host", 1)), + ]; + let composite_filter = run_real_hash_join( + 2, + Arc::clone(&composite_schema), + Arc::clone(&composite_schema), + partitions( + &composite_schema, + vec![ + vec![utf8(&["trace-0", "trace-1"]), utf8(&["host-a", "host-a"])], + vec![utf8(&["trace-2"]), utf8(&["host-b"])], + ], + ), + partitions( + &composite_schema, + vec![ + vec![utf8(&["trace-0", "trace-9"]), utf8(&["host-a", "host-z"])], + vec![utf8(&["trace-2"]), utf8(&["host-b"])], + ], + ), + composite_on, + ) + .await; + assert!(has_expr::(&composite_filter.expr)); + // Same per-partition `CASE` shape as the float case: unsupported, not `true`. + assert_unsupported( + DynFilterPayload::from_datafusion_expr( + &composite_filter.expr, + REMOTE_DYN_FILTER_PAYLOAD_MAX_BYTES, + ) + .unwrap_err(), + ); + + // Dictionary keys: not a plain `Utf8` key column. + let dict_type = DataType::Dictionary(Box::new(DataType::Int32), Box::new(DataType::Utf8)); + let dict_schema = one_column_schema("trace_id", dict_type); + let dict_on = key("trace_id", 0); + let mut dict_builder = StringDictionaryBuilder::::new(); + dict_builder.append_value("trace-0"); + dict_builder.append_value("trace-1"); + let dict_values: ArrayRef = Arc::new(dict_builder.finish()); + let dict_filter = run_real_hash_join( + 2, + Arc::clone(&dict_schema), + Arc::clone(&dict_schema), + partitions(&dict_schema, vec![vec![Arc::clone(&dict_values)]]), + partitions(&dict_schema, vec![vec![dict_values]]), + vec![(Arc::clone(&dict_on), Arc::clone(&dict_on))], + ) + .await; + assert!(has_expr::(&dict_filter.expr)); + let decoded = decode( + &dict_filter.expr, + &dict_filter.probe_schema, + REMOTE_DYN_FILTER_PAYLOAD_MAX_BYTES, + ); + // Dictionary keys are not a plain `Utf8` key column either. This producer shape + // is a flat `bounds AND lookup`, so retention keeps the bounds conjunct that + // DataFusion itself published and drops only the membership. + let display = decoded.to_string(); + assert!(!has_expr::(&decoded), "{display}"); + assert!(!has_expr::(&decoded), "{display}"); + assert!( + display.contains(">="), + "lower bound must survive: {display}" + ); + assert!( + display.contains("<="), + "upper bound must survive: {display}" + ); + } + + #[tokio::test] + async fn producer_paths_encode_150_and_1024_keys() { + // The two producer shapes that can carry a build key list: the static `IN` list + // pushdown (150 and 1024 are the pushdown limits of the runtime experiment) and + // the hash lookup. Neither is capped by an encoder-side value/byte policy: the + // only bound is the payload budget itself. + for key_count in [150, 1024] { + let (schema, filter, values) = real_join_with_keys(key_count).await; + assert!(has_expr::(&filter.expr)); + let decoded = decode( + &filter.expr, + &filter.probe_schema, + REMOTE_DYN_FILTER_PAYLOAD_MAX_BYTES, + ); + let lists = in_lists(&decoded); + assert_eq!(lists.len(), 1, "{key_count} keys: {decoded}"); + assert_eq!(in_list_values(&lists[0]), values); + + // The static `IN` list pushdown of the same size encodes as well. + let in_list = Arc::new( + InListExpr::try_new( + key("trace_id", 0), + values.iter().map(|value| lit(value.clone())).collect(), + false, + &schema, + ) + .unwrap(), + ) as Arc; + let decoded = decode( + &in_list, + &filter.probe_schema, + REMOTE_DYN_FILTER_PAYLOAD_MAX_BYTES, + ); + let lists = in_lists(&decoded); + assert_eq!(lists.len(), 1, "{key_count} static keys: {decoded}"); + assert_eq!(in_list_values(&lists[0]), values); + } + } + + #[tokio::test] + async fn over_budget_membership_case_is_a_size_refusal() { + let schema = one_column_schema("trace_id", DataType::Utf8); + // Long values so the membership lists dominate the payload. + let long = "t".repeat(256); + let values = (0..24) + .map(|i| format!("{long}-{i:02}")) + .collect::>(); + let borrowed = values.iter().map(String::as_str).collect::>(); + let build = partitions(&schema, vec![vec![utf8(&borrowed)]]); + let probe = partitions(&schema, vec![vec![utf8(&borrowed)]]); + let trace_id = key("trace_id", 0); + let filter = run_real_hash_join( + 3, + Arc::clone(&schema), + Arc::clone(&schema), + build, + probe, + vec![(Arc::clone(&trace_id), Arc::clone(&trace_id))], + ) + .await; + assert!(has_expr::(&filter.expr)); + + // The real payload budget carries all three branch memberships exactly. + let decoded = decode( + &filter.expr, + &filter.probe_schema, + REMOTE_DYN_FILTER_PAYLOAD_MAX_BYTES, + ); + assert_eq!(in_lists(&decoded).len(), 3); + let case = decoded.downcast_ref::().expect("CASE preserved"); + assert_eq!(case.when_then_expr().len(), 3); + + // The whole predicate is one top-level `CASE` conjunct that carries the + // membership, so a budget that only fits `true` has nothing safe to keep: + // membership is never rewritten inside `CASE` and the payload is an explicit + // error instead of an always-true filter. The predicates *are* representable, they + // only do not fit, so the refusal is a size one and not "no wire form". + let true_size = encode_physical_expr_to_bytes(&lit(true)).unwrap().len(); + assert!(true_size < REMOTE_DYN_FILTER_PAYLOAD_MAX_BYTES); + assert_too_large( + DynFilterPayload::from_datafusion_expr(&filter.expr, true_size).unwrap_err(), + ); + } + + #[test] + fn over_budget_negation_is_a_size_refusal() { + let schema = Arc::new(Schema::new(vec![Field::new("host", DataType::Utf8, false)])); + let host = Arc::new(Column::new("host", 0)) as Arc; + let long = "h".repeat(256); + let in_list = Arc::new( + InListExpr::try_new( + Arc::clone(&host), + (0..16).map(|i| lit(format!("{long}-{i:02}"))).collect(), + false, + &schema, + ) + .unwrap(), + ) as Arc; + // `NOT (host IN (...))`: dropping the list in place would evaluate `NOT true` + // = false and drop every row, so the whole conjunct is dropped. Nothing is left + // to ship and the predicate itself is representable, so the refusal is a size one. + let not_in = Arc::new(NotExpr::new(Arc::clone(&in_list))) as Arc; + let true_size = encode_physical_expr_to_bytes(&lit(true)).unwrap().len(); + + assert_too_large(DynFilterPayload::from_datafusion_expr(¬_in, true_size).unwrap_err()); + } + + #[tokio::test] + async fn recovered_payload_uses_only_existing_wire_variants() { + let schema = one_column_schema("trace_id", DataType::Utf8); + let (build, probe, values) = utf8_join(3); + let trace_id = key("trace_id", 0); + let filter = run_real_hash_join( + 3, + Arc::clone(&schema), + Arc::clone(&schema), + build, + probe, + vec![(Arc::clone(&trace_id), Arc::clone(&trace_id))], + ) + .await; + let max = REMOTE_DYN_FILTER_PAYLOAD_MAX_BYTES; + + // The recovered payload decodes with the default extension codec, which rejects + // every expression variant it does not know: a new wire variant would fail here. + let payload = DynFilterPayload::from_datafusion_expr(&filter.expr, max).unwrap(); + let bytes = match &payload { + DynFilterPayload::Datafusion(bytes) => bytes.clone(), + }; + let decoded = payload + .decode_datafusion_expr(&TaskContext::default(), &filter.probe_schema, max) + .unwrap(); + assert_eq!(in_lists(&decoded).len(), 3); + assert_eq!( + hash_seed( + filter + .expr + .downcast_ref::() + .unwrap() + .expr() + .unwrap() + ), + hash_seed(decoded.downcast_ref::().unwrap().expr().unwrap()), + "HashExpr routing seed must survive the wire" + ); + + // Receivers still accept a plain `true` payload: an older sender could publish one, + // and a producer may legitimately publish `true` itself. This transport no longer + // synthesizes `true` as an encoding fallback, so the decode-side compatibility stays + // while the encode-side fallback is gone. + let legacy_bytes = encode_physical_expr_to_bytes(&lit(true)).unwrap(); + assert!(legacy_bytes.len() < bytes.len()); + let legacy_decoded = DynFilterPayload::Datafusion(legacy_bytes) + .decode_datafusion_expr(&TaskContext::default(), &filter.probe_schema, max) + .unwrap(); + assert_eq!(legacy_decoded.to_string(), "true"); + let mut rows = values.clone(); + rows.push("miss-not-a-member".to_string()); + let batch = evaluation_batch(&schema, &rows); + assert_fail_open(&filter.expr, &legacy_decoded, &batch); } } diff --git a/src/common/query/src/request/remote_membership_test_support.rs b/src/common/query/src/request/remote_membership_test_support.rs new file mode 100644 index 00000000000..6bcc16d9b49 --- /dev/null +++ b/src/common/query/src/request/remote_membership_test_support.rs @@ -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, + /// Schema of the probe side the predicate applies to. + pub probe_schema: Arc, +} + +/// Schema with a single nullable column. +pub fn one_column_schema(name: &str, data_type: DataType) -> Arc { + 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, columns: Vec>) -> Vec> { + 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 { + 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, + right_schema: Arc, + build_partitions: Vec>, + probe_partitions: Vec>, + on: Vec<(Arc, Arc)>, +) -> RealDynFilter { + assert!(partition_count >= 1); + + let left_scan: Arc = + MemorySourceConfig::try_new_exec(&build_partitions, Arc::clone(&left_schema), None) + .unwrap(); + let right_scan: Arc = + 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, + Arc::new(RepartitionExec::try_new(right_scan, right_partitioning).unwrap()) + as Arc, + ) + } 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 = Arc::clone(&probe_filter) as _; + // The probe subtree must reference the produced filter, otherwise the join never + // publishes it. + let right: Arc = + 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 = 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::>().await.unwrap(); + } + }) + .collect::>(); + 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>, Vec) { + let schema = one_column_schema("trace_id", DataType::Utf8); + let values = (0..partition_count * 8) + .map(|i| format!("trace-{i:02}")) + .collect::>(); + let borrowed = values.iter().map(String::as_str).collect::>(); + 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::>(); + probe_values.extend(misses.iter().map(String::as_str)); + let probe = partitions(&schema, vec![vec![utf8(&probe_values)]]); + (build, probe, values) +} diff --git a/src/common/query/src/series_frame.rs b/src/common/query/src/series_frame.rs new file mode 100644 index 00000000000..b74fafd6fe3 --- /dev/null +++ b/src/common/query/src/series_frame.rs @@ -0,0 +1,1661 @@ +// 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. + +//! Streaming boundary between finite raw-series chunks and DataFusion record batches. +//! +//! Schema fields identify the ordered logical payload fields and codec layout; additional +//! application metadata is permitted when stable across the stream. A key-encoded frame also +//! declares its own label decode description, and the frame is the sole source of decode +//! information: [`unpack_raw_series`] reads the fields, the label mode, the description, and the +//! producer ordering from the received schema, keeps the description on the returned stream, and +//! therefore needs no [`RawLabelSource`]. A caller that holds a scan-bound identity — the physical +//! region key layout a decoded identity came from — compares that identity's declared label +//! decode layout with [`ensure_frame_matches_label_source`] instead of passing it as a decode +//! input; that comparison is equality of the description alone and proves nothing about region +//! identity or provenance, and neither side is authenticated as field provenance. This adapter +//! preserves +//! scan candidates only; it is not a residual filter, authorization check, remote transport, or +//! compaction boundary. Raw frames accept all three [`SeriesOrdering`] declarations, while evaluated +//! frames accept only `Contiguous`. Raw `Interleaved` supports independently closed producer +//! fragment chains in sequence, including recurring keys; it does not multiplex open chains. +//! +//! An evaluated frame is the same physical family: [`pack_evaluated_series`] and +//! [`unpack_evaluated_series`] carry computed values under complete labels and grid positions, so a +//! compute consumer needs neither a storage key nor a scan binding to read them. + +use std::future::Future; +use std::pin::Pin; +use std::sync::Arc; +use std::task::{Context, Poll}; +use std::time::Duration; + +use common_error::ext::BoxedError; +use common_recordbatch::{DfRecordBatch, DfSendableRecordBatchStream}; +use datafusion_common::DataFusionError; +use datatypes::arrow::datatypes::{Schema as ArrowSchema, SchemaRef as ArrowSchemaRef}; +use datatypes::error::InvalidSeriesSnafu; +use datatypes::series::aggregate_state::{AggregateStateSchema, StateSeries}; +use datatypes::series::frame::{ + FrameContent, FrameLabelMode, LABEL_DECODE_VERSION, LabelDecodeColumn, LabelDecodeEncoding, + LabelDecodeSpec, LabelDecodeTag, SeriesFrameBuilder, SeriesFrameCursor, SeriesFrameDeclaration, + SeriesFrameDecoder, StateFrameRow, series_frame_label_decode, series_frame_schema, +}; +use datatypes::series::raw::RawSeriesChunk; +use datatypes::series::samples::{Series, SeriesSchema}; +use datatypes::series::{SeriesLabels, SeriesOrdering}; +use futures_util::Stream; +use store_api::codec::PrimaryKeyEncoding; +use store_api::region_engine::{ + NO_BOUND_LABEL_SOURCE, RawLabelSource, RawSeriesStream, SendableRawSeriesStream, +}; +use tokio::time::{Instant, Sleep}; + +#[cfg(test)] +mod tests; + +const ORDERING_KEY: &str = "greptime.series.ordering"; + +/// A stream of evaluated series chunks and their finality. +/// +/// The pair is what an evaluated producer has and an evaluated consumer needs: the values on their +/// absolute grid positions, and whether this chunk closed the chain it belongs to. It is deliberately +/// not a third runtime chunk type - `Series` is the runtime value, and finality is the one fact a +/// chunk has to carry besides it. +pub type SendableEvaluatedSeriesStream = + Pin> + Send>>; + +/// A stream of aggregate-state chunks and their producer-local finality. +/// +/// Export accepts the existing field-major [`StateSeries`] representation and columnarises each +/// chunk once. Import is intentionally asymmetric: [`SendableStateFrameStream`] retains typed Arrow +/// handles so consumers do not rebuild a nested state tree. +pub type SendableStateSeriesStream = + Pin> + Send>>; + +/// A stream of decoded state rows retaining typed handles into their Arrow batch. +pub type SendableStateFrameStream = + Pin> + Send>>; + +/// Builds the canonical raw frame schema with the producer's label binding and ordering. +/// +/// Ordering records a producer guarantee; it is not inferred from frame contents. The label binding +/// determines both the label mode and, for a primary-key binding, the self-describing label decode +/// description written into the schema, so a frame can never declare a label layout it does not +/// describe. +pub fn raw_series_frame_schema_with_ordering( + schema: &SeriesSchema, + label_source: &RawLabelSource, + ordering: SeriesOrdering, +) -> datafusion_common::Result { + if schema.eval_grid.is_some() { + return Err(invalid( + "a raw frame cannot carry a schema with an evaluation grid", + )); + } + frame_schema_with( + schema, + label_mode(label_source), + label_decode_spec(label_source).as_ref(), + ordering, + ) +} + +/// Assembles a declared frame schema from an explicit label mode and decode description. +/// +/// The mode and description pair is checked by [`series_frame_schema`], so a key mode without a +/// description and an explicit mode with one are both rejected here instead of reaching the wire. +/// A node that re-declares its child's frame and publishes under that declaration uses this: the +/// declaration has to survive the round trip, and this is the one place that decides what it is. +pub fn frame_schema_with( + schema: &SeriesSchema, + mode: FrameLabelMode, + decode: Option<&LabelDecodeSpec>, + ordering: SeriesOrdering, +) -> datafusion_common::Result { + // An evaluated frame has no storage key to be ordered by, so the only claim it can honour is + // that each chain is contiguous. Writing a stronger one would produce a frame the reader refuses + // and a plan that fails where it could have been refused. + if schema.eval_grid.is_some() { + ensure_contiguous_ordering(ordering)?; + } + let ordering = match ordering { + SeriesOrdering::Contiguous => "contiguous", + SeriesOrdering::KeyThenTime => "read_key_then_time", + SeriesOrdering::Interleaved => "interleaved", + }; + let schema = series_frame_schema(schema, mode, decode).map_err(codec_error)?; + let mut metadata = schema.metadata().clone(); + metadata.insert(ORDERING_KEY.to_string(), ordering.to_string()); + Ok(Arc::new(ArrowSchema::new_with_metadata( + schema.fields().clone(), + metadata, + ))) +} + +/// Derives the label decode description a frame must carry for this binding. +/// +/// A primary-key binding reduces to exactly what decoding reads: the metric name, the primary-key +/// encoding, the ordered key columns with their physical types, and the logical tags. Region +/// metadata guarantees the key list holds every tag column and nothing else, so the description +/// needs no per-column role. Explicit bindings already carry complete labels and declare no +/// description. +/// +/// The result is canonical: its logical tags are in [`LabelDecodeSpec::canonicalize`] order, which +/// is what the writer serializes, so a derived description and a received one for the same labels +/// are the same value and the same text. Derivation cannot fail, because a physical type is copied +/// rather than translated; a description a reader cannot honour is rejected when it is read, and a +/// decoder rejects the tags it cannot bind. +pub fn label_decode_spec(source: &RawLabelSource) -> Option { + let RawLabelSource::PrimaryKey { + metric_name, + physical_metadata, + logical_tags, + } = source + else { + return None; + }; + let primary_key = physical_metadata + .primary_key_columns() + .map(|column| LabelDecodeColumn { + column_id: column.column_id, + name: column.column_schema.name.clone(), + physical_type: column.column_schema.data_type.clone(), + }) + .collect(); + let mut description = LabelDecodeSpec { + version: LABEL_DECODE_VERSION, + metric_name: metric_name.to_string(), + encoding: match physical_metadata.primary_key_encoding { + PrimaryKeyEncoding::Dense => LabelDecodeEncoding::Dense, + PrimaryKeyEncoding::Sparse => LabelDecodeEncoding::Sparse, + }, + primary_key, + logical_tags: logical_tags + .iter() + .map(|tag| LabelDecodeTag { + column_id: tag.column_id, + name: tag.name.to_string(), + }) + .collect(), + }; + description.canonicalize(); + Some(description) +} + +/// Reads the producer ordering declared by a complete v2 frame schema. +/// +/// Ordering is mandatory stream metadata; it is never inferred from frame contents. +pub fn series_frame_ordering(schema: &ArrowSchema) -> datafusion_common::Result { + match schema.metadata().get(ORDERING_KEY).map(String::as_str) { + Some("contiguous") => Ok(SeriesOrdering::Contiguous), + Some("read_key_then_time") => Ok(SeriesOrdering::KeyThenTime), + Some("interleaved") => Ok(SeriesOrdering::Interleaved), + None | Some(_) => Err(invalid("missing or unknown series ordering")), + } +} + +/// Packs a storage raw-series stream into DataFusion record batches incrementally. +/// +/// Rows accumulate across chunks into batches bounded by the builder's row and estimated payload +/// limits; one legal oversized row may be emitted alone, and these limits are a work bound, not a +/// resident-memory cap. A ready batch is yielded without polling the source again. +/// +/// Buffered rows are published as soon as the source reports `Pending`, i.e. this constructor needs +/// no timer and works on any executor. A caller that knows its poller is a Tokio runtime with the +/// time driver enabled may hold buffered rows across a pending period with +/// [`pack_raw_series_with`]. +/// +/// Even under [`SeriesOrdering::Interleaved`], each producer fragment chain must close before +/// another starts; arbitrary multiplexing of open chains is rejected. Closed fragment chains may +/// recur with the same key and overlapping timestamps. Finality closes a producer fragment, not +/// necessarily the logical series. For `Contiguous`, validation checks adjacent chunk conditions +/// but does not certify nonadjacent recurrence. +/// +/// The stream's own declaration is the only decode input: a frame unpacked without a scan-bound +/// [`RawLabelSource`] round trips unchanged instead of being re-declared from a binding it does not +/// have, and nothing is derived from a binding here. The declaration also decides the frame's label +/// mode, so a chunk whose labels disagree with it is rejected when that chunk is coded. +pub fn pack_raw_series( + source: SendableRawSeriesStream, +) -> datafusion_common::Result { + pack_raw_series_with(source, PendingBatching::Immediate) +} + +/// Packs a storage raw-series stream with the pending batching its poller can support. +/// +/// [`PendingBatching::Immediate`] behaves exactly like [`pack_raw_series`]. [`PendingBatching`] +/// explains what a caller has to know before asking for a deadline. +pub fn pack_raw_series_with( + source: SendableRawSeriesStream, + batching: PendingBatching, +) -> datafusion_common::Result { + let ordering = source.ordering(); + let schema = source.schema().clone(); + let decode = source.label_decode_spec().cloned(); + let labels = declared_label_mode(&decode); + // The declared frame schema carries the producer ordering and the label decode description; + // every ready batch is published under it, including when no row is ever produced. + let frame_schema = frame_schema_with(&schema, labels, decode.as_ref(), ordering)?; + let builder = SeriesFrameBuilder::try_new( + &schema, + labels, + decode.as_ref(), + SeriesFrameBuilder::DEFAULT_MAX_ROWS, + SeriesFrameBuilder::DEFAULT_MAX_BYTES, + ) + .map_err(codec_error)?; + Ok(Box::pin(PackStream { + source: Some(source), + schema, + labels, + batches: PackBatches::new(builder, frame_schema), + ordering, + validator: SequenceValidator::new(ordering), + pending: PendingFlush::new(batching), + })) +} + +/// Packs a stream of evaluated chunks into DataFusion record batches incrementally. +/// +/// An evaluated frame names its series by their complete labels and addresses time on the evaluation +/// grid `schema` declares, so there is nothing to decode and no storage key to carry: the frame +/// declares `explicit` identity and `grid_spans` time, and the grid is written once instead of +/// repeating timestamps on every row. +/// +/// Only [`SeriesOrdering::Contiguous`] is declared, because that is the one ordering this layer can +/// promise and check: each chunk chain is contiguous with itself. A caller that has reason to claim +/// [`SeriesOrdering::KeyThenTime`] about computed values would have to justify it, and a consumer +/// must never infer it from the presence of labels. +/// +/// Bounds, backpressure, and error handling are the raw path's: rows accumulate into batches bounded +/// by the builder's row and estimated payload limits, a ready batch is yielded before the source is +/// polled again, and a `Pending` source still delivers what is buffered. +pub fn pack_evaluated_series( + source: SendableEvaluatedSeriesStream, + schema: Arc, +) -> datafusion_common::Result { + if schema.eval_grid.is_none() { + return Err(invalid( + "an evaluated frame needs a schema with an evaluation grid", + )); + } + let frame_schema = frame_schema_with( + &schema, + FrameLabelMode::Explicit, + None, + SeriesOrdering::Contiguous, + )?; + let builder = SeriesFrameBuilder::try_new( + &schema, + FrameLabelMode::Explicit, + None, + SeriesFrameBuilder::DEFAULT_MAX_ROWS, + SeriesFrameBuilder::DEFAULT_MAX_BYTES, + ) + .map_err(codec_error)?; + Ok(Box::pin(PackEvaluatedStream { + source: Some(source), + schema, + batches: PackBatches::new(builder, frame_schema), + validator: EvaluatedSequenceValidator::new(), + })) +} + +/// Packs aggregate-state chunks into bounded DataFusion record batches. +/// +/// The producer supplies one [`StateSeries`] per group chunk; the cursor columnarises it into the +/// frame once. Aggregate state requires a grid, explicit labels and contiguous ordering. The state +/// schema is revalidated with its own constructor before any stream is returned. +pub fn pack_aggregate_state( + source: SendableStateSeriesStream, + state: Arc, + schema: Arc, +) -> datafusion_common::Result { + if schema.eval_grid.is_none() { + return Err(invalid("an aggregate state frame needs an evaluation grid")); + } + AggregateStateSchema::try_new(state.kind, state.components.to_vec()).map_err(codec_error)?; + let frame_schema = datatypes::series::frame::aggregate_state_frame_schema( + &state, + &schema, + FrameLabelMode::Explicit, + ) + .map_err(codec_error)?; + let mut metadata = frame_schema.metadata().clone(); + metadata.insert(ORDERING_KEY.to_string(), "contiguous".to_string()); + let frame_schema = Arc::new(ArrowSchema::new_with_metadata( + frame_schema.fields().clone(), + metadata, + )); + let builder = SeriesFrameBuilder::try_new_aggregate_state( + &state, + &schema, + FrameLabelMode::Explicit, + SeriesFrameBuilder::DEFAULT_MAX_ROWS, + SeriesFrameBuilder::DEFAULT_MAX_BYTES, + ) + .map_err(codec_error)?; + let decoder = + SeriesFrameDecoder::try_new_aggregate_state(&state, &schema, FrameLabelMode::Explicit) + .map_err(codec_error)?; + // Decoding the empty batch validates the exact declared layout before publishing this stream. + decoder + .decode_aggregate_state(&DfRecordBatch::new_empty(frame_schema.clone())) + .map_err(codec_error)?; + Ok(Box::pin(PackStateStream { + source: Some(source), + state, + schema, + batches: PackBatches::new(builder, frame_schema), + })) +} + +/// Unpacks aggregate-state frames while retaining Arrow-backed state rows. +/// +/// Kind and ordered components must both agree: the kind describes the accumulator semantics while +/// components describe its physical values. Expected fields and grid are checked independently. +pub fn unpack_aggregate_state( + source: DfSendableRecordBatchStream, + expected_state: Option>, + expected_series: Option>, +) -> datafusion_common::Result { + let frame_schema = source.schema(); + let declaration = SeriesFrameDeclaration::parse(frame_schema.as_ref()).map_err(codec_error)?; + if declaration.content() != FrameContent::AggregateState { + return Err(invalid(format!( + "expected an aggregate state frame, found {}", + declaration.content().as_str() + ))); + } + ensure_contiguous_ordering(series_frame_ordering(frame_schema.as_ref())?)?; + let state = declaration + .aggregate_state() + .ok_or_else(|| invalid("aggregate state declaration has no aggregate state"))?; + if let Some(expected) = expected_state { + if state.kind != expected.kind { + return Err(invalid( + "aggregate state kind does not match expected state", + )); + } + if state.components != expected.components { + return Err(invalid( + "aggregate state components do not match expected state", + )); + } + } + let schema = Arc::new(declaration.series().clone()); + if let Some(expected) = expected_series { + if expected.fields.len() != schema.fields.len() + || expected + .fields + .iter() + .zip(schema.fields.iter()) + .any(|(a, b)| a.name != b.name) + { + return Err(invalid( + "aggregate state fields do not match expected series", + )); + } + if expected.eval_grid.as_ref().map(|grid| grid.spec()) + != schema.eval_grid.as_ref().map(|grid| grid.spec()) + { + return Err(invalid( + "aggregate state grid does not match expected series", + )); + } + } + let decoder = + SeriesFrameDecoder::try_new_aggregate_state(state, &schema, FrameLabelMode::Explicit) + .map_err(codec_error)?; + // Validate even empty streams before returning them, rather than deferring declaration errors. + decoder + .decode_aggregate_state(&DfRecordBatch::new_empty(frame_schema.clone())) + .map_err(codec_error)?; + Ok(Box::pin(UnpackStateStream { + source: Some(source), + frame_schema, + pending: Vec::new().into_iter(), + decoder, + })) +} + +/// Unpacks DataFusion batches declared by [`pack_raw_series`]. +/// +/// The frame is the sole source of decode information: the payload fields, the label mode, the +/// label decode description, and the producer ordering are all read from the stream's own schema, +/// so unpacking a frame a producer wrote needs no local copy of its binding. Like packing, unpacking +/// accepts `Interleaved` only when every producer fragment chain closes before the next starts; it +/// rejects multiplexed open chains. Closed fragment chains may recur with the same key and overlapping +/// timestamps. Validation does not certify nonadjacent recurrence for `Contiguous` ordering. +/// +/// Every frame is validated here, unconditionally. The declared layout must be this revision's, the +/// label decode description must parse, name a known version, and agree with the declared label +/// mode - a key frame must declare one and an explicit frame must not, since explicit labels are +/// already complete. The declared fields and the empty batch are then decoded once, so a stream that +/// could not be decoded is rejected before it is returned. +/// +/// A frame that declares evaluated content is refused here, before anything is read: a raw consumer +/// reads timestamps rather than grid positions, so the two contents are not interchangeable. +/// +/// `expected` is a check, never an input. When it is given it must name the same logical fields in +/// the same order and the same evaluation grid as the frame declares - which for a raw frame is that +/// both sides carry none - and a mismatch is an error. The decoder and the returned stream's schema +/// are built from the frame either way, so a caller cannot supply a field layout the frame does not +/// declare. +pub fn unpack_raw_series( + source: DfSendableRecordBatchStream, + expected: Option>, +) -> datafusion_common::Result { + let frame_schema = source.schema(); + let declaration = SeriesFrameDeclaration::parse(frame_schema.as_ref()).map_err(codec_error)?; + if declaration.content() != FrameContent::Raw { + return Err(invalid("expected a raw frame, found an evaluated one")); + } + let labels = declaration.labels(); + let declared = declaration.label_decode().cloned(); + let schema = Arc::new(declaration.series().clone()); + if let Some(expected) = &expected { + ensure_declared_schema(&schema, expected)?; + } + let ordering = series_frame_ordering(frame_schema.as_ref())?; + let decoder = + SeriesFrameDecoder::try_new(&schema, labels, declared.as_ref()).map_err(codec_error)?; + // Validate even empty streams' declared schema and layout before returning the stream. + let empty = DfRecordBatch::new_empty(frame_schema.clone()); + decoder.decode_raw(&empty).map_err(codec_error)?; + Ok(Box::pin(UnpackStream { + source: Some(source), + schema, + frame_schema, + label_decode_spec: declared, + ordering, + validator: SequenceValidator::new(ordering), + pending: Vec::new().into_iter(), + decoder, + })) +} + +/// Unpacks DataFusion batches declared by [`pack_evaluated_series`]. +/// +/// The frame declares its grid, its field list, and its label mode, so the returned stream carries +/// the [`SeriesSchema`] the rows are addressed on and needs no planning-side copy of it. The grid is +/// the frame's own declaration: the timestamps stay unmaterialized until a consumer asks for one. +/// +/// A frame that declares raw samples, keyed identity, or an ordering other than `contiguous` is +/// refused before the stream is returned, as is a grid the declaration check cannot make sense of. +/// `expected` is a check and never an input, exactly as on the raw path: when given it must name the +/// same fields and the same grid the frame declares. +pub fn unpack_evaluated_series( + source: DfSendableRecordBatchStream, + expected: Option>, +) -> datafusion_common::Result { + let frame_schema = source.schema(); + let declaration = SeriesFrameDeclaration::parse(frame_schema.as_ref()).map_err(codec_error)?; + if declaration.content() != FrameContent::Evaluated { + return Err(invalid(format!( + "expected an evaluated frame, found {}", + declaration.content().as_str() + ))); + } + ensure_contiguous_ordering(series_frame_ordering(frame_schema.as_ref())?)?; + let schema = Arc::new(declaration.series().clone()); + if let Some(expected) = &expected { + ensure_declared_schema(&schema, expected)?; + } + let decoder = SeriesFrameDecoder::try_new(&schema, FrameLabelMode::Explicit, None) + .map_err(codec_error)?; + let empty = DfRecordBatch::new_empty(frame_schema.clone()); + decoder.decode_evaluated(&empty).map_err(codec_error)?; + Ok(Box::pin(UnpackEvaluatedStream { + source: Some(source), + frame_schema, + validator: EvaluatedSequenceValidator::new(), + pending: Vec::new().into_iter(), + decoder, + })) +} + +/// Rejects an `expected` series schema the frame does not declare. +/// +/// Only the two things a caller can get wrong are checked, because those are the only two things +/// [`SeriesSchema`] holds: the logical fields and their order, and the evaluation grid. A raw frame +/// carries no grid and an evaluated one carries exactly its own, so the grid comparison is also what +/// keeps a raw expectation from decoding an evaluated frame. +fn ensure_declared_schema( + declared: &SeriesSchema, + expected: &SeriesSchema, +) -> datafusion_common::Result<()> { + if expected.fields.len() != declared.fields.len() + || expected + .fields + .iter() + .zip(declared.fields.iter()) + .any(|(expected, declared)| expected.name != declared.name) + { + return Err(invalid( + "frame fields do not match the expected series schema", + )); + } + match (&expected.eval_grid, &declared.eval_grid) { + (None, None) => Ok(()), + (Some(expected), Some(declared)) if expected.spec() == declared.spec() => Ok(()), + _ => Err(invalid( + "frame evaluation grid does not match the expected series schema", + )), + } +} + +/// Checks that a frame declares the label decode layout a scan-bound binding describes. +/// +/// This compares one thing: the description parsed from the frame's +/// `greptime.series.label_decode` metadata against the description derived from `label_source`, by +/// plain equality. A difference in the version, the metric name, the primary-key encoding, the +/// ordered key columns and their physical types, or the logical tags is a mismatch. Nothing else is +/// compared, so agreeing descriptions do **not** establish that these are the region's chunks: no +/// region id, table id, or provenance is part of either side, and two regions whose tags have the +/// same ids, names, and types produce equal descriptions. The check answers "does this frame describe +/// the label layout this binding expects", never "is this the region I asked for". +/// +/// It belongs to the caller that holds both sides: a frame describes its own labels, so +/// [`unpack_raw_series`] decodes it without a binding, and a caller that received the frame from a +/// peer compares the declaration here instead of decoding under whichever side it trusts. +/// +/// The comparison is plain equality. The writer canonicalizes the description (see +/// [`LabelDecodeSpec::canonicalize`]), so a description that reaches a reader already has one +/// spelling and equality says everything there is to say about it. +pub fn ensure_frame_matches_label_source( + frame: &ArrowSchema, + label_source: &RawLabelSource, +) -> datafusion_common::Result<()> { + let declared = series_frame_label_decode(frame).map_err(codec_error)?; + if declared != label_decode_spec(label_source) { + return Err(invalid( + "raw frame label decode description does not match the supplied binding", + )); + } + Ok(()) +} + +fn label_mode(source: &RawLabelSource) -> FrameLabelMode { + match source { + RawLabelSource::PrimaryKey { .. } => FrameLabelMode::Key, + RawLabelSource::Explicit => FrameLabelMode::Explicit, + } +} + +/// Returns the label mode a frame declares: a key frame describes its key, an explicit frame +/// carries complete labels and declares no description. +fn declared_label_mode(declared: &Option) -> FrameLabelMode { + match declared { + Some(_) => FrameLabelMode::Key, + None => FrameLabelMode::Explicit, + } +} + +/// Rejects an evaluated frame that claims more order than its producer promised. +/// +/// Computed values have no storage key to be ordered by, so `read_key_then_time` is not a claim this +/// layer can honour; `Interleaved` is not supported for evaluated frames. Treating either as +/// `contiguous` would silently weaken a guarantee a consumer may rely on. +fn ensure_contiguous_ordering(ordering: SeriesOrdering) -> datafusion_common::Result<()> { + match ordering { + SeriesOrdering::Contiguous => Ok(()), + SeriesOrdering::KeyThenTime => Err(invalid( + "an evaluated frame cannot claim key-then-time ordering", + )), + SeriesOrdering::Interleaved => Err(invalid("interleaved series ordering is not supported")), + } +} + +fn codec_error(error: datatypes::error::Error) -> DataFusionError { + DataFusionError::External(Box::new(BoxedError::new(error))) +} + +fn upstream_error(error: BoxedError) -> DataFusionError { + DataFusionError::External(Box::new(error)) +} + +fn invalid(reason: impl Into) -> DataFusionError { + DataFusionError::External(Box::new(BoxedError::new( + InvalidSeriesSnafu { + reason: reason.into(), + } + .build(), + ))) +} + +/// Cross-chunk validation state for raw producer fragment chains. Every chain's chunks must be +/// contiguous, including for `Interleaved`; this validator checks adjacent chunks only and retains +/// the previous owned key (not an Arrow buffer), timestamp, metric, and finality. An `Interleaved` +/// chain releases that state on closure, so later fragment chains may recur with the same key, +/// labels, and timestamps independently. +struct SequenceValidator { + ordering: SeriesOrdering, + previous_key: Option>, + previous_timestamp: Option, + previous_metric: Option, + previous_is_last: bool, +} + +impl SequenceValidator { + fn new(ordering: SeriesOrdering) -> Self { + Self { + ordering, + previous_key: None, + previous_timestamp: None, + previous_metric: None, + previous_is_last: false, + } + } + + fn finish(&self) -> datafusion_common::Result<()> { + if self.previous_key.is_some() && !self.previous_is_last { + return Err(invalid("raw series stream ended before key was final")); + } + Ok(()) + } + + fn validate(&mut self, chunk: &RawSeriesChunk) -> datafusion_common::Result<()> { + let key = chunk.primary_key.as_slice(); + let timestamp = chunk + .time + .len() + .checked_sub(1) + .and_then(|last| chunk.time.timestamp(last)) + .ok_or_else(|| invalid("empty raw series chunk"))?; + if let Some(previous) = &self.previous_key { + match previous.as_slice().cmp(key) { + std::cmp::Ordering::Equal => { + if self.previous_is_last { + return Err(invalid("raw series key recurred after final chunk")); + } + if self.previous_metric != chunk.metric { + return Err(invalid("raw series metric changed within key")); + } + let first = chunk + .time + .timestamp(0) + .ok_or_else(|| invalid("empty raw series chunk"))?; + if self.previous_timestamp.is_some_and(|last| first <= last) { + return Err(invalid( + "raw series timestamps are not increasing across chunks", + )); + } + } + _ => { + if !self.previous_is_last { + return Err(invalid("raw series key changed before final chunk")); + } + if self.ordering == SeriesOrdering::KeyThenTime && previous.as_slice() > key { + return Err(invalid("raw series keys are not ordered")); + } + } + } + } + if self.ordering == SeriesOrdering::Interleaved && chunk.is_last { + self.previous_key = None; + self.previous_timestamp = None; + self.previous_metric = None; + self.previous_is_last = false; + } else { + self.previous_key = Some(key.to_vec()); + self.previous_timestamp = Some(timestamp); + self.previous_metric = chunk.metric.clone(); + self.previous_is_last = chunk.is_last; + } + Ok(()) + } +} + +/// Cross-chunk validation state for evaluated chains. +/// +/// This is a **chain-local** validator. It checks exactly three things: that a chunk does not change +/// identity while its chain is open, that a chain closes exactly once, and that the positions of an +/// open chain keep increasing across adjacent chunks. It keeps at most the one open chain, so it +/// never certifies that a complete identity does not recur later in the stream; that global +/// non-recurrence is a producer contract enforced where identities are completed (the repartition +/// owner), not here. +/// +/// `is_last` closes one chunk chain and nothing more. It is not the end of a label set: a range +/// function or a label rewrite can make two input series show the same complete labels, and each of +/// them closes itself, so a closed chain may be followed by another chain whose labels happen to be +/// equal. Only the still-open chain is remembered, which is what keeps such a contribution from being +/// refused as a re-opened series while still refusing a chain that changes identity before it closes. +struct EvaluatedSequenceValidator { + /// The labels of the open chain and the last grid position it carried. + open: Option<(SeriesLabels, usize)>, +} + +impl EvaluatedSequenceValidator { + fn new() -> Self { + Self { open: None } + } + + fn finish(&self) -> datafusion_common::Result<()> { + if self.open.is_some() { + return Err(invalid( + "evaluated series stream ended before a chain closed", + )); + } + Ok(()) + } + + fn validate(&mut self, series: &Series, is_last: bool) -> datafusion_common::Result<()> { + let (Some(first), Some(last)) = (series.time.first_position(), series.time.last_position()) + else { + // No carried position: only a closing chunk may be empty, and it closes the chain it + // belongs to without advancing it. + if !is_last { + return Err(invalid( + "an evaluated chunk without positions must close its series", + )); + } + match &self.open { + Some((labels, _)) if labels == &series.metric => self.open = None, + Some(_) => { + return Err(invalid( + "evaluated series identity changed before its chain closed", + )); + } + None => {} + } + return Ok(()); + }; + if let Some((labels, previous)) = &self.open { + if labels != &series.metric { + return Err(invalid( + "evaluated series identity changed before its chain closed", + )); + } + if first <= *previous { + return Err(invalid( + "evaluated series positions are not increasing across chunks", + )); + } + } + self.open = (!is_last).then(|| (series.metric.clone(), last)); + Ok(()) + } +} + +/// The batching half of a pack stream: the builder, the cursor installed in it, and the declared +/// schema every ready batch is published under. +struct PackBatches { + frame_schema: ArrowSchemaRef, + builder: Option, + cursor: Option, +} + +impl PackBatches { + fn new(builder: SeriesFrameBuilder, frame_schema: ArrowSchemaRef) -> Self { + Self { + frame_schema, + builder: Some(builder), + cursor: None, + } + } + + /// Installs the cursor of the chunk just read, replacing whatever was left of the previous one. + fn install(&mut self, cursor: SeriesFrameCursor) { + self.cursor = Some(cursor); + } + + /// Advances the installed cursor until it yields one ready batch or is exhausted, dropping an + /// exhausted cursor. `None` means no batch is ready, so the source may be polled again. + fn advance(&mut self) -> datatypes::error::Result> { + let ready = match (self.cursor.as_mut(), self.builder.as_mut()) { + (Some(cursor), Some(builder)) => cursor.append_to(builder)?, + _ => return Ok(None), + }; + match ready { + Some(batch) => Ok(Some(batch)), + None => { + self.cursor = None; + Ok(None) + } + } + } + + /// Flushes the rows buffered so far, if any, so a pending source can still deliver data. + fn flush(&mut self) -> datatypes::error::Result> { + match self.builder.as_mut() { + Some(builder) => builder.flush(), + None => Ok(None), + } + } + + /// Releases the buffered owners, leaving the stream terminal; batches already yielded are + /// unaffected. + fn release(&mut self) { + self.cursor = None; + self.builder = None; + } + + /// Publishes one ready batch under the declared frame schema, which is the builder's own layout + /// plus the producer's ordering metadata. A batch whose fields cannot be declared releases the + /// stream instead of yielding rows with an undeclared layout. + fn declare( + &mut self, + batch: DfRecordBatch, + ) -> Poll>> { + match DfRecordBatch::try_new(self.frame_schema.clone(), batch.columns().to_vec()) { + Ok(batch) => Poll::Ready(Some(Ok(batch))), + Err(error) => { + self.release(); + Poll::Ready(Some(Err(DataFusionError::from(error)))) + } + } + } +} + +/// How long a pending source may keep buffered rows before they are published as a batch of their +/// own. +/// +/// One fixed short delay bounds how long a partially filled batch is held, so a slow producer costs +/// at most this latency per pending period instead of one batch per series. +const PENDING_FLUSH_DELAY: Duration = Duration::from_millis(1); + +/// How a pack stream treats the rows it has buffered when its source reports `Pending`. +/// +/// The choice belongs to the code that builds the stream, because that is the only place that knows +/// how the stream will be polled. Nothing is probed at run time: the only way to ask Tokio whether +/// a time driver exists is to create a timer and catch the panic, and that unwind still runs the +/// panic hook, logs an error, and counts a panic, so it is not a capability test. +#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)] +pub enum PendingBatching { + /// Publish the buffered rows as the pending period begins. + /// + /// Needs no timer, so a Tokio runtime with or without the time driver, and an executor with no + /// runtime at all, may poll the stream. This is the default because a stream built in one place + /// is not necessarily polled by the runtime that built it. + #[default] + Immediate, + /// Keep buffering across pending periods until the builder is full or a short deadline + /// elapses. + /// + /// The deadline is a Tokio timer, so the stream must be polled by a runtime whose time driver + /// is enabled (`Builder::enable_time()`, or `enable_all()` as every + /// `common_runtime::Runtime` does). A poller with no runtime context, and a poller on a + /// different runtime than the one that armed the deadline, fall back to publishing + /// immediately; only a runtime without a time driver has no fallback and panics inside + /// `sleep_until`, exactly like any other Tokio timer. + Deadline, +} + +/// Bounded batching across a pending raw source. +/// +/// The first pending period that has buffered rows publishes them immediately, so a stream whose +/// source delivers one chunk at a time keeps its original first-batch latency. Every later pending +/// period keeps accumulating rows until the builder is full - which [`PackBatches::advance`] reports +/// on its own - or until [`PENDING_FLUSH_DELAY`] elapses, whichever comes first. One deadline serves +/// the whole pending period, so rows arriving meanwhile extend the batch instead of restarting the +/// wait, and a pending source with nothing buffered arms no timer at all. +/// +/// Only [`PendingBatching::Deadline`] arms a timer; [`PendingBatching::Immediate`] publishes at +/// every pending period and never touches the time driver. +struct PendingFlush { + /// The batching the stream's builder asked for. + batching: PendingBatching, + /// Whether the buffered rows of the first pending period were already published immediately. + first_flushed: bool, + /// Whether the builder may hold rows, i.e. whether a deadline would have anything to publish. + /// + /// A flush leaves the builder empty and no source wake refills it, so waiting there would only + /// spin a timer. The estimate is exact after every flush and errs to `true` between installing + /// a chunk and the flush that publishes it, which costs at most one empty timer per chunk that + /// happened to fill a batch exactly. + maybe_buffered: bool, + /// End of the pending period the stream is in, while a timer is armed. + deadline: Option, + /// The timer that wakes the stream at `deadline`; polling it registers this stream's waker. + /// + /// A [`Sleep`] belongs to the time driver that was current when it was created, so this one is + /// only polled while [`PendingFlush::timer_runtime`] is still the current runtime, and it is + /// dropped with the stream. Dropping a timer after its runtime shut down only deregisters the + /// entry, which Tokio supports; polling one there panics, which is why the deadline is disarmed + /// instead of polled when the poller is not the runtime that armed it. + timer: Option>>, + /// The runtime that owns `timer`, i.e. the one that was current when the deadline was armed. + timer_runtime: Option, +} + +impl PendingFlush { + fn new(batching: PendingBatching) -> Self { + Self { + batching, + first_flushed: false, + maybe_buffered: false, + deadline: None, + timer: None, + timer_runtime: None, + } + } + + /// Releases the deadline, leaving no timer registered with the runtime. + fn disarm(&mut self) { + self.deadline = None; + self.timer = None; + self.timer_runtime = None; + } + + /// Records that the builder published everything it had, so it is empty again. + fn flushed(&mut self) { + self.maybe_buffered = false; + self.disarm(); + } + + /// Records that a chunk was installed, which may buffer rows. + fn installed(&mut self) { + self.maybe_buffered = true; + } + + /// Polls the armed deadline and reports whether it elapsed, or whether waiting for it became + /// impossible. + /// + /// Polling the timer is what registers this stream's waker with the runtime, so an elapsed + /// deadline wakes the stream by itself instead of waiting for the source to wake it first. The + /// report is `true` in either case, so the caller publishes the buffered rows now: a deadline + /// that belongs to another runtime would never wake this poller, and polling it after its + /// runtime shut down would panic. + fn elapsed(&mut self, cx: &mut Context<'_>) -> bool { + if self.timer.is_none() { + return false; + } + if self.timer_runtime != current_runtime_id() { + self.disarm(); + return true; + } + let Some(timer) = self.timer.as_mut() else { + return false; + }; + if timer.as_mut().poll(cx).is_pending() { + return false; + } + self.disarm(); + true + } + + /// Arms the deadline for a later pending period, keeping an armed one as it is. + /// + /// Returns `false` when there is nothing to wait for: the caller asked for + /// [`PendingBatching::Immediate`], no rows are buffered, or this stream is polled outside a + /// Tokio runtime. The caller then publishes the buffered rows immediately instead of waiting for + /// a deadline that would never fire. + /// + /// # Panics + /// + /// Panics inside `sleep_until`, like any other Tokio timer, when the runtime polling the stream + /// has no time driver. That is the one environment a probe could not detect and an unwind only + /// hides, so [`PendingBatching::Deadline`] is an explicit promise of the code that builds the + /// stream. + fn arm(&mut self, cx: &mut Context<'_>) -> bool { + if self.batching == PendingBatching::Immediate { + return false; + } + if self.deadline.is_some() { + return true; + } + if !self.maybe_buffered { + return false; + } + let Ok(runtime) = tokio::runtime::Handle::try_current() else { + return false; + }; + let deadline = Instant::now() + PENDING_FLUSH_DELAY; + let mut timer = Box::pin(tokio::time::sleep_until(deadline)); + // Polling a fresh sleep registers the waker, and it cannot be ready at once. + if timer.as_mut().poll(cx).is_ready() { + return false; + } + self.deadline = Some(deadline); + self.timer = Some(timer); + self.timer_runtime = Some(runtime.id()); + true + } +} + +/// The runtime that would own a timer armed by the current poll, if there is one. +fn current_runtime_id() -> Option { + tokio::runtime::Handle::try_current() + .ok() + .map(|handle| handle.id()) +} + +struct PackStream { + source: Option, + schema: Arc, + labels: FrameLabelMode, + batches: PackBatches, + ordering: SeriesOrdering, + validator: SequenceValidator, + pending: PendingFlush, +} + +impl PackStream { + /// Releases the source and drops every buffered owner, leaving the stream terminal. + fn finish(&mut self) { + self.source = None; + self.batches.release(); + self.validator = SequenceValidator::new(self.ordering); + self.pending.disarm(); + } + + /// Publishes the rows buffered so far, or returns to waiting on the source when there are none. + fn publish_buffered(&mut self) -> Poll>> { + match self.batches.flush() { + Ok(Some(batch)) => { + self.pending.flushed(); + self.batches.declare(batch) + } + Ok(None) => { + // Nothing to publish, so the pending source stays the only wakeup. + self.pending.flushed(); + Poll::Pending + } + Err(error) => { + self.finish(); + Poll::Ready(Some(Err(codec_error(error)))) + } + } + } + + /// Decides what a pending source yields once its own waker is registered. + /// + /// The first buffered pending still publishes at once, keeping the first-batch latency of a + /// source that delivers one chunk at a time; every later pending period hands the decision to + /// the deadline or to the builder filling up, when the stream's [`PendingBatching`] allows a + /// deadline at all. + fn poll_pending( + &mut self, + cx: &mut Context<'_>, + ) -> Poll>> { + if !self.pending.first_flushed { + return match self.batches.flush() { + Ok(Some(batch)) => { + self.pending.first_flushed = true; + self.pending.flushed(); + self.batches.declare(batch) + } + // Nothing is buffered, so the first buffered pending is still to come. + Ok(None) => Poll::Pending, + Err(error) => { + self.finish(); + Poll::Ready(Some(Err(codec_error(error)))) + } + }; + } + if self.pending.arm(cx) { + return Poll::Pending; + } + // Either nothing is buffered here, or this stream may not wait for a deadline where it is + // polled, so publishing now is the only bounded choice. + self.publish_buffered() + } +} + +impl Stream for PackStream { + type Item = datafusion_common::Result; + + fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + let this = &mut *self; + loop { + // The deadline is checked before the source is read again: rows it already promised to + // publish are not postponed by a source that keeps waking, and polling the timer here is + // what keeps this stream's waker registered with the runtime. + if this.pending.elapsed(cx) { + match this.batches.flush() { + Ok(Some(batch)) => { + this.pending.flushed(); + return this.batches.declare(batch); + } + // The deadline was armed on rows that the builder already published, so reading + // the source again is what the buffered estimate allows. + Ok(None) => this.pending.flushed(), + Err(error) => { + this.finish(); + return Poll::Ready(Some(Err(codec_error(error)))); + } + } + } + match this.batches.advance() { + Ok(Some(batch)) => return this.batches.declare(batch), + Ok(None) => {} + Err(error) => { + this.finish(); + return Poll::Ready(Some(Err(codec_error(error)))); + } + } + let polled = match this.source.as_mut() { + Some(source) => source.as_mut().poll_next(cx), + None => return Poll::Ready(None), + }; + match polled { + // The source registered its waker above, so a later chunk, EOF, or error still wakes + // this stream even while the buffered rows wait for the deadline. + Poll::Pending => return this.poll_pending(cx), + Poll::Ready(None) => { + if let Err(error) = this.validator.finish() { + this.finish(); + return Poll::Ready(Some(Err(error))); + } + let flushed = this.batches.flush(); + // The declared schema is read before the release below, so the last batch is + // published under the same schema as every batch before it. + let declared = this.batches.frame_schema.clone(); + this.finish(); + return match flushed { + Ok(Some(batch)) => { + match DfRecordBatch::try_new(declared, batch.columns().to_vec()) { + Ok(batch) => Poll::Ready(Some(Ok(batch))), + Err(error) => Poll::Ready(Some(Err(DataFusionError::from(error)))), + } + } + Ok(None) => Poll::Ready(None), + Err(error) => Poll::Ready(Some(Err(codec_error(error)))), + }; + } + Poll::Ready(Some(Err(error))) => { + this.finish(); + return Poll::Ready(Some(Err(upstream_error(error)))); + } + Poll::Ready(Some(Ok(chunk))) => { + if let Err(error) = this.validator.validate(&chunk) { + this.finish(); + return Poll::Ready(Some(Err(error))); + } + match SeriesFrameCursor::try_new_raw(&this.schema, this.labels, chunk) { + Ok(cursor) => { + this.batches.install(cursor); + this.pending.installed(); + } + Err(error) => { + this.finish(); + return Poll::Ready(Some(Err(codec_error(error)))); + } + } + } + } + } + } +} + +impl datafusion::physical_plan::RecordBatchStream for PackStream { + fn schema(&self) -> ArrowSchemaRef { + self.batches.frame_schema.clone() + } +} + +/// The pack stream of [`pack_aggregate_state`]. +struct PackStateStream { + source: Option, + state: Arc, + schema: Arc, + batches: PackBatches, +} + +impl PackStateStream { + fn finish(&mut self) { + self.source = None; + self.batches.release(); + } +} + +impl Stream for PackStateStream { + type Item = datafusion_common::Result; + + fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + let this = &mut *self; + loop { + match this.batches.advance() { + Ok(Some(batch)) => return this.batches.declare(batch), + Ok(None) => {} + Err(error) => { + this.finish(); + return Poll::Ready(Some(Err(codec_error(error)))); + } + } + let polled = match this.source.as_mut() { + Some(source) => source.as_mut().poll_next(cx), + None => return Poll::Ready(None), + }; + match polled { + Poll::Pending => { + return match this.batches.flush() { + Ok(Some(batch)) => this.batches.declare(batch), + Ok(None) => Poll::Pending, + Err(error) => { + this.finish(); + Poll::Ready(Some(Err(codec_error(error)))) + } + }; + } + Poll::Ready(None) => { + let flushed = this.batches.flush(); + let declared = this.batches.frame_schema.clone(); + this.finish(); + return match flushed { + Ok(Some(batch)) => { + match DfRecordBatch::try_new(declared, batch.columns().to_vec()) { + Ok(batch) => Poll::Ready(Some(Ok(batch))), + Err(error) => Poll::Ready(Some(Err(DataFusionError::from(error)))), + } + } + Ok(None) => Poll::Ready(None), + Err(error) => Poll::Ready(Some(Err(codec_error(error)))), + }; + } + Poll::Ready(Some(Err(error))) => { + this.finish(); + return Poll::Ready(Some(Err(upstream_error(error)))); + } + Poll::Ready(Some(Ok((series, is_last)))) => { + match SeriesFrameCursor::try_new_aggregate_state( + &this.state, + &this.schema, + series, + is_last, + ) { + Ok(cursor) => this.batches.install(cursor), + Err(error) => { + this.finish(); + return Poll::Ready(Some(Err(codec_error(error)))); + } + } + } + } + } + } +} + +impl datafusion::physical_plan::RecordBatchStream for PackStateStream { + fn schema(&self) -> ArrowSchemaRef { + self.batches.frame_schema.clone() + } +} + +/// The unpack stream of [`unpack_aggregate_state`]. +struct UnpackStateStream { + source: Option, + frame_schema: ArrowSchemaRef, + pending: std::vec::IntoIter, + decoder: SeriesFrameDecoder, +} + +impl UnpackStateStream { + fn finish(&mut self) { + self.source = None; + self.pending = Vec::new().into_iter(); + } +} + +impl Stream for UnpackStateStream { + type Item = Result; + + fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + let this = &mut *self; + let mut empty_batches = 0; + loop { + if let Some(row) = this.pending.next() { + return Poll::Ready(Some(Ok(row))); + } + let polled = match this.source.as_mut() { + Some(source) => source.as_mut().poll_next(cx), + None => return Poll::Ready(None), + }; + match polled { + Poll::Pending => return Poll::Pending, + Poll::Ready(None) => { + this.finish(); + return Poll::Ready(None); + } + Poll::Ready(Some(Err(error))) => { + this.finish(); + return Poll::Ready(Some(Err(BoxedError::new( + crate::error::Error::GeneralDataFusion { + error, + location: snafu::Location::default(), + }, + )))); + } + Poll::Ready(Some(Ok(batch))) => { + let result = if batch.schema() != this.frame_schema { + Err(invalid("aggregate state frame schema mismatch")) + } else { + this.decoder + .decode_aggregate_state(&batch) + .map_err(codec_error) + }; + match result { + Ok(rows) if rows.is_empty() => { + empty_batches += 1; + if empty_batches == MAX_EMPTY_BATCHES_PER_POLL { + cx.waker().wake_by_ref(); + return Poll::Pending; + } + } + Ok(rows) => this.pending = rows.into_iter(), + Err(error) => { + this.finish(); + return Poll::Ready(Some(Err(unpack_error(error)))); + } + } + } + } + } + } +} + +/// The pack stream of [`pack_evaluated_series`]. +struct PackEvaluatedStream { + source: Option, + schema: Arc, + batches: PackBatches, + validator: EvaluatedSequenceValidator, +} + +impl PackEvaluatedStream { + /// Releases the source and drops every buffered owner, leaving the stream terminal. + fn finish(&mut self) { + self.source = None; + self.batches.release(); + self.validator = EvaluatedSequenceValidator::new(); + } +} + +impl Stream for PackEvaluatedStream { + type Item = datafusion_common::Result; + + fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + let this = &mut *self; + loop { + match this.batches.advance() { + Ok(Some(batch)) => return this.batches.declare(batch), + Ok(None) => {} + Err(error) => { + this.finish(); + return Poll::Ready(Some(Err(codec_error(error)))); + } + } + let polled = match this.source.as_mut() { + Some(source) => source.as_mut().poll_next(cx), + None => return Poll::Ready(None), + }; + match polled { + Poll::Pending => { + let flushed = this.batches.flush(); + return match flushed { + Ok(Some(batch)) => this.batches.declare(batch), + Ok(None) => Poll::Pending, + Err(error) => { + this.finish(); + Poll::Ready(Some(Err(codec_error(error)))) + } + }; + } + Poll::Ready(None) => { + if let Err(error) = this.validator.finish() { + this.finish(); + return Poll::Ready(Some(Err(error))); + } + let flushed = this.batches.flush(); + // The declared schema is read before the release below, so the last batch is + // published under the same schema as every batch before it. + let declared = this.batches.frame_schema.clone(); + this.finish(); + return match flushed { + Ok(Some(batch)) => { + match DfRecordBatch::try_new(declared, batch.columns().to_vec()) { + Ok(batch) => Poll::Ready(Some(Ok(batch))), + Err(error) => Poll::Ready(Some(Err(DataFusionError::from(error)))), + } + } + Ok(None) => Poll::Ready(None), + Err(error) => Poll::Ready(Some(Err(codec_error(error)))), + }; + } + Poll::Ready(Some(Err(error))) => { + this.finish(); + return Poll::Ready(Some(Err(upstream_error(error)))); + } + Poll::Ready(Some(Ok((series, is_last)))) => { + if let Err(error) = this.validator.validate(&series, is_last) { + this.finish(); + return Poll::Ready(Some(Err(error))); + } + match SeriesFrameCursor::try_new_evaluated(&this.schema, series, is_last) { + Ok(cursor) => this.batches.install(cursor), + Err(error) => { + this.finish(); + return Poll::Ready(Some(Err(codec_error(error)))); + } + } + } + } + } + } +} + +impl datafusion::physical_plan::RecordBatchStream for PackEvaluatedStream { + fn schema(&self) -> ArrowSchemaRef { + self.batches.frame_schema.clone() + } +} + +struct UnpackStream { + source: Option, + schema: Arc, + frame_schema: ArrowSchemaRef, + /// The description parsed from the frame schema; the only input decoding needs. + label_decode_spec: Option, + ordering: SeriesOrdering, + validator: SequenceValidator, + pending: std::vec::IntoIter, + decoder: SeriesFrameDecoder, +} + +impl RawSeriesStream for UnpackStream { + fn schema(&self) -> &Arc { + &self.schema + } + + /// Returns [`NO_BOUND_LABEL_SOURCE`]: a frame establishes its own label layout and carries no + /// scan-bound identity, so decoding reads [`Self::label_decode_spec`] and never this. There is + /// no physical region key layout to report and none is invented from the description, which + /// deliberately carries no region metadata. + fn label_source(&self) -> &RawLabelSource { + &NO_BOUND_LABEL_SOURCE + } + + /// Returns the label decode description the frame declared, which is what decoding reads; an + /// explicit-label frame declares none. + fn label_decode_spec(&self) -> Option<&LabelDecodeSpec> { + self.label_decode_spec.as_ref() + } + + fn ordering(&self) -> SeriesOrdering { + self.ordering + } +} + +impl UnpackStream { + fn finish(&mut self) { + self.source = None; + self.pending = Vec::new().into_iter(); + self.validator = SequenceValidator::new(self.ordering); + } +} + +impl Stream for UnpackStream { + type Item = Result; + + fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + let this = &mut *self; + let mut empty_batches = 0; + loop { + if let Some(chunk) = this.pending.next() { + return Poll::Ready(Some(Ok(chunk))); + } + let polled = match this.source.as_mut() { + Some(source) => source.as_mut().poll_next(cx), + None => return Poll::Ready(None), + }; + match polled { + Poll::Pending => return Poll::Pending, + Poll::Ready(None) => { + let result = this.validator.finish(); + this.finish(); + return Poll::Ready(result.err().map(|error| Err(unpack_error(error)))); + } + Poll::Ready(Some(Err(error))) => { + this.finish(); + return Poll::Ready(Some(Err(BoxedError::new( + crate::error::Error::GeneralDataFusion { + error, + location: snafu::Location::default(), + }, + )))); + } + Poll::Ready(Some(Ok(batch))) => { + let result = (|| { + if batch.schema() != this.frame_schema { + return Err(invalid("raw frame schema mismatch")); + } + this.decoder + .decode_raw(&batch) + .map_err(codec_error) + .and_then(|chunks| { + for chunk in &chunks { + this.validator.validate(chunk)?; + } + Ok(chunks) + }) + })(); + match result { + Ok(chunks) => { + if chunks.is_empty() { + empty_batches += 1; + if empty_batches == MAX_EMPTY_BATCHES_PER_POLL { + cx.waker().wake_by_ref(); + return Poll::Pending; + } + } else { + this.pending = chunks.into_iter(); + } + } + Err(error) => { + this.finish(); + return Poll::Ready(Some(Err(unpack_error(error)))); + } + } + } + } + } + } +} + +/// The unpack stream of [`unpack_evaluated_series`]. +struct UnpackEvaluatedStream { + source: Option, + frame_schema: ArrowSchemaRef, + validator: EvaluatedSequenceValidator, + pending: std::vec::IntoIter<(Series, bool)>, + decoder: SeriesFrameDecoder, +} + +impl UnpackEvaluatedStream { + fn finish(&mut self) { + self.source = None; + self.pending = Vec::new().into_iter(); + self.validator = EvaluatedSequenceValidator::new(); + } +} + +impl Stream for UnpackEvaluatedStream { + type Item = Result<(Series, bool), BoxedError>; + + fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + let this = &mut *self; + let mut empty_batches = 0; + loop { + if let Some(chunk) = this.pending.next() { + return Poll::Ready(Some(Ok(chunk))); + } + let polled = match this.source.as_mut() { + Some(source) => source.as_mut().poll_next(cx), + None => return Poll::Ready(None), + }; + match polled { + Poll::Pending => return Poll::Pending, + Poll::Ready(None) => { + let result = this.validator.finish(); + this.finish(); + return Poll::Ready(result.err().map(|error| Err(unpack_error(error)))); + } + Poll::Ready(Some(Err(error))) => { + this.finish(); + return Poll::Ready(Some(Err(BoxedError::new( + crate::error::Error::GeneralDataFusion { + error, + location: snafu::Location::default(), + }, + )))); + } + Poll::Ready(Some(Ok(batch))) => { + let result = (|| { + if batch.schema() != this.frame_schema { + return Err(invalid("evaluated frame schema mismatch")); + } + this.decoder + .decode_evaluated(&batch) + .map_err(codec_error) + .and_then(|chunks| { + for (series, is_last) in &chunks { + this.validator.validate(series, *is_last)?; + } + Ok(chunks) + }) + })(); + match result { + Ok(chunks) => { + if chunks.is_empty() { + empty_batches += 1; + if empty_batches == MAX_EMPTY_BATCHES_PER_POLL { + cx.waker().wake_by_ref(); + return Poll::Pending; + } + } else { + this.pending = chunks.into_iter(); + } + } + Err(error) => { + this.finish(); + return Poll::Ready(Some(Err(unpack_error(error)))); + } + } + } + } + } + } +} + +/// How many empty batches one poll reads before yielding, so a stream of them cannot hold the task. +const MAX_EMPTY_BATCHES_PER_POLL: usize = 32; + +/// Wraps a decode or validation error as the boxed error an unpack stream reports. +fn unpack_error(error: DataFusionError) -> BoxedError { + BoxedError::new(crate::error::Error::GeneralDataFusion { + error, + location: snafu::Location::default(), + }) +} diff --git a/src/common/query/src/series_frame/tests.rs b/src/common/query/src/series_frame/tests.rs new file mode 100644 index 00000000000..e1e6b2c5e95 --- /dev/null +++ b/src/common/query/src/series_frame/tests.rs @@ -0,0 +1,4303 @@ +// 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. + +mod evaluated; +mod lifecycle; +mod state; + +use std::collections::{HashMap, VecDeque}; +use std::io::Cursor; +use std::pin::Pin; +use std::sync::Arc; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::task::{Context, Poll, Wake, Waker}; + +use common_error::ext::{BoxedError, PlainError}; +use common_error::status_code::StatusCode; +use common_recordbatch::DfSendableRecordBatchStream; +use datafusion::physical_plan::RecordBatchStream; +use datatypes::arrow::array::{Array, Float64Array, UInt32Array}; +use datatypes::arrow::buffer::{Buffer, ScalarBuffer}; +use datatypes::arrow::compute::concat_batches; +use datatypes::arrow::datatypes::{DataType, Schema, SchemaRef}; +use datatypes::arrow::ipc::{reader::StreamReader, writer::StreamWriter}; +use datatypes::arrow::record_batch::RecordBatch; +use datatypes::series::Label; +use datatypes::series::SeriesLabels; +use datatypes::series::SeriesOrdering; +use datatypes::series::frame::{ + FrameLabelMode, LabelDecodeSpec, raw_series_frame_schema, series_frame_schema, +}; +use datatypes::series::histogram::{BucketSideView, CounterResetHint, HistogramBatchBuilder}; +use datatypes::series::raw::{RawSeriesChunk, RawTimestamps}; +use datatypes::series::samples::{ + DenseSamplesRef, FieldSpec, SampleRef, Samples, SeriesFields, SeriesSchema, +}; +use futures_util::{Stream, StreamExt}; +use store_api::region_engine::{ + BoundTag, RawLabelSource, RawSeriesStream, SendableRawSeriesStream, +}; +use tokio::sync::mpsc::UnboundedSender; + +use super::{ + PENDING_FLUSH_DELAY, PendingBatching, ensure_frame_matches_label_source, label_decode_spec, + pack_raw_series, pack_raw_series_with, series_frame_ordering, unpack_raw_series, +}; + +/// One item of a raw series source. +type RawItem = Result; + +fn schema() -> Arc { + Arc::new(SeriesSchema { + fields: vec![FieldSpec { + name: Arc::from("value"), + }] + .into(), + eval_grid: None, + }) +} + +/// The one grid every evaluated fixture is addressed on: 512 positions, 1000 ms apart. +fn evaluated_grid() -> Arc { + Arc::new( + datatypes::series::time::EvalGrid::try_new( + datatypes::series::time::GridSpec::try_new(0, 1000, 512).unwrap(), + ) + .unwrap(), + ) +} + +/// A schema with one `value` field addressed on [`evaluated_grid`], which is what makes it an +/// evaluated declaration. +fn evaluated_schema() -> Arc { + Arc::new(SeriesSchema { + fields: vec![FieldSpec { + name: Arc::from("value"), + }] + .into(), + eval_grid: Some(evaluated_grid()), + }) +} +fn metric() -> SeriesLabels { + SeriesLabels::try_new(Some(Arc::from("cpu")), vec![]).unwrap() +} +fn labeled_metric(host: &str) -> SeriesLabels { + SeriesLabels::try_new( + Some(Arc::from("cpu")), + vec![Label { + name: Arc::from("host"), + value: Arc::from(host), + }], + ) + .unwrap() +} +fn chunk_with( + key: &[u8], + times: &[i64], + values: Vec>, + metric: Option, + last: bool, +) -> RawSeriesChunk { + RawSeriesChunk::try_new( + &schema(), + Buffer::from(key.to_vec()), + metric, + RawTimestamps::try_new(ScalarBuffer::from(times.to_vec())).unwrap(), + SeriesFields::one(Samples::from_float(Float64Array::from(values))), + last, + ) + .unwrap() +} +fn chunk(key: &[u8], times: &[i64], last: bool) -> RawSeriesChunk { + chunk_with( + key, + times, + times.iter().map(|t| Some(*t as f64)).collect(), + Some(metric()), + last, + ) +} + +#[derive(Debug)] +struct RawMock { + schema: Arc, + items: VecDeque>, + binding: RawLabelSource, + /// The description this fixture declares, derived once from `binding`. + label_decode_spec: Option, + ordering: SeriesOrdering, + polls: Arc, + drops: Arc, + /// After this many rows were returned, the next poll reports `Pending` once and wakes the + /// task. `None` keeps the source always ready. + pending_after: Option, + pending_reported: bool, + /// Fails instead of polling, proving a constructor rejected the source before any poll. + panic_on_poll: bool, + emitted: usize, +} +impl Drop for RawMock { + fn drop(&mut self) { + self.drops.fetch_add(1, Ordering::SeqCst); + } +} +impl Stream for RawMock { + type Item = Result; + fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + assert!( + !self.panic_on_poll, + "a source rejected before polling must never be polled" + ); + self.polls.fetch_add(1, Ordering::SeqCst); + if !self.pending_reported && self.pending_after == Some(self.emitted) { + self.pending_reported = true; + cx.waker().wake_by_ref(); + return Poll::Pending; + } + let item = self.items.pop_front(); + if item.is_some() { + self.emitted += 1; + } + Poll::Ready(item) + } +} +impl RawSeriesStream for RawMock { + fn schema(&self) -> &Arc { + &self.schema + } + fn label_source(&self) -> &RawLabelSource { + &self.binding + } + fn label_decode_spec(&self) -> Option<&LabelDecodeSpec> { + self.label_decode_spec.as_ref() + } + fn ordering(&self) -> SeriesOrdering { + self.ordering + } +} +struct DfMock { + schema: SchemaRef, + items: VecDeque>, + polls: Arc, + drops: Arc, + /// After this many batches were returned, the next poll reports `Pending` once and wakes + /// the task. `None` keeps the source always ready. + pending_after: Option, + pending_reported: bool, + /// Fails instead of polling, proving a constructor rejected the source before any poll. + panic_on_poll: bool, + emitted: usize, +} +impl Drop for DfMock { + fn drop(&mut self) { + self.drops.fetch_add(1, Ordering::SeqCst); + } +} +impl Stream for DfMock { + type Item = datafusion_common::Result; + fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + assert!( + !self.panic_on_poll, + "a source rejected before polling must never be polled" + ); + self.polls.fetch_add(1, Ordering::SeqCst); + if !self.pending_reported && self.pending_after == Some(self.emitted) { + self.pending_reported = true; + cx.waker().wake_by_ref(); + return Poll::Pending; + } + let item = self.items.pop_front(); + if item.is_some() { + self.emitted += 1; + } + Poll::Ready(item) + } +} +impl RecordBatchStream for DfMock { + fn schema(&self) -> SchemaRef { + self.schema.clone() + } +} +fn raw( + items: Vec, + ordering: SeriesOrdering, +) -> (SendableRawSeriesStream, Arc, Arc) { + raw_items( + items.into_iter().map(Ok).collect(), + schema(), + RawLabelSource::Explicit, + ordering, + None, + ) +} +fn raw_pending( + items: Vec, + ordering: SeriesOrdering, + pending_after: usize, +) -> (SendableRawSeriesStream, Arc, Arc) { + raw_items( + items.into_iter().map(Ok).collect(), + schema(), + RawLabelSource::Explicit, + ordering, + Some(pending_after), + ) +} +fn raw_custom( + items: Vec, + ordering: SeriesOrdering, + binding: RawLabelSource, +) -> (SendableRawSeriesStream, Arc, Arc) { + raw_items( + items.into_iter().map(Ok).collect(), + schema(), + binding, + ordering, + None, + ) +} +fn raw_never_polled( + ordering: SeriesOrdering, +) -> (SendableRawSeriesStream, Arc, Arc) { + let polls = Arc::new(AtomicUsize::new(0)); + let drops = Arc::new(AtomicUsize::new(0)); + ( + Box::pin(RawMock { + schema: schema(), + items: VecDeque::new(), + binding: RawLabelSource::Explicit, + label_decode_spec: None, + ordering, + polls: polls.clone(), + drops: drops.clone(), + pending_after: None, + pending_reported: false, + panic_on_poll: true, + emitted: 0, + }), + polls, + drops, + ) +} +fn raw_items( + items: Vec>, + schema: Arc, + binding: RawLabelSource, + ordering: SeriesOrdering, + pending_after: Option, +) -> (SendableRawSeriesStream, Arc, Arc) { + let polls = Arc::new(AtomicUsize::new(0)); + let drops = Arc::new(AtomicUsize::new(0)); + // A fixture holding a key binding declares the layout it encodes, like a real producer; a + // fixture with explicit labels already carries complete ones and declares none. + let label_decode_spec = label_decode_spec(&binding); + ( + Box::pin(RawMock { + schema, + items: items.into(), + binding, + label_decode_spec, + ordering, + polls: polls.clone(), + drops: drops.clone(), + pending_after, + pending_reported: false, + panic_on_poll: false, + emitted: 0, + }), + polls, + drops, + ) +} + +/// A raw source whose readiness the test drives: it yields the sent items, then reports `Pending` +/// without a wake of its own until the test sends more or drops the sender to signal EOF. Unlike +/// [`RawMock`] it can stall the stream any number of times, which is what the bounded pending +/// behavior needs. +struct RawChannel { + schema: Arc, + binding: RawLabelSource, + ordering: SeriesOrdering, + items: tokio::sync::mpsc::UnboundedReceiver, + polls: Arc, + drops: Arc, +} +impl Drop for RawChannel { + fn drop(&mut self) { + self.drops.fetch_add(1, Ordering::SeqCst); + } +} +impl Stream for RawChannel { + type Item = RawItem; + fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + let this = &mut *self; + this.polls.fetch_add(1, Ordering::SeqCst); + this.items.poll_recv(cx) + } +} +impl RawSeriesStream for RawChannel { + fn schema(&self) -> &Arc { + &self.schema + } + fn label_source(&self) -> &RawLabelSource { + &self.binding + } + fn label_decode_spec(&self) -> Option<&LabelDecodeSpec> { + None + } + fn ordering(&self) -> SeriesOrdering { + self.ordering + } +} +fn hand_driven_raw( + ordering: SeriesOrdering, +) -> ( + SendableRawSeriesStream, + UnboundedSender, + Arc, + Arc, +) { + let (tx, items) = tokio::sync::mpsc::unbounded_channel(); + let polls = Arc::new(AtomicUsize::new(0)); + let drops = Arc::new(AtomicUsize::new(0)); + ( + Box::pin(RawChannel { + schema: schema(), + binding: RawLabelSource::Explicit, + ordering, + items, + polls: polls.clone(), + drops: drops.clone(), + }), + tx, + polls, + drops, + ) +} +fn send(tx: &UnboundedSender, item: RawSeriesChunk) { + tx.send(Ok(item)).expect("the pack stream is still live"); +} + +fn df_source( + batches: Vec, + declared: SchemaRef, +) -> ( + DfSendableRecordBatchStream, + Arc, + Arc, +) { + df_items(batches.into_iter().map(Ok).collect(), declared, None) +} +fn df_pending( + batches: Vec, + declared: SchemaRef, + pending_after: usize, +) -> ( + DfSendableRecordBatchStream, + Arc, + Arc, +) { + df_items( + batches.into_iter().map(Ok).collect(), + declared, + Some(pending_after), + ) +} +fn df_never_polled( + declared: SchemaRef, +) -> ( + DfSendableRecordBatchStream, + Arc, + Arc, +) { + let polls = Arc::new(AtomicUsize::new(0)); + let drops = Arc::new(AtomicUsize::new(0)); + ( + Box::pin(DfMock { + schema: declared, + items: VecDeque::new(), + polls: polls.clone(), + drops: drops.clone(), + pending_after: None, + pending_reported: false, + panic_on_poll: true, + emitted: 0, + }), + polls, + drops, + ) +} +fn df_items( + items: Vec>, + declared: SchemaRef, + pending_after: Option, +) -> ( + DfSendableRecordBatchStream, + Arc, + Arc, +) { + let polls = Arc::new(AtomicUsize::new(0)); + let drops = Arc::new(AtomicUsize::new(0)); + ( + Box::pin(DfMock { + schema: declared, + items: items.into(), + polls: polls.clone(), + drops: drops.clone(), + pending_after, + pending_reported: false, + panic_on_poll: false, + emitted: 0, + }), + polls, + drops, + ) +} +async fn pack_all(input: SendableRawSeriesStream) -> Vec { + let mut stream = pack_raw_series(input).unwrap(); + let mut out = vec![]; + while let Some(v) = stream.next().await { + out.push(v.unwrap()); + } + out +} + +#[tokio::test] +async fn contiguous_adapter_does_not_certify_nonadjacent_recurrence() { + // A/B/A violates the producer's contiguous-key contract; adapters validate adjacent chunks + // only and preserve the supplied sequence rather than sorting, merging, or dropping rows. + let expected = [ + (b"a".as_slice(), 1, 11.0), + (b"b".as_slice(), 2, 22.0), + (b"a".as_slice(), 3, 33.0), + ]; + let input = expected + .iter() + .map(|(key, time, value)| { + chunk_with(key, &[*time], vec![Some(*value)], Some(metric()), true) + }) + .collect(); + let (source, _, _) = raw(input, SeriesOrdering::Contiguous); + let batches = pack_all(source).await; + assert_eq!(batches.len(), 1, "ready chunks coalesce into one batch"); + assert_eq!(batches[0].num_rows(), 3); + let frame_schema = batches[0].schema(); + let (source, _, _) = df_source(batches, frame_schema); + let mut decoded = unpack_raw_series(source, Some(schema())).unwrap(); + + for (key, time, value) in expected { + let actual = decoded.next().await.unwrap().unwrap(); + assert_chunk(&actual, key, &[time], &[Some(value)], true); + assert_metric(&actual, None); + } + assert!(decoded.next().await.is_none()); +} + +/// Raw Interleaved supports concatenated independently closed producer fragments, not a +/// merge: identical identities may recur with overlapping timestamps and different labels. +#[tokio::test] +async fn interleaved_closed_fragment_roundtrips() { + type Row = (&'static [u8], i64, bool, Option<&'static str>); + let cases: &[(&str, &[Row])] = &[ + ("empty", &[]), + ( + "adjacent_same_key_equal_time", + &[(b"a", 5, true, None), (b"a", 5, true, None)], + ), + ( + "adjacent_multichunk_reversed_time_and_labels", + &[ + (b"a", 10, false, Some("x")), + (b"a", 12, true, Some("x")), + (b"a", 2, false, Some("y")), + (b"a", 3, true, Some("y")), + ], + ), + ( + "nonadjacent_same_key_overlapping_time", + &[ + (b"a", 5, true, None), + (b"b", 8, true, None), + (b"a", 4, true, None), + ], + ), + ]; + for (name, rows) in cases { + // Pending forces a batch boundary inside the multichunk fragment, exercising state + // continuity both across batches and when several closed fragments share a batch. + let chunks = rows + .iter() + .map(|(key, time, last, host)| { + chunk_with( + key, + &[*time], + vec![Some(*time as f64)], + Some(host.map_or_else(metric, labeled_metric)), + *last, + ) + }) + .collect(); + let (input, _, _) = raw_pending(chunks, SeriesOrdering::Interleaved, 1); + let mut packed = pack_raw_series(input).unwrap(); + let declared = packed.schema(); + assert_eq!( + declared.metadata()["greptime.series.ordering"], + "interleaved", + "{name}" + ); + let mut batches = Vec::new(); + while let Some(batch) = packed.next().await { + let batch = batch.unwrap_or_else(|error| panic!("{name}: {error}")); + assert_eq!(batch.schema(), declared, "{name}"); + batches.push(batch); + } + let (input, _, _) = df_source(batches, declared); + let mut output = unpack_raw_series(input, Some(schema())).unwrap(); + assert_eq!(output.ordering(), SeriesOrdering::Interleaved, "{name}"); + for (key, time, last, host) in *rows { + let chunk = output.next().await.unwrap().unwrap(); + assert_chunk(&chunk, key, &[*time], &[Some(*time as f64)], *last); + assert_metric(&chunk, *host); + } + assert!(output.next().await.is_none(), "{name}"); + } +} + +/// The key-encoded form uses the same ordering and fragment-local finality as explicit labels. +#[tokio::test] +async fn interleaved_key_fragment_roundtrip() { + let binding = key_binding("cpu"); + let chunks = vec![ + chunk_with(b"key", &[4], vec![Some(4.0)], None, false), + chunk_with(b"key", &[5], vec![Some(5.0)], None, true), + chunk_with(b"key", &[1], vec![Some(1.0)], None, true), + ]; + let (input, _, _) = raw_custom(chunks, SeriesOrdering::Interleaved, binding.clone()); + let mut packed = pack_raw_series(input).unwrap(); + let declared = packed.schema(); + assert_eq!( + datatypes::series::frame::series_frame_label_decode(&declared).unwrap(), + label_decode_spec(&binding) + ); + let mut batches = Vec::new(); + while let Some(batch) = packed.next().await { + batches.push(batch.unwrap()); + } + let (input, _, _) = df_source(batches, declared); + let mut output = unpack_raw_series(input, Some(schema())).unwrap(); + assert_eq!(output.ordering(), SeriesOrdering::Interleaved); + for (time, last) in [(4, false), (5, true), (1, true)] { + let chunk = output.next().await.unwrap().unwrap(); + assert_chunk(&chunk, b"key", &[time], &[Some(time as f64)], last); + assert!(chunk.metric.is_none()); + } + assert!(output.next().await.is_none()); +} + +fn assert_metric(chunk: &RawSeriesChunk, host: Option<&str>) { + let actual = chunk + .metric + .as_ref() + .expect("explicit chunks retain metric"); + assert_eq!(actual.name(), Some("cpu")); + assert_eq!(actual.tags().len(), usize::from(host.is_some())); + if let Some(host) = host { + assert_eq!(actual.tags()[0].name.as_ref(), "host"); + assert_eq!(actual.tags()[0].value.as_ref(), host); + } +} + +fn assert_chunk( + actual: &RawSeriesChunk, + key: &[u8], + times: &[i64], + values: &[Option], + last: bool, +) { + assert_eq!(actual.primary_key.as_slice(), key); + assert_eq!( + (0..actual.time.len()) + .map(|i| actual.time.timestamp(i).unwrap()) + .collect::>(), + times + ); + assert_eq!(actual.is_last, last); + let arr = match actual.fields.as_slice()[0].dense().unwrap() { + datatypes::series::samples::DenseSamplesRef::Float(a) => a, + _ => panic!("expected float field"), + }; + assert_eq!(arr.len(), values.len()); + for (i, value) in values.iter().enumerate() { + assert_eq!(arr.is_valid(i), value.is_some()); + if let Some(value) = value { + assert_eq!(arr.value(i).to_bits(), value.to_bits()); + } + } +} + +#[tokio::test] +async fn roundtrip_explicit_unordered_contiguous_preserves_complete_chunk_contents() { + let chunks = vec![ + chunk_with( + b"complete-b", + &[1, 2], + vec![Some(-0.0), None], + Some(metric()), + false, + ), + chunk_with( + b"complete-b", + &[3], + vec![Some(f64::from_bits(0x7ff8_0000_0000_0042))], + Some(metric()), + true, + ), + chunk_with(b"complete-a", &[4], vec![Some(9.25)], Some(metric()), true), + ]; + let (input, polls, _) = raw(chunks, SeriesOrdering::Contiguous); + let mut packed = pack_raw_series(input).unwrap(); + assert_eq!(polls.load(Ordering::SeqCst), 0); + let frame_schema = packed.schema(); + let first = packed.next().await.unwrap().unwrap(); + assert_eq!( + first.num_rows(), + 3, + "three dense chunks coalesce into three frame rows, containing four positions" + ); + assert_eq!( + polls.load(Ordering::SeqCst), + 4, + "the complete batch is flushed once EOF is observed" + ); + assert!(packed.next().await.is_none()); + let batches = vec![first]; + let source: DfSendableRecordBatchStream = Box::pin(DfMock { + schema: frame_schema, + items: batches.into_iter().map(Ok).collect(), + polls: Arc::new(AtomicUsize::new(0)), + drops: Arc::new(AtomicUsize::new(0)), + pending_after: None, + pending_reported: false, + panic_on_poll: false, + emitted: 0, + }); + let mut output = unpack_raw_series(source, Some(schema())).unwrap(); + assert_chunk( + &output.next().await.unwrap().unwrap(), + b"complete-b", + &[1, 2], + &[Some(-0.0), None], + false, + ); + assert_chunk( + &output.next().await.unwrap().unwrap(), + b"complete-b", + &[3], + &[Some(f64::from_bits(0x7ff8_0000_0000_0042))], + true, + ); + assert_chunk( + &output.next().await.unwrap().unwrap(), + b"complete-a", + &[4], + &[Some(9.25)], + true, + ); + assert!(output.next().await.is_none()); +} + +#[tokio::test] +async fn key_then_time_valid_roundtrip() { + let (input, _, _) = raw( + vec![chunk(b"a", &[1], true), chunk(b"b", &[2], true)], + SeriesOrdering::KeyThenTime, + ); + let batches = pack_all(input).await; + assert_eq!(batches.len(), 1, "cross-chunk rows share one bounded batch"); + assert_eq!(batches[0].num_rows(), 2); + let frame_schema = batches[0].schema(); + let source: DfSendableRecordBatchStream = Box::pin(DfMock { + schema: frame_schema, + items: batches.into_iter().map(Ok).collect(), + polls: Arc::new(AtomicUsize::new(0)), + drops: Arc::new(AtomicUsize::new(0)), + pending_after: None, + pending_reported: false, + panic_on_poll: false, + emitted: 0, + }); + let mut out = unpack_raw_series(source, Some(schema())).unwrap(); + assert_chunk( + &out.next().await.unwrap().unwrap(), + b"a", + &[1], + &[Some(1.0)], + true, + ); + assert_chunk( + &out.next().await.unwrap().unwrap(), + b"b", + &[2], + &[Some(2.0)], + true, + ); + assert!(out.next().await.is_none()); +} + +#[tokio::test] +async fn invalid_sequence_reports_valid_prefix_then_one_terminal_error() { + struct Case { + name: &'static str, + items: Vec, + order: SeriesOrdering, + prefix: Vec<(&'static [u8], i64, bool, Option<&'static str>)>, + } + let cases = vec![ + Case { + name: "final_then_same_key", + items: vec![chunk(b"a", &[1], true), chunk(b"a", &[2], true)], + order: SeriesOrdering::Contiguous, + prefix: vec![(b"a", 1, true, None)], + }, + Case { + name: "key_then_time_final_then_same_key", + items: vec![chunk(b"a", &[1], true), chunk(b"a", &[2], true)], + order: SeriesOrdering::KeyThenTime, + prefix: vec![(b"a", 1, true, None)], + }, + Case { + name: "unfinished_then_new_key", + items: vec![chunk(b"a", &[1], false), chunk(b"b", &[2], true)], + order: SeriesOrdering::Contiguous, + prefix: vec![(b"a", 1, false, None)], + }, + Case { + name: "key_decrease_after_intervening_keys", + items: vec![ + chunk(b"a", &[1], true), + chunk(b"b", &[2], true), + chunk(b"a", &[3], true), + ], + order: SeriesOrdering::KeyThenTime, + prefix: vec![(b"a", 1, true, None), (b"b", 2, true, None)], + }, + Case { + name: "sorted_key_decrease", + items: vec![chunk(b"b", &[1], true), chunk(b"a", &[2], true)], + order: SeriesOrdering::KeyThenTime, + prefix: vec![(b"b", 1, true, None)], + }, + Case { + name: "timestamp_equal_across_chunks", + items: vec![chunk(b"a", &[2], false), chunk(b"a", &[2], true)], + order: SeriesOrdering::Contiguous, + prefix: vec![(b"a", 2, false, None)], + }, + Case { + name: "timestamp_decreases_across_chunks", + items: vec![chunk(b"a", &[3], false), chunk(b"a", &[2], true)], + order: SeriesOrdering::Contiguous, + prefix: vec![(b"a", 3, false, None)], + }, + Case { + name: "interleaved_multiplexed_open_chains", + items: vec![ + chunk(b"a", &[1], false), + chunk(b"b", &[2], true), + chunk(b"a", &[3], true), + ], + order: SeriesOrdering::Interleaved, + prefix: vec![(b"a", 1, false, None)], + }, + Case { + name: "interleaved_changed_key_before_open_fragment_closes", + items: vec![ + chunk(b"a", &[1], false), + chunk(b"b", &[2], false), + chunk(b"a", &[3], true), + ], + order: SeriesOrdering::Interleaved, + prefix: vec![(b"a", 1, false, None)], + }, + Case { + name: "interleaved_timestamp_equal_within_open_chain", + items: vec![chunk(b"a", &[2], false), chunk(b"a", &[2], true)], + order: SeriesOrdering::Interleaved, + prefix: vec![(b"a", 2, false, None)], + }, + Case { + name: "interleaved_timestamp_decreases_within_open_chain", + items: vec![chunk(b"a", &[3], false), chunk(b"a", &[2], true)], + order: SeriesOrdering::Interleaved, + prefix: vec![(b"a", 3, false, None)], + }, + Case { + name: "interleaved_metric_changes_within_open_chain", + items: vec![ + chunk_with( + b"a", + &[1], + vec![Some(1.0)], + Some(labeled_metric("x")), + false, + ), + chunk_with(b"a", &[2], vec![Some(2.0)], Some(labeled_metric("y")), true), + ], + order: SeriesOrdering::Interleaved, + prefix: vec![(b"a", 1, false, Some("x"))], + }, + Case { + name: "metric_changes_within_key", + items: vec![ + chunk_with( + b"a", + &[1], + vec![Some(1.0)], + Some(labeled_metric("x")), + false, + ), + chunk_with(b"a", &[2], vec![Some(2.0)], Some(labeled_metric("y")), true), + ], + order: SeriesOrdering::Contiguous, + prefix: vec![(b"a", 1, false, Some("x"))], + }, + ]; + for case in cases { + // The valid prefix is flushed by an upstream `Pending`, so the test observes both the + // retained rows and the single terminal error honestly under the batching builder. + let (input, _, _) = raw_pending(case.items.clone(), case.order, case.prefix.len()); + let mut s = pack_raw_series(input).unwrap(); + if !case.prefix.is_empty() { + let batch = s.next().await.unwrap().unwrap(); + assert_eq!(batch.num_rows(), case.prefix.len(), "{}", case.name); + let chunks = datatypes::series::frame::unpack_raw_series_frame( + &schema(), + datatypes::series::frame::FrameLabelMode::Explicit, + None, + &batch, + ) + .unwrap(); + assert_eq!(chunks.len(), case.prefix.len(), "{}", case.name); + for (chunk, prefix) in chunks.iter().zip(&case.prefix) { + let (key, time, last, host) = *prefix; + assert_chunk(chunk, key, &[time], &[Some(time as f64)], last); + assert_metric(chunk, host); + } + } + let err = s.next().await.unwrap().unwrap_err(); + assert_eq!( + crate::error::datafusion_status_code::(&err, None), + StatusCode::InvalidArguments, + "{}", + case.name + ); + assert!(s.next().await.is_none(), "{}", case.name); + + // Encode chunks independently, bypassing stream validation, to exercise unpack's + // own cross-frame state machine against precisely the same invalid sequence. + let mut frames = Vec::new(); + for item in &case.items { + frames.extend( + datatypes::series::frame::pack_raw_series_chunk( + &schema(), + datatypes::series::frame::FrameLabelMode::Explicit, + None, + item, + ) + .unwrap(), + ); + } + // The ordering is a property of the frame, so the frames must declare the case's one for + // unpack to validate the same sequence the producer rejected. + let frame_schema = super::raw_series_frame_schema_with_ordering( + &schema(), + &RawLabelSource::Explicit, + case.order, + ) + .unwrap(); + let frames = frames + .into_iter() + .map(|frame| { + RecordBatch::try_new(frame_schema.clone(), frame.columns().to_vec()).unwrap() + }) + .collect(); + let (source, _, _) = df_source(frames, frame_schema); + let mut decoded = unpack_raw_series(source, Some(schema())).unwrap(); + for (key, time, last, host) in &case.prefix { + let chunk = decoded.next().await.unwrap().unwrap(); + assert_chunk(&chunk, key, &[*time], &[Some(*time as f64)], *last); + assert_metric(&chunk, *host); + } + let error = decoded.next().await.unwrap().unwrap_err(); + assert_eq!( + common_error::ext::ErrorExt::status_code(&error), + StatusCode::InvalidArguments + ); + assert!(decoded.next().await.is_none()); + } + // The unpack side of a non-final stream: the row arrives with `is_last` false and the + // missing final key is reported once, at EOF. + let frame = datatypes::series::frame::pack_raw_series_chunk( + &schema(), + datatypes::series::frame::FrameLabelMode::Explicit, + None, + &chunk(b"unfinished", &[7], false), + ) + .unwrap(); + let frame_schema = frame[0].schema(); + let (source, _, _) = df_source(frame, frame_schema); + let mut decoded = unpack_raw_series(source, Some(schema())).unwrap(); + let first = decoded.next().await.unwrap().unwrap(); + assert_chunk(&first, b"unfinished", &[7], &[Some(7.0)], false); + assert_eq!( + common_error::ext::ErrorExt::status_code(&decoded.next().await.unwrap().unwrap_err()), + StatusCode::InvalidArguments + ); + assert!(decoded.next().await.is_none()); +} + +/// Once a closed fragment is followed by an open one, EOF must still report the latter on both +/// paths; closing the previous fragment must not erase the new fragment's state. +#[tokio::test] +async fn interleaved_unfinished_fragment_at_eof_is_rejected() { + let rows = vec![chunk(b"a", &[10], true), chunk(b"a", &[1], false)]; + let (input, _, _) = raw_pending(rows.clone(), SeriesOrdering::Interleaved, 1); + let mut packed = pack_raw_series(input).unwrap(); + let prefix = packed.next().await.unwrap().unwrap(); + assert_eq!(prefix.num_rows(), 1); + let error = packed.next().await.unwrap().unwrap_err(); + assert_eq!( + crate::error::datafusion_status_code::(&error, None), + StatusCode::InvalidArguments + ); + assert!(error.to_string().contains("ended before key was final")); + assert!(packed.next().await.is_none()); + + let frame_schema = super::raw_series_frame_schema_with_ordering( + &schema(), + &RawLabelSource::Explicit, + SeriesOrdering::Interleaved, + ) + .unwrap(); + let mut frames = Vec::new(); + for row in &rows { + for frame in datatypes::series::frame::pack_raw_series_chunk( + &schema(), + FrameLabelMode::Explicit, + None, + row, + ) + .unwrap() + { + frames.push( + RecordBatch::try_new(frame_schema.clone(), frame.columns().to_vec()).unwrap(), + ); + } + } + let (source, _, _) = df_source(frames, frame_schema); + let mut decoded = unpack_raw_series(source, Some(schema())).unwrap(); + for (time, last) in [(10, true), (1, false)] { + let chunk = decoded.next().await.unwrap().unwrap(); + assert_chunk(&chunk, b"a", &[time], &[Some(time as f64)], last); + } + let error = decoded.next().await.unwrap().unwrap_err(); + assert_eq!( + common_error::ext::ErrorExt::status_code(&error), + StatusCode::InvalidArguments + ); + assert!(error.to_string().contains("ended before key was final")); + assert!(decoded.next().await.is_none()); +} + +/// EOF before a non-final key is an error: buffered rows are not reported as a partial success. +#[tokio::test] +async fn pack_rejects_nonfinal_eof_without_buffered_partial_success() { + let (input, polls, _) = raw( + vec![chunk_with( + b"unfinished", + &[1, 2], + vec![Some(1.0), Some(2.0)], + Some(metric()), + false, + )], + SeriesOrdering::Contiguous, + ); + let mut packed = pack_raw_series(input).unwrap(); + let error = packed.next().await.unwrap().unwrap_err(); + assert_eq!( + crate::error::datafusion_status_code::(&error, None), + StatusCode::InvalidArguments + ); + assert!( + packed.next().await.is_none(), + "the buffered rows are discarded, never emitted as a successful batch" + ); + assert_eq!( + polls.load(Ordering::SeqCst), + 2, + "the row was buffered, then EOF rejected the missing final key" + ); +} + +fn primary_binding(metadata: store_api::metadata::RegionMetadataRef) -> RawLabelSource { + RawLabelSource::PrimaryKey { + metric_name: Arc::from("cpu"), + physical_metadata: metadata, + logical_tags: Arc::from([BoundTag { + column_id: 0, + name: Arc::from("host"), + }]), + } +} + +/// A key frame states its whole label layout, so unpacking keeps exactly that description and no +/// binding: the description is what a consumer decodes from, and the physical region metadata the +/// producer read under never reaches the receiver. +#[tokio::test] +async fn the_declared_description_is_retained_and_no_binding_is_invented() { + use api::v1::SemanticType; + use datatypes::schema::ColumnSchema; + use store_api::metadata::{ColumnMetadata, RegionMetadataBuilder}; + use store_api::storage::RegionId; + let mut builder = RegionMetadataBuilder::new(RegionId::new(1, 1)); + builder + .push_column_metadata(ColumnMetadata { + column_schema: ColumnSchema::new( + "host", + datatypes::data_type::ConcreteDataType::string_datatype(), + false, + ), + semantic_type: SemanticType::Tag, + column_id: 0, + }) + .push_column_metadata(ColumnMetadata { + column_schema: ColumnSchema::new( + "ts", + datatypes::data_type::ConcreteDataType::timestamp_millisecond_datatype(), + false, + ), + semantic_type: SemanticType::Timestamp, + column_id: 1, + }) + .primary_key(vec![0]); + let metadata = Arc::new(builder.build().unwrap()); + let binding = primary_binding(metadata.clone()); + let description = label_decode_spec(&binding).expect("a primary-key binding describes its key"); + let (input, _, _) = raw_custom( + vec![ + RawSeriesChunk::try_new( + &schema(), + Buffer::from(b"encoded-complete-key".to_vec()), + None, + RawTimestamps::try_new(ScalarBuffer::from(vec![1])).unwrap(), + SeriesFields::one(Samples::from_float(Float64Array::from(vec![Some(3.0)]))), + true, + ) + .unwrap(), + ], + SeriesOrdering::Contiguous, + binding.clone(), + ); + let mut packed = pack_raw_series(input).unwrap(); + let batch = packed.next().await.unwrap().unwrap(); + let source: DfSendableRecordBatchStream = Box::pin(DfMock { + schema: batch.schema(), + items: VecDeque::from([Ok(batch)]), + polls: Arc::new(AtomicUsize::new(0)), + drops: Arc::new(AtomicUsize::new(0)), + pending_after: None, + pending_reported: false, + panic_on_poll: false, + emitted: 0, + }); + let mut out = unpack_raw_series(source, None).unwrap(); + let decoded = out.next().await.unwrap().unwrap(); + assert_eq!(decoded.primary_key.as_slice(), b"encoded-complete-key"); + assert!(decoded.metric.is_none()); + assert_eq!( + out.label_decode_spec(), + Some(&description), + "the declaration is retained exactly as the frame states it" + ); + assert_eq!(description.metric_name, "cpu"); + assert_eq!(description.primary_key.len(), 1); + assert_eq!(description.primary_key[0].column_id, 0); + assert_eq!(description.primary_key[0].name, "host"); + assert_eq!(description.logical_tags.len(), 1); + assert_eq!(description.logical_tags[0].name, "host"); + assert!( + matches!(out.label_source(), RawLabelSource::Explicit), + "the physical region metadata the producer read under is not carried across the frame" + ); +} + +#[tokio::test] +async fn explicit_mode_rejects_key_payload_and_primary_mode_rejects_explicit_metric() { + let (input, _, _) = raw( + vec![ + RawSeriesChunk::try_new( + &schema(), + Buffer::from(b"a".to_vec()), + None, + RawTimestamps::try_new(ScalarBuffer::from(vec![1])).unwrap(), + SeriesFields::one(Samples::from_float(Float64Array::from(vec![Some(1.0)]))), + true, + ) + .unwrap(), + ], + SeriesOrdering::Contiguous, + ); + let mut s = pack_raw_series(input).unwrap(); + assert!(s.next().await.unwrap().is_err()); + assert!(s.next().await.is_none()); +} + +#[tokio::test] +async fn primary_key_mode_rejects_explicit_metric_payload() { + let mut builder = + store_api::metadata::RegionMetadataBuilder::new(store_api::storage::RegionId::new(1, 2)); + use api::v1::SemanticType; + use datatypes::schema::ColumnSchema; + use store_api::metadata::ColumnMetadata; + builder + .push_column_metadata(ColumnMetadata { + column_schema: ColumnSchema::new( + "host", + datatypes::data_type::ConcreteDataType::string_datatype(), + false, + ), + semantic_type: SemanticType::Tag, + column_id: 0, + }) + .push_column_metadata(ColumnMetadata { + column_schema: ColumnSchema::new( + "ts", + datatypes::data_type::ConcreteDataType::timestamp_millisecond_datatype(), + false, + ), + semantic_type: SemanticType::Timestamp, + column_id: 1, + }) + .primary_key(vec![0]); + let metadata = Arc::new(builder.build().unwrap()); + let (input, _, _) = raw_custom( + vec![chunk(b"a", &[1], true)], + SeriesOrdering::Contiguous, + primary_binding(metadata), + ); + let mut stream = pack_raw_series(input).unwrap(); + assert_eq!( + crate::error::datafusion_status_code::( + &stream.next().await.unwrap().unwrap_err(), + None, + ), + StatusCode::InvalidArguments + ); + assert!(stream.next().await.is_none()); +} + +#[tokio::test] +async fn explicit_metric_must_remain_stable_within_key() { + // The first row is flushed by `Pending` so the retained frame and the later violation are + // both observed under the batching builder. + let (input, polls, _) = raw_pending( + vec![ + chunk_with( + b"a", + &[1], + vec![Some(1.0)], + Some(labeled_metric("x")), + false, + ), + chunk_with(b"a", &[2], vec![Some(2.0)], Some(labeled_metric("y")), true), + ], + SeriesOrdering::Contiguous, + 1, + ); + let mut s = pack_raw_series(input).unwrap(); + let batch = s.next().await.unwrap().unwrap(); + assert_eq!(batch.num_rows(), 1); + assert_eq!( + polls.load(Ordering::SeqCst), + 2, + "the stable row is flushed at Pending before the second chunk is read" + ); + let chunks = datatypes::series::frame::unpack_raw_series_frame( + &schema(), + datatypes::series::frame::FrameLabelMode::Explicit, + None, + &batch, + ) + .unwrap(); + assert_chunk(&chunks[0], b"a", &[1], &[Some(1.0)], false); + assert_metric(&chunks[0], Some("x")); + let err = s.next().await.unwrap().unwrap_err(); + assert_eq!( + crate::error::datafusion_status_code::(&err, None), + StatusCode::InvalidArguments + ); + assert!(s.next().await.is_none()); +} + +#[tokio::test] +async fn locally_invalid_public_raw_chunk_is_rejected() { + let mut bad = chunk(b"a", &[1], true); + bad.fields = SeriesFields::one(Samples::from_float(Float64Array::from(vec![ + Some(1.0), + Some(2.0), + ]))); + let polls = Arc::new(AtomicUsize::new(0)); + let source = Box::pin(RawMock { + schema: schema(), + items: VecDeque::from([Ok(bad)]), + binding: RawLabelSource::Explicit, + label_decode_spec: None, + ordering: SeriesOrdering::Contiguous, + polls, + drops: Arc::new(AtomicUsize::new(0)), + pending_after: None, + pending_reported: false, + panic_on_poll: false, + emitted: 0, + }); + let mut s = pack_raw_series(source).unwrap(); + let err = s.next().await.unwrap().unwrap_err(); + assert_eq!( + crate::error::datafusion_status_code::(&err, None), + StatusCode::InvalidArguments + ); + assert!(s.next().await.is_none()); +} + +#[tokio::test] +async fn empty_streams_keep_self_describing_schema() { + let (input, _, _) = raw(vec![], SeriesOrdering::Contiguous); + let mut packed = pack_raw_series(input).unwrap(); + let frame_schema = packed.schema(); + assert_eq!( + frame_schema.field(0).name(), + "read_key", + "the wire column name is unchanged" + ); + assert!(packed.next().await.is_none()); + // A declared-but-empty stream is still validated against the expected schema before any + // poll, and then ends without producing rows. + let (source, polls, _) = df_source(vec![], frame_schema.clone()); + let mut unpacked = unpack_raw_series(source, Some(schema())).unwrap(); + assert_eq!(polls.load(Ordering::SeqCst), 0); + assert_eq!(unpacked.schema().fields.len(), 1); + assert_eq!(unpacked.schema().fields[0].name.as_ref(), "value"); + assert!(unpacked.next().await.is_none()); +} + +#[tokio::test] +async fn upstream_error_status_is_preserved_once_and_releases_source() { + for status in [StatusCode::RequestOutdated, StatusCode::Unsupported] { + let polls = Arc::new(AtomicUsize::new(0)); + let drops = Arc::new(AtomicUsize::new(0)); + let e = BoxedError::new(PlainError::new("upstream".into(), status)); + let source = Box::pin(RawMock { + schema: schema(), + items: VecDeque::from([Err(e)]), + binding: RawLabelSource::Explicit, + label_decode_spec: None, + ordering: SeriesOrdering::Contiguous, + polls: polls.clone(), + drops: drops.clone(), + pending_after: None, + pending_reported: false, + panic_on_poll: false, + emitted: 0, + }); + let mut packed = pack_raw_series(source).unwrap(); + let error = packed.next().await.unwrap().unwrap_err(); + assert_eq!( + crate::error::datafusion_status_code::(&error, None), + status + ); + assert!(packed.next().await.is_none()); + assert_eq!(polls.load(Ordering::SeqCst), 1); + assert_eq!(drops.load(Ordering::SeqCst), 1); + let batch_schema = datatypes::series::frame::raw_series_frame_schema( + &schema(), + datatypes::series::frame::FrameLabelMode::Explicit, + ) + .unwrap(); + let plain = PlainError::new("upstream df".into(), status); + let polls = Arc::new(AtomicUsize::new(0)); + let drops = Arc::new(AtomicUsize::new(0)); + let source: DfSendableRecordBatchStream = Box::pin(DfMock { + schema: batch_schema, + items: VecDeque::from([Err(datafusion_common::DataFusionError::External(Box::new( + BoxedError::new(plain), + )))]), + polls: polls.clone(), + drops: drops.clone(), + pending_after: None, + pending_reported: false, + panic_on_poll: false, + emitted: 0, + }); + let mut unpacked = unpack_raw_series(source, Some(schema())).unwrap(); + let error = unpacked.next().await.unwrap().unwrap_err(); + assert_eq!(common_error::ext::ErrorExt::status_code(&error), status); + assert!(unpacked.next().await.is_none()); + assert_eq!(polls.load(Ordering::SeqCst), 1); + assert_eq!(drops.load(Ordering::SeqCst), 1); + } +} + +#[tokio::test] +async fn dropping_adapter_releases_upstream_and_pending_item_is_resumed() { + let (input, polls, drops) = raw_pending( + vec![chunk(b"a", &[1], true), chunk(b"b", &[2], true)], + SeriesOrdering::Contiguous, + 1, + ); + let mut packed = pack_raw_series(input).unwrap(); + let first = packed.next().await.unwrap().unwrap(); + assert_eq!(first.num_rows(), 1); + assert_eq!( + polls.load(Ordering::SeqCst), + 2, + "the buffered row is flushed at Pending before the next item" + ); + let chunks = datatypes::series::frame::unpack_raw_series_frame( + &schema(), + datatypes::series::frame::FrameLabelMode::Explicit, + None, + &first, + ) + .unwrap(); + assert_chunk(&chunks[0], b"a", &[1], &[Some(1.0)], true); + let second = packed.next().await.unwrap().unwrap(); + assert_eq!(second.num_rows(), 1); + assert_eq!( + polls.load(Ordering::SeqCst), + 4, + "Pending is resumed and the remaining row is flushed at EOF" + ); + let chunks = datatypes::series::frame::unpack_raw_series_frame( + &schema(), + datatypes::series::frame::FrameLabelMode::Explicit, + None, + &second, + ) + .unwrap(); + assert_chunk(&chunks[0], b"b", &[2], &[Some(2.0)], true); + drop(packed); + assert_eq!(drops.load(Ordering::SeqCst), 1); +} + +#[tokio::test] +async fn unpack_rejects_mismatched_batch_schema_before_polling() { + let wrong = datatypes::arrow::datatypes::Schema::empty().into(); + let (source, polls, drops) = df_source(vec![], wrong); + assert!(unpack_raw_series(source, Some(schema())).is_err()); + assert_eq!(polls.load(Ordering::SeqCst), 0); + assert_eq!(drops.load(Ordering::SeqCst), 1); +} + +/// A schema with an evaluation grid is a legal *evaluated* frame declaration, so it is no longer a +/// reason to refuse a stream at construction; it is still no schema to carry *raw* chunks under, so +/// the first raw chunk is rejected instead of the stream. +#[tokio::test] +async fn grid_schema_is_legal_but_cannot_carry_a_raw_chunk() { + let mut grid_schema = (*schema()).clone(); + grid_schema.eval_grid = Some(Arc::new( + datatypes::series::time::EvalGrid::try_new( + datatypes::series::time::GridSpec::try_new(0, 10, 1).unwrap(), + ) + .unwrap(), + )); + let grid_schema = Arc::new(grid_schema); + + // An empty stream under a grid schema constructs: the declaration is legal and no row disagrees + // with it. + let polls = Arc::new(AtomicUsize::new(0)); + let source = Box::pin(RawMock { + schema: grid_schema.clone(), + items: VecDeque::new(), + binding: RawLabelSource::Explicit, + label_decode_spec: None, + ordering: SeriesOrdering::Contiguous, + polls: polls.clone(), + drops: Arc::new(AtomicUsize::new(0)), + pending_after: None, + pending_reported: false, + panic_on_poll: false, + emitted: 0, + }); + let mut packed = pack_raw_series(source).unwrap(); + assert!(packed.next().await.is_none()); + assert_eq!(polls.load(Ordering::SeqCst), 1); + + // A raw chunk cannot be addressed on a grid, so the chunk that arrives under this declaration is + // what fails. + let polls = Arc::new(AtomicUsize::new(0)); + let source = Box::pin(RawMock { + schema: grid_schema, + items: VecDeque::from([Ok(chunk(b"a", &[1], true))]), + binding: RawLabelSource::Explicit, + label_decode_spec: None, + ordering: SeriesOrdering::Contiguous, + polls: polls.clone(), + drops: Arc::new(AtomicUsize::new(0)), + pending_after: None, + pending_reported: false, + panic_on_poll: false, + emitted: 0, + }); + let mut packed = pack_raw_series(source).unwrap(); + let error = packed.next().await.unwrap().unwrap_err(); + assert_eq!( + crate::error::datafusion_status_code::(&error, None), + StatusCode::InvalidArguments + ); + assert!(packed.next().await.is_none()); +} + +#[tokio::test] +async fn unpack_batch_sequence_error_is_atomic_for_all_rows() { + let mut batches = Vec::new(); + // `KeyThenTime` is what makes a recurring key an error, so the frame has to declare it. + let frame_schema = super::raw_series_frame_schema_with_ordering( + &schema(), + &RawLabelSource::Explicit, + SeriesOrdering::KeyThenTime, + ) + .unwrap(); + for (key, time) in [ + (b"a".as_slice(), 1), + (b"b".as_slice(), 2), + (b"a".as_slice(), 3), + ] { + let (input, _, _) = raw(vec![chunk(key, &[time], true)], SeriesOrdering::KeyThenTime); + batches.extend(pack_all(input).await); + } + let multi = concat_batches(&frame_schema, &batches).unwrap(); + let (source, _, _) = df_source(vec![multi], frame_schema); + let mut unpacked = unpack_raw_series(source, Some(schema())).unwrap(); + assert!(unpacked.next().await.unwrap().is_err()); + assert!(unpacked.next().await.is_none()); +} + +#[tokio::test] +async fn unpack_rejects_late_invalid_frame_row_before_prefix() { + let frame_schema = datatypes::series::frame::raw_series_frame_schema( + &schema(), + datatypes::series::frame::FrameLabelMode::Explicit, + ) + .unwrap(); + let first = datatypes::series::frame::pack_raw_series_chunk( + &schema(), + datatypes::series::frame::FrameLabelMode::Explicit, + None, + &chunk(b"a", &[1], true), + ) + .unwrap() + .remove(0); + let mut second = datatypes::series::frame::pack_raw_series_chunk( + &schema(), + datatypes::series::frame::FrameLabelMode::Explicit, + None, + &chunk(b"b", &[2], true), + ) + .unwrap() + .remove(0); + let mut columns = second.columns().to_vec(); + let time_struct = columns[2] + .as_any() + .downcast_ref::() + .unwrap(); + let lists = time_struct + .column(0) + .as_any() + .downcast_ref::() + .unwrap(); + let datatypes::arrow::datatypes::DataType::List(list_field) = lists.data_type() else { + panic!("expected list") + }; + let invalid_times = datatypes::arrow::array::Int64Array::from(vec![2, 1]); + let invalid_list = datatypes::arrow::array::ListArray::new( + list_field.clone(), + datatypes::arrow::buffer::OffsetBuffer::new(ScalarBuffer::from(vec![0, 2])), + Arc::new(invalid_times), + None, + ); + columns[2] = Arc::new( + datatypes::arrow::array::StructArray::try_new( + time_struct.fields().clone(), + vec![Arc::new(invalid_list)], + None, + ) + .unwrap(), + ); + second = RecordBatch::try_new(frame_schema.clone(), columns).unwrap(); + let multi = concat_batches(&frame_schema, &[first, second]).unwrap(); + let (source, _, _) = df_source(vec![multi], frame_schema); + let mut unpacked = unpack_raw_series(source, Some(schema())).unwrap(); + let error = unpacked.next().await.unwrap().unwrap_err(); + assert_eq!( + common_error::ext::ErrorExt::status_code(&error), + StatusCode::InvalidArguments + ); + assert!(unpacked.next().await.is_none()); +} + +#[tokio::test] +async fn frame_application_metadata_is_stable_and_schema_change_rejected() { + let base_schema = datatypes::series::frame::raw_series_frame_schema( + &schema(), + datatypes::series::frame::FrameLabelMode::Explicit, + ) + .unwrap(); + let mut application_metadata = base_schema.metadata().clone(); + application_metadata.insert("app".into(), "v1".into()); + let declared = Arc::new( + (*base_schema) + .clone() + .with_metadata(application_metadata.clone()), + ); + let first = datatypes::series::frame::pack_raw_series_chunk( + &schema(), + datatypes::series::frame::FrameLabelMode::Explicit, + None, + &chunk(b"a", &[1], true), + ) + .unwrap() + .remove(0) + .with_schema(declared.clone()) + .unwrap(); + let stable_second = datatypes::series::frame::pack_raw_series_chunk( + &schema(), + datatypes::series::frame::FrameLabelMode::Explicit, + None, + &chunk(b"b", &[2], true), + ) + .unwrap() + .remove(0) + .with_schema(declared.clone()) + .unwrap(); + let (source, _, _) = df_source(vec![first.clone(), stable_second], declared.clone()); + let mut stable = unpack_raw_series(source, Some(schema())).unwrap(); + assert_chunk( + &stable.next().await.unwrap().unwrap(), + b"a", + &[1], + &[Some(1.0)], + true, + ); + assert_chunk( + &stable.next().await.unwrap().unwrap(), + b"b", + &[2], + &[Some(2.0)], + true, + ); + assert!(stable.next().await.is_none()); + + for changed_value in [Some("v2"), None] { + let mut changed = application_metadata.clone(); + if let Some(value) = changed_value { + changed.insert("app".into(), value.into()); + } else { + changed.remove("app"); + } + let changed_schema = Arc::new((*base_schema).clone().with_metadata(changed)); + let bad_batch = datatypes::series::frame::pack_raw_series_chunk( + &schema(), + datatypes::series::frame::FrameLabelMode::Explicit, + None, + &chunk(b"b", &[2], true), + ) + .unwrap() + .remove(0) + .with_schema(changed_schema) + .unwrap(); + let (source, _, _) = df_source(vec![first.clone(), bad_batch], declared.clone()); + let mut unpacked = unpack_raw_series(source, Some(schema())).unwrap(); + assert_chunk( + &unpacked.next().await.unwrap().unwrap(), + b"a", + &[1], + &[Some(1.0)], + true, + ); + let error = unpacked.next().await.unwrap().unwrap_err(); + assert_eq!( + common_error::ext::ErrorExt::status_code(&error), + StatusCode::InvalidArguments + ); + assert!(unpacked.next().await.is_none()); + } +} + +struct CountingWake(AtomicUsize); + +impl Wake for CountingWake { + fn wake(self: Arc) { + self.0.fetch_add(1, Ordering::SeqCst); + } + + fn wake_by_ref(self: &Arc) { + self.0.fetch_add(1, Ordering::SeqCst); + } +} + +fn poll_unpacked( + stream: &mut SendableRawSeriesStream, + waker: &Waker, +) -> Poll>> { + stream.as_mut().poll_next(&mut Context::from_waker(waker)) +} + +fn poll_packed( + stream: &mut DfSendableRecordBatchStream, + waker: &Waker, +) -> Poll>> { + stream.as_mut().poll_next(&mut Context::from_waker(waker)) +} + +/// Packs a test source with the deadline batching its pending tests exercise. +/// +/// The policy is a promise about the poller, so only the tests that drive a stream on a timer-enabled +/// runtime may ask for it; every other test keeps the timer-free default. +fn pack_with_deadline(input: SendableRawSeriesStream) -> DfSendableRecordBatchStream { + pack_raw_series_with(input, PendingBatching::Deadline).unwrap() +} + +/// Polls a pack stream once inside `runtime`, so the stream sees that runtime as its poller. +fn poll_once_on( + runtime: &tokio::runtime::Runtime, + stream: &mut DfSendableRecordBatchStream, +) -> Poll>> { + runtime.block_on(std::future::poll_fn(|cx| { + Poll::Ready(stream.as_mut().poll_next(cx)) + })) +} + +fn expect_batch( + stream: &mut DfSendableRecordBatchStream, + waker: &Waker, + label: &str, +) -> RecordBatch { + match poll_packed(stream, waker) { + Poll::Ready(Some(Ok(batch))) => batch, + other => panic!("{label}: expected a batch, got {other:?}"), + } +} + +#[tokio::test] +async fn unpack_bounds_empty_batches_per_poll_and_eventually_yields_row() { + const BUDGET: usize = 32; + let (input, _, _) = raw( + vec![chunk(b"after-empty", &[9], true)], + SeriesOrdering::Contiguous, + ); + let mut packed = pack_raw_series(input).unwrap(); + let row = packed.next().await.unwrap().unwrap(); + let frame_schema = row.schema(); + let mut batches = vec![RecordBatch::new_empty(frame_schema.clone()); 10_000]; + batches.push(row); + let (source, polls, _) = df_source(batches, frame_schema); + let mut unpacked = unpack_raw_series(source, Some(schema())).unwrap(); + let wake = Arc::new(CountingWake(AtomicUsize::new(0))); + let waker = Waker::from(wake.clone()); + + let before = polls.load(Ordering::SeqCst); + assert!(matches!( + poll_unpacked(&mut unpacked, &waker), + Poll::Pending + )); + assert_eq!(polls.load(Ordering::SeqCst) - before, BUDGET); + assert_eq!(wake.0.load(Ordering::SeqCst), 1); + + let mut yielded = false; + let mut expected_wakes = 1; + for _ in 0..=10_000 / BUDGET { + let before = polls.load(Ordering::SeqCst); + let wakes_before = wake.0.load(Ordering::SeqCst); + match poll_unpacked(&mut unpacked, &waker) { + Poll::Pending => { + assert_eq!(polls.load(Ordering::SeqCst) - before, BUDGET); + expected_wakes += 1; + assert_eq!(wake.0.load(Ordering::SeqCst) - wakes_before, 1); + assert_eq!(wake.0.load(Ordering::SeqCst), expected_wakes); + } + Poll::Ready(Some(Ok(chunk))) => { + assert!(polls.load(Ordering::SeqCst) - before <= BUDGET + 1); + assert_eq!(polls.load(Ordering::SeqCst), 10_001); + assert_eq!(wake.0.load(Ordering::SeqCst), wakes_before); + assert_eq!(wake.0.load(Ordering::SeqCst), 10_000 / BUDGET); + assert_chunk(&chunk, b"after-empty", &[9], &[Some(9.0)], true); + yielded = true; + break; + } + other => panic!("unexpected poll result: {other:?}"), + } + } + assert!(yielded, "bounded polling should eventually yield the row"); + assert!(matches!( + poll_unpacked(&mut unpacked, &waker), + Poll::Ready(None) + )); + assert_eq!(wake.0.load(Ordering::SeqCst), 10_000 / BUDGET); +} + +#[test] +fn unpack_yields_at_empty_batch_budget_before_observing_eof() { + const BUDGET: usize = 32; + let frame_schema = datatypes::series::frame::raw_series_frame_schema( + &schema(), + datatypes::series::frame::FrameLabelMode::Explicit, + ) + .unwrap(); + let batches = vec![RecordBatch::new_empty(frame_schema.clone()); BUDGET]; + let (source, polls, _) = df_source(batches, frame_schema); + let mut unpacked = unpack_raw_series(source, Some(schema())).unwrap(); + let wake = Arc::new(CountingWake(AtomicUsize::new(0))); + let waker = Waker::from(wake.clone()); + + assert!(matches!( + poll_unpacked(&mut unpacked, &waker), + Poll::Pending + )); + assert_eq!(polls.load(Ordering::SeqCst), BUDGET); + assert_eq!(wake.0.load(Ordering::SeqCst), 1); + assert!(matches!( + poll_unpacked(&mut unpacked, &waker), + Poll::Ready(None) + )); + assert_eq!(wake.0.load(Ordering::SeqCst), 1); +} + +#[test] +fn unpack_propagates_upstream_pending_without_extra_wake() { + let frame_schema = datatypes::series::frame::raw_series_frame_schema( + &schema(), + datatypes::series::frame::FrameLabelMode::Explicit, + ) + .unwrap(); + let (source, polls, _) = df_pending( + vec![RecordBatch::new_empty(frame_schema.clone())], + frame_schema, + 1, + ); + let mut unpacked = unpack_raw_series(source, Some(schema())).unwrap(); + let wake = Arc::new(CountingWake(AtomicUsize::new(0))); + let waker = Waker::from(wake.clone()); + + assert!(matches!( + poll_unpacked(&mut unpacked, &waker), + Poll::Pending + )); + assert_eq!(polls.load(Ordering::SeqCst), 2); + assert_eq!(wake.0.load(Ordering::SeqCst), 1, "only upstream wakes"); +} + +#[test] +fn unpack_reports_bad_batch_at_budget_boundary_before_yielding() { + const BUDGET: usize = 32; + let frame_schema = datatypes::series::frame::raw_series_frame_schema( + &schema(), + datatypes::series::frame::FrameLabelMode::Explicit, + ) + .unwrap(); + let mut batches = vec![RecordBatch::new_empty(frame_schema.clone()); BUDGET - 1]; + batches.push(RecordBatch::new_empty( + datatypes::arrow::datatypes::Schema::empty().into(), + )); + let (source, polls, _) = df_source(batches, frame_schema); + let mut unpacked = unpack_raw_series(source, Some(schema())).unwrap(); + let wake = Arc::new(CountingWake(AtomicUsize::new(0))); + let waker = Waker::from(wake.clone()); + + assert!(matches!( + poll_unpacked(&mut unpacked, &waker), + Poll::Ready(Some(Err(_))) + )); + assert_eq!(polls.load(Ordering::SeqCst), BUDGET); + assert_eq!(wake.0.load(Ordering::SeqCst), 0); + assert!(matches!( + poll_unpacked(&mut unpacked, &waker), + Poll::Ready(None) + )); +} + +#[test] +fn unpack_surfaces_upstream_error_after_budget_yield_once() { + const BUDGET: usize = 32; + let frame_schema = datatypes::series::frame::raw_series_frame_schema( + &schema(), + datatypes::series::frame::FrameLabelMode::Explicit, + ) + .unwrap(); + let error = datafusion_common::DataFusionError::External(Box::new(BoxedError::new( + PlainError::new("after empty batches".into(), StatusCode::Unsupported), + ))); + let mut items = (0..BUDGET) + .map(|_| Ok(RecordBatch::new_empty(frame_schema.clone()))) + .collect::>(); + items.push(Err(error)); + let polls = Arc::new(AtomicUsize::new(0)); + let source = Box::pin(DfMock { + schema: frame_schema, + items: items.into(), + polls: polls.clone(), + drops: Arc::new(AtomicUsize::new(0)), + pending_after: None, + pending_reported: false, + panic_on_poll: false, + emitted: 0, + }); + let mut unpacked = unpack_raw_series(source, Some(schema())).unwrap(); + let wake = Arc::new(CountingWake(AtomicUsize::new(0))); + let waker = Waker::from(wake.clone()); + + assert!(matches!( + poll_unpacked(&mut unpacked, &waker), + Poll::Pending + )); + assert_eq!(polls.load(Ordering::SeqCst), BUDGET); + let Poll::Ready(Some(Err(error))) = poll_unpacked(&mut unpacked, &waker) else { + panic!("upstream error should be returned after budget yield"); + }; + assert_eq!( + common_error::ext::ErrorExt::status_code(&error), + StatusCode::Unsupported + ); + assert!(matches!( + poll_unpacked(&mut unpacked, &waker), + Poll::Ready(None) + )); +} + +#[tokio::test] +async fn unpack_drains_decoded_rows_before_polling_another_batch() { + let (input, _, _) = raw( + vec![chunk(b"a", &[1], true), chunk(b"b", &[2], true)], + SeriesOrdering::KeyThenTime, + ); + let batches = pack_all(input).await; + let frame_schema = batches[0].schema(); + let multi = concat_batches(&frame_schema, &batches).unwrap(); + let (source, polls, _) = df_source(vec![multi], frame_schema); + let mut unpacked = unpack_raw_series(source, Some(schema())).unwrap(); + assert_chunk( + &unpacked.next().await.unwrap().unwrap(), + b"a", + &[1], + &[Some(1.0)], + true, + ); + assert_eq!(polls.load(Ordering::SeqCst), 1); + assert_chunk( + &unpacked.next().await.unwrap().unwrap(), + b"b", + &[2], + &[Some(2.0)], + true, + ); + assert_eq!( + polls.load(Ordering::SeqCst), + 1, + "decoded pending row precedes upstream polling" + ); + assert!(unpacked.next().await.is_none()); +} + +/// An `expected` schema the raw frame does not declare is rejected before any poll, whether it names +/// no field at all or carries an evaluation grid. A grid schema is a legal *evaluated* declaration +/// now, so it is refused here because a raw frame carries no grid, not because the schema itself is +/// impossible. +#[tokio::test] +async fn unpack_preflights_empty_and_grid_schemas_without_polling() { + let invalid_schemas = [ + SeriesSchema { + fields: Arc::from([]), + eval_grid: None, + }, + SeriesSchema { + fields: schema().fields.clone(), + eval_grid: Some(Arc::new( + datatypes::series::time::EvalGrid::try_new( + datatypes::series::time::GridSpec::try_new(0, 10, 1).unwrap(), + ) + .unwrap(), + )), + }, + ]; + for expected in invalid_schemas { + let frame_schema = datatypes::series::frame::raw_series_frame_schema( + &schema(), + datatypes::series::frame::FrameLabelMode::Explicit, + ) + .unwrap(); + let (source, polls, drops) = df_source(vec![], frame_schema); + assert!(unpack_raw_series(source, Some(Arc::new(expected))).is_err()); + assert_eq!(polls.load(Ordering::SeqCst), 0); + assert_eq!(drops.load(Ordering::SeqCst), 1); + } +} + +fn named_fields_schema(names: [&str; 2]) -> Arc { + Arc::new(SeriesSchema { + fields: names + .into_iter() + .map(|name| FieldSpec { + name: Arc::from(name), + }) + .collect(), + eval_grid: None, + }) +} + +fn named_fields_chunk(schema: &SeriesSchema) -> RawSeriesChunk { + RawSeriesChunk::try_new( + schema, + Buffer::from(b"series-key".to_vec()), + Some(metric()), + RawTimestamps::try_new(ScalarBuffer::from(vec![7_i64, 8])).unwrap(), + SeriesFields::try_from_vec(vec![ + Samples::from_float(Float64Array::from(vec![Some(1.0), Some(2.0)])), + Samples::from_float(Float64Array::from(vec![Some(10.0), Some(20.0)])), + ]) + .unwrap(), + true, + ) + .unwrap() +} + +#[tokio::test] +async fn named_frame_fields_roundtrip_and_reject_wrong_bindings_before_polling() { + let expected = named_fields_schema(["cpu_usage", "cpu_idle"]); + let input_chunk = named_fields_chunk(&expected); + let input: SendableRawSeriesStream = Box::pin(RawMock { + schema: expected.clone(), + items: VecDeque::from([Ok(input_chunk)]), + binding: RawLabelSource::Explicit, + label_decode_spec: None, + ordering: SeriesOrdering::KeyThenTime, + polls: Arc::new(AtomicUsize::new(0)), + drops: Arc::new(AtomicUsize::new(0)), + pending_after: None, + pending_reported: false, + panic_on_poll: false, + emitted: 0, + }); + let batches = pack_all(input).await; + let mut ipc = Vec::new(); + { + let mut writer = StreamWriter::try_new(&mut ipc, &batches[0].schema()).unwrap(); + for batch in &batches { + writer.write(batch).unwrap(); + } + writer.finish().unwrap(); + } + let reader = StreamReader::try_new(Cursor::new(ipc), None).unwrap(); + let frame_schema = reader.schema(); + let ipc_batches = reader.map(Result::unwrap).collect::>(); + let payload_fields = frame_schema.field_with_name("fields").unwrap().data_type(); + let DataType::Struct(payload_fields) = payload_fields else { + panic!("expected struct payload field"); + }; + assert_eq!( + payload_fields + .iter() + .map(|field| field.name()) + .collect::>(), + ["cpu_usage", "cpu_idle"] + ); + + let (source, _, _) = df_source(ipc_batches.clone(), frame_schema.clone()); + let mut decoded = unpack_raw_series(source, Some(expected.clone())).unwrap(); + let actual = decoded.next().await.unwrap().unwrap(); + assert_chunk( + &actual, + b"series-key", + &[7, 8], + &[Some(1.0), Some(2.0)], + true, + ); + assert_eq!(actual.fields.len(), 2); + let second = match actual.fields.as_slice()[1].dense().unwrap() { + DenseSamplesRef::Float(values) => values, + _ => panic!("expected float field"), + }; + assert_eq!(second.null_count(), 0); + assert_eq!(second.values(), &[10.0, 20.0]); + assert_metric(&actual, None); + assert!(decoded.next().await.is_none()); + + for (wrong_names, empty) in [ + (["cpu_idle", "cpu_usage"], false), + (["cpu_usage", "renamed_idle"], false), + (["cpu_idle", "cpu_usage"], true), + (["cpu_usage", "renamed_idle"], true), + ] { + let wrong_schema = named_fields_schema(wrong_names); + let batches = if empty { vec![] } else { ipc_batches.clone() }; + let (source, polls, drops) = df_source(batches, frame_schema.clone()); + assert!(unpack_raw_series(source, Some(wrong_schema)).is_err()); + assert_eq!(polls.load(Ordering::SeqCst), 0); + assert_eq!(drops.load(Ordering::SeqCst), 1); + } +} + +fn histogram_table() -> Arc { + 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: &[1.5, 4.5], + positive: BucketSideView { + span_offsets: &[1], + span_lengths: &[2], + buckets: &[3.25, 7.5], + }, + negative: BucketSideView { + span_offsets: &[-2], + span_lengths: &[1], + buckets: &[0.75], + }, + }) + .unwrap(); + } + builder.finish().unwrap() +} + +/// Ready rows are bounded to the default row limit and emitted as soon as that limit is reached, +/// without reading ahead to EOF; the remainder is flushed when EOF is observed. +#[tokio::test] +async fn pack_bounds_ready_rows_at_default_row_limit_before_eof() { + const TOTAL: usize = 300; + const ROW_LIMIT: usize = 256; + let items = (0..TOTAL) + .map(|i| { + RawSeriesChunk::try_new( + &schema(), + Buffer::from(format!("s{i:03}").into_bytes()), + Some(metric()), + RawTimestamps::try_new(ScalarBuffer::from(vec![i as i64])).unwrap(), + SeriesFields::one(Samples::from_float(Float64Array::from(vec![Some( + i as f64 + 0.5, + )]))), + true, + ) + .unwrap() + }) + .collect::>(); + let (input, polls, drops) = raw(items, SeriesOrdering::KeyThenTime); + let mut packed = pack_raw_series(input).unwrap(); + + let first = packed.next().await.unwrap().unwrap(); + assert_eq!(first.num_rows(), ROW_LIMIT); + assert_eq!( + polls.load(Ordering::SeqCst), + ROW_LIMIT, + "the row bound emits a batch without observing EOF or polling a further chunk" + ); + assert_eq!(drops.load(Ordering::SeqCst), 0, "the source is still live"); + + let second = packed.next().await.unwrap().unwrap(); + assert_eq!(second.num_rows(), TOTAL - ROW_LIMIT); + assert_eq!(polls.load(Ordering::SeqCst), TOTAL + 1); + assert_eq!(drops.load(Ordering::SeqCst), 1, "EOF releases the source"); + assert!(packed.next().await.is_none()); + assert_eq!( + polls.load(Ordering::SeqCst), + TOTAL + 1, + "the terminal poll does not revisit the released source" + ); + + // Compare every series' full payload, not only the batch shape. + let mut seen = 0usize; + for batch in [&first, &second] { + let decoded = datatypes::series::frame::unpack_raw_series_frame( + &schema(), + datatypes::series::frame::FrameLabelMode::Explicit, + None, + batch, + ) + .unwrap(); + for chunk in decoded { + let key = format!("s{seen:03}"); + assert_chunk( + &chunk, + key.as_bytes(), + &[seen as i64], + &[Some(seen as f64 + 0.5)], + true, + ); + assert_metric(&chunk, None); + seen += 1; + } + } + assert_eq!(seen, TOTAL, "every ready series survives exactly once"); +} + +/// One chunk of `rows` single-sample float segments (so every row is a union-of-segment row), +/// plus a clone of every per-row value array, used to observe that a retained batch stays +/// readable once these source-side owners are dropped. +fn per_row_segment_chunk(rows: usize, key: &[u8]) -> (RawSeriesChunk, Vec) { + let owners = (0..rows) + .map(|i| Float64Array::from(vec![Some(i as f64)])) + .collect::>(); + let samples = owners + .clone() + .into_iter() + .map(Samples::from_float) + .collect::>(); + let chunk = RawSeriesChunk::try_new( + &schema(), + Buffer::from(key.to_vec()), + Some(metric()), + RawTimestamps::try_new(ScalarBuffer::from((0..rows as i64).collect::>())).unwrap(), + SeriesFields::one(Samples::try_from_chunks(samples).unwrap()), + true, + ) + .unwrap(); + (chunk, owners) +} + +/// One chunk with more rows than the limit yields exactly one bounded batch per poll: the first +/// batch needs no second source poll, and the remainder needs only EOF. The stream never builds a +/// chunk-wide list of batches. +#[tokio::test] +async fn pack_splits_one_chunk_into_bounded_batches_without_repolling_the_source() { + const ROWS: usize = 300; + let (chunk, _owners) = per_row_segment_chunk(ROWS, b"single"); + let (input, polls, drops) = raw(vec![chunk], SeriesOrdering::Contiguous); + let mut packed = pack_raw_series(input).unwrap(); + + let first = packed.next().await.unwrap().unwrap(); + assert_eq!(first.num_rows(), 256); + assert_eq!( + polls.load(Ordering::SeqCst), + 1, + "a single source poll fills the bounded first batch" + ); + let second = packed.next().await.unwrap().unwrap(); + assert_eq!(second.num_rows(), ROWS - 256); + assert_eq!( + polls.load(Ordering::SeqCst), + 2, + "the remainder needs only the EOF poll, not another chunk" + ); + assert_eq!(drops.load(Ordering::SeqCst), 1); + assert!(packed.next().await.is_none()); + + let mut seen = 0usize; + for batch in [&first, &second] { + let decoded = datatypes::series::frame::unpack_raw_series_frame( + &schema(), + datatypes::series::frame::FrameLabelMode::Explicit, + None, + batch, + ) + .unwrap(); + for chunk in decoded { + assert_chunk( + &chunk, + b"single", + &[seen as i64], + &[Some(seen as f64)], + seen + 1 == ROWS, + ); + seen += 1; + } + } + assert_eq!(seen, ROWS); +} + +/// Dropping the pack stream while its chunk cursor is still live: the upstream source and the +/// remaining rows go away without another poll, and the last emitted batch stays self-contained, +/// readable after every source-side owner is dropped. +#[tokio::test] +async fn dropping_pack_mid_chunk_keeps_last_batch_and_releases_source() { + const ROWS: usize = 300; + let (chunk, owners) = per_row_segment_chunk(ROWS, b"single"); + let (input, polls, drops) = raw(vec![chunk], SeriesOrdering::Contiguous); + let mut packed = pack_raw_series(input).unwrap(); + + let batch = packed.next().await.unwrap().unwrap(); + assert_eq!(batch.num_rows(), 256); + assert_eq!(polls.load(Ordering::SeqCst), 1); + assert_eq!( + drops.load(Ordering::SeqCst), + 0, + "the live cursor keeps its chunk and the source alive" + ); + + drop(packed); + assert_eq!( + drops.load(Ordering::SeqCst), + 1, + "the drop releases upstream" + ); + assert_eq!( + polls.load(Ordering::SeqCst), + 1, + "the drop neither polls upstream nor drains the rest of the chunk" + ); + + // The retained batch owns its payload: it decodes fully after the source-side owners go. + drop(owners); + let decoded = datatypes::series::frame::unpack_raw_series_frame( + &schema(), + datatypes::series::frame::FrameLabelMode::Explicit, + None, + &batch, + ) + .unwrap(); + assert_eq!(decoded.len(), 256); + for (index, chunk) in decoded.iter().enumerate() { + // `is_last` stays false: the final row of the chunk is not in this batch. + assert_chunk( + chunk, + b"single", + &[index as i64], + &[Some(index as f64)], + false, + ); + } + assert_eq!(polls.load(Ordering::SeqCst), 1); +} + +/// Two ready chunks of one key, with more rows buffered than `Pending` reports: the partial +/// batch is flushed complete at that first `Pending` without EOF, keeping `is_last` false while the +/// series is not final in the source. A later `Pending` waits for its deadline instead of publishing +/// at once, and the final row follows at EOF. +#[tokio::test(start_paused = true)] +async fn pack_flushes_ready_rows_at_pending_then_remainder_at_eof() { + let (input, tx, polls, drops) = hand_driven_raw(SeriesOrdering::Contiguous); + let mut packed = pack_with_deadline(input); + let wake = Arc::new(CountingWake(AtomicUsize::new(0))); + let waker = Waker::from(wake.clone()); + + send( + &tx, + chunk_with(b"k", &[1], vec![Some(1.0)], Some(metric()), false), + ); + send( + &tx, + chunk_with(b"k", &[2], vec![Some(2.0)], Some(metric()), false), + ); + let first = match poll_packed(&mut packed, &waker) { + Poll::Ready(Some(Ok(batch))) => batch, + other => panic!("expected a flush at Pending, got {other:?}"), + }; + assert_eq!(first.num_rows(), 2, "both ready rows are complete results"); + assert_eq!( + polls.load(Ordering::SeqCst), + 3, + "two ready rows and one Pending poll, without reaching EOF" + ); + assert_eq!( + wake.0.load(Ordering::SeqCst), + 0, + "the first buffered Pending publishes without waiting for a wake" + ); + let decoded = datatypes::series::frame::unpack_raw_series_frame( + &schema(), + datatypes::series::frame::FrameLabelMode::Explicit, + None, + &first, + ) + .unwrap(); + assert_eq!(decoded.len(), 2); + assert_chunk(&decoded[0], b"k", &[1], &[Some(1.0)], false); + assert_chunk(&decoded[1], b"k", &[2], &[Some(2.0)], false); + + // A later pending keeps its rows buffered, so both of them share one batch. + send( + &tx, + chunk_with(b"k", &[3], vec![Some(3.0)], Some(metric()), false), + ); + send( + &tx, + chunk_with(b"k", &[4], vec![Some(4.0)], Some(metric()), false), + ); + assert!( + matches!(poll_packed(&mut packed, &waker), Poll::Pending), + "a later Pending waits for the deadline instead of publishing" + ); + assert_eq!( + polls.load(Ordering::SeqCst), + 6, + "two rows and one Pending poll" + ); + let wakes = wake.0.load(Ordering::SeqCst); + tokio::time::advance(PENDING_FLUSH_DELAY).await; + assert_eq!( + wake.0.load(Ordering::SeqCst) - wakes, + 1, + "the armed deadline wakes the stream by itself" + ); + let second = match poll_packed(&mut packed, &waker) { + Poll::Ready(Some(Ok(batch))) => batch, + other => panic!("expected the deadline to publish both rows, got {other:?}"), + }; + assert_eq!( + second.num_rows(), + 2, + "both later rows share one bounded batch" + ); + assert_eq!( + polls.load(Ordering::SeqCst), + 6, + "the deadline flush polls no source" + ); + let decoded = datatypes::series::frame::unpack_raw_series_frame( + &schema(), + datatypes::series::frame::FrameLabelMode::Explicit, + None, + &second, + ) + .unwrap(); + assert_eq!(decoded.len(), 2); + assert_chunk(&decoded[0], b"k", &[3], &[Some(3.0)], false); + assert_chunk(&decoded[1], b"k", &[4], &[Some(4.0)], false); + + // The remainder is published exactly once at EOF, which also releases the source. + send( + &tx, + chunk_with(b"k", &[5], vec![Some(5.0)], Some(metric()), true), + ); + drop(tx); + let last = match poll_packed(&mut packed, &waker) { + Poll::Ready(Some(Ok(batch))) => batch, + other => panic!("expected the remainder at EOF, got {other:?}"), + }; + assert_eq!(last.num_rows(), 1); + assert_eq!(polls.load(Ordering::SeqCst), 8); + assert_eq!(drops.load(Ordering::SeqCst), 1); + let decoded = datatypes::series::frame::unpack_raw_series_frame( + &schema(), + datatypes::series::frame::FrameLabelMode::Explicit, + None, + &last, + ) + .unwrap(); + assert_chunk(&decoded[0], b"k", &[5], &[Some(5.0)], true); + assert!(matches!( + poll_packed(&mut packed, &waker), + Poll::Ready(None) + )); +} + +/// The byte bound is a work estimate, not a memory cap: a legal row larger than the estimate is +/// emitted whole as its own batch and never split or dropped. +#[tokio::test] +async fn pack_emits_oversized_legal_rows_whole() { + const SAMPLES: usize = 200_000; + let big = |key: &[u8], offset: i64| { + RawSeriesChunk::try_new( + &schema(), + Buffer::from(key.to_vec()), + Some(metric()), + RawTimestamps::try_new(ScalarBuffer::from((0..SAMPLES as i64).collect::>())) + .unwrap(), + SeriesFields::one(Samples::from_float(Float64Array::from( + (0..SAMPLES) + .map(|i| Some(offset as f64 + i as f64)) + .collect::>(), + ))), + true, + ) + .unwrap() + }; + let (input, polls, _) = raw( + vec![big(b"large-a", 0), big(b"large-b", SAMPLES as i64)], + SeriesOrdering::Contiguous, + ); + let mut packed = pack_raw_series(input).unwrap(); + + let first = packed.next().await.unwrap().unwrap(); + assert_eq!(first.num_rows(), 1, "an oversized row is not split"); + assert!( + polls.load(Ordering::SeqCst) <= 2, + "the oversized row is emitted before EOF, at most after one look-ahead poll" + ); + let second = packed.next().await.unwrap().unwrap(); + assert_eq!(second.num_rows(), 1); + assert!(packed.next().await.is_none()); + + for (batch, key, offset) in [ + (&first, b"large-a".as_slice(), 0_i64), + (&second, b"large-b", 200_000), + ] { + let chunks = datatypes::series::frame::unpack_raw_series_frame( + &schema(), + datatypes::series::frame::FrameLabelMode::Explicit, + None, + batch, + ) + .unwrap(); + assert_eq!(chunks.len(), 1); + let chunk = &chunks[0]; + assert_eq!(chunk.primary_key.as_slice(), key); + assert!(chunk.is_last); + assert_eq!(chunk.time.len(), SAMPLES); + assert_eq!(chunk.time.timestamp(0), Some(0)); + assert_eq!(chunk.time.timestamp(SAMPLES - 1), Some(SAMPLES as i64 - 1)); + let samples = chunk.fields.get(0).unwrap(); + assert_eq!(samples.len(), SAMPLES); + for index in [0, SAMPLES / 2, SAMPLES - 1] { + match samples.sample(index) { + SampleRef::Float(value) => { + assert_eq!(value.to_bits(), (offset as f64 + index as f64).to_bits()); + } + SampleRef::Missing | SampleRef::Histogram(_) => panic!("expected float samples"), + } + } + } +} + +/// Two chunks with different per-field segment boundaries coalesce into one frame, survive a real +/// Arrow IPC round trip, and decode back to every value, sample bit, row-local histogram index, +/// and finality flag. +#[tokio::test] +async fn multirow_ipc_roundtrip_preserves_cross_chunk_variable_segments() { + let schema = named_fields_schema(["value", "latency"]); + let table = histogram_table(); + let first = RawSeriesChunk::try_new( + &schema, + Buffer::from(b"series-key".to_vec()), + Some(metric()), + RawTimestamps::try_new(ScalarBuffer::from(vec![10_i64, 20, 30])).unwrap(), + SeriesFields::try_from_vec(vec![ + Samples::try_from_chunks(vec![ + Samples::from_float(Float64Array::from(vec![Some(1.0), None])), + Samples::from_float(Float64Array::from(vec![Some(f64::from_bits( + 0x7ff8_0000_0000_0042, + ))])), + ]) + .unwrap(), + Samples::try_from_histogram( + UInt32Array::from(vec![Some(1), None, Some(0)]), + table.clone(), + ) + .unwrap(), + ]) + .unwrap(), + false, + ) + .unwrap(); + let second = RawSeriesChunk::try_new( + &schema, + Buffer::from(b"series-key".to_vec()), + Some(metric()), + RawTimestamps::try_new(ScalarBuffer::from(vec![40_i64, 50])).unwrap(), + SeriesFields::try_from_vec(vec![ + Samples::try_from_chunks(vec![ + Samples::from_float(Float64Array::from(vec![Some(-0.0)])), + Samples::from_float(Float64Array::from(vec![Some(f64::from_bits( + crate::prometheus::PROMETHEUS_STALE_NAN_BITS, + ))])), + ]) + .unwrap(), + Samples::try_from_histogram(UInt32Array::from(vec![Some(0), Some(2)]), table).unwrap(), + ]) + .unwrap(), + true, + ) + .unwrap(); + + let (input, polls, _) = raw_items( + vec![Ok(first), Ok(second)], + schema.clone(), + RawLabelSource::Explicit, + SeriesOrdering::KeyThenTime, + None, + ); + let batches = pack_all(input).await; + assert_eq!(polls.load(Ordering::SeqCst), 3); + assert_eq!(batches.len(), 1, "cross-chunk rows share one bounded batch"); + assert_eq!(batches[0].num_rows(), 4); + + let mut ipc = Vec::new(); + { + let mut writer = StreamWriter::try_new(&mut ipc, &batches[0].schema()).unwrap(); + for batch in &batches { + writer.write(batch).unwrap(); + } + writer.finish().unwrap(); + } + let reader = StreamReader::try_new(Cursor::new(ipc), None).unwrap(); + assert_eq!( + reader.schema(), + batches[0].schema(), + "IPC preserves the layout, metadata, and field order" + ); + let frame_schema = reader.schema(); + let ipc_batches = reader.map(Result::unwrap).collect::>(); + let (source, _, _) = df_source(ipc_batches, frame_schema); + let mut decoded = unpack_raw_series(source, Some(schema.clone())).unwrap(); + + struct Expected { + time: i64, + float_bits: Option, + hist_sum: Option, + } + // Table rows: 0 => sum 10.5, 1 => sum -9.5, 2 => sum 7.25. Each frame row compacts + // referenced histogram rows densely, so the same local index can carry different sums. + let nan_bits = f64::from_bits(0x7ff8_0000_0000_0042).to_bits(); + let rows: [(Vec, bool); 4] = [ + ( + vec![ + Expected { + time: 10, + float_bits: Some(1.0_f64.to_bits()), + hist_sum: Some(-9.5), + }, + Expected { + time: 20, + float_bits: None, + hist_sum: None, + }, + ], + false, + ), + ( + vec![Expected { + time: 30, + float_bits: Some(nan_bits), + hist_sum: Some(10.5), + }], + false, + ), + ( + vec![Expected { + time: 40, + float_bits: Some((-0.0_f64).to_bits()), + hist_sum: Some(10.5), + }], + false, + ), + ( + vec![Expected { + time: 50, + float_bits: Some(crate::prometheus::PROMETHEUS_STALE_NAN_BITS), + hist_sum: Some(7.25), + }], + true, + ), + ]; + for (expected, last) in rows { + let chunk = decoded.next().await.unwrap().unwrap(); + assert_eq!(chunk.primary_key.as_slice(), b"series-key"); + assert_eq!(chunk.is_last, last); + assert_metric(&chunk, None); + assert_eq!(chunk.time.len(), expected.len()); + let DenseSamplesRef::Histogram(hist) = chunk.fields.get(1).unwrap().dense().unwrap() else { + panic!("expected a dense histogram field") + }; + for (index, expected) in expected.iter().enumerate() { + assert_eq!(chunk.time.timestamp(index), Some(expected.time)); + match chunk.fields.get(0).unwrap().sample(index) { + SampleRef::Float(value) => { + assert_eq!(Some(value.to_bits()), expected.float_bits); + } + SampleRef::Missing => assert_eq!(expected.float_bits, None), + SampleRef::Histogram(_) => panic!("expected a float field"), + } + match expected.hist_sum { + Some(sum) => { + assert!(hist.indices().is_valid(index)); + assert_eq!(hist.indices().value(index), 0); + let view = hist.view_at(index).expect("histogram sample present"); + assert_eq!(view.sum.to_bits(), sum.to_bits()); + assert_eq!(view.schema, -7); + assert_eq!(view.reset_hint, CounterResetHint::Unrecognized(37)); + assert_eq!(view.custom_values, [1.5, 4.5]); + } + None => { + assert!(hist.indices().is_null(index), "null index survives IPC"); + assert!(hist.view_at(index).is_none()); + } + } + } + } + assert!(decoded.next().await.is_none()); +} + +/// A `Pending` flush after ready rows and a later upstream error: the buffered row is never +/// reported, the original error surfaces immediately and once, and the source is released. +#[tokio::test] +async fn pack_discards_buffered_rows_and_reports_upstream_error_once() { + let status = StatusCode::Unsupported; + let (input, polls, drops) = raw_items( + vec![ + Ok(chunk(b"a", &[1], true)), + Ok(chunk(b"b", &[2], true)), + Err(BoxedError::new(PlainError::new( + "mid-stream".into(), + status, + ))), + ], + schema(), + RawLabelSource::Explicit, + SeriesOrdering::Contiguous, + Some(1), + ); + let mut packed = pack_raw_series(input).unwrap(); + let wake = Arc::new(CountingWake(AtomicUsize::new(0))); + let waker = Waker::from(wake.clone()); + + let first = match poll_packed(&mut packed, &waker) { + Poll::Ready(Some(Ok(batch))) => batch, + other => panic!("expected the buffered row at Pending, got {other:?}"), + }; + assert_eq!(first.num_rows(), 1); + assert_eq!(polls.load(Ordering::SeqCst), 2); + + let error = match poll_packed(&mut packed, &waker) { + Poll::Ready(Some(Err(error))) => error, + other => panic!("expected the upstream error, got {other:?}"), + }; + assert_eq!( + crate::error::datafusion_status_code::(&error, None), + status + ); + assert_eq!( + polls.load(Ordering::SeqCst), + 4, + "the second row is buffered, then the error is polled" + ); + assert_eq!( + drops.load(Ordering::SeqCst), + 1, + "the error releases the source" + ); + assert!( + matches!(poll_packed(&mut packed, &waker), Poll::Ready(None)), + "no buffered row may follow the error" + ); + assert_eq!( + polls.load(Ordering::SeqCst), + 4, + "the error is reported exactly once" + ); +} + +/// One row then a permanently pending source: the first buffered `Pending` still publishes at once, +/// and a later buffered `Pending` publishes at its own deadline without the source waking again. +#[tokio::test(start_paused = true)] +async fn pack_pending_publishes_first_batch_at_once_then_waits_for_the_deadline() { + let (input, tx, polls, drops) = hand_driven_raw(SeriesOrdering::Contiguous); + let mut packed = pack_with_deadline(input); + let wake = Arc::new(CountingWake(AtomicUsize::new(0))); + let waker = Waker::from(wake.clone()); + + // The first buffered pending keeps the original first-batch latency. + send(&tx, chunk(b"k", &[1], false)); + let first = expect_batch(&mut packed, &waker, "first pending"); + assert_eq!(first.num_rows(), 1); + assert_eq!( + polls.load(Ordering::SeqCst), + 2, + "one row and one Pending poll" + ); + assert_eq!( + wake.0.load(Ordering::SeqCst), + 0, + "the first pending publishes without waiting for a wake" + ); + + // The next chunk stays buffered until the deadline instead of being published alone. + send(&tx, chunk(b"k", &[2], true)); + assert!(matches!(poll_packed(&mut packed, &waker), Poll::Pending)); + assert_eq!(polls.load(Ordering::SeqCst), 4); + assert_eq!(drops.load(Ordering::SeqCst), 0); + let wakes = wake.0.load(Ordering::SeqCst); + tokio::time::advance(PENDING_FLUSH_DELAY).await; + assert_eq!( + wake.0.load(Ordering::SeqCst) - wakes, + 1, + "the armed deadline wakes the stream without a source wake" + ); + let second = expect_batch(&mut packed, &waker, "deadline flush"); + assert_eq!( + polls.load(Ordering::SeqCst), + 4, + "the deadline flush polls no source" + ); + let decoded = datatypes::series::frame::unpack_raw_series_frame( + &schema(), + datatypes::series::frame::FrameLabelMode::Explicit, + None, + &second, + ) + .unwrap(); + assert_chunk(&decoded[0], b"k", &[2], &[Some(2.0)], true); + + drop(tx); + assert!( + matches!(poll_packed(&mut packed, &waker), Poll::Ready(None)), + "the delivered tail leaves nothing behind" + ); + assert_eq!(drops.load(Ordering::SeqCst), 1); +} + +/// A pending source with nothing buffered arms no deadline: a quiet stream neither spins a timer nor +/// publishes an empty batch, however long it waits. +#[tokio::test(start_paused = true)] +async fn pack_pending_without_buffered_rows_arms_no_deadline() { + let (input, tx, polls, _drops) = hand_driven_raw(SeriesOrdering::Contiguous); + let mut packed = pack_with_deadline(input); + let wake = Arc::new(CountingWake(AtomicUsize::new(0))); + let waker = Waker::from(wake.clone()); + + send(&tx, chunk(b"k", &[1], true)); + assert_eq!( + expect_batch(&mut packed, &waker, "first pending").num_rows(), + 1 + ); + + // The buffer is empty here, so waiting on the source is the only wakeup. + for _ in 0..3 { + let polls_before = polls.load(Ordering::SeqCst); + assert!(matches!(poll_packed(&mut packed, &waker), Poll::Pending)); + assert_eq!( + polls.load(Ordering::SeqCst) - polls_before, + 1, + "each poll reads the source once" + ); + let wakes = wake.0.load(Ordering::SeqCst); + tokio::time::advance(PENDING_FLUSH_DELAY * 4).await; + assert_eq!( + wake.0.load(Ordering::SeqCst), + wakes, + "an empty cache arms no timer" + ); + } +} + +/// A later pending sets one deadline: rows arriving before it extend the batch instead of restarting +/// the wait. +#[tokio::test(start_paused = true)] +async fn pack_pending_deadline_is_not_reset_by_new_rows() { + let (input, tx, polls, _drops) = hand_driven_raw(SeriesOrdering::Contiguous); + let mut packed = pack_with_deadline(input); + let wake = Arc::new(CountingWake(AtomicUsize::new(0))); + let waker = Waker::from(wake.clone()); + + send(&tx, chunk(b"k", &[1], false)); + assert_eq!( + expect_batch(&mut packed, &waker, "first pending").num_rows(), + 1 + ); + + // This chunk arms the deadline. + send(&tx, chunk(b"k", &[2], false)); + assert!(matches!(poll_packed(&mut packed, &waker), Poll::Pending)); + + // A row arriving before the deadline joins the same batch and does not move the deadline. + tokio::time::advance(PENDING_FLUSH_DELAY / 2).await; + send(&tx, chunk(b"k", &[3], false)); + assert!(matches!(poll_packed(&mut packed, &waker), Poll::Pending)); + tokio::time::advance(PENDING_FLUSH_DELAY / 4).await; + assert!( + matches!(poll_packed(&mut packed, &waker), Poll::Pending), + "the deadline is measured from the pending period, not from the newest row" + ); + let polls_before = polls.load(Ordering::SeqCst); + tokio::time::advance(PENDING_FLUSH_DELAY / 4).await; + let merged = expect_batch(&mut packed, &waker, "unchanged deadline"); + assert_eq!( + merged.num_rows(), + 2, + "both rows share the batch of the original deadline" + ); + assert_eq!( + polls.load(Ordering::SeqCst), + polls_before, + "the deadline flush polls no source" + ); + let decoded = datatypes::series::frame::unpack_raw_series_frame( + &schema(), + datatypes::series::frame::FrameLabelMode::Explicit, + None, + &merged, + ) + .unwrap(); + assert_eq!(decoded.len(), 2); + assert_chunk(&decoded[0], b"k", &[2], &[Some(2.0)], false); + assert_chunk(&decoded[1], b"k", &[3], &[Some(3.0)], false); +} + +/// A builder that reached its row bound publishes without waiting for the deadline, and the tail +/// still follows exactly once at EOF. +#[tokio::test(start_paused = true)] +async fn pack_pending_publishes_when_the_row_bound_fills() { + let (input, tx, _polls, drops) = hand_driven_raw(SeriesOrdering::Contiguous); + let mut packed = pack_with_deadline(input); + let wake = Arc::new(CountingWake(AtomicUsize::new(0))); + let waker = Waker::from(wake.clone()); + // One Arrow segment per sample, so the raw walk emits one row per sample instead of one per + // chunk, which is what the 256-row bound needs. + let segmented = |from: i64, rows: usize, last: bool| -> RawSeriesChunk { + let samples = (0..rows) + .map(|index| { + Samples::from_float(Float64Array::from(vec![Some((from + index as i64) as f64)])) + }) + .collect::>(); + RawSeriesChunk::try_new( + &schema(), + Buffer::from(b"k".to_vec()), + Some(metric()), + RawTimestamps::try_new(ScalarBuffer::from( + (from..from + rows as i64).collect::>(), + )) + .unwrap(), + SeriesFields::one(Samples::try_from_chunks(samples).unwrap()), + last, + ) + .unwrap() + }; + + send(&tx, segmented(0, 1, false)); + assert_eq!( + expect_batch(&mut packed, &waker, "first pending").num_rows(), + 1 + ); + + // Two more chunks reach the 256-row bound while the source is only pending. + send(&tx, segmented(1, 130, false)); + send(&tx, segmented(131, 130, false)); + let full = expect_batch(&mut packed, &waker, "row bound"); + assert_eq!(full.num_rows(), 256, "a full builder publishes at once"); + + // The rows the full batch left behind and the closing row share the next deadline batch. + send(&tx, segmented(261, 1, true)); + assert!(matches!(poll_packed(&mut packed, &waker), Poll::Pending)); + tokio::time::advance(PENDING_FLUSH_DELAY).await; + let tail = expect_batch(&mut packed, &waker, "tail"); + assert_eq!( + tail.num_rows(), + 5, + "the four rows the full batch left behind and the closing row" + ); + let decoded = datatypes::series::frame::unpack_raw_series_frame( + &schema(), + datatypes::series::frame::FrameLabelMode::Explicit, + None, + &tail, + ) + .unwrap(); + assert_eq!(decoded.len(), 5); + assert_chunk(&decoded[3], b"k", &[260], &[Some(260.0)], false); + assert_chunk(&decoded[4], b"k", &[261], &[Some(261.0)], true); + + drop(tx); + assert!( + matches!(poll_packed(&mut packed, &waker), Poll::Ready(None)), + "the tail is published once" + ); + assert_eq!(drops.load(Ordering::SeqCst), 1); +} + +/// The byte bound publishes before the deadline as well: a row that would cross the estimated cap +/// flushes the rows already buffered. +#[tokio::test(start_paused = true)] +async fn pack_pending_publishes_when_the_byte_bound_fills() { + const SAMPLES: usize = 40_000; + let (input, tx, _polls, _drops) = hand_driven_raw(SeriesOrdering::Contiguous); + let mut packed = pack_with_deadline(input); + let wake = Arc::new(CountingWake(AtomicUsize::new(0))); + let waker = Waker::from(wake.clone()); + let samples = |from: usize| -> (Vec, Vec>) { + let times: Vec = (from..from + SAMPLES).map(|index| index as i64).collect(); + let values = times.iter().map(|time| Some(*time as f64)).collect(); + (times, values) + }; + + let (times, values) = samples(0); + send(&tx, chunk_with(b"b", ×, values, Some(metric()), false)); + assert_eq!( + expect_batch(&mut packed, &waker, "first pending").num_rows(), + 1, + "one chunk is one row however many samples it carries" + ); + + let (times, values) = samples(SAMPLES); + send(&tx, chunk_with(b"b", ×, values, Some(metric()), false)); + assert!( + matches!(poll_packed(&mut packed, &waker), Poll::Pending), + "the buffered row waits for the deadline" + ); + + // The next row would cross the byte cap, so the buffered row is published at once. + let (times, values) = samples(SAMPLES * 2); + send(&tx, chunk_with(b"b", ×, values, Some(metric()), true)); + let byte_bound = expect_batch(&mut packed, &waker, "byte bound"); + assert_eq!(byte_bound.num_rows(), 1); + let decoded = datatypes::series::frame::unpack_raw_series_frame( + &schema(), + datatypes::series::frame::FrameLabelMode::Explicit, + None, + &byte_bound, + ) + .unwrap(); + assert_eq!(decoded.len(), 1); + assert_eq!(decoded[0].time.len(), SAMPLES); + assert_eq!(decoded[0].time.timestamp(0), Some(SAMPLES as i64)); + assert!(!decoded[0].is_last); + + // The row that crossed the cap keeps waiting, and the tail is published once at the deadline. + assert!(matches!(poll_packed(&mut packed, &waker), Poll::Pending)); + tokio::time::advance(PENDING_FLUSH_DELAY).await; + let tail = expect_batch(&mut packed, &waker, "tail"); + assert_eq!(tail.num_rows(), 1); + let decoded = datatypes::series::frame::unpack_raw_series_frame( + &schema(), + datatypes::series::frame::FrameLabelMode::Explicit, + None, + &tail, + ) + .unwrap(); + assert_eq!(decoded[0].time.timestamp(0), Some((SAMPLES * 2) as i64)); + assert!(decoded[0].is_last); +} + +/// Raw `Interleaved` fragments stay independent across a bounded batch: one batch can hold two +/// closed chains, and a fragment chain may recur with the same key in a later deadline batch. +#[tokio::test(start_paused = true)] +async fn pack_pending_batches_interleaved_fragments_with_recurring_keys() { + let (input, tx, _polls, _drops) = hand_driven_raw(SeriesOrdering::Interleaved); + let mut packed = pack_with_deadline(input); + let wake = Arc::new(CountingWake(AtomicUsize::new(0))); + let waker = Waker::from(wake.clone()); + + send( + &tx, + chunk_with(b"a", &[5], vec![Some(5.0)], Some(labeled_metric("x")), true), + ); + send( + &tx, + chunk_with(b"b", &[8], vec![Some(8.0)], Some(labeled_metric("y")), true), + ); + let first = expect_batch(&mut packed, &waker, "first pending"); + assert_eq!( + first.num_rows(), + 2, + "one batch holds two independently closed chains" + ); + let decoded = datatypes::series::frame::unpack_raw_series_frame( + &schema(), + datatypes::series::frame::FrameLabelMode::Explicit, + None, + &first, + ) + .unwrap(); + assert_eq!(decoded.len(), 2); + assert_chunk(&decoded[0], b"a", &[5], &[Some(5.0)], true); + assert_chunk(&decoded[1], b"b", &[8], &[Some(8.0)], true); + + // A recurring key is a new closed fragment chain, so it may repeat timestamps too. + send( + &tx, + chunk_with(b"a", &[4], vec![Some(4.0)], Some(labeled_metric("x")), true), + ); + assert!(matches!(poll_packed(&mut packed, &waker), Poll::Pending)); + tokio::time::advance(PENDING_FLUSH_DELAY).await; + let second = expect_batch(&mut packed, &waker, "recurring key"); + assert_eq!(second.num_rows(), 1); + let decoded = datatypes::series::frame::unpack_raw_series_frame( + &schema(), + datatypes::series::frame::FrameLabelMode::Explicit, + None, + &second, + ) + .unwrap(); + assert_chunk(&decoded[0], b"a", &[4], &[Some(4.0)], true); +} + +/// An unclosed chain reaching EOF is rejected after the delivered prefix: the published batches stay +/// published, the buffered tail is dropped, and the source is released. +#[tokio::test(start_paused = true)] +async fn pack_pending_rejects_unclosed_chain_at_eof_after_delivering_prefix() { + let (input, tx, polls, drops) = hand_driven_raw(SeriesOrdering::Contiguous); + let mut packed = pack_with_deadline(input); + let wake = Arc::new(CountingWake(AtomicUsize::new(0))); + let waker = Waker::from(wake.clone()); + + send( + &tx, + chunk_with(b"k", &[1], vec![Some(1.0)], Some(metric()), false), + ); + assert_eq!( + expect_batch(&mut packed, &waker, "first pending").num_rows(), + 1 + ); + + // A later row is published at the deadline while its chain stays open. + send( + &tx, + chunk_with(b"k", &[2], vec![Some(2.0)], Some(metric()), false), + ); + assert!(matches!(poll_packed(&mut packed, &waker), Poll::Pending)); + tokio::time::advance(PENDING_FLUSH_DELAY).await; + assert_eq!( + expect_batch(&mut packed, &waker, "deadline flush").num_rows(), + 1 + ); + + // The closing chunk never arrives, so EOF reports the existing error and publishes nothing. + send( + &tx, + chunk_with(b"k", &[3], vec![Some(3.0)], Some(metric()), false), + ); + drop(tx); + let error = match poll_packed(&mut packed, &waker) { + Poll::Ready(Some(Err(error))) => error, + other => panic!("expected an unclosed chain to be rejected, got {other:?}"), + }; + assert_eq!( + crate::error::datafusion_status_code::(&error, None), + StatusCode::InvalidArguments + ); + assert_eq!(drops.load(Ordering::SeqCst), 1, "EOF releases the source"); + assert!( + matches!(poll_packed(&mut packed, &waker), Poll::Ready(None)), + "no buffered row may follow the rejection" + ); + let polls_after = polls.load(Ordering::SeqCst); + assert!( + matches!(poll_packed(&mut packed, &waker), Poll::Ready(None)), + "the rejection is reported exactly once" + ); + assert_eq!(polls.load(Ordering::SeqCst), polls_after); +} + +/// An upstream error after a deadline was armed: the error surfaces once, the buffered rows are +/// dropped, the delivered prefix stays, and the armed deadline is released. +#[tokio::test(start_paused = true)] +async fn pack_pending_error_after_armed_deadline_reports_once_and_drops_buffer() { + let status = StatusCode::Unsupported; + let (input, tx, polls, drops) = hand_driven_raw(SeriesOrdering::Contiguous); + let mut packed = pack_with_deadline(input); + let wake = Arc::new(CountingWake(AtomicUsize::new(0))); + let waker = Waker::from(wake.clone()); + + send(&tx, chunk(b"a", &[1], true)); + let prefix = expect_batch(&mut packed, &waker, "first pending"); + assert_eq!(prefix.num_rows(), 1); + + send(&tx, chunk(b"b", &[2], true)); + assert!( + matches!(poll_packed(&mut packed, &waker), Poll::Pending), + "the row waits for the deadline" + ); + assert_eq!(drops.load(Ordering::SeqCst), 0); + + tx.send(Err(BoxedError::new(PlainError::new( + "mid-stream".into(), + status, + )))) + .unwrap(); + let error = match poll_packed(&mut packed, &waker) { + Poll::Ready(Some(Err(error))) => error, + other => panic!("expected the upstream error, got {other:?}"), + }; + assert_eq!( + crate::error::datafusion_status_code::(&error, None), + status + ); + assert_eq!( + drops.load(Ordering::SeqCst), + 1, + "the error releases the source" + ); + + let polls_after = polls.load(Ordering::SeqCst); + let wakes = wake.0.load(Ordering::SeqCst); + tokio::time::advance(PENDING_FLUSH_DELAY * 4).await; + assert_eq!( + wake.0.load(Ordering::SeqCst), + wakes, + "the error releases the armed deadline" + ); + assert!( + matches!(poll_packed(&mut packed, &waker), Poll::Ready(None)), + "the undelivered row is dropped" + ); + assert_eq!( + polls.load(Ordering::SeqCst), + polls_after, + "the error is reported exactly once" + ); +} + +/// Dropping a pack stream that is waiting on a deadline releases the source and the timer. +#[tokio::test(start_paused = true)] +async fn dropping_pending_pack_releases_source_and_deadline() { + let (input, tx, polls, drops) = hand_driven_raw(SeriesOrdering::Contiguous); + let mut packed = pack_with_deadline(input); + let wake = Arc::new(CountingWake(AtomicUsize::new(0))); + let waker = Waker::from(wake.clone()); + + send(&tx, chunk(b"a", &[1], true)); + assert_eq!( + expect_batch(&mut packed, &waker, "first pending").num_rows(), + 1 + ); + send(&tx, chunk(b"b", &[2], true)); + assert!(matches!(poll_packed(&mut packed, &waker), Poll::Pending)); + + let polls_before = polls.load(Ordering::SeqCst); + let wakes = wake.0.load(Ordering::SeqCst); + drop(packed); + assert_eq!( + drops.load(Ordering::SeqCst), + 1, + "the drop releases upstream" + ); + tokio::time::advance(PENDING_FLUSH_DELAY * 4).await; + assert_eq!( + wake.0.load(Ordering::SeqCst), + wakes, + "the drop releases the armed deadline" + ); + assert_eq!( + polls.load(Ordering::SeqCst), + polls_before, + "the drop neither polls upstream nor drains the buffer" + ); + assert!( + tx.send(Ok(chunk(b"c", &[3], true))).is_err(), + "the dropped stream closed its source channel" + ); +} + +/// The deadline policy is a promise about the poller, not a probe: a stream polled with no Tokio +/// runtime at all has no timer to wait for, so it publishes at every pending period instead of +/// panicking on a timer that cannot be created there. +#[test] +fn deadline_batching_without_a_tokio_runtime_publishes_at_every_pending() { + let (input, tx, polls, drops) = hand_driven_raw(SeriesOrdering::Contiguous); + let mut packed = pack_with_deadline(input); + let wake = Arc::new(CountingWake(AtomicUsize::new(0))); + let waker = Waker::from(wake.clone()); + + // Each of these pending periods would keep the row buffered on a timer-enabled poller; without + // one the row is published as the pending period begins. + for (time, last) in [(1i64, false), (2, false), (3, true)] { + send(&tx, chunk(b"k", &[time], last)); + let batch = expect_batch(&mut packed, &waker, "no runtime"); + assert_eq!(batch.num_rows(), 1, "the row is published at its pending"); + } + // Sending wakes the registered receiver, so the stream is driven by its source here and never by + // a timer. + drop(tx); + assert!(matches!( + poll_packed(&mut packed, &waker), + Poll::Ready(None) + )); + assert_eq!( + polls.load(Ordering::SeqCst), + 7, + "two source polls per published row and one for the end of the source" + ); + assert_eq!(drops.load(Ordering::SeqCst), 1); +} + +/// The default batching needs no time driver, so a runtime built without `enable_time` polls the +/// stream exactly like any other: buffered rows are published at the pending period. +/// +/// This is the environment the deadline policy documents as its precondition, which is why it is a +/// choice of the caller and not something the stream guesses from the batch path. +#[test] +fn immediate_batching_polls_on_a_runtime_without_the_time_driver() { + let runtime = tokio::runtime::Builder::new_current_thread() + .build() + .expect("a runtime without any driver still builds"); + let (input, tx, polls, drops) = hand_driven_raw(SeriesOrdering::Contiguous); + let mut packed = pack_raw_series(input).unwrap(); + + send(&tx, chunk(b"k", &[1], false)); + send(&tx, chunk(b"k", &[2], true)); + let published = match poll_once_on(&runtime, &mut packed) { + Poll::Ready(Some(Ok(batch))) => batch.num_rows(), + other => panic!("expected the buffered rows at the pending period, got {other:?}"), + }; + assert_eq!(published, 2, "both rows are published at the same pending"); + drop(tx); + assert!(matches!( + poll_once_on(&runtime, &mut packed), + Poll::Ready(None) + )); + assert_eq!( + polls.load(Ordering::SeqCst), + 4, + "two ready chunks, one Pending poll, and the end of the source" + ); + assert_eq!(drops.load(Ordering::SeqCst), 1); +} + +/// The deadline policy's one precondition: a poller without the time driver cannot arm a timer, and +/// the stream reports that by panicking like any other Tokio timer instead of swallowing it. That +/// panic is what makes the policy the caller's declaration rather than a run-time probe of the +/// batch path. +#[test] +fn deadline_batching_on_a_runtime_without_time_panics_at_the_arm() { + let runtime = tokio::runtime::Builder::new_current_thread() + .build() + .expect("a runtime without any driver still builds"); + let (input, tx, _polls, _drops) = hand_driven_raw(SeriesOrdering::Contiguous); + let mut packed = pack_with_deadline(input); + + send(&tx, chunk(b"k", &[1], false)); + assert!( + matches!( + poll_once_on(&runtime, &mut packed), + Poll::Ready(Some(Ok(_))) + ), + "the first pending publishes at once" + ); + send(&tx, chunk(b"k", &[2], true)); + + // The panic message is the contract, not test output, so it is kept out of the log. + let hook = std::panic::take_hook(); + std::panic::set_hook(Box::new(|_| {})); + let armed = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + poll_once_on(&runtime, &mut packed) + })); + std::panic::set_hook(hook); + let payload = armed.expect_err("a runtime without the time driver cannot arm the deadline"); + // It is the time driver's own panic, not a `Debug` assertion of this stream: "a Tokio 1.x + // context was found, but timers are disabled". A runtime context without a time driver is the + // one poller this stream cannot fall back from, because Tokio exposes no way to ask. + let message = payload + .downcast_ref::() + .map(String::as_str) + .or_else(|| payload.downcast_ref::<&str>().copied()) + .unwrap_or_default(); + assert!( + message.contains("timer"), + "the panic must come from the disabled time driver, got: {message}" + ); +} + +/// An armed deadline belongs to the runtime that armed it. Once that runtime is gone, dropping the +/// stream releases the timer without polling it, which Tokio supports for a timer whose driver shut +/// down. +#[test] +fn armed_deadline_is_dropped_after_its_runtime_shut_down() { + let runtime = tokio::runtime::Builder::new_current_thread() + .enable_time() + .build() + .unwrap(); + let (input, tx, _polls, drops) = hand_driven_raw(SeriesOrdering::Contiguous); + let mut packed = pack_with_deadline(input); + + send(&tx, chunk(b"k", &[1], false)); + assert!( + matches!( + poll_once_on(&runtime, &mut packed), + Poll::Ready(Some(Ok(_))) + ), + "the first pending publishes at once" + ); + send(&tx, chunk(b"k", &[2], true)); + assert!( + matches!(poll_once_on(&runtime, &mut packed), Poll::Pending), + "the later pending arms the deadline" + ); + + drop(runtime); + drop(packed); + assert_eq!(drops.load(Ordering::SeqCst), 1); +} + +/// A stream whose armed deadline belongs to a shut-down runtime publishes immediately when another +/// runtime polls it, instead of polling a timer that runtime does not own. +#[test] +fn armed_deadline_on_a_shut_down_runtime_publishes_immediately_elsewhere() { + let arming = tokio::runtime::Builder::new_current_thread() + .enable_time() + .build() + .unwrap(); + let (input, tx, polls, drops) = hand_driven_raw(SeriesOrdering::Contiguous); + let mut packed = pack_with_deadline(input); + + send(&tx, chunk(b"k", &[1], false)); + assert!( + matches!(poll_once_on(&arming, &mut packed), Poll::Ready(Some(Ok(_)))), + "the first pending publishes at once" + ); + send(&tx, chunk(b"k", &[2], true)); + assert!( + matches!(poll_once_on(&arming, &mut packed), Poll::Pending), + "the later pending arms the deadline" + ); + let armed_polls = polls.load(Ordering::SeqCst); + drop(arming); + + let other = tokio::runtime::Builder::new_current_thread() + .enable_time() + .build() + .unwrap(); + let batch = match poll_once_on(&other, &mut packed) { + Poll::Ready(Some(Ok(batch))) => batch, + other => panic!("expected the buffered row at the foreign poller, got {other:?}"), + }; + assert_eq!( + batch.num_rows(), + 1, + "the buffered row is published instead of waiting for a foreign deadline" + ); + assert_eq!( + polls.load(Ordering::SeqCst), + armed_polls, + "publishing it polls no source" + ); + drop(tx); + assert!(matches!( + poll_once_on(&other, &mut packed), + Poll::Ready(None) + )); + assert_eq!(drops.load(Ordering::SeqCst), 1); +} + +/// A malformed public chunk that bypasses `RawSeriesChunk::try_new` reports the existing +/// invalid-arguments error instead of panicking, and still releases the source. +#[tokio::test] +async fn public_chunk_with_empty_times_is_rejected_without_panic() { + let empty_times = || RawTimestamps::try_new(ScalarBuffer::from(Vec::::new())).unwrap(); + let mut aligned = chunk(b"a", &[1], true); + aligned.time = empty_times(); + aligned.fields = SeriesFields::one(Samples::from_float(Float64Array::new_null(0))); + let mut mismatched = chunk(b"a", &[1], true); + mismatched.time = empty_times(); + + for (label, bad) in [("empty", aligned), ("mismatched", mismatched)] { + let (input, polls, drops) = raw_items( + vec![Ok(bad)], + schema(), + RawLabelSource::Explicit, + SeriesOrdering::Contiguous, + None, + ); + let mut packed = pack_raw_series(input).unwrap(); + let error = match packed.next().await { + Some(Err(error)) => error, + other => panic!("{label}: expected a rejection, got {other:?}"), + }; + assert_eq!( + crate::error::datafusion_status_code::(&error, None), + StatusCode::InvalidArguments, + "{label}" + ); + assert!(packed.next().await.is_none(), "{label}"); + assert_eq!(polls.load(Ordering::SeqCst), 1, "{label}"); + assert_eq!(drops.load(Ordering::SeqCst), 1, "{label}"); + } +} + +/// An Interleaved declaration is available for raw streams without polling either source, including +/// streams that ultimately contain no batches. +#[tokio::test] +async fn interleaved_constructors_accept_without_polling() { + let frame = super::raw_series_frame_schema_with_ordering( + &schema(), + &RawLabelSource::Explicit, + SeriesOrdering::Interleaved, + ) + .unwrap(); + assert_eq!(frame.metadata()["greptime.series.ordering"], "interleaved"); + assert_eq!( + series_frame_ordering(&frame).unwrap(), + SeriesOrdering::Interleaved + ); + + let (source, polls, drops) = raw_never_polled(SeriesOrdering::Interleaved); + let packed = pack_raw_series(source).unwrap(); + assert_eq!(packed.schema(), frame); + assert_eq!(polls.load(Ordering::SeqCst), 0); + drop(packed); + assert_eq!(drops.load(Ordering::SeqCst), 1); + + let (source, polls, drops) = df_never_polled(frame); + let unpacked = unpack_raw_series(source, Some(schema())).unwrap(); + assert_eq!(unpacked.ordering(), SeriesOrdering::Interleaved); + assert_eq!(polls.load(Ordering::SeqCst), 0); + drop(unpacked); + assert_eq!(drops.load(Ordering::SeqCst), 1); +} + +/// The unpack stream rejects a batch whose schema differs from the stream's declared schema, +/// including drift in metadata the codec itself does not interpret and an empty batch that +/// carries the drift; the reserved layout metadata is rejected as well. Since the current layout is +/// `v1`, the drift case rewrites the layout to `v2`: any value other than this revision's is refused, +/// so a stale or a future spelling cannot be decoded under the current columns. +#[tokio::test] +async fn unpack_rejects_unrelated_metadata_drift_and_empty_schema_changes() { + let base = datatypes::series::frame::raw_series_frame_schema( + &schema(), + datatypes::series::frame::FrameLabelMode::Explicit, + ) + .unwrap(); + let first = datatypes::series::frame::pack_raw_series_chunk( + &schema(), + datatypes::series::frame::FrameLabelMode::Explicit, + None, + &chunk(b"a", &[1], true), + ) + .unwrap() + .remove(0); + + let mut unrelated = base.metadata().clone(); + unrelated.insert("app.unrelated".into(), "x".into()); + // The current layout is `v1`, so a frame that declares `v2` is the drift here. + let mut reserved = base.metadata().clone(); + reserved.insert("greptime.series.layout".into(), "v2".into()); + let mut renamed = base.metadata().clone(); + renamed.insert("app.renamed".into(), "y".into()); + let mut different_ordering = base.metadata().clone(); + different_ordering.insert("greptime.series.ordering".into(), "interleaved".into()); + + let cases: [(&str, Arc, bool); 4] = [ + ( + "unrelated metadata added", + Arc::new((*base).clone().with_metadata(unrelated)), + false, + ), + ( + "reserved layout metadata changed", + Arc::new((*base).clone().with_metadata(reserved)), + false, + ), + ( + "unrelated metadata on an empty batch", + Arc::new((*base).clone().with_metadata(renamed)), + true, + ), + ( + "ordering changed on an empty batch", + Arc::new((*base).clone().with_metadata(different_ordering)), + true, + ), + ]; + for (label, changed, empty) in cases { + let bad = if empty { + RecordBatch::new_empty(changed) + } else { + RecordBatch::try_new(changed, first.columns().to_vec()).unwrap() + }; + let (source, _, _) = df_source(vec![first.clone(), bad], base.clone()); + let mut unpacked = unpack_raw_series(source, Some(schema())).unwrap(); + assert_chunk( + &unpacked.next().await.unwrap().unwrap(), + b"a", + &[1], + &[Some(1.0)], + true, + ); + let error = unpacked.next().await.unwrap().unwrap_err(); + assert_eq!( + common_error::ext::ErrorExt::status_code(&error), + StatusCode::InvalidArguments, + "{label}" + ); + assert!(unpacked.next().await.is_none(), "{label}"); + } +} + +/// The ordering and layout fixture: literal metadata maps are read the way a receiver reads them, +/// so the same text pins both what `series_frame_ordering` answers and whether the declaration as a +/// whole is accepted. +#[test] +fn raw_series_ordering_metadata_fixture() { + #[derive(serde::Deserialize)] + struct Case { + name: String, + metadata: HashMap, + ordering: Option, + /// `accepted` or `rejected`: whether the whole declaration is one this revision reads. + declaration: String, + } + + let cases: Vec = serde_json::from_str(include_str!( + "../../../../../tests/compatibility/wire/raw_series_ordering/v1_metadata.json" + )) + .unwrap(); + for case in cases { + let literal_ordering = match case.ordering.as_deref() { + Some("contiguous") => Some(SeriesOrdering::Contiguous), + Some("read_key_then_time") => Some(SeriesOrdering::KeyThenTime), + Some(value) => panic!("{} has invalid fixture ordering {value}", case.name), + None => None, + }; + // The columns have to match the content the case declares, so an evaluated case is built on + // an evaluated layout rather than read through a raw one. + let evaluated = case + .metadata + .get("greptime.series.content") + .is_some_and(|content| content == "evaluated"); + let frame_schema = if evaluated { + series_frame_schema(&evaluated_schema(), FrameLabelMode::Explicit, None).unwrap() + } else { + raw_series_frame_schema(&schema(), FrameLabelMode::Explicit).unwrap() + }; + let frame_schema = frame_schema.as_ref().clone().with_metadata(case.metadata); + match literal_ordering { + Some(expected) => assert_eq!( + series_frame_ordering(&frame_schema) + .unwrap_or_else(|error| panic!("{}: {error}", case.name)), + expected, + "{}", + case.name + ), + None => assert!( + series_frame_ordering(&frame_schema).is_err(), + "{}", + case.name + ), + } + let declared = datatypes::series::frame::SeriesFrameDeclaration::parse(&frame_schema); + match case.declaration.as_str() { + "accepted" => { + let declared = declared.unwrap_or_else(|error| panic!("{}: {error}", case.name)); + if evaluated { + assert_eq!( + declared.content(), + datatypes::series::frame::FrameContent::Evaluated, + "{}", + case.name + ); + } + } + "rejected" => assert!( + declared.is_err(), + "{}: the declaration must be refused", + case.name + ), + other => panic!("{} has invalid fixture declaration {other}", case.name), + } + } +} + +#[tokio::test] +async fn pack_declares_ordering_on_every_batch_and_ipc_roundtrips_it() { + for ordering in [ + SeriesOrdering::Contiguous, + SeriesOrdering::KeyThenTime, + SeriesOrdering::Interleaved, + ] { + for chunks in [ + vec![ + chunk_with(b"a", &[1], vec![Some(1.0)], Some(metric()), false), + chunk_with(b"a", &[2], vec![None], Some(metric()), true), + chunk_with(b"b", &[3], vec![Some(3.0)], Some(metric()), true), + ], + vec![], + ] { + let is_empty = chunks.is_empty(); + // The bounded multi-row builder coalesces these three rows into one batch; the + // replaced single-row packing emitted one batch per chunk. + let expected_batch_count = if is_empty { 0 } else { 1 }; + let canonical_schema = + raw_series_frame_schema(&schema(), FrameLabelMode::Explicit).unwrap(); + let mut expected_metadata = canonical_schema.metadata().clone(); + expected_metadata.insert( + "greptime.series.ordering".to_string(), + match ordering { + SeriesOrdering::Contiguous => "contiguous", + SeriesOrdering::KeyThenTime => "read_key_then_time", + SeriesOrdering::Interleaved => "interleaved", + } + .to_string(), + ); + let (input, _, _) = raw(chunks, ordering); + let mut packed = pack_raw_series(input).unwrap(); + let declared = packed.schema(); + assert_eq!(declared.fields(), canonical_schema.fields()); + assert_eq!(declared.metadata(), &expected_metadata); + assert_eq!(series_frame_ordering(&declared).unwrap(), ordering); + let mut batches = Vec::new(); + while let Some(batch) = packed.next().await { + let batch = batch.unwrap(); + assert_eq!(batch.schema(), declared); + batches.push(batch); + } + + let mut ipc = Vec::new(); + { + let mut writer = StreamWriter::try_new(&mut ipc, &declared).unwrap(); + for batch in &batches { + writer.write(batch).unwrap(); + } + writer.finish().unwrap(); + } + let reader = StreamReader::try_new(Cursor::new(ipc), None).unwrap(); + assert_eq!(reader.schema(), declared); + assert_eq!(series_frame_ordering(&reader.schema()).unwrap(), ordering); + let ipc_batches = reader.map(Result::unwrap).collect::>(); + assert_eq!(ipc_batches.len(), batches.len()); + assert_eq!(ipc_batches.len(), expected_batch_count); + assert!(ipc_batches.iter().all(|batch| batch.schema() == declared)); + let (source, _, _) = df_source(ipc_batches, declared); + let mut decoded = unpack_raw_series(source, Some(schema())).unwrap(); + assert_eq!(decoded.ordering(), ordering); + if is_empty { + assert!(decoded.next().await.is_none()); + } else { + for (key, time, value, last) in [ + (b"a".as_slice(), 1, Some(1.0), false), + (b"a".as_slice(), 2, None, true), + (b"b".as_slice(), 3, Some(3.0), true), + ] { + let actual = decoded.next().await.unwrap().unwrap(); + assert_chunk(&actual, key, &[time], &[value], last); + assert_metric(&actual, None); + } + assert!(decoded.next().await.is_none()); + } + } + } +} + +/// A primary-key binding over a region whose only tag is `host`. +fn key_binding(metric: &str) -> RawLabelSource { + use api::v1::SemanticType; + use datatypes::schema::ColumnSchema; + use store_api::metadata::{ColumnMetadata, RegionMetadataBuilder}; + use store_api::storage::RegionId; + let mut builder = RegionMetadataBuilder::new(RegionId::new(1, 1)); + builder + .push_column_metadata(ColumnMetadata { + column_schema: ColumnSchema::new( + "host", + datatypes::data_type::ConcreteDataType::string_datatype(), + false, + ), + semantic_type: SemanticType::Tag, + column_id: 0, + }) + .push_column_metadata(ColumnMetadata { + column_schema: ColumnSchema::new( + "ts", + datatypes::data_type::ConcreteDataType::timestamp_millisecond_datatype(), + false, + ), + semantic_type: SemanticType::Timestamp, + column_id: 1, + }) + .primary_key(vec![0]); + let metadata = Arc::new(builder.build().unwrap()); + RawLabelSource::PrimaryKey { + metric_name: Arc::from(metric), + physical_metadata: metadata, + logical_tags: Arc::from([BoundTag { + column_id: 0, + name: Arc::from("host"), + }]), + } +} + +/// A primary-key binding over a region whose two tags are `host` then `zone`. +fn two_tag_binding(metric: &str) -> RawLabelSource { + use api::v1::SemanticType; + use datatypes::schema::ColumnSchema; + use store_api::metadata::{ColumnMetadata, RegionMetadataBuilder}; + use store_api::storage::RegionId; + let mut builder = RegionMetadataBuilder::new(RegionId::new(1, 1)); + builder + .push_column_metadata(ColumnMetadata { + column_schema: ColumnSchema::new( + "host", + datatypes::data_type::ConcreteDataType::string_datatype(), + false, + ), + semantic_type: SemanticType::Tag, + column_id: 0, + }) + .push_column_metadata(ColumnMetadata { + column_schema: ColumnSchema::new( + "zone", + datatypes::data_type::ConcreteDataType::string_datatype(), + false, + ), + semantic_type: SemanticType::Tag, + column_id: 1, + }) + .push_column_metadata(ColumnMetadata { + column_schema: ColumnSchema::new( + "ts", + datatypes::data_type::ConcreteDataType::timestamp_millisecond_datatype(), + false, + ), + semantic_type: SemanticType::Timestamp, + column_id: 2, + }) + .primary_key(vec![0, 1]); + let metadata = Arc::new(builder.build().unwrap()); + RawLabelSource::PrimaryKey { + metric_name: Arc::from(metric), + physical_metadata: metadata, + logical_tags: Arc::from([ + BoundTag { + column_id: 0, + name: Arc::from("host"), + }, + BoundTag { + column_id: 1, + name: Arc::from("zone"), + }, + ]), + } +} + +/// A raw key frame declaring the supplied description, as a producer with a primary-key binding +/// writes it. +fn key_layout() -> SchemaRef { + let description = + label_decode_spec(&key_binding("cpu")).expect("a primary-key binding describes its key"); + series_frame_schema(&schema(), FrameLabelMode::Key, Some(&description)).unwrap() +} + +/// A key frame whose metadata carries exactly the supplied description text and nothing else. +/// +/// The text is written verbatim, not canonicalized, so a case can pin what a writer must have +/// ordered and what a reader refuses to reorder. +fn key_frame_with_encoded(encoded: &str) -> SchemaRef { + let layout = key_layout(); + let mut metadata = layout.metadata().clone(); + metadata.insert( + "greptime.series.label_decode".to_string(), + encoded.to_string(), + ); + Arc::new(Schema::new_with_metadata(layout.fields().clone(), metadata)) +} + +/// A key frame whose `greptime.series.label_decode` entry is the supplied description. +fn key_frame_with(description: &datatypes::series::frame::LabelDecodeSpec) -> SchemaRef { + key_frame_with_encoded(&serde_json::to_string(description).unwrap()) +} + +/// Logical tag order is fixed by the writer, so the wire form has one spelling and the comparison +/// is plain equality. The ordered key columns are the encoding, so the same columns in another +/// order are a different layout and are rejected. +/// +/// The tag order is canonical rather than meaningful: the decoder sorts tags by name when it binds +/// them (`src/mito-codec/src/labels.rs:235`), so sorting in the writer cannot change a decoded label +/// set. What it does change is that the written text no longer depends on the caller's order, which +/// is what makes one comparison rule enough for both a local check and the byte-exact remote one. +#[tokio::test] +async fn frame_check_compares_the_canonical_description_and_key_order_exactly() { + let binding = two_tag_binding("cpu"); + let description = label_decode_spec(&binding).expect("a primary-key binding describes its key"); + assert_eq!( + description.logical_tags.len(), + 2, + "two tags to canonicalize" + ); + + // A description derived from the binding is already canonical, whichever order the binding + // lists its tags in. + let RawLabelSource::PrimaryKey { + metric_name, + physical_metadata, + logical_tags, + } = &binding + else { + unreachable!("the fixture is a primary-key binding") + }; + let mut reversed_tags = logical_tags.to_vec(); + reversed_tags.reverse(); + let reordered_binding = RawLabelSource::PrimaryKey { + metric_name: metric_name.clone(), + physical_metadata: physical_metadata.clone(), + logical_tags: reversed_tags.into(), + }; + assert_eq!( + label_decode_spec(&reordered_binding).expect("a primary-key binding describes its key"), + description, + "a binding's tag order does not reach the description" + ); + let reordered = + label_decode_spec(&reordered_binding).expect("a primary-key binding describes its key"); + assert_eq!( + key_frame_with(&reordered).metadata(), + key_frame_with(&description).metadata(), + "and so two producers with the same tags write the same bytes" + ); + + // A frame that is not canonical is compared as written instead of being guessed equal. + let mut non_canonical = description.clone(); + non_canonical.logical_tags.reverse(); + let frame = key_frame_with(&non_canonical); + assert!( + ensure_frame_matches_label_source(frame.as_ref(), &binding).is_err(), + "the reader does not reorder what a writer should have ordered" + ); + + // The ordered key columns are the encoding and are never reordered. + let mut reordered_key = description; + reordered_key.primary_key.reverse(); + let frame = key_frame_with(&reordered_key); + assert!( + ensure_frame_matches_label_source(frame.as_ref(), &binding).is_err(), + "primary-key column order is the encoding and is compared as written" + ); +} + +/// The identity check a caller performs on its own compares the frame's declaration with the +/// binding it holds: a different metric, another key layout, or an explicit frame with no +/// declaration at all is a disagreement, and the frame alone still decides what is decoded. +#[tokio::test] +async fn frame_check_rejects_a_binding_the_frame_does_not_describe() { + let description = + label_decode_spec(&key_binding("cpu")).expect("a primary-key binding describes its key"); + let frame = key_frame_with(&description); + assert!( + ensure_frame_matches_label_source(frame.as_ref(), &key_binding("cpu")).is_ok(), + "the same binding is the same layout" + ); + assert!( + ensure_frame_matches_label_source(frame.as_ref(), &key_binding("other_metric")).is_err(), + "another metric is another label layout" + ); + assert!( + ensure_frame_matches_label_source(frame.as_ref(), &RawLabelSource::Explicit).is_err(), + "an explicit identity expects a frame that carries complete labels" + ); + + let explicit = raw_series_frame_schema(&schema(), FrameLabelMode::Explicit).unwrap(); + assert!( + ensure_frame_matches_label_source(explicit.as_ref(), &key_binding("cpu")).is_err(), + "a frame declaring no layout cannot satisfy a primary-key identity" + ); + assert!( + ensure_frame_matches_label_source(explicit.as_ref(), &RawLabelSource::Explicit).is_ok(), + "an explicit frame is what an explicit identity expects" + ); +} + +/// The description parsed at unpack time is retained on the returned stream, so a consumer that +/// holds only the frame can decode; an explicit frame retains none. +#[tokio::test] +async fn unpack_retains_the_declared_description_without_a_binding() { + let binding = key_binding("cpu"); + let description = label_decode_spec(&binding).expect("a primary-key binding describes its key"); + + let (source, _, _) = df_source(vec![], key_frame_with(&description)); + let unpacked = unpack_raw_series(source, None).unwrap(); + assert_eq!(unpacked.label_decode_spec(), Some(&description)); + assert!( + matches!(unpacked.label_source(), RawLabelSource::Explicit), + "no physical region key layout is invented for a frame that carries none" + ); + + let explicit = raw_series_frame_schema(&schema(), FrameLabelMode::Explicit).unwrap(); + let (source, _, _) = df_source(vec![], explicit); + let unpacked = unpack_raw_series(source, None).unwrap(); + assert_eq!( + unpacked.label_decode_spec(), + None, + "explicit labels are already complete and need no decoder" + ); +} + +/// The description is validated whether or not a binding is supplied, so trusting the frame never +/// means skipping validation: an unknown version, an unknown field, a malformed entry, a logical +/// tag outside the key, a key frame without a description, and an explicit frame carrying one are +/// all rejected before the stream is returned. +#[tokio::test] +async fn unpack_rejects_invalid_descriptions_without_a_binding() { + let description = + label_decode_spec(&key_binding("cpu")).expect("a primary-key binding describes its key"); + let encoded = |value: &serde_json::Value| serde_json::to_string(value).unwrap(); + let mut unknown_version = serde_json::to_value(&description).unwrap(); + unknown_version["version"] = + serde_json::json!(datatypes::series::frame::LABEL_DECODE_VERSION + 1); + let mut unknown_field = serde_json::to_value(&description).unwrap(); + unknown_field["future_field"] = serde_json::json!(1); + let mut unlisted_tag = serde_json::to_value(&description).unwrap(); + unlisted_tag["logical_tags"] = serde_json::json!([{ "column_id": 7, "name": "absent" }]); + let cases = [ + ("unknown version", encoded(&unknown_version)), + ("unknown field", encoded(&unknown_field)), + ( + "logical tag outside the primary key", + encoded(&unlisted_tag), + ), + ("malformed entry", "{".to_string()), + ]; + for (label, text) in cases { + let (source, polls, _) = df_source(vec![], key_frame_with_encoded(&text)); + let error = match unpack_raw_series(source, None) { + Ok(_) => panic!("{label}: an invalid description must be rejected"), + Err(error) => error, + }; + assert_eq!( + crate::error::datafusion_status_code::(&error, None), + StatusCode::InvalidArguments, + "{label}" + ); + assert_eq!( + polls.load(Ordering::SeqCst), + 0, + "{label}: a rejected frame is never polled" + ); + } + + // A key frame nobody can decode: the description is removed from the frame the producer wrote. + // Construction cannot express this, which is the point - the reader is what refuses it. + let mut without_description = key_layout().metadata().clone(); + without_description.remove("greptime.series.label_decode"); + let key_without_description = Arc::new(Schema::new_with_metadata( + key_layout().fields().clone(), + without_description, + )); + let (source, _, _) = df_source(vec![], key_without_description); + assert!( + unpack_raw_series(source, None).is_err(), + "a key frame nobody can decode is rejected instead of being trusted" + ); + + let explicit = raw_series_frame_schema(&schema(), FrameLabelMode::Explicit).unwrap(); + let mut metadata = explicit.metadata().clone(); + metadata.insert( + "greptime.series.label_decode".to_string(), + encoded(&serde_json::to_value(&description).unwrap()), + ); + let explicit_with_description = Arc::new(Schema::new_with_metadata( + explicit.fields().clone(), + metadata, + )); + let (source, _, _) = df_source(vec![], explicit_with_description); + assert!( + unpack_raw_series(source, None).is_err(), + "an explicit frame declares no description, so one is a contradiction" + ); +} + +fn key_chunk() -> RawSeriesChunk { + chunk_with(b"encoded-complete-key", &[1], vec![Some(3.0)], None, true) +} + +/// Every packed key frame declares the label decode description derived from its binding, so a +/// consumer needs no scan-side label source. Explicit frames declare none. +#[tokio::test] +async fn pack_declares_the_label_decode_description_of_its_binding() { + let binding = key_binding("cpu"); + let (input, _, _) = raw_custom( + vec![key_chunk()], + SeriesOrdering::Contiguous, + binding.clone(), + ); + let mut packed = pack_raw_series(input).unwrap(); + let declared = packed.schema(); + // A key frame's canonical layout carries its description and explicit default ordering. + let canonical = key_layout(); + assert_eq!( + declared.metadata().len(), + canonical.metadata().len(), + "the stream schema preserves the complete canonical declaration" + ); + assert_eq!( + datatypes::series::frame::series_frame_label_decode(&declared).unwrap(), + label_decode_spec(&binding), + "the declared description is derived from the binding, not from the first row" + ); + let batch = packed.next().await.unwrap().unwrap(); + assert_eq!(batch.schema(), declared); + + let (input, _, _) = raw_custom( + vec![key_chunk()], + SeriesOrdering::Contiguous, + RawLabelSource::Explicit, + ); + let packed = pack_raw_series(input).unwrap(); + let declared = packed.schema(); + assert_eq!( + datatypes::series::frame::series_frame_label_decode(&declared).unwrap(), + None, + "explicit labels are already complete" + ); + let canonical_explicit = raw_series_frame_schema(&schema(), FrameLabelMode::Explicit).unwrap(); + assert_eq!( + declared.metadata().len(), + canonical_explicit.metadata().len(), + "an explicit frame preserves the complete canonical declaration" + ); +} + +/// A key frame that omits its description is not decodable, and unpacking says so instead of falling +/// back to a caller-side layout; the description that is present survives the round trip. +#[tokio::test] +async fn unpack_round_trips_a_key_frame_and_rejects_one_without_a_description() { + let binding = key_binding("cpu"); + let (input, _, _) = raw_custom( + vec![key_chunk()], + SeriesOrdering::Contiguous, + binding.clone(), + ); + let mut packed = pack_raw_series(input).unwrap(); + let declared = packed.schema(); + let batch = packed.next().await.unwrap().unwrap(); + + // The frame and the binding agree, so the round trip decodes. + let (source, _, _) = df_source(vec![batch.clone()], declared.clone()); + let mut decoded = unpack_raw_series(source, Some(schema())).unwrap(); + let chunk = decoded.next().await.unwrap().unwrap(); + assert_eq!(chunk.primary_key.as_slice(), b"encoded-complete-key"); + + // A frame that omits the description is not decodable from the schema alone. The producer + // cannot write one, so the entry is dropped from the frame it did write: the reader is what has + // to refuse it. + let mut metadata = declared.metadata().clone(); + metadata.remove("greptime.series.label_decode"); + let stripped = Arc::new(datatypes::arrow::datatypes::Schema::new_with_metadata( + declared.fields().clone(), + metadata, + )); + let stripped_batch = RecordBatch::try_new(stripped.clone(), batch.columns().to_vec()).unwrap(); + let (source, _, _) = df_source(vec![stripped_batch], stripped); + let error = match unpack_raw_series(source, Some(schema())) { + Ok(_) => panic!("a key frame without a description must be rejected"), + Err(error) => error, + }; + assert_eq!( + crate::error::datafusion_status_code::(&error, None), + StatusCode::InvalidArguments + ); +} + +/// An evaluated stream with no ordering declaration is rejected before the empty source is polled. +#[tokio::test] +async fn unpack_rejects_missing_ordering_on_empty_evaluated_stream() { + let frame = series_frame_schema(&evaluated_schema(), FrameLabelMode::Explicit, None).unwrap(); + let mut metadata = frame.metadata().clone(); + metadata.remove("greptime.series.ordering"); + let frame = Arc::new(Schema::new_with_metadata(frame.fields().clone(), metadata)); + let (source, polls, _) = df_source(vec![], frame); + assert!(super::unpack_evaluated_series(source, None).is_err()); + assert_eq!(polls.load(Ordering::SeqCst), 0); +} + +#[tokio::test] +async fn unpack_reports_the_ordering_the_frame_declares() { + let (input, _, _) = raw_custom( + vec![key_chunk()], + SeriesOrdering::KeyThenTime, + key_binding("cpu"), + ); + let packed = pack_raw_series(input).unwrap(); + assert_eq!( + series_frame_ordering(packed.schema().as_ref()).unwrap(), + SeriesOrdering::KeyThenTime, + "the producer declaration reaches the wire" + ); + + let unpacked = unpack_raw_series(packed, None).unwrap(); + assert_eq!( + unpacked.ordering(), + SeriesOrdering::KeyThenTime, + "unpacking derives the ordering from the frame, not from a caller" + ); + + let frame = raw_series_frame_schema(&schema(), FrameLabelMode::Explicit).unwrap(); + let mut metadata = frame.metadata().clone(); + metadata.remove("greptime.series.ordering"); + let frame = Arc::new(Schema::new_with_metadata(frame.fields().clone(), metadata)); + let (source, _, _) = df_source(vec![], frame); + assert!(unpack_raw_series(source, None).is_err()); +} + +/// Reserved layout metadata this revision does not write is rejected instead of being read as the +/// current layout, so a frame cannot be decoded under a contract it did not declare. The current +/// layout is `v1`; a `v2` frame and every unknown value are refused alike. +#[tokio::test] +async fn unpack_rejects_unknown_layout_metadata() { + let cases = [ + ("greptime.series.layout", "v2"), + ("greptime.series.layout", "v3"), + ("greptime.series.content", "series"), + ("greptime.series.time", "timestamps_v2"), + ("greptime.series.ordering", "hash_then_time"), + ]; + for (key, value) in cases { + let frame = raw_series_frame_schema(&schema(), FrameLabelMode::Explicit).unwrap(); + let mut metadata = frame.metadata().clone(); + metadata.insert(key.to_string(), value.to_string()); + let frame = Arc::new(Schema::new_with_metadata(frame.fields().clone(), metadata)); + let (source, polls, _) = df_source(vec![], frame); + assert!( + unpack_raw_series(source, None).is_err(), + "{key} = {value} is not a declaration this revision reads" + ); + assert_eq!(polls.load(Ordering::SeqCst), 0, "{key}"); + } +} + +/// `expected` is a check, not an input: a schema the frame does not declare is rejected, and the +/// same frame unpacks without it because the frame is the only source of decode information. +#[tokio::test] +async fn unpack_rejects_an_expected_schema_the_frame_does_not_declare() { + let frame = raw_series_frame_schema(&schema(), FrameLabelMode::Explicit).unwrap(); + + let other_field = Arc::new(SeriesSchema { + fields: vec![FieldSpec { + name: Arc::from("other_value"), + }] + .into(), + eval_grid: None, + }); + let (source, polls, _) = df_source(vec![], frame.clone()); + let error = match unpack_raw_series(source, Some(other_field)) { + Ok(_) => panic!("a field layout the frame does not declare must be rejected"), + Err(error) => error, + }; + assert_eq!( + crate::error::datafusion_status_code::(&error, None), + StatusCode::InvalidArguments + ); + assert_eq!(polls.load(Ordering::SeqCst), 0, "nothing is polled"); + + let two_fields = Arc::new(SeriesSchema { + fields: vec![ + FieldSpec { + name: Arc::from("value"), + }, + FieldSpec { + name: Arc::from("second"), + }, + ] + .into(), + eval_grid: None, + }); + let (source, _, _) = df_source(vec![], frame.clone()); + assert!( + unpack_raw_series(source, Some(two_fields)).is_err(), + "the same names in a longer list are another layout" + ); + + let (source, _, _) = df_source(vec![], frame.clone()); + assert!( + unpack_raw_series(source, Some(schema())).is_ok(), + "the schema the frame declares is accepted" + ); + + let (source, _, _) = df_source(vec![], frame); + let unpacked = unpack_raw_series(source, None).unwrap(); + assert_eq!( + unpacked + .schema() + .fields + .iter() + .map(|field| field.name.as_ref()) + .collect::>(), + vec!["value"], + "the returned schema is the frame's, whether or not an expectation was given" + ); +} + +/// Unpacking a frame and packing it again keeps both declarations, so a relayed stream is the same +/// stream: the description still decodes the same labels and the ordering still holds. +#[tokio::test] +async fn unpack_pack_unpack_preserves_the_description_and_the_ordering() { + let binding = key_binding("cpu"); + let description = label_decode_spec(&binding).expect("a primary-key binding describes its key"); + let (input, _, _) = raw_custom(vec![key_chunk()], SeriesOrdering::KeyThenTime, binding); + let packed = pack_raw_series(input).unwrap(); + assert_eq!( + datatypes::series::frame::series_frame_label_decode(packed.schema().as_ref()).unwrap(), + Some(description.clone()) + ); + + let unpacked = unpack_raw_series(packed, None).unwrap(); + assert_eq!(unpacked.label_decode_spec(), Some(&description)); + assert_eq!(unpacked.ordering(), SeriesOrdering::KeyThenTime); + + let repacked = pack_raw_series(unpacked).unwrap(); + assert_eq!( + datatypes::series::frame::series_frame_label_decode(repacked.schema().as_ref()).unwrap(), + Some(description.clone()), + "the repacked frame declares what the unpacked stream declared" + ); + assert_eq!( + series_frame_ordering(repacked.schema().as_ref()).unwrap(), + SeriesOrdering::KeyThenTime, + "the repacked frame keeps the ordering it was unpacked under" + ); + + let mut again = unpack_raw_series(repacked, None).unwrap(); + assert_eq!(again.label_decode_spec(), Some(&description)); + assert_eq!(again.ordering(), SeriesOrdering::KeyThenTime); + let chunk = again.next().await.unwrap().unwrap(); + assert_eq!(chunk.primary_key.as_slice(), b"encoded-complete-key"); + assert!(chunk.metric.is_none(), "key chunks stay undecoded"); + assert!(again.next().await.is_none()); +} + +/// Each typed schema entry point refuses the content it cannot describe. +/// +/// The raw entry point is handed an evaluated series schema and the shared builder is handed an +/// evaluated schema with a non-contiguous ordering. Both would otherwise produce a frame whose +/// declaration contradicts its own columns, and the reader would be the first to notice — after the +/// producer had already published it. +#[test] +fn typed_schema_entry_points_refuse_the_content_they_cannot_describe() { + assert!( + super::raw_series_frame_schema_with_ordering( + &evaluated_schema(), + &RawLabelSource::Explicit, + SeriesOrdering::Contiguous, + ) + .is_err(), + "a raw frame cannot carry a schema with an evaluation grid" + ); + assert!( + super::frame_schema_with( + &evaluated_schema(), + FrameLabelMode::Explicit, + None, + SeriesOrdering::KeyThenTime, + ) + .is_err(), + "an evaluated frame has no storage key to be ordered by" + ); + assert!( + super::frame_schema_with( + &evaluated_schema(), + FrameLabelMode::Explicit, + None, + SeriesOrdering::Interleaved, + ) + .is_err(), + "an evaluated frame cannot declare interleaved ordering" + ); + assert!( + super::frame_schema_with( + &evaluated_schema(), + FrameLabelMode::Explicit, + None, + SeriesOrdering::Contiguous, + ) + .is_ok(), + "contiguous is the one ordering an evaluated frame can honour" + ); +} diff --git a/src/common/query/src/series_frame/tests/evaluated.rs b/src/common/query/src/series_frame/tests/evaluated.rs new file mode 100644 index 00000000000..26dfdc871a8 --- /dev/null +++ b/src/common/query/src/series_frame/tests/evaluated.rs @@ -0,0 +1,1479 @@ +// 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. + +//! Streaming round trips through an evaluated series frame. +//! +//! An evaluated frame names its series by their complete labels and addresses time on the grid its +//! schema declares, so every test here drives the real path - pack, a record batch stream, unpack - +//! and compares what a consumer receives against what a producer sent. A schema snapshot would +//! prove the declaration; these prove the values. +//! +//! A frame row is one run of positions on the shared grid, so unpacking yields one [`Series`] per +//! row rather than one per source chunk. A consumer rebuilds a chunk chain by concatenating rows up +//! to the one that carries `is_last`, which is what these tests do. + +use std::io::Cursor; +use std::sync::Arc; +use std::sync::atomic::Ordering; + +use common_error::ext::{BoxedError, ErrorExt, PlainError}; +use common_error::status_code::StatusCode; +use common_recordbatch::DfSendableRecordBatchStream; +use datatypes::arrow::array::{ + Array, BooleanArray, Float64Array, ListArray, StructArray, UInt32Array, UInt64Array, +}; +use datatypes::arrow::buffer::OffsetBuffer; +use datatypes::arrow::datatypes::{DataType, SchemaRef}; +use datatypes::arrow::ipc::{reader::StreamReader, writer::StreamWriter}; +use datatypes::arrow::record_batch::{RecordBatch, RecordBatchOptions}; +use datatypes::series::frame::{FrameLabelMode, SeriesFrameBuilder, SeriesFrameCursor}; +use datatypes::series::histogram::{ + BucketSideView, CounterResetHint, HistogramBatch, HistogramBatchBuilder, HistogramView, +}; +use datatypes::series::samples::{ + DenseSamplesRef, FieldSpec, SampleRef, Samples, Series, SeriesFields, SeriesSchema, +}; +use datatypes::series::time::{GridSpan, TimeAxis}; +use datatypes::series::{Label, SeriesLabels, SeriesOrdering}; +use futures_util::StreamExt; + +use super::super::{ + SendableEvaluatedSeriesStream, pack_evaluated_series, series_frame_ordering, + unpack_evaluated_series, unpack_raw_series, +}; +use super::{df_source, evaluated_grid, evaluated_schema, schema}; + +/// Complete labels of the `cpu` metric on one host. +fn labels(host: &str) -> SeriesLabels { + SeriesLabels::try_new( + Some(Arc::from("cpu")), + vec![Label { + name: Arc::from("host"), + value: Arc::from(host), + }], + ) + .unwrap() +} + +/// One validated evaluated chunk: `values` on the runs `spans` of the shared test grid. +fn series(spans: &[(usize, usize)], values: Vec>, metric: SeriesLabels) -> Series { + series_on(&evaluated_schema(), spans, values, metric) +} + +/// An evaluated schema large enough for multi-batch lifecycle fixtures. +fn large_evaluated_schema() -> Arc { + Arc::new(SeriesSchema { + fields: evaluated_schema().fields.clone(), + eval_grid: Some(Arc::new( + datatypes::series::time::EvalGrid::try_new( + datatypes::series::time::GridSpec::try_new(0, 1000, 1600).unwrap(), + ) + .unwrap(), + )), + }) +} + +/// One validated evaluated chunk on the supplied schema's grid. +fn series_on( + schema: &SeriesSchema, + spans: &[(usize, usize)], + values: Vec>, + metric: SeriesLabels, +) -> Series { + let time = TimeAxis::from_grid_spans( + schema.eval_grid.as_ref().unwrap().clone(), + spans + .iter() + .map(|(start, len)| GridSpan::new(*start, *len)) + .collect(), + ) + .unwrap(); + let fields = SeriesFields::one(Samples::from_float(Float64Array::from(values))); + Series::try_new(schema, metric, time, fields).unwrap() +} + +/// An evaluated producer stream over the supplied chunks and their finality. +fn source(items: Vec<(Series, bool)>) -> SendableEvaluatedSeriesStream { + Box::pin(futures_util::stream::iter( + items.into_iter().map(Ok::<_, BoxedError>), + )) +} + +/// A counted source whose guard records when the packer releases its upstream stream. +fn observed_source( + items: Vec>, + polls: Arc, + dropped: Arc, +) -> SendableEvaluatedSeriesStream { + struct DropGuard(Arc); + impl Drop for DropGuard { + fn drop(&mut self) { + self.0.store(true, Ordering::SeqCst); + } + } + + Box::pin(futures_util::stream::unfold( + (items.into_iter(), DropGuard(dropped)), + move |(mut items, guard)| { + let polls = polls.clone(); + async move { + polls.fetch_add(1, Ordering::SeqCst); + let item = items.next()?; + Some((item, (items, guard))) + } + }, + )) +} + +/// Packs the supplied chunks, keeping the stream so a test can observe its errors. +fn pack(items: Vec<(Series, bool)>) -> DfSendableRecordBatchStream { + pack_evaluated_series(source(items), evaluated_schema()).unwrap() +} + +/// Packs the supplied chunks and drains every ready batch. +async fn packed(items: Vec<(Series, bool)>) -> Vec { + let mut stream = pack(items); + let mut out = Vec::new(); + while let Some(batch) = stream.next().await { + out.push(batch.unwrap()); + } + out +} + +/// Unpacks the batches a producer published, under the schema they declare. +fn unpack(batches: Vec, declared: SchemaRef) -> SendableEvaluatedSeriesStream { + let (source, _, _) = df_source(batches, declared); + unpack_evaluated_series(source, Some(evaluated_schema())).unwrap() +} + +/// Drains one unpacked stream, so a test can assert on the whole sequence at once. +async fn drain(mut stream: SendableEvaluatedSeriesStream) -> Vec<(Series, bool)> { + let mut out = Vec::new(); + while let Some(chunk) = stream.next().await { + out.push(chunk.unwrap()); + } + out +} + +/// The absolute grid positions a decoded chunk carries, in order. +fn positions(series: &Series) -> Vec { + series + .time + .positions() + .map(|(position, _)| position) + .collect() +} + +/// The float payload of the one `value` field, in compact-row order. +fn values(series: &Series) -> Vec> { + series + .fields + .as_slice() + .first() + .expect("the fixture has one value field") + .iter() + .map(|sample| match sample { + SampleRef::Missing => None, + SampleRef::Float(value) => Some(value), + _ => panic!("the fixture carries float samples"), + }) + .collect() +} + +/// The positions and values of every decoded row, concatenated in stream order. +fn flat(rows: &[(Series, bool)]) -> (Vec, Vec>) { + let mut all_positions = Vec::new(); + let mut all_values = Vec::new(); + for (row, _) in rows { + all_positions.extend(positions(row)); + all_values.extend(values(row)); + } + (all_positions, all_values) +} + +/// Rewrites the `is_last` column of a frame, so a test can produce a row a producer refuses to write +/// and check that the reader refuses it too. +fn with_is_last(batch: &RecordBatch, is_last: bool) -> RecordBatch { + let mut columns = batch.columns().to_vec(); + columns[1] = Arc::new(BooleanArray::from(vec![is_last; batch.num_rows()])); + RecordBatch::try_new(batch.schema(), columns).unwrap() +} + +/// Rewrites the `read_key` column of a frame, so a test can attach the storage key an evaluated row +/// must not carry. +fn with_read_key(batch: &RecordBatch, key: &[u8]) -> RecordBatch { + let keys = vec![Some(key); batch.num_rows()]; + let mut columns = batch.columns().to_vec(); + columns[0] = Arc::new(datatypes::arrow::array::BinaryArray::from(keys)); + RecordBatch::try_new(batch.schema(), columns).unwrap() +} + +/// The frame schema a producer's batches carry, with one metadata entry changed the way a divergent +/// producer would write it. +fn relabelled(declared: &SchemaRef, key: &str, value: Option<&str>) -> SchemaRef { + let mut metadata = declared.metadata().clone(); + match value { + Some(value) => metadata.insert(key.to_string(), value.to_string()), + None => metadata.remove(key), + }; + Arc::new(datatypes::arrow::datatypes::Schema::new_with_metadata( + declared.fields().clone(), + metadata, + )) +} + +/// One dense chunk keeps every position, label, and value, and its finality. +#[tokio::test] +async fn dense_roundtrip_preserves_positions_labels_and_values() { + let metric = labels("a"); + let expected: Vec> = (0..8) + .map(|row| (row % 3 != 0).then_some(row as f64)) + .collect(); + let batches = packed(vec![( + series(&[(0, 8)], expected.clone(), metric.clone()), + true, + )]) + .await; + assert_eq!(batches.len(), 1, "eight positions are one row"); + assert_eq!(batches[0].num_rows(), 1); + + let declared = batches[0].schema(); + assert_eq!( + series_frame_ordering(declared.as_ref()).unwrap(), + SeriesOrdering::Contiguous, + "an evaluated frame declares contiguous ordering" + ); + let declaration = datatypes::series::frame::SeriesFrameDeclaration::parse(declared.as_ref()) + .expect("an evaluated frame declares itself"); + assert_eq!( + declaration.content(), + datatypes::series::frame::FrameContent::Evaluated + ); + assert_eq!( + declaration.labels(), + datatypes::series::frame::FrameLabelMode::Explicit + ); + assert_eq!( + declared + .metadata() + .get("greptime.series.time") + .map(String::as_str), + Some("grid_spans"), + "an evaluated frame addresses time on its grid" + ); + assert!(declaration.label_decode().is_none(), "no key is decoded"); + + let rows = drain(unpack(batches, declared)).await; + assert_eq!(rows.len(), 1); + let (chunk, is_last) = &rows[0]; + assert!(is_last, "the source closed the chain"); + assert_eq!(chunk.metric, metric, "labels round trip"); + assert_eq!(positions(chunk), (0..8).collect::>()); + assert_eq!(values(chunk), expected, "every value, including nulls"); + assert!( + chunk + .time + .grid() + .is_some_and(|grid| grid.spec() == evaluated_grid().spec()), + "the decoded chunk is addressed on the frame's own grid" + ); +} + +/// A sparse chunk keeps its holes: the decoded positions are exactly the ones the producer sent, and +/// every field stays aligned with them. +#[tokio::test] +async fn sparse_roundtrip_keeps_holes_and_field_alignment() { + let metric = labels("b"); + let expected = vec![Some(1.0), None, Some(3.0), Some(4.0), None]; + let batches = packed(vec![( + series(&[(0, 2), (5, 3)], expected.clone(), metric.clone()), + true, + )]) + .await; + assert_eq!(batches.len(), 1); + let declared = batches[0].schema(); + let rows = drain(unpack(batches, declared)).await; + + let (decoded_positions, decoded_values) = flat(&rows); + assert_eq!( + decoded_positions, + vec![0, 1, 5, 6, 7], + "the hole between the runs is not filled" + ); + assert_eq!( + decoded_values, expected, + "values stay aligned to positions, hole included" + ); + for (row, _) in &rows { + assert_eq!(row.metric, metric); + for hole in [2, 3, 4] { + assert!( + row.time.row_of(hole).is_none(), + "no row exists at a position the chunk does not hold" + ); + } + } + assert!( + rows.last().expect("at least one row").1, + "only the last row of the chunk closes the chain" + ); + assert_eq!( + rows.iter().filter(|(_, is_last)| *is_last).count(), + 1, + "one chain, one close" + ); +} + +/// A chunk with no positions that closes its chain is one frame row, not a dropped chunk: a consumer +/// has to see the finality it carries. +#[tokio::test] +async fn zero_sample_closing_chunk_is_kept_as_one_row() { + let metric = labels("c"); + let batches = packed(vec![ + ( + series(&[(3, 2)], vec![Some(1.0), Some(2.0)], metric.clone()), + false, + ), + (series(&[], vec![], metric.clone()), true), + ]) + .await; + assert_eq!(batches.len(), 1); + assert_eq!( + batches[0].num_rows(), + 2, + "the closing chunk keeps its own row" + ); + + let declared = batches[0].schema(); + let rows = drain(unpack(batches, declared)).await; + assert_eq!(rows.len(), 2); + let (carried, carried_is_last) = &rows[0]; + assert!(!carried_is_last, "the first chunk stays open"); + assert_eq!(positions(carried), vec![3, 4]); + assert_eq!(values(carried), vec![Some(1.0), Some(2.0)]); + let (closing, closing_is_last) = &rows[1]; + assert!(closing_is_last, "the closing chunk keeps its finality"); + assert_eq!( + positions(closing), + Vec::::new(), + "and carries no position" + ); + assert_eq!(values(closing), Vec::>::new()); + assert_eq!(closing.metric, metric, "labels survive on a closing chunk"); +} + +/// One grid position per run, so a chunk with `count` positions starting at `start` becomes `count` +/// frame rows: one row per run, which is what a batch bound can split. +fn single_position_spans(start: usize, count: usize) -> Vec<(usize, usize)> { + (0..count).map(|offset| (start + offset, 1)).collect() +} + +/// The evaluated packer drains one large sparse chunk in bounded batches without re-polling upstream. +#[tokio::test] +async fn evaluated_pack_drains_large_sparse_chunk_before_polling_again() { + let schema = large_evaluated_schema(); + let positions: Vec = (0..1600).step_by(2).collect(); + let spans: Vec<(usize, usize)> = positions.iter().map(|position| (*position, 1)).collect(); + let expected: Vec> = (0..positions.len()) + .map(|index| Some(index as f64)) + .collect(); + let mut chunk = series_on(&schema, &spans, expected.clone(), labels("large")); + chunk.fields = SeriesFields::one( + Samples::try_from_chunks( + expected + .iter() + .map(|value| Samples::from_float(Float64Array::from(vec![*value]))) + .collect(), + ) + .unwrap(), + ); + let polls = Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let dropped = Arc::new(std::sync::atomic::AtomicBool::new(false)); + let upstream = observed_source(vec![Ok((chunk, true))], polls.clone(), dropped.clone()); + let mut stream = pack_evaluated_series(upstream, schema.clone()).unwrap(); + let mut batches = Vec::new(); + let mut batch = stream.next().await.unwrap().unwrap(); + assert_eq!(batch.num_rows(), SeriesFrameBuilder::DEFAULT_MAX_ROWS); + batches.push(batch); + assert_eq!(polls.load(Ordering::SeqCst), 1); + for _ in 0..2 { + batch = stream.next().await.unwrap().unwrap(); + assert_eq!(batch.num_rows(), SeriesFrameBuilder::DEFAULT_MAX_ROWS); + batches.push(batch); + assert_eq!(polls.load(Ordering::SeqCst), 1); + } + while let Some(batch) = stream.next().await { + batches.push(batch.unwrap()); + } + assert!(batches.len() > 1); + assert!(dropped.load(Ordering::SeqCst)); + assert!(stream.next().await.is_none()); + assert!(stream.next().await.is_none()); + let declared = batches[0].schema(); + let (source, _, _) = df_source(batches, declared); + let rows = drain(unpack_evaluated_series(source, Some(schema)).unwrap()).await; + let (actual_positions, actual_values) = flat(&rows); + assert_eq!(actual_positions, positions); + assert_float_payload_eq(&actual_values, &expected, "large sparse values"); + assert_eq!(rows.iter().filter(|(_, last)| *last).count(), 1); + assert!(rows.last().unwrap().1); +} + +/// Dropping a partially drained output releases both upstream and buffered label ownership. +#[tokio::test] +async fn evaluated_pack_drop_releases_unfinished_large_chunk() { + let identity: Arc = Arc::from("drop-aware"); + let weak = Arc::downgrade(&identity); + let metric = SeriesLabels::try_new(Some(identity.clone()), vec![]).unwrap(); + let schema = large_evaluated_schema(); + let positions: Vec = (0..1600).step_by(2).collect(); + let spans: Vec<(usize, usize)> = positions.iter().map(|position| (*position, 1)).collect(); + let mut chunk = series_on(&schema, &spans, vec![Some(1.0); spans.len()], metric); + chunk.fields = SeriesFields::one( + Samples::try_from_chunks( + (0..positions.len()) + .map(|_| Samples::from_float(Float64Array::from(vec![Some(1.0)]))) + .collect(), + ) + .unwrap(), + ); + drop(identity); + let polls = Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let dropped = Arc::new(std::sync::atomic::AtomicBool::new(false)); + let upstream = observed_source(vec![Ok((chunk, true))], polls, dropped.clone()); + let mut stream = pack_evaluated_series(upstream, schema).unwrap(); + assert!(stream.next().await.unwrap().unwrap().num_rows() > 0); + assert!(!dropped.load(Ordering::SeqCst), "output is unfinished"); + assert!(weak.upgrade().is_some(), "buffered output retains labels"); + drop(stream); + assert!(dropped.load(Ordering::SeqCst)); + assert!( + weak.upgrade().is_none(), + "drop releases buffered label owner" + ); +} + +/// A source error discards buffered success rather than publishing it before the error. +#[tokio::test] +async fn evaluated_pack_error_discards_buffer_and_releases_source() { + let identity: Arc = Arc::from("error-owner"); + let weak = Arc::downgrade(&identity); + let metric = SeriesLabels::try_new(Some(identity.clone()), vec![]).unwrap(); + let chunk = series(&[(0, 1)], vec![Some(1.0)], metric); + drop(identity); + let error = BoxedError::new(PlainError::new( + "source failed".into(), + StatusCode::Unsupported, + )); + let polls = Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let dropped = Arc::new(std::sync::atomic::AtomicBool::new(false)); + let upstream = observed_source( + vec![Ok((chunk, false)), Err(error)], + polls.clone(), + dropped.clone(), + ); + let mut stream = pack_evaluated_series(upstream, evaluated_schema()).unwrap(); + assert!(stream.next().await.unwrap().is_err()); + assert!(dropped.load(Ordering::SeqCst)); + assert_eq!(polls.load(Ordering::SeqCst), 2); + assert!(weak.upgrade().is_none()); + assert!(stream.next().await.is_none()); + assert!(stream.next().await.is_none()); +} + +/// Dense source chunks coalesce to one frame row each while preserving order and finality across batches. +#[tokio::test] +async fn multi_chunk_multi_batch_stream_preserves_order_and_finality() { + let metric = labels("d"); + let first: Vec> = (0..300).map(|row| Some(row as f64)).collect(); + let second: Vec> = (0..10).map(|row| Some(row as f64)).collect(); + let batches = packed(vec![ + ( + series(&single_position_spans(0, 300), first, metric.clone()), + false, + ), + ( + series(&single_position_spans(300, 10), second, metric.clone()), + true, + ), + ]) + .await; + assert_eq!(batches.len(), 1, "both dense chunks fit in one batch"); + assert_eq!( + batches.iter().map(RecordBatch::num_rows).sum::(), + 2, + "one frame row per dense chunk" + ); + + let declared = batches[0].schema(); + assert!(batches.iter().all(|batch| batch.schema() == declared)); + let rows = drain(unpack(batches, declared)).await; + let (decoded_positions, _) = flat(&rows); + assert_eq!( + decoded_positions, + (0..310).collect::>(), + "no position is repeated, reordered, or dropped across batches" + ); + assert!(rows.iter().all(|(row, _)| row.metric == metric)); + let closes = rows + .iter() + .enumerate() + .filter(|(_, (_, is_last))| *is_last) + .map(|(index, _)| index) + .collect::>(); + assert_eq!( + closes, + vec![rows.len() - 1], + "exactly the last row closes the chain, inherited from the source's final chunk" + ); +} + +/// Two chains whose labels happen to be equal are two chains: each closes itself, and the second is +/// not mistaken for a reopened series. +#[tokio::test] +async fn consecutive_chains_with_equal_labels_each_close_independently() { + let metric = labels("e"); + let batches = packed(vec![ + ( + series(&[(0, 2)], vec![Some(1.0), Some(2.0)], metric.clone()), + true, + ), + ( + series(&[(2, 2)], vec![Some(3.0), Some(4.0)], metric.clone()), + true, + ), + ]) + .await; + + let declared = batches[0].schema(); + let rows = drain(unpack(batches, declared)).await; + assert_eq!(rows.len(), 2, "one row per source chunk"); + assert!( + rows.iter().all(|(_, is_last)| *is_last), + "each chain closes itself, so neither is refused as a reopened series" + ); + assert!(rows.iter().all(|(row, _)| row.metric == metric)); + assert_eq!(positions(&rows[0].0), vec![0, 1]); + assert_eq!(values(&rows[0].0), vec![Some(1.0), Some(2.0)]); + assert_eq!(positions(&rows[1].0), vec![2, 3]); + assert_eq!(values(&rows[1].0), vec![Some(3.0), Some(4.0)]); +} + +/// Malformed chunks are rejected before buffered rows escape, and terminal failures release the +/// producer and any label owners held by its chunks. +#[tokio::test] +async fn evaluated_pack_rejects_malformed_sequences_before_publishing() { + let cases = [ + ( + "identity changed", + vec![ + (series(&[(0, 1)], vec![Some(1.0)], labels("first")), false), + (series(&[(1, 1)], vec![Some(2.0)], labels("other")), true), + ], + "identity changed", + ), + ( + "overlap", + vec![ + ( + series(&[(1, 2)], vec![Some(1.0), Some(2.0)], labels("same")), + false, + ), + (series(&[(2, 1)], vec![Some(3.0)], labels("same")), true), + ], + "positions are not increasing", + ), + ( + "backward", + vec![ + (series(&[(3, 1)], vec![Some(1.0)], labels("same")), false), + (series(&[(1, 1)], vec![Some(2.0)], labels("same")), true), + ], + "positions are not increasing", + ), + ]; + for (name, mut items, expected_error) in cases { + let owner: Arc = Arc::from("tracked-label-owner"); + let weak = Arc::downgrade(&owner); + if name != "identity changed" { + let metric_name = items[0].0.metric.name().map(Arc::::from); + let tracked = SeriesLabels::try_new( + metric_name, + vec![Label { + name: Arc::from("tracked"), + value: owner.clone(), + }], + ) + .unwrap(); + for (chunk, _) in &mut items { + chunk.metric = tracked.clone(); + } + } + drop(owner); + let polls = Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let dropped = Arc::new(std::sync::atomic::AtomicBool::new(false)); + let upstream = observed_source(items.into_iter().map(Ok).collect(), polls, dropped.clone()); + let mut stream = pack_evaluated_series(upstream, evaluated_schema()).unwrap(); + let error = stream.next().await.unwrap().unwrap_err(); + assert!( + error.to_string().contains(expected_error), + "{name}: {error}" + ); + assert!(dropped.load(Ordering::SeqCst), "{name}: source dropped"); + if name != "identity changed" { + assert!(weak.upgrade().is_none(), "{name}: label owner released"); + } + assert!(stream.next().await.is_none(), "{name}: stable EOF"); + assert!(stream.next().await.is_none(), "{name}: repeated EOF"); + } +} + +/// A chain still open at EOF is an error on both sides: a producer that never closed a series cannot +/// finish, and a receiver cannot pretend the stream ended cleanly. +#[tokio::test] +async fn eof_with_an_open_chain_is_an_error() { + let metric = labels("f"); + let mut stream = pack(vec![( + series(&[(0, 2)], vec![Some(1.0), Some(2.0)], metric.clone()), + false, + )]); + // The rows are buffered until EOF, where the missing close is reported instead of a batch. + let error = loop { + match stream.next().await { + Some(Ok(_)) => continue, + Some(Err(error)) => break error, + None => panic!("an open chain at EOF must be reported"), + } + }; + assert_eq!( + crate::error::datafusion_status_code::(&error, None), + StatusCode::InvalidArguments + ); + assert!(stream.next().await.is_none(), "the error is reported once"); + + // The receiving side reaches the same conclusion from the frame alone. + let closing = packed(vec![( + series(&[(0, 2)], vec![Some(1.0), Some(2.0)], metric), + true, + )]) + .await; + let declared = closing[0].schema(); + let opened = with_is_last(&closing[0], false); + let (source, _, _) = df_source(vec![opened], declared); + let mut unpacked = unpack_evaluated_series(source, Some(evaluated_schema())).unwrap(); + assert!(!unpacked.next().await.unwrap().unwrap().1); + let error = unpacked.next().await.unwrap().unwrap_err(); + assert_eq!(error.status_code(), StatusCode::InvalidArguments); + assert!(unpacked.next().await.is_none()); +} + +/// A chunk with no position that does not close its chain can never make progress, so both sides +/// refuse it. +#[tokio::test] +async fn zero_sample_chunk_that_does_not_close_is_rejected() { + let metric = labels("g"); + let mut stream = pack(vec![(series(&[], vec![], metric.clone()), false)]); + let error = stream.next().await.unwrap().unwrap_err(); + assert_eq!( + crate::error::datafusion_status_code::(&error, None), + StatusCode::InvalidArguments + ); + assert!(stream.next().await.is_none()); + + let closing = packed(vec![(series(&[], vec![], metric), true)]).await; + assert_eq!(closing[0].num_rows(), 1); + let declared = closing[0].schema(); + let not_closing = with_is_last(&closing[0], false); + let (source, _, _) = df_source(vec![not_closing], declared); + let mut unpacked = unpack_evaluated_series(source, Some(evaluated_schema())).unwrap(); + let error = unpacked.next().await.unwrap().unwrap_err(); + assert_eq!(error.status_code(), StatusCode::InvalidArguments); + assert!(unpacked.next().await.is_none()); +} + +/// Computed values have no storage key to be ordered by, so an evaluated frame that declares any +/// other ordering, or a spelling the wire does not define, is refused before the stream is returned. +#[tokio::test] +async fn evaluated_frame_rejects_non_contiguous_ordering() { + let batches = packed(vec![( + series(&[(0, 1)], vec![Some(1.0)], labels("h")), + true, + )]) + .await; + let declared = batches[0].schema(); + for ordering in ["read_key_then_time", "interleaved"] { + let schema = relabelled(&declared, "greptime.series.ordering", Some(ordering)); + let (source, polls, _) = df_source(vec![], schema); + assert!( + unpack_evaluated_series(source, Some(evaluated_schema())).is_err(), + "{ordering} is not an ordering computed values can claim" + ); + assert_eq!(polls.load(Ordering::SeqCst), 0); + } +} + +/// Every contradictory or unreadable declaration is refused instead of decoded: a missing or +/// malformed grid, a time mode that contradicts the content, and keyed identity on computed values. +#[tokio::test] +async fn evaluated_frame_rejects_contradictory_declarations() { + let batches = packed(vec![( + series(&[(0, 1)], vec![Some(1.0)], labels("i")), + true, + )]) + .await; + let declared = batches[0].schema(); + let cases: [(&str, SchemaRef); 6] = [ + ( + "no grid", + relabelled(&declared, "greptime.series.grid", None), + ), + ( + "malformed grid", + relabelled(&declared, "greptime.series.grid", Some("grid")), + ), + ( + "incomplete grid", + relabelled(&declared, "greptime.series.grid", Some(r#"{"start_ms":0}"#)), + ), + ( + "evaluated with timestamps", + relabelled(&declared, "greptime.series.time", Some("timestamps")), + ), + ( + "evaluated with key labels", + relabelled(&declared, "greptime.series.labels", Some("key")), + ), + ( + "raw content", + relabelled(&declared, "greptime.series.content", Some("raw")), + ), + ]; + for (label, schema) in cases { + let (source, polls, _) = df_source(vec![], schema); + assert!( + unpack_evaluated_series(source, None).is_err(), + "{label}: must be rejected" + ); + assert_eq!( + polls.load(Ordering::SeqCst), + 0, + "{label}: a rejected frame is never polled" + ); + } + + // `expected` is a check, never an input: a schema without the frame's grid is a disagreement. + let (source, _, _) = df_source(vec![], declared); + assert!( + unpack_evaluated_series(source, Some(schema())).is_err(), + "a raw expectation cannot decode an evaluated frame" + ); +} + +/// The two contents are not interchangeable: each unpack entry point refuses the other's frame. +#[tokio::test] +async fn each_unpack_entry_point_refuses_the_other_content() { + let evaluated = packed(vec![( + series(&[(0, 1)], vec![Some(1.0)], labels("j")), + true, + )]) + .await; + let declared = evaluated[0].schema(); + let (source, _, _) = df_source(evaluated, declared); + assert!( + unpack_raw_series(source, None).is_err(), + "a raw reader cannot decode grid-addressed rows" + ); + + let raw_frame = datatypes::series::frame::raw_series_frame_schema( + &schema(), + datatypes::series::frame::FrameLabelMode::Explicit, + ) + .unwrap(); + let (source, _, _) = df_source(vec![], raw_frame); + assert!( + unpack_evaluated_series(source, None).is_err(), + "an evaluated reader cannot decode timestamp-addressed rows" + ); +} + +/// An evaluated row names its series by label, so a row that also carries a storage key is a +/// contradiction: the reader refuses it instead of decoding an identity it cannot check. +#[tokio::test] +async fn evaluated_frame_rejects_a_storage_key_on_a_row() { + let batches = packed(vec![( + series(&[(0, 2)], vec![Some(1.0), Some(2.0)], labels("l")), + true, + )]) + .await; + let declared = batches[0].schema(); + let keyed = with_read_key(&batches[0], b"encoded-key"); + let (source, _, _) = df_source(vec![keyed], declared); + let mut unpacked = unpack_evaluated_series(source, Some(evaluated_schema())).unwrap(); + let error = unpacked.next().await.unwrap().unwrap_err(); + assert_eq!(error.status_code(), StatusCode::InvalidArguments); + assert!(unpacked.next().await.is_none()); +} + +/// An evaluated frame is self-describing across Arrow IPC: the schema, its metadata, and its rows +/// survive serialization, and a consumer decodes them with no planning-side copy of the grid. +#[tokio::test] +async fn evaluated_frame_roundtrips_through_arrow_ipc() { + let metric = labels("k"); + let expected: Vec> = vec![Some(1.5), None, Some(3.5)]; + let batches = packed(vec![( + series(&[(0, 2), (4, 1)], expected.clone(), metric.clone()), + true, + )]) + .await; + let declared = batches[0].schema(); + + let mut ipc = Vec::new(); + { + let mut writer = StreamWriter::try_new(&mut ipc, &declared).unwrap(); + for batch in &batches { + writer.write(batch).unwrap(); + } + writer.finish().unwrap(); + } + let reader = StreamReader::try_new(Cursor::new(ipc), None).unwrap(); + let read_schema = reader.schema(); + assert_eq!(read_schema, declared); + assert_eq!( + datatypes::series::frame::SeriesFrameDeclaration::parse(read_schema.as_ref()) + .unwrap() + .series() + .eval_grid + .as_ref() + .expect("the frame still declares its grid") + .spec(), + evaluated_grid().spec() + ); + + let read: Vec = reader.map(Result::unwrap).collect(); + assert_eq!(read.len(), batches.len()); + let (source, _, _) = df_source(read, read_schema); + // No `expected` schema is supplied: the frame alone says what its rows mean. + let rows = drain(unpack_evaluated_series(source, None).unwrap()).await; + let (decoded_positions, decoded_values) = flat(&rows); + assert_eq!(decoded_positions, vec![0, 1, 4]); + assert_eq!(decoded_values, expected); + assert!(rows.iter().all(|(row, _)| row.metric == metric)); + assert!(rows.last().expect("at least one row").1); +} + +/// A schema with two value fields addressed on [`evaluated_grid`], so a fixture can carry more than +/// the single float field [`series`] declares. +fn pair_schema() -> Arc { + Arc::new(SeriesSchema { + fields: vec![ + FieldSpec { + name: Arc::from("value"), + }, + FieldSpec { + name: Arc::from("score"), + }, + ] + .into(), + eval_grid: Some(evaluated_grid()), + }) +} + +/// One validated evaluated chunk: `fields` on the runs `spans` of the shared test grid, declared +/// under `schema`. +fn chunk_on( + schema: &SeriesSchema, + spans: &[(usize, usize)], + fields: SeriesFields, + metric: SeriesLabels, +) -> Series { + let time = TimeAxis::from_grid_spans( + evaluated_grid(), + spans + .iter() + .map(|(start, len)| GridSpan::new(*start, *len)) + .collect(), + ) + .unwrap(); + Series::try_new(schema, metric, time, fields).unwrap() +} + +/// Packs the supplied chunks under `schema` and drains every ready batch, for a fixture whose field +/// list is not the single `value` field [`evaluated_schema`] declares. +async fn packed_under(schema: Arc, items: Vec<(Series, bool)>) -> Vec { + let mut stream = pack_evaluated_series(source(items), schema).unwrap(); + let mut out = Vec::new(); + while let Some(batch) = stream.next().await { + out.push(batch.unwrap()); + } + out +} + +/// Unpacks a producer's batches as a consumer that planned the same series schema would, which is +/// how a fixture with more than the one `value` field is read back. +fn unpack_as( + batches: Vec, + declared: SchemaRef, + expected: Arc, +) -> SendableEvaluatedSeriesStream { + let (source, _, _) = df_source(batches, declared); + unpack_evaluated_series(source, Some(expected)).unwrap() +} + +/// The float payload of field `index`, in compact-row order. +fn field_values(series: &Series, index: usize) -> Vec> { + series + .fields + .get(index) + .expect("the fixture reads a field it declared") + .iter() + .map(|sample| match sample { + SampleRef::Missing => None, + SampleRef::Float(value) => Some(value), + _ => panic!("the fixture carries float samples"), + }) + .collect() +} + +/// Compares two per-position float payloads, with `NaN` comparing equal to itself. +/// +/// `Option` cannot be compared with `==` here: the fixtures carry `NaN` as a *value*, and +/// `NaN != NaN`, so equality would report a faithful round trip as a mismatch. Comparing bit +/// patterns keeps a value distinct from a missing position, and `None` still has to meet `None`. +fn assert_float_payload_eq(actual: &[Option], expected: &[Option], field: &str) { + assert_eq!(actual.len(), expected.len(), "{field}: position count"); + for (position, (lhs, rhs)) in actual.iter().zip(expected).enumerate() { + match (lhs, rhs) { + (None, None) => {} + (Some(lhs), Some(rhs)) => assert_eq!( + lhs.to_bits(), + rhs.to_bits(), + "{field}: position {position} must keep its value" + ), + _ => panic!("{field}: position {position} is {lhs:?}, expected {rhs:?}"), + } + } +} + +/// How many positions carry a `NaN` value and how many carry nothing, counted separately because +/// the two must not be confused on the way through the codec. +fn nan_and_null_counts(values: &[Option]) -> (usize, usize) { + let nan = values + .iter() + .filter(|value| value.is_some_and(|value| value.is_nan())) + .count(); + let null = values.iter().filter(|value| value.is_none()).count(); + (nan, null) +} + +/// The native histogram table the histogram fixture references: two rows with distinct sums, the +/// first with a start timestamp and the second without. +/// +/// The shape is the one `datatypes::series::frame::tests::histogram_batch_with_sum` builds, so this +/// test compares against the same payload the frame layer's own tests use instead of inventing a +/// second fixture. +fn histogram_batch() -> Arc { + 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 view = |sum, start_timestamp| 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, + }, + }; + let mut builder = HistogramBatchBuilder::new(); + builder.push(view(-9.5, Some(-123))).unwrap(); + builder.push(view(90.5, None)).unwrap(); + builder.finish().unwrap() +} + +/// The payload struct of one field of a frame batch: the float list and the histogram payload. +/// +/// A field is one column of the frame's `fields` struct, so this is how a test can tell which +/// representation the codec put on the wire instead of only what came back out of it. +fn frame_field_payload(batch: &RecordBatch, field: usize) -> &StructArray { + batch + .column(3) + .as_any() + .downcast_ref::() + .expect("a frame carries its fields as a struct") + .column(field) + .as_any() + .downcast_ref::() + .expect("a field payload is a struct") +} + +/// A multi-field chunk keeps each field's missing positions independent: one position carries a +/// value in one field and nothing in the other, and a `NaN` value never collapses into a missing one. +/// +/// This is the spec's `evaluated/multi-field` case. A schema snapshot cannot stand in for it, because +/// `NaN` and a missing value are both "no ordinary number" once the payload is only a list: which of +/// the two a position holds is visible only after a round trip. +#[tokio::test] +async fn multi_field_partial_nulls_are_not_nan() { + // Position 0 carries only `value` and position 2 only `score`. `NaN` is a value in both fields, + // and the position next to it in the other field is missing. + let value: Vec> = vec![Some(1.0), Some(f64::NAN), None, Some(f64::NAN), Some(4.0)]; + let score: Vec> = vec![None, None, Some(3.0), Some(5.0), Some(f64::NAN)]; + let metric = labels("n"); + let schema = pair_schema(); + let fields = SeriesFields::try_from_vec(vec![ + Samples::from_float(Float64Array::from(value.clone())), + Samples::from_float(Float64Array::from(score.clone())), + ]) + .unwrap(); + let batches = packed_under( + schema.clone(), + vec![( + chunk_on(&schema, &[(0, 2), (5, 3)], fields, metric.clone()), + true, + )], + ) + .await; + // Sparse runs share one frame row; the grid hole is still represented by separate spans. + assert_eq!(batches.len(), 1); + assert_eq!(batches[0].num_rows(), 1); + // Both fields are columns of the row, and both carry float values of their own. + for row in 0..batches[0].num_rows() { + for field in [0, 1] { + let payload = frame_field_payload(&batches[0], field); + assert!( + !payload.column(0).is_null(row), + "field {field} carries a float payload on row {row}" + ); + } + } + + let declared = batches[0].schema(); + let rows = drain(unpack_as(batches, declared, schema)).await; + assert_eq!(rows.len(), 1, "one decoded chunk per frame row"); + assert!( + rows.iter().all(|(row, _)| row.metric == metric), + "the row names the same series" + ); + assert!(rows[0].1, "the sole coalesced row closes the chain"); + // Concatenated in stream order, exactly as the producer's single chunk was laid out. + let decoded_positions: Vec = rows.iter().flat_map(|(row, _)| positions(row)).collect(); + assert_eq!( + decoded_positions, + vec![0, 1, 5, 6, 7], + "the hole between the two runs is not filled" + ); + let decoded_value: Vec> = rows + .iter() + .flat_map(|(row, _)| field_values(row, 0)) + .collect(); + let decoded_score: Vec> = rows + .iter() + .flat_map(|(row, _)| field_values(row, 1)) + .collect(); + // Per position, because each field decides for itself whether it holds a value. + assert_float_payload_eq(&decoded_value, &value, "value"); + assert_float_payload_eq(&decoded_score, &score, "score"); + // `NaN` and null are counted apart: a codec that turned one into the other would keep the + // position count and the alignment while losing the distinction this test is about. + assert_eq!( + nan_and_null_counts(&decoded_value), + nan_and_null_counts(&value), + "value: the NaN and null counts survive" + ); + assert_eq!( + nan_and_null_counts(&decoded_score), + nan_and_null_counts(&score), + "score: the NaN and null counts survive" + ); + assert_eq!( + nan_and_null_counts(&decoded_value), + (2, 1), + "two NaN values and one null, not three nulls" + ); + assert_eq!( + nan_and_null_counts(&decoded_score), + (1, 2), + "one NaN value and two nulls, not three values" + ); + // The same position carries a value in one field and nothing in the other, in both directions. + assert_eq!(decoded_value[0], Some(1.0)); + assert_eq!(decoded_score[0], None); + assert_eq!(decoded_value[2], None); + assert_eq!(decoded_score[2], Some(3.0)); + // And a NaN is a value: it keeps its own position, where the other field is missing. + assert!(decoded_value[1].is_some_and(f64::is_nan)); + assert_eq!(decoded_score[1], None); +} + +/// A histogram field keeps its native payload across the wire: the frame carries the table and the +/// per-position references to it, so what a consumer decodes is still a histogram. +/// +/// This is the spec's `native histogram/mixed` case. A length check cannot stand in for it, because a +/// silent float rendition preserves the position count; what rules the conversion out is the payload +/// kind on both sides of the wire and the values behind the references. +#[tokio::test] +async fn histogram_payload_roundtrips_without_float_conversion() { + let table = histogram_batch(); + let indices = UInt32Array::from(vec![Some(0), None, Some(1)]); + let samples = Samples::try_from_histogram(indices.clone(), table).unwrap(); + let metric = labels("m"); + let batches = packed(vec![( + chunk_on( + &evaluated_schema(), + &[(3, 3)], + SeriesFields::one(samples), + metric.clone(), + ), + true, + )]) + .await; + assert_eq!(batches.len(), 1); + assert_eq!(batches[0].num_rows(), 1, "one run is one frame row"); + + // On the wire the field is a payload struct that carries the histogram and no float list, so the + // codec never filled a float rendition in on the way out. + let payload = frame_field_payload(&batches[0], 0); + assert!( + payload.column(0).is_null(0), + "a histogram field has no float payload" + ); + assert!( + !payload.column(1).is_null(0), + "the histogram payload is what the frame carries" + ); + + let declared = batches[0].schema(); + let rows = drain(unpack(batches, declared)).await; + assert_eq!(rows.len(), 1); + let (decoded, is_last) = &rows[0]; + assert!(is_last); + assert_eq!(decoded.metric, metric); + assert_eq!(positions(decoded), vec![3, 4, 5]); + let field = decoded.fields.get(0).expect("the fixture has one field"); + let DenseSamplesRef::Histogram(histograms) = field.dense().expect("the field is dense") else { + panic!("a histogram field must decode as a histogram, not as a float or mixed segment"); + }; + assert_eq!(histograms.len(), 3, "every position is still there"); + assert_eq!( + histograms.batch().len(), + 2, + "both input histograms are still referenced" + ); + let decoded_indices = histograms.indices(); + assert_eq!(decoded_indices.len(), indices.len()); + for position in 0..indices.len() { + assert_eq!( + decoded_indices.is_valid(position), + indices.is_valid(position), + "position {position}: a null reference stays null" + ); + if indices.is_valid(position) { + assert_eq!(decoded_indices.value(position), indices.value(position)); + } + } + // The values behind the references are the input payload, not a lossy rendition of it. + let first = histograms + .view_at(0) + .expect("position 0 references a histogram"); + assert_eq!(first.count.to_bits(), 17.25_f64.to_bits()); + assert_eq!(first.sum.to_bits(), (-9.5_f64).to_bits()); + assert_eq!(first.start_timestamp, Some(-123)); + assert_eq!( + first + .positive + .buckets + .iter() + .map(|bucket| bucket.to_bits()) + .collect::>(), + [3.25_f64.to_bits(), 7.5_f64.to_bits()] + ); + assert!( + histograms.view_at(1).is_none(), + "a null reference stays missing instead of resolving to a neighbour's payload" + ); + let second = histograms + .view_at(2) + .expect("position 2 references a histogram"); + assert_eq!(second.count.to_bits(), 17.25_f64.to_bits()); + assert_eq!(second.sum.to_bits(), 90.5_f64.to_bits()); + assert_eq!(second.start_timestamp, None); + // The per-position kind survives as well: a referenced position is a histogram sample, never a + // float one. + assert!(matches!(field.sample(0), SampleRef::Histogram(_))); + assert!(matches!(field.sample(1), SampleRef::Missing)); + assert!(matches!(field.sample(2), SampleRef::Histogram(_))); +} + +/// One field can hold floats and histograms at different positions, and the codec keeps them apart: +/// each position decodes as the kind it was written as. +/// +/// This is the `native histogram/mixed` case in its harder form. A codec could keep the position +/// count and still promote one kind into the other in a single position, which only a per-position +/// kind comparison catches. +#[tokio::test] +async fn mixed_payload_roundtrips_without_dropping_either_kind() { + let table = histogram_batch(); + // Position 0 is a float, 1 a histogram, 2 nothing, and 3 a NaN float - which must not be read as + // a missing position, nor as the neighbouring histogram. + let floats = Float64Array::from(vec![Some(1.5), None, None, Some(f64::NAN)]); + let indices = UInt32Array::from(vec![None, Some(0), None, None]); + let histograms = datatypes::series::samples::HistogramSamples::try_new(indices, table).unwrap(); + let samples = Samples::try_from_mixed(floats, histograms).unwrap(); + let metric = labels("o"); + let batches = packed(vec![( + chunk_on( + &evaluated_schema(), + &[(6, 4)], + SeriesFields::one(samples), + metric.clone(), + ), + true, + )]) + .await; + assert_eq!(batches.len(), 1); + assert_eq!(batches[0].num_rows(), 1); + + // A mixed field is the one payload shape that carries both halves, so the frame neither dropped + // the float positions nor flattened the histogram ones. + let payload = frame_field_payload(&batches[0], 0); + assert!( + !payload.column(0).is_null(0), + "a mixed field carries its floats" + ); + assert!( + !payload.column(1).is_null(0), + "a mixed field carries its histograms" + ); + + let declared = batches[0].schema(); + let rows = drain(unpack(batches, declared)).await; + assert_eq!(rows.len(), 1); + let (decoded, is_last) = &rows[0]; + assert!(is_last); + assert_eq!(decoded.metric, metric); + assert_eq!(positions(decoded), vec![6, 7, 8, 9]); + let field = decoded.fields.get(0).expect("the fixture has one field"); + let DenseSamplesRef::Mixed(mixed) = field.dense().expect("the field is dense") else { + panic!("a mixed field must decode as mixed, not as one of its two halves"); + }; + assert_eq!(mixed.floats().len(), 4); + assert_eq!(mixed.histograms().len(), 4); + assert_eq!( + mixed.histograms().batch().len(), + 1, + "only the referenced histogram row survives compaction" + ); + match field.sample(0) { + SampleRef::Float(value) => assert_eq!(value.to_bits(), 1.5_f64.to_bits()), + _ => panic!("position 0 was a float"), + } + match field.sample(1) { + SampleRef::Histogram(histogram) => { + assert_eq!(histogram.count.to_bits(), 17.25_f64.to_bits()); + assert_eq!(histogram.sum.to_bits(), (-9.5_f64).to_bits()); + assert_eq!(histogram.start_timestamp, Some(-123)); + } + _ => panic!("position 1 was a histogram"), + } + assert!(matches!(field.sample(2), SampleRef::Missing)); + assert!(mixed.histograms().view_at(2).is_none()); + match field.sample(3) { + // A NaN float stays a float value, and its histogram slot stays empty. + SampleRef::Float(value) => assert!(value.is_nan()), + _ => panic!("position 3 was a NaN float"), + } +} + +/// A frame whose spans add up beyond `usize` is refused, not answered with a wrapped count. +/// +/// The count of a row's positions is the first arithmetic a decoded row does, and it happens before +/// the row is checked against the grid it claims: two spans of `usize::MAX / 2 + 1` each are neither +/// ordered nor inside any grid, but summing them is what a decoder would do first. The sum is +/// therefore checked, so the frame is refused with an error instead of panicking in a debug build or +/// wrapping in a release one. +#[tokio::test] +async fn spans_that_overflow_the_position_count_are_refused() { + let batches = packed(vec![( + series(&[(0, 2)], vec![Some(1.0), Some(2.0)], labels("v")), + true, + )]) + .await; + let declared = batches[0].schema(); + let huge = u64::try_from(usize::MAX / 2 + 1).expect("a stride that leaves usize behind"); + // Two spans, because one is already representable: only their sum leaves `usize`, and that sum + // is what a decoder must check before it can report which span was wrong. + let hostile = with_spans(&batches[0], &[(0, huge), (huge, huge)], true); + let mut stream = unpack(vec![hostile], declared); + let error = stream + .next() + .await + .expect("a refused frame still yields its error") + .expect_err("the position count overflows"); + assert!( + error.to_string().contains("grid span length overflow"), + "refused for another reason: {error}" + ); +} + +/// An empty row that closes nothing is refused by the decoder itself, not only by the stream. +/// +/// A row covering no position is the closing chunk's shape: it exists to carry `is_last`. One that +/// carries `is_last = false` opens a chain it can never advance, so a consumer would wait for a +/// close that no later row owes. The stream validator refuses this, and so does the public decoder, +/// because a caller driving the decoder directly must not be handed a chunk no producer could have +/// written. +#[tokio::test] +async fn an_empty_row_that_closes_nothing_is_refused_by_the_decoder() { + // A legal empty closing chunk is packed first: the illegal shape cannot be produced, which is + // the point of the check below. Making it illegal means clearing its finality and nothing else, + // so the emptiness and the payload lengths stay consistent and only finality can refuse it. + let batches = packed(vec![(series(&[], vec![], labels("w")), true)]).await; + let declared = batches[0].schema(); + assert_eq!(1, batches[0].num_rows(), "the closing chunk is one row"); + let emptied = with_spans(&batches[0], &[], false); + let mut stream = unpack(vec![emptied], declared); + let error = stream + .next() + .await + .expect("a refused frame still yields its error") + .expect_err("an empty row that closes nothing is refused"); + assert!( + error + .to_string() + .contains("an evaluated chunk without positions must close its series"), + "refused for another reason: {error}" + ); +} + +/// Rewrites the span list of every row in `batch` to `spans`, and its finality to `is_last`. +/// +/// Both are rewritten together because a test that breaks a row's shape usually breaks its finality +/// as well: a producer cannot write an empty row that closes nothing, so such a row only exists once +/// a test builds it. +fn with_spans(batch: &RecordBatch, spans: &[(u64, u64)], is_last: bool) -> RecordBatch { + let declared = batch.schema(); + let DataType::Struct(time_members) = declared.field(2).data_type() else { + panic!("time is a struct"); + }; + let DataType::List(span_item) = time_members[0].data_type() else { + panic!("spans are a list"); + }; + let DataType::Struct(span_fields) = span_item.data_type() else { + panic!("a span is a struct"); + }; + let starts: Vec = spans.iter().map(|(start, _)| *start).collect(); + let lengths: Vec = spans.iter().map(|(_, len)| *len).collect(); + let values = StructArray::try_new( + span_fields.clone(), + vec![ + Arc::new(UInt64Array::from(starts)), + Arc::new(UInt64Array::from(lengths)), + ], + None, + ) + .unwrap(); + let lengths_per_row = vec![spans.len(); batch.num_rows()]; + let list = ListArray::try_new( + span_item.clone(), + OffsetBuffer::new(offset_buffer(&lengths_per_row).into()), + Arc::new(values), + None, + ) + .unwrap(); + let time = StructArray::try_new(time_members.clone(), vec![Arc::new(list)], None).unwrap(); + let mut columns = batch.columns().to_vec(); + columns[1] = Arc::new(BooleanArray::from(vec![is_last; batch.num_rows()])); + columns[2] = Arc::new(time); + RecordBatch::try_new_with_options( + declared, + columns, + &RecordBatchOptions::new().with_row_count(Some(batch.num_rows())), + ) + .unwrap() +} + +/// The cumulative list offsets of the given row lengths. +fn offset_buffer(lengths: &[usize]) -> Vec { + let mut offsets = Vec::with_capacity(lengths.len() + 1); + let mut total = 0i32; + offsets.push(0); + for length in lengths { + total += i32::try_from(*length).expect("a test row fits an Arrow offset"); + offsets.push(total); + } + offsets +} + +/// A cursor holding positions on one grid cannot fill a builder that declares another. +/// +/// Both grids describe the same number of points, so every position the cursor writes is in range +/// for the builder and the frame would decode cleanly. What it would decode to is a different set of +/// instants, which no later check could detect: the numbers are the only thing on the wire. The +/// builder therefore compares the grids themselves, not whether a grid is present. +#[test] +fn a_cursor_on_one_grid_cannot_fill_a_builder_declaring_another() { + // Both grids have four points, so the cursor's positions fit the builder exactly. + let other_grid = || { + Arc::new( + datatypes::series::time::EvalGrid::try_new( + datatypes::series::time::GridSpec::try_new(60_000, 10_000, 4) + .expect("a valid grid"), + ) + .expect("a valid grid"), + ) + }; + let other_schema = SeriesSchema { + fields: evaluated_schema().fields.clone(), + eval_grid: Some(other_grid()), + }; + // A chunk that is legal on its own grid: the series and the schema agree, so nothing but the + // builder's own declaration can refuse it. + let fields = SeriesFields::one(Samples::from_float(Float64Array::from(vec![Some(1.0)]))); + let time = TimeAxis::from_grid_spans(other_grid(), vec![GridSpan::new(0, 1)]) + .expect("one span on its own grid"); + let chunk = Series::try_new(&other_schema, labels("g"), time, fields).expect("a legal chunk"); + let mut cursor = + SeriesFrameCursor::try_new_evaluated(&other_schema, chunk, true).expect("a legal cursor"); + + let mut builder = SeriesFrameBuilder::try_new( + &evaluated_schema(), + FrameLabelMode::Explicit, + None, + SeriesFrameBuilder::DEFAULT_MAX_ROWS, + SeriesFrameBuilder::DEFAULT_MAX_BYTES, + ) + .expect("the schema is a frame"); + let error = cursor + .append_to(&mut builder) + .expect_err("the grids differ"); + assert!( + error.to_string().contains("schema mismatch"), + "refused for another reason: {error}" + ); +} diff --git a/src/common/query/src/series_frame/tests/lifecycle.rs b/src/common/query/src/series_frame/tests/lifecycle.rs new file mode 100644 index 00000000000..a7b3c36af62 --- /dev/null +++ b/src/common/query/src/series_frame/tests/lifecycle.rs @@ -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, + binding: RawLabelSource, + chunk: Option, +} + +impl Stream for RawFixture { + type Item = Result; + + fn poll_next(mut self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll> { + Poll::Ready(self.chunk.take().map(Ok)) + } +} + +impl RawSeriesStream for RawFixture { + fn schema(&self) -> &Arc { + &self.schema + } + + fn label_source(&self) -> &RawLabelSource { + &self.binding + } + + fn ordering(&self) -> SeriesOrdering { + SeriesOrdering::Contiguous + } +} + +fn histogram_batch() -> Arc { + 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, +) { + 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::>() + .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::>() + .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)); +} diff --git a/src/common/query/src/series_frame/tests/state.rs b/src/common/query/src/series_frame/tests/state.rs new file mode 100644 index 00000000000..1b8344f598e --- /dev/null +++ b/src/common/query/src/series_frame/tests/state.rs @@ -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 { + 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 { + Arc::new(SeriesSchema { + fields: fields + .iter() + .map(|name| FieldSpec { + name: Arc::from(*name), + }) + .collect(), + eval_grid: Some(evaluated_grid()), + }) +} + +fn wrong_grid_schema() -> Arc { + 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>>) -> (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, + schema: Arc, +) -> Vec { + 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, + schema: Arc, +) -> DfSendableRecordBatchStream { + df_source(batches, schema).0 +} + +async fn rows( + batches: Vec, + state: Option>, + schema: Option>, +) -> Vec { + 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 { + 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![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![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![true, false, true] + ); + assert_eq!( + (0..3) + .map(|i| fields.is_present(1, i).unwrap()) + .collect::>(), + 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::>(); + 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()); +} diff --git a/src/common/recordbatch/src/adapter.rs b/src/common/recordbatch/src/adapter.rs index f8d645bd3e1..a053003a7df 100644 --- a/src/common/recordbatch/src/adapter.rs +++ b/src/common/recordbatch/src/adapter.rs @@ -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> + 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::() { + 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, +} + +/// 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 `: `. + 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, +} + +/// Builds the tree a reader sees, when it asks for it. +type NativeTreeReader = Arc 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, + /// A report this value took over while combining with another, which wins over `reader`. + adopted: Mutex>, +} + +/// 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::() + } +} + +impl CustomMetricValue for NativeTreeMetric { + /// A value to accumulate a combination into: it holds nothing until it combines with one. + fn new_empty(&self) -> Arc { + 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) { + let Some(other) = other.as_any().downcast_ref::() 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) -> bool { + other + .as_any() + .downcast_ref::() + .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, 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 { @@ -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::() 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>>> = 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(); diff --git a/src/common/recordbatch/src/error.rs b/src/common/recordbatch/src/error.rs index bddb8ae8032..cb14c4e1c93 100644 --- a/src/common/recordbatch/src/error.rs +++ b/src/common/recordbatch/src/error.rs @@ -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")); + } } } } diff --git a/src/common/recordbatch/src/filter.rs b/src/common/recordbatch/src/filter.rs index 0893d2aa3ad..3d8d7da7051 100644 --- a/src/common/recordbatch/src/filter.rs +++ b/src/common/recordbatch/src/filter.rs @@ -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 { - 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 { diff --git a/src/common/recordbatch/src/filter/predicate.rs b/src/common/recordbatch/src/filter/predicate.rs index e283633dc02..d9827004b53 100644 --- a/src/common/recordbatch/src/filter/predicate.rs +++ b/src/common/recordbatch/src/filter/predicate.rs @@ -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::() + .unwrap() + .values() + .to_vec() + }) + .collect::>(); + 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::>(); + 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 diff --git a/src/common/recordbatch/src/recordbatch.rs b/src/common/recordbatch/src/recordbatch.rs index 48a2757489f..60105391086 100644 --- a/src/common/recordbatch/src/recordbatch.rs +++ b/src/common/recordbatch/src/recordbatch.rs @@ -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 { + 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::().offsets(), validity_size) + } + ArrowDataType::LargeUtf8 => { + offset_slice_memory_size(len, array.as_string::().offsets(), validity_size) + } + ArrowDataType::Binary => { + offset_slice_memory_size(len, array.as_binary::().offsets(), validity_size) + } + ArrowDataType::LargeBinary => { + offset_slice_memory_size(len, array.as_binary::().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 { + 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( + len: usize, + offsets: &[O], + validity_size: usize, +) -> Option { + let offsets_size = len.checked_add(1)?.checked_mul(size_of::())?; + 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(&self, serializer: S) -> std::result::Result 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(len: usize) -> Vec { + let values = (0..len) + .map(|index| Some(T::Native::usize_as(index))) + .collect::>(); + let with_nulls = (0..len) + .map(|index| (index % 3 != 0).then(|| T::Native::usize_as(index))) + .collect::>(); + let all_null = (0..len) + .map(|_| None::) + .collect::>(); + + 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::>()); + 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::>(), + ); + 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> = 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> = 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::>::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::>::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::>()); + let nullable = BooleanArray::from( + (0..len) + .map(|index| (index % 4 != 0).then_some(index % 3 == 0)) + .collect::>(), + ); + let all_null = BooleanArray::from(vec![None::; 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 = 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::>(); + let numbers = (0_u64..1024).collect::>(); + let flags = (0..1024).map(|value| value % 3 == 0).collect::>(); + 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::>(); + + 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::(); + let buffer_total = slices + .iter() + .map(RecordBatch::buffer_memory_size) + .sum::(); + 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 = (0..512).collect(); + let flags = (0..512) + .map(|value| (value % 5 != 0).then_some(value % 3 == 0)) + .collect::>(); + let strings = (0..512) + .map(|value| (value % 4 != 0).then(|| format!("value-{value}"))) + .collect::>(); + let binary = (0..512_u32) + .map(|value| (value % 4 != 0).then(|| value.to_le_bytes().to_vec())) + .collect::>(); + 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::(usize::MAX, &[0, 0], 0) + ); + // The visible value bytes push the total over the edge. + assert_eq!( + None, + offset_slice_memory_size::(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::(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::::from_iter(vec![ + Some("first"), + None, + Some("a longer dictionary value"), + ]); + let list = ListArray::from_iter_primitive::(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![ diff --git a/src/common/substrait/Cargo.toml b/src/common/substrait/Cargo.toml index a56b56b8301..21b3d8a7396 100644 --- a/src/common/substrait/Cargo.toml +++ b/src/common/substrait/Cargo.toml @@ -20,3 +20,6 @@ datafusion-substrait.workspace = true promql.workspace = true prost.workspace = true snafu.workspace = true + +[dev-dependencies] +tokio.workspace = true diff --git a/src/common/substrait/src/extension_serializer.rs b/src/common/substrait/src/extension_serializer.rs index 5e94a1a57ae..e87b632f5de 100644 --- a/src/common/substrait/src/extension_serializer.rs +++ b/src/common/substrait/src/extension_serializer.rs @@ -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> { match node.name() { + name if name == FusedSeries::name() => { + let fused = node + .as_any() + .downcast_ref::() + .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::() + .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> { 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::() + .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); + } +} diff --git a/src/common/telemetry/Cargo.toml b/src/common/telemetry/Cargo.toml index 1e146a5a75e..33be63ed92e 100644 --- a/src/common/telemetry/Cargo.toml +++ b/src/common/telemetry/Cargo.toml @@ -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 diff --git a/src/common/telemetry/src/logging.rs b/src/common/telemetry/src/logging.rs index b1430bbd726..5154f7dc67e 100644 --- a/src/common/telemetry/src/logging.rs +++ b/src/common/telemetry/src/logging.rs @@ -15,6 +15,7 @@ //! logging stuffs, inspired by databend mod file_retention; +use std::any::Any; use std::collections::HashMap; use std::env; use std::io::IsTerminal; @@ -24,6 +25,9 @@ use std::time::Duration; use common_base::readable_size::ReadableSize; use common_base::serde::empty_string_as_default; +use common_error::ext::ErrorExt; +use common_error::status_code::StatusCode; +use common_macro::stack_trace_debug; use file_retention::{DirectoryRetention, LogFileKind, build_file_appender}; use once_cell::sync::{Lazy, OnceCell}; use opentelemetry::trace::TracerProvider; @@ -33,6 +37,7 @@ use opentelemetry_sdk::propagation::TraceContextPropagator; use opentelemetry_sdk::trace::{Sampler, Tracer}; use opentelemetry_semantic_conventions::resource; use serde::{Deserialize, Serialize}; +use snafu::{Location, Snafu}; use tracing::callsite; use tracing::metadata::LevelFilter; use tracing_appender::non_blocking::{NonBlocking, WorkerGuard}; @@ -45,6 +50,31 @@ use tracing_subscriber::{EnvFilter, Registry, filter}; use crate::tracing_sampler::{TracingSampleOptions, create_sampler}; +/// Failure to initialize a file appender. +#[derive(Snafu)] +#[stack_trace_debug] +pub enum InitLoggingError { + #[snafu(display("Failed to initialize file logging in {directory}: {error}.{hint}"))] + FileAppender { + directory: String, + #[snafu(source)] + error: tracing_appender::rolling::InitError, + hint: &'static str, + #[snafu(implicit)] + location: Location, + }, +} + +impl ErrorExt for InitLoggingError { + fn status_code(&self) -> StatusCode { + StatusCode::InvalidArguments + } + + fn as_any(&self) -> &dyn Any { + self + } +} + /// The default endpoint when use gRPC exporter protocol. pub const DEFAULT_OTLP_GRPC_ENDPOINT: &str = "http://localhost:4317"; @@ -265,7 +295,7 @@ enum TraceState { } /// The logging options that used to initialize the logger. -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, PartialEq, Serialize, Deserialize)] #[serde(default)] pub struct LoggingOptions { /// The directory to store log files. If not set, logs will be written to stdout. @@ -303,13 +333,53 @@ pub struct LoggingOptions { pub otlp_export_protocol: Option, /// Additional HTTP headers for OTLP exporter. - #[serde(skip_serializing_if = "HashMap::is_empty")] + #[serde( + skip_serializing_if = "HashMap::is_empty", + serialize_with = "serialize_otlp_headers" + )] pub otlp_headers: HashMap, /// Whether to enable per-region metrics. pub enable_per_region_metrics: bool, } +impl std::fmt::Debug for LoggingOptions { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("LoggingOptions") + .field("dir", &self.dir) + .field("level", &self.level) + .field("log_format", &self.log_format) + .field("max_log_files", &self.max_log_files) + .field("max_log_dir_size", &self.max_log_dir_size) + .field("append_stdout", &self.append_stdout) + .field("enable_file_logging", &self.enable_file_logging) + .field("enable_otlp_tracing", &self.enable_otlp_tracing) + .field("otlp_endpoint", &self.otlp_endpoint) + .field("tracing_sample_ratio", &self.tracing_sample_ratio) + .field("otlp_export_protocol", &self.otlp_export_protocol) + .field("enable_per_region_metrics", &self.enable_per_region_metrics) + .field("otlp_headers", &redacted_otlp_headers(&self.otlp_headers)) + .finish() + } +} + +fn redacted_otlp_headers(headers: &HashMap) -> HashMap<&str, &str> { + headers + .keys() + .map(|key| (key.as_str(), "[REDACTED]")) + .collect() +} + +fn serialize_otlp_headers( + headers: &HashMap, + serializer: S, +) -> std::result::Result +where + S: serde::Serializer, +{ + redacted_otlp_headers(headers).serialize(serializer) +} + /// The protocol of OTLP export. #[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "snake_case")] @@ -434,13 +504,16 @@ pub fn init_default_ut_logging() { level: Some(level), ..Default::default() }; - *g = Some(init_global_logging( - "unittest", - &opts, - &TracingOptions::default(), - None, - None, - )); + *g = Some( + init_global_logging( + "unittest", + &opts, + &TracingOptions::default(), + None, + None, + ) + .expect("failed to initialize test logging"), + ); crate::info!("logs dir = {}", dir); }); @@ -458,15 +531,12 @@ pub fn init_global_logging( tracing_opts: &TracingOptions, node_id: Option, slow_query_opts: Option<&SlowQueryOptions>, -) -> Vec { - static START: Once = Once::new(); +) -> Result, InitLoggingError> { + static START: OnceCell<()> = OnceCell::new(); let mut guards = vec![]; let node_id = node_id.unwrap_or_else(|| "none".to_string()); - START.call_once(|| { - // Enable log compatible layer to convert log record to tracing span. - LogTracer::init().expect("log tracer must be valid"); - + START.get_or_try_init(|| -> Result<(), InitLoggingError> { let stdout_writer = if opts.append_stdout { let (writer, guard) = tracing_appender::non_blocking(std::io::stdout()); guards.push(guard); @@ -491,7 +561,7 @@ pub fn init_global_logging( // Configure the file logging layer with rolling policy. let file_logging_layer = if file_logging_enabled { let rolling_appender = - build_file_appender(opts, LogFileKind::Default, retention.as_ref()); + build_file_appender(opts, LogFileKind::Default, retention.as_ref())?; let (writer, guard) = tracing_appender::non_blocking(rolling_appender); guards.push(guard); @@ -503,7 +573,7 @@ pub fn init_global_logging( // Configure the error file logging layer with rolling policy. let err_file_logging_layer = if file_logging_enabled { let rolling_appender = - build_file_appender(opts, LogFileKind::Error, retention.as_ref()); + build_file_appender(opts, LogFileKind::Error, retention.as_ref())?; let (writer, guard) = tracing_appender::non_blocking(rolling_appender); guards.push(guard); @@ -515,14 +585,23 @@ pub fn init_global_logging( None }; - if slow_query_logging_enabled { + let slow_query_logger = if slow_query_logging_enabled { + Some(build_slow_query_logger( + opts, + stdout_writer, + retention.as_ref(), + &mut guards, + )?) + } else { + None + }; + + // Build all file appenders before installing any global logging state. + // A filesystem failure can then be returned without poisoning initialization. + LogTracer::init().expect("log tracer must be valid"); + if let Some(logger) = slow_query_logger { SLOW_QUERY_LOGGER - .set(build_slow_query_logger( - opts, - stdout_writer, - retention.as_ref(), - &mut guards, - )) + .set(logger) .expect("slow query logger already initialized"); } @@ -619,9 +698,10 @@ pub fn init_global_logging( tracing::subscriber::set_global_default(subscriber) .expect("error setting global tracing subscriber"); - }); + Ok(()) + })?; - guards + Ok(guards) } fn create_tracer(app_name: &str, node_id: &str, opts: &LoggingOptions) -> Tracer { @@ -707,12 +787,12 @@ fn build_slow_query_logger( stdout_writer: Option, retention: Option<&DirectoryRetention>, guards: &mut Vec, -) -> tracing::Dispatch { +) -> Result { let stdout_layer = stdout_writer.map(|writer| { build_logging_layer(writer, opts.log_format, std::io::stdout().is_terminal()) }); let file_layer = if opts.enable_file_logging && !opts.dir.is_empty() { - let rolling_appender = build_file_appender(opts, LogFileKind::SlowQuery, retention); + let rolling_appender = build_file_appender(opts, LogFileKind::SlowQuery, retention)?; let (writer, guard) = tracing_appender::non_blocking(rolling_appender); guards.push(guard); Some(build_logging_layer(writer, opts.log_format, false)) @@ -724,12 +804,12 @@ fn build_slow_query_logger( *metadata.level() == tracing::Level::INFO && metadata.fields().field("slow").is_some() }) .with_max_level_hint(LevelFilter::INFO); - tracing::Dispatch::new( + Ok(tracing::Dispatch::new( Registry::default() .with(filter) .with(stdout_layer) .with(file_layer), - ) + )) } fn build_logging_layer( @@ -762,6 +842,100 @@ mod tests { use super::*; + #[test] + fn test_file_logging_initialization_failure() { + const CHILD_ENV: &str = "GREPTIME_TEST_LOGGING_INIT_FAILURE"; + if env::var_os(CHILD_ENV).is_none() { + let output = std::process::Command::new(env::current_exe().unwrap()) + .args([ + "--exact", + "logging::tests::test_file_logging_initialization_failure", + "--nocapture", + ]) + .env(CHILD_ENV, "1") + .output() + .unwrap(); + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + return; + } + + let dir = tempfile::tempdir().unwrap(); + let mut opts = LoggingOptions { + dir: dir.path().to_str().unwrap().to_string(), + max_log_dir_size: ReadableSize::mb(1), + append_stdout: false, + ..Default::default() + }; + let slow_opts = SlowQueryOptions { + enable: true, + record_type: SlowQueriesRecordType::Log, + ..Default::default() + }; + for link in [ + ".greptimedb.current", + ".greptimedb-err.current", + ".greptimedb-slow-queries.current", + ] { + let path = dir.path().join(link); + // A directory collision fails even on runners allowed to create symlinks. + std::fs::create_dir(&path).unwrap(); + let error = init_global_logging( + "test", + &opts, + &TracingOptions::default(), + None, + Some(&slow_opts), + ) + .unwrap_err(); + let message = error.to_string(); + assert!(message.contains("logging.max_log_dir_size"), "{message}"); + assert!(message.contains(&opts.dir), "{message}"); + assert!(message.contains("Developer Mode"), "{message}"); + assert!(LOG_RELOAD_HANDLE.get().is_none()); + assert!(SLOW_QUERY_LOGGER.get().is_none()); + std::fs::remove_dir(path).unwrap(); + for entry in std::fs::read_dir(dir.path()).unwrap() { + let entry = entry.unwrap(); + if entry.file_type().unwrap().is_symlink() { + std::fs::remove_file(entry.path()).unwrap(); + } + } + } + + // Disabling retention succeeds with the same collision and after failed attempts. + std::fs::create_dir(dir.path().join(".greptimedb.current")).unwrap(); + opts.max_log_dir_size = ReadableSize::default(); + let guards = init_global_logging( + "test", + &opts, + &TracingOptions::default(), + None, + Some(&slow_opts), + ) + .unwrap(); + crate::error!("logging works after initialization failures"); + drop(guards); + let error_log = std::fs::read_dir(dir.path()) + .unwrap() + .map(|entry| entry.unwrap().path()) + .find(|path| { + path.file_name() + .unwrap() + .to_string_lossy() + .starts_with("greptimedb-err.") + }) + .unwrap(); + assert!( + std::fs::read_to_string(error_log) + .unwrap() + .contains("logging works after initialization failures") + ); + } + #[test] fn test_slow_query_logging() { const CASE_ENV: &str = "GREPTIME_TEST_SLOW_QUERY_LOGGING"; @@ -875,7 +1049,8 @@ mod tests { &TracingOptions::default(), None, (case != "no_options").then_some(&slow_opts), - ); + ) + .unwrap(); for level in ["warn", "error", "off", "info"] { LOG_RELOAD_HANDLE @@ -1261,6 +1436,26 @@ mod tests { assert_eq!(protocol, OtlpExportProtocol::Http); } + #[test] + fn test_otlp_headers_are_redacted() { + let options: LoggingOptions = serde_json::from_value(serde_json::json!({ + "otlp_headers": {"authorization": "Bearer otlp-secret", "x-api-key": "api-secret"} + })) + .unwrap(); + assert_eq!(options.otlp_headers["authorization"], "Bearer otlp-secret"); + assert_eq!(options.otlp_headers["x-api-key"], "api-secret"); + for output in [ + serde_json::to_string(&options).unwrap(), + format!("{options:#?}"), + ] { + assert!(!output.contains("otlp-secret")); + assert!(!output.contains("api-secret")); + assert!(output.contains("authorization")); + assert!(output.contains("x-api-key")); + assert!(output.contains("[REDACTED]")); + } + } + #[test] fn test_logging_options_partial_eq_all_fields() { let base = LoggingOptions::default(); diff --git a/src/common/telemetry/src/logging/file_retention.rs b/src/common/telemetry/src/logging/file_retention.rs index 6ea9846be1a..d2a962ad748 100644 --- a/src/common/telemetry/src/logging/file_retention.rs +++ b/src/common/telemetry/src/logging/file_retention.rs @@ -24,9 +24,10 @@ use std::time::SystemTime; use common_base::readable_size::ReadableSize; use parking_lot::Mutex; +use snafu::ResultExt; use tracing_appender::rolling::{RollingFileAppender, Rotation}; -use crate::logging::LoggingOptions; +use crate::logging::{FileAppenderSnafu, InitLoggingError, LoggingOptions}; /// A managed file-log kind. #[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)] @@ -421,7 +422,7 @@ pub(crate) fn build_file_appender( opts: &LoggingOptions, kind: LogFileKind, retention: Option<&DirectoryRetention>, -) -> Box { +) -> Result, InitLoggingError> { // Directory retention owns size and count pruning so its index remains authoritative. let upstream_max_log_files = if retention.is_some() { 0 @@ -436,18 +437,28 @@ pub(crate) fn build_file_appender( builder = builder.latest_symlink(kind.current_link_name()); } - let appender = builder.build(&opts.dir).unwrap_or_else(|error| { - panic!( - "initializing rolling file appender at {} failed: {}", - opts.dir, error - ) - }); + // FIXME(tokio-rs/tracing#3612): tracing-appender lists the directory to prune old logs + // before creating it, so a missing directory prints a misleading error. If this fails, + // `build` reports it. + let _ = fs::create_dir_all(&opts.dir); + let appender = builder.build(&opts.dir).with_context(|_| FileAppenderSnafu { + directory: opts.dir.clone(), + hint: if retention.is_some() { + " logging.max_log_dir_size requires creating symbolic links in this directory. Check directory permissions and conflicting paths; on Windows, enable Developer Mode or set logging.max_log_dir_size = \"0B\" to disable size-based retention." + } else { + "" + }, + })?; if let Some(retention) = retention { retention.register(kind); - Box::new(RetentionAppender::new(appender, retention.clone(), kind)) + Ok(Box::new(RetentionAppender::new( + appender, + retention.clone(), + kind, + ))) } else { - Box::new(appender) + Ok(Box::new(appender)) } } @@ -517,7 +528,7 @@ mod tests { }; let retention = DirectoryRetention::new(directory.path(), ReadableSize::mb(1), 0).unwrap(); - let _appender = build_file_appender(&opts, LogFileKind::Default, Some(&retention)); + let _appender = build_file_appender(&opts, LogFileKind::Default, Some(&retention)).unwrap(); let symlink = directory.path().join(".greptimedb.current"); assert!(symlink.is_symlink()); @@ -538,7 +549,8 @@ mod tests { ..Default::default() }; let retention = DirectoryRetention::new(directory.path(), ReadableSize(1024), 0).unwrap(); - let mut appender = build_file_appender(&opts, LogFileKind::Default, Some(&retention)); + let mut appender = + build_file_appender(&opts, LogFileKind::Default, Some(&retention)).unwrap(); retention.initialize(); appender.write_all(b"current").unwrap(); @@ -566,7 +578,8 @@ mod tests { ..Default::default() }; let retention = DirectoryRetention::new(directory.path(), ReadableSize(1024), 0).unwrap(); - let mut appender = build_file_appender(&opts, LogFileKind::Default, Some(&retention)); + let mut appender = + build_file_appender(&opts, LogFileKind::Default, Some(&retention)).unwrap(); retention.initialize(); appender.write_all(b"current").unwrap(); @@ -589,7 +602,8 @@ mod tests { ..Default::default() }; let retention = DirectoryRetention::new(directory.path(), ReadableSize::gb(1), 2).unwrap(); - let mut appender = build_file_appender(&opts, LogFileKind::Default, Some(&retention)); + let mut appender = + build_file_appender(&opts, LogFileKind::Default, Some(&retention)).unwrap(); retention.initialize(); appender.write_all(b"current").unwrap(); @@ -612,7 +626,8 @@ mod tests { ..Default::default() }; let retention = DirectoryRetention::new(directory.path(), ReadableSize(1), 0).unwrap(); - let mut appender = build_file_appender(&opts, LogFileKind::Default, Some(&retention)); + let mut appender = + build_file_appender(&opts, LogFileKind::Default, Some(&retention)).unwrap(); retention.initialize(); appender.write_all(b"current").unwrap(); diff --git a/src/common/wal/src/config.rs b/src/common/wal/src/config.rs index 950f833dec9..0d26085452c 100644 --- a/src/common/wal/src/config.rs +++ b/src/common/wal/src/config.rs @@ -374,6 +374,25 @@ mod tests { } } + #[test] + fn test_kafka_password_serialization() { + for kind in ["PLAIN", "SCRAM-SHA-256", "SCRAM-SHA-512"] { + let input = format!("type = '{kind}'\nusername = 'alice'\npassword = 'kafka-secret'"); + let config: KafkaClientSaslConfig = toml::from_str(&input).unwrap(); + match &config { + KafkaClientSaslConfig::Plain { password, .. } + | KafkaClientSaslConfig::ScramSha256 { password, .. } + | KafkaClientSaslConfig::ScramSha512 { password, .. } => { + assert_eq!(password, "kafka-secret") + } + } + let serialized = toml::to_string(&config).unwrap(); + assert!(!serialized.contains("kafka-secret")); + assert!(serialized.contains("")); + assert!(serialized.contains("alice")); + } + } + #[test] fn test_kafka_wal_config_debug_redacts_password() { let config = MetasrvWalConfig::Kafka(MetasrvKafkaConfig { diff --git a/src/common/wal/src/config/kafka/common.rs b/src/common/wal/src/config/kafka/common.rs index daa5607e476..e1f00869aac 100644 --- a/src/common/wal/src/config/kafka/common.rs +++ b/src/common/wal/src/config/kafka/common.rs @@ -69,20 +69,30 @@ pub struct KafkaClientSasl { pub enum KafkaClientSaslConfig { Plain { username: String, + #[serde(serialize_with = "serialize_password")] password: String, }, #[serde(rename = "SCRAM-SHA-256")] ScramSha256 { username: String, + #[serde(serialize_with = "serialize_password")] password: String, }, #[serde(rename = "SCRAM-SHA-512")] ScramSha512 { username: String, + #[serde(serialize_with = "serialize_password")] password: String, }, } +fn serialize_password(_: &str, serializer: S) -> std::result::Result +where + S: serde::Serializer, +{ + serializer.serialize_str("") +} + impl fmt::Debug for KafkaClientSaslConfig { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { diff --git a/src/common/wal/src/config/object_store.rs b/src/common/wal/src/config/object_store.rs index 9e4a371baae..c41adadcb69 100644 --- a/src/common/wal/src/config/object_store.rs +++ b/src/common/wal/src/config/object_store.rs @@ -17,12 +17,19 @@ use std::time::Duration; use common_base::readable_size::ReadableSize; use serde::{Deserialize, Serialize}; -/// Generation of the node prefix in standalone mode. +/// Fixed directory generation used by standalone and distributed WAL stores. /// -/// Standalone runs a single datanode that never changes generation, so the -/// prefix layout carries the constant. Distributed mode will take both the -/// node id and the generation from the metasrv. -pub const STANDALONE_GENERATION: u64 = 0; +/// The directory remains stable across process restarts. This is distinct from +/// both the heartbeat node epoch and the store epoch carried in object headers. +pub const FIXED_DIRECTORY_GENERATION: u64 = 0; + +/// Plugin marker allowing a metasrv-controlled datanode to use object-store WAL. +/// +/// OSS does not register this marker. Cluster integration registers it only after +/// the distributed WAL prerequisites are available; it does not itself configure +/// metasrv or enable region failover. +#[derive(Debug, Clone, Copy)] +pub struct EnableObjectStoreWal; /// When an append to the object store WAL returns. #[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)] @@ -124,7 +131,7 @@ mod tests { fn test_node_prefix() { let config = ObjectStoreWalConfig::default(); assert_eq!( - config.node_prefix(0, STANDALONE_GENERATION), + config.node_prefix(0, FIXED_DIRECTORY_GENERATION), "wal/datanodes/0/epochs/0" ); diff --git a/src/datanode/src/alive_keeper.rs b/src/datanode/src/alive_keeper.rs index 13af76202d5..30e27929a29 100644 --- a/src/datanode/src/alive_keeper.rs +++ b/src/datanode/src/alive_keeper.rs @@ -16,7 +16,7 @@ use std::collections::HashMap; use std::sync::Arc; use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; -use api::v1::meta::GrantedRegion; +use api::v1::meta::GrantedRegion as PbGrantedRegion; use async_trait::async_trait; use common_error::ext::ErrorExt; use common_error::status_code::StatusCode; @@ -26,7 +26,7 @@ use common_meta::heartbeat::handler::{ }; use common_telemetry::{debug, error, info, trace, warn}; use snafu::OptionExt; -use store_api::region_engine::{RegionRole, SettableRegionRoleState}; +use store_api::region_engine::{GrantedRegion, RegionRole, SettableRegionRoleState}; use store_api::region_request::{RegionCloseRequest, RegionRequest}; use store_api::storage::RegionId; #[cfg(test)] @@ -137,15 +137,22 @@ impl RegionAliveKeeper { /// Renews the lease of regions to `deadline`, granted for a heartbeat sent at `sent_at`. async fn renew_region_leases( &self, - regions: &[GrantedRegion], + regions: &[PbGrantedRegion], sent_at: Instant, deadline: Instant, ) { for region in regions { - let (role, region_id) = (region.role().into(), RegionId::from(region.region_id)); + let region = GrantedRegion::from(region.clone()); + let region_id = region.region_id; if let Some(handle) = self.find_handle(region_id).await { handle - .reset_deadline(role, sent_at, deadline, region.extensions.clone()) + .reset_deadline(ResetLease { + role: region.region_role, + sent_at, + deadline, + candidate_lease_id: region.candidate_lease_id, + extensions: region.extensions, + }) .await; } else { warn!( @@ -301,13 +308,23 @@ enum CountdownCommand { /// 4 * `heartbeat_interval_millis` Start(u64), /// Reset countdown deadline to the given instance. - /// (NextRole, HeartbeatSentAt, Deadline, ExtensionInfo) - Reset((RegionRole, Instant, Instant, HashMap>)), + Reset(ResetLease), /// Returns the current deadline of the countdown task. #[cfg(test)] Deadline(oneshot::Sender), } +/// A region lease received in a heartbeat response. +#[derive(Debug)] +struct ResetLease { + role: RegionRole, + /// When the heartbeat was sent. + sent_at: Instant, + deadline: Instant, + candidate_lease_id: Option, + extensions: HashMap>, +} + pub type CountdownTaskHandlerExtRef = Arc; /// Extension trait for [CountdownTaskHandlerExt] to reset deadline of a region. @@ -319,7 +336,7 @@ pub trait CountdownTaskHandlerExt: Send + Sync { region_id: RegionId, role: RegionRole, deadline: Instant, - extension_info: HashMap>, + extensions: HashMap>, ); } @@ -379,23 +396,8 @@ impl CountdownTaskHandle { None } - async fn reset_deadline( - &self, - role: RegionRole, - sent_at: Instant, - deadline: Instant, - extension_info: HashMap>, - ) { - if let Err(e) = self - .tx - .send(CountdownCommand::Reset(( - role, - sent_at, - deadline, - extension_info, - ))) - .await - { + async fn reset_deadline(&self, lease: ResetLease) { + if let Err(e) = self.tx.send(CountdownCommand::Reset(lease)).await { warn!( "Failed to reset region alive keeper deadline: {e}. \ Maybe the task is stopped due to region been closed." @@ -447,9 +449,9 @@ impl CountdownTask { started = true; } }, - Some(CountdownCommand::Reset((role, sent_at, deadline, extension_info))) => { + Some(CountdownCommand::Reset(ResetLease { role, sent_at, deadline, candidate_lease_id, extensions })) => { let prev_role_leader = self.region_server.is_region_leader(self.region_id).unwrap_or(false); - let applied = match self.region_server.set_region_role_with_lease(self.region_id, role, sent_at.into_std(), deadline.into_std()) { + let applied = match self.region_server.set_region_role_with_lease(self.region_id, role, sent_at.into_std(), deadline.into_std(), candidate_lease_id) { Ok(applied) => applied, Err(err) => { if err.status_code() == StatusCode::RegionNotFound { @@ -480,7 +482,7 @@ impl CountdownTask { self.region_id, role, deadline, - extension_info, + extensions, ).await; } trace!( @@ -538,7 +540,10 @@ mod test { use crate::tests::{MockRegionEngine, mock_region_server}; /// Handles a heartbeat response that grants `regions` for a heartbeat sent now. - async fn handle_lease_response(alive_keeper: &RegionAliveKeeper, regions: Vec) { + async fn handle_lease_response( + alive_keeper: &RegionAliveKeeper, + regions: Vec, + ) { let sent_at = alive_keeper.epoch().elapsed(); handle_lease_response_sent_at(alive_keeper, sent_at, regions).await; } @@ -548,7 +553,7 @@ mod test { async fn handle_lease_response_sent_at( alive_keeper: &RegionAliveKeeper, sent_at: Duration, - regions: Vec, + regions: Vec, ) { let (tx, _rx) = mpsc::channel(1); let response = HeartbeatResponse { @@ -587,9 +592,10 @@ mod test { let alive_keeper = RegionAliveKeeper::new(region_server.clone(), None, Duration::from_millis(100)); alive_keeper.register_region(region_id).await; - let grant = GrantedRegion { + let grant = PbGrantedRegion { region_id: region_id.as_u64(), role: api::v1::meta::RegionRole::Leader.into(), + candidate_lease_id: 0, extensions: HashMap::new(), }; handle_lease_response(&alive_keeper, vec![grant]).await; @@ -598,6 +604,28 @@ mod test { assert_eq!(0, finalized.load(Ordering::Relaxed)); } + #[tokio::test(flavor = "multi_thread")] + async fn lease_response_passes_candidate_lease_id_to_engine() { + common_telemetry::init_default_ut_logging(); + let region_server = mock_region_server(); + let (engine, _) = MockRegionEngine::new(MITO_ENGINE_NAME); + let region_id = RegionId::new(1024, 1); + region_server.register_test_region(region_id, engine.clone()); + let alive_keeper = + RegionAliveKeeper::new(region_server.clone(), None, Duration::from_millis(100)); + alive_keeper.register_region(region_id).await; + let grant = PbGrantedRegion { + region_id: region_id.as_u64(), + role: api::v1::meta::RegionRole::Follower.into(), + candidate_lease_id: 7, + extensions: HashMap::new(), + }; + handle_lease_response(&alive_keeper, vec![grant]).await; + // The countdown task has handled the grant once it answers. + alive_keeper.deadline(region_id).await.unwrap(); + assert_eq!(*engine.candidate_lease_ids.lock().unwrap(), vec![Some(7)]); + } + #[tokio::test(flavor = "multi_thread")] async fn lease_responses_let_regions_write() { common_telemetry::init_default_ut_logging(); @@ -642,9 +670,10 @@ mod test { // A Leader grant renews the lease of the region. alive_keeper.register_region(region_id).await; - let grant = GrantedRegion { + let grant = PbGrantedRegion { region_id: region_id.as_u64(), role: api::v1::meta::RegionRole::Leader.into(), + candidate_lease_id: 0, extensions: HashMap::new(), }; handle_lease_response(&alive_keeper, vec![grant.clone()]).await; @@ -716,9 +745,10 @@ mod test { // Renew lease then sleep. alive_keeper .renew_region_leases( - &[GrantedRegion { + &[PbGrantedRegion { region_id: region_id.as_u64(), role: api::v1::meta::RegionRole::Leader.into(), + candidate_lease_id: 0, extensions: HashMap::new(), }], Instant::now(), @@ -773,12 +803,13 @@ mod test { // Reset deadline. countdown_handle - .reset_deadline( - RegionRole::Leader, - Instant::now(), - Instant::now() + Duration::from_millis(heartbeat_interval_millis * 5), - HashMap::new(), - ) + .reset_deadline(ResetLease { + role: RegionRole::Leader, + sent_at: Instant::now(), + deadline: Instant::now() + Duration::from_millis(heartbeat_interval_millis * 5), + candidate_lease_id: None, + extensions: HashMap::new(), + }) .await; assert!( countdown_handle.deadline().await.unwrap() @@ -821,9 +852,10 @@ mod test { alive_keeper.register_region(region_id).await; alive_keeper .renew_region_leases( - &[GrantedRegion { + &[PbGrantedRegion { region_id: region_id.as_u64(), role: api::v1::meta::RegionRole::StagingLeader.into(), + candidate_lease_id: 0, extensions: HashMap::new(), }], Instant::now(), @@ -870,9 +902,10 @@ mod test { alive_keeper.register_region(region_id).await; alive_keeper .renew_region_leases( - &[GrantedRegion { + &[PbGrantedRegion { region_id: region_id.as_u64(), role: api::v1::meta::RegionRole::Leader.into(), + candidate_lease_id: 0, extensions: HashMap::new(), }], Instant::now(), @@ -913,9 +946,10 @@ mod test { alive_keeper.register_region(region_id).await; alive_keeper .renew_region_leases( - &[GrantedRegion { + &[PbGrantedRegion { region_id: region_id.as_u64(), role: api::v1::meta::RegionRole::StagingLeader.into(), + candidate_lease_id: 0, extensions: HashMap::new(), }], Instant::now(), diff --git a/src/datanode/src/datanode.rs b/src/datanode/src/datanode.rs index 9a797f49c95..f33188a8208 100644 --- a/src/datanode/src/datanode.rs +++ b/src/datanode/src/datanode.rs @@ -41,7 +41,9 @@ use common_stat::ResourceStatImpl; use common_telemetry::{error, info, warn}; use common_wal::config::DatanodeWalConfig; use common_wal::config::kafka::DatanodeKafkaConfig; -use common_wal::config::object_store::{ObjectStoreWalConfig, STANDALONE_GENERATION}; +use common_wal::config::object_store::{ + EnableObjectStoreWal, FIXED_DIRECTORY_GENERATION, ObjectStoreWalConfig, +}; use common_wal::config::raft_engine::RaftEngineConfig; use file_engine::engine::FileRegionEngine; use futures::future::join_all; @@ -102,6 +104,8 @@ pub struct Datanode { leases_notifier: Option>, plugins: Plugins, object_store_log_store: Option>, + /// The raft-engine WAL, if any. Stopped after the region server, see [Datanode::shutdown]. + raft_engine_log_store: Option>, } impl Datanode { @@ -160,15 +164,6 @@ impl Datanode { ); let _ = self.greptimedb_telemetry_task.stop().await; - if let Some(heartbeat_task) = &self.heartbeat_task { - record_shutdown_error( - &mut first_error, - heartbeat_task - .close() - .map_err(BoxedError::new) - .context(ShutdownInstanceSnafu), - ); - } // The object store WAL stops before the regions close: its stop // uploads the backlog or drops it, and answers every wait for its // entries, so a flush that waits for the WAL, queued or run by the @@ -183,7 +178,24 @@ impl Datanode { .context(ShutdownInstanceSnafu), ); } + // WAL draining still needs heartbeat renewal; stop it before the heartbeat. + if let Some(heartbeat_task) = &self.heartbeat_task { + record_shutdown_error( + &mut first_error, + heartbeat_task + .close() + .map_err(BoxedError::new) + .context(ShutdownInstanceSnafu), + ); + } record_shutdown_error(&mut first_error, self.region_server.stop().await); + // The stopped engines no longer hold the raft-engine WAL, so it can be closed. + if let Some(log_store) = self.raft_engine_log_store.take() { + record_shutdown_error( + &mut first_error, + close_raft_engine_log_store(log_store).await, + ); + } first_error.map_or(Ok(()), Err) } @@ -213,10 +225,15 @@ pub struct DatanodeBuilder { topic_stats_reporter: Option>, open_regions_writable_override: Option, local_file_access: LocalFileAccess, + /// Set as soon as the raft-engine log store exists so that a failed build can close it. + raft_engine_log_store: Option>, #[cfg(feature = "enterprise")] extension_range_provider_factory: Option, /// Set as soon as the object store log store exists so that a failed build can stop it. object_store_log_store: Option>, + /// Set as soon as the region server exists so that a failed build can stop its engines, + /// which hold the log stores. + region_server: Option, } impl DatanodeBuilder { @@ -230,6 +247,8 @@ impl DatanodeBuilder { cache_registry: None, open_regions_writable_override: None, local_file_access: LocalFileAccess::Disabled, + raft_engine_log_store: None, + region_server: None, #[cfg(feature = "enterprise")] extension_range_provider_factory: None, topic_stats_reporter: None, @@ -304,14 +323,26 @@ impl DatanodeBuilder { self.try_build().await } - /// Builds the datanode and stops the object store log store if a later step fails. + /// Builds the datanode and, if a later step fails, stops the engines and the log stores it + /// opened. async fn try_build(&mut self) -> Result { let result = self.build_inner().await; - if result.is_err() - && let Some(log_store) = &self.object_store_log_store - && let Err(err) = log_store.stop().await - { - warn!(err; "Failed to stop the object store log store after a failed build"); + if result.is_err() { + if let Some(log_store) = &self.object_store_log_store + && let Err(err) = log_store.stop().await + { + warn!(err; "Failed to stop the object store log store after a failed build"); + } + if let Some(region_server) = self.region_server.take() + && let Err(err) = region_server.stop().await + { + warn!(err; "Failed to stop the region server after a failed build"); + } + if let Some(log_store) = self.raft_engine_log_store.take() + && let Err(err) = close_raft_engine_log_store(log_store).await + { + warn!(err; "Failed to close the raft-engine log store after a failed build"); + } } result } @@ -330,7 +361,10 @@ impl DatanodeBuilder { // writable upon open. let controlled_by_metasrv = meta_client.is_some(); if let DatanodeWalConfig::ObjectStore(config) = &self.opts.wal { - ensure!(!controlled_by_metasrv, ObjectStoreWalNotStandaloneSnafu); + ensure!( + !controlled_by_metasrv || self.plugins.get::().is_some(), + ObjectStoreWalNotStandaloneSnafu + ); validate_object_store_wal_config(config)?; } @@ -372,10 +406,17 @@ impl DatanodeBuilder { cache_registry.clone(), ) .await?; + self.region_server = Some(region_server.clone()); // A region acknowledges only writes whose WAL append completed within its lease from // the metasrv. if controlled_by_metasrv && let Some(mito) = region_server.mito_engine() { mito.require_write_lease(); + if let Some(log_store) = &self.object_store_log_store { + log_store + .set_io_permit(mito.object_store_wal_io_permit()) + .map_err(Box::new) + .context(OpenLogStoreSnafu)?; + } } // TODO(weny): Considering introducing a readonly kv_backend trait. @@ -390,6 +431,20 @@ impl DatanodeBuilder { let open_with_writable = self .open_regions_writable_override .unwrap_or(!controlled_by_metasrv); + let initialization_guard = self.opts.init_regions_in_background.then(|| { + let regions = region_open_requests + .leader_regions + .iter() + .map(|(id, _)| *id); + #[cfg(feature = "enterprise")] + let regions = regions.chain( + region_open_requests + .follower_regions + .iter() + .map(|(id, _)| *id), + ); + region_server.track_region_initialization(regions) + }); let open_all_regions = open_all_regions( region_server.clone(), region_open_requests, @@ -402,6 +457,7 @@ impl DatanodeBuilder { if self.opts.init_regions_in_background { // Opens regions in background. common_runtime::spawn_global(async move { + let _initialization_guard = initialization_guard; if let Err(err) = open_all_regions.await { error!(err; "Failed to open regions during the startup."); } @@ -432,6 +488,7 @@ impl DatanodeBuilder { None }; + self.region_server = None; Ok(Datanode { services: ServerHandlers::default(), heartbeat_task, @@ -441,6 +498,7 @@ impl DatanodeBuilder { leases_notifier, plugins: self.plugins.clone(), object_store_log_store: self.object_store_log_store.take(), + raft_engine_log_store: self.raft_engine_log_store.take(), }) } @@ -744,6 +802,7 @@ impl DatanodeBuilder { let log_store = Self::build_raft_engine_log_store(&opts.storage.data_home, raft_engine_config) .await?; + self.raft_engine_log_store = Some(log_store.clone()); let builder = MitoEngineBuilder::new( &opts.storage.data_home, @@ -840,7 +899,7 @@ impl DatanodeBuilder { } /// Builds [ObjectStoreLogStore] under the node prefix of `node_id` in the - /// standalone generation, the prefix the regions persist in their WAL options. + /// fixed directory generation, the prefix the regions persist in their WAL options. async fn build_object_store_log_store( object_store: ObjectStore, config: &ObjectStoreWalConfig, @@ -850,7 +909,7 @@ impl DatanodeBuilder { "Creating object store logstore with config: {:?}, node id: {}", config, node_id ); - ObjectStoreLogStore::try_new(object_store, config, node_id, STANDALONE_GENERATION) + ObjectStoreLogStore::try_new(object_store, config, node_id, FIXED_DIRECTORY_GENERATION) .await .map_err(Box::new) .context(OpenLogStoreSnafu) @@ -904,6 +963,25 @@ pub(crate) fn record_shutdown_error(first_error: &mut Option, resu } } +/// Closes the raft-engine WAL, which takes its last reference: raft-engine only closes the +/// active log file when its engine is dropped. If something else still holds the WAL, it is +/// stopped instead and the file stays open until that reference is dropped. +async fn close_raft_engine_log_store(log_store: Arc) -> Result<()> { + let result = match Arc::try_unwrap(log_store) { + Ok(log_store) => log_store.close().await, + Err(log_store) => { + warn!( + "The raft-engine WAL is still referenced elsewhere ({} references), stopping it without closing its active log file", + Arc::strong_count(&log_store) - 1 + ); + log_store.stop().await + } + }; + result + .map_err(BoxedError::new) + .context(ShutdownInstanceSnafu) +} + /// Returns the object store that holds the WAL objects: the default one for an /// empty `storage_provider`, otherwise the configured provider with that name. fn wal_object_store( @@ -1141,7 +1219,7 @@ mod tests { use std::path::Path; use std::sync::Arc; use std::sync::atomic::{AtomicUsize, Ordering}; - use std::time::Duration; + use std::time::{Duration, Instant}; use api::v1::{ColumnSchema, Rows}; use cache::build_datanode_layered_cache_registry; @@ -1160,7 +1238,10 @@ mod tests { use common_meta::node_manager::NodeManagerRef; use common_test_util::temp_dir::{create_named_temp_file, create_temp_dir}; use common_wal::config::DatanodeWalConfig; - use common_wal::config::object_store::{AckMode, ObjectStoreWalConfig, STANDALONE_GENERATION}; + use common_wal::config::object_store::{ + AckMode, EnableObjectStoreWal, FIXED_DIRECTORY_GENERATION, ObjectStoreWalConfig, + }; + use common_wal::config::raft_engine::RaftEngineConfig; use common_wal::options::{ObjectStoreWalOptions, WAL_OPTIONS_KEY, WalOptions}; use log_store::ObjectStoreLogStore; use log_store::error::Error as LogStoreError; @@ -1293,6 +1374,16 @@ mod tests { std::fs::read_dir(dir).unwrap().next().is_none() } + /// Opens the raft-engine WAL under `data_home` again, which only succeeds once the previous + /// engine was released (raft-engine holds a lock on its directory while open). + async fn assert_raft_engine_wal_reopens(data_home: &str) { + let reopened = + DatanodeBuilder::build_raft_engine_log_store(data_home, &RaftEngineConfig::default()) + .await + .unwrap(); + reopened.stop().await.unwrap(); + } + /// Returns true if the store rejects even an empty append, which it does only once stopped. async fn is_stopped(log_store: &ObjectStoreLogStore) -> bool { matches!( @@ -1478,6 +1569,99 @@ mod tests { assert!(is_empty_dir(data_home.path())); } + #[tokio::test] + async fn test_cluster_object_store_wal_builder_installs_node_lease() { + let data_home = create_temp_dir("cluster-wal-node-lease"); + let config = ObjectStoreWalConfig { + prefix: "cluster-a/wal".to_string(), + ..enqueued_wal_config(Duration::from_secs(3600)) + }; + let mut builder = + object_store_wal_builder(data_home.path().to_str().unwrap(), config.clone()); + builder.opts.node_id = Some(7); + builder.plugins.insert(EnableObjectStoreWal); + builder.with_meta_client(Arc::new( + MetaClientBuilder::datanode_default_options(7).build(), + )); + let mut datanode = builder.build().await.unwrap(); + assert!(datanode.heartbeat_task.is_some()); + let log_store = datanode.object_store_log_store().unwrap(); + let engine = datanode.region_server.mito_engine().unwrap(); + let prefix = config.node_prefix(7, FIXED_DIRECTORY_GENERATION); + assert_eq!("cluster-a/wal/datanodes/7/epochs/0", prefix); + let provider = Provider::object_store_provider(REGION, prefix); + let entry = log_store.entry(vec![1], 0, REGION, &provider).unwrap(); + let response = log_store.append_batch(vec![entry]).await.unwrap(); + let entry_id = response.last_entry_ids[®ION]; + + // The builder installs the permit: no test-side set_io_permit call. + assert_matches!( + log_store.seal_open_batch().await.unwrap_err(), + LogStoreError::ObjectStoreWalLeaseExpired { .. } + ); + assert_eq!(0, log_store.latest_entry_id(&provider).unwrap()); + let deadline = Instant::now() + Duration::from_secs(60); + engine.renew_node_lease(deadline); + log_store.seal_open_batch().await.unwrap(); + assert_eq!(entry_id, log_store.latest_entry_id(&provider).unwrap()); + engine.freeze_lease_clock(deadline); + assert_matches!( + log_store.seal_open_batch().await.unwrap_err(), + LogStoreError::ObjectStoreWalLeaseExpired { .. } + ); + engine.renew_node_lease(deadline + Duration::from_secs(60)); + log_store.seal_open_batch().await.unwrap(); + datanode.shutdown().await.unwrap(); + } + + #[tokio::test] + async fn test_cluster_object_store_wal_shutdown_keeps_heartbeat_until_drained() { + let data_home = create_temp_dir("cluster-wal-shutdown"); + let config = enqueued_wal_config(Duration::from_secs(3600)); + let mut builder = + object_store_wal_builder(data_home.path().to_str().unwrap(), config.clone()); + builder.plugins.insert(EnableObjectStoreWal); + builder.with_meta_client(Arc::new( + MetaClientBuilder::datanode_default_options(0).build(), + )); + let mut datanode = builder.build().await.unwrap(); + let log_store = datanode.object_store_log_store().unwrap(); + let engine = datanode.region_server.mito_engine().unwrap(); + engine.renew_node_lease(Instant::now() + WAIT); + // Observe the real close flag without starting network heartbeats. + let heartbeat_running = datanode + .heartbeat_task + .as_ref() + .unwrap() + .running_flag_for_test(); + heartbeat_running.store(true, Ordering::Release); + let provider = Provider::object_store_provider( + REGION, + config.node_prefix(0, FIXED_DIRECTORY_GENERATION), + ); + let entry = log_store.entry(vec![1], 0, REGION, &provider).unwrap(); + let response = log_store.append_batch(vec![entry]).await.unwrap(); + log_store.hold_creates(); + let shutdown = tokio::spawn(async move { datanode.shutdown().await }); + tokio::time::timeout(WAIT, log_store.wait_for_parked_creates(1)) + .await + .unwrap() + .unwrap(); + assert!(!shutdown.is_finished()); + assert!(heartbeat_running.load(Ordering::Acquire)); + log_store.release_creates(); + tokio::time::timeout(WAIT, shutdown) + .await + .unwrap() + .unwrap() + .unwrap(); + assert!(!heartbeat_running.load(Ordering::Acquire)); + assert_eq!( + response.last_entry_ids[®ION], + log_store.latest_entry_id(&provider).unwrap() + ); + } + #[tokio::test] async fn test_build_rejects_unknown_wal_storage_provider() { let data_home = create_temp_dir("object-store-wal-unknown-provider"); @@ -1657,6 +1841,7 @@ mod tests { assert!(datanode.object_store_log_store.is_none()); assert!(data_home.path().join("wal").exists()); datanode.shutdown().await.unwrap(); + assert_raft_engine_wal_reopens(data_home.path().to_str().unwrap()).await; } #[tokio::test] @@ -1728,6 +1913,60 @@ mod tests { assert!(is_stopped(&log_store).await); } + #[tokio::test] + async fn test_shutdown_closes_raft_engine_wal_of_written_region() { + common_telemetry::init_default_ut_logging(); + let data_home = create_temp_dir("raft-engine-wal-written-region"); + let mut datanode = datanode_builder( + data_home.path().to_str().unwrap(), + DatanodeWalConfig::RaftEngine(RaftEngineConfig::default()), + Arc::new(MemoryKvBackend::new()), + ) + .build() + .await + .unwrap(); + let region_server = datanode.region_server(); + let request = CreateRequestBuilder::new().build(); + let schema = rows_schema(&request); + region_server + .handle_request(REGION, RegionRequest::Create(request)) + .await + .unwrap(); + put_rows(®ion_server, &schema, 0..3, false).await; + + datanode.shutdown().await.unwrap(); + + // The open region and its writes must not keep the WAL referenced: if the datanode does + // not hold the last reference, it only stops the WAL and the reopen below fails. + assert_raft_engine_wal_reopens(data_home.path().to_str().unwrap()).await; + } + + #[tokio::test] + async fn test_shutdown_closes_raft_engine_wal_after_engine_failures() { + common_telemetry::init_default_ut_logging(); + let data_home = create_temp_dir("raft-engine-wal-shutdown-failure"); + let builder = datanode_builder( + data_home.path().to_str().unwrap(), + DatanodeWalConfig::RaftEngine(RaftEngineConfig::default()), + Arc::new(MemoryKvBackend::new()), + ); + let mut datanode = builder.build().await.unwrap(); + let (engine, _) = MockRegionEngine::with_custom_apply_fn("failing", |engine| { + engine.handle_stop_mock_fn = Some(Box::new(|| { + error::UnexpectedSnafu { + violated: "stop failed", + } + .fail() + })); + }); + datanode.region_server().register_engine(engine); + + let err = datanode.shutdown().await.unwrap_err(); + + assert_matches!(err, Error::StopRegionEngine { .. }); + assert_raft_engine_wal_reopens(data_home.path().to_str().unwrap()).await; + } + #[tokio::test] async fn test_failed_build_stops_object_store_log_store() { common_telemetry::init_default_ut_logging(); @@ -1748,6 +1987,27 @@ mod tests { assert!(is_stopped(log_store).await); } + #[tokio::test] + async fn test_failed_build_closes_raft_engine_log_store() { + common_telemetry::init_default_ut_logging(); + let data_home = create_temp_dir("raft-engine-wal-failed-build"); + let kv_backend = Arc::new(MemoryKvBackend::new()); + // Regions registered in the metadata but missing on disk fail the region open + // that runs after the log store and the engines are built. + setup_table_datanode(&(kv_backend.clone() as _)).await; + let mut builder = datanode_builder( + data_home.path().to_str().unwrap(), + DatanodeWalConfig::RaftEngine(RaftEngineConfig::default()), + kv_backend, + ); + + assert!(builder.try_build().await.is_err()); + + assert!(builder.region_server.is_none()); + assert!(builder.raft_engine_log_store.is_none()); + assert_raft_engine_wal_reopens(data_home.path().to_str().unwrap()).await; + } + const REGION: RegionId = RegionId::new(1024, 1); fn enqueued_wal_config(flush_interval: Duration) -> ObjectStoreWalConfig { @@ -1760,7 +2020,7 @@ mod tests { /// The options that put a region on the WAL of a datanode with `config`. fn region_wal_options(config: &ObjectStoreWalConfig) -> HashMap { - let prefix = config.node_prefix(0, STANDALONE_GENERATION); + let prefix = config.node_prefix(0, FIXED_DIRECTORY_GENERATION); let wal_options = serde_json::to_string(&WalOptions::ObjectStore(ObjectStoreWalOptions::new(prefix))) .unwrap(); @@ -1808,7 +2068,7 @@ mod tests { skipped_rows: usize, ) -> (Datanode, Arc) { let config = enqueued_wal_config(flush_interval); - let prefix = config.node_prefix(0, STANDALONE_GENERATION); + let prefix = config.node_prefix(0, FIXED_DIRECTORY_GENERATION); let mut request = CreateRequestBuilder::new().build(); request.options.extend(region_wal_options(&config)); let datanode = object_store_wal_builder(data_home, config) @@ -2009,7 +2269,7 @@ mod tests { fn test_node_prefix_passes_validation() { let config = ObjectStoreWalConfig::default(); let derived = ObjectStoreWalConfig { - prefix: config.node_prefix(0, STANDALONE_GENERATION), + prefix: config.node_prefix(0, FIXED_DIRECTORY_GENERATION), ..config }; validate_object_store_wal_config(&derived).unwrap(); diff --git a/src/datanode/src/error.rs b/src/datanode/src/error.rs index d5037c2874e..2a560393ad7 100644 --- a/src/datanode/src/error.rs +++ b/src/datanode/src/error.rs @@ -330,7 +330,9 @@ pub enum Error { location: Location, }, - #[snafu(display("Object store WAL is only supported in standalone mode"))] + #[snafu(display( + "Object store WAL supports standalone only in this build; metasrv-controlled deployment requires a build with distributed object-store WAL integration" + ))] ObjectStoreWalNotStandalone { #[snafu(implicit)] location: Location, diff --git a/src/datanode/src/heartbeat.rs b/src/datanode/src/heartbeat.rs index 3bf1f6b5365..7127dbbd6a1 100644 --- a/src/datanode/src/heartbeat.rs +++ b/src/datanode/src/heartbeat.rs @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -use std::collections::HashMap; +use std::collections::{HashMap, HashSet}; use std::sync::Arc; use std::sync::atomic::{AtomicBool, Ordering}; use std::time::Duration; @@ -379,7 +379,22 @@ impl HeartbeatTask { } } _ = &mut sleep => { + // Read opening first so a completed open is covered by either snapshot. + let opening_regions = region_server_clone.opening_regions(); let region_stats = Self::load_region_stats(®ion_server_clone); + let opening_regions = if opening_regions.is_empty() { + Vec::new() + } else { + let reported_regions: HashSet<_> = region_stats.iter() + .map(|stat| stat.region_id) + .collect(); + opening_regions.into_iter() + .filter(|region_id| !reported_regions.contains(®ion_id.as_u64())) + .map(|region_id| api::v1::meta::OpeningRegion { + region_id: region_id.as_u64(), + }) + .collect() + }; let topic_stats = region_server_clone.topic_stats(); let now = Instant::now(); let duration_since_epoch = (now - epoch).as_millis() as u64; @@ -389,6 +404,7 @@ impl HeartbeatTask { gc_stat.into_extensions(&mut extensions); let mut req = HeartbeatRequest { + opening_regions, region_stats, topic_stats, duration_since_epoch, @@ -485,6 +501,12 @@ impl HeartbeatTask { .collect() } + /// Exposes the lifecycle flag for shutdown-order tests without a network task. + #[cfg(test)] + pub(crate) fn running_flag_for_test(&self) -> Arc { + self.running.clone() + } + pub fn close(&self) -> Result<()> { let running = self.running.clone(); if running diff --git a/src/datanode/src/heartbeat/handler/flush_region.rs b/src/datanode/src/heartbeat/handler/flush_region.rs index c1f055c0eb3..e31a0a3b7f9 100644 --- a/src/datanode/src/heartbeat/handler/flush_region.rs +++ b/src/datanode/src/heartbeat/handler/flush_region.rs @@ -18,11 +18,11 @@ use common_meta::instruction::{ FlushErrorStrategy, FlushRegionReply, FlushRegions, FlushStrategy, InstructionError, InstructionReply, }; -use common_telemetry::{debug, warn}; +use common_telemetry::{debug, error, warn}; use store_api::region_request::{RegionFlushReason, RegionFlushRequest, RegionRequest}; use store_api::storage::RegionId; -use crate::error::{self, RegionNotFoundSnafu, RegionNotReadySnafu, Result, UnexpectedSnafu}; +use crate::error::{self, RegionNotFoundSnafu, RegionNotReadySnafu, Result}; use crate::heartbeat::handler::{HandlerContext, InstructionHandler}; pub struct FlushRegionsHandler; @@ -125,6 +125,9 @@ impl HandlerContext { match &result { Ok(_) => results.push((region_id, Ok(()))), Err(err) => { + // Log the full error chain here; the reply carries the + // classification and the root cause of the original error. + error!(err; "Failed to flush region, region_id: {}", region_id); results.push((region_id, Err(InstructionError::from_error(err)))); // For fail-fast strategy, abort on first error @@ -179,13 +182,7 @@ impl HandlerContext { } let mut watcher = register_result.into_watcher(); - match self.flush_tasks.wait_until_finish(&mut watcher).await { - Ok(()) => Ok(()), - Err(err) => Err(UnexpectedSnafu { - violated: format!("Flush task failed: {err:?}"), - } - .build()), - } + self.flush_tasks.wait_until_finish(&mut watcher).await } } @@ -193,12 +190,15 @@ impl HandlerContext { mod tests { use std::sync::{Arc, RwLock}; + use common_error::ext::RetryHint; + use common_error::status_code::StatusCode; use common_meta::instruction::{FlushErrorStrategy, FlushRegions}; use common_meta::kv_backend::memory::MemoryKvBackend; use mito2::engine::MITO_ENGINE_NAME; use store_api::storage::RegionId; use super::*; + use crate::error::{RegionBusySnafu, UnexpectedSnafu}; use crate::tests::{MockRegionEngine, mock_region_server}; type FlushedRequests = Arc)>>>; @@ -366,6 +366,100 @@ mod tests { assert!(flush_reply.results[1].1.is_err()); } + /// A task body error used to verify that the reply keeps its classification. + #[derive(Clone, Copy, Debug)] + enum TaskFlushError { + RegionBusy, + Unexpected, + } + + impl TaskFlushError { + fn build(self, region_id: RegionId) -> crate::error::Error { + match self { + Self::RegionBusy => RegionBusySnafu { region_id }.build(), + Self::Unexpected => UnexpectedSnafu { + violated: "flush task boom marker", + } + .build(), + } + } + + fn expected(self) -> (StatusCode, RetryHint) { + match self { + Self::RegionBusy => (StatusCode::RegionBusy, RetryHint::Retryable), + Self::Unexpected => (StatusCode::Unexpected, RetryHint::NonRetryable), + } + } + + fn message_fragment(self, region_id: RegionId) -> String { + match self { + Self::RegionBusy => format!("Region {region_id} is busy"), + Self::Unexpected => "flush task boom marker".to_string(), + } + } + } + + #[tokio::test] + async fn test_handle_flush_region_sync_keeps_task_error_classification() { + let failing_region = RegionId::new(1024, 1); + let succeeding_region = RegionId::new(1024, 2); + + for error in [TaskFlushError::RegionBusy, TaskFlushError::Unexpected] { + let flushed_regions: Arc>> = Arc::new(RwLock::new(Vec::new())); + + let mock_region_server = mock_region_server(); + let flushed_regions_ref = flushed_regions.clone(); + let (mock_engine, _) = + MockRegionEngine::with_custom_apply_fn(MITO_ENGINE_NAME, move |region_engine| { + region_engine.handle_request_mock_fn = + Some(Box::new(move |region_id, _request| { + flushed_regions_ref.write().unwrap().push(region_id); + if region_id == failing_region { + Err(error.build(region_id)) + } else { + Ok(0) + } + })); + }); + mock_region_server.register_test_region(failing_region, mock_engine.clone()); + mock_region_server.register_test_region(succeeding_region, mock_engine); + + let kv_backend = Arc::new(MemoryKvBackend::new()); + let handler_context = HandlerContext::new_for_test(mock_region_server, kv_backend); + let instruction = FlushRegions::sync_batch( + vec![failing_region, succeeding_region], + FlushErrorStrategy::TryAll, + ); + let reply = FlushRegionsHandler + .handle(&handler_context, instruction) + .await + .unwrap() + .expect_flush_regions_reply(); + + assert!(!reply.overall_success, "{error:?}"); + assert_eq!(reply.results.len(), 2, "{error:?}"); + assert_eq!(reply.results[0].0, failing_region, "{error:?}"); + let reply_error = reply.results[0].1.as_ref().unwrap_err(); + let (code, retry_hint) = error.expected(); + assert_eq!(reply_error.code, code, "{error:?}"); + assert_eq!(reply_error.retry_hint, retry_hint, "{error:?}"); + assert!( + reply_error + .message + .contains(&error.message_fragment(failing_region)), + "{error:?}: {}", + reply_error.message + ); + assert_eq!(reply.results[1].0, succeeding_region, "{error:?}"); + assert!(reply.results[1].1.is_ok(), "{error:?}"); + assert_eq!( + *flushed_regions.read().unwrap(), + vec![failing_region, succeeding_region], + "{error:?}" + ); + } + } + #[test] fn test_flush_regions_display() { let region_id = RegionId::new(1024, 1); diff --git a/src/datanode/src/region_server.rs b/src/datanode/src/region_server.rs index 07068f5a4d3..fbfa7ad57de 100644 --- a/src/datanode/src/region_server.rs +++ b/src/datanode/src/region_server.rs @@ -47,7 +47,7 @@ use common_runtime::{JoinHandle, Runtime}; use common_telemetry::tracing::{self, info_span}; use common_telemetry::tracing_context::{FutureExt, TracingContext}; use common_telemetry::{debug, error, info, warn}; -use dashmap::DashMap; +use dashmap::{DashMap, DashSet}; use datafusion::datasource::TableProvider; use datafusion_common::tree_node::TreeNode; use datatypes::schema::SchemaRef; @@ -402,6 +402,34 @@ impl RegionServer { Ok(maybe_guard_stream(stream, permit)) } + /// Tracks all background initialization requests before the opening task starts. + pub(crate) fn track_region_initialization( + &self, + regions: impl IntoIterator, + ) -> RegionInitializationGuard { + for region_id in regions { + self.inner.initializing_regions.insert(region_id); + } + RegionInitializationGuard(self.inner.initializing_regions.clone()) + } + + /// Returns initialization requests that are queued or not yet reportable. + pub(crate) fn opening_regions(&self) -> Vec { + self.inner + .initializing_regions + .iter() + .filter_map(|entry| { + let region_id = *entry.key(); + let reportable = self + .inner + .region_map + .get(®ion_id) + .is_some_and(|region| region.role(region_id).is_some()); + (!reportable).then_some(region_id) + }) + .collect() + } + /// Returns all opened and reportable regions. /// /// Notes: except all metrics regions. @@ -470,6 +498,7 @@ impl RegionServer { role: RegionRole, sent_at: std::time::Instant, deadline: std::time::Instant, + candidate_lease_id: Option, ) -> Result { let engine = self .inner @@ -477,7 +506,7 @@ impl RegionServer { .get(®ion_id) .with_context(|| RegionNotFoundSnafu { region_id })?; engine - .set_region_role_with_lease(region_id, role, sent_at, deadline) + .set_region_role_with_lease(region_id, role, sent_at, deadline, candidate_lease_id) .with_context(|_| HandleRegionRequestSnafu { region_id }) } @@ -1340,9 +1369,21 @@ impl Deref for RegionEngineWithStatus { } } +/// Clears unfinished initialization requests when startup completes, fails, or is cancelled. +#[must_use = "the guard clears tracked initialization on drop"] +pub(crate) struct RegionInitializationGuard(Arc>); + +impl Drop for RegionInitializationGuard { + fn drop(&mut self) { + self.0.clear(); + } +} + struct RegionServerInner { engines: RwLock>, region_map: DashMap, + /// Regions queued or opening during background initialization only. + initializing_regions: Arc>, query_engine: QueryEngineRef, runtime: Runtime, event_listener: RegionServerEventListenerRef, @@ -1468,6 +1509,7 @@ impl RegionServerInner { Self { engines: RwLock::new(HashMap::new()), region_map: DashMap::new(), + initializing_regions: Arc::new(DashSet::new()), query_engine, runtime, event_listener, @@ -1824,6 +1866,20 @@ impl RegionServerInner { &self, batch_request: BatchRegionDdlRequest, ) -> Result { + // Drops may remove dependent regions and may partially succeed. Complete each + // request's registration changes before proceeding to the next request. + if let BatchRegionDdlRequest::Drop(requests) = batch_request { + let mut response = RegionResponse::new(0); + for (region_id, request) in requests { + let result = self + .handle_request(region_id, RegionRequest::Drop(request)) + .await?; + response.affected_rows += result.affected_rows; + response.extensions.extend(result.extensions); + } + return Ok(response); + } + let region_changes = match &batch_request { BatchRegionDdlRequest::Create(requests) => requests .iter() @@ -1944,6 +2000,12 @@ impl RegionServerInner { CurrentEngine::EarlyReturn(rows) => return Ok(RegionResponse::new(rows)), }; + let logical_regions = if matches!(region_change, RegionChange::Deregisters) { + self.prepare_logical_regions_for_deregistration(&engine, region_id) + } else { + Vec::new() + }; + // Sets corresponding region status to registering/deregistering before the operation. self.set_region_status_not_ready(region_id, &engine, ®ion_change); @@ -1956,6 +2018,14 @@ impl RegionServerInner { } match result { Ok(result) => { + for (logical_region, _) in logical_regions { + self.set_region_status_ready( + logical_region, + engine.clone(), + RegionChange::Deregisters, + ) + .await?; + } // Sets corresponding region status to ready. self.set_region_status_ready(region_id, engine.clone(), region_change) .await?; @@ -1967,6 +2037,9 @@ impl RegionServerInner { }) } Err(err) => { + for (logical_region, status) in logical_regions { + self.region_map.insert(logical_region, status); + } // Removes the region status if the operation fails. self.unset_region_status(region_id, &engine, region_change); Err(err) @@ -2039,6 +2112,7 @@ impl RegionServerInner { RegionChange::None | RegionChange::Ingest | RegionChange::OfflineCleanup(_) => {} RegionChange::Register(_) => { self.region_map.remove(®ion_id); + self.initializing_regions.remove(®ion_id); } RegionChange::Deregisters => { self.region_map @@ -2064,6 +2138,7 @@ impl RegionServerInner { ); self.region_map .insert(region_id, RegionEngineWithStatus::Ready(engine.clone())); + self.initializing_regions.remove(®ion_id); match attribute { RegionAttribute::Metric { physical } => { @@ -2100,6 +2175,26 @@ impl RegionServerInner { Ok(()) } + /// Captures only existing registrations so failures cannot resurrect closed logical regions. + fn prepare_logical_regions_for_deregistration( + &self, + engine: &RegionEngineRef, + physical_region_id: RegionId, + ) -> Vec<(RegionId, RegionEngineWithStatus)> { + let Some(metric_engine) = engine.as_any().downcast_ref::() else { + return Vec::new(); + }; + let logical_regions = metric_engine + .loaded_logical_regions(physical_region_id) + .into_iter() + .filter_map(|id| self.region_map.get(&id).map(|status| (id, status.clone()))) + .collect::>(); + for (region_id, _) in &logical_regions { + self.set_region_status_not_ready(*region_id, engine, &RegionChange::Deregisters); + } + logical_regions + } + async fn register_logical_regions( &self, engine: &RegionEngineRef, @@ -2375,7 +2470,7 @@ mod tests { use common_error::ext::{ErrorExt, RetryHint}; use common_recordbatch::RecordBatches; use common_recordbatch::adapter::{RecordBatchMetrics, RegionWatermarkEntry}; - use common_wal::config::object_store::{ObjectStoreWalConfig, STANDALONE_GENERATION}; + use common_wal::config::object_store::{FIXED_DIRECTORY_GENERATION, ObjectStoreWalConfig}; use common_wal::options::{ObjectStoreWalOptions, WAL_OPTIONS_KEY, WalOptions}; use datatypes::prelude::{ConcreteDataType, VectorRef}; use datatypes::schema::{ColumnSchema, Schema}; @@ -2634,6 +2729,59 @@ mod tests { )); } + #[tokio::test] + async fn test_background_region_initialization() { + let server = mock_region_server(); + let queued = RegionId::new(1, 1); + let opening = RegionId::new(1, 2); + let guard = server.track_region_initialization([queued, opening]); + let (mut engine, _receiver) = MockRegionEngine::new(MITO_ENGINE_NAME); + Arc::get_mut(&mut engine).unwrap().mock_role = Some(None); + let engine: RegionEngineRef = engine; + server + .inner + .region_map + .insert(opening, RegionEngineWithStatus::Registering(engine.clone())); + let mut regions = server.opening_regions(); + regions.sort_unstable(); + assert_eq!(regions, vec![queued, opening]); + + server.inner.unset_region_status( + opening, + &engine, + RegionChange::Register(RegionAttribute::Mito), + ); + assert_eq!(server.opening_regions(), vec![queued]); + + // An engine may report a role before the whole open batch returns. + let (serving_engine, _receiver) = MockRegionEngine::new(MITO_ENGINE_NAME); + for status in [ + RegionEngineWithStatus::Registering(serving_engine.clone()), + RegionEngineWithStatus::Ready(serving_engine.clone()), + ] { + server.inner.region_map.insert(queued, status); + assert!(server.opening_regions().is_empty()); + assert!(server.inner.initializing_regions.contains(&queued)); + } + server + .inner + .set_region_status_ready( + queued, + serving_engine, + RegionChange::Register(RegionAttribute::Mito), + ) + .await + .unwrap(); + assert!(!server.inner.initializing_regions.contains(&queued)); + assert!(server.opening_regions().is_empty()); + + // Keep one unfinished request to verify guard cleanup. + server.inner.initializing_regions.insert(opening); + assert_eq!(server.opening_regions(), vec![opening]); + drop(guard); + assert!(server.opening_regions().is_empty()); + } + #[tokio::test] async fn test_region_registering() { common_telemetry::init_default_ut_logging(); @@ -3588,7 +3736,7 @@ mod tests { ObjectStore::new(Memory::default()).unwrap(), &wal_config, 0, - STANDALONE_GENERATION, + FIXED_DIRECTORY_GENERATION, ) .await .unwrap(); @@ -3598,7 +3746,7 @@ mod tests { let mut region_server = mock_region_server(); region_server.register_engine(Arc::new(engine)); let wal_options = serde_json::to_string(&WalOptions::ObjectStore( - ObjectStoreWalOptions::new(wal_config.node_prefix(0, STANDALONE_GENERATION)), + ObjectStoreWalOptions::new(wal_config.node_prefix(0, FIXED_DIRECTORY_GENERATION)), )) .unwrap(); (region_server, log_store, wal_options) @@ -3629,6 +3777,202 @@ mod tests { } } + #[tokio::test] + async fn test_metric_physical_drop_and_close_unregister_logical_regions() { + for mode in ["drop", "close", "batch_drop"] { + let mut env = TestEnv::with_prefix("region-server-metric-drop").await; + let mito = env.create_engine(MitoConfig::default()).await; + let metric = Arc::new( + MetricEngine::try_new(mito.clone(), metric_engine::config::EngineConfig::default()) + .unwrap(), + ); + let mut server = mock_region_server(); + server.register_engine(metric.clone()); + // Keep a second physical group alive to catch overbroad unregistering. + for table in [10, 20] { + let physical = RegionId::new(table, 0); + let logical = RegionId::new(table + 1, 0); + let mut create = CreateRequestBuilder::new().build(); + create.engine = METRIC_ENGINE_NAME.to_string(); + create.column_metadatas = vec![ + store_api::metadata::ColumnMetadata { + column_id: 0, + semantic_type: SemanticType::Timestamp, + column_schema: ColumnSchema::new( + "greptime_timestamp", + ConcreteDataType::timestamp_millisecond_datatype(), + false, + ), + }, + store_api::metadata::ColumnMetadata { + column_id: 1, + semantic_type: SemanticType::Field, + column_schema: ColumnSchema::new( + "greptime_value", + ConcreteDataType::float64_datatype(), + false, + ), + }, + ]; + create.primary_key.clear(); + create.table_dir = format!("metric-drop/{table}/"); + create.options = HashMap::from([( + store_api::metric_engine_consts::PHYSICAL_TABLE_METADATA_KEY.to_string(), + String::new(), + )]); + server + .handle_request(physical, RegionRequest::Create(create.clone())) + .await + .unwrap(); + create.table_dir = format!("metric-drop/{}/", table + 1); + create.options = HashMap::from([( + store_api::metric_engine_consts::LOGICAL_TABLE_METADATA_KEY.to_string(), + physical.as_u64().to_string(), + )]); + server + .handle_request(logical, RegionRequest::Create(create.clone())) + .await + .unwrap(); + if table == 10 { + let closed = RegionId::new(12, 0); + server + .handle_request(closed, RegionRequest::Create(create.clone())) + .await + .unwrap(); + server + .handle_request(closed, RegionRequest::Close(RegionCloseRequest::default())) + .await + .unwrap(); + } + } + let physical = RegionId::new(10, 0); + let logical = RegionId::new(11, 0); + let mut dependents = metric.loaded_logical_regions(physical); + dependents.sort_unstable(); + assert_eq!(dependents, vec![logical, RegionId::new(12, 0)]); + assert!(metric.loaded_logical_regions(logical).is_empty()); + // Rejection must leave both registrations usable for a subsequent forced drop. + assert!( + server + .handle_request( + physical, + RegionRequest::Drop(RegionDropRequest { + fast_path: false, + force: false, + partial_drop: false, + }) + ) + .await + .is_err() + ); + assert!(!server.inner.region_map.contains_key(&RegionId::new(12, 0))); + for id in [physical, logical] { + assert!(matches!( + server.inner.region_map.get(&id).unwrap().value(), + RegionEngineWithStatus::Ready(_) + )); + } + server + .inner + .region_map + .insert(logical, RegionEngineWithStatus::Registering(metric.clone())); + assert!( + server + .handle_request( + physical, + RegionRequest::Drop(RegionDropRequest { + fast_path: false, + force: false, + partial_drop: false, + }) + ) + .await + .is_err() + ); + assert!(matches!( + server.inner.region_map.get(&logical).unwrap().value(), + RegionEngineWithStatus::Registering(_) + )); + server + .inner + .region_map + .insert(logical, RegionEngineWithStatus::Ready(metric.clone())); + if mode == "batch_drop" { + // First group commits, second rejects. Retrying must not resurrect the first. + for _ in 0..2 { + assert!( + server + .inner + .handle_batch_ddl_requests(BatchRegionDdlRequest::Drop(vec![ + ( + physical, + RegionDropRequest { + fast_path: false, + force: true, + partial_drop: false + } + ), + ( + RegionId::new(20, 0), + RegionDropRequest { + fast_path: false, + force: false, + partial_drop: false + } + ), + ])) + .await + .is_err() + ); + assert!(!server.inner.region_map.contains_key(&physical)); + assert!(!server.inner.region_map.contains_key(&logical)); + } + } + let request = || { + if mode == "close" { + RegionRequest::Close(RegionCloseRequest::default()) + } else { + RegionRequest::Drop(RegionDropRequest { + fast_path: false, + force: true, + partial_drop: false, + }) + } + }; + // A retry of an already completed removal remains harmless. + for _ in 0..2 { + if mode == "batch_drop" { + server + .inner + .handle_batch_ddl_requests(BatchRegionDdlRequest::Drop(vec![( + physical, + RegionDropRequest { + fast_path: false, + force: true, + partial_drop: false, + }, + )])) + .await + .unwrap(); + } else { + server.handle_request(physical, request()).await.unwrap(); + } + } + for id in [physical, logical] { + assert!(!server.inner.region_map.contains_key(&id)); + } + assert!(metric.loaded_logical_regions(physical).is_empty()); + for id in [RegionId::new(20, 0), RegionId::new(21, 0)] { + assert!(server.inner.region_map.contains_key(&id)); + } + assert_eq!( + metric.loaded_logical_regions(RegionId::new(20, 0)), + vec![RegionId::new(21, 0)] + ); + server.stop().await.unwrap(); + } + } + #[tokio::test] async fn test_metric_batch_failure_indices() { let mut env = TestEnv::with_prefix("region-server-metric-results").await; diff --git a/src/datanode/src/region_server/catalog/inspect.rs b/src/datanode/src/region_server/catalog/inspect.rs index da3ebdb130b..875d7271b37 100644 --- a/src/datanode/src/region_server/catalog/inspect.rs +++ b/src/datanode/src/region_server/catalog/inspect.rs @@ -426,6 +426,7 @@ mod tests { flushed_entry_id: None, flushed_sequence: None, committed_sequence: None, + wal_recovery: Default::default(), }, ) .await diff --git a/src/datanode/src/region_server/catalog/tests/manifest.rs b/src/datanode/src/region_server/catalog/tests/manifest.rs index 91b9f757a3d..81288b506a6 100644 --- a/src/datanode/src/region_server/catalog/tests/manifest.rs +++ b/src/datanode/src/region_server/catalog/tests/manifest.rs @@ -74,6 +74,7 @@ async fn manifest_engine(regions: u32, files_per_region: usize) -> (TestEnv, Mit flushed_entry_id: None, flushed_sequence: None, committed_sequence: None, + wal_recovery: Default::default(), }, ) .await @@ -189,6 +190,7 @@ async fn test_manifest_referring_region_and_origin_path() { flushed_entry_id: None, flushed_sequence: None, committed_sequence: None, + wal_recovery: Default::default(), }, ) .await diff --git a/src/datanode/src/tests.rs b/src/datanode/src/tests.rs index a126d3429fd..0ee830af535 100644 --- a/src/datanode/src/tests.rs +++ b/src/datanode/src/tests.rs @@ -13,7 +13,7 @@ // limitations under the License. use std::any::Any; -use std::sync::Arc; +use std::sync::{Arc, Mutex}; use std::time::Duration; use api::region::RegionResponse; @@ -135,6 +135,8 @@ pub struct MockRegionEngine { pub(crate) handle_sync_region_mock_fn: Option, pub(crate) handle_stop_mock_fn: Option, pub(crate) mock_role: Option>, + /// The candidate lease ids of the leases the engine received. + pub(crate) candidate_lease_ids: Mutex>>, engine: String, } @@ -152,6 +154,7 @@ impl MockRegionEngine { handle_sync_region_mock_fn: None, handle_stop_mock_fn: None, mock_role: None, + candidate_lease_ids: Mutex::default(), engine: engine.to_string(), }), rx, @@ -174,6 +177,7 @@ impl MockRegionEngine { handle_sync_region_mock_fn: None, handle_stop_mock_fn: None, mock_role: None, + candidate_lease_ids: Mutex::default(), engine: engine.to_string(), }), rx, @@ -196,6 +200,7 @@ impl MockRegionEngine { handle_sync_region_mock_fn: None, handle_stop_mock_fn: None, mock_role: None, + candidate_lease_ids: Mutex::default(), engine: engine.to_string(), }), rx, @@ -219,6 +224,7 @@ impl MockRegionEngine { handle_sync_region_mock_fn: None, handle_stop_mock_fn: None, mock_role: None, + candidate_lease_ids: Mutex::default(), engine: engine.to_string(), }; @@ -295,7 +301,12 @@ impl RegionEngine for MockRegionEngine { role: RegionRole, _sent_at: std::time::Instant, _deadline: std::time::Instant, + candidate_lease_id: Option, ) -> Result { + self.candidate_lease_ids + .lock() + .unwrap() + .push(candidate_lease_id); // A mocked role stays, so a grant of another role is not applied. Ok(self.mock_role.flatten().is_none_or(|mocked| mocked == role)) } diff --git a/src/datatypes/Cargo.toml b/src/datatypes/Cargo.toml index d684415400b..8cf586a6143 100644 --- a/src/datatypes/Cargo.toml +++ b/src/datatypes/Cargo.toml @@ -27,12 +27,13 @@ enum_dispatch = "0.3" jsonb.workspace = true num = "0.4" num-traits = "0.2" +once_cell.workspace = true ordered-float.workspace = true parquet-variant.workspace = true parquet-variant-compute.workspace = true parquet-variant-json.workspace = true paste.workspace = true -serde.workspace = true +serde = { workspace = true, features = ["rc"] } serde_json.workspace = true snafu.workspace = true sqlparser.workspace = true diff --git a/src/datatypes/src/error.rs b/src/datatypes/src/error.rs index b41e199e3a0..3a3f5f751b2 100644 --- a/src/datatypes/src/error.rs +++ b/src/datatypes/src/error.rs @@ -343,6 +343,13 @@ pub enum Error { location: Location, }, + #[snafu(display("Invalid series: {reason}"))] + InvalidSeries { + reason: String, + #[snafu(implicit)] + location: Location, + }, + #[snafu(display("unexpected: {reason}"))] Unexpected { reason: String, @@ -376,7 +383,8 @@ impl ErrorExt for Error { | InvalidVector { .. } | InvalidFulltextOption { .. } | InvalidSkippingIndexOption { .. } - | InvalidCompressionOption { .. } => StatusCode::InvalidArguments, + | InvalidCompressionOption { .. } + | InvalidSeries { .. } => StatusCode::InvalidArguments, #[cfg(feature = "enterprise")] InvalidSketchOption { .. } => StatusCode::InvalidArguments, diff --git a/src/datatypes/src/json/value.rs b/src/datatypes/src/json/value.rs index 7bcb1ecc2b9..5d115f99441 100644 --- a/src/datatypes/src/json/value.rs +++ b/src/datatypes/src/json/value.rs @@ -379,6 +379,11 @@ impl JsonValue { self.json_variant } + /// Borrows the JSON representation without constructing a tree of value references. + pub fn variant(&self) -> &JsonVariant { + &self.json_variant + } + pub(crate) fn into_value(self) -> Value { fn helper(v: JsonVariant) -> Value { match v { diff --git a/src/datatypes/src/lib.rs b/src/datatypes/src/lib.rs index 0dcce168571..fee2ab7f819 100644 --- a/src/datatypes/src/lib.rs +++ b/src/datatypes/src/lib.rs @@ -24,6 +24,7 @@ pub mod prelude; pub mod scalars; pub mod schema; pub mod serialize; +pub mod series; pub mod time; pub mod timestamp; pub mod type_id; diff --git a/src/datatypes/src/schema.rs b/src/datatypes/src/schema.rs index cae7b9aa2bc..e992e7070a6 100644 --- a/src/datatypes/src/schema.rs +++ b/src/datatypes/src/schema.rs @@ -39,7 +39,8 @@ pub use crate::schema::column_schema::{ COLUMN_SKIPPING_INDEX_OPT_KEY_TYPE, COMMENT_KEY, COMPRESSION_KEY, ColumnEncoding, ColumnExtType, ColumnSchema, CompressionOptions, CompressionType, FULLTEXT_KEY, FulltextAnalyzer, FulltextBackend, FulltextOptions, HLL_KEY, INVERTED_INDEX_KEY, KLL_KEY, - MG_KEY, Metadata, SKIPPING_INDEX_KEY, SkippingIndexOptions, SkippingIndexType, TIME_INDEX_KEY, + METRIC_NAME_KEY, MG_KEY, Metadata, SKIPPING_INDEX_KEY, SkippingIndexOptions, SkippingIndexType, + TIME_INDEX_KEY, is_metric_name_field, metric_name_field_metadata, }; pub use crate::schema::constraint::ColumnDefaultConstraint; #[cfg(feature = "enterprise")] diff --git a/src/datatypes/src/schema/column_schema.rs b/src/datatypes/src/schema/column_schema.rs index d43f95b4c44..6361ce65636 100644 --- a/src/datatypes/src/schema/column_schema.rs +++ b/src/datatypes/src/schema/column_schema.rs @@ -42,6 +42,16 @@ pub type Metadata = HashMap; /// Key used to store whether the column is time index in arrow field's metadata. pub const TIME_INDEX_KEY: &str = "greptime:time_index"; +/// Key used to store whether the column carries the metric name of each row in arrow field's +/// metadata. +/// +/// A PromQL result normally carries one metric name for the whole response, which the response +/// layer derives from the statement. A native set operator reports the series of both operands, so +/// its rows carry the name of the side each one came from, and that name is a column of the plan. +/// This declaration is what says a column is that name rather than an ordinary label; a column's +/// name cannot say it, because a label an operation generates may legitimately be called +/// `__name__`. +pub const METRIC_NAME_KEY: &str = "greptime:metric_name"; pub const COMMENT_KEY: &str = "greptime:storage:comment"; /// Key used to store default constraint in arrow field's metadata. const DEFAULT_CONSTRAINT_KEY: &str = "greptime:default_constraint"; @@ -248,6 +258,28 @@ impl ColumnSchema { .unwrap_or(false) } + /// Whether this column carries the metric name of its row. + /// + /// See [METRIC_NAME_KEY] for what a producer declares and the response layer that reads it. + pub fn is_metric_name(&self) -> bool { + self.metadata + .get(METRIC_NAME_KEY) + .map(|value| value.eq_ignore_ascii_case("true")) + .unwrap_or(false) + } + + /// Marks this column as carrying the metric name of its row, or clears the mark. + pub fn with_metric_name(mut self, is_metric_name: bool) -> Self { + if is_metric_name { + let _ = self + .metadata + .insert(METRIC_NAME_KEY.to_string(), "true".to_string()); + } else { + let _ = self.metadata.remove(METRIC_NAME_KEY); + } + self + } + pub fn is_fulltext_indexed(&self) -> bool { self.fulltext_options() .unwrap_or_default() @@ -762,6 +794,25 @@ impl TryFrom<&ColumnSchema> for Field { } } +/// The arrow field metadata that declares a column as carrying the metric name of its rows. +/// +/// A producer that builds an arrow [Field] directly, rather than through a [ColumnSchema], attaches +/// this to the name column so the response layer reads the name from it; see [METRIC_NAME_KEY]. +pub fn metric_name_field_metadata() -> Metadata { + let mut metadata = Metadata::new(); + let _ = metadata.insert(METRIC_NAME_KEY.to_string(), "true".to_string()); + metadata +} + +/// Whether the metadata of `field` declares it as carrying the metric name of its rows. +pub fn is_metric_name_field(field: &Field) -> bool { + field + .metadata() + .get(METRIC_NAME_KEY) + .map(|value| value.eq_ignore_ascii_case("true")) + .unwrap_or(false) +} + /// Fulltext options for a column. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Visit, VisitMut)] #[serde(rename_all = "kebab-case")] diff --git a/src/datatypes/src/series.rs b/src/datatypes/src/series.rs new file mode 100644 index 00000000000..56369e93dd8 --- /dev/null +++ b/src/datatypes/src/series.rs @@ -0,0 +1,383 @@ +// 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. + +pub mod aggregate_state; +pub mod frame; +pub mod histogram; +pub mod raw; +pub mod samples; +pub mod time; + +#[cfg(test)] +mod tests; + +use std::any::Any; +use std::sync::{Arc, OnceLock}; + +use arrow::array::{Array, StringArray}; +use arrow::record_batch::RecordBatch; + +use crate::error::{InvalidSeriesSnafu, Result}; + +/// Ordering guarantee within one stream and each of its output partitions. +/// +/// Every series has strictly increasing sample positions, including across chunks; positions +/// are raw timestamps or, for evaluated series, current-stage evaluation times or grid positions. +/// They need not all be explicit times on the grid. Within one series or producer fragment, +/// no mode permits duplicate positions. `Interleaved` permits A1, B1, A2; only the latter two modes +/// keep each series contiguous. `KeyThenTime` also orders by this stream's series identity, then time: +/// raw streams use the complete bound-compatible identity (not just a TSID or hash), while +/// evaluated streams use current name/label identity, not storage primary keys or object address/hash. +/// This ordering is not a query-global ordering, partition-ownership rule, or finality guarantee. +/// +/// A raw frame adapter accepts only a subset of `Interleaved`: it transports independently closed +/// producer fragment chains in sequence, allowing the same key and overlapping timestamps in +/// different fragment chains. Finality closes a fragment, not necessarily the logical series. The +/// adapter rejects switching keys before a chain closes; it does not support arbitrary multiplexing +/// of open chains, even though the general ordering permits it. +#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize, Hash)] +pub enum SeriesOrdering { + /// Series chunks may interleave; positions within each series remain strictly increasing. + Interleaved, + /// Each series is contiguous; distinct series need not be ordered. + Contiguous, + /// Series are ordered by stream identity and then by strictly increasing position. + KeyThenTime, +} + +/// A label with shared UTF-8 name and value strings. +#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize, Hash)] +pub struct Label { + /// Label name. + pub name: Arc, + /// Label value. + pub value: Arc, +} + +/// The PromQL-visible labels of one series: an optional metric name (`__name__`) +/// plus its name-sorted ordinary labels. +/// +/// The metric name is only the `__name__` value (see [`Self::name`]); this type is +/// the whole label set a PromQL series shows. It is neither a canonical +/// matching/grouping identity nor a storage identity (read key / primary key). +#[derive(Clone, Debug)] +pub struct SeriesLabels { + name: Option>, + tags: LabelStorage, +} + +impl serde::Serialize for SeriesLabels { + fn serialize( + &self, + serializer: S, + ) -> std::result::Result { + (&self.name, self.tags()).serialize(serializer) + } +} +impl<'de> serde::Deserialize<'de> for SeriesLabels { + fn deserialize>( + deserializer: D, + ) -> std::result::Result { + let (name, tags): (Option>, Vec