Files
greptimedb/tests/compatibility
jeremyhi 10893e0412 feat: report a downgraded region's last entry once durable and roll back for skip-WAL rows (#10765)
* feat: report a downgraded region's last entry once durable and roll back for skip-WAL rows

A downgrade of a region whose manifest is published conditionally (writes
require a lease and the WAL is the object store WAL) no longer flushes
unless the memtable holds rows that are not in the WAL; the next leader
recovers the rest from the source's WAL. A change to Follower reports the
last entry id only once the WAL is durable through it.

A downgrade reply now carries `has_skip_wal_writes` when the region may
still hold rows outside the WAL after the downgrade; the metasrv then
rolls the migration back instead of retrying or taking the region over,
and aborts with that reason. An empty memtable left marked by a failed
write no longer reports such rows.

Signed-off-by: jeremyhi <jiachun_feng@proton.me>

* fix: flush a downgrading region that skips the WAL and tighten tests

A handover of a region whose options skip the WAL records no tail of its
source, so a downgrade now flushes such a region even when its memtable
holds only rows logged before the option changed.

Tests cover that case, the metadata region's rows on the Noop WAL, a
Follower change that waits without holding the worker and again on a
region that is already a Follower, a flagged reply after an unflagged
one in the same batch, the failure of a write that installs no row, and
the abort reason of a failed candidate upgrade. Docs scope the meaning
of a false `has_skip_wal_writes` and of the metadata region's flush.

Signed-off-by: jeremyhi <jiachun_feng@proton.me>

* fix: report logged rows of a region that skips the WAL and bound an abandoned downgrade

A region whose options skip the WAL is handed over without a tail of its
source, so its unflushed rows count as rows the next leader cannot
recover from the WAL: `MitoRegion::has_skip_wal_writes` reports them and
decides the downgrade's flush, so a follower that cannot flush them rolls
the migration back.

The datanode bounds each region's downgrade, the flush and the change to
Follower together, by its flush timeout and replies with a retryable
error past it. The task that waits for the WAL to be durable stops
waiting once nobody waits for its reply, and a role change builds the
durability barrier only for a Follower.

Tests cover a follower whose options were made to skip the WAL, with and
without rows, a downgrade timeout that releases the region, and a
rollback of two requested regions; the abort reason of a failed
candidate upgrade is compared exactly.

Signed-off-by: jeremyhi <jiachun_feng@proton.me>

* fix: refuse a handover to a candidate with stale skip-WAL options

A candidate whose options skip the WAL commits an empty handover, which
records no tail of its source. An ALTER during the migration reaches only
the routed source, so a candidate can still skip the WAL while the source
logs rows it does not flush. Such a handover now fails, committing
nothing, when the source has unflushed WAL entries; the error is not
retryable, since only closing the candidate after the rollback fixes its
options.

The datanode waits for a shared downgrade flush without its own timer,
under the downgrade's single bound. Docs describe the rollback reason as
rows the candidate may not recover from the WAL, and when a false flag
can be trusted. Tests cover the refused handover and its recovery once
the options match, a flagged reply carrying an error, and a downgrade
timeout that waits until the durability wait is admitted.

Signed-off-by: jeremyhi <jiachun_feng@proton.me>

* test: split the abandoned downgrade test and cover a deadline used up by the last attempt

The datanode test of a timed-out downgrade no longer waits for the
durability wait to be admitted, which raced the deadline; a Mito test
drops the reply of a Follower change once its wait is admitted and
checks that the region is released. A metasrv test covers a last
downgrade attempt whose mailbox expiry uses up the procedure's time:
the candidate upgrade then rolls the migration back without sending
anything. The rollback test keeps a flagged success and a flagged error.

Docs describe the skip-WAL predicate as rows the next leader may not
recover, scope the durability comment to a Follower change, note that
the metasrv must also understand the flag, and say why a refused
handover is not retried.

Signed-off-by: jeremyhi <jiachun_feng@proton.me>

* test: scope the mock leader to the downgrade deadline test

Signed-off-by: jeremyhi <jiachun_feng@proton.me>

* refactor: report only skip-WAL rows now that a handover records the source's tail

A handover or takeover now records the source's tail even when the
candidate's options skip the WAL, so the rows a region logged before its
options turned skip_wal on are recovered from that tail. The downgrade
flush and the flag therefore count only rows written without the WAL:
every other row in the memtable is in the WAL up to the reported last
entry, which the Follower change still waits to be durable whatever the
region's options.

Tests run the source through the graceful downgrade: rows logged before
the option, with and without an earlier flush, reach a candidate by a
handover or by a takeover after the report was lost; a candidate that a
rolled-back migration left awaiting its Leader lease recovers the rows
the source logged since; a downgrade under enqueued acknowledgement
waits for those rows to be durable; and rows written while the WAL was
skipped stay reported after the option is turned off again.

Signed-off-by: jeremyhi <jiachun_feng@proton.me>

* fix: release the region before the durability wait and tighten downgrade tests

The task that changes a region to Follower finishes the work that needs
the region, including the fencing notification, before it waits for
the last entry to become durable, so a pending wait holds only the last
entry id, the barrier and the reply.

Tests check that a downgrade of an object store WAL region without
write leases still flushes, that each setup role change succeeds, and
that an abandoned wait is dropped, observed through the log store it
holds. Docs state the durability barrier per provider.

Signed-off-by: jeremyhi <jiachun_feng@proton.me>

* test: cover a mixed downgrade flush, the flag on a timed-out downgrade and its abort reason

A downgrade's flush of logged and skip-WAL rows persists both, as a
reopen without WAL replay shows. A downgrade that times out still
reports the skip-WAL rows its region holds. The last downgrade attempt
that uses up the deadline aborts as a failed candidate upgrade. The
timeout reply is built in a match that rustfmt formats.

Signed-off-by: jeremyhi <jiachun_feng@proton.me>

* docs: scope the downgrade flush skip and the reply fixture wording

Signed-off-by: jeremyhi <jiachun_feng@proton.me>

* test: let the only downgrade attempt use up the deadline

Signed-off-by: jeremyhi <jiachun_feng@proton.me>

* fix: reply to a role change before the fencing notice unless a Follower waits for its WAL

Only a successful change to Follower notifies, releases the region and waits for its WAL before it replies; every other outcome replies first, as before. Log the entry the wait is for and an abandoned wait, and describe the deadline test's lease as ending with the procedure's time.

Signed-off-by: jeremyhi <jiachun_feng@proton.me>

* test: drop the retry interval the single-attempt deadline test never waits

Signed-off-by: jeremyhi <jiachun_feng@proton.me>

* fix: reply to a Leader change before its sweep, and check the partial-flush handover's bound

A successful change to Leader replies before it schedules the HDFS temp-file sweep, as before. The partial-flush handover case asserts that the source's flushed entry id is the first batch's last entry, strictly between zero and the final entry. The region server's skip-WAL accessor is crate-visible.

Signed-off-by: jeremyhi <jiachun_feng@proton.me>

* docs: say which logged rows a handover and a takeover recover after a downgrade skips its flush

Signed-off-by: jeremyhi <jiachun_feng@proton.me>

* fix: skip a retried downgrade's flush of a metric metadata region that is already a Follower

A downgrade whose change to Follower timed out after the metadata region became a Follower is retried with a Downgrading flush, which failed on the metadata region because a Follower is not flushable, so every retry failed. The flush now skips that region; its handover still fails while it holds entries its manifest does not cover. Drop tests that decide no condition this change adds, and tighten doc wording.

Signed-off-by: jeremyhi <jiachun_feng@proton.me>

* fix: flush a metric metadata Follower that still holds rows on a retried downgrade

Skip the retried downgrade's flush of the metadata region only when it is a Follower whose memtables are empty; one that still holds rows gets the flush, which fails as before. Restore the check that a flagged downgrade reply decodes into the pre-field layout.

Signed-off-by: jeremyhi <jiachun_feng@proton.me>

* test: check the reason first and fence the pair in the dirty metadata Follower test

Read the metadata region's role and memtables only for a Downgrading flush. The dirty metadata Follower test sets the pair to DowngradingLeader through the metric engine, as the downgrade handler does, and checks that the flush fails on the Follower.

Signed-off-by: jeremyhi <jiachun_feng@proton.me>

* test: check that only a downgrade's flush skips a flushed metadata Follower

The clean retry first sends a flush without a reason, which still fails on the metadata Follower, then the downgrade's flush, which skips it. A shared helper changes a role and asserts that it succeeded.

Signed-off-by: jeremyhi <jiachun_feng@proton.me>

* style: address review nits on the downgrade reply and flush test

Name the role states through SettableRegionRoleState instead of importing its variants, order the derives of DowngradeRegionReply as elsewhere in the file, and drop the comment that restates the role helper.

Signed-off-by: jeremyhi <jiachun_feng@proton.me>

---------

Signed-off-by: jeremyhi <jiachun_feng@proton.me>
2026-12-03 10:36:04 +00:00
..

GreptimeDB Compatibility Test Framework

Compatibility tests verify that one GreptimeDB version can restart on state written by another version.

SQL restart tests are run via cargo sqlness compat and reuse the sqlness-runner infrastructure.

Wire fixtures

Frozen protobuf fixtures are exercised by the Rust tests that own their context conversion, not by SQLness case discovery. The legacy query-context fixture checks omitted read-preference defaulting and unrelated metadata preservation:

cargo nextest run -p session -E 'test(test_legacy_query_context_wire_defaults_to_leader)'

The same legacy fixture also checks that logical ALTER requests without pinned table IDs retain their original behavior, and that new pinned IDs survive the query-context protobuf conversion:

cargo nextest run -p common-meta -E 'test(test_pinned_logical_table_ids_wire_compatibility)'

The ID guard requires an updated metasrv; older metasrvs ignore the new internal extension. Update metasrv before enabling exemplar source-schema reconciliation on frontends. No procedure-state or protobuf fields are added.

The native histogram Remote Read fixture checks the sampled encoder against independent Prometheus protobuf values, including exact integer counts, custom bounds, and NaN payloads:

cargo nextest run -p servers -E 'test(native_histogram_remote_read_wire_fixture)'

The legacy region lease fixture checks that a lease without a candidate lease id decodes as such and encodes to the same bytes as before the field existed:

cargo nextest run -p store-api -E 'test(test_legacy_granted_region_wire)'

The pending tails discard fixture checks that a region request discarding pending WAL tails stays at body field 24:

cargo nextest run -p store-api -E 'test(test_discard_pending_tails_request_wire)'

The region statistic fixtures check that a region statistic without pending tails decodes and encodes as before the flag existed:

cargo nextest run -p common-meta -E 'test(test_has_pending_tails_wire)'

The downgrade region reply fixture checks that a downgrade reply that reports has_skip_wal_writes as false decodes and encodes as before the flag existed, and that a reply with the flag decodes in the layout before it:

cargo nextest run -p common-meta -E 'test(test_has_skip_wal_writes_wire)'

Object store WAL fixtures

Frozen objects of the object store WAL are checked byte for byte by the format tests of log-store. The SQL runner cannot cover the object store WAL: it owns wal.provider. See the fixture notes.

Manifest fixtures

Table-compaction fixtures are exercised by mito2's Rust tests. They cover ordinary file-edit compatibility, supported SST levels, and explicit rejection of unpublished prototype task-state records.

The inline sketch-index fixtures in src/mito2/src/manifest/action.rs cover both file-level and column-level descriptors and mixed builtin/sketch indexes. They run without the enterprise feature:

cargo nextest run -p mito2 -E 'test(test_sketch_index_manifest_fixture)'

These fixtures verify supported-reader decoding, not downgrade support for binaries that predate the new index types. Upgrade all manifest readers before enabling a writer that emits these descriptors; downgrade only to readers that recognize them. The OSS build does not generate sketch payloads, so SQL restart cases cannot create these descriptors through an OSS writer.

Frozen region manifests that carry pending WAL tails are checked by the manifest tests of mito2. No SQL statement records a pending tail. See the fixture notes.

Quick Start

# Self-compat smoke test (current binary only):
cargo run -p sqlness-runner -- compat

# Test from a specific released version to current:
cargo run -p sqlness-runner -- compat --from-version v0.9.5

# Test between two local binary directories:
cargo run -p sqlness-runner -- compat --from-bins-dir ./bins/old --to-bins-dir ./bins/new

# Test a downgrade from the current build to a released binary:
cargo run -p sqlness-runner -- compat --from-bins-dir ./bins/current --to-version v1.2.1

# Run a compatibility case in standalone mode:
cargo run -p sqlness-runner -- compat --topology standalone --test-filter "downgrade_compatibility"

# Run a specific case:
cargo run -p sqlness-runner -- compat --test-filter "basic_table"

# Preview which cases would run (no services started):
cargo run -p sqlness-runner -- compat --dry-run --from-version v0.9.5

# See all options:
cargo run -p sqlness-runner -- compat --help

Prerequisites

  • Docker (for etcd): PR1 always uses Docker etcd for distributed metadata. External metadata stores are future work.
  • From binary: Either --from-version <version> to auto-pull a release, or --from-bins-dir <path> to use a local build. The binary greptime must exist directly inside the given directory.
  • To binary: Defaults to the current debug build (target/debug/greptime). Override with --to-bins-dir <path> or fetch a release with --to-version <version>.
  • Custom target-dir: If you use a non-default CARGO_TARGET_DIR, the debug binary won't be at target/debug/greptime. Pass --from-bins-dir / --to-bins-dir explicitly pointing to your custom target directory. Alternatively, run cargo build -p greptime without a custom target-dir.

Case Format

Each compat case is a directory under tests/compatibility/cases/ containing three required files plus an expected output file:

my_case/
  case.toml       # Metadata (required)
  setup.sql       # SQL to run on the from version (required)
  verify.sql      # SQL to run on the to version (required)
  verify.result   # Expected output from verify.sql

case.toml — Required Metadata

name = "my_case"
reason = "Why this compatibility case exists"
introduced_by = "PR #1234 or feature name"
topologies = ["distributed", "standalone"]
from_range = ["*"]
to_range = ["*"]
features = ["table"]
owner = "team-name"
# optional:
namespace = "my_explicit_namespace"   # defaults to sanitized directory name

Required fields: name, reason, introduced_by, topologies, from_range, to_range, features, owner.

Old-Stage Datanode Configuration Overlay

To apply a datanode configuration overlay while running the old stage, add this strict optional table to case.toml:

[old_config]
datanode = "old-datanode.overlay.toml"

datanode is required whenever [old_config] is present; empty tables and unknown keys are rejected. The reference is relative to the case directory and must remain confined to that directory. The sidecar is native datanode TOML, which the runner loads and preflights before starting services or creating state.

The runner first applies the datanode baseline, then merges the sidecar. Tables merge recursively only when both values are tables. Scalars, type mismatches, arrays, and arrays of tables replace the baseline value atomically. In particular, region_engine has no special merge behavior.

Runner-owned fields cannot be changed by an overlay: mode, node_id, storage.data_home, meta_client_options.metasrv_addrs, and wal.provider, plus wal.dir for Raft WAL or wal.broker_endpoints for Kafka WAL. The runner restores these fields to its baseline values, or deletes them when the baseline has no value. It warns about protected-field overrides without printing their values.

Version-Range Filtering

from_range and to_range control which binary versions a case applies to:

Entry Meaning
"*" Matches any version (including unknown).
"vX.Y.Z" or "=vX.Y.Z" Matches exactly version X.Y.Z.
">=vX.Y.Z" Matches X.Y.Z or later.
">vX.Y.Z" Matches versions strictly later than X.Y.Z.
"<=vX.Y.Z" Matches X.Y.Z or earlier.
"<vX.Y.Z" Matches versions strictly earlier than X.Y.Z.

The range list is OR: a case matches if any entry matches.

Best-effort enforcement: The runner tries to determine the effective version:

  • --from-version is used directly.
  • --from-bins-dir / --to-bins-dir (or the default debug build) runs <binary> --version to infer the version.
  • When the version cannot be determined (e.g. binary missing or --version fails), non-wildcard ranges are skipped with a message; wildcard (*) ranges still match.

Example (legacy_jsonb):

from_range = ["<=v1.1.0"]
to_range = [">=v1.1.1"]

This case only runs when the old binary is <= v1.1.0 and the new binary is >= v1.1.1.

CI Version Window

The CI job uses tests/compatibility/ci.toml to choose the small sliding window of recent released from versions to test against the PR-built to binary:

from_versions = ["v1.0.0", "v1.1.0"]

Keep this window small for PR and merge-queue latency: the goal is to catch upgrade compatibility issues from recent releases to the latest build, not to retest every historical version on every PR. Case-level from_range/to_range still decides which cases run for each version pair; the CI window only decides which old binaries are sampled. Broader historical windows belong in nightly or release-validation workflows.

The GitHub Actions workflow delegates the window loading and compat invocation to .github/scripts/run-compat.py; the workflow YAML should stay as a thin wrapper around artifact download/extraction and this script.

downgrade_to_versions optionally lists releases that CI restarts after the PR-built cluster. Those runs select only the downgrade_compatibility case in both distributed and standalone topologies. The oldest supported target is v1.2.0: SSTs written since #10528 can have inverted index segments that cross row group boundaries, and older readers return fewer rows for indexed queries on them without an error.

setup.sql — Setup Phase (From Version)

SQL statements executed on the from version cluster. These must succeed (any error fails the case). Setup output is NOT compared against any result file.

Rules:

  • Statements are semicolon-terminated
  • -- prefix for ordinary comments
  • -- SQLNESS ... interceptor comments follow ordinary sqlness semantics

verify.sql — Verify Phase (To Version)

SQL statements executed on the to version cluster. Output is compared against verify.result in sqlness snapshot style.

verify.result — Expected Output

Expected output in sqlness format. If this file is missing, the runner generates it from actual output and fails — the author must review, commit the generated file, and rerun.

<statement>;

<output>

<next statement>;

<output>

If output differs from expected, the run fails and verify.result is updated with actual output.

PR1 Limitations

  • Sqlness interceptors: -- SQLNESS ... comments are applied per statement using the same interceptor registry as the ordinary sqlness runner, including the GreptimeDB PROTOCOL interceptor. For PROTOCOL POSTGRES, the namespace prelude uses SET search_path instead of USE. Avoid unqualified PostgreSQL-protocol table names starting with pg_: GreptimeDB's current PostgreSQL compatibility parser rewrites them to pg_catalog.<table>.
  • Distributed topology: The compat runner starts 1 metasrv + 3 datanodes + 1 frontend + 1 flownode. Standalone compatibility runs need no external metadata store.
  • No comment-based compat config: The compat runner does not define extra compatibility configuration in SQL comments; sqlness comments keep their normal sqlness meaning.

Namespace Isolation

Each case runs in its own database namespace to prevent cross-case interference:

  • Default namespace is derived from the case directory name (sanitized to [a-z][a-z0-9_]*)
  • Override with namespace in case.toml
  • Duplicate namespaces are rejected at discovery time (before version filtering)
  • Before each statement, the runner executes a namespace prelude (not written to verify.result): CREATE DATABASE IF NOT EXISTS <ns> via gRPC; then USE <ns> for gRPC/MySQL statements or SET search_path TO '<ns>' for PostgreSQL statements.

Batch Behavior

  • The baseline (no-overlay) profile runs first. Cases whose old datanode TOML is semantically equivalent share one profile; profiles run serially and in isolation.
  • Each profile has its own state and etcd lifecycle. Its overlay is applied only to old-stage datanodes and remains in effect through old-stage setup restarts. The current stage always uses a clean configuration.
  • Cases run serially (no parallelism in PR1). Namespace state is session/protocol state and cannot be shared concurrently.
  • Same namespace across cases is rejected.
  • Without fail-fast, the runner verifies only cases whose setup succeeded. With fail-fast, it cleans up the active profile before stopping.
  • --dry-run displays the selected profiles, cases, and sidecar paths without printing configuration values; it starts no services.

xfail Policy (Future)

For PR1, all cases are expected to pass. Future PRs will add xfail support with required issue and expiry fields.

Cross-Job Distributed State

PR1 runs setup and verify in the same job (same process). Cross-job artifact restore for distributed state is not supported in PR1 due to port randomization and etcd lease expiration.