diff --git a/.github/scheduled-validations.json b/.github/scheduled-validations.json index 0d30e7d15c..30a9b71e60 100644 --- a/.github/scheduled-validations.json +++ b/.github/scheduled-validations.json @@ -1239,6 +1239,33 @@ "origin": "baseline", "alert_contract": "scheduled-validation" }, + { + "workflow": ".github/workflows/nightly-rdma.yml", + "name": "Nightly RDMA Build", + "roles": [ + "periodic", + "manual", + "release" + ], + "events": [ + "schedule", + "workflow_dispatch" + ], + "cadence": "nightly", + "timezone": "UTC", + "schedule": [ + "0 0 * * *" + ], + "owner": "@overtrue", + "policy": "active", + "monitor": "workflow", + "max_age_hours": 36, + "result_owner": "nightly-rdma.yml", + "disposition": "independent RDMA/NIXL nightly package; adds rustfs-nightly-rdma-latest.deb on the shared nightly release without replacing GNU assets or dispatching nightly-candidate-ready", + "failure_owner": "workflow", + "origin": "added", + "alert_contract": "scheduled-validation" + }, { "workflow": ".github/workflows/nix-flake-update.yml", "name": "Update Nix Flake", diff --git a/.github/workflows/README.md b/.github/workflows/README.md index e8890ff618..59764461c3 100644 --- a/.github/workflows/README.md +++ b/.github/workflows/README.md @@ -19,6 +19,7 @@ Every other label in this repository is capacity RustFS pays for. ARC pods and l | `ubicloud-standard-16-arm` | RustFS | Ubicloud VM, alias of `ubicloud-standard-16-arm-ubuntu-2404`: Ubuntu 24.04 arm64, 16 vCPU, 48 GB, 300 GB disk. Reached through the `build.yml` matrix, so `actionlint.yaml` does not list it | native aarch64 release builds (`linux-aarch64-musl`, `linux-aarch64-gnu`) | | `dind-sm-standard-2` | RustFS | ARC pod with Docker-in-Docker | Docker workloads with a measured resource or environment requirement beyond the hosted runner | | `smoke-testing`, `pf-testing` | RustFS | long-lived lab machines | the packaged functional chain and performance suites | +| `rdma` | RustFS | long-lived lab machine with native NIXL/RDMA libraries | `rdma-build.yml` compile checks and the `nightly-rdma.yml` native release package | The self-hosted pods and the hosted image are both Ubuntu 24.04, so a binary built on one runs on the other; `ci.yml` builds the debug binary on `sm-standard-4` and runs it on both pools. @@ -45,7 +46,7 @@ A hosted runner is also the only choice for a few things the pods cannot do: `mo - Every `shared-key` has exactly one writer. `cache-warm.yml` owns `ci-dev`, `ci-feat-proto` and `ci-uring`; every other `./.github/actions/setup` call states `cache-save-if` explicitly, and `scripts/security/check_cache_save_if.sh` fails the build when one does not. - The `ci-dev` key ends in a digest of `warm-ci-dev`'s build commands. Changing what that job warms therefore needs a new key, or readers keep restoring the old artifacts: `scripts/ci_gate.py --check-workflow` prints the key the commands require and fails until the writer and every registered `sm-standard-4` reader (`ci.yml`, `dual-stack-nightly.yml`, `e2e-replication-nightly.yml`, `fuzz.yml`, `gateway-acceptance.yml`, `mint.yml` and `reference-parity.yml`) name it. -- All readers of a key run on the same image as its writer. Keys that live on hosted runners say so in their name (`ci-uring` is warmed on `ubuntu-latest`; `ci-e2e-distributed-hosted` is written on `ubuntu-latest` by `e2e-distributed.yml` and read without saving by hosted server/E2E lanes such as `gateway-acceptance.yml`, `on-demand-migration-interop.yml`, `oidc-keycloak.yml`, `minio-interop.yml`, `e2e-upgrade.yml` and `rdma-feature-check.yml`). `rdma-build.yml` owns `ci-nixl-rdma` on the `rdma` label and is the only job that saves it. +- All readers of a key run on the same image as its writer. Keys that live on hosted runners say so in their name (`ci-uring` is warmed on `ubuntu-latest`; `ci-e2e-distributed-hosted` is written on `ubuntu-latest` by `e2e-distributed.yml` and read without saving by hosted server/E2E lanes such as `gateway-acceptance.yml`, `on-demand-migration-interop.yml`, `oidc-keycloak.yml`, `minio-interop.yml`, `e2e-upgrade.yml` and `rdma-feature-check.yml`). `rdma-build.yml` owns `ci-nixl-rdma` on the `rdma` label and is the only job that saves it. `nightly-rdma.yml` owns `nightly-rdma-nixl` on that same label and is the only job that saves it. - Moving a job between pools therefore means renaming its key. The new key is empty until a run from `main` (a scheduled run, or a manual dispatch of that workflow from `main`) saves it; until then that lane does a cold build. The `build.yml` aarch64 release legs append `-ubicloud-arm` for this reason. `cache-warm.yml` does not write those keys. - `CARGO_BUILD_JOBS` and every other `CARGO*`, `CC*`, `CFLAGS*`, `CXX*`, `CMAKE*` and `RUST*` variable is hashed into the key. `ci.yml` sets `CARGO_BUILD_JOBS` at step level for that reason; promoting it to job level rotates the key for every lane that shares it. diff --git a/.github/workflows/nightly-rdma.yml b/.github/workflows/nightly-rdma.yml new file mode 100644 index 0000000000..9db8070447 --- /dev/null +++ b/.github/workflows/nightly-rdma.yml @@ -0,0 +1,595 @@ +# Copyright 2024 RustFS 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. + +name: Nightly RDMA Build + +# Standalone nightly package of the rustfs binary with the nixl feature. +# It does not call nightly-gnu.yml, does not share that workflow's +# concurrency group, and does not dispatch nightly-candidate-ready. +# rustfs-functional-chain.yml listens only for "Nightly GNU Build", so a +# failure here cannot block or break the GNU nightly functional-testing chain. +# +# The schedule is midnight Asia/Shanghai. +# NIXL links the runner's native libraries, so this job uses cargo build +# rather than cargo zigbuild and the glibc 2.31 cross baseline. + +on: + schedule: + - cron: "0 0 * * *" + timezone: "Asia/Shanghai" + workflow_dispatch: + inputs: + branch: + description: 'Branch/ref to build and publish as the RDMA nightly (empty = scheduled source, see NIGHTLY_BUILD_REF)' + required: false + default: '' + +permissions: + contents: read + +# Scheduled builds follow the NIGHTLY_BRANCH repo variable so the channel can +# be pointed at e.g. `release` for the GA cycle and back to `main` afterwards +# without touching this file. Manual runs take the `branch` input, falling +# back to the branch the run was dispatched from. +concurrency: + group: nightly-rdma-build-${{ github.event_name }}-${{ github.event_name == 'schedule' && (vars.NIGHTLY_BRANCH || 'main') || (inputs.branch || github.ref_name) }} + cancel-in-progress: ${{ github.event_name == 'workflow_dispatch' }} + +env: + CARGO_TERM_COLOR: always + RUST_BACKTRACE: 1 + NIGHTLY_BUILD_REF: ${{ github.event_name == 'schedule' && (vars.NIGHTLY_BRANCH || 'main') || (inputs.branch || github.ref_name) }} + +jobs: + resolve-source: + if: github.repository == 'rustfs/rustfs' + name: Resolve nightly source + runs-on: ubuntu-latest + timeout-minutes: 10 + outputs: + source_sha: ${{ steps.source.outputs.sha }} + source_ref: ${{ steps.source.outputs.ref }} + steps: + - name: Checkout selected source + uses: actions/checkout@f548e57e544e1ff5a4c46bf1e1b8685f8e4a348a # v7 + with: + persist-credentials: false + ref: ${{ env.NIGHTLY_BUILD_REF }} + - name: Record immutable source + id: source + run: | + echo "sha=$(git rev-parse HEAD)" >> "$GITHUB_OUTPUT" + echo "ref=${NIGHTLY_BUILD_REF}" >> "$GITHUB_OUTPUT" + + build: + needs: resolve-source + name: Build x86_64 RDMA + # Hardware or environment: native NIXL/RDMA libraries on the self-hosted + # `rdma` runner. Hosted ubuntu-latest has no libnixl, and a glibc 2.31 + # zigbuild cannot link those libraries. Bare label, same form as + # rdma-build.yml (not a [self-hosted, ...] list). + runs-on: rdma + timeout-minutes: 150 + env: + NIGHTLY_BUILD_REF: ${{ needs.resolve-source.outputs.source_ref }} + FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: "true" + steps: + - name: Checkout repository + uses: actions/checkout@f548e57e544e1ff5a4c46bf1e1b8685f8e4a348a # v7 + with: + persist-credentials: false + ref: ${{ needs.resolve-source.outputs.source_sha }} + + - name: Setup Rust environment + uses: ./.github/actions/setup + with: + rust-version: stable + # Own key: rust-cache does not include the runner label. + # rdma-build.yml owns ci-nixl-rdma; this nightly must not share it. + # Save only when the resolved source ref is main. github.ref is the + # branch that holds this workflow file, so a scheduled run with + # NIGHTLY_BRANCH set to something else would otherwise write that + # tree into nightly-rdma-nixl. + cache-shared-key: nightly-rdma-nixl + cache-save-if: ${{ needs.resolve-source.outputs.source_ref == 'main' }} + install-build-packaging-tools: 'false' + install-test-tools: 'false' + + - name: Install only missing native build tools + shell: bash + run: | + set -euo pipefail + packages=() + command -v g++ >/dev/null || packages+=(g++) + ldconfig -p | grep -q 'libclang' || packages+=(libclang-dev) + command -v unzip >/dev/null || packages+=(unzip) + command -v fakeroot >/dev/null || packages+=(fakeroot) + if (( ${#packages[@]} )); then + sudo apt-get update + sudo apt-get install --no-install-recommends -y "${packages[@]}" + fi + + - name: Download static console assets + shell: bash + env: + GITHUB_TOKEN: ${{ github.token }} + run: | + # Packaging tools are off on this lane, so setup does not install unzip. + if ! command -v unzip >/dev/null 2>&1; then + sudo apt-get update -qq + sudo apt-get install -y -qq unzip + fi + if ! command -v unzip >/dev/null 2>&1; then + echo "unzip is required to extract console assets" >&2 + exit 1 + fi + + mkdir -p ./rustfs/static + + verify_sha256() { + local expected="$1" + local file="$2" + local actual="" + local actual_line="" + + if command -v sha256sum >/dev/null 2>&1; then + actual_line=$(sha256sum -- "$file") || return 1 + elif command -v shasum >/dev/null 2>&1; then + actual_line=$(shasum -a 256 -- "$file") || return 1 + else + echo "No SHA-256 verification tool found" >&2 + return 1 + fi + actual="${actual_line%%[[:space:]]*}" + + if [ "$actual" = "$expected" ]; then + echo "SHA256 verified OK: $actual" + return 0 + else + echo "SHA256 mismatch: expected=$expected actual=$actual" >&2 + return 1 + fi + } + + download_console_assets() { + local curl_bin="curl" + local python_bin="python3" + local console_api="https://api.github.com/repos/rustfs/console/releases/latest" + local console_json="console-release.json" + local console_url + local console_sha256 + local curl_auth_args=() + console_tag="" + + chmod +w ./rustfs/static/LICENSE || true + + if ! command -v "$python_bin" >/dev/null 2>&1; then + python_bin="python" + fi + if ! command -v "$python_bin" >/dev/null 2>&1; then + echo "No Python interpreter found for release metadata parsing" >&2 + return 1 + fi + + if [[ -n "${GITHUB_TOKEN:-}" ]]; then + curl_auth_args=(-H "Authorization: Bearer ${GITHUB_TOKEN}" -H "X-GitHub-Api-Version: 2022-11-28") + fi + + "$curl_bin" "${curl_auth_args[@]}" --fail -L "$console_api" \ + -o "$console_json" --retry 3 --retry-delay 5 --max-time 300 || return 1 + + read -r console_tag console_url console_sha256 < <("$python_bin" - "$console_json" <<'PY' + import json + import re + import sys + + with open(sys.argv[1], encoding="utf-8") as handle: + release = json.load(handle) + + tag = release.get("tag_name", "") or "unknown" + + for asset in release.get("assets", []): + name = asset.get("name", "") + digest = asset.get("digest", "") + url = asset.get("browser_download_url", "") + if name.startswith("rustfs-console-") and name.endswith(".zip") and digest.startswith("sha256:") and url: + sha256 = digest.split(":", 1)[1] + if not re.fullmatch(r"[0-9a-fA-F]{64}", sha256): + raise SystemExit(f"console zip asset has invalid sha256 digest: {sha256}") + sys.stdout.buffer.write(f"{tag} {url} {sha256}\n".encode("utf-8")) + break + else: + raise SystemExit("no console zip asset with sha256 digest found") + PY + ) || return 1 + + if [[ -z "$console_url" || -z "$console_sha256" ]]; then + echo "Console release metadata is missing URL or SHA-256 digest" >&2 + return 1 + fi + + echo "Console release: ${console_tag}" + echo "Downloading console asset: ${console_url}" + "$curl_bin" --fail -L "$console_url" -o console.zip --retry 3 --retry-delay 5 --max-time 300 || return 1 + verify_sha256 "$console_sha256" console.zip || return 2 + unzip -o console.zip -d ./rustfs/static || return 2 + } + + if download_console_assets; then + rm -f console.zip console-release.json + else + status=$? + rm -f console.zip console-release.json + if [[ "$status" -eq 2 ]]; then + echo "Console asset integrity verification failed" >&2 + fi + echo "Failed to download verified console assets" >&2 + exit 1 + fi + + if [[ ! -s ./rustfs/static/index.html ]]; then + echo "Console asset archive is missing static/index.html" >&2 + exit 1 + fi + + asset_count=$(find ./rustfs/static -type f | wc -l | tr -d '[:space:]') + echo "Console assets ready: version=${console_tag:-unknown}, ${asset_count} files extracted to ./rustfs/static" + + - name: Build RustFS with NIXL + shell: bash + run: | + set -euo pipefail + # Force rebuild by touching build.rs so a restored cache cannot + # reuse a rustfs artifact compiled before these console assets existed. + # Native build: NIXL links the runner's libraries, so this lane does + # not use cargo zigbuild or the glibc 2.31 baseline. + touch rustfs/build.rs + NIXL_NO_STUBS_FALLBACK=1 cargo build --release --locked -p rustfs --bin rustfs --features nixl + + - name: Verify console + shell: bash + run: | + set -euo pipefail + + find_free_port() { + python3 - <<'PY' + import socket + + with socket.socket() as sock: + sock.bind(("127.0.0.1", 0)) + print(sock.getsockname()[1]) + PY + } + + binary="target/release/rustfs" + data_dir="$(mktemp -d)" + log_file="${RUNNER_TEMP}/rustfs-console-smoke.log" + server_pid="" + trap ' + if [[ -n "${server_pid:-}" ]]; then + kill "$server_pid" 2>/dev/null || true + wait "$server_pid" 2>/dev/null || true + fi + rm -rf "$data_dir" + ' EXIT + + if [[ ! -x "$binary" ]]; then + echo "rustfs binary not found: ${binary}" >&2 + exit 1 + fi + + api_port="$(find_free_port)" + console_port="$(find_free_port)" + console_url="http://127.0.0.1:${console_port}/rustfs/console/" + + "$binary" server \ + --address "127.0.0.1:${api_port}" \ + --console-enable \ + --console-address "127.0.0.1:${console_port}" \ + --access-key console-smoke \ + --secret-key console-smoke-secret \ + "$data_dir" >"$log_file" 2>&1 & + server_pid=$! + + response="" + for _ in {1..40}; do + response="$(curl --silent --output /dev/null --write-out '%{http_code} %{content_type}' "$console_url" || true)" + if [[ "$response" == 200\ text/html* ]]; then + exit 0 + fi + sleep 0.25 + done + + echo "Console endpoint did not return 200 text/html: $response" >&2 + cat "$log_file" + exit 1 + + - name: Build DEB package + id: deb + shell: bash + run: | + set -euo pipefail + + # Nightly snapshot name: rustfs-nightly-rdma- + # (Asia/Shanghai, matching the schedule timezone so the file date + # always matches the cron's intended day). + DEB_DATE="$(TZ=Asia/Shanghai date +%Y-%m-%d)" + DEB_FILE="rustfs-nightly-rdma-${DEB_DATE}.deb" + LATEST_FILE="rustfs-nightly-rdma-latest.deb" + PKG_DIR="rustfs-nightly-rdma-${DEB_DATE}" + + command -v fakeroot >/dev/null 2>&1 || sudo apt-get install -y -qq fakeroot + + BIN="target/release/rustfs" + test -x "${BIN}" || { echo "rustfs binary not found: ${BIN}"; exit 1; } + + # Native NIXL link: the libc floor is the highest GLIBC symbol this + # binary needs, using the same version-needs section as + # scripts/release/check_glibc.py. The zigbuild 2.31 floor does not + # apply here. + GLIBC_MIN="$(python3 - "${BIN}" <<'PY' + import os + import re + import subprocess + import sys + + binary = sys.argv[1] + result = subprocess.run( + ["readelf", "--version-info", "--wide", binary], + check=True, + capture_output=True, + text=True, + env={**os.environ, "LC_ALL": "C"}, + ) + needs = result.stdout.partition("Version needs section")[2] + symbols = re.findall(r"\bName:\s+GLIBC_([0-9]+(?:\.[0-9]+)+)", needs) + if not symbols: + raise SystemExit(f"{binary}: no GLIBC version needs found") + + def version_key(value): + parts = tuple(int(part) for part in value.split(".")) + return parts + (0,) * max(0, 3 - len(parts)) + + print(max(symbols, key=version_key)) + PY + )" + + mkdir -p "${PKG_DIR}/DEBIAN" + mkdir -p "${PKG_DIR}/usr/bin" + mkdir -p "${PKG_DIR}/etc/default" + mkdir -p "${PKG_DIR}/lib/systemd/system" + mkdir -p "${PKG_DIR}/usr/share/doc/rustfs" + + cp "${BIN}" "${PKG_DIR}/usr/bin/rustfs" + chmod 755 "${PKG_DIR}/usr/bin/rustfs" + cp deploy/build/rustfs.service "${PKG_DIR}/lib/systemd/system/" + + cat > "${PKG_DIR}/etc/default/rustfs" << 'ENVEOF' + # RustFS Environment Configuration + # See https://docs.rustfs.com for more information + # RUSTFS_ACCESS_KEY= + # RUSTFS_SECRET_KEY= + # RUSTFS_VOLUMES="" + # RUSTFS_ADDRESS=":9000" + # RUSTFS_CONSOLE_ADDRESS=":9001" + # RUSTFS_CONSOLE_ENABLE=true + # RUSTFS_OBS_LOGGER_LEVEL=error + # RUSTFS_OBS_LOG_DIRECTORY="/var/log/rustfs/" + ENVEOF + + # dpkg versions must start with a digit and cannot contain hyphens; + # a date-based snapshot version keeps the nightly installable + # alongside release packages. The ~nightly.rdma suffix stays distinct + # from the GNU nightly's ~nightly version. + DEB_VERSION="${DEB_DATE//-/.}~nightly.rdma" + + cat > "${PKG_DIR}/DEBIAN/control" << EOF + Package: rustfs + Version: ${DEB_VERSION} + Section: utils + Priority: optional + Architecture: amd64 + Depends: libc6 (>= ${GLIBC_MIN}) + Maintainer: RustFS Team + Description: High-performance distributed object storage (RDMA/NIXL nightly) + RustFS is a high-performance distributed object storage software + built using Rust with the nixl feature. It is compatible with the + MinIO and S3 API. This package is linked against the RDMA runner's + native libraries. + Homepage: https://rustfs.com + EOF + + cat > "${PKG_DIR}/DEBIAN/conffiles" << 'CONFFILES' + /etc/default/rustfs + CONFFILES + + ./scripts/release/package_service_scripts.sh after-install > "${PKG_DIR}/DEBIAN/postinst" + chmod 755 "${PKG_DIR}/DEBIAN/postinst" + + ./scripts/release/package_service_scripts.sh before-remove > "${PKG_DIR}/DEBIAN/prerm" + chmod 755 "${PKG_DIR}/DEBIAN/prerm" + + ./scripts/release/package_service_scripts.sh after-remove > "${PKG_DIR}/DEBIAN/postrm" + chmod 755 "${PKG_DIR}/DEBIAN/postrm" + + cp LICENSE "${PKG_DIR}/usr/share/doc/rustfs/" + cp README.md "${PKG_DIR}/usr/share/doc/rustfs/" + + test -s "${PKG_DIR}/usr/bin/rustfs" + test -s "${PKG_DIR}/lib/systemd/system/rustfs.service" + test -s "${PKG_DIR}/etc/default/rustfs" + test -s "${PKG_DIR}/DEBIAN/postinst" + test -s "${PKG_DIR}/DEBIAN/prerm" + test -s "${PKG_DIR}/DEBIAN/postrm" + test -s "${PKG_DIR}/usr/share/doc/rustfs/LICENSE" + test -s "${PKG_DIR}/usr/share/doc/rustfs/README.md" + + fakeroot dpkg-deb --build "${PKG_DIR}" + test "$(dpkg-deb -f "${DEB_FILE}" Package)" = "rustfs" + test "$(dpkg-deb -f "${DEB_FILE}" Version)" = "${DEB_VERSION}" + cp -a "${DEB_FILE}" "${LATEST_FILE}" + cmp -s "${DEB_FILE}" "${LATEST_FILE}" + ls -lh "${DEB_FILE}" "${LATEST_FILE}" + echo "deb_date=${DEB_DATE}" >> "${GITHUB_OUTPUT}" + echo "deb_file=${DEB_FILE}" >> "${GITHUB_OUTPUT}" + + - name: Upload DEB artifact + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: rustfs-nightly-rdma-latest.deb + path: rustfs-nightly-rdma-latest.deb + if-no-files-found: error + + # Dated package plus the rolling alias, on the same nightly prefix as + # nightly-gnu.yml. Names are rustfs-nightly-rdma-* so this upload does + # not replace rustfs-nightly-latest.deb. Skipped when the R2 secrets + # are not configured (artifact-only mode). No immutable candidate and + # no nightly-candidate-ready dispatch. + - name: Upload DEB to Cloudflare R2 + env: + DEB_FILE: ${{ steps.deb.outputs.deb_file }} + LATEST_FILE: rustfs-nightly-rdma-latest.deb + R2_ACCESS_KEY_ID: ${{ secrets.R2_ACCESS_KEY_ID }} + R2_SECRET_ACCESS_KEY: ${{ secrets.R2_SECRET_ACCESS_KEY }} + R2_ENDPOINT: ${{ secrets.R2_ENDPOINT }} + R2_BUCKET: ${{ secrets.R2_BUCKET }} + AWS_EC2_METADATA_DISABLED: true + shell: bash + run: | + set -euo pipefail + + if [[ -z "${R2_ACCESS_KEY_ID}" || -z "${R2_SECRET_ACCESS_KEY}" || -z "${R2_ENDPOINT}" || -z "${R2_BUCKET}" ]]; then + echo "⚠️ R2 credentials missing, skipping upload" + exit 0 + fi + + export AWS_ACCESS_KEY_ID="${R2_ACCESS_KEY_ID}" + export AWS_SECRET_ACCESS_KEY="${R2_SECRET_ACCESS_KEY}" + export AWS_DEFAULT_REGION="auto" + + if ! command -v aws >/dev/null 2>&1; then + echo "aws CLI not found on runner; installing" + aws_arch="$(uname -m)" + case "${aws_arch}" in + x86_64) aws_arch="x86_64" ;; + aarch64|arm64) aws_arch="aarch64" ;; + *) + echo "Unsupported Linux architecture for AWS CLI: ${aws_arch}" >&2 + exit 1 + ;; + esac + aws_install_root="${RUNNER_TEMP}/aws-cli" + rm -rf "${aws_install_root}" + mkdir -p "${aws_install_root}" + curl --fail --location --retry 3 \ + "https://awscli.amazonaws.com/awscli-exe-linux-${aws_arch}.zip" \ + --output "${aws_install_root}/awscliv2.zip" + unzip -q "${aws_install_root}/awscliv2.zip" -d "${aws_install_root}" + "${aws_install_root}/aws/install" \ + --install-dir "${aws_install_root}/aws-cli" \ + --bin-dir "${aws_install_root}/bin" + export PATH="${aws_install_root}/bin:${PATH}" + fi + aws --version + + R2_PREFIX="s3://${R2_BUCKET}/artifacts/rustfs/packages/nightly/" + echo "Uploading ${DEB_FILE} and ${LATEST_FILE} to ${R2_PREFIX}" + aws s3 cp "${DEB_FILE}" "${R2_PREFIX}" --endpoint-url "${R2_ENDPOINT}" --only-show-errors + aws s3 cp "${LATEST_FILE}" "${R2_PREFIX}" --endpoint-url "${R2_ENDPOINT}" --only-show-errors + echo "R2 upload complete" + + # Add rustfs-nightly-rdma-latest.deb to the rolling `nightly` release + # on rustfs/auto-testing, the same tag nightly-gnu.yml publishes to. + # Only that asset is replaced. rustfs-nightly-latest.deb, + # rustfs-nightly-latest.rpm, and the release body written by + # scripts/release/publish_nightly_assets.sh are left untouched. + # The release is created only when the tag does not exist yet. + # Skipped when PF_TESTING_GH_TOKEN is not configured. + # Does not dispatch nightly-candidate-ready. + - name: Publish RDMA package to the auto-testing nightly release + env: + ASSETS_TOKEN: ${{ secrets.PF_TESTING_GH_TOKEN }} + DEB_FILE: rustfs-nightly-rdma-latest.deb + DEB_DATE: ${{ steps.deb.outputs.deb_date }} + shell: bash + run: | + set -euo pipefail + + if [[ -z "${ASSETS_TOKEN}" ]]; then + echo "PF_TESTING_GH_TOKEN is missing, skipping nightly release asset publish" + exit 0 + fi + + : "${DEB_FILE:?DEB_FILE is required}" + : "${DEB_DATE:?DEB_DATE is required}" + [[ -f "${DEB_FILE}" ]] || { echo "missing package: ${DEB_FILE}" >&2; exit 1; } + [[ "${DEB_DATE}" =~ ^[0-9]{4}-[0-9]{2}-[0-9]{2}$ ]] + + API="https://api.github.com/repos/rustfs/auto-testing" + UPLOADS="https://uploads.github.com/repos/rustfs/auto-testing/releases" + AUTH="Authorization: token ${ASSETS_TOKEN}" + RELEASE_TAG="nightly" + ASSET_NAME="rustfs-nightly-rdma-latest.deb" + + release_id="$(curl -fsS --retry 3 -H "${AUTH}" "${API}/releases/tags/${RELEASE_TAG}" \ + | python3 -c 'import json,sys; print(json.load(sys.stdin).get("id", ""))' 2>/dev/null || true)" + if [[ -z "${release_id}" ]]; then + echo "creating the rolling nightly release" + release_id="$(curl -fsS --retry 3 -X POST -H "${AUTH}" -H "Content-Type: application/json" \ + -d '{"tag_name":"nightly","name":"Nightly builds","body":"Rolling nightly builds. Assets are replaced on every build; the release body documents the provenance of the current files."}' \ + "${API}/releases" | python3 -c 'import json,sys; print(json.load(sys.stdin)["id"])')" + fi + [[ -n "${release_id}" ]] || { echo "could not resolve the nightly release id" >&2; exit 1; } + + asset_id="$(curl -fsS --retry 3 -H "${AUTH}" "${API}/releases/tags/${RELEASE_TAG}" \ + | ASSET_NAME="${ASSET_NAME}" python3 -c ' + import json, os, sys + release = json.load(sys.stdin) + asset_name = os.environ["ASSET_NAME"] + protected = {"rustfs-nightly-latest.deb", "rustfs-nightly-latest.rpm"} + if asset_name in protected: + raise SystemExit("refusing to replace a GNU nightly asset") + print(next((asset["id"] for asset in release.get("assets", []) if asset["name"] == asset_name), "")) + ')" + if [[ -n "${asset_id}" ]]; then + curl -fsS --retry 3 -X DELETE -H "${AUTH}" "${API}/releases/assets/${asset_id}" >/dev/null + fi + curl -fsS --retry 3 --max-time 900 -X POST \ + -H "${AUTH}" \ + -H "Content-Type: application/octet-stream" \ + --data-binary "@${DEB_FILE}" \ + "${UPLOADS}/${release_id}/assets?name=${ASSET_NAME}" >/dev/null + echo "published ${ASSET_NAME} to the rustfs/auto-testing nightly release without changing its body" + + alert-on-failure: + name: Alert on scheduled failure + needs: [resolve-source, build] + if: >- + github.repository == 'rustfs/rustfs' && ( + always() && github.event_name == 'schedule' && + (contains(needs.*.result, 'failure') || contains(needs.*.result, 'cancelled')) + ) + runs-on: ubuntu-latest + timeout-minutes: 10 + permissions: + contents: read + issues: write + steps: + - uses: actions/checkout@f548e57e544e1ff5a4c46bf1e1b8685f8e4a348a # v7 + with: + persist-credentials: false + - name: Open or update failure-tracking issue + uses: ./.github/actions/schedule-failure-issue + with: + github-token: ${{ secrets.BACKLOG_ISSUE_TOKEN }} diff --git a/Cargo.toml b/Cargo.toml index d0446f68a4..0b748618f8 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -125,7 +125,7 @@ rustfs-iam = { path = "crates/iam", version = "1.0.8" } rustfs-keystone = { path = "crates/keystone", version = "1.0.8" } rustfs-license = { path = "crates/license", version = "1.0.8" } rustfs-lifecycle = { path = "crates/lifecycle", version = "1.0.8" } -rustfs-kms = { path = "crates/kms", version = "1.0.8" } +rustfs-kms = { path = "crates/kms", version = "1.0.8", default-features = false } rustfs-lock = { path = "crates/lock", version = "1.0.8" } rustfs-madmin = { path = "crates/madmin", version = "1.0.8" } rustfs-notify = { path = "crates/notify", version = "1.0.8" } @@ -144,7 +144,7 @@ rustfs-rio-v2 = { path = "crates/rio-v2", version = "1.0.8" } rustfs-s3-client = { path = "crates/s3-client", version = "1.0.8" } rustfs-s3-types = { path = "crates/s3-types", version = "1.0.8" } rustfs-s3-ops = { path = "crates/s3-ops", version = "1.0.8" } -rustfs-s3select-api = { path = "crates/s3select-api", version = "1.0.8" } +rustfs-s3select-api = { path = "crates/s3select-api", version = "1.0.8", default-features = false } rustfs-s3select-query = { path = "crates/s3select-query", version = "1.0.8" } rustfs-scanner = { path = "crates/scanner", version = "1.0.8" } rustfs-security-governance = { path = "crates/security-governance", version = "1.0.8" } diff --git a/crates/e2e_test/src/multipart_storage_class_test.rs b/crates/e2e_test/src/multipart_storage_class_test.rs index 413bfc394a..4c56adfca9 100644 --- a/crates/e2e_test/src/multipart_storage_class_test.rs +++ b/crates/e2e_test/src/multipart_storage_class_test.rs @@ -226,6 +226,18 @@ mod tests { .await?; let resumed_client = env.create_s3_client(); + let pending = resumed_client + .list_multipart_uploads() + .bucket(bucket) + .prefix(&key) + .send() + .await?; + let upload = pending + .uploads() + .iter() + .find(|upload| upload.key() == Some(key.as_str()) && upload.upload_id() == Some(upload_id)) + .ok_or("ListMultipartUploads omitted the pending upload")?; + assert_eq!(upload.storage_class().map(StorageClass::as_str), Some(class_name)); let before_retry = resumed_client .list_parts() .bucket(bucket) diff --git a/crates/ecstore/src/disk/os.rs b/crates/ecstore/src/disk/os.rs index c0c7d944d2..66b97c8aa4 100644 --- a/crates/ecstore/src/disk/os.rs +++ b/crates/ecstore/src/disk/os.rs @@ -2728,18 +2728,25 @@ const DEFAULT_FSYNC_WORKER_IDLE_SPIN_ITERS: usize = 256; const MAX_FSYNC_WORKER_IDLE_SPIN_ITERS: usize = 1024; const FALLBACK_NAMESPACE_QUEUE_SHARDS: usize = 8; +const ENV_FSYNC_WORKERS_PER_DISK: &str = "RUSTFS_EXPERIMENTAL_FSYNC_WORKERS_PER_DISK"; const ENV_FSYNC_WORKER_IDLE_SPIN_ITERS: &str = "RUSTFS_EXPERIMENTAL_FSYNC_WORKER_IDLE_SPIN_ITERS"; const ENV_FSYNC_WORKER_KEEP_MULTIPLE_IDLE: &str = "RUSTFS_EXPERIMENTAL_FSYNC_WORKER_KEEP_MULTIPLE_IDLE"; #[derive(Clone, Copy, Debug, PartialEq, Eq)] -struct FsyncWorkerIdlePolicy { +struct FsyncWorkerPolicy { + max_workers: usize, spin_iters: usize, keep_multiple_idle: bool, } -impl FsyncWorkerIdlePolicy { +impl FsyncWorkerPolicy { fn from_env() -> Self { + let max_workers = match rustfs_utils::get_env_usize(ENV_FSYNC_WORKERS_PER_DISK, MAX_FSYNC_WORKERS_PER_DISK) { + 4 => 4, + _ => MAX_FSYNC_WORKERS_PER_DISK, + }; Self { + max_workers, spin_iters: rustfs_utils::get_env_usize(ENV_FSYNC_WORKER_IDLE_SPIN_ITERS, DEFAULT_FSYNC_WORKER_IDLE_SPIN_ITERS) .min(MAX_FSYNC_WORKER_IDLE_SPIN_ITERS), keep_multiple_idle: rustfs_utils::get_env_bool(ENV_FSYNC_WORKER_KEEP_MULTIPLE_IDLE, true), @@ -2748,7 +2755,7 @@ impl FsyncWorkerIdlePolicy { } // Resolve once so each queue uses one policy throughout worker retirement and respawn. -static FSYNC_WORKER_IDLE_POLICY: LazyLock = LazyLock::new(FsyncWorkerIdlePolicy::from_env); +static FSYNC_WORKER_POLICY: LazyLock = LazyLock::new(FsyncWorkerPolicy::from_env); #[derive(Clone, Copy, PartialEq, Eq)] enum DiskBlockingLane { @@ -2788,7 +2795,7 @@ struct DiskBlockingQueueLane { pub(crate) struct DiskBlockingQueue { lanes: [DiskBlockingQueueLane; 3], - fsync_idle_policy: FsyncWorkerIdlePolicy, + fsync_worker_policy: FsyncWorkerPolicy, #[cfg(test)] before_idle_spin: Mutex>>, } @@ -2857,13 +2864,13 @@ impl Drop for DiskBlockingWorkerGuard { impl DiskBlockingQueue { fn new() -> Arc { - Self::with_fsync_idle_policy(*FSYNC_WORKER_IDLE_POLICY) + Self::with_fsync_worker_policy(*FSYNC_WORKER_POLICY) } - fn with_fsync_idle_policy(fsync_idle_policy: FsyncWorkerIdlePolicy) -> Arc { + fn with_fsync_worker_policy(fsync_worker_policy: FsyncWorkerPolicy) -> Arc { Arc::new(Self { lanes: std::array::from_fn(|_| DiskBlockingQueueLane::default()), - fsync_idle_policy, + fsync_worker_policy, #[cfg(test)] before_idle_spin: Mutex::new(None), }) @@ -2878,7 +2885,7 @@ impl DiskBlockingQueue { fn lane_max_workers(&self, lane: DiskBlockingLane) -> usize { match lane { DiskBlockingLane::Foreground | DiskBlockingLane::Isolated => MAX_NAMESPACE_WORKERS_PER_DISK, - DiskBlockingLane::Fsync => MAX_FSYNC_WORKERS_PER_DISK, + DiskBlockingLane::Fsync => self.fsync_worker_policy.max_workers, } } @@ -2985,7 +2992,7 @@ impl DiskBlockingQueue { .ready .store(!state.jobs.is_empty(), std::sync::atomic::Ordering::Relaxed); if job.is_none() { - if (lane != DiskBlockingLane::Fsync || !queue.fsync_idle_policy.keep_multiple_idle) + if (lane != DiskBlockingLane::Fsync || !queue.fsync_worker_policy.keep_multiple_idle) && state.idle_workers > 0 { state.active_workers = state.active_workers.saturating_sub(1); @@ -3013,7 +3020,7 @@ impl DiskBlockingQueue { } } let spin_iters = if lane == DiskBlockingLane::Fsync { - queue.fsync_idle_policy.spin_iters + queue.fsync_worker_policy.spin_iters } else { WORKER_IDLE_SPIN_ITERS }; @@ -14329,9 +14336,10 @@ mod tests { assert_eq!(completed, 257, "yielding must not discard hot-disk jobs"); } - fn fsync_idle_test_policies() -> impl Iterator { + fn fsync_idle_test_policies() -> impl Iterator { [0, 256, 1024].into_iter().flat_map(|spin_iters| { - [false, true].map(|keep_multiple_idle| FsyncWorkerIdlePolicy { + [false, true].map(|keep_multiple_idle| FsyncWorkerPolicy { + max_workers: MAX_FSYNC_WORKERS_PER_DISK, spin_iters, keep_multiple_idle, }) @@ -14352,13 +14360,15 @@ mod tests { ] { temp_env::with_vars( [ + (ENV_FSYNC_WORKERS_PER_DISK, None), (ENV_FSYNC_WORKER_IDLE_SPIN_ITERS, spin_value), (ENV_FSYNC_WORKER_KEEP_MULTIPLE_IDLE, multiple_value), ], || { assert_eq!( - FsyncWorkerIdlePolicy::from_env(), - FsyncWorkerIdlePolicy { + FsyncWorkerPolicy::from_env(), + FsyncWorkerPolicy { + max_workers: MAX_FSYNC_WORKERS_PER_DISK, spin_iters: expected_spins, keep_multiple_idle: expected_multiple, }, @@ -14369,12 +14379,31 @@ mod tests { } } + #[test] + fn disk_blocking_queue_fsync_worker_limit_accepts_only_experiment_values() { + for (input, expected) in [ + (None, 8), + (Some("4"), 4), + (Some("8"), 8), + (Some("0"), 8), + (Some("16"), 8), + (Some("invalid"), 8), + ] { + temp_env::with_var(ENV_FSYNC_WORKERS_PER_DISK, input, || { + let queue = DiskBlockingQueue::with_fsync_worker_policy(FsyncWorkerPolicy::from_env()); + assert_eq!(queue.lane_max_workers(DiskBlockingLane::Fsync), expected, "input={input:?}"); + assert_eq!(queue.lane_max_workers(DiskBlockingLane::Foreground), MAX_NAMESPACE_WORKERS_PER_DISK); + assert_eq!(queue.lane_max_workers(DiskBlockingLane::Isolated), MAX_NAMESPACE_WORKERS_PER_DISK); + }); + } + } + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn disk_blocking_queue_drains_bursts_across_worker_retirement() { use std::sync::atomic::{AtomicUsize, Ordering}; for policy in fsync_idle_test_policies() { for lane in [DiskBlockingLane::Foreground, DiskBlockingLane::Fsync] { - let queue = DiskBlockingQueue::with_fsync_idle_policy(policy); + let queue = DiskBlockingQueue::with_fsync_worker_policy(policy); let completed = Arc::new(AtomicUsize::new(0)); for _ in 0..8 { let mut producers = tokio::task::JoinSet::new(); @@ -14499,7 +14528,8 @@ mod tests { for keep_multiple_idle in [false, true] { tokio::time::timeout(Duration::from_secs(5), async { - let queue = DiskBlockingQueue::with_fsync_idle_policy(FsyncWorkerIdlePolicy { + let queue = DiskBlockingQueue::with_fsync_worker_policy(FsyncWorkerPolicy { + max_workers: MAX_FSYNC_WORKERS_PER_DISK, spin_iters: 256, keep_multiple_idle, }); @@ -14621,8 +14651,14 @@ mod tests { async fn disk_blocking_queue_fsync_lane_scales_workers_and_retires_idle() { use std::sync::atomic::{AtomicUsize, Ordering}; - for policy in fsync_idle_test_policies() { - let queue = DiskBlockingQueue::with_fsync_idle_policy(policy); + for policy in fsync_idle_test_policies().flat_map(|idle_policy| { + [4, MAX_FSYNC_WORKERS_PER_DISK].map(|max_workers| FsyncWorkerPolicy { + max_workers, + ..idle_policy + }) + }) { + let max_workers = policy.max_workers; + let queue = DiskBlockingQueue::with_fsync_worker_policy(policy); let active = Arc::new(AtomicUsize::new(0)); let max_seen = Arc::new(AtomicUsize::new(0)); let entered = Arc::new(AtomicUsize::new(0)); @@ -14631,7 +14667,7 @@ mod tests { let (release_tx, _) = tokio::sync::broadcast::channel::<()>(1); let mut handles = Vec::new(); - for i in 0..(MAX_FSYNC_WORKERS_PER_DISK + 4) { + for i in 0..(max_workers + 4) { let q = Arc::clone(&queue); let active = Arc::clone(&active); let max_seen = Arc::clone(&max_seen); @@ -14648,12 +14684,12 @@ mod tests { let cur = active.fetch_add(1, Ordering::SeqCst) + 1; max_seen.fetch_max(cur, Ordering::SeqCst); let ord = entered.fetch_add(1, Ordering::SeqCst) + 1; - if ord == MAX_FSYNC_WORKERS_PER_DISK + if ord == max_workers && let Some(tx) = all_entered_tx.lock().expect("lock completion sender").take() { let _ = tx.send(()); } - if ord <= MAX_FSYNC_WORKERS_PER_DISK { + if ord <= max_workers { let _ = release_rx.blocking_recv(); } active.fetch_sub(1, Ordering::SeqCst); @@ -14668,13 +14704,27 @@ mod tests { .await .expect("all fsync workers should enter within timeout") .expect("all_entered channel"); + tokio::time::timeout(Duration::from_secs(5), async { + loop { + { + let state = queue.lane(DiskBlockingLane::Fsync).state.lock(); + assert_eq!(state.active_workers, max_workers); + if state.jobs.len() == 4 { + break; + } + } + tokio::task::yield_now().await; + } + }) + .await + .expect("all excess jobs must queue while the fsync workers are busy"); let _ = release_tx.send(()); for (i, handle) in handles.into_iter().enumerate() { assert_eq!(handle.await.expect("task join").expect("fsync job"), i); } assert_eq!( max_seen.load(Ordering::SeqCst), - MAX_FSYNC_WORKERS_PER_DISK, + max_workers, "fsync lane must run MAX_FSYNC_WORKERS_PER_DISK concurrent workers up to its configured bound" ); tokio::time::timeout(std::time::Duration::from_secs(5), async { diff --git a/crates/ecstore/src/set_disk/ops/multipart.rs b/crates/ecstore/src/set_disk/ops/multipart.rs index 06ea812ecf..8987565935 100644 --- a/crates/ecstore/src/set_disk/ops/multipart.rs +++ b/crates/ecstore/src/set_disk/ops/multipart.rs @@ -2819,7 +2819,7 @@ impl SetDisks { }; Ok(Some((file_info, object))) })(); - let (file_info, object) = match decoded { + let (mut file_info, object) = match decoded { Ok(Some(decoded)) => decoded, Ok(None) => return Ok(None), // Deterministic damage (undecodable metadata that still @@ -2856,7 +2856,11 @@ impl SetDisks { object, upload_id: runtime_sources::deployment_upload_id(raw_upload_id), initiated, - ..Default::default() + user_defined: file_info + .metadata + .remove_entry(metadata_keys::STORAGE_CLASS) + .into_iter() + .collect(), })) } }) diff --git a/crates/kms/src/backends/mod.rs b/crates/kms/src/backends/mod.rs index 8b811c11d4..163f23e659 100644 --- a/crates/kms/src/backends/mod.rs +++ b/crates/kms/src/backends/mod.rs @@ -294,6 +294,13 @@ pub(crate) fn list_keys_page_size(limit: Option) -> Option { } } +/// Drop directory entries (such as Vault KV2 version sub-paths `"my-key/"` or +/// Vault Transit BYOK `"import/"`) from a key listing; only real key records +/// may be listed. +pub(crate) fn filter_key_directory_entries(keys: Vec) -> Vec { + keys.into_iter().filter(|key| !key.ends_with('/')).collect() +} + /// The response to a request for zero keys. /// /// `truncated` is false even when keys exist: a zero-length page carries no diff --git a/crates/kms/src/backends/vault.rs b/crates/kms/src/backends/vault.rs index dd0449494a..72f3129a4c 100644 --- a/crates/kms/src/backends/vault.rs +++ b/crates/kms/src/backends/vault.rs @@ -423,15 +423,6 @@ enum CasMutation { Skip(T), } -/// Drop KV2 directory entries from a key listing. -/// -/// Once a key has version records, listing the key prefix returns both the key -/// record itself ("my-key") and a directory entry for its version sub-path -/// ("my-key/"); only the former is a key. -fn filter_key_directory_entries(keys: Vec) -> Vec { - keys.into_iter().filter(|key| !key.ends_with('/')).collect() -} - /// Resolve which master key version wrapped an envelope. /// /// `Some` versions are honored verbatim: if the record for that version is missing @@ -1122,7 +1113,7 @@ impl VaultKmsClient { match keys { Some(keys) => { - let keys = filter_key_directory_entries(keys); + let keys = crate::backends::filter_key_directory_entries(keys); debug!("Found {} keys in Vault", keys.len()); Ok(keys) } @@ -3170,7 +3161,10 @@ mod tests { // Listing the key prefix returns "my-key/" as a directory entry once // my-key has version records; only real key records may be listed. let listed = vec!["alpha".to_string(), "alpha/".to_string(), "beta".to_string()]; - assert_eq!(filter_key_directory_entries(listed), vec!["alpha".to_string(), "beta".to_string()]); + assert_eq!( + crate::backends::filter_key_directory_entries(listed), + vec!["alpha".to_string(), "beta".to_string()] + ); } #[test] diff --git a/crates/kms/src/backends/vault_transit.rs b/crates/kms/src/backends/vault_transit.rs index a11bd4fe77..99aa6ef5f8 100644 --- a/crates/kms/src/backends/vault_transit.rs +++ b/crates/kms/src/backends/vault_transit.rs @@ -22,8 +22,8 @@ use crate::backends::vault_credentials::{ use crate::backends::{ BackendCapabilities, ExpiredKeyRemoval, KmsBackend, ListedKeyFailure, StateGatedOperation, UnreadableKeys, classify_listed_key_failure, destruction_requires_pending_deletion, empty_key_page, ensure_key_state_permits, - ensure_rewrap_context_matches, ensure_tag_keys_are_mutable, list_keys_page_size, paginate_keys, started_at_the_first_key, - validate_key_id_segment, + ensure_rewrap_context_matches, ensure_tag_keys_are_mutable, filter_key_directory_entries, list_keys_page_size, paginate_keys, + started_at_the_first_key, validate_key_id_segment, }; use crate::config::{KmsConfig, VaultTransitConfig}; use crate::encryption::{DataKeyEnvelope, generate_key_material}; @@ -1418,7 +1418,7 @@ impl VaultTransitKmsClient { .run("vault_transit_list_keys", OpClass::ReadIdempotent, move || async move { let vault = self.vault().map_err(AttemptError::fatal)?; match key::list(&vault.client, &self.config.mount_path).await { - Ok(response) => Ok(response.keys), + Ok(response) => Ok(filter_key_directory_entries(response.keys)), // An empty transit engine answers LIST with a bare 404; // that is an empty listing, not a backend failure. Err(error) if is_empty_transit_list(&error) => Ok(Vec::new()), @@ -2416,6 +2416,43 @@ mod tests { assert_eq!(response.next_marker, None); } + /// Regression test for rustfs/rustfs#9846. + /// + /// Once BYOK key import is used on a Transit mount, Vault/OpenBao includes + /// the directory entry `"import/"` in `LIST /v1/transit/keys`. It is not a + /// key ID and must be filtered out before `key_info()` validates key names. + #[tokio::test] + async fn list_keys_ignores_byok_import_directory_entry() { + let metadata = TransitKeyMetadata::from_create_request(&CreateKeyRequest::default()); + let (vault, client) = scripted_client(vec![ + ScriptedResponse::ok(serde_json::json!({ + "keys": ["import/", "my-key"] + })), + ScriptedResponse::ok(transit_key_read_data("my-key")), + ScriptedResponse::ok(metadata_read_data(&metadata)), + ]) + .await; + + let response = client + .list_keys(&ListKeysRequest::default(), None) + .await + .expect("directory entries like import/ must be ignored when listing transit keys"); + assert_eq!(response.keys.len(), 1); + assert_eq!(response.keys[0].key_id, "my-key"); + assert!(response.unreadable_key_ids.is_empty()); + assert!(!response.truncated); + + let requests = vault.requests(); + assert_eq!( + requests, + vec![ + "LIST /v1/transit/keys".to_string(), + "GET /v1/transit/keys/my-key".to_string(), + "GET /v1/secret/data/rustfs/kms/transit-metadata/my-key".to_string(), + ] + ); + } + fn test_vault_transit_config() -> VaultTransitConfig { VaultTransitConfig { address: "http://127.0.0.1:8200".to_string(), diff --git a/crates/protocols/Cargo.toml b/crates/protocols/Cargo.toml index f8cff5c432..963a27e00f 100644 --- a/crates/protocols/Cargo.toml +++ b/crates/protocols/Cargo.toml @@ -152,7 +152,7 @@ rustls = { workspace = true, default-features = false, optional = true, features # Swift specific dependencies (optional) rustfs-keystone = { workspace = true, optional = true } rustfs-ecstore = { workspace = true, optional = true } -rustfs-kms = { workspace = true, optional = true } +rustfs-kms = { workspace = true, default-features = true, optional = true } rustfs-gateway-types = { workspace = true } rustfs-rio = { workspace = true, optional = true } rustfs-sse = { workspace = true, optional = true } diff --git a/crates/scanner/src/scanner_folder/tests/fair_prefix_quantum.rs b/crates/scanner/src/scanner_folder/tests/fair_prefix_quantum.rs index a03cc34499..7aa0d42cb6 100644 --- a/crates/scanner/src/scanner_folder/tests/fair_prefix_quantum.rs +++ b/crates/scanner/src/scanner_folder/tests/fair_prefix_quantum.rs @@ -673,12 +673,14 @@ async fn cold_linked_prefixes_resume_their_own_replica_coverage() { max_objects: Some(6), ..Default::default() }; + let tier_registry_generation = crate::runtime_tier_registry_for_cycle(1, 0).await.generation; // Six turns per disk leave one final B quantum. Each cold process must // recover that disk's linked tree as well as its complete child coverage. for round in 0..(2 * 40_usize.div_ceil(6) + 1) { let (root, peer) = if round < 12 && round % 2 == 0 { (&a, &b) } else { (&b, &a) }; let identity = crate::DataUsageScanIdentity { publication_epoch: u64::try_from(round).expect("bounded round") + 10, + tier_registry_generation, ..cache.info.scan_identity.expect("retained bucket identity") }; cache.prepare_bucket_checkpoint( diff --git a/crates/scanner/src/scanner_io/tests/service_cohort.rs b/crates/scanner/src/scanner_io/tests/service_cohort.rs index 15cdb37eab..edb3db418a 100644 --- a/crates/scanner/src/scanner_io/tests/service_cohort.rs +++ b/crates/scanner/src/scanner_io/tests/service_cohort.rs @@ -48,6 +48,10 @@ async fn create_cohort_bucket_objects(store: &ECStore, bucket: &str, objects: us .make_bucket(bucket, &MakeBucketOptions::default()) .await .expect("fixture bucket"); + write_cohort_bucket_objects(store, bucket, objects).await; +} + +async fn write_cohort_bucket_objects(store: &ECStore, bucket: &str, objects: usize) { for set in store.all_set_disks() { for index in 0..objects { let object = format!("object-{index:04}"); @@ -196,8 +200,11 @@ async fn service_cohort_production_dispatch_services_waiters_across_sources_case "ongoing dirty/new bootstrap must not displace the original cohort" ); - // Admission fairness is not completed coverage: the changed hot bucket - // produces a complete observation while its primary remains uncertified. + // Admission fairness is not completed coverage: once the hot bucket + // mutates under an active producer usage watch, cycle 5 produces a + // complete observation while its primary remains uncertified. + write_cohort_bucket_objects(&store, &hot, 1).await; + record_dirty_usage_bucket(&hot); let ctx = CancellationToken::new(); let (result, usage) = run_cohort_cycle(&store, cohort, 5, ScannerCycleBudget::new(&ctx, ScannerCycleBudgetConfig::default())).await; diff --git a/docs/operations/object-io-tuning-ab-matrix.md b/docs/operations/object-io-tuning-ab-matrix.md index 5e06dc309c..ff09f1c31f 100644 --- a/docs/operations/object-io-tuning-ab-matrix.md +++ b/docs/operations/object-io-tuning-ab-matrix.md @@ -76,6 +76,12 @@ iostat -xz 5 > telemetry/iostat.txt & | `RUSTFS_DURABILITY_MODE` / `RUSTFS_DRIVE_SYNC_ENABLE` | mode-dependent | Per-shard fsync/sync discipline on commit | `set_disk_rename` P99 | Weakening it changes the durability contract — a deliberate tradeoff, never a free win | | `RUSTFS_RUNTIME_WORKER_THREADS` / `RUSTFS_RUNTIME_MAX_BLOCKING_THREADS` | Tokio defaults | Async workers + `spawn_blocking` pool feeding per-block encode | `set_disk_encode` P95 + mpstat | Oversubscription | +#### Per-disk fsync worker concurrency experiment + +Use `RUSTFS_EXPERIMENTAL_FSYNC_WORKERS_PER_DISK` to compare a cap of `4` active workers with the default `8` on the foreground Fsync lane of each disk. An unset value or a value other than `4` or `8` selects `8`. The process reads it at first queue creation. Restart every participating server per leg with the same binary, using `8` for A1/A2 and `4` for B1/B2. + +Qualify the same-build A/A baseline before comparing the caps. Keep the effective bucket mode at `strict`, the offered workload and idle policy fixed, and record the start-of-round disk state. Compare throughput, PUT p99/p99.9, and the worker dispatch and execution stages. A lower cap can move time from filesystem waits into the worker queue, so use end-to-end PUT latency to evaluate it. The namespace and isolated lanes use their own worker policies. + #### Fsync worker idle policy experiment The disk fsync queue exposes two independent experimental controls for measuring idle CPU cost. Both are cached at first queue creation and require restarting every participating server when changed. The default spin budget is 256 iterations per empty-queue episode, with multiple idle workers allowed. @@ -85,7 +91,7 @@ The disk fsync queue exposes two independent experimental controls for measuring | `RUSTFS_EXPERIMENTAL_FSYNC_WORKER_IDLE_SPIN_ITERS` | `256` | Spin budget per empty-queue episode, clamped to `0..=1024`. `0` immediately rechecks retirement under the queue mutex. Invalid values use the default. Set `1024` to restore the longer spin budget. | | `RUSTFS_EXPERIMENTAL_FSYNC_WORKER_KEEP_MULTIPLE_IDLE` | `true` | `false` retires an empty fsync worker when another idle/reserved worker already exists. Invalid values use the default. | -These controls affect the foreground fsync lane's idle policy. Its maximum execution concurrency remains eight workers per disk, and the namespace and isolated cleanup lanes retain their own policy. The queue's internal idle count includes worker reservations awaiting execution, so measure actual worker and spin activity through the diagnostics below. +These controls affect the foreground fsync lane's idle policy. Keep its worker cap at eight per disk for the idle policy experiment. The queue's internal idle count includes worker reservations awaiting execution, so measure actual worker and spin activity through the diagnostics below. Use one fixed binary and the four cells below to distinguish the two factors and their interaction. Keep effective bucket durability at `strict`, and record inline admission, versioning, EC layout, CPU quota, storage mapping, background activity and build identity for each run. A historical release comparison also requires fixing that release's source and build inputs. diff --git a/docs/testing/ci-gates.md b/docs/testing/ci-gates.md index 9582718eaa..2da638bc0f 100644 --- a/docs/testing/ci-gates.md +++ b/docs/testing/ci-gates.md @@ -97,6 +97,7 @@ Scheduled lanes never block a PR. Their workflow-local gate fails the run. The v | `minio-interop.yml` (nightly) | `minio-interop` | EC + SSE read-parity gate | yes, with `never_ran_grace_until` | pinned Docker fixture steps in the workflow | | `on-demand-migration-interop.yml` (nightly) | `minio-source`, `cloud-source` (`aws`, `r2`, `gcs`) | report-only provider interop; one JSON report per provider naming cases, timings and source request counts, plus JUnit and MinIO logs. A cloud provider whose `ODM_INTEROP_*` secrets are absent is skipped with a summary note, not failed | yes | start the pinned MinIO container as in the job, export the `RUSTFS_ODM_INTEROP_*` variables, run `python3 scripts/e2e_binary.py build --bins`, then `python3 scripts/e2e_binary.py run -- cargo nextest run --profile e2e-odm-interop -p e2e_test` | | `nightly-gnu.yml` (nightly) | `build`, `kms-vault-lane`, `kms-vault-ha-failover` | build, live Vault, and HA failover gates | yes | commands and pinned Vault images in the workflow | +| `nightly-rdma.yml` (nightly) | `resolve-source`, `build` | native NIXL release package `rustfs-nightly-rdma-latest.deb` on the `rdma` runner; does not dispatch the functional chain | yes | commands in the workflow; requires the `rdma` runner and native NIXL libraries | | `audit.yml` (nightly) | `cargo-deny`, `workflow-pin-report` | dependency and workflow-pin gates | yes | `cargo deny check`; `scripts/security/check_workflow_pins.sh` | | `mint.yml` (nightly) | `image`, `mint` (`legacy` pinned reference and `gateway` candidate), `compare` | fail-closed dual-stack diff-table gate (`scripts/mint_stack_diff.py`): requires verified distinct binary provenance and an empty `(sdk, test, legacy, gateway)` diff table across both Mint `log.json` reports; uploads per-leg logs and `diff.md`/`diff.json` | yes | pinned Docker sequence per leg in the workflow, then `python3 scripts/mint_stack_diff.py --require-meta` | | `coverage.yml` (weekly) | `coverage` | report-only trend; lcov and JSON artifact | yes (disabled) | `make coverage` | diff --git a/rustfs/Cargo.toml b/rustfs/Cargo.toml index dc917ec225..4b387ad35a 100644 --- a/rustfs/Cargo.toml +++ b/rustfs/Cargo.toml @@ -272,7 +272,7 @@ rustfs-filemeta.workspace = true rustfs-iam = { workspace = true } rustfs-keystone = { workspace = true } rustfs-license = { workspace = true } -rustfs-kms = { workspace = true } +rustfs-kms = { workspace = true, default-features = true } rustfs-lock.workspace = true rustfs-log-analyzer = { workspace = true } rustfs-madmin = { workspace = true } @@ -296,7 +296,7 @@ rustfs-s3-ops = { workspace = true } rustfs-sse = { workspace = true } rustfs-security-governance = { workspace = true } rustfs-data-usage = { workspace = true } -rustfs-s3select-api = { workspace = true } +rustfs-s3select-api = { workspace = true, default-features = true } rustfs-s3select-query = { workspace = true } rustfs-extension-schema = { workspace = true } rustfs-targets = { workspace = true } diff --git a/rustfs/src/admin/handlers/table_catalog/mod.rs b/rustfs/src/admin/handlers/table_catalog/mod.rs index 2f73e168d0..df8ab293f6 100644 --- a/rustfs/src/admin/handlers/table_catalog/mod.rs +++ b/rustfs/src/admin/handlers/table_catalog/mod.rs @@ -4382,7 +4382,11 @@ fn apply_table_updates_at( let mut last_added_schema_id = None; let mut last_added_spec_id = None; let mut last_added_sort_order_id = None; - let mut added_snapshot_ids = BTreeSet::new(); + let mut snapshot_roots = if updates.iter().any(|update| update["action"] == "set-snapshot-ref") { + SnapshotCommitRoots::new(&metadata) + } else { + SnapshotCommitRoots::default() + }; for update in updates { let action = update @@ -4416,13 +4420,14 @@ fn apply_table_updates_at( apply_set_default_sort_order_update(&mut metadata, update, last_added_sort_order_id)?; } "add-snapshot" => { - added_snapshot_ids.insert(apply_add_snapshot_update(&mut metadata, update)?); + let id = apply_add_snapshot_update(&mut metadata, update)?; + snapshot_roots.add(id, &update["snapshot"]); } "set-snapshot-ref" => { - apply_set_snapshot_ref_update(&mut metadata, update, &added_snapshot_ids, commit_timestamp_ms)?; + apply_set_snapshot_ref_update(&mut metadata, update, &mut snapshot_roots, commit_timestamp_ms)?; } "remove-snapshots" => apply_remove_snapshots_update(&mut metadata, update)?, - "remove-snapshot-ref" => apply_remove_snapshot_ref_update(&mut metadata, update)?, + "remove-snapshot-ref" => apply_remove_snapshot_ref_update(&mut metadata, update, &mut snapshot_roots)?, "set-location" => apply_set_location_update(&mut metadata, update)?, "set-properties" => apply_set_properties_update(&mut metadata, update)?, "remove-properties" => apply_remove_properties_update(&mut metadata, update)?, @@ -4463,7 +4468,7 @@ fn apply_table_updates_at( } } - prune_intermediate_snapshot_log_entries(&mut metadata, &added_snapshot_ids)?; + prune_intermediate_snapshot_log_entries(&mut metadata, &snapshot_roots.added)?; if metadata.get("format-version").is_some() { crate::table_catalog::synchronize_table_metadata_version_fields(&mut metadata).map_err(catalog_store_error)?; @@ -4481,8 +4486,8 @@ fn apply_table_updates_at( Ok(metadata) } -fn prune_intermediate_snapshot_log_entries(metadata: &mut serde_json::Value, added_snapshot_ids: &BTreeSet) -> S3Result<()> { - if added_snapshot_ids.is_empty() { +fn prune_intermediate_snapshot_log_entries(metadata: &mut serde_json::Value, added: &BTreeSet) -> S3Result<()> { + if added.is_empty() { return Ok(()); } let current_snapshot_id = metadata.get("current-snapshot-id").and_then(serde_json::Value::as_i64); @@ -4497,7 +4502,7 @@ fn prune_intermediate_snapshot_log_entries(metadata: &mut serde_json::Value, add entry .get("snapshot-id") .and_then(serde_json::Value::as_i64) - .is_none_or(|snapshot_id| !added_snapshot_ids.contains(&snapshot_id) || Some(snapshot_id) == current_snapshot_id) + .is_none_or(|snapshot_id| !added.contains(&snapshot_id) || Some(snapshot_id) == current_snapshot_id) }); Ok(()) } @@ -5143,10 +5148,9 @@ fn snapshot_has_manifest_references(snapshot: &serde_json::Value) -> bool { .get("manifests") .and_then(serde_json::Value::as_array) .is_some_and(|manifests| { - !manifests.is_empty() - && manifests - .iter() - .all(|manifest| manifest.as_str().is_some_and(|manifest| !manifest.is_empty())) + manifests + .iter() + .all(|manifest| manifest.as_str().is_some_and(|manifest| !manifest.is_empty())) }) } @@ -5162,6 +5166,14 @@ impl SnapshotLiveFiles { self.data_files.contains_key(location) || self.delete_files.contains_key(location) } + fn live_file_count(&self) -> usize { + self.data_files.len() + self.delete_files.len() + } + + fn live_identity(&self, location: &str) -> Option<&SnapshotFileIdentity> { + self.data_files.get(location).or_else(|| self.delete_files.get(location)) + } + fn identity( &self, location: &str, @@ -5183,6 +5195,7 @@ struct SnapshotFileChanges { deleted_delete_files: BTreeSet, existing_files: BTreeSet, invalid_existing_files: bool, + min_live_data_sequence_number: Option, } impl SnapshotFileChanges { @@ -5192,14 +5205,25 @@ impl SnapshotFileChanges { current_live_files: &SnapshotLiveFiles, partition_spec_id: i32, ) { + if reference.object_kind == crate::table_catalog::TableMetadataMaintenanceObjectKind::DataFile { + self.record_live_data_sequence(reference.sequence_number.unwrap_or(0)); + } self.invalid_existing_files |= !current_live_files .identity(&reference.location, &reference.object_kind) .is_some_and(|identity| identity.matches_existing_reference(&reference, partition_spec_id)); self.invalid_existing_files |= !self.existing_files.insert(reference.location); } - fn has_delete_or_row_level_change(&self) -> bool { - !self.added_delete_files.is_empty() || !self.deleted_data_files.is_empty() || !self.deleted_delete_files.is_empty() + fn record_live_data_sequence(&mut self, sequence_number: i64) { + self.min_live_data_sequence_number = Some( + self.min_live_data_sequence_number + .map_or(sequence_number, |current| current.min(sequence_number)), + ); + } + + fn accounts_for_parent_files(&self, parent: &SnapshotLiveFiles) -> bool { + // Existing and deleted entries are unique, disjoint, and checked against the parent. + self.existing_files.len() + self.deleted_data_files.len() + self.deleted_delete_files.len() == parent.live_file_count() } fn has_any_change(&self) -> bool { @@ -5213,7 +5237,6 @@ impl SnapshotFileChanges { struct SnapshotChangeContext<'a> { current_live_files: &'a SnapshotLiveFiles, - track_existing_files: bool, snapshot_id: i64, sequence_number: i64, } @@ -5309,7 +5332,6 @@ where snapshot, SnapshotChangeContext { current_live_files: &parent_live_files, - track_existing_files: operation == "replace", snapshot_id, sequence_number, }, @@ -5323,47 +5345,48 @@ where )); } } - match operation { - "append" => { - if changes.has_deleted_files() || !changes.added_delete_files.is_empty() { - return Err(s3_error!(InvalidRequest, "append snapshot cannot delete data files or add delete files")); - } + "append" if !changes.deleted_data_files.is_empty() || !changes.added_delete_files.is_empty() => { + return Err(s3_error!(InvalidRequest, "append snapshot cannot delete data files or add delete files")); } - "overwrite" | "delete" | "replace" => { - if parent_snapshot_id.is_none() { - return Err(s3_error!(InvalidRequest, "row-level snapshot operation requires a parent snapshot")); - } - if operation == "replace" && !changes.has_any_change() { - if changes.invalid_existing_files - || changes.existing_files.len() != parent_live_files.data_files.len() + parent_live_files.delete_files.len() - { - return Err(s3_error!( - InvalidRequest, - "manifest rewrite must preserve the parent snapshot's live files" - )); - } - } else if operation == "overwrite" { - if !changes.has_any_change() { - return Err(s3_error!(InvalidRequest, "overwrite snapshot operation requires changed files")); - } - } else if !changes.has_delete_or_row_level_change() { - return Err(s3_error!( - InvalidRequest, - "row-level snapshot operation requires deleted data files or added delete files" - )); - } - for location in changes.deleted_data_files.iter().chain(changes.deleted_delete_files.iter()) { - if !parent_live_files.contains(location) { - return Err(commit_requirement_failed( - "commit requirement failed: deleted file is not in the parent snapshot", - )); - } - } + "replace" if changes.has_any_change() && !changes.has_deleted_files() => { + return Err(s3_error!(InvalidRequest, "replace snapshot operation requires deleted files")); } + "delete" if !changes.added_data_files.is_empty() => { + return Err(s3_error!(InvalidRequest, "delete snapshot cannot add data files")); + } + "append" | "overwrite" | "delete" | "replace" => {} _ => return Err(s3_error!(InvalidRequest, "unsupported snapshot operation: {operation}")), } + for location in changes.deleted_data_files.iter().chain(changes.deleted_delete_files.iter()) { + if changes.existing_files.contains(location) { + return Err(s3_error!(InvalidRequest, "snapshot cannot mark the same file as existing and deleted")); + } + let Some(identity) = parent_live_files.live_identity(location) else { + return Err(commit_requirement_failed( + "commit requirement failed: deleted file is not in the parent snapshot", + )); + }; + if operation == "append" + && changes + .min_live_data_sequence_number + .is_some_and(|min_data_seq| identity.sequence_number.unwrap_or(0) >= min_data_seq) + { + return Err(s3_error!(InvalidRequest, "append snapshot cannot delete active delete files")); + } + } + + if changes.invalid_existing_files || !changes.accounts_for_parent_files(&parent_live_files) { + let message = match operation { + "append" => "append snapshot must preserve the parent snapshot's live files", + "replace" if !changes.has_any_change() => "manifest rewrite must preserve the parent snapshot's live files", + _ if !changes.has_any_change() => "no-op snapshot must preserve the parent snapshot's live files", + _ if changes.invalid_existing_files => "existing manifest entry must match a live file in the parent snapshot", + _ => "snapshot must retain or explicitly delete each live file in the parent snapshot", + }; + return Err(s3_error!(InvalidRequest, "{message}")); + } Ok(()) } @@ -5467,18 +5490,16 @@ where { return Err(s3_error!(InvalidRequest, "inherited manifest must preserve its manifest-list identity")); } - if context.track_existing_files { - for reference in manifest - .references - .into_iter() - .filter(|reference| matches!(reference.entry_status, Some(0 | 1))) - { - changes.record_existing_file( - reference, - context.current_live_files, - manifest.location.partition_spec_id.unwrap_or(0), - ); - } + for reference in manifest + .references + .into_iter() + .filter(|reference| matches!(reference.entry_status, Some(0 | 1))) + { + changes.record_existing_file( + reference, + context.current_live_files, + manifest.location.partition_spec_id.unwrap_or(0), + ); } continue; } @@ -5517,41 +5538,57 @@ where return Err(s3_error!(InvalidRequest, "added manifest entry file sequence must match its manifest")); } if status == 2 - && context - .current_live_files - .identity(&reference.location, &reference.object_kind) - .is_some_and(|current_identity| { - current_identity.sequence_number != reference.sequence_number - || current_identity.file_sequence_number != reference.file_sequence_number - }) + && let Some(current_identity) = context.current_live_files.live_identity(&reference.location) { - return Err(s3_error!( - InvalidRequest, - "deleted manifest entry must preserve the current file sequence" - )); + if current_identity.content != reference.content { + return Err(s3_error!(InvalidRequest, "deleted manifest entry content must match the parent snapshot")); + } + if current_identity.sequence_number.unwrap_or(0) != reference.sequence_number.unwrap_or(0) + || current_identity.file_sequence_number.unwrap_or(0) != reference.file_sequence_number.unwrap_or(0) + { + return Err(s3_error!( + InvalidRequest, + "deleted manifest entry must preserve the current file sequence" + )); + } } match (status, &reference.object_kind) { (0, _) => { - if context.track_existing_files { - changes.record_existing_file( - reference, - context.current_live_files, - manifest.location.partition_spec_id.unwrap_or(0), - ); - } + changes.record_existing_file( + reference, + context.current_live_files, + manifest.location.partition_spec_id.unwrap_or(0), + ); } (1, crate::table_catalog::TableMetadataMaintenanceObjectKind::DataFile) => { - changes.added_data_files.insert(reference.location); + changes.record_live_data_sequence(reference.sequence_number.unwrap_or(context.sequence_number)); + if changes.added_delete_files.contains(&reference.location) + || !changes.added_data_files.insert(reference.location) + { + return Err(s3_error!(InvalidRequest, "snapshot contains a duplicate file reference")); + } } (1, crate::table_catalog::TableMetadataMaintenanceObjectKind::DeleteFile) => { - changes.added_delete_files.insert(reference.location); + if changes.added_data_files.contains(&reference.location) + || !changes.added_delete_files.insert(reference.location) + { + return Err(s3_error!(InvalidRequest, "snapshot contains a duplicate file reference")); + } } (2, crate::table_catalog::TableMetadataMaintenanceObjectKind::DataFile) => { - changes.deleted_data_files.insert(reference.location); + if changes.deleted_delete_files.contains(&reference.location) + || !changes.deleted_data_files.insert(reference.location) + { + return Err(s3_error!(InvalidRequest, "snapshot contains a duplicate file reference")); + } } (2, crate::table_catalog::TableMetadataMaintenanceObjectKind::DeleteFile) => { - changes.deleted_delete_files.insert(reference.location); + if changes.deleted_data_files.contains(&reference.location) + || !changes.deleted_delete_files.insert(reference.location) + { + return Err(s3_error!(InvalidRequest, "snapshot contains a duplicate file reference")); + } } _ => return Err(s3_error!(InvalidRequest, "manifest entry status is unsupported")), } @@ -5723,10 +5760,112 @@ fn table_commit_object_key( Ok(object_key) } +#[derive(Clone, Copy, Default)] +struct SnapshotHistory { + root: Option, + // Sequence of the root or the oldest retained snapshot before an expired parent. + first_sequence: i64, +} + +impl SnapshotHistory { + fn is_separate_from(self, other: Self, added: &BTreeSet) -> bool { + let (root, root_sequence, oldest_retained) = match (self.root, other.root) { + (Some(left), Some(right)) => return left != right, + (Some(root), None) => (root, self.first_sequence, other.first_sequence), + (None, Some(root)) => (root, other.first_sequence, self.first_sequence), + (None, None) => return false, + }; + // An expired ancestor predates its retained child. V1 has no sequence numbers. + added.contains(&root) || (oldest_retained > 0 && root_sequence >= oldest_retained) + } +} + +#[derive(Default)] +struct SnapshotCommitRoots { + by_snapshot: BTreeMap, + by_branch: BTreeMap, + added: BTreeSet, +} + +impl SnapshotCommitRoots { + fn new(metadata: &serde_json::Value) -> Self { + let mut roots = Self::default(); + let mut parents: BTreeMap<_, _> = metadata["snapshots"] + .as_array() + .into_iter() + .flatten() + .filter_map(|snapshot| { + Some(( + snapshot["snapshot-id"].as_i64()?, + (snapshot["parent-snapshot-id"].as_i64(), snapshot["sequence-number"].as_i64().unwrap_or(0)), + )) + }) + .collect(); + // Imported snapshots can appear in any order. Resolve each retained parent link once. + let mut path = Vec::new(); + while let Some((&start, _)) = parents.first_key_value() { + let mut id = start; + let mut history = SnapshotHistory::default(); + while let Some((parent, sequence)) = parents.remove(&id) { + path.push(id); + history.first_sequence = sequence; + let Some(parent) = parent else { + history.root = Some(id); + break; + }; + id = parent; + } + let history = roots.by_snapshot.get(&id).copied().unwrap_or(history); + roots.by_snapshot.extend(path.drain(..).map(|id| (id, history))); + } + + roots.by_branch = metadata["refs"] + .as_object() + .into_iter() + .flatten() + .filter(|(_, reference)| reference["type"] == "branch") + .filter_map(|(name, reference)| Some((name.clone(), reference["snapshot-id"].as_i64()?))) + .collect(); + if let Some(id) = crate::table_catalog::table_snapshot_ref_id(metadata, "main") { + roots.by_branch.insert("main".to_owned(), id); + } + roots + } + + fn add(&mut self, id: i64, snapshot: &serde_json::Value) { + let history = match snapshot["parent-snapshot-id"].as_i64() { + Some(parent) => self.by_snapshot.get(&parent).copied().unwrap_or_default(), + None => SnapshotHistory { + root: Some(id), + first_sequence: snapshot["sequence-number"].as_i64().unwrap_or(0), + }, + }; + self.by_snapshot.insert(id, history); + self.added.insert(id); + } + + fn set_ref(&mut self, metadata: &serde_json::Value, name: &str, is_branch: bool, id: i64) -> S3Result<()> { + let current = self.by_branch.get(name).copied().or_else(|| { + // Setting a branch can also replace an existing tag. + crate::table_catalog::table_snapshot_ref_id(metadata, name).filter(|_| is_branch) + }); + if let Some(previous) = current + && let (Some(target), Some(source)) = (self.by_snapshot.get(&id), self.by_snapshot.get(&previous)) + && target.is_separate_from(*source, &self.added) + { + return Err(s3_error!(InvalidRequest, "cannot publish a new snapshot history over an existing branch")); + } + if is_branch || current.is_some() { + self.by_branch.insert(name.to_owned(), id); + } + Ok(()) + } +} + fn apply_set_snapshot_ref_update( metadata: &mut serde_json::Value, update: &serde_json::Value, - added_snapshot_ids: &BTreeSet, + roots: &mut SnapshotCommitRoots, commit_timestamp_ms: i64, ) -> S3Result<()> { let ref_name = update @@ -5744,42 +5883,40 @@ fn apply_set_snapshot_ref_update( .filter(|(key, _)| key.as_str() != "action" && key.as_str() != "ref-name") .map(|(key, value)| (key.clone(), value.clone())) .collect::>(); - if !metadata + let snapshot = metadata .get("snapshots") .and_then(serde_json::Value::as_array) - .is_some_and(|snapshots| { + .and_then(|snapshots| { snapshots .iter() - .any(|snapshot| snapshot.get("snapshot-id").and_then(serde_json::Value::as_i64) == Some(snapshot_id)) + .find(|snapshot| snapshot.get("snapshot-id").and_then(serde_json::Value::as_i64) == Some(snapshot_id)) }) - { - return Err(s3_error!(InvalidRequest, "set-snapshot-ref targets an unknown snapshot")); - } + .ok_or_else(|| s3_error!(InvalidRequest, "set-snapshot-ref targets an unknown snapshot"))?; + let new_snapshot = roots.added.contains(&snapshot_id); + roots.set_ref( + metadata, + ref_name, + reference.get("type").and_then(serde_json::Value::as_str) == Some("branch"), + snapshot_id, + )?; let next_reference = serde_json::Value::Object(reference); let unchanged = metadata .get("refs") .and_then(serde_json::Value::as_object) .and_then(|refs| refs.get(ref_name)) == Some(&next_reference); + let timestamp_ms = if ref_name == "main" && !unchanged && new_snapshot { + snapshot + .get("timestamp-ms") + .and_then(serde_json::Value::as_i64) + .ok_or_else(|| s3_error!(InvalidRequest, "snapshot timestamp-ms must be an integer"))? + } else { + commit_timestamp_ms + }; ensure_object_field(metadata, "refs")?.insert(ref_name.to_string(), next_reference); if ref_name == "main" { metadata_object_mut(metadata)?.insert("current-snapshot-id".to_string(), serde_json::Value::from(snapshot_id)); if !unchanged { - let timestamp_ms = if added_snapshot_ids.contains(&snapshot_id) { - metadata - .get("snapshots") - .and_then(serde_json::Value::as_array) - .and_then(|snapshots| { - snapshots - .iter() - .find(|snapshot| snapshot.get("snapshot-id").and_then(serde_json::Value::as_i64) == Some(snapshot_id)) - }) - .and_then(|snapshot| snapshot.get("timestamp-ms")) - .and_then(serde_json::Value::as_i64) - .ok_or_else(|| s3_error!(InvalidRequest, "snapshot timestamp-ms must be an integer"))? - } else { - commit_timestamp_ms - }; ensure_array_field(metadata, "snapshot-log")?.push(serde_json::json!({ "timestamp-ms": timestamp_ms, "snapshot-id": snapshot_id @@ -5867,13 +6004,20 @@ fn apply_remove_snapshots_update(metadata: &mut serde_json::Value, update: &serd Ok(()) } -fn apply_remove_snapshot_ref_update(metadata: &mut serde_json::Value, update: &serde_json::Value) -> S3Result<()> { +fn apply_remove_snapshot_ref_update( + metadata: &mut serde_json::Value, + update: &serde_json::Value, + roots: &mut SnapshotCommitRoots, +) -> S3Result<()> { let ref_name = update .get("ref-name") .and_then(serde_json::Value::as_str) .ok_or_else(|| s3_error!(InvalidRequest, "remove-snapshot-ref requires ref-name"))?; - let removed = ensure_object_field(metadata, "refs")?.remove(ref_name).is_some(); - if removed && ref_name == "main" { + let clears_current = ref_name == "main" && crate::table_catalog::table_snapshot_ref_id(metadata, ref_name).is_some(); + ensure_object_field(metadata, "refs")?.remove(ref_name); + // Only explicit ref removal permits a new history. Snapshot expiration may also remove a ref from metadata. + roots.by_branch.remove(ref_name); + if clears_current { metadata_object_mut(metadata)?.insert("current-snapshot-id".to_string(), serde_json::Value::from(-1)); } Ok(()) diff --git a/rustfs/src/admin/handlers/table_catalog/tests.rs b/rustfs/src/admin/handlers/table_catalog/tests.rs index 846c40fc59..d9bbb420e6 100644 --- a/rustfs/src/admin/handlers/table_catalog/tests.rs +++ b/rustfs/src/admin/handlers/table_catalog/tests.rs @@ -12879,15 +12879,9 @@ async fn row_level_conflict_allows_add_only_overwrite_snapshot() { .expect("created metadata should have table location"); let current_manifest_list = format!("{table_location}/metadata/snap-10.avro"); let current_data_file = format!("{table_location}/data/part-10.parquet"); - seed_test_snapshot_manifest( - &metadata_backend, - "warehouse", - ¤t_manifest_list, - 10, - 1, - &[(¤t_data_file, 0, 1, 10, 1)], - ) - .await; + let current_manifest = format!("{table_location}/metadata/manifest-10.avro"); + seed_test_manifest(&metadata_backend, "warehouse", ¤t_manifest, &[(¤t_data_file, 0, 1, 10, 1)]).await; + seed_test_manifest_list(&metadata_backend, "warehouse", ¤t_manifest_list, &[¤t_manifest], 1, 10).await; let append_request: RestCommitTableRequest = serde_json::from_value(serde_json::json!({ "requirements": [], "updates": [ @@ -12925,13 +12919,13 @@ async fn row_level_conflict_allows_add_only_overwrite_snapshot() { let overwrite_manifest_list = format!("{table_location}/metadata/snap-11.avro"); let added_data_file = format!("{table_location}/data/part-11.parquet"); - seed_test_snapshot_manifest( + let added_manifest = format!("{table_location}/metadata/manifest-11.avro"); + seed_test_manifest(&metadata_backend, "warehouse", &added_manifest, &[(&added_data_file, 0, 1, 11, 2)]).await; + seed_test_manifest_list_entries( &metadata_backend, "warehouse", &overwrite_manifest_list, - 11, - 2, - &[(&added_data_file, 0, 1, 11, 2)], + &[(¤t_manifest, 1, 10), (&added_manifest, 2, 11)], ) .await; let overwrite_request: RestCommitTableRequest = serde_json::from_value(serde_json::json!({ @@ -13377,6 +13371,2055 @@ async fn row_level_conflict_rejects_manifest_outside_table_warehouse() { assert_eq!(unchanged.generation, committed.generation); } +#[tokio::test] +async fn issue_9632_noop_delete_commits_succeed_and_preserve_live_files() { + use crate::table_catalog::test_support::manifest_list_avro_entries_with_min_sequences; + + let backend = TestTableCatalogObjectBackend::content_addressed(); + let store = crate::table_catalog::ObjectTableCatalogStore::new(backend.clone()); + let namespace = crate::table_catalog::Namespace::parse("analytics").expect("namespace should parse"); + + // 1. Empty table (parent = None) 0-change "delete". + let empty_created = create_standard_events_table(&store, &backend, &namespace).await; + let empty_location = empty_created.metadata["location"] + .as_str() + .expect("empty table location should exist"); + let empty_list = format!("{empty_location}/metadata/snap-empty-10.avro"); + backend + .put_bytes( + "warehouse", + &test_snapshot_object_key("warehouse", &empty_list), + test_manifest_list_avro_bytes(&[], 1, 10), + ) + .await; + let empty_delete: RestCommitTableRequest = serde_json::from_value(serde_json::json!({ + "requirements": [{"type": "assert-ref-snapshot-id", "ref": "main", "snapshot-id": null}], + "updates": [ + { + "action": "add-snapshot", + "snapshot": { + "snapshot-id": 10, + "sequence-number": 1, + "timestamp-ms": 1000, + "manifest-list": empty_list, + "summary": {"operation": "delete"} + } + }, + {"action": "set-snapshot-ref", "ref-name": "main", "snapshot-id": 10, "type": "branch"} + ] + })) + .expect("empty delete request should parse"); + let empty_committed = commit_table_response( + &store, + &trusted_table_commit_backend(&backend), + "warehouse", + &namespace, + "events", + empty_delete, + ) + .await + .expect("0-change delete on an empty table should succeed"); + assert_eq!(empty_committed.metadata["current-snapshot-id"], 10); + assert_eq!(empty_committed.metadata["last-sequence-number"], 1); + let entry = store.load_table("warehouse", "analytics", "events").await.unwrap().unwrap(); + let empty_live = load_snapshot_live_files(&backend, "warehouse", &entry, &empty_committed.metadata, Some(10)) + .await + .unwrap(); + assert_eq!(empty_live.live_file_count(), 0); + + // 2. Populated table (data + MoR delete) 0-change "delete": inherited manifests, replay, status=0 rewrite, and post-truncate pure-DELETED manifest drop. + let data_file = format!("{empty_location}/data/part-11.parquet"); + let data_manifest = format!("{empty_location}/metadata/manifest-11.avro"); + let list_11 = format!("{empty_location}/metadata/snap-11.avro"); + seed_test_manifest(&backend, "warehouse", &data_manifest, &[(&data_file, 0, 1, 11, 2)]).await; + seed_test_manifest_list(&backend, "warehouse", &list_11, &[&data_manifest], 2, 11).await; + commit_table_response( + &store, + &trusted_table_commit_backend(&backend), + "warehouse", + &namespace, + "events", + serde_json::from_value(serde_json::json!({ + "requirements": [{"type": "assert-ref-snapshot-id", "ref": "main", "snapshot-id": 10}], + "updates": [ + { + "action": "add-snapshot", + "snapshot": { + "snapshot-id": 11, + "parent-snapshot-id": 10, + "sequence-number": 2, + "timestamp-ms": 2000, + "manifest-list": list_11, + "summary": {"operation": "append"} + } + }, + {"action": "set-snapshot-ref", "ref-name": "main", "snapshot-id": 11, "type": "branch"} + ] + })) + .unwrap(), + ) + .await + .expect("append after empty delete should succeed"); + + let delete_file = format!("{empty_location}/delete/pos-12.parquet"); + let delete_manifest = format!("{empty_location}/metadata/manifest-12.avro"); + let delete_bytes = test_manifest_avro_bytes(&[(&delete_file, 1, 1, 12, 3)]); + let data_manifest_len = backend + .state + .lock() + .await + .objects + .get(&("warehouse".to_string(), test_snapshot_object_key("warehouse", &data_manifest))) + .unwrap() + .data + .len(); + backend + .put_bytes( + "warehouse", + &test_snapshot_object_key("warehouse", &delete_manifest), + delete_bytes.clone(), + ) + .await; + seed_test_manifest_data_files(&backend, "warehouse", &[(&delete_file, 1, 1, 12, 3)]).await; + let list_12 = format!("{empty_location}/metadata/snap-12.avro"); + backend + .put_bytes( + "warehouse", + &test_snapshot_object_key("warehouse", &list_12), + manifest_list_avro_entries_with_min_sequences(&[ + (&data_manifest, data_manifest_len, 0, 0, 2, 2, 11), + (&delete_manifest, delete_bytes.len(), 0, 1, 3, 3, 12), + ]), + ) + .await; + commit_table_response( + &store, + &trusted_table_commit_backend(&backend), + "warehouse", + &namespace, + "events", + serde_json::from_value(serde_json::json!({ + "requirements": [{"type": "assert-ref-snapshot-id", "ref": "main", "snapshot-id": 11}], + "updates": [ + { + "action": "add-snapshot", + "snapshot": { + "snapshot-id": 12, + "parent-snapshot-id": 11, + "sequence-number": 3, + "timestamp-ms": 3000, + "manifest-list": list_12, + "summary": {"operation": "delete"} + } + }, + {"action": "set-snapshot-ref", "ref-name": "main", "snapshot-id": 12, "type": "branch"} + ] + })) + .unwrap(), + ) + .await + .expect("MoR delete commit should succeed"); + + // Inherited-manifests 0-change "delete" + idempotent replay. + let list_13 = format!("{empty_location}/metadata/snap-13.avro"); + backend + .put_bytes( + "warehouse", + &test_snapshot_object_key("warehouse", &list_13), + manifest_list_avro_entries_with_min_sequences(&[ + (&data_manifest, data_manifest_len, 0, 0, 2, 2, 11), + (&delete_manifest, delete_bytes.len(), 0, 1, 3, 3, 12), + ]), + ) + .await; + let noop_inherited_json = serde_json::json!({ + "commit-id": "96320000-0000-4000-8000-000000000013", + "requirements": [{"type": "assert-ref-snapshot-id", "ref": "main", "snapshot-id": 12}], + "updates": [ + { + "action": "add-snapshot", + "snapshot": { + "snapshot-id": 13, + "parent-snapshot-id": 12, + "sequence-number": 4, + "timestamp-ms": 4000, + "manifest-list": list_13, + "summary": {"operation": "delete"} + } + }, + {"action": "set-snapshot-ref", "ref-name": "main", "snapshot-id": 13, "type": "branch"} + ] + }); + let noop_inherited = commit_table_response( + &store, + &trusted_table_commit_backend(&backend), + "warehouse", + &namespace, + "events", + serde_json::from_value(noop_inherited_json.clone()).unwrap(), + ) + .await + .expect("0-change delete inheriting parent manifests should succeed"); + assert_eq!(noop_inherited.metadata["current-snapshot-id"], 13); + assert_eq!(noop_inherited.metadata["last-sequence-number"], 4); + let after_13 = store.load_table("warehouse", "analytics", "events").await.unwrap().unwrap(); + let replay_13 = commit_table_response( + &store, + &trusted_table_commit_backend(&backend), + "warehouse", + &namespace, + "events", + serde_json::from_value(noop_inherited_json).unwrap(), + ) + .await + .expect("0-change delete commit should replay idempotently"); + assert_eq!(replay_13.metadata, noop_inherited.metadata); + assert_eq!( + store + .load_table("warehouse", "analytics", "events") + .await + .unwrap() + .unwrap() + .generation, + after_13.generation + ); + + // Rewritten status=0 (EXISTING) manifests 0-change "delete". + let rewritten_data = format!("{empty_location}/metadata/manifest-14-data.avro"); + let rewritten_delete = format!("{empty_location}/metadata/manifest-14-del.avro"); + let rewritten_data_bytes = test_manifest_avro_bytes(&[(&data_file, 0, 0, 11, 2)]); + let rewritten_delete_bytes = test_manifest_avro_bytes(&[(&delete_file, 1, 0, 12, 3)]); + backend + .put_bytes( + "warehouse", + &test_snapshot_object_key("warehouse", &rewritten_data), + rewritten_data_bytes.clone(), + ) + .await; + backend + .put_bytes( + "warehouse", + &test_snapshot_object_key("warehouse", &rewritten_delete), + rewritten_delete_bytes.clone(), + ) + .await; + let list_14 = format!("{empty_location}/metadata/snap-14.avro"); + backend + .put_bytes( + "warehouse", + &test_snapshot_object_key("warehouse", &list_14), + manifest_list_avro_entries_with_min_sequences(&[ + (&rewritten_data, rewritten_data_bytes.len(), 0, 0, 5, 2, 14), + (&rewritten_delete, rewritten_delete_bytes.len(), 0, 1, 5, 3, 14), + ]), + ) + .await; + let noop_rewritten = commit_table_response( + &store, + &trusted_table_commit_backend(&backend), + "warehouse", + &namespace, + "events", + serde_json::from_value(serde_json::json!({ + "requirements": [{"type": "assert-ref-snapshot-id", "ref": "main", "snapshot-id": 13}], + "updates": [ + { + "action": "add-snapshot", + "snapshot": { + "snapshot-id": 14, + "parent-snapshot-id": 13, + "sequence-number": 5, + "timestamp-ms": 5000, + "manifest-list": list_14, + "summary": {"operation": "delete"} + } + }, + {"action": "set-snapshot-ref", "ref-name": "main", "snapshot-id": 14, "type": "branch"} + ] + })) + .unwrap(), + ) + .await + .expect("0-change delete rewriting live entries as status=0 should succeed"); + assert_eq!(noop_rewritten.metadata["current-snapshot-id"], 14); + let entry_14 = store.load_table("warehouse", "analytics", "events").await.unwrap().unwrap(); + let live_14 = load_snapshot_live_files(&backend, "warehouse", &entry_14, &noop_rewritten.metadata, Some(14)) + .await + .unwrap(); + assert_eq!(live_14.data_files.len(), 1); + assert_eq!(live_14.delete_files.len(), 1); + + // Truncate all live files via status=2 in S15, then drop pure-DELETED manifests in S16 0-change "delete". + let trunc_data = format!("{empty_location}/metadata/manifest-15-data.avro"); + let trunc_delete = format!("{empty_location}/metadata/manifest-15-del.avro"); + let trunc_data_bytes = test_manifest_avro_bytes(&[(&data_file, 0, 2, 15, 2)]); + let trunc_delete_bytes = test_manifest_avro_bytes(&[(&delete_file, 1, 2, 15, 3)]); + backend + .put_bytes("warehouse", &test_snapshot_object_key("warehouse", &trunc_data), trunc_data_bytes.clone()) + .await; + backend + .put_bytes( + "warehouse", + &test_snapshot_object_key("warehouse", &trunc_delete), + trunc_delete_bytes.clone(), + ) + .await; + let list_15 = format!("{empty_location}/metadata/snap-15.avro"); + backend + .put_bytes( + "warehouse", + &test_snapshot_object_key("warehouse", &list_15), + manifest_list_avro_entries_with_min_sequences(&[ + (&trunc_data, trunc_data_bytes.len(), 0, 0, 6, 2, 15), + (&trunc_delete, trunc_delete_bytes.len(), 0, 1, 6, 3, 15), + ]), + ) + .await; + commit_table_response( + &store, + &trusted_table_commit_backend(&backend), + "warehouse", + &namespace, + "events", + serde_json::from_value(serde_json::json!({ + "requirements": [{"type": "assert-ref-snapshot-id", "ref": "main", "snapshot-id": 14}], + "updates": [ + { + "action": "add-snapshot", + "snapshot": { + "snapshot-id": 15, + "parent-snapshot-id": 14, + "sequence-number": 6, + "timestamp-ms": 6000, + "manifest-list": list_15, + "summary": {"operation": "delete"} + } + }, + {"action": "set-snapshot-ref", "ref-name": "main", "snapshot-id": 15, "type": "branch"} + ] + })) + .unwrap(), + ) + .await + .expect("truncate-all delete should succeed"); + + let list_16 = format!("{empty_location}/metadata/snap-16.avro"); + backend + .put_bytes( + "warehouse", + &test_snapshot_object_key("warehouse", &list_16), + test_manifest_list_avro_bytes(&[], 7, 16), + ) + .await; + let post_truncate = commit_table_response( + &store, + &trusted_table_commit_backend(&backend), + "warehouse", + &namespace, + "events", + serde_json::from_value(serde_json::json!({ + "requirements": [{"type": "assert-ref-snapshot-id", "ref": "main", "snapshot-id": 15}], + "updates": [ + { + "action": "add-snapshot", + "snapshot": { + "snapshot-id": 16, + "parent-snapshot-id": 15, + "sequence-number": 7, + "timestamp-ms": 7000, + "manifest-list": list_16, + "summary": {"operation": "delete"} + } + }, + {"action": "set-snapshot-ref", "ref-name": "main", "snapshot-id": 16, "type": "branch"} + ] + })) + .unwrap(), + ) + .await + .expect("0-change delete dropping pure-DELETED manifests after truncate should succeed"); + assert_eq!(post_truncate.metadata["current-snapshot-id"], 16); + assert_eq!(post_truncate.metadata["last-sequence-number"], 7); +} + +#[tokio::test] +async fn publishing_new_snapshot_histories_preserves_existing_branch_heads() { + let backend = TestTableCatalogObjectBackend::content_addressed(); + let store = crate::table_catalog::ObjectTableCatalogStore::new(backend.clone()); + let namespace = crate::table_catalog::Namespace::parse("analytics").unwrap(); + let created = create_standard_events_table(&store, &backend, &namespace).await; + let location = created.metadata["location"].as_str().unwrap(); + let data_file = format!("{location}/data/older-partition.parquet"); + let list = format!("{location}/metadata/snap-10.avro"); + seed_test_snapshot_manifest(&backend, "warehouse", &list, 10, 1, &[(&data_file, 0, 1, 10, 1)]).await; + let empty_list = format!("{location}/metadata/snap-11.avro"); + seed_test_manifest_list(&backend, "warehouse", &empty_list, &[], 2, 11).await; + + let commit = async |updates: Vec| { + let request = serde_json::from_value(serde_json::json!({ "updates": updates })).unwrap(); + commit_table_response( + &store, + &trusted_table_commit_backend(&backend), + "warehouse", + &namespace, + "events", + request, + ) + .await + }; + let publish = |branch: &str, id: i64| serde_json::json!({"action": "set-snapshot-ref", "ref-name": branch, "type": "branch", "snapshot-id": id}); + let tag = |name: &str, id: i64| serde_json::json!({"action": "set-snapshot-ref", "ref-name": name, "type": "tag", "snapshot-id": id}); + let append = serde_json::json!({"action": "add-snapshot", "snapshot": { + "snapshot-id": 10, "sequence-number": 1, "timestamp-ms": 1000, + "manifest-list": list, "summary": {"operation": "append"} + }}); + let populated = commit(vec![append, publish("main", 10), publish("audit", 10), tag("release", 10)]) + .await + .unwrap(); + let root = |operation: &str| { + serde_json::json!({"action": "add-snapshot", "snapshot": { + "snapshot-id": 11, "sequence-number": 2, "timestamp-ms": 2000, + "manifest-list": empty_list, "summary": {"operation": operation} + }}) + }; + let child_list = format!("{location}/metadata/snap-12.avro"); + seed_test_manifest_list(&backend, "warehouse", &child_list, &[], 3, 12).await; + let child = serde_json::json!({"action": "add-snapshot", "snapshot": { + "snapshot-id": 12, "parent-snapshot-id": 11, "sequence-number": 3, "timestamp-ms": 3000, + "manifest-list": child_list, "summary": {"operation": "append"} + }}); + let third_list = format!("{location}/metadata/snap-13.avro"); + seed_test_manifest_list(&backend, "warehouse", &third_list, &[], 4, 13).await; + let third_root = serde_json::json!({"action": "add-snapshot", "snapshot": { + "snapshot-id": 13, "sequence-number": 4, "timestamp-ms": 4000, + "manifest-list": third_list, "summary": {"operation": "delete"} + }}); + let mut grandchild = third_root.clone(); + grandchild["snapshot"]["parent-snapshot-id"] = serde_json::json!(12); + let reject = async |updates| { + let error = commit(updates).await.unwrap_err(); + assert_eq!(error.code(), &S3ErrorCode::InvalidRequest); + assert_eq!(error.message(), Some("cannot publish a new snapshot history over an existing branch")); + }; + for branch in ["main", "audit"] { + for operation in ["append", "overwrite", "replace", "delete"] { + reject(vec![root(operation), publish(branch, 11)]).await; + reject(vec![root(operation), child.clone(), publish(branch, 12)]).await; + } + } + reject(vec![root("delete"), publish("release", 11)]).await; + reject(vec![root("overwrite"), tag("audit", 11)]).await; + reject(vec![ + root("overwrite"), + publish("new-branch", 11), + child.clone(), + grandchild, + publish("audit", 13), + ]) + .await; + reject(vec![ + root("append"), + publish("new-branch", 11), + third_root.clone(), + publish("new-branch", 13), + ]) + .await; + reject(vec![ + serde_json::json!({"action": "remove-snapshots", "snapshot-ids": [10]}), + root("append"), + publish("main", 11), + ]) + .await; + let assert_preserved = async |expected: &RestCommitTableResponse| { + let entry = store.load_table("warehouse", "analytics", "events").await.unwrap().unwrap(); + assert_eq!(entry.version_token, expected.version_token); + assert_eq!( + table_metadata_location_for_client("warehouse", &entry.metadata_location), + expected.metadata_location + ); + let persisted = read_persisted_table_metadata_for_entry(&backend, &entry, &entry.metadata_location, true) + .await + .unwrap(); + assert_eq!(persisted["current-snapshot-id"], 10); + let audit = crate::table_catalog::table_snapshot_ref_id(&persisted, "audit"); + assert_eq!(audit, Some(10)); + let live = load_snapshot_live_files(&backend, "warehouse", &entry, &persisted, audit) + .await + .unwrap(); + assert!(live.data_files.contains_key(&data_file)); + }; + assert_preserved(&populated).await; + + let branched = commit(vec![ + root("overwrite"), + tag("release-next", 11), + publish("new-branch", 11), + child, + publish("new-branch", 12), + ]) + .await + .unwrap(); + assert_eq!(branched.metadata["refs"]["new-branch"]["snapshot-id"], 12); + assert_eq!(branched.metadata["current-snapshot-id"], 10); + + let staged = commit(vec![third_root]).await.unwrap(); + assert_eq!(staged.metadata["current-snapshot-id"], 10); + reject(vec![publish("audit", 13)]).await; + reject(vec![publish("main", 12)]).await; + let stage_child = |parent: i64, manifest_list: &str| { + serde_json::json!({"action": "add-snapshot", "snapshot": { + "snapshot-id": 14, "parent-snapshot-id": parent, "sequence-number": 5, "timestamp-ms": 5000, + "manifest-list": manifest_list, "summary": {"operation": "delete"} + }}) + }; + reject(vec![stage_child(13, &third_list), publish("audit", 14)]).await; + assert_preserved(&staged).await; + + commit(vec![stage_child(10, &list)]).await.unwrap(); + let published = commit(vec![publish("audit", 14)]).await.unwrap(); + assert_eq!(published.metadata["refs"]["audit"]["snapshot-id"], 14); + let restored = commit(vec![publish("audit", 10), tag("release", 13)]).await.unwrap(); + assert_eq!(restored.metadata["refs"]["release"]["snapshot-id"], 13); + assert_preserved(&restored).await; + + let reset = serde_json::json!({"action": "remove-snapshot-ref", "ref-name": "audit"}); + let replaced = commit(vec![reset, publish("audit", 13)]).await.unwrap(); + assert_eq!(replaced.metadata["refs"]["audit"]["snapshot-id"], 13); + assert_eq!(replaced.metadata["current-snapshot-id"], 10); +} + +#[tokio::test] +async fn row_level_delete_mutations_and_stale_delete_conflict() { + use crate::table_catalog::test_support::manifest_list_avro_entries_with_min_sequences; + + let store = TestTableCatalogStore::default(); + let backend = TestTableCatalogObjectBackend::content_addressed(); + let namespace = crate::table_catalog::Namespace::parse("analytics").expect("namespace should parse"); + let created = create_standard_events_table(&store, &backend, &namespace).await; + let location = created.metadata["location"].as_str().expect("table location should exist"); + + // Empty-table MoR equality delete (parent = None, content = 2, status = 1). + let eq_delete = format!("{location}/delete/eq-10.parquet"); + let eq_manifest = format!("{location}/metadata/manifest-10.avro"); + let eq_bytes = test_manifest_avro_bytes(&[(&eq_delete, 2, 1, 10, 1)]); + backend + .put_bytes("warehouse", &test_snapshot_object_key("warehouse", &eq_manifest), eq_bytes.clone()) + .await; + seed_test_manifest_data_files(&backend, "warehouse", &[(&eq_delete, 2, 1, 10, 1)]).await; + let list_10 = format!("{location}/metadata/snap-10.avro"); + backend + .put_bytes( + "warehouse", + &test_snapshot_object_key("warehouse", &list_10), + manifest_list_avro_entries_with_min_sequences(&[(&eq_manifest, eq_bytes.len(), 0, 1, 1, 1, 10)]), + ) + .await; + let commit_10 = commit_table_response( + &store, + &trusted_table_commit_backend(&backend), + "warehouse", + &namespace, + "events", + serde_json::from_value(serde_json::json!({ + "requirements": [{"type": "assert-ref-snapshot-id", "ref": "main", "snapshot-id": null}], + "updates": [ + { + "action": "add-snapshot", + "snapshot": { + "snapshot-id": 10, + "sequence-number": 1, + "timestamp-ms": 1000, + "manifest-list": list_10, + "summary": {"operation": "delete"} + } + }, + {"action": "set-snapshot-ref", "ref-name": "main", "snapshot-id": 10, "type": "branch"} + ] + })) + .unwrap(), + ) + .await + .expect("empty-table equality delete should commit"); + assert_eq!(commit_10.metadata["current-snapshot-id"], 10); + + // Append D1 + D2 while inheriting eq_delete. + let d1 = format!("{location}/data/part-11-a.parquet"); + let d2 = format!("{location}/data/part-11-b.parquet"); + let data_manifest_11 = format!("{location}/metadata/manifest-11.avro"); + let data_11_bytes = test_manifest_avro_bytes(&[(&d1, 0, 1, 11, 2), (&d2, 0, 1, 11, 2)]); + backend + .put_bytes( + "warehouse", + &test_snapshot_object_key("warehouse", &data_manifest_11), + data_11_bytes.clone(), + ) + .await; + seed_test_manifest_data_files(&backend, "warehouse", &[(&d1, 0, 1, 11, 2), (&d2, 0, 1, 11, 2)]).await; + let list_11 = format!("{location}/metadata/snap-11.avro"); + backend + .put_bytes( + "warehouse", + &test_snapshot_object_key("warehouse", &list_11), + manifest_list_avro_entries_with_min_sequences(&[ + (&data_manifest_11, data_11_bytes.len(), 0, 0, 2, 2, 11), + (&eq_manifest, eq_bytes.len(), 0, 1, 1, 1, 10), + ]), + ) + .await; + commit_table_response( + &store, + &trusted_table_commit_backend(&backend), + "warehouse", + &namespace, + "events", + serde_json::from_value(serde_json::json!({ + "requirements": [{"type": "assert-ref-snapshot-id", "ref": "main", "snapshot-id": 10}], + "updates": [ + { + "action": "add-snapshot", + "snapshot": { + "snapshot-id": 11, + "parent-snapshot-id": 10, + "sequence-number": 2, + "timestamp-ms": 2000, + "manifest-list": list_11, + "summary": {"operation": "append"} + } + }, + {"action": "set-snapshot-ref", "ref-name": "main", "snapshot-id": 11, "type": "branch"} + ] + })) + .unwrap(), + ) + .await + .expect("append preserving equality delete should commit"); + + // Metadata status=2 data delete of D1 while keeping D2 (status=0) and inheriting eq_delete. + let data_manifest_12 = format!("{location}/metadata/manifest-12.avro"); + let data_12_bytes = test_manifest_avro_bytes(&[(&d1, 0, 2, 12, 2), (&d2, 0, 0, 11, 2)]); + backend + .put_bytes( + "warehouse", + &test_snapshot_object_key("warehouse", &data_manifest_12), + data_12_bytes.clone(), + ) + .await; + let list_12 = format!("{location}/metadata/snap-12.avro"); + backend + .put_bytes( + "warehouse", + &test_snapshot_object_key("warehouse", &list_12), + manifest_list_avro_entries_with_min_sequences(&[ + (&data_manifest_12, data_12_bytes.len(), 0, 0, 3, 2, 12), + (&eq_manifest, eq_bytes.len(), 0, 1, 1, 1, 10), + ]), + ) + .await; + let commit_12 = commit_table_response( + &store, + &trusted_table_commit_backend(&backend), + "warehouse", + &namespace, + "events", + serde_json::from_value(serde_json::json!({ + "requirements": [{"type": "assert-ref-snapshot-id", "ref": "main", "snapshot-id": 11}], + "updates": [ + { + "action": "add-snapshot", + "snapshot": { + "snapshot-id": 12, + "parent-snapshot-id": 11, + "sequence-number": 3, + "timestamp-ms": 3000, + "manifest-list": list_12, + "summary": {"operation": "delete"} + } + }, + {"action": "set-snapshot-ref", "ref-name": "main", "snapshot-id": 12, "type": "branch"} + ] + })) + .unwrap(), + ) + .await + .expect("metadata status=2 data delete should commit"); + let entry_12 = store.load_table("warehouse", "analytics", "events").await.unwrap().unwrap(); + let live_12 = load_snapshot_live_files(&backend, "warehouse", &entry_12, &commit_12.metadata, Some(12)) + .await + .unwrap(); + assert!(!live_12.data_files.contains_key(&d1)); + assert!(live_12.data_files.contains_key(&d2)); + assert!(live_12.delete_files.contains_key(&eq_delete)); + + // MoR status=1 position delete on populated table while inheriting D2 and eq_delete. + let pos_delete = format!("{location}/delete/pos-13.parquet"); + let pos_manifest = format!("{location}/metadata/manifest-13-pos.avro"); + let pos_bytes = test_manifest_avro_bytes(&[(&pos_delete, 1, 1, 13, 4)]); + backend + .put_bytes("warehouse", &test_snapshot_object_key("warehouse", &pos_manifest), pos_bytes.clone()) + .await; + seed_test_manifest_data_files(&backend, "warehouse", &[(&pos_delete, 1, 1, 13, 4)]).await; + let list_13_pos = format!("{location}/metadata/snap-13-pos.avro"); + backend + .put_bytes( + "warehouse", + &test_snapshot_object_key("warehouse", &list_13_pos), + manifest_list_avro_entries_with_min_sequences(&[ + (&data_manifest_12, data_12_bytes.len(), 0, 0, 3, 2, 12), + (&eq_manifest, eq_bytes.len(), 0, 1, 1, 1, 10), + (&pos_manifest, pos_bytes.len(), 0, 1, 4, 4, 13), + ]), + ) + .await; + let commit_13 = commit_table_response( + &store, + &trusted_table_commit_backend(&backend), + "warehouse", + &namespace, + "events", + serde_json::from_value(serde_json::json!({ + "requirements": [{"type": "assert-ref-snapshot-id", "ref": "main", "snapshot-id": 12}], + "updates": [ + { + "action": "add-snapshot", + "snapshot": { + "snapshot-id": 13, + "parent-snapshot-id": 12, + "sequence-number": 4, + "timestamp-ms": 4000, + "manifest-list": list_13_pos, + "summary": {"operation": "delete"} + } + }, + {"action": "set-snapshot-ref", "ref-name": "main", "snapshot-id": 13, "type": "branch"} + ] + })) + .unwrap(), + ) + .await + .expect("MoR position delete should commit"); + let entry_13 = store.load_table("warehouse", "analytics", "events").await.unwrap().unwrap(); + let live_13 = load_snapshot_live_files(&backend, "warehouse", &entry_13, &commit_13.metadata, Some(13)) + .await + .unwrap(); + assert_eq!(live_13.delete_files.len(), 2); + + // Stale status=2 delete of already-deleted D1 must fail with 409 Conflict. + let stale_manifest = format!("{location}/metadata/manifest-14-stale.avro"); + let stale_bytes = test_manifest_avro_bytes(&[(&d1, 0, 2, 14, 2), (&d2, 0, 0, 11, 2)]); + backend + .put_bytes("warehouse", &test_snapshot_object_key("warehouse", &stale_manifest), stale_bytes.clone()) + .await; + let list_14 = format!("{location}/metadata/snap-14.avro"); + backend + .put_bytes( + "warehouse", + &test_snapshot_object_key("warehouse", &list_14), + manifest_list_avro_entries_with_min_sequences(&[ + (&stale_manifest, stale_bytes.len(), 0, 0, 5, 2, 14), + (&eq_manifest, eq_bytes.len(), 0, 1, 1, 1, 10), + (&pos_manifest, pos_bytes.len(), 0, 1, 4, 4, 13), + ]), + ) + .await; + let error = commit_table_response( + &store, + &trusted_table_commit_backend(&backend), + "warehouse", + &namespace, + "events", + serde_json::from_value(serde_json::json!({ + "requirements": [{"type": "assert-ref-snapshot-id", "ref": "main", "snapshot-id": 13}], + "updates": [ + { + "action": "add-snapshot", + "snapshot": { + "snapshot-id": 14, + "parent-snapshot-id": 13, + "sequence-number": 5, + "timestamp-ms": 5000, + "manifest-list": list_14, + "summary": {"operation": "delete"} + } + }, + {"action": "set-snapshot-ref", "ref-name": "main", "snapshot-id": 14, "type": "branch"} + ] + })) + .unwrap(), + ) + .await + .expect_err("deleting a non-live file on delete must fail with 409"); + assert_eq!(error.code(), &S3ErrorCode::Custom(ICEBERG_ERROR_COMMIT_FAILED.into())); + assert_eq!(error.status_code(), Some(StatusCode::CONFLICT)); + assert_eq!( + error.message(), + Some("commit requirement failed: deleted file is not in the parent snapshot") + ); + let unchanged = store.load_table("warehouse", "analytics", "events").await.unwrap().unwrap(); + assert_eq!(unchanged.metadata_location, entry_13.metadata_location); + assert_eq!(unchanged.generation, entry_13.generation); +} + +#[tokio::test] +async fn noop_and_root_overwrite_replace_wap_and_v1_empty_manifests_commits() { + use crate::table_catalog::test_support::manifest_list_avro_entries_with_min_sequences; + + // 1. Empty-table (parent = None) 0-change "overwrite" and 0-change "replace". + for operation in ["overwrite", "replace"] { + let store = TestTableCatalogStore::default(); + let backend = TestTableCatalogObjectBackend::content_addressed(); + let namespace = crate::table_catalog::Namespace::parse("analytics").unwrap(); + let created = create_standard_events_table(&store, &backend, &namespace).await; + let location = created.metadata["location"].as_str().unwrap(); + let list = format!("{location}/metadata/snap-10.avro"); + backend + .put_bytes( + "warehouse", + &test_snapshot_object_key("warehouse", &list), + test_manifest_list_avro_bytes(&[], 1, 10), + ) + .await; + let committed = commit_table_response( + &store, + &trusted_table_commit_backend(&backend), + "warehouse", + &namespace, + "events", + serde_json::from_value(serde_json::json!({ + "requirements": [{"type": "assert-ref-snapshot-id", "ref": "main", "snapshot-id": null}], + "updates": [ + { + "action": "add-snapshot", + "snapshot": { + "snapshot-id": 10, + "sequence-number": 1, + "timestamp-ms": 1000, + "manifest-list": list, + "summary": {"operation": operation} + } + }, + {"action": "set-snapshot-ref", "ref-name": "main", "snapshot-id": 10, "type": "branch"} + ] + })) + .unwrap(), + ) + .await + .unwrap_or_else(|err| panic!("empty-table 0-change {operation} should succeed: {err}")); + assert_eq!(committed.metadata["current-snapshot-id"], 10); + } + + // 2. Empty-table mutating "overwrite", populated 0-change "overwrite", WAP stageOnly(), and atomic REPLACE TABLE. + let store = TestTableCatalogStore::default(); + let backend = TestTableCatalogObjectBackend::content_addressed(); + let namespace = crate::table_catalog::Namespace::parse("analytics").unwrap(); + let created = create_standard_events_table(&store, &backend, &namespace).await; + let location = created.metadata["location"].as_str().unwrap(); + + let d1 = format!("{location}/data/part-10.parquet"); + let manifest_10 = format!("{location}/metadata/manifest-10.avro"); + let list_10 = format!("{location}/metadata/snap-10.avro"); + seed_test_manifest(&backend, "warehouse", &manifest_10, &[(&d1, 0, 1, 10, 1)]).await; + seed_test_manifest_list(&backend, "warehouse", &list_10, &[&manifest_10], 1, 10).await; + let root_overwrite = commit_table_response( + &store, + &trusted_table_commit_backend(&backend), + "warehouse", + &namespace, + "events", + serde_json::from_value(serde_json::json!({ + "requirements": [{"type": "assert-ref-snapshot-id", "ref": "main", "snapshot-id": null}], + "updates": [ + { + "action": "add-snapshot", + "snapshot": { + "snapshot-id": 10, + "sequence-number": 1, + "timestamp-ms": 1000, + "manifest-list": list_10, + "summary": {"operation": "overwrite"} + } + }, + {"action": "set-snapshot-ref", "ref-name": "main", "snapshot-id": 10, "type": "branch"} + ] + })) + .unwrap(), + ) + .await + .expect("empty-table mutating overwrite should succeed"); + assert_eq!(root_overwrite.metadata["current-snapshot-id"], 10); + + // Populated 0-change "overwrite" (inherited manifest S11 + status=0 rewritten manifest S12). + let list_11 = format!("{location}/metadata/snap-11.avro"); + seed_test_manifest_list(&backend, "warehouse", &list_11, &[&manifest_10], 1, 10).await; + commit_table_response( + &store, + &trusted_table_commit_backend(&backend), + "warehouse", + &namespace, + "events", + serde_json::from_value(serde_json::json!({ + "requirements": [{"type": "assert-ref-snapshot-id", "ref": "main", "snapshot-id": 10}], + "updates": [ + { + "action": "add-snapshot", + "snapshot": { + "snapshot-id": 11, + "parent-snapshot-id": 10, + "sequence-number": 2, + "timestamp-ms": 2000, + "manifest-list": list_11, + "summary": {"operation": "overwrite"} + } + }, + {"action": "set-snapshot-ref", "ref-name": "main", "snapshot-id": 11, "type": "branch"} + ] + })) + .unwrap(), + ) + .await + .expect("populated 0-change overwrite inheriting manifest should succeed"); + + let manifest_12 = format!("{location}/metadata/manifest-12.avro"); + let bytes_12 = test_manifest_avro_bytes(&[(&d1, 0, 0, 10, 1)]); + backend + .put_bytes("warehouse", &test_snapshot_object_key("warehouse", &manifest_12), bytes_12.clone()) + .await; + let list_12 = format!("{location}/metadata/snap-12.avro"); + backend + .put_bytes( + "warehouse", + &test_snapshot_object_key("warehouse", &list_12), + manifest_list_avro_entries_with_min_sequences(&[(&manifest_12, bytes_12.len(), 0, 0, 3, 1, 12)]), + ) + .await; + commit_table_response( + &store, + &trusted_table_commit_backend(&backend), + "warehouse", + &namespace, + "events", + serde_json::from_value(serde_json::json!({ + "requirements": [{"type": "assert-ref-snapshot-id", "ref": "main", "snapshot-id": 11}], + "updates": [ + { + "action": "add-snapshot", + "snapshot": { + "snapshot-id": 12, + "parent-snapshot-id": 11, + "sequence-number": 3, + "timestamp-ms": 3000, + "manifest-list": list_12, + "summary": {"operation": "overwrite"} + } + }, + {"action": "set-snapshot-ref", "ref-name": "main", "snapshot-id": 12, "type": "branch"} + ] + })) + .unwrap(), + ) + .await + .expect("populated 0-change overwrite with status=0 manifest should succeed"); + + // Staging a parentless snapshot leaves the current branch head in place. + let staged_file = format!("{location}/data/staged-13.parquet"); + let list_13 = format!("{location}/metadata/snap-13.avro"); + seed_test_snapshot_manifest(&backend, "warehouse", &list_13, 13, 4, &[(&staged_file, 0, 1, 13, 4)]).await; + let wap_commit = commit_table_response( + &store, + &trusted_table_commit_backend(&backend), + "warehouse", + &namespace, + "events", + serde_json::from_value(serde_json::json!({ + "updates": [{ + "action": "add-snapshot", + "snapshot": { + "snapshot-id": 13, + "sequence-number": 4, + "timestamp-ms": 4000, + "manifest-list": list_13, + "summary": {"operation": "overwrite"} + } + }] + })) + .unwrap(), + ) + .await + .expect("staging a root snapshot should preserve main"); + assert_eq!(wap_commit.metadata["current-snapshot-id"], 12); + assert_eq!(wap_commit.metadata["refs"]["main"]["snapshot-id"], 12); + + // Atomic REPLACE TABLE: stale assert-ref-snapshot-id fails with 409; matching requirement succeeds with 200. + let replacement_file = format!("{location}/data/replacement-14.parquet"); + let list_14 = format!("{location}/metadata/snap-14.avro"); + seed_test_snapshot_manifest(&backend, "warehouse", &list_14, 14, 5, &[(&replacement_file, 0, 1, 14, 5)]).await; + let before_replace = store.load_table("warehouse", "analytics", "events").await.unwrap().unwrap(); + for stale_ref in [serde_json::Value::Null, serde_json::Value::from(10)] { + let error = commit_table_response( + &store, + &trusted_table_commit_backend(&backend), + "warehouse", + &namespace, + "events", + serde_json::from_value(serde_json::json!({ + "requirements": [{"type": "assert-ref-snapshot-id", "ref": "main", "snapshot-id": stale_ref}], + "updates": [ + {"action": "remove-snapshot-ref", "ref-name": "main"}, + { + "action": "add-snapshot", + "snapshot": { + "snapshot-id": 14, + "sequence-number": 5, + "timestamp-ms": 5000, + "manifest-list": list_14, + "summary": {"operation": "overwrite"} + } + }, + {"action": "set-snapshot-ref", "ref-name": "main", "snapshot-id": 14, "type": "branch"} + ] + })) + .unwrap(), + ) + .await + .expect_err("stale assert-ref-snapshot-id on REPLACE TABLE must conflict"); + assert_eq!(error.code(), &S3ErrorCode::Custom(ICEBERG_ERROR_COMMIT_FAILED.into())); + assert_eq!(error.status_code(), Some(StatusCode::CONFLICT)); + } + let unchanged = store.load_table("warehouse", "analytics", "events").await.unwrap().unwrap(); + assert_eq!(unchanged.metadata_location, before_replace.metadata_location); + + let replaced = commit_table_response( + &store, + &trusted_table_commit_backend(&backend), + "warehouse", + &namespace, + "events", + serde_json::from_value(serde_json::json!({ + "requirements": [{"type": "assert-ref-snapshot-id", "ref": "main", "snapshot-id": 12}], + "updates": [ + {"action": "remove-snapshot-ref", "ref-name": "main"}, + { + "action": "add-snapshot", + "snapshot": { + "snapshot-id": 14, + "sequence-number": 5, + "timestamp-ms": 5000, + "manifest-list": list_14, + "summary": {"operation": "overwrite"} + } + }, + {"action": "set-snapshot-ref", "ref-name": "main", "snapshot-id": 14, "type": "branch"} + ] + })) + .unwrap(), + ) + .await + .expect("atomic REPLACE TABLE with matching assert-ref-snapshot-id should succeed"); + assert_eq!(replaced.metadata["current-snapshot-id"], 14); + assert_eq!(replaced.metadata["refs"]["main"]["snapshot-id"], 14); + let after_replace = store.load_table("warehouse", "analytics", "events").await.unwrap().unwrap(); + let replaced_live = load_snapshot_live_files(&backend, "warehouse", &after_replace, &replaced.metadata, Some(14)) + .await + .unwrap(); + assert_eq!(replaced_live.live_file_count(), 1); + assert!(replaced_live.data_files.contains_key(&replacement_file)); + + // 3. Iceberg v1 empty inline "manifests": []. + create_table_response( + &store, + &trusted_table_commit_backend(&backend), + "warehouse", + &namespace, + serde_json::from_value(serde_json::json!({ + "name": "legacy_v1", + "properties": {"format-version": "1"}, + "schema": {"type": "struct", "fields": [{"id": 1, "name": "id", "required": true, "type": "long"}]} + })) + .unwrap(), + true, + ) + .await + .expect("v1 table should create"); + let v1_commit = commit_table_response( + &store, + &trusted_table_commit_backend(&backend), + "warehouse", + &namespace, + "legacy_v1", + serde_json::from_value(serde_json::json!({ + "updates": [ + { + "action": "add-snapshot", + "snapshot": { + "snapshot-id": 10, + "timestamp-ms": 1000, + "manifests": [], + "summary": {"operation": "delete"} + } + }, + {"action": "set-snapshot-ref", "ref-name": "main", "snapshot-id": 10, "type": "branch"} + ] + })) + .unwrap(), + ) + .await + .expect("Iceberg v1 empty inline manifests array should commit"); + assert_eq!(v1_commit.metadata["current-snapshot-id"], 10); +} + +#[tokio::test] +async fn merge_append_prunes_obsolete_delete_files_and_rejects_active_delete_pruning() { + use crate::table_catalog::test_support::manifest_list_avro_entries_with_min_sequences; + + let store = TestTableCatalogStore::default(); + let backend = TestTableCatalogObjectBackend::content_addressed(); + let namespace = crate::table_catalog::Namespace::parse("analytics").unwrap(); + let created = create_standard_events_table(&store, &backend, &namespace).await; + let location = created.metadata["location"].as_str().unwrap(); + + // S10 (seq=1): append D1 (seq=1). + let d1 = format!("{location}/data/d1.parquet"); + let m10 = format!("{location}/metadata/m10.avro"); + let l10 = format!("{location}/metadata/snap-10.avro"); + seed_test_manifest(&backend, "warehouse", &m10, &[(&d1, 0, 1, 10, 1)]).await; + seed_test_manifest_list(&backend, "warehouse", &l10, &[&m10], 1, 10).await; + commit_table_response( + &store, + &trusted_table_commit_backend(&backend), + "warehouse", + &namespace, + "events", + serde_json::from_value(serde_json::json!({ + "updates": [ + {"action": "add-snapshot", "snapshot": { + "snapshot-id": 10, "sequence-number": 1, "timestamp-ms": 1000, + "manifest-list": l10, "summary": {"operation": "append"} + }}, + {"action": "set-snapshot-ref", "ref-name": "main", "snapshot-id": 10, "type": "branch"} + ] + })) + .unwrap(), + ) + .await + .unwrap(); + let m10_len = backend + .state + .lock() + .await + .objects + .get(&("warehouse".to_string(), test_snapshot_object_key("warehouse", &m10))) + .unwrap() + .data + .len(); + + // S11 (seq=2): MoR delete adding Del1 (seq=2), inheriting D1. + let del1 = format!("{location}/delete/del1.parquet"); + let m11_del = format!("{location}/metadata/m11-del.avro"); + let m11_del_bytes = test_manifest_avro_bytes(&[(&del1, 1, 1, 11, 2)]); + backend + .put_bytes("warehouse", &test_snapshot_object_key("warehouse", &m11_del), m11_del_bytes.clone()) + .await; + seed_test_manifest_data_files(&backend, "warehouse", &[(&del1, 1, 1, 11, 2)]).await; + let l11 = format!("{location}/metadata/snap-11.avro"); + backend + .put_bytes( + "warehouse", + &test_snapshot_object_key("warehouse", &l11), + manifest_list_avro_entries_with_min_sequences(&[ + (&m10, m10_len, 0, 0, 1, 1, 10), + (&m11_del, m11_del_bytes.len(), 0, 1, 2, 2, 11), + ]), + ) + .await; + commit_table_response( + &store, + &trusted_table_commit_backend(&backend), + "warehouse", + &namespace, + "events", + serde_json::from_value(serde_json::json!({ + "updates": [ + {"action": "add-snapshot", "snapshot": { + "snapshot-id": 11, "parent-snapshot-id": 10, "sequence-number": 2, "timestamp-ms": 2000, + "manifest-list": l11, "summary": {"operation": "delete"} + }}, + {"action": "set-snapshot-ref", "ref-name": "main", "snapshot-id": 11, "type": "branch"} + ] + })) + .unwrap(), + ) + .await + .unwrap(); + + // S12 (seq=3): delete D1 via status=2 while inheriting Del1 (seq=2). + let m12_data = format!("{location}/metadata/m12-data.avro"); + let m12_data_bytes = test_manifest_avro_bytes(&[(&d1, 0, 2, 12, 1)]); + backend + .put_bytes("warehouse", &test_snapshot_object_key("warehouse", &m12_data), m12_data_bytes.clone()) + .await; + let l12 = format!("{location}/metadata/snap-12.avro"); + backend + .put_bytes( + "warehouse", + &test_snapshot_object_key("warehouse", &l12), + manifest_list_avro_entries_with_min_sequences(&[ + (&m12_data, m12_data_bytes.len(), 0, 0, 3, 1, 12), + (&m11_del, m11_del_bytes.len(), 0, 1, 2, 2, 11), + ]), + ) + .await; + commit_table_response( + &store, + &trusted_table_commit_backend(&backend), + "warehouse", + &namespace, + "events", + serde_json::from_value(serde_json::json!({ + "updates": [ + {"action": "add-snapshot", "snapshot": { + "snapshot-id": 12, "parent-snapshot-id": 11, "sequence-number": 3, "timestamp-ms": 3000, + "manifest-list": l12, "summary": {"operation": "delete"} + }}, + {"action": "set-snapshot-ref", "ref-name": "main", "snapshot-id": 12, "type": "branch"} + ] + })) + .unwrap(), + ) + .await + .unwrap(); + + // S13 (seq=4): append D2 (seq=4), dropping pure-DELETED m12_data and inheriting Del1 (seq=2). + let d2 = format!("{location}/data/d2.parquet"); + let m13_data = format!("{location}/metadata/m13-data.avro"); + let m13_data_bytes = test_manifest_avro_bytes(&[(&d2, 0, 1, 13, 4)]); + backend + .put_bytes("warehouse", &test_snapshot_object_key("warehouse", &m13_data), m13_data_bytes.clone()) + .await; + seed_test_manifest_data_files(&backend, "warehouse", &[(&d2, 0, 1, 13, 4)]).await; + let l13 = format!("{location}/metadata/snap-13.avro"); + backend + .put_bytes( + "warehouse", + &test_snapshot_object_key("warehouse", &l13), + manifest_list_avro_entries_with_min_sequences(&[ + (&m13_data, m13_data_bytes.len(), 0, 0, 4, 4, 13), + (&m11_del, m11_del_bytes.len(), 0, 1, 2, 2, 11), + ]), + ) + .await; + commit_table_response( + &store, + &trusted_table_commit_backend(&backend), + "warehouse", + &namespace, + "events", + serde_json::from_value(serde_json::json!({ + "updates": [ + {"action": "add-snapshot", "snapshot": { + "snapshot-id": 13, "parent-snapshot-id": 12, "sequence-number": 4, "timestamp-ms": 4000, + "manifest-list": l13, "summary": {"operation": "append"} + }}, + {"action": "set-snapshot-ref", "ref-name": "main", "snapshot-id": 13, "type": "branch"} + ] + })) + .unwrap(), + ) + .await + .expect("append dropping pure-DELETED parent manifest should commit"); + + // S14 (seq=5): add active delete file Del2 (seq=5 >= min_data_seq=4). + let del2 = format!("{location}/delete/del2.parquet"); + let m14_del = format!("{location}/metadata/m14-del.avro"); + let m14_del_bytes = test_manifest_avro_bytes(&[(&del2, 1, 1, 14, 5)]); + backend + .put_bytes("warehouse", &test_snapshot_object_key("warehouse", &m14_del), m14_del_bytes.clone()) + .await; + seed_test_manifest_data_files(&backend, "warehouse", &[(&del2, 1, 1, 14, 5)]).await; + let l14 = format!("{location}/metadata/snap-14.avro"); + backend + .put_bytes( + "warehouse", + &test_snapshot_object_key("warehouse", &l14), + manifest_list_avro_entries_with_min_sequences(&[ + (&m13_data, m13_data_bytes.len(), 0, 0, 4, 4, 13), + (&m11_del, m11_del_bytes.len(), 0, 1, 2, 2, 11), + (&m14_del, m14_del_bytes.len(), 0, 1, 5, 5, 14), + ]), + ) + .await; + commit_table_response( + &store, + &trusted_table_commit_backend(&backend), + "warehouse", + &namespace, + "events", + serde_json::from_value(serde_json::json!({ + "updates": [ + {"action": "add-snapshot", "snapshot": { + "snapshot-id": 14, "parent-snapshot-id": 13, "sequence-number": 5, "timestamp-ms": 5000, + "manifest-list": l14, "summary": {"operation": "delete"} + }}, + {"action": "set-snapshot-ref", "ref-name": "main", "snapshot-id": 14, "type": "branch"} + ] + })) + .unwrap(), + ) + .await + .unwrap(); + let before_15 = store.load_table("warehouse", "analytics", "events").await.unwrap().unwrap(); + + // Negative: pruning active Del2 (seq=5 >= min_data_seq=4) must fail with 400. + let d3 = format!("{location}/data/d3.parquet"); + let m15_new_data = format!("{location}/metadata/m15-data.avro"); + let m15_new_data_bytes = test_manifest_avro_bytes(&[(&d3, 0, 1, 15, 6)]); + backend + .put_bytes( + "warehouse", + &test_snapshot_object_key("warehouse", &m15_new_data), + m15_new_data_bytes.clone(), + ) + .await; + seed_test_manifest_data_files(&backend, "warehouse", &[(&d3, 0, 1, 15, 6)]).await; + + let m15_bad_del = format!("{location}/metadata/m15-bad-del.avro"); + let m15_bad_del_bytes = test_manifest_avro_bytes(&[(&del1, 1, 0, 11, 2), (&del2, 1, 2, 15, 5)]); + backend + .put_bytes( + "warehouse", + &test_snapshot_object_key("warehouse", &m15_bad_del), + m15_bad_del_bytes.clone(), + ) + .await; + let l15_bad = format!("{location}/metadata/snap-15-bad.avro"); + backend + .put_bytes( + "warehouse", + &test_snapshot_object_key("warehouse", &l15_bad), + manifest_list_avro_entries_with_min_sequences(&[ + (&m13_data, m13_data_bytes.len(), 0, 0, 4, 4, 13), + (&m15_new_data, m15_new_data_bytes.len(), 0, 0, 6, 6, 15), + (&m15_bad_del, m15_bad_del_bytes.len(), 0, 1, 6, 2, 15), + ]), + ) + .await; + let bad_error = commit_table_response( + &store, + &trusted_table_commit_backend(&backend), + "warehouse", + &namespace, + "events", + serde_json::from_value(serde_json::json!({ + "updates": [ + {"action": "add-snapshot", "snapshot": { + "snapshot-id": 15, "parent-snapshot-id": 14, "sequence-number": 6, "timestamp-ms": 6000, + "manifest-list": l15_bad, "summary": {"operation": "append"} + }}, + {"action": "set-snapshot-ref", "ref-name": "main", "snapshot-id": 15, "type": "branch"} + ] + })) + .unwrap(), + ) + .await + .expect_err("append must reject deleting an active delete file"); + assert_eq!(bad_error.code(), &S3ErrorCode::InvalidRequest); + assert_eq!(bad_error.message(), Some("append snapshot cannot delete active delete files")); + assert_eq!( + store + .load_table("warehouse", "analytics", "events") + .await + .unwrap() + .unwrap() + .metadata_location, + before_15.metadata_location + ); + + // Boundary negative: del_seq == min_data_seq (Del_eq at seq=1 when min_data_seq == 1). + let store_eq = TestTableCatalogStore::default(); + let backend_eq = TestTableCatalogObjectBackend::content_addressed(); + let created_eq = create_standard_events_table(&store_eq, &backend_eq, &namespace).await; + let loc_eq = created_eq.metadata["location"].as_str().unwrap(); + let d_eq = format!("{loc_eq}/data/d-eq.parquet"); + let del_eq = format!("{loc_eq}/delete/del-eq.parquet"); + let m_eq_data = format!("{loc_eq}/metadata/m-eq-data.avro"); + let m_eq_del = format!("{loc_eq}/metadata/m-eq-del.avro"); + let m_eq_data_bytes = test_manifest_avro_bytes(&[(&d_eq, 0, 1, 10, 1)]); + let m_eq_del_bytes = test_manifest_avro_bytes(&[(&del_eq, 1, 1, 10, 1)]); + backend_eq + .put_bytes("warehouse", &test_snapshot_object_key("warehouse", &m_eq_data), m_eq_data_bytes.clone()) + .await; + backend_eq + .put_bytes("warehouse", &test_snapshot_object_key("warehouse", &m_eq_del), m_eq_del_bytes.clone()) + .await; + seed_test_manifest_data_files(&backend_eq, "warehouse", &[(&d_eq, 0, 1, 10, 1), (&del_eq, 1, 1, 10, 1)]).await; + let l_eq_10 = format!("{loc_eq}/metadata/snap-10.avro"); + backend_eq + .put_bytes( + "warehouse", + &test_snapshot_object_key("warehouse", &l_eq_10), + manifest_list_avro_entries_with_min_sequences(&[ + (&m_eq_data, m_eq_data_bytes.len(), 0, 0, 1, 1, 10), + (&m_eq_del, m_eq_del_bytes.len(), 0, 1, 1, 1, 10), + ]), + ) + .await; + commit_table_response( + &store_eq, + &trusted_table_commit_backend(&backend_eq), + "warehouse", + &namespace, + "events", + serde_json::from_value(serde_json::json!({ + "updates": [ + {"action": "add-snapshot", "snapshot": { + "snapshot-id": 10, "sequence-number": 1, "timestamp-ms": 1000, + "manifest-list": l_eq_10, "summary": {"operation": "overwrite"} + }}, + {"action": "set-snapshot-ref", "ref-name": "main", "snapshot-id": 10, "type": "branch"} + ] + })) + .unwrap(), + ) + .await + .unwrap(); + let m_eq_prune = format!("{loc_eq}/metadata/m-eq-prune.avro"); + let m_eq_prune_bytes = test_manifest_avro_bytes(&[(&del_eq, 1, 2, 11, 1)]); + backend_eq + .put_bytes("warehouse", &test_snapshot_object_key("warehouse", &m_eq_prune), m_eq_prune_bytes.clone()) + .await; + let l_eq_11 = format!("{loc_eq}/metadata/snap-11.avro"); + backend_eq + .put_bytes( + "warehouse", + &test_snapshot_object_key("warehouse", &l_eq_11), + manifest_list_avro_entries_with_min_sequences(&[ + (&m_eq_data, m_eq_data_bytes.len(), 0, 0, 1, 1, 10), + (&m_eq_prune, m_eq_prune_bytes.len(), 0, 1, 2, 1, 11), + ]), + ) + .await; + let eq_err = commit_table_response( + &store_eq, + &trusted_table_commit_backend(&backend_eq), + "warehouse", + &namespace, + "events", + serde_json::from_value(serde_json::json!({ + "updates": [ + {"action": "add-snapshot", "snapshot": { + "snapshot-id": 11, "parent-snapshot-id": 10, "sequence-number": 2, "timestamp-ms": 2000, + "manifest-list": l_eq_11, "summary": {"operation": "append"} + }}, + {"action": "set-snapshot-ref", "ref-name": "main", "snapshot-id": 11, "type": "branch"} + ] + })) + .unwrap(), + ) + .await + .expect_err("append must reject deleting a delete file with del_seq == min_data_seq"); + assert_eq!(eq_err.code(), &S3ErrorCode::InvalidRequest); + assert_eq!(eq_err.message(), Some("append snapshot cannot delete active delete files")); + + // Positive MergeAppend: pruning obsolete Del1 (seq=2 < min_data_seq=4) while preserving D2 and active Del2 succeeds. + let m15_ok_del = format!("{location}/metadata/m15-ok-del.avro"); + let m15_ok_del_bytes = test_manifest_avro_bytes(&[(&del1, 1, 2, 15, 2), (&del2, 1, 0, 14, 5)]); + backend + .put_bytes("warehouse", &test_snapshot_object_key("warehouse", &m15_ok_del), m15_ok_del_bytes.clone()) + .await; + let l15_ok = format!("{location}/metadata/snap-15-ok.avro"); + backend + .put_bytes( + "warehouse", + &test_snapshot_object_key("warehouse", &l15_ok), + manifest_list_avro_entries_with_min_sequences(&[ + (&m13_data, m13_data_bytes.len(), 0, 0, 4, 4, 13), + (&m15_new_data, m15_new_data_bytes.len(), 0, 0, 6, 6, 15), + (&m15_ok_del, m15_ok_del_bytes.len(), 0, 1, 6, 2, 15), + ]), + ) + .await; + let ok_commit = commit_table_response( + &store, + &trusted_table_commit_backend(&backend), + "warehouse", + &namespace, + "events", + serde_json::from_value(serde_json::json!({ + "updates": [ + {"action": "add-snapshot", "snapshot": { + "snapshot-id": 15, "parent-snapshot-id": 14, "sequence-number": 6, "timestamp-ms": 6000, + "manifest-list": l15_ok, "summary": {"operation": "append"} + }}, + {"action": "set-snapshot-ref", "ref-name": "main", "snapshot-id": 15, "type": "branch"} + ] + })) + .unwrap(), + ) + .await + .expect("MergeAppend pruning obsolete delete file (seq < min_data_seq) should succeed"); + assert_eq!(ok_commit.metadata["current-snapshot-id"], 15); + let after_15 = store.load_table("warehouse", "analytics", "events").await.unwrap().unwrap(); + let live_15 = load_snapshot_live_files(&backend, "warehouse", &after_15, &ok_commit.metadata, Some(15)) + .await + .unwrap(); + assert_eq!(live_15.data_files.len(), 2); + assert_eq!(live_15.delete_files.len(), 1); + assert!(live_15.delete_files.contains_key(&del2)); + assert!(!live_15.delete_files.contains_key(&del1)); +} + +#[tokio::test] +async fn snapshot_commit_rejects_silent_truncation_tampered_existing_and_disguised_operations() { + use crate::table_catalog::test_support::manifest_list_avro_entries_with_min_sequences; + + let store = TestTableCatalogStore::default(); + let backend = TestTableCatalogObjectBackend::content_addressed(); + let namespace = crate::table_catalog::Namespace::parse("analytics").unwrap(); + let created = create_standard_events_table(&store, &backend, &namespace).await; + let location = created.metadata["location"].as_str().unwrap(); + + // Seed parent snapshot 10 with two live data files D1 and D2. + let d1 = format!("{location}/data/part-1.parquet"); + let d2 = format!("{location}/data/part-2.parquet"); + let d3 = format!("{location}/data/part-3.parquet"); + let forged = format!("{location}/data/forged.parquet"); + let del_file = format!("{location}/delete/del-3.parquet"); + for path in [&d3, &forged, &del_file] { + backend + .put_bytes("warehouse", &test_snapshot_object_key("warehouse", path), b"data".to_vec()) + .await; + } + let m10_a = format!("{location}/metadata/m10-a.avro"); + let m10_b = format!("{location}/metadata/m10-b.avro"); + seed_test_manifest(&backend, "warehouse", &m10_a, &[(&d1, 0, 1, 10, 1)]).await; + seed_test_manifest(&backend, "warehouse", &m10_b, &[(&d2, 0, 1, 10, 1)]).await; + let l10 = format!("{location}/metadata/snap-10.avro"); + seed_test_manifest_list(&backend, "warehouse", &l10, &[&m10_a, &m10_b], 1, 10).await; + commit_table_response( + &store, + &trusted_table_commit_backend(&backend), + "warehouse", + &namespace, + "events", + serde_json::from_value(serde_json::json!({ + "updates": [ + {"action": "add-snapshot", "snapshot": { + "snapshot-id": 10, "sequence-number": 1, "timestamp-ms": 1000, + "manifest-list": l10, "summary": {"operation": "append"} + }}, + {"action": "set-snapshot-ref", "ref-name": "main", "snapshot-id": 10, "type": "branch"} + ] + })) + .unwrap(), + ) + .await + .unwrap(); + let baseline = store.load_table("warehouse", "analytics", "events").await.unwrap().unwrap(); + let m10_a_len = backend + .state + .lock() + .await + .objects + .get(&("warehouse".to_string(), test_snapshot_object_key("warehouse", &m10_a))) + .unwrap() + .data + .len(); + let m10_b_len = backend + .state + .lock() + .await + .objects + .get(&("warehouse".to_string(), test_snapshot_object_key("warehouse", &m10_b))) + .unwrap() + .data + .len(); + + let put_manifest = |name: &str, bytes: Vec| { + let path = format!("{location}/metadata/{name}.avro"); + let len = bytes.len(); + let backend = backend.clone(); + async move { + backend + .put_bytes("warehouse", &test_snapshot_object_key("warehouse", &path), bytes) + .await; + (path, len) + } + }; + let put_list = |name: &str, entries: &[(&str, usize, i32, i32, i64, i64, i64)]| { + let path = format!("{location}/metadata/{name}.avro"); + let bytes = manifest_list_avro_entries_with_min_sequences(entries); + let backend = backend.clone(); + async move { + backend + .put_bytes("warehouse", &test_snapshot_object_key("warehouse", &path), bytes) + .await; + path + } + }; + + let empty_list = put_list("snap-empty", &[]).await; + let partial_existing_list = put_list("snap-partial-existing", &[(&m10_a, m10_a_len, 0, 0, 1, 1, 10)]).await; + let (m_add_d3, m_add_d3_len) = put_manifest("m-add-d3", test_manifest_avro_bytes(&[(&d3, 0, 1, 11, 2)])).await; + let (m_add_del, m_add_del_len) = put_manifest("m-add-del", test_manifest_avro_bytes(&[(&del_file, 1, 1, 11, 2)])).await; + let partial_append_list = put_list( + "snap-partial-append", + &[(&m10_a, m10_a_len, 0, 0, 1, 1, 10), (&m_add_d3, m_add_d3_len, 0, 0, 2, 2, 11)], + ) + .await; + let add_only_full_list = put_list( + "snap-add-only-full", + &[ + (&m10_a, m10_a_len, 0, 0, 1, 1, 10), + (&m10_b, m10_b_len, 0, 0, 1, 1, 10), + (&m_add_d3, m_add_d3_len, 0, 0, 2, 2, 11), + ], + ) + .await; + let add_only_root_list = put_list("snap-add-only-root", &[(&m_add_d3, m_add_d3_len, 0, 0, 2, 2, 11)]).await; + let add_del_root_list = put_list("snap-add-del-root", &[(&m_add_del, m_add_del_len, 0, 1, 2, 2, 11)]).await; + let mixed_root_list = put_list( + "snap-mixed-root", + &[ + (&m_add_d3, m_add_d3_len, 0, 0, 2, 2, 11), + (&m_add_del, m_add_del_len, 0, 1, 2, 2, 11), + ], + ) + .await; + + let (m_forged_existing, m_forged_existing_len) = + put_manifest("m-forged-existing", test_manifest_avro_bytes(&[(&forged, 0, 0, 10, 1)])).await; + let forged_noop_list = put_list( + "snap-forged-noop", + &[ + (&m10_a, m10_a_len, 0, 0, 1, 1, 10), + (&m_forged_existing, m_forged_existing_len, 0, 0, 2, 1, 11), + ], + ) + .await; + let forged_root_list = put_list("snap-forged-root", &[(&m_forged_existing, m_forged_existing_len, 0, 0, 2, 1, 11)]).await; + let forged_root_mutating_list = put_list( + "snap-forged-root-mut", + &[ + (&m_forged_existing, m_forged_existing_len, 0, 0, 2, 1, 11), + (&m_add_d3, m_add_d3_len, 0, 0, 2, 2, 11), + ], + ) + .await; + + let tampered_bytes = manifest_rewrite_metadata_bytes(test_manifest_avro_bytes(&[(&d1, 0, 0, 10, 1)]), "record_count"); + let (m_tampered_d1, m_tampered_d1_len) = put_manifest("m-tampered-d1", tampered_bytes).await; + let tampered_noop_list = put_list( + "snap-tampered-noop", + &[ + (&m_tampered_d1, m_tampered_d1_len, 0, 0, 2, 1, 11), + (&m10_b, m10_b_len, 0, 0, 1, 1, 10), + ], + ) + .await; + let tampered_append_list = put_list( + "snap-tampered-append", + &[ + (&m_tampered_d1, m_tampered_d1_len, 0, 0, 2, 1, 11), + (&m10_b, m10_b_len, 0, 0, 1, 1, 10), + (&m_add_d3, m_add_d3_len, 0, 0, 2, 2, 11), + ], + ) + .await; + + let (m_del_d2, m_del_d2_len) = put_manifest("m-del-d2", test_manifest_avro_bytes(&[(&d2, 0, 2, 11, 1)])).await; + let tampered_mutating_delete_list = put_list( + "snap-tampered-mut-del", + &[ + (&m_tampered_d1, m_tampered_d1_len, 0, 0, 2, 1, 11), + (&m_del_d2, m_del_d2_len, 0, 0, 2, 1, 11), + ], + ) + .await; + let tampered_mutating_overwrite_list = put_list( + "snap-tampered-mut-ow", + &[ + (&m_tampered_d1, m_tampered_d1_len, 0, 0, 2, 1, 11), + (&m_add_d3, m_add_d3_len, 0, 0, 2, 2, 11), + ], + ) + .await; + + let (m_forged_del_data, m_forged_del_data_len) = + put_manifest("m-forged-del-data", test_manifest_avro_bytes(&[(&d1, 0, 2, 11, 1)])).await; + let forged_del_data_list = + put_list("snap-forged-del-data", &[(&m_forged_del_data, m_forged_del_data_len, 0, 0, 2, 1, 11)]).await; + let (m_forged_del_delete, m_forged_del_delete_len) = + put_manifest("m-forged-del-delete", test_manifest_avro_bytes(&[(&del_file, 1, 2, 11, 1)])).await; + let forged_del_delete_list = put_list( + "snap-forged-del-delete", + &[(&m_forged_del_delete, m_forged_del_delete_len, 0, 1, 2, 1, 11)], + ) + .await; + + // Content-confusion: deleting live DataFile d1 using PositionDelete content=1 status=2. + let (m_wrong_content_del, m_wrong_content_del_len) = + put_manifest("m-wrong-content-del", test_manifest_avro_bytes(&[(&d1, 1, 2, 11, 1)])).await; + let wrong_content_list = put_list( + "snap-wrong-content", + &[ + (&m_wrong_content_del, m_wrong_content_del_len, 0, 1, 2, 1, 11), + (&m10_b, m10_b_len, 0, 0, 1, 1, 10), + ], + ) + .await; + + let cases = &[ + ( + "root-delete-adds-data-and-delete-files", + None, + "delete", + &mixed_root_list, + StatusCode::BAD_REQUEST, + "delete snapshot cannot add data files", + ), + ( + "delete-omits-untouched-data-file", + Some(10), + "delete", + &forged_del_data_list, + StatusCode::BAD_REQUEST, + "snapshot must retain or explicitly delete each live file in the parent snapshot", + ), + ( + "overwrite-omits-untouched-data-file", + Some(10), + "overwrite", + &partial_append_list, + StatusCode::BAD_REQUEST, + "snapshot must retain or explicitly delete each live file in the parent snapshot", + ), + ( + "replace-omits-untouched-data-file", + Some(10), + "replace", + &forged_del_data_list, + StatusCode::BAD_REQUEST, + "snapshot must retain or explicitly delete each live file in the parent snapshot", + ), + // Silent truncation via empty or partial manifest-list on populated delete, overwrite, append. + ( + "delete-empty-truncation", + Some(10), + "delete", + &empty_list, + StatusCode::BAD_REQUEST, + "no-op snapshot must preserve the parent snapshot's live files", + ), + ( + "delete-partial-truncation", + Some(10), + "delete", + &partial_existing_list, + StatusCode::BAD_REQUEST, + "no-op snapshot must preserve the parent snapshot's live files", + ), + ( + "overwrite-empty-truncation", + Some(10), + "overwrite", + &empty_list, + StatusCode::BAD_REQUEST, + "no-op snapshot must preserve the parent snapshot's live files", + ), + ( + "overwrite-partial-truncation", + Some(10), + "overwrite", + &partial_existing_list, + StatusCode::BAD_REQUEST, + "no-op snapshot must preserve the parent snapshot's live files", + ), + ( + "append-empty-truncation", + Some(10), + "append", + &empty_list, + StatusCode::BAD_REQUEST, + "append snapshot must preserve the parent snapshot's live files", + ), + ( + "append-partial-truncation", + Some(10), + "append", + &partial_append_list, + StatusCode::BAD_REQUEST, + "append snapshot must preserve the parent snapshot's live files", + ), + // Forged / tampered status=0 (EXISTING) across 0-change & mutating delete, overwrite, append, and parent=None. + ( + "delete-noop-forged-existing", + Some(10), + "delete", + &forged_noop_list, + StatusCode::BAD_REQUEST, + "no-op snapshot must preserve the parent snapshot's live files", + ), + ( + "delete-noop-tampered-existing", + Some(10), + "delete", + &tampered_noop_list, + StatusCode::BAD_REQUEST, + "no-op snapshot must preserve the parent snapshot's live files", + ), + ( + "delete-mutating-tampered-existing", + Some(10), + "delete", + &tampered_mutating_delete_list, + StatusCode::BAD_REQUEST, + "existing manifest entry must match a live file in the parent snapshot", + ), + ( + "overwrite-noop-forged-existing", + Some(10), + "overwrite", + &forged_noop_list, + StatusCode::BAD_REQUEST, + "no-op snapshot must preserve the parent snapshot's live files", + ), + ( + "overwrite-mutating-tampered-existing", + Some(10), + "overwrite", + &tampered_mutating_overwrite_list, + StatusCode::BAD_REQUEST, + "existing manifest entry must match a live file in the parent snapshot", + ), + ( + "append-tampered-existing", + Some(10), + "append", + &tampered_append_list, + StatusCode::BAD_REQUEST, + "append snapshot must preserve the parent snapshot's live files", + ), + ( + "root-delete-forged-existing", + None, + "delete", + &forged_root_list, + StatusCode::BAD_REQUEST, + "no-op snapshot must preserve the parent snapshot's live files", + ), + ( + "root-overwrite-noop-forged-existing", + None, + "overwrite", + &forged_root_list, + StatusCode::BAD_REQUEST, + "no-op snapshot must preserve the parent snapshot's live files", + ), + ( + "root-overwrite-mutating-forged-existing", + None, + "overwrite", + &forged_root_mutating_list, + StatusCode::BAD_REQUEST, + "existing manifest entry must match a live file in the parent snapshot", + ), + ( + "root-replace-forged-existing", + None, + "replace", + &forged_root_list, + StatusCode::BAD_REQUEST, + "manifest rewrite must preserve the parent snapshot's live files", + ), + ( + "root-append-forged-existing", + None, + "append", + &forged_root_list, + StatusCode::BAD_REQUEST, + "append snapshot must preserve the parent snapshot's live files", + ), + // Forged status=2 (DELETED) on parent=None -> 409 Conflict. + ( + "root-delete-forged-deleted", + None, + "delete", + &forged_del_data_list, + StatusCode::CONFLICT, + "commit requirement failed: deleted file is not in the parent snapshot", + ), + ( + "root-overwrite-forged-deleted", + None, + "overwrite", + &forged_del_data_list, + StatusCode::CONFLICT, + "commit requirement failed: deleted file is not in the parent snapshot", + ), + ( + "root-replace-forged-deleted", + None, + "replace", + &forged_del_data_list, + StatusCode::CONFLICT, + "commit requirement failed: deleted file is not in the parent snapshot", + ), + ( + "root-append-forged-deleted-delete-file", + None, + "append", + &forged_del_delete_list, + StatusCode::CONFLICT, + "commit requirement failed: deleted file is not in the parent snapshot", + ), + // Add-only data/delete commits disguised as "delete" or "replace". + ( + "populated-add-only-disguised-as-delete", + Some(10), + "delete", + &add_only_full_list, + StatusCode::BAD_REQUEST, + "delete snapshot cannot add data files", + ), + ( + "root-add-only-disguised-as-delete", + None, + "delete", + &add_only_root_list, + StatusCode::BAD_REQUEST, + "delete snapshot cannot add data files", + ), + ( + "populated-add-only-disguised-as-replace", + Some(10), + "replace", + &add_only_full_list, + StatusCode::BAD_REQUEST, + "replace snapshot operation requires deleted files", + ), + ( + "root-add-only-data-disguised-as-replace", + None, + "replace", + &add_only_root_list, + StatusCode::BAD_REQUEST, + "replace snapshot operation requires deleted files", + ), + ( + "root-add-only-delete-disguised-as-replace", + None, + "replace", + &add_del_root_list, + StatusCode::BAD_REQUEST, + "replace snapshot operation requires deleted files", + ), + // Content-kind confusion on status=2. + ( + "append-delete-content-confusion", + Some(10), + "append", + &wrong_content_list, + StatusCode::BAD_REQUEST, + "deleted manifest entry content must match the parent snapshot", + ), + ( + "delete-content-confusion", + Some(10), + "delete", + &wrong_content_list, + StatusCode::BAD_REQUEST, + "deleted manifest entry content must match the parent snapshot", + ), + ]; + + for (label, parent_id, operation, list_path, expected_status, expected_message) in cases { + // A root snapshot can be published to a new branch for manifest validation. + let ref_name = if parent_id.is_none() { "new-branch" } else { "main" }; + let mut snapshot = serde_json::json!({ + "snapshot-id": 11, + "sequence-number": 2, + "timestamp-ms": 2000, + "manifest-list": list_path, + "summary": {"operation": operation} + }); + if let Some(parent_id) = parent_id { + snapshot["parent-snapshot-id"] = serde_json::Value::from(*parent_id); + } + let Err(error) = commit_table_response( + &store, + &trusted_table_commit_backend(&backend), + "warehouse", + &namespace, + "events", + serde_json::from_value(serde_json::json!({ + "updates": [ + {"action": "add-snapshot", "snapshot": snapshot}, + {"action": "set-snapshot-ref", "ref-name": ref_name, "snapshot-id": 11, "type": "branch"} + ] + })) + .unwrap(), + ) + .await + else { + panic!("[{label}] invalid snapshot commit must fail"); + }; + if *expected_status == StatusCode::CONFLICT { + assert_eq!(error.code(), &S3ErrorCode::Custom(ICEBERG_ERROR_COMMIT_FAILED.into()), "[{label}]"); + assert_eq!(error.status_code(), Some(StatusCode::CONFLICT), "[{label}]"); + } else { + assert_eq!(error.code(), &S3ErrorCode::InvalidRequest, "[{label}]"); + } + assert_eq!(error.message(), Some(*expected_message), "[{label}]"); + let after = store.load_table("warehouse", "analytics", "events").await.unwrap().unwrap(); + assert_eq!(after.metadata_location, baseline.metadata_location, "[{label}]"); + assert_eq!(after.version_token, baseline.version_token, "[{label}]"); + assert_eq!(after.generation, baseline.generation, "[{label}]"); + } + + // Intermediate snapshot marking the same file as both existing (status=0) and deleted (status=2) must fail with 400. + let both_existing_and_deleted = put_list( + "snap-existing-and-deleted", + &[ + (&m10_a, m10_a_len, 0, 0, 1, 1, 10), + (&m10_b, m10_b_len, 0, 0, 1, 1, 10), + (&m_forged_del_data, m_forged_del_data_len, 0, 0, 2, 1, 11), + ], + ) + .await; + let final_list = put_list("snap-12-valid", &[(&m10_b, m10_b_len, 0, 0, 1, 1, 10)]).await; + let overlap_error = commit_table_response( + &store, + &trusted_table_commit_backend(&backend), + "warehouse", + &namespace, + "events", + serde_json::from_value(serde_json::json!({ + "updates": [ + {"action": "add-snapshot", "snapshot": { + "snapshot-id": 11, "parent-snapshot-id": 10, "sequence-number": 2, + "timestamp-ms": 2000, "manifest-list": both_existing_and_deleted, + "summary": {"operation": "delete"} + }}, + {"action": "add-snapshot", "snapshot": { + "snapshot-id": 12, "parent-snapshot-id": 11, "sequence-number": 3, + "timestamp-ms": 3000, "manifest-list": final_list, + "summary": {"operation": "delete"} + }}, + {"action": "set-snapshot-ref", "ref-name": "main", "snapshot-id": 12, "type": "branch"}, + {"action": "remove-snapshots", "snapshot-ids": [11]} + ] + })) + .unwrap(), + ) + .await + .expect_err("intermediate snapshot marking file both existing and deleted must fail"); + assert_eq!(overlap_error.code(), &S3ErrorCode::InvalidRequest); + assert_eq!( + overlap_error.message(), + Some("snapshot cannot mark the same file as existing and deleted") + ); + let after = store.load_table("warehouse", "analytics", "events").await.unwrap().unwrap(); + assert_eq!(after.metadata_location, baseline.metadata_location); +} + #[tokio::test] async fn statistics_updates_reject_unpublished_objects_before_pointer_update() { let store = TestTableCatalogStore::default(); @@ -13843,6 +15886,53 @@ fn removing_an_intermediate_snapshot_truncates_earlier_history() { assert_eq!(updated["snapshot-log"], serde_json::json!([{"timestamp-ms": 12, "snapshot-id": 12}])); } +#[test] +fn root_delete_publication_respects_an_implicit_main_branch() { + let mut metadata = serde_json::json!({ + "current-snapshot-id": 10, + "snapshots": [ + {"snapshot-id": 10}, + {"snapshot-id": 11, "timestamp-ms": 100, "summary": {"operation": "delete"}} + ] + }); + let publish = serde_json::json!({"action": "set-snapshot-ref", "ref-name": "main", "snapshot-id": 11, "type": "branch"}); + let mut roots = SnapshotCommitRoots::new(&metadata); + let requirement = serde_json::json!({"type": "assert-ref-snapshot-id", "ref": "main", "snapshot-id": 10}); + validate_table_commit_requirements(&metadata, &[requirement]).unwrap(); + let error = apply_set_snapshot_ref_update(&mut metadata, &publish, &mut roots, 100).unwrap_err(); + assert_eq!(error.code(), &S3ErrorCode::InvalidRequest); + assert_eq!(metadata["current-snapshot-id"], 10); + + apply_remove_snapshot_ref_update( + &mut metadata, + &serde_json::json!({"action": "remove-snapshot-ref", "ref-name": "main"}), + &mut roots, + ) + .unwrap(); + assert_eq!(metadata["current-snapshot-id"], -1); + apply_set_snapshot_ref_update(&mut metadata, &publish, &mut roots, 100).unwrap(); + assert_eq!(metadata["current-snapshot-id"], 11); +} + +#[test] +fn expired_parents_preserve_ancestor_moves_and_reject_newer_roots() { + // Snapshot 2 has expired. Snapshot 1 can still be an ancestor of 3, but 5 cannot. + let metadata = serde_json::json!({ + "current-snapshot-id": 3, + "snapshots": [ + {"snapshot-id": 4, "parent-snapshot-id": 3, "sequence-number": 4}, + {"snapshot-id": 3, "parent-snapshot-id": 2, "sequence-number": 3}, + {"snapshot-id": 5, "sequence-number": 5}, + {"snapshot-id": 1, "sequence-number": 1} + ] + }); + let mut roots = SnapshotCommitRoots::new(&metadata); + roots.set_ref(&metadata, "main", true, 4).unwrap(); + assert!(roots.set_ref(&metadata, "main", true, 5).is_err()); + roots.set_ref(&metadata, "main", true, 1).unwrap(); + roots.set_ref(&metadata, "main", true, 4).unwrap(); +} + #[test] fn removing_main_snapshot_reference_clears_current_snapshot() { let metadata = serde_json::json!({ diff --git a/rustfs/src/app/multipart_usecase/list.rs b/rustfs/src/app/multipart_usecase/list.rs index c7376abd0d..662a7be223 100644 --- a/rustfs/src/app/multipart_usecase/list.rs +++ b/rustfs/src/app/multipart_usecase/list.rs @@ -20,6 +20,7 @@ use crate::app::dto_values; use crate::app::storage_api::multipart_usecase::contract::multipart::ListMultipartsInfo; pub(crate) use crate::app::storage_api::multipart_usecase::contract::multipart::ListPartsInfo; use crate::app::storage_api::multipart_usecase::contract::multipart::ListPartsOwner; +use crate::app::storage_api::multipart_usecase::storage_class::effective_class; use rustfs_gateway_types::dto as gateway_dto; use rustfs_gateway_types::{BucketName, ObjectKey, RecordedUpload, UploadIdClaim, resolve_upload_async}; use rustfs_s3_types::S3Result; @@ -247,6 +248,9 @@ fn list_multipart_uploads_output( key: Some(key), upload_id: Some(upload.upload_id), initiated: upload.initiated.map(dto_values::timestamp), + storage_class: Some(gateway_dto::StorageClass::custom( + effective_class(upload.user_defined.get(AMZ_STORAGE_CLASS).map(String::as_str), None).to_owned(), + )), owner: Some(owner.clone()), initiator: Some(initiator.clone()), ..Default::default() diff --git a/rustfs/src/app/storage_api.rs b/rustfs/src/app/storage_api.rs index 2762dc9e19..6710bafda1 100644 --- a/rustfs/src/app/storage_api.rs +++ b/rustfs/src/app/storage_api.rs @@ -1803,6 +1803,7 @@ pub(crate) mod multipart_usecase { pub(crate) use super::{ access, bucket, compression, data_usage, error, helper, io, options, request_context, s3_api, set_disk, sse, + storage_class, }; pub(crate) use crate::storage::storage_api::{ DEFAULT_EC_BLOCK_SIZE, EC_BLOCK_SIZE_HINT_INTERNAL_SUFFIX, EC_BLOCK_SIZE_HINT_METADATA_KEY, diff --git a/rustfs/src/server/gateway_stack.rs b/rustfs/src/server/gateway_stack.rs index ba4692f142..4a8849d1b1 100644 --- a/rustfs/src/server/gateway_stack.rs +++ b/rustfs/src/server/gateway_stack.rs @@ -817,9 +817,26 @@ mod snowball_tests { use tokio_tar::Header; use uuid::Uuid; - #[tokio::test] + #[test] #[serial_test::serial] - async fn snowball_extract_preserves_sha256_failure_after_sniffing() { + fn snowball_extract_preserves_sha256_failure_after_sniffing() { + let handle = std::thread::Builder::new() + .name("snowball-sha256".to_string()) + .stack_size(8 * rustfs_config::DEFAULT_THREAD_STACK_SIZE) + .spawn(|| { + let runtime = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .expect("snowball test runtime"); + runtime.block_on(snowball_extract_preserves_sha256_failure_after_sniffing_case()); + }) + .expect("snowball test thread"); + if let Err(payload) = handle.join() { + std::panic::resume_unwind(payload); + } + } + + async fn snowball_extract_preserves_sha256_failure_after_sniffing_case() { let store = crate::app::gating_test_env::shared_gating_ecstore().await; if crate::runtime_sources::current_app_context().is_none() { crate::runtime_sources::install_test_app_context(Arc::clone(&store)).await; diff --git a/rustfs/src/server/gateway_stack/tests/control_plane.rs b/rustfs/src/server/gateway_stack/tests/control_plane.rs index f2d4067bd8..fb8a86cc7b 100644 --- a/rustfs/src/server/gateway_stack/tests/control_plane.rs +++ b/rustfs/src/server/gateway_stack/tests/control_plane.rs @@ -1087,9 +1087,26 @@ async fn assert_typed_admin_gets_and_object_lambda_fallback(stack: &GatewayStack } } -#[tokio::test] +#[test] #[serial_test::serial] -async fn typed_admin_routes_enforce_pre_body_iam_target_validation_and_presigned_object_lambda() { +fn typed_admin_routes_enforce_pre_body_iam_target_validation_and_presigned_object_lambda() { + let handle = std::thread::Builder::new() + .name("typed-admin-routes".to_string()) + .stack_size(8 * rustfs_config::DEFAULT_THREAD_STACK_SIZE) + .spawn(|| { + let runtime = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .expect("typed admin test runtime"); + runtime.block_on(typed_admin_routes_enforce_pre_body_iam_target_validation_and_presigned_object_lambda_case()); + }) + .expect("typed admin test thread"); + if let Err(payload) = handle.join() { + std::panic::resume_unwind(payload); + } +} + +async fn typed_admin_routes_enforce_pre_body_iam_target_validation_and_presigned_object_lambda_case() { use rustfs_gateway_dialect_rustfs_admin::native::{extensions, ops as native_ops}; let (_env, stack) = Box::pin(build_typed_admin_fixture()).await; diff --git a/rustfs/src/server/http.rs b/rustfs/src/server/http.rs index c3647e75f7..f5a072769b 100644 --- a/rustfs/src/server/http.rs +++ b/rustfs/src/server/http.rs @@ -9310,7 +9310,7 @@ mod tests { .send() .await .expect("incomplete upload response"); - assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR); + assert_eq!(response.status(), StatusCode::BAD_REQUEST); let message = response.text().await.expect("upload error body"); assert!(message.contains("body size mismatch"), "unexpected upload failure: {message}"); assert!(root.path().join("bucket/incomplete").exists(), "file creation completed before failure"); @@ -9546,14 +9546,20 @@ mod tests { }) .service(RpcRequestPathService::new(Routes::new(node).prepare())); let server = tokio::spawn(async move { - let (socket, peer) = listener.accept().await.expect("accept ReadAll recovery connection"); - let service = ServiceBuilder::new() - .layer(AddExtensionLayer::new(Some(RemoteAddr(peer)))) - .service(service); - ConnBuilder::new(TokioExecutor::new()) - .serve_connection(TokioIo::new(socket), TowerToHyperService::new(service)) - .await - .expect("serve ReadAll recovery connection"); + let mut connections = tokio::task::JoinSet::new(); + loop { + let Ok((socket, peer)) = listener.accept().await else { + break; + }; + let service = ServiceBuilder::new() + .layer(AddExtensionLayer::new(Some(RemoteAddr(peer)))) + .service(service.clone()); + connections.spawn(async move { + let _ = ConnBuilder::new(TokioExecutor::new()) + .serve_connection(TokioIo::new(socket), TowerToHyperService::new(service)) + .await; + }); + } }); let mut endpoint = Endpoint::try_from(format!("http://{addr}/missing-read-all-disk").as_str()).expect("ReadAll remote endpoint"); diff --git a/rustfs/src/table_catalog/iceberg/manifest.rs b/rustfs/src/table_catalog/iceberg/manifest.rs index 0754e45ae8..64a313ddba 100644 --- a/rustfs/src/table_catalog/iceberg/manifest.rs +++ b/rustfs/src/table_catalog/iceberg/manifest.rs @@ -104,12 +104,15 @@ fn manifest_data_file_metadata(value: &apache_avro::types::Value) -> TableCatalo { format.make_ascii_uppercase(); } - // Iceberg maps with integer keys are encoded as Avro arrays; their entry order has no meaning. + // Iceberg maps with integer keys are encoded as Avro arrays; empty maps match null and entry order has no meaning. if matches!( name.as_str(), "column_sizes" | "value_counts" | "null_value_counts" | "nan_value_counts" | "lower_bounds" | "upper_bounds" ) && let Value::Array(entries) = &mut value { + if entries.is_empty() { + continue; + } entries.sort_by_key(|entry| avro_record_field(entry, "key").and_then(avro_i32_value)); } metadata.insert(name, value); diff --git a/rustfs/src/table_catalog/iceberg/validation.rs b/rustfs/src/table_catalog/iceberg/validation.rs index 0cbbabbf04..91aa931b76 100644 --- a/rustfs/src/table_catalog/iceberg/validation.rs +++ b/rustfs/src/table_catalog/iceberg/validation.rs @@ -3719,6 +3719,16 @@ fn validate_i64_requirement_with_metadata_key( Ok(()) } +pub(crate) fn table_snapshot_ref_id(metadata: &serde_json::Value, ref_name: &str) -> Option { + // Iceberg's main branch also exists in older metadata without an explicit refs entry. + if ref_name == "main" + && let Some(id) = metadata.get("current-snapshot-id").and_then(serde_json::Value::as_i64) + { + return (id != -1).then_some(id); + } + metadata.get("refs")?.get(ref_name)?.get("snapshot-id")?.as_i64() +} + fn validate_ref_snapshot_requirement( metadata: &serde_json::Value, requirement: &serde_json::Value, @@ -3727,11 +3737,7 @@ fn validate_ref_snapshot_requirement( .get("ref") .and_then(serde_json::Value::as_str) .ok_or_else(|| TableCatalogStoreError::Invalid("assert-ref-snapshot-id requires ref".to_string()))?; - let refs = metadata.get("refs").and_then(serde_json::Value::as_object); - let actual = refs - .and_then(|refs| refs.get(ref_name)) - .and_then(|reference| reference.get("snapshot-id")) - .and_then(serde_json::Value::as_i64); + let actual = table_snapshot_ref_id(metadata, ref_name); if requirement.get("snapshot-id").is_some_and(serde_json::Value::is_null) { if actual.is_some() { return Err(TableCatalogStoreError::Conflict( diff --git a/rustfs/src/table_catalog/tests.rs b/rustfs/src/table_catalog/tests.rs index 30e1e21076..48f998f152 100644 --- a/rustfs/src/table_catalog/tests.rs +++ b/rustfs/src/table_catalog/tests.rs @@ -3886,6 +3886,115 @@ fn apache_avro_021_iceberg_manifest_fixtures_remain_readable() { assert_eq!(data_file.partition, vec![("dt".to_string(), apache_avro::types::Value::Date(20_312))]); } +#[test] +fn manifest_data_file_metadata_normalizes_empty_metric_maps_to_null() { + use apache_avro::types::Value; + + let base = manifest_avro_bytes(&[("s3://warehouse/tables/table-id/data/part.parquet", 0)]); + let decode_metadata = |mode: &str| { + if mode == "omitted" { + return data_file_references_from_manifest_avro(&base) + .expect("base manifest should decode") + .remove(0) + .data_file_metadata; + } + let reader = apache_avro::Reader::new(base.as_slice()).expect("base manifest reader should initialize"); + let mut schema_json = serde_json::to_value(reader.writer_schema()).expect("schema should serialize"); + let mut records = reader.map(|record| record.expect("record should decode")).collect::>(); + let fields = schema_json["fields"] + .as_array_mut() + .expect("manifest fields should be an array") + .iter_mut() + .find(|field| field["name"] == "data_file") + .expect("data_file field should exist")["type"]["fields"] + .as_array_mut() + .expect("data_file fields should be an array"); + + let mut extra_fields = Vec::new(); + if mode == "empty_split_offsets" { + fields.push(serde_json::json!({ + "name": "split_offsets", + "type": ["null", {"type": "array", "items": "long"}] + })); + extra_fields.push(("split_offsets".to_string(), Value::Union(1, Box::new(Value::Array(Vec::new()))))); + } else { + for name in [ + "column_sizes", + "value_counts", + "null_value_counts", + "nan_value_counts", + "lower_bounds", + "upper_bounds", + ] { + let is_bound = matches!(name, "lower_bounds" | "upper_bounds"); + let array_schema = serde_json::json!({ + "type": "array", + "items": { + "type": "record", + "name": format!("{name}_entry"), + "fields": [ + {"name": "key", "type": "int"}, + {"name": "value", "type": if is_bound { "bytes" } else { "long" }} + ] + } + }); + let (field_type, field_value) = match mode { + "null" => (serde_json::json!(["null", array_schema]), Value::Union(0, Box::new(Value::Null))), + "empty_union" => ( + serde_json::json!(["null", array_schema]), + Value::Union(1, Box::new(Value::Array(Vec::new()))), + ), + "empty_array" => (array_schema, Value::Array(Vec::new())), + "populated" => { + let entry = Value::Record(vec![ + ("key".to_string(), Value::Int(1)), + ("value".to_string(), if is_bound { Value::Bytes(vec![1]) } else { Value::Long(1) }), + ]); + ( + serde_json::json!(["null", array_schema]), + Value::Union(1, Box::new(Value::Array(vec![entry]))), + ) + } + other => panic!("unexpected mode: {other}"), + }; + fields.push(serde_json::json!({"name": name, "type": field_type})); + extra_fields.push((name.to_string(), field_value)); + } + } + + let Value::Record(entry_fields) = &mut records[0] else { + panic!("manifest entry must be a record"); + }; + let Value::Record(data_fields) = &mut entry_fields + .iter_mut() + .find(|(name, _)| name == "data_file") + .expect("data_file should exist") + .1 + else { + panic!("data_file must be a record"); + }; + data_fields.extend(extra_fields); + + let schema = apache_avro::Schema::parse(schema_json).expect("modified manifest schema should parse"); + let mut writer = apache_avro::Writer::new(&schema, Vec::new()).expect("manifest writer should initialize"); + for record in records { + writer.append_value(record).expect("manifest record should append"); + } + let encoded = writer.into_inner().expect("manifest writer should flush"); + data_file_references_from_manifest_avro(&encoded) + .expect("modified manifest should decode") + .remove(0) + .data_file_metadata + }; + + let omitted = decode_metadata("omitted"); + assert_eq!(omitted, decode_metadata("null")); + assert_eq!(omitted, decode_metadata("empty_union")); + assert_eq!(omitted, decode_metadata("empty_array")); + assert_ne!(decode_metadata("empty_union"), decode_metadata("populated")); + assert_ne!(omitted, decode_metadata("empty_split_offsets")); +} + #[tokio::test] async fn iceberg_snapshot_graph_rejects_unknown_partition_specs() { let backend = TestCatalogObjectBackend::default(); diff --git a/scripts/check_test_wiring.py b/scripts/check_test_wiring.py index 0b90f84c7c..ed4829e74a 100755 --- a/scripts/check_test_wiring.py +++ b/scripts/check_test_wiring.py @@ -524,6 +524,7 @@ SCHEDULED_ALERT_CHECKOUT_OVERRIDES = { ".github/workflows/ci.yml": "actions/checkout@f548e57e544e1ff5a4c46bf1e1b8685f8e4a348a", ".github/workflows/fuzz.yml": "actions/checkout@f548e57e544e1ff5a4c46bf1e1b8685f8e4a348a", ".github/workflows/nightly-gnu.yml": "actions/checkout@f548e57e544e1ff5a4c46bf1e1b8685f8e4a348a", + ".github/workflows/nightly-rdma.yml": "actions/checkout@f548e57e544e1ff5a4c46bf1e1b8685f8e4a348a", ".github/workflows/runner-hygiene.yml": "actions/checkout@f548e57e544e1ff5a4c46bf1e1b8685f8e4a348a", ".github/workflows/scheduled-validation-watchdog.yml": "actions/checkout@f548e57e544e1ff5a4c46bf1e1b8685f8e4a348a", ".github/workflows/scheduled-validation-freshness.yml": "actions/checkout@f548e57e544e1ff5a4c46bf1e1b8685f8e4a348a", @@ -1418,12 +1419,19 @@ def check_scheduled_alerts(root: Path) -> list[str]: errors.append(f"{relative}: missing simple numeric schedule") continue minute, hour = map(int, schedule.groups()) - if minute == 0: - errors.append(f"{relative}: scheduled validation must avoid minute zero") entry_end = cron_indices[position + 1] if position + 1 < len(cron_indices) else len(schedule_lines) entry = "\n".join(schedule_lines[cron_index + 1 : entry_end]) timezone_match = re.search(r"^\s*timezone:\s*[\"']?([^\"'\s]+)", entry, re.MULTILINE) timezone_name = timezone_match.group(1) if timezone_match else None + # nightly-rdma.yml is pinned to midnight Asia/Shanghai. Every + # other scheduled validation still avoids minute zero. The UTC + # slot is checked for collisions below. + midnight_shanghai = ( + relative == ".github/workflows/nightly-rdma.yml" + and (minute, hour, timezone_name) == (0, 0, "Asia/Shanghai") + ) + if minute == 0 and not midnight_shanghai: + errors.append(f"{relative}: scheduled validation must avoid minute zero") try: utc_slots = schedule_utc_slots(hour, minute, timezone_name) except ZoneInfoNotFoundError: @@ -6634,6 +6642,7 @@ class SelfTests(unittest.TestCase): ".github/workflows/ci.yml", ".github/workflows/fuzz.yml", ".github/workflows/nightly-gnu.yml", + ".github/workflows/nightly-rdma.yml", ".github/workflows/runner-hygiene.yml", ) with tempfile.TemporaryDirectory() as tmp: @@ -6878,6 +6887,19 @@ class SelfTests(unittest.TestCase): self.assertEqual(len(check_scheduled_alerts(root)), 1) first.write_text(original) + rdma = root / ".github/workflows/nightly-rdma.yml" + rdma_original = rdma.read_text() + rdma.write_text(re.sub( + r'- cron: "\d+ \d+ \* \* \*"\n', + '- cron: "0 0 * * *"\n timezone: "Asia/Shanghai"\n', + rdma_original, + count=1, + )) + self.assertEqual(check_scheduled_alerts(root), []) + rdma.write_text(re.sub(r'- cron: "\d+ \d+', '- cron: "0 0', rdma_original, count=1)) + self.assertTrue(any("must avoid minute zero" in error for error in check_scheduled_alerts(root))) + rdma.write_text(rdma_original) + second = root / SCHEDULED_ALERT_WORKFLOWS[1] second_original = second.read_text() second.write_text(re.sub(r'- cron: "\d+ \d+', '- cron: "1 1', second_original, count=1))