diff --git a/Cargo.lock b/Cargo.lock
index c80f9d761a5..c716ca8c81a 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -2931,6 +2931,7 @@ dependencies = [
"backtrace",
"common-base",
"common-error",
+ "common-macro",
"common-version",
"console-subscriber",
"greptime-proto",
@@ -2945,6 +2946,7 @@ dependencies = [
"prometheus 0.14.0",
"serde",
"serde_json",
+ "snafu 0.8.6",
"tempfile",
"tokio",
"tracing",
@@ -6160,7 +6162,7 @@ dependencies = [
[[package]]
name = "greptime-proto"
version = "0.1.0"
-source = "git+https://github.com/GreptimeTeam/greptime-proto.git?rev=5870f5adc4d601173e742888e7db2032a690b583#5870f5adc4d601173e742888e7db2032a690b583"
+source = "git+https://github.com/GreptimeTeam/greptime-proto.git?rev=c46f7ee9c82ff90f5762ae192fcf8bb2b0d6046f#c46f7ee9c82ff90f5762ae192fcf8bb2b0d6046f"
dependencies = [
"prost 0.14.1",
"prost-types 0.14.1",
@@ -8711,6 +8713,7 @@ dependencies = [
"object-store",
"partition",
"prometheus 0.14.0",
+ "rstest",
"serde",
"serde_json",
"smallvec",
@@ -13776,6 +13779,7 @@ dependencies = [
"local-ip-address",
"log-query",
"loki-proto",
+ "lz4_flex 0.14.0",
"meter-core",
"meter-macros",
"metric-engine",
diff --git a/Cargo.toml b/Cargo.toml
index 1e327fc30d4..71c6d3308ea 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -164,7 +164,7 @@ fs2 = "0.4"
fst = "0.4.7"
futures = "0.3"
futures-util = "0.3"
-greptime-proto = { git = "https://github.com/GreptimeTeam/greptime-proto.git", rev = "5870f5adc4d601173e742888e7db2032a690b583" }
+greptime-proto = { git = "https://github.com/GreptimeTeam/greptime-proto.git", rev = "c46f7ee9c82ff90f5762ae192fcf8bb2b0d6046f" }
hdfs-native = "0.14.6"
hex = "0.4"
hostname = "0.4.0"
@@ -183,6 +183,8 @@ jsonb = { git = "https://github.com/GreptimeTeam/jsonb", rev = "5a6472858d860ac0
lazy_static = "1.4"
local-ip-address = "0.6"
loki-proto = { git = "https://github.com/GreptimeTeam/loki-proto.git", rev = "f69c8924c4babe516373e26a4118be82d976629c" }
+# Keep in sync with Arrow IPC's decoder; COPY bounds its output before Arrow decoding.
+lz4_flex = { version = "=0.14.0", default-features = false, features = ["frame", "std"] }
meter-core = { git = "https://github.com/GreptimeTeam/greptime-meter.git", rev = "f743c3a5fe8c1f57363eac5866c356b7d91f9b39" }
mockall = "0.13"
moka = "0.12"
diff --git a/config/config.md b/config/config.md
index 9bbed619ab3..16e98f77aea 100644
--- a/config/config.md
+++ b/config/config.md
@@ -13,11 +13,12 @@
| Key | Type | Default | Descriptions |
| --- | -----| ------- | ----------- |
| `default_timezone` | String | Unset | The default timezone of the server. |
-| `default_column_prefix` | String | Unset | The default column prefix for auto-created time index, value, and native histogram columns. Legacy OTLP summary columns keep their historical `greptime_` prefix. |
+| `default_column_prefix` | String | Unset | The default column prefix for auto-created time index, value, native histogram, and exemplar-label columns. Legacy OTLP summary columns keep their historical `greptime_` prefix. |
| `auto_create_table` | Bool | `true` | Server-side global switch for auto table creation on write. When `false`, a missing table is never auto-created even if the request sets the `auto_create_table` hint to `true`. Default: `true`. |
+| `auto_create_physical_table_timestamp_unit` | String | Unset | Time index unit for physical metric tables created by auto table creation (Prometheus remote write, OTLP metrics, and other metric-engine ingestion). New logical tables created under such a physical table inherit its unit. Options: "Second", "Millisecond" (default), "Microsecond", "Nanosecond". |
| `user_provider` | String | Unset | The user provider for authentication. Examples: "static_user_provider:file:/path/to/users", "static_user_provider:cmd:greptime_user=greptime_pwd" Password verifier formats: "plain:", "pbkdf2_sha256:::", "mysql_native_password:", "pg_scram_sha256::::" "pbkdf2_sha256" and "pg_scram_sha256" protect passwords at rest, but such users cannot log in over MySQL: `static_user_provider` and `watch_file_user_provider` only negotiate `mysql_native_password`, which cannot verify these formats. "mysql_native_password" is MySQL-specific and cannot authenticate over PostgreSQL at all. PostgreSQL SCRAM only covers "plain" and "pg_scram_sha256" users; if any user is "pbkdf2_sha256" or "mysql_native_password", PostgreSQL falls back to cleartext password auth for every user. For "pg_scram_sha256" users, keep the default iteration count (4096) and salt length (16): both are observable in the SCRAM server-first message, and non-default values weaken resistance to username enumeration. |
-| `max_in_flight_write_bytes` | String | 0 | Maximum total memory for all concurrent write request bodies and messages (HTTP, gRPC, Flight). Set to 0 to disable the limit. Default: "0" (unlimited) |
-| `write_bytes_exhausted_policy` | String | `wait` | Policy when write bytes quota is exhausted. Options: "wait" (default, 10s timeout), "wait()" (e.g., "wait(30s)"), "fail" |
+| `max_in_flight_write_bytes` | String | 0 | Shared quota for concurrent write request bodies and messages (HTTP, gRPC, Flight) plus retained decoder memory and estimated PB-to-Arrow conversion memory for ordinary-table batching. A batch must fit together with its request's existing reservations; only additional memory is acquired. Set to 0 to disable the limit. Default: "0" (unlimited) |
+| `write_bytes_exhausted_policy` | String | `wait` | Policy when write bytes quota is exhausted. Options: "wait" (default, 10s timeout), "wait()" (e.g., "wait(30s)"), "fail" Table-batch conversion never waits for additional memory. Under a wait policy, temporary contention returns a retryable error; requests that cannot fit are rejected. |
| `init_regions_in_background` | Bool | `false` | Initialize all regions in the background during the startup. By default, it provides services after all regions have been initialized. |
| `init_regions_parallelism` | Integer | `16` | Parallelism of initializing regions. |
| `max_concurrent_queries` | Integer | `0` | The maximum concurrent region-read streams. Zero means unlimited. A single query can consume multiple permits. |
@@ -259,7 +260,7 @@
| `logging.enable_file_logging` | Bool | `true` | Whether to write logs to files in `dir`. |
| `logging.log_format` | String | `text` | The log format. Can be `text`/`json`. |
| `logging.max_log_files` | Integer | `720` | The maximum amount of log files. |
-| `logging.max_log_dir_size` | String | `0B` | The maximum total size of managed log files in `dir`. Old closed log files are removed before writing when necessary. Active files may exceed it. Set to `0B` to disable. |
+| `logging.max_log_dir_size` | String | `0B` | The maximum total size of managed log files in `dir`. Old closed log files are removed before writing when necessary. Active files may exceed it. Set to `0B` to disable. Requires symbolic links in the log directory; initialization fails if they cannot be created. On Windows, enable Developer Mode or leave this at `0B`. |
| `logging.enable_per_region_metrics` | Bool | `false` | Whether to enable per-region metrics. Default to false. |
| `logging.otlp_export_protocol` | String | `http` | The OTLP tracing export protocol. Can be `grpc`/`http`. |
| `logging.otlp_headers` | -- | -- | Additional OTLP headers, only valid when using OTLP http |
@@ -291,11 +292,12 @@
| Key | Type | Default | Descriptions |
| --- | -----| ------- | ----------- |
| `default_timezone` | String | Unset | The default timezone of the server. |
-| `default_column_prefix` | String | Unset | The default column prefix for auto-created time index, value, and native histogram columns. Legacy OTLP summary columns keep their historical `greptime_` prefix. |
+| `default_column_prefix` | String | Unset | The default column prefix for auto-created time index, value, native histogram, and exemplar-label columns. Legacy OTLP summary columns keep their historical `greptime_` prefix. |
| `auto_create_table` | Bool | `true` | Server-side global switch for auto table creation on write. When `false`, a missing table is never auto-created even if the request sets the `auto_create_table` hint to `true`. Default: `true`. |
+| `auto_create_physical_table_timestamp_unit` | String | Unset | Time index unit for physical metric tables created by auto table creation (Prometheus remote write, OTLP metrics, and other metric-engine ingestion). New logical tables created under such a physical table inherit its unit. Options: "Second", "Millisecond" (default), "Microsecond", "Nanosecond". |
| `user_provider` | String | Unset | The user provider for authentication. Examples: "static_user_provider:file:/path/to/users", "static_user_provider:cmd:greptime_user=greptime_pwd" Password verifier formats: "plain:", "pbkdf2_sha256:::", "mysql_native_password:", "pg_scram_sha256::::" "pbkdf2_sha256" and "pg_scram_sha256" protect passwords at rest, but such users cannot log in over MySQL: `static_user_provider` and `watch_file_user_provider` only negotiate `mysql_native_password`, which cannot verify these formats. "mysql_native_password" is MySQL-specific and cannot authenticate over PostgreSQL at all. PostgreSQL SCRAM only covers "plain" and "pg_scram_sha256" users; if any user is "pbkdf2_sha256" or "mysql_native_password", PostgreSQL falls back to cleartext password auth for every user. For "pg_scram_sha256" users, keep the default iteration count (4096) and salt length (16): both are observable in the SCRAM server-first message, and non-default values weaken resistance to username enumeration. |
-| `max_in_flight_write_bytes` | String | 0 | Maximum total memory for all concurrent write request bodies and messages (HTTP, gRPC, Flight). Set to 0 to disable the limit. Default: "0" (unlimited) |
-| `write_bytes_exhausted_policy` | String | `wait` | Policy when write bytes quota is exhausted. Options: "wait" (default, 10s timeout), "wait()" (e.g., "wait(30s)"), "fail" |
+| `max_in_flight_write_bytes` | String | 0 | Shared quota for concurrent write request bodies and messages (HTTP, gRPC, Flight) plus retained decoder memory and estimated PB-to-Arrow conversion memory for ordinary-table batching. A batch must fit together with its request's existing reservations; only additional memory is acquired. Set to 0 to disable the limit. Default: "0" (unlimited) |
+| `write_bytes_exhausted_policy` | String | `wait` | Policy when write bytes quota is exhausted. Options: "wait" (default, 10s timeout), "wait()" (e.g., "wait(30s)"), "fail" Table-batch conversion never waits for additional memory. Under a wait policy, temporary contention returns a retryable error; requests that cannot fit are rejected. |
| `runtime` | -- | -- | The runtime options. |
| `runtime.global_rt_size` | Integer | Auto | The number of threads to execute the runtime for global read operations. Defaults to max(num_cpus, 2). |
| `runtime.compact_rt_size` | Integer | Auto | The number of threads to execute compact operations. Defaults to max(num_cpus / 2, 2). |
@@ -420,7 +422,7 @@
| `logging.enable_file_logging` | Bool | `true` | Whether to write logs to files in `dir`. |
| `logging.log_format` | String | `text` | The log format. Can be `text`/`json`. |
| `logging.max_log_files` | Integer | `720` | The maximum amount of log files. |
-| `logging.max_log_dir_size` | String | `0B` | The maximum total size of managed log files in `dir`. Old closed log files are removed before writing when necessary. Active files may exceed it. Set to `0B` to disable. |
+| `logging.max_log_dir_size` | String | `0B` | The maximum total size of managed log files in `dir`. Old closed log files are removed before writing when necessary. Active files may exceed it. Set to `0B` to disable. Requires symbolic links in the log directory; initialization fails if they cannot be created. On Windows, enable Developer Mode or leave this at `0B`. |
| `logging.enable_per_region_metrics` | Bool | `false` | Whether to enable per-region metrics. Default to false. |
| `logging.otlp_export_protocol` | String | `http` | The OTLP tracing export protocol. Can be `grpc`/`http`. |
| `logging.otlp_headers` | -- | -- | Additional OTLP headers, only valid when using OTLP http |
@@ -539,7 +541,7 @@
| `logging.enable_file_logging` | Bool | `true` | Whether to write logs to files in `dir`. |
| `logging.log_format` | String | `text` | The log format. Can be `text`/`json`. |
| `logging.max_log_files` | Integer | `720` | The maximum amount of log files. |
-| `logging.max_log_dir_size` | String | `0B` | The maximum total size of managed log files in `dir`. Old closed log files are removed before writing when necessary. Active files may exceed it. Set to `0B` to disable. |
+| `logging.max_log_dir_size` | String | `0B` | The maximum total size of managed log files in `dir`. Old closed log files are removed before writing when necessary. Active files may exceed it. Set to `0B` to disable. Requires symbolic links in the log directory; initialization fails if they cannot be created. On Windows, enable Developer Mode or leave this at `0B`. |
| `logging.otlp_export_protocol` | String | `http` | The OTLP tracing export protocol. Can be `grpc`/`http`. |
| `logging.otlp_headers` | -- | -- | Additional OTLP headers, only valid when using OTLP http |
| `logging.tracing_sample_ratio` | -- | Unset | The percentage of tracing will be sampled and exported. Valid range `[0, 1]`, 1 means all traces are sampled, 0 means all traces are not sampled, the default value is 1. ratio > 1 are treated as 1. Fractions < 0 are treated as 0 |
@@ -555,7 +557,7 @@
| Key | Type | Default | Descriptions |
| --- | -----| ------- | ----------- |
| `node_id` | Integer | Unset | The datanode identifier and should be unique in the cluster. |
-| `default_column_prefix` | String | Unset | The default column prefix for auto-created time index, value, and native histogram columns. Legacy OTLP summary columns keep their historical `greptime_` prefix. |
+| `default_column_prefix` | String | Unset | The default column prefix for auto-created time index, value, native histogram, and exemplar-label columns. Legacy OTLP summary columns keep their historical `greptime_` prefix. |
| `require_lease_before_startup` | Bool | `false` | Start services after regions have obtained leases. It will block the datanode start if it can't receive leases in the heartbeat from metasrv. |
| `init_regions_in_background` | Bool | `false` | Initialize all regions in the background during the startup. By default, it provides services after all regions have been initialized. |
| `init_regions_parallelism` | Integer | `16` | Parallelism of initializing regions. |
@@ -746,7 +748,7 @@
| `logging.enable_file_logging` | Bool | `true` | Whether to write logs to files in `dir`. |
| `logging.log_format` | String | `text` | The log format. Can be `text`/`json`. |
| `logging.max_log_files` | Integer | `720` | The maximum amount of log files. |
-| `logging.max_log_dir_size` | String | `0B` | The maximum total size of managed log files in `dir`. Old closed log files are removed before writing when necessary. Active files may exceed it. Set to `0B` to disable. |
+| `logging.max_log_dir_size` | String | `0B` | The maximum total size of managed log files in `dir`. Old closed log files are removed before writing when necessary. Active files may exceed it. Set to `0B` to disable. Requires symbolic links in the log directory; initialization fails if they cannot be created. On Windows, enable Developer Mode or leave this at `0B`. |
| `logging.otlp_export_protocol` | String | `http` | The OTLP tracing export protocol. Can be `grpc`/`http`. |
| `logging.otlp_headers` | -- | -- | Additional OTLP headers, only valid when using OTLP http |
| `logging.tracing_sample_ratio` | -- | Unset | The percentage of tracing will be sampled and exported. Valid range `[0, 1]`, 1 means all traces are sampled, 0 means all traces are not sampled, the default value is 1. ratio > 1 are treated as 1. Fractions < 0 are treated as 0 |
@@ -807,7 +809,7 @@
| `logging.enable_file_logging` | Bool | `true` | Whether to write logs to files in `dir`. |
| `logging.log_format` | String | `text` | The log format. Can be `text`/`json`. |
| `logging.max_log_files` | Integer | `720` | The maximum amount of log files. |
-| `logging.max_log_dir_size` | String | `0B` | The maximum total size of managed log files in `dir`. Old closed log files are removed before writing when necessary. Active files may exceed it. Set to `0B` to disable. |
+| `logging.max_log_dir_size` | String | `0B` | The maximum total size of managed log files in `dir`. Old closed log files are removed before writing when necessary. Active files may exceed it. Set to `0B` to disable. Requires symbolic links in the log directory; initialization fails if they cannot be created. On Windows, enable Developer Mode or leave this at `0B`. |
| `logging.otlp_export_protocol` | String | `http` | The OTLP tracing export protocol. Can be `grpc`/`http`. |
| `logging.otlp_headers` | -- | -- | Additional OTLP headers, only valid when using OTLP http |
| `logging.tracing_sample_ratio` | -- | Unset | The percentage of tracing will be sampled and exported. Valid range `[0, 1]`, 1 means all traces are sampled, 0 means all traces are not sampled, the default value is 1. ratio > 1 are treated as 1. Fractions < 0 are treated as 0 |
diff --git a/config/datanode.example.toml b/config/datanode.example.toml
index 45f1d93d39a..342ceb0a17a 100644
--- a/config/datanode.example.toml
+++ b/config/datanode.example.toml
@@ -2,7 +2,7 @@
## @toml2docs:none-default
node_id = 42
-## The default column prefix for auto-created time index, value, and native histogram columns.
+## The default column prefix for auto-created time index, value, native histogram, and exemplar-label columns.
## Legacy OTLP summary columns keep their historical `greptime_` prefix.
## @toml2docs:none-default
default_column_prefix = "greptime"
@@ -906,6 +906,8 @@ max_log_files = 720
## The maximum total size of managed log files in `dir`.
## Old closed log files are removed before writing when necessary. Active files may exceed it. Set to `0B` to disable.
+## Requires symbolic links in the log directory; initialization fails if they cannot be created.
+## On Windows, enable Developer Mode or leave this at `0B`.
max_log_dir_size = "0B"
## The OTLP tracing export protocol. Can be `grpc`/`http`.
diff --git a/config/flownode.example.toml b/config/flownode.example.toml
index fab31fed510..8faeb2cc227 100644
--- a/config/flownode.example.toml
+++ b/config/flownode.example.toml
@@ -126,6 +126,8 @@ max_log_files = 720
## The maximum total size of managed log files in `dir`.
## Old closed log files are removed before writing when necessary. Active files may exceed it. Set to `0B` to disable.
+## Requires symbolic links in the log directory; initialization fails if they cannot be created.
+## On Windows, enable Developer Mode or leave this at `0B`.
max_log_dir_size = "0B"
## The OTLP tracing export protocol. Can be `grpc`/`http`.
diff --git a/config/frontend.example.toml b/config/frontend.example.toml
index f0c1402327f..d5638b66f58 100644
--- a/config/frontend.example.toml
+++ b/config/frontend.example.toml
@@ -2,7 +2,7 @@
## @toml2docs:none-default
default_timezone = "UTC"
-## The default column prefix for auto-created time index, value, and native histogram columns.
+## The default column prefix for auto-created time index, value, native histogram, and exemplar-label columns.
## Legacy OTLP summary columns keep their historical `greptime_` prefix.
## @toml2docs:none-default
default_column_prefix = "greptime"
@@ -11,6 +11,13 @@ default_column_prefix = "greptime"
## When `false`, a missing table is never auto-created even if the request sets the `auto_create_table` hint to `true`. Default: `true`.
#+ auto_create_table = true
+## Time index unit for physical metric tables created by auto table creation
+## (Prometheus remote write, OTLP metrics, and other metric-engine ingestion).
+## New logical tables created under such a physical table inherit its unit.
+## Options: "Second", "Millisecond" (default), "Microsecond", "Nanosecond".
+## @toml2docs:none-default
+#+ auto_create_physical_table_timestamp_unit = "Millisecond"
+
## The user provider for authentication.
## Examples: "static_user_provider:file:/path/to/users", "static_user_provider:cmd:greptime_user=greptime_pwd"
## Password verifier formats: "plain:", "pbkdf2_sha256:::",
@@ -27,13 +34,17 @@ default_column_prefix = "greptime"
## @toml2docs:none-default
#+ user_provider = "static_user_provider:file:/path/to/users"
-## Maximum total memory for all concurrent write request bodies and messages (HTTP, gRPC, Flight).
+## Shared quota for concurrent write request bodies and messages (HTTP, gRPC, Flight)
+## plus retained decoder memory and estimated PB-to-Arrow conversion memory for ordinary-table batching.
+## A batch must fit together with its request's existing reservations; only additional memory is acquired.
## Set to 0 to disable the limit. Default: "0" (unlimited)
## @toml2docs:none-default="0"
#+ max_in_flight_write_bytes = "1GB"
## Policy when write bytes quota is exhausted.
## Options: "wait" (default, 10s timeout), "wait()" (e.g., "wait(30s)"), "fail"
+## Table-batch conversion never waits for additional memory. Under a wait policy,
+## temporary contention returns a retryable error; requests that cannot fit are rejected.
#+ write_bytes_exhausted_policy = "wait"
## The runtime options.
@@ -453,6 +464,8 @@ max_log_files = 720
## The maximum total size of managed log files in `dir`.
## Old closed log files are removed before writing when necessary. Active files may exceed it. Set to `0B` to disable.
+## Requires symbolic links in the log directory; initialization fails if they cannot be created.
+## On Windows, enable Developer Mode or leave this at `0B`.
max_log_dir_size = "0B"
## Whether to enable per-region metrics.
diff --git a/config/metasrv.example.toml b/config/metasrv.example.toml
index fe4c38d02f9..35ba3ae0a98 100644
--- a/config/metasrv.example.toml
+++ b/config/metasrv.example.toml
@@ -392,6 +392,8 @@ max_log_files = 720
## The maximum total size of managed log files in `dir`.
## Old closed log files are removed before writing when necessary. Active files may exceed it. Set to `0B` to disable.
+## Requires symbolic links in the log directory; initialization fails if they cannot be created.
+## On Windows, enable Developer Mode or leave this at `0B`.
max_log_dir_size = "0B"
## The OTLP tracing export protocol. Can be `grpc`/`http`.
diff --git a/config/standalone.example.toml b/config/standalone.example.toml
index 7682e537861..237f106992b 100644
--- a/config/standalone.example.toml
+++ b/config/standalone.example.toml
@@ -2,7 +2,7 @@
## @toml2docs:none-default
default_timezone = "UTC"
-## The default column prefix for auto-created time index, value, and native histogram columns.
+## The default column prefix for auto-created time index, value, native histogram, and exemplar-label columns.
## Legacy OTLP summary columns keep their historical `greptime_` prefix.
## @toml2docs:none-default
default_column_prefix = "greptime"
@@ -11,6 +11,13 @@ default_column_prefix = "greptime"
## When `false`, a missing table is never auto-created even if the request sets the `auto_create_table` hint to `true`. Default: `true`.
#+ auto_create_table = true
+## Time index unit for physical metric tables created by auto table creation
+## (Prometheus remote write, OTLP metrics, and other metric-engine ingestion).
+## New logical tables created under such a physical table inherit its unit.
+## Options: "Second", "Millisecond" (default), "Microsecond", "Nanosecond".
+## @toml2docs:none-default
+#+ auto_create_physical_table_timestamp_unit = "Millisecond"
+
## The user provider for authentication.
## Examples: "static_user_provider:file:/path/to/users", "static_user_provider:cmd:greptime_user=greptime_pwd"
## Password verifier formats: "plain:", "pbkdf2_sha256:::",
@@ -27,13 +34,17 @@ default_column_prefix = "greptime"
## @toml2docs:none-default
#+ user_provider = "static_user_provider:file:/path/to/users"
-## Maximum total memory for all concurrent write request bodies and messages (HTTP, gRPC, Flight).
+## Shared quota for concurrent write request bodies and messages (HTTP, gRPC, Flight)
+## plus retained decoder memory and estimated PB-to-Arrow conversion memory for ordinary-table batching.
+## A batch must fit together with its request's existing reservations; only additional memory is acquired.
## Set to 0 to disable the limit. Default: "0" (unlimited)
## @toml2docs:none-default="0"
#+ max_in_flight_write_bytes = "1GB"
## Policy when write bytes quota is exhausted.
## Options: "wait" (default, 10s timeout), "wait()" (e.g., "wait(30s)"), "fail"
+## Table-batch conversion never waits for additional memory. Under a wait policy,
+## temporary contention returns a retryable error; requests that cannot fit are rejected.
#+ write_bytes_exhausted_policy = "wait"
## Initialize all regions in the background during the startup.
@@ -1099,6 +1110,8 @@ max_log_files = 720
## The maximum total size of managed log files in `dir`.
## Old closed log files are removed before writing when necessary. Active files may exceed it. Set to `0B` to disable.
+## Requires symbolic links in the log directory; initialization fails if they cannot be created.
+## On Windows, enable Developer Mode or leave this at `0B`.
max_log_dir_size = "0B"
## Whether to enable per-region metrics.
diff --git a/docs/rfcs/2026-09-06-object-store-wal.md b/docs/rfcs/2026-09-06-object-store-wal.md
index c94abc073aa..be152130289 100644
--- a/docs/rfcs/2026-09-06-object-store-wal.md
+++ b/docs/rfcs/2026-09-06-object-store-wal.md
@@ -174,10 +174,51 @@ To move the WAL to another location, stop the instance, copy every object under
The check does not catch every change of location. A location whose prefix already holds objects passes a region that never flushed, and a region whose watermark names an object at or below the newest object holding entries there, whatever history those objects hold. A refused start on an empty prefix leaves its start object behind when the process ends before the delete completes or when the delete fails, which is logged; the next start then finds a prefix with only start objects and passes a region that never flushed, while it still refuses every region whose watermark names an object. The same holds when the store created a region before the refusal. When it admitted an append or a release before the refusal, as it can when regions open while the instance already serves, the store withdraws nothing and the prefix keeps an object holding entries, which may already have collected the start object; the next start then also passes every region whose watermark names an object at or below that one.
-**Metrics.** The store exports metrics under `greptime_logstore_object_store_wal_`. The write path reports `seal_to_durable_seconds`, the time from sealing a batch until its object is durable, `append_ack_seconds`, the time an append waits for its acknowledgement in the `durable` mode, `object_bytes` and `object_entries`, the size and the entry count of every object sealed, and `created_objects_total`, the creates that succeeded, an identical retry included; a create is counted and timed whether or not its batch is still there to be indexed, since an object a poisoned store gave up on is as durable as any other. `indexed_objects` and `indexed_bytes` are the objects and the bytes the catalog holds, set by a recovery that succeeded and moved by every object indexed or unindexed afterwards, so a collection takes the object it deleted off both, and a recovery that is abandoned publishes neither. A recovery that succeeds reports `recovery_seconds` and the objects it read footers from in `recovered_objects_total`, both of the same recoveries, so one that is abandoned at a fetch or rejected by the catalog contributes to neither; a read stream reports `read_seconds` once it has been read to its end, and one that fails or is dropped part way reports nothing. The failure paths are counted: `create_conflicts_total` for a create that found a conflicting object, `create_failures_total` for one the object store did not confirm, `poisoned_total` for a store that recorded a terminal error, `skipped_segments_total` for a segment a read skipped, `missing_history_accepted_total` for a region that `accept_missing_history` let open without its history, and `stalled_appends_total` with `stalled_append_seconds` for an append held back because the sealed batches were full, in either mode, or by the `enqueued` backlog thresholds, timed until it is admitted or refused, a stop, a terminal error, a failing store or the teardown of the actor releasing it included. The gauge `failing` counts the stores whose backlog the object store refuses with an error that requires intervention, and `rejected_appends_total` the appends and releases such a store rejected; the attempts of a failing store are counted in `create_failures_total`. The delete counters of a collection and the release record counter are described under *Entry ids*. The histogram buckets are chosen for the default flush interval of 100 ms and the default `max_batch_bytes` of 8 MiB.
+**Metrics.** The store exports metrics under `greptime_logstore_object_store_wal_`. The write path reports `seal_to_durable_seconds`, the time from sealing a batch until its object is durable, `append_ack_seconds`, the time an append waits for its acknowledgement in the `durable` mode, `object_bytes` and `object_entries`, the size and the entry count of every object sealed, and `created_objects_total`, the creates that succeeded, an identical retry included; a create is counted and timed whether or not its batch is still there to be indexed, since an object a poisoned store gave up on is as durable as any other. `indexed_objects` and `indexed_bytes` are the objects and the bytes the catalog holds, set by a recovery that succeeded and moved by every object indexed or unindexed afterwards, so a collection takes the object it deleted off both, and a recovery that is abandoned publishes neither. A recovery that succeeds reports `recovery_seconds` and the objects it read footers from in `recovered_objects_total`, both of the same recoveries, so one that is abandoned at a fetch or rejected by the catalog contributes to neither; a read stream reports `read_seconds` once it has been read to its end, and one that fails or is dropped part way reports nothing. The failure paths are counted: `create_conflicts_total` for a create that found a conflicting object, `create_failures_total` for one the object store did not confirm, `poisoned_total` for a store that recorded a terminal error, `skipped_segments_total` for a segment a read skipped, `missing_history_accepted_total` for a region that `accept_missing_history` let open without its history, and `stalled_appends_total` with `stalled_append_seconds` for an append held back because the sealed batches were full, in either mode, or by the `enqueued` backlog thresholds, timed until it is admitted or refused, a stop, a terminal error, a failing store or the teardown of the actor releasing it included. The gauge `failing` counts the stores whose backlog the object store refuses with an error that requires intervention, and `rejected_appends_total` the appends and releases such a store rejected; the attempts of a failing store are counted in `create_failures_total`. The gauge `io_permission_unavailable` counts live stores observed without permission to initiate object-store I/O, including idle stores and those awaiting their first grant. Each store is counted once while permission is unavailable and removed from the count when permission returns or its actor exits; the gauge measures permission availability, not backlog size. The delete counters of a collection and the release record counter are described under *Entry ids*. The histogram buckets are chosen for the default flush interval of 100 ms and the default `max_batch_bytes` of 8 MiB.
A `testing` cargo feature exposes hooks to wait for admitted appends, to seal the open batch, to hold and release creates and to make creates fail, so engine tests can flush deterministically and observe entries that are admitted but not durable.
+### Node lease and recovery fencing
+
+A metasrv-controlled datanode accepts object-store WAL only when its plugins
+contain `EnableObjectStoreWal`; OSS does not register this marker. The builder
+installs an I/O permit backed by Mito's node lease before opening regions. The
+permit exposes only whether new object-store I/O is allowed; the WAL does not
+own deadlines or heartbeat renewal. Standalone installs no permit. The node
+prefix retains the fixed `epochs/0` directory across restarts, independently of
+the heartbeat node epoch and the store epoch in object headers. Metasrv
+configuration, failover integration and Enterprise registration remain separate
+prerequisites for enabling the distributed WAL.
+Startup's initial object and its withdrawal after a missing-history failure are
+exempt so startup does not depend on a heartbeat that has not started yet.
+
+Every new upload, including a retry or release-only object, and every collection
+delete checks the permit immediately before issuance. Issued operations may
+finish, including their transport retries. The flush timer checks expiry and
+renewal without sealing while expired. Expiry fails durable open and unindexed
+batches with a retryable error, ignores their late upload results and never
+reuses their ids. Enqueued batches already acknowledged remain pending until
+renewal. Release records remain available for a later batch, while their current
+waiters fail. An admission that would wait for upload capacity fails immediately
+while expired; ordinary admissions continue to rely on the region write lease.
+
+The datanode keeps the heartbeat running until the object-store WAL stops, then
+closes the heartbeat and regions. If the lease expires during shutdown, the WAL
+drops its unindexed backlog without waiting for uploads, and still waits for
+issued deletes. Expiry is checked on the next flush timer tick, including during
+shutdown, so detection can take one configured flush interval plus actor
+scheduling delay. Dropping acknowledged enqueued entries has crash semantics.
+
+Recovery still selects the latest complete chain, but before writing its initial
+object checks that the selected tip carries the maximum epoch among all listed
+headers. Falling back to an older epoch fails without modifying storage, with
+the skipped epochs, object counts and sequence ranges in the error. Explicit
+`accept_missing_history` permits this fallback only as an operator recovery:
+previous writers must have exited and acknowledged unflushed data may be lost.
+The new initial object's epoch exceeds every listed epoch. An incomplete branch
+within the selected epoch does not trigger this rejection. Remote readers always
+reject an older-epoch fallback, independent of this setting.
+
## Mito integration
Mito maps `WalOptions::ObjectStore { prefix }` to `Provider::object_store_provider(region_id, prefix)`; resolving object store options against a Raft Engine or Kafka log store reports the existing incompatible-provider error. Reads go through the region-scoped reader used for Kafka, so a namespace shared by many regions never leaks entries across regions even if a log store returned them. Object store regions are opened individually rather than grouped by topic. After replay, `topic_latest_entry_id` follows the existing remote-WAL rule: it is taken from the store's latest entry id only when the region's memtables are empty, otherwise it stays at the replay start, because that value feeds pruning and must never advance past unflushed data. Before a flush, a full truncate or a discard of unflushed data publishes a manifest watermark, Mito waits on the durability barrier described under *Acknowledgement*; with the `durable` mode and with every other provider the wait returns at once. When Mito drops a region it calls `release_region` after `obsolete`, as described under *Entry ids*; the default of that method does nothing, so the other providers handle a dropped region as before. Neither a release nor an `obsolete` of an object store region that fails, the latter for instance on a store that the release of another region poisoned, fails the drop, since nothing sends the drop of a removed region again and a caller that drops several regions, such as the metric engine with its data and metadata regions, would leave the others undone: the region's runtime state is cleaned up and its files are scheduled for deletion as for any drop, and the failure is logged; an `obsolete` that fails for another provider fails the drop as before. A store that is neither stopped nor poisoned keeps the record and writes it with its next object; a stopped or poisoned store keeps none, and the region stays unreleased after a restart. The store carries the record in a later object, as described under *Entry ids*; a crash before any later create succeeds loses it, and the dropped region's segments then hold the reclaim boundary after the restart. Before Mito replays an existing region on open, on catch-up or for a create that finds the region present, it runs the history check described under *Log store*.
@@ -271,7 +312,7 @@ The reference implementation was validated on the following evidence; the tests
- Object store access: an unwritable store; a listing, a trailer fetch, a footer fetch, a segment fetch and a delete that fail; a delete that fails and is retried by the next collection; an object collected between the listing and its fetch, below and at the tip's reclaim boundary; an object store that answers slowly.
- Store state: an object the catalog rejects, per-region entry id exhaustion, the catalog refusing a next sequence past the maximum, every stop path with several creates in flight that succeed, fail transiently or conflict after stop began, a stop with a delete in flight, an append held back by full sealed batches, and the appends the backlog thresholds were holding back released by admission, by a stop, by a terminal error and by the teardown of the actor.
- Pipelined uploader: concurrent creates acknowledged in sequence order, every sealed batch linked to its pipeline predecessor, the open batch sealing at the threshold while creates are in flight, a transient failure failing every batch that is not indexed, created ones included, a permanent failure poisoning the store.
-- Chain recovery: a linear chain, orphans below and above the tip, a broken tip falling back to the latest complete object, a late object of an earlier epoch next to the chain of a later one, a missing predecessor, objects present without a complete chain, orphans raising the next sequence, and the start object on an empty prefix and meeting objects of an earlier and of a later epoch.
+- Chain recovery: a linear chain, orphans below and above the tip, an incomplete branch within the selected epoch, rejection of an older-epoch fallback before any mutation and its explicit acceptance with `accept_missing_history`, a late object of an earlier epoch next to the chain of a later one, a missing predecessor, objects present without a complete chain, orphans raising the next sequence, and the start object on an empty prefix and meeting objects of an earlier and of a later epoch.
### What the evidence does not cover
diff --git a/src/cmd/src/cli.rs b/src/cmd/src/cli.rs
index 3739d4cc4fc..92aca3a5625 100644
--- a/src/cmd/src/cli.rs
+++ b/src/cmd/src/cli.rs
@@ -77,7 +77,8 @@ impl Command {
&TracingOptions::default(),
None,
None,
- );
+ )
+ .context(crate::error::InitLoggingSnafu)?;
let tool = self.cmd.build().await.context(error::BuildCliSnafu)?;
let instance = Instance {
diff --git a/src/cmd/src/datanode/builder.rs b/src/cmd/src/datanode/builder.rs
index 6df7ac728e8..fc933a9c5be 100644
--- a/src/cmd/src/datanode/builder.rs
+++ b/src/cmd/src/datanode/builder.rs
@@ -67,7 +67,8 @@ impl InstanceBuilder {
&dn_opts.tracing,
dn_opts.node_id.map(|x| x.to_string()),
None,
- );
+ )
+ .context(crate::error::InitLoggingSnafu)?;
common_runtime::init_datanode_runtimes(&opts.runtime);
diff --git a/src/cmd/src/error.rs b/src/cmd/src/error.rs
index 7b0decf05ca..84553439ab1 100644
--- a/src/cmd/src/error.rs
+++ b/src/cmd/src/error.rs
@@ -23,6 +23,13 @@ use snafu::{Location, Snafu};
#[snafu(visibility(pub))]
#[stack_trace_debug]
pub enum Error {
+ #[snafu(display("Failed to initialize logging"))]
+ InitLogging {
+ #[snafu(implicit)]
+ location: Location,
+ source: common_telemetry::logging::InitLoggingError,
+ },
+
#[snafu(display("Failed to install ring crypto provider: {}", msg))]
InitTlsProvider {
#[snafu(implicit)]
@@ -337,6 +344,7 @@ pub type Result = std::result::Result;
impl ErrorExt for Error {
fn status_code(&self) -> StatusCode {
match self {
+ Error::InitLogging { source, .. } => source.status_code(),
Error::StartDatanode { source, .. } => source.status_code(),
Error::StartFrontend { source, .. } => source.status_code(),
Error::ShutdownDatanode { source, .. } => source.status_code(),
diff --git a/src/cmd/src/flownode.rs b/src/cmd/src/flownode.rs
index 0dfcf85e2e7..91faf313dc3 100644
--- a/src/cmd/src/flownode.rs
+++ b/src/cmd/src/flownode.rs
@@ -251,7 +251,8 @@ impl StartCommand {
&opts.component.tracing,
opts.component.node_id.map(|x| x.to_string()),
None,
- );
+ )
+ .context(crate::error::InitLoggingSnafu)?;
common_runtime::init_global_runtimes(&opts.runtime);
diff --git a/src/cmd/src/frontend.rs b/src/cmd/src/frontend.rs
index b9aa76f0f49..7a430d7619d 100644
--- a/src/cmd/src/frontend.rs
+++ b/src/cmd/src/frontend.rs
@@ -384,7 +384,8 @@ impl StartCommand {
&opts.component.tracing,
opts.component.node_id.clone(),
Some(&opts.component.slow_query),
- );
+ )
+ .context(crate::error::InitLoggingSnafu)?;
common_runtime::init_global_runtimes(&opts.runtime);
@@ -464,7 +465,9 @@ impl StartCommand {
)
.context(error::BuildCacheRegistrySnafu)?;
- if let Some(plugin_cache_builder) = plugins::frontend::configure_cache_registry(&plugins) {
+ if let Some(plugin_cache_builder) =
+ plugins::frontend::configure_cache_registry(&plugins, cached_meta_backend.clone())
+ {
layered_cache_builder =
layered_cache_builder.add_cache_registry(plugin_cache_builder.build());
}
diff --git a/src/cmd/src/metasrv.rs b/src/cmd/src/metasrv.rs
index 369f5c428d1..7df4b92ab00 100644
--- a/src/cmd/src/metasrv.rs
+++ b/src/cmd/src/metasrv.rs
@@ -324,7 +324,8 @@ impl StartCommand {
&opts.component.tracing,
None,
None,
- );
+ )
+ .context(crate::error::InitLoggingSnafu)?;
common_runtime::init_global_runtimes(&opts.runtime);
diff --git a/src/cmd/src/standalone.rs b/src/cmd/src/standalone.rs
index 0521aa9404f..934429517f4 100644
--- a/src/cmd/src/standalone.rs
+++ b/src/cmd/src/standalone.rs
@@ -54,7 +54,7 @@ use common_telemetry::{info, warn};
use common_time::timezone::set_default_timezone;
use common_version::{short_version, verbose_version};
use common_wal::config::DatanodeWalConfig;
-use common_wal::config::object_store::STANDALONE_GENERATION;
+use common_wal::config::object_store::FIXED_DIRECTORY_GENERATION;
use datanode::config::{DatanodeOptions, StorageConfig};
use datanode::datanode::{Datanode, DatanodeBuilder};
use datanode::region_server::RegionServer;
@@ -98,7 +98,7 @@ pub async fn build_standalone_wal_provider(
) -> Result {
match wal {
DatanodeWalConfig::ObjectStore(config) => Ok(WalProvider::ObjectStore {
- prefix: config.node_prefix(node_id.unwrap_or(0), STANDALONE_GENERATION),
+ prefix: config.node_prefix(node_id.unwrap_or(0), FIXED_DIRECTORY_GENERATION),
}),
DatanodeWalConfig::RaftEngine(_)
| DatanodeWalConfig::Kafka(_)
@@ -498,7 +498,8 @@ impl StartCommand {
&opts.component.tracing,
None,
Some(&opts.component.slow_query),
- );
+ )
+ .context(crate::error::InitLoggingSnafu)?;
common_runtime::init_standalone_runtimes(&opts.runtime);
@@ -1220,7 +1221,7 @@ mod tests {
..Default::default()
};
// The regions persist the node prefix the datanode runs its store under.
- let node_prefix = config.node_prefix(0, STANDALONE_GENERATION);
+ let node_prefix = config.node_prefix(0, FIXED_DIRECTORY_GENERATION);
assert_eq!(node_prefix, "cluster-a/wal/datanodes/0/epochs/0");
let provider = build_standalone_wal_provider(
&DatanodeWalConfig::ObjectStore(config),
diff --git a/src/cmd/tests/load_config_test.rs b/src/cmd/tests/load_config_test.rs
index 129fbc5a81c..4f2a68ba988 100644
--- a/src/cmd/tests/load_config_test.rs
+++ b/src/cmd/tests/load_config_test.rs
@@ -25,6 +25,7 @@ use common_options::datanode::{ClientOptions, DatanodeClientOptions};
use common_runtime::global::RuntimeOptions;
use common_telemetry::logging::{DEFAULT_LOGGING_DIR, DEFAULT_OTLP_HTTP_ENDPOINT, LoggingOptions};
use common_test_util::temp_dir::create_named_temp_file;
+use common_time::timestamp::TimeUnit;
use common_wal::config::DatanodeWalConfig;
use common_wal::config::raft_engine::RaftEngineConfig;
use datanode::config::{DatanodeOptions, RegionEngineConfig, StorageConfig};
@@ -249,6 +250,7 @@ fn test_load_frontend_example_config() {
default_timezone: Some("UTC".to_string()),
default_column_prefix: Some("greptime".to_string()),
auto_create_table: true,
+ auto_create_physical_table_timestamp_unit: TimeUnit::Millisecond,
meta_client: Some(MetaClientOptions {
metasrv_addrs: vec!["127.0.0.1:3002".to_string()],
timeout: Duration::from_secs(3),
@@ -430,6 +432,7 @@ fn test_load_standalone_example_config() {
default_timezone: Some("UTC".to_string()),
default_column_prefix: Some("greptime".to_string()),
auto_create_table: true,
+ auto_create_physical_table_timestamp_unit: TimeUnit::Millisecond,
wal: DatanodeWalConfig::RaftEngine(RaftEngineConfig {
dir: Some(format!("{}/{}", DEFAULT_DATA_HOME, WAL_DIR)),
sync_period: Some(Duration::from_secs(5)),
diff --git a/src/common/base/src/cancellation.rs b/src/common/base/src/cancellation.rs
index 94aa872834c..d08a1ba7b03 100644
--- a/src/common/base/src/cancellation.rs
+++ b/src/common/base/src/cancellation.rs
@@ -104,6 +104,8 @@ where
#[derive(Copy, Clone, Debug)]
pub struct Cancelled;
+impl std::error::Error for Cancelled {}
+
impl Display for Cancelled {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "Future has been cancelled")
diff --git a/src/common/meta/AGENTS.md b/src/common/meta/AGENTS.md
index 69d76d3c5ca..1be24b2ee9a 100644
--- a/src/common/meta/AGENTS.md
+++ b/src/common/meta/AGENTS.md
@@ -27,6 +27,10 @@ and durable DDL procedures. Metasrv process and service wiring live in
invalidation.
- Procedure changes must preserve persisted state and `TYPE_NAME`; new
procedures need loader registration in `src/common/meta/src/ddl_manager.rs`.
+- Database drops persist bounded logical-table batches before deleting metadata.
+ Replays must finish cache invalidation even after table-name keys are gone;
+ physical-region removal follows the logical phase. Keep the legacy single-table
+ executor readable for in-flight procedures from older versions.
- Marker-style table options that no region consumes (`greptime.semantic.*`,
`repartition.column.hint`) go through `AnnotationFamily` in
`src/table/src/requests.rs` — classification, validation, logical-table
diff --git a/src/common/meta/src/cache_invalidator.rs b/src/common/meta/src/cache_invalidator.rs
index edf84b00b83..5e781e9c7da 100644
--- a/src/common/meta/src/cache_invalidator.rs
+++ b/src/common/meta/src/cache_invalidator.rs
@@ -173,6 +173,10 @@ where
let key = NodeAddressKey::with_flownode(*node_id);
self.invalidate_key(&key.to_bytes()).await;
}
+ #[cfg(feature = "enterprise")]
+ CacheIdent::TriggerId(_) => {
+ // Trigger keys are owned by enterprise cache invalidators.
+ }
CacheIdent::User(_) => {
// User cache invalidation is handled by external
// CacheInvalidator implementations.
diff --git a/src/common/meta/src/ddl/alter_logical_tables.rs b/src/common/meta/src/ddl/alter_logical_tables.rs
index ccf130cec8c..ac70980329a 100644
--- a/src/common/meta/src/ddl/alter_logical_tables.rs
+++ b/src/common/meta/src/ddl/alter_logical_tables.rs
@@ -24,7 +24,7 @@ use common_procedure::{Context, EventContext, EventTrigger, LockKey, Procedure,
use common_telemetry::{debug, error, info, warn};
pub use executor::make_alter_region_request;
use serde::{Deserialize, Serialize};
-use snafu::{ResultExt, ensure};
+use snafu::ResultExt;
use store_api::metadata::ColumnMetadata;
use store_api::metric_engine_consts::ALTER_PHYSICAL_EXTENSION_KEY;
use strum::AsRefStr;
@@ -40,7 +40,7 @@ use crate::ddl::event::table::{
TableDdlEvent, TableDdlEventType, TableDdlLocator, alter_table_kind_name,
};
use crate::ddl::utils::{extract_column_metadatas, map_to_procedure_error, sync_follower_regions};
-use crate::error::{self, Result};
+use crate::error::Result;
use crate::instruction::CacheIdent;
use crate::key::DeserializedValueWithBytes;
use crate::key::table_info::TableInfoValue;
@@ -67,7 +67,7 @@ fn build_validator_from_alter_table_data<'a>(
.iter()
.map(|task| &task.alter_table)
.collect::>();
- AlterLogicalTableValidator::new(physical_table_id, alters)
+ AlterLogicalTableValidator::new(physical_table_id, alters, &data.logical_table_ids)
}
/// Builds the executor from the [`AlterTablesData`].
@@ -149,26 +149,6 @@ impl AlterLogicalTablesProcedure {
);
}
- // Locks are fixed at submission. A logical table that resolves to an
- // id outside the locked set here was dropped and recreated in between,
- // so this procedure holds no lock for it. Procedures restored from
- // pre-upgrade state have no recorded ids and keep the old behavior.
- if !self.data.logical_table_ids.is_empty() {
- for value in &table_info_values {
- let table_id = value.get_inner_ref().table_info.ident.table_id;
- ensure!(
- self.data.logical_table_ids.contains(&table_id),
- error::UnexpectedSnafu {
- err_msg: format!(
- "logical table {} (id {table_id}) is not covered by the \
- procedure locks; retry the statement",
- value.get_inner_ref().table_info.name
- ),
- }
- );
- }
- }
-
// Updates the procedure state.
retain_unskipped(&mut self.data.tasks, &skip_alter);
self.data.physical_table_info = Some(physical_table_info);
diff --git a/src/common/meta/src/ddl/alter_logical_tables/validator.rs b/src/common/meta/src/ddl/alter_logical_tables/validator.rs
index 7e6c130351f..af0c642d919 100644
--- a/src/common/meta/src/ddl/alter_logical_tables/validator.rs
+++ b/src/common/meta/src/ddl/alter_logical_tables/validator.rs
@@ -26,7 +26,7 @@ use crate::ddl::utils::table_info::{
};
use crate::error::{
AlterLogicalTablesInvalidArgumentsSnafu, Result, TableInfoNotFoundSnafu,
- TableRouteNotFoundSnafu,
+ TableRouteNotFoundSnafu, UnexpectedSnafu,
};
use crate::key::table_info::TableInfoValue;
use crate::key::table_route::{PhysicalTableRouteValue, TableRouteManager, TableRouteValue};
@@ -36,13 +36,19 @@ use crate::key::{DeserializedValueWithBytes, TableMetadataManagerRef};
pub struct AlterLogicalTableValidator<'a> {
physical_table_id: TableId,
alters: Vec<&'a AlterTableExpr>,
+ expected_table_ids: &'a [TableId],
}
impl<'a> AlterLogicalTableValidator<'a> {
- pub fn new(physical_table_id: TableId, alters: Vec<&'a AlterTableExpr>) -> Self {
+ pub fn new(
+ physical_table_id: TableId,
+ alters: Vec<&'a AlterTableExpr>,
+ expected_table_ids: &'a [TableId],
+ ) -> Self {
Self {
physical_table_id,
alters,
+ expected_table_ids,
}
}
@@ -187,6 +193,14 @@ impl<'a> AlterLogicalTableValidator<'a> {
let table_ids =
get_all_table_ids_by_names(table_metadata_manager.table_name_manager(), &table_names)
.await?;
+ // Check before skipping completed ALTERs, while the procedure holds the pinned ID locks.
+ // Old persisted procedures have no pinned IDs and retain their previous behavior.
+ ensure!(
+ self.expected_table_ids.is_empty() || self.expected_table_ids == table_ids,
+ UnexpectedSnafu {
+ err_msg: "logical tables changed and are not covered by the procedure locks; retry the statement",
+ }
+ );
let mut table_info_values = get_all_table_info_values_by_table_ids(
table_metadata_manager.table_info_manager(),
&table_ids,
diff --git a/src/common/meta/src/ddl/drop_database.rs b/src/common/meta/src/ddl/drop_database.rs
index 5bbd229ec5b..d083d4402b0 100644
--- a/src/common/meta/src/ddl/drop_database.rs
+++ b/src/common/meta/src/ddl/drop_database.rs
@@ -26,7 +26,7 @@ use common_procedure::{
Context as ProcedureContext, EventContext, EventTrigger, LockKey, Procedure,
Result as ProcedureResult, Status,
};
-use futures::stream::BoxStream;
+use futures::stream::{BoxStream, Peekable};
use serde::{Deserialize, Serialize};
use snafu::ResultExt;
use tonic::async_trait;
@@ -54,12 +54,14 @@ pub(crate) enum DropTableTarget {
Physical,
}
+type TableStream = Peekable>>;
+
/// Context of [DropDatabaseProcedure] execution.
pub(crate) struct DropDatabaseContext {
catalog: String,
schema: String,
drop_if_exists: bool,
- tables: Option>>,
+ tables: Option,
retrying: bool,
}
diff --git a/src/common/meta/src/ddl/drop_database/cursor.rs b/src/common/meta/src/ddl/drop_database/cursor.rs
index e060567be58..7e300efde86 100644
--- a/src/common/meta/src/ddl/drop_database/cursor.rs
+++ b/src/common/meta/src/ddl/drop_database/cursor.rs
@@ -13,21 +13,24 @@
// limitations under the License.
use std::any::Any;
+use std::collections::HashSet;
+use std::pin::Pin;
+use common_base::readable_size::ReadableSize;
use common_catalog::format_full_table_name;
use common_procedure::Status;
-use futures::TryStreamExt;
+use futures::{StreamExt, TryStreamExt};
use serde::{Deserialize, Serialize};
-use snafu::OptionExt;
+use snafu::{OptionExt, ensure};
use table::metadata::{TableId, TableType};
use table::table_name::TableName;
use crate::cache_invalidator::Context;
use crate::ddl::DdlContext;
-use crate::ddl::drop_database::executor::DropDatabaseExecutor;
+use crate::ddl::drop_database::executor::{DropDatabaseBatchExecutor, DropDatabaseExecutor};
use crate::ddl::drop_database::metadata::DropDatabaseRemoveMetadata;
use crate::ddl::drop_database::{DropDatabaseContext, DropTableTarget, State};
-use crate::error::{Result, TableInfoNotFoundSnafu};
+use crate::error::{Result, TableInfoNotFoundSnafu, UnexpectedSnafu};
use crate::instruction::CacheIdent;
use crate::key::table_route::TableRouteValue;
@@ -42,6 +45,123 @@ impl DropDatabaseCursor {
Self { target }
}
+ /// Collects a bounded page without mutating metadata. Only the executor's batch is durable.
+ async fn collect_logical_tables(
+ &mut self,
+ ddl_ctx: &DdlContext,
+ ctx: &mut DropDatabaseContext,
+ ) -> Result<(Box, Status)> {
+ let page = Self::collect_page(ctx).await?;
+ if page.is_empty() {
+ return self.handle_reach_end(ctx);
+ }
+ let tables = Self::logical_tables(ddl_ctx, ctx, page).await?;
+ if tables.is_empty() {
+ return Ok((Box::new(Self::new(self.target)), Status::executing(false)));
+ }
+ Ok((
+ Box::new(DropDatabaseBatchExecutor { tables }),
+ Status::executing(true),
+ ))
+ }
+
+ // Leave headroom below etcd's default 1.5 MiB request limit.
+ const MAX_BATCH_BYTES: usize = ReadableSize::mb(1).as_bytes() as usize;
+
+ fn estimated_table_bytes(catalog: &str, schema: &str, name: &str) -> usize {
+ // A control byte can expand to 6 JSON bytes, then 7 inside ProcedureMessage's
+ // JSON string. Round up to 8x and allow 128 bytes for fixed per-table JSON/key overhead.
+ 128 + 8 * (catalog.len() + schema.len() + name.len())
+ }
+
+ async fn collect_page(ctx: &mut DropDatabaseContext) -> Result> {
+ let mut page = Vec::new();
+ let mut bytes: usize = 0;
+ let tables = ctx.tables.as_mut().unwrap();
+ loop {
+ match Pin::new(&mut *tables).peek().await {
+ Some(Ok((name, _))) => {
+ let size = Self::estimated_table_bytes(&ctx.catalog, &ctx.schema, name);
+ if !page.is_empty() && bytes.saturating_add(size) > Self::MAX_BATCH_BYTES {
+ break;
+ }
+ // A single oversized name must still make progress. Procedure storage
+ // already splits oversized values; never strand an existing table here.
+ bytes = bytes.saturating_add(size);
+ }
+ Some(Err(_)) => {} // Consume below to propagate the owned error.
+ None => break,
+ }
+ let (name, value) = tables.try_next().await?.unwrap();
+ page.push((name, value.table_id()));
+ }
+ Ok(page)
+ }
+
+ async fn logical_tables(
+ ddl_ctx: &DdlContext,
+ ctx: &mut DropDatabaseContext,
+ page: Vec<(String, TableId)>,
+ ) -> Result> {
+ let manager = &ddl_ctx.table_metadata_manager;
+ let ids = page.iter().map(|(_, id)| *id).collect::>();
+ let infos = manager.table_info_manager().batch_get(&ids).await?;
+ let routes = manager
+ .table_route_manager()
+ .table_route_storage()
+ .batch_get(&ids)
+ .await?;
+ let physical_ids = routes
+ .iter()
+ .filter_map(|route| match route {
+ Some(TableRouteValue::Logical(route)) => Some(route.physical_table_id()),
+ _ => None,
+ })
+ .collect::>()
+ .into_iter()
+ .collect::>();
+ let physical_infos = manager
+ .table_info_manager()
+ .batch_get(&physical_ids)
+ .await?;
+ let mut tables = Vec::new();
+ for ((name, id), route) in page.into_iter().zip(routes) {
+ let info = infos.get(&id).with_context(|| TableInfoNotFoundSnafu {
+ table: format_full_table_name(&ctx.catalog, &ctx.schema, &name),
+ })?;
+ if info.table_info.table_type == TableType::View {
+ // Views are handled in the physical phase so collecting a batch has no side effects.
+ continue;
+ }
+ if let Some(TableRouteValue::Logical(route)) = route {
+ let physical = physical_infos
+ .get(&route.physical_table_id())
+ .with_context(|| TableInfoNotFoundSnafu {
+ table: route.physical_table_id().to_string(),
+ })?;
+ // Metadata-only deletion is safe only when the backing table is dropped with us.
+ ensure!(
+ physical.table_info.catalog_name == ctx.catalog
+ && physical.table_info.schema_name == ctx.schema,
+ UnexpectedSnafu {
+ err_msg: format!(
+ "Logical table {} references physical table {} (id {}) outside the dropped database",
+ format_full_table_name(&ctx.catalog, &ctx.schema, &name),
+ format_full_table_name(
+ &physical.table_info.catalog_name,
+ &physical.table_info.schema_name,
+ &physical.table_info.name,
+ ),
+ route.physical_table_id(),
+ ),
+ }
+ );
+ tables.push((id, TableName::new(&ctx.catalog, &ctx.schema, name)));
+ }
+ }
+ Ok(tables)
+ }
+
fn handle_reach_end(
&mut self,
ctx: &mut DropDatabaseContext,
@@ -62,32 +182,12 @@ impl DropDatabaseCursor {
async fn handle_table(
&mut self,
- ddl_ctx: &DdlContext,
ctx: &mut DropDatabaseContext,
table_name: String,
table_id: TableId,
table_route_value: TableRouteValue,
) -> Result<(Box, Status)> {
match (self.target, table_route_value) {
- (DropTableTarget::Logical, TableRouteValue::Logical(route)) => {
- let physical_table_id = route.physical_table_id();
-
- let (_, table_route) = ddl_ctx
- .table_metadata_manager
- .table_route_manager()
- .get_physical_table_route(physical_table_id)
- .await?;
- Ok((
- Box::new(DropDatabaseExecutor::new(
- table_id,
- table_id,
- TableName::new(&ctx.catalog, &ctx.schema, &table_name),
- table_route.region_routes,
- self.target,
- )),
- Status::executing(true),
- ))
- }
(DropTableTarget::Physical, TableRouteValue::Physical(table_route)) => Ok((
Box::new(DropDatabaseExecutor::new(
table_id,
@@ -104,7 +204,6 @@ impl DropDatabaseCursor {
)),
}
}
-
async fn handle_view(
&self,
ddl_ctx: &DdlContext,
@@ -148,50 +247,61 @@ impl State for DropDatabaseCursor {
ddl_ctx: &DdlContext,
ctx: &mut DropDatabaseContext,
) -> Result<(Box, Status)> {
- if ctx.tables.as_deref().is_none() {
+ if ctx.tables.is_none() {
let tables = ddl_ctx
.table_metadata_manager
.table_name_manager()
.tables(&ctx.catalog, &ctx.schema);
- ctx.tables = Some(tables);
+ ctx.tables = Some(tables.peekable());
}
- // Safety: must exist
- match ctx.tables.as_mut().unwrap().try_next().await? {
- Some((table_name, table_name_value)) => {
- let table_id = table_name_value.table_id();
+ let result = async {
+ if self.target == DropTableTarget::Logical {
+ return self.collect_logical_tables(ddl_ctx, ctx).await;
+ }
+ // Safety: must exist
+ match ctx.tables.as_mut().unwrap().try_next().await? {
+ Some((table_name, table_name_value)) => {
+ let table_id = table_name_value.table_id();
- let table_info_value = ddl_ctx
- .table_metadata_manager
- .table_info_manager()
- .get(table_id)
- .await?
- .with_context(|| TableInfoNotFoundSnafu {
- table: format_full_table_name(&ctx.catalog, &ctx.schema, &table_name),
- })?;
+ let table_info_value = ddl_ctx
+ .table_metadata_manager
+ .table_info_manager()
+ .get(table_id)
+ .await?
+ .with_context(|| TableInfoNotFoundSnafu {
+ table: format_full_table_name(&ctx.catalog, &ctx.schema, &table_name),
+ })?;
- if table_info_value.table_info.table_type == TableType::View {
- return self.handle_view(ddl_ctx, ctx, table_name, table_id).await;
- }
+ if table_info_value.table_info.table_type == TableType::View {
+ return self.handle_view(ddl_ctx, ctx, table_name, table_id).await;
+ }
- match ddl_ctx
- .table_metadata_manager
- .table_route_manager()
- .table_route_storage()
- .get(table_id)
- .await?
- {
- Some(table_route_value) => {
- self.handle_table(ddl_ctx, ctx, table_name, table_id, table_route_value)
- .await
+ match ddl_ctx
+ .table_metadata_manager
+ .table_route_manager()
+ .table_route_storage()
+ .get(table_id)
+ .await?
+ {
+ Some(table_route_value) => {
+ self.handle_table(ctx, table_name, table_id, table_route_value)
+ .await
+ }
+ None => Ok((
+ Box::new(DropDatabaseCursor::new(self.target)),
+ Status::executing(false),
+ )),
}
- None => Ok((
- Box::new(DropDatabaseCursor::new(self.target)),
- Status::executing(false),
- )),
}
+ None => self.handle_reach_end(ctx),
}
- None => self.handle_reach_end(ctx),
}
+ .await;
+ if result.is_err() {
+ // The entry was consumed but no deletion plan was persisted. Rescan on retry.
+ ctx.tables.take();
+ }
+ result
}
fn as_any(&self) -> &dyn Any {
@@ -206,12 +316,163 @@ mod tests {
use common_catalog::consts::{DEFAULT_CATALOG_NAME, DEFAULT_SCHEMA_NAME};
use crate::ddl::drop_database::cursor::DropDatabaseCursor;
- use crate::ddl::drop_database::executor::DropDatabaseExecutor;
+ use crate::ddl::drop_database::executor::{DropDatabaseBatchExecutor, DropDatabaseExecutor};
use crate::ddl::drop_database::metadata::DropDatabaseRemoveMetadata;
use crate::ddl::drop_database::{DropDatabaseContext, DropTableTarget, State};
use crate::ddl::test_util::{create_logical_table, create_physical_table};
use crate::test_util::{MockDatanodeManager, new_ddl_context};
+ #[tokio::test]
+ async fn test_cursor_read_failure_rescans() {
+ use crate::key::table_name::TableNameValue;
+ use futures::StreamExt;
+ for target in [DropTableTarget::Logical, DropTableTarget::Physical] {
+ let ddl = new_ddl_context(Arc::new(MockDatanodeManager::new(())));
+ let physical = create_physical_table(&ddl, "physical").await;
+ let mut ctx = DropDatabaseContext {
+ catalog: DEFAULT_CATALOG_NAME.into(),
+ schema: DEFAULT_SCHEMA_NAME.into(),
+ drop_if_exists: false,
+ retrying: false,
+ tables: Some(
+ futures::stream::iter(vec![Ok(("missing".into(), TableNameValue::new(99999)))])
+ .boxed()
+ .peekable(),
+ ),
+ };
+ let mut cursor = DropDatabaseCursor::new(target);
+ assert!(cursor.next(&ddl, &mut ctx).await.is_err());
+ assert!(ctx.tables.is_none());
+ let (state, _) = cursor.next(&ddl, &mut ctx).await.unwrap();
+ if target == DropTableTarget::Physical {
+ assert!(state.as_any().is::());
+ } else {
+ assert!(state.as_any().is::());
+ }
+ assert!(
+ ddl.table_metadata_manager
+ .table_info_manager()
+ .get(physical)
+ .await
+ .unwrap()
+ .is_some()
+ );
+ }
+ }
+
+ #[tokio::test]
+ async fn test_collect_page_oversized_singleton_makes_progress() {
+ use crate::key::table_name::TableNameValue;
+ use futures::StreamExt;
+ let mut ctx = DropDatabaseContext {
+ catalog: DEFAULT_CATALOG_NAME.into(),
+ schema: DEFAULT_SCHEMA_NAME.into(),
+ drop_if_exists: false,
+ retrying: false,
+ tables: Some(
+ futures::stream::iter(vec![
+ Ok((
+ "x".repeat(DropDatabaseCursor::MAX_BATCH_BYTES),
+ TableNameValue::new(1),
+ )),
+ Ok(("small".into(), TableNameValue::new(2))),
+ ])
+ .boxed()
+ .peekable(),
+ ),
+ };
+ let page = DropDatabaseCursor::collect_page(&mut ctx).await.unwrap();
+ assert_eq!(page.len(), 1);
+ assert_eq!(page[0].1, 1);
+ assert_eq!(
+ DropDatabaseCursor::collect_page(&mut ctx).await.unwrap(),
+ vec![("small".into(), 2)]
+ );
+ assert!(
+ DropDatabaseCursor::collect_page(&mut ctx)
+ .await
+ .unwrap()
+ .is_empty()
+ );
+ }
+
+ #[tokio::test]
+ async fn test_collect_page_limits_and_request_headroom() {
+ use common_procedure::store::ProcedureMessage;
+ use futures::StreamExt;
+ use table::table_name::TableName;
+
+ use crate::ddl::drop_database::DropDatabaseProcedure;
+ use crate::key::TableMetadataManager;
+ use crate::key::table_name::TableNameValue;
+ for name in [
+ "short".to_string(),
+ "x".repeat(64 * 1024),
+ "\"\\\n\u{0001}䏿–‡".repeat(4096),
+ ] {
+ let ddl = new_ddl_context(Arc::new(MockDatanodeManager::new(())));
+ let count = if name.len() < 1024 { 5000 } else { 65 };
+ let entries = (0..count)
+ .map(|id| Ok((name.clone(), TableNameValue::new(id))))
+ .collect::>();
+ let mut ctx = DropDatabaseContext {
+ catalog: DEFAULT_CATALOG_NAME.into(),
+ schema: DEFAULT_SCHEMA_NAME.into(),
+ drop_if_exists: false,
+ tables: Some(futures::stream::iter(entries).boxed().peekable()),
+ retrying: false,
+ };
+ let mut collected = Vec::new();
+ loop {
+ let page = DropDatabaseCursor::collect_page(&mut ctx).await.unwrap();
+ if page.is_empty() {
+ break;
+ }
+ let estimated = page
+ .iter()
+ .map(|(name, _)| {
+ DropDatabaseCursor::estimated_table_bytes(&ctx.catalog, &ctx.schema, name)
+ })
+ .sum::();
+ assert!(estimated <= DropDatabaseCursor::MAX_BATCH_BYTES);
+ let tables = page
+ .iter()
+ .map(|(name, id)| (*id, TableName::new(&ctx.catalog, &ctx.schema, name)))
+ .collect::>();
+ // Each delete has one bytes field nested in two messages. Allow
+ // 32 bytes per key for tags and length varints, plus a txn envelope.
+ let delete_bytes = 64
+ + tables
+ .iter()
+ .flat_map(|(id, name)| TableMetadataManager::table_identity_keys(*id, name))
+ .map(|key| key.len() + 32)
+ .sum::();
+ assert!(delete_bytes <= estimated);
+ let mut procedure = DropDatabaseProcedure::new(
+ ctx.catalog.clone(),
+ ctx.schema.clone(),
+ false,
+ ddl.clone(),
+ );
+ procedure.state = Box::new(DropDatabaseBatchExecutor { tables });
+ let message = ProcedureMessage {
+ type_name: DropDatabaseProcedure::TYPE_NAME.into(),
+ data: common_procedure::Procedure::dump(&procedure).unwrap(),
+ parent_id: None,
+ subprocedure_recovery: common_procedure::SubprocedureRecovery::Discard,
+ step: u32::MAX,
+ error: None,
+ context: Default::default(),
+ };
+ let serialized = serde_json::to_vec(&message).unwrap();
+ assert!(serialized.len() <= estimated);
+ assert!(serialized.len() + 512 * 1024 < 1536 * 1024);
+ collected.extend(page.into_iter().map(|(_, id)| id));
+ }
+ assert_eq!(collected, (0..count).collect::>());
+ }
+ }
+
#[tokio::test]
async fn test_next_without_logical_tables() {
let node_manager = Arc::new(MockDatanodeManager::new(()));
@@ -267,16 +528,10 @@ mod tests {
assert!(status.need_persist());
let executor = state
.as_any()
- .downcast_ref::()
+ .downcast_ref::()
.unwrap();
- let (_, table_route) = ddl_context
- .table_metadata_manager
- .table_route_manager()
- .get_physical_table_route(physical_table_id)
- .await
- .unwrap();
- assert_eq!(table_route.region_routes, executor.physical_region_routes);
- assert_eq!(executor.target, DropTableTarget::Logical);
+ assert_eq!(executor.tables.len(), 1);
+ assert_eq!(executor.tables[0].1.table_name, "metric_0");
}
#[tokio::test]
diff --git a/src/common/meta/src/ddl/drop_database/executor.rs b/src/common/meta/src/ddl/drop_database/executor.rs
index 1c01060c5ed..84d2eafe5fd 100644
--- a/src/common/meta/src/ddl/drop_database/executor.rs
+++ b/src/common/meta/src/ddl/drop_database/executor.rs
@@ -21,12 +21,14 @@ use snafu::OptionExt;
use table::metadata::TableId;
use table::table_name::TableName;
+use crate::cache_invalidator::Context;
use crate::ddl::DdlContext;
use crate::ddl::drop_database::cursor::DropDatabaseCursor;
use crate::ddl::drop_database::{DropDatabaseContext, DropTableTarget, State};
use crate::ddl::drop_table::executor::DropTableExecutor;
use crate::ddl::utils::get_region_wal_options;
use crate::error::{self, Result};
+use crate::instruction::CacheIdent;
use crate::key::table_route::TableRouteValue;
use crate::region_keeper::OperatingRegionGuard;
use crate::rpc::router::{RegionRoute, operating_leader_region_roles};
@@ -140,7 +142,7 @@ impl State for DropDatabaseExecutor {
&ddl_ctx.leader_region_registry,
&self.physical_region_routes,
true,
- false,
+ self.target == DropTableTarget::Physical,
false,
)
.await?;
@@ -157,6 +159,54 @@ impl State for DropDatabaseExecutor {
}
}
+/// A durable logical-table deletion batch. Physical regions are removed in the next phase.
+#[derive(Debug, Serialize, Deserialize)]
+pub(crate) struct DropDatabaseBatchExecutor {
+ pub(crate) tables: Vec<(TableId, TableName)>,
+}
+
+#[async_trait::async_trait]
+#[typetag::serde]
+impl State for DropDatabaseBatchExecutor {
+ async fn next(
+ &mut self,
+ ddl_ctx: &DdlContext,
+ _ctx: &mut DropDatabaseContext,
+ ) -> Result<(Box, Status)> {
+ ddl_ctx
+ .table_metadata_manager
+ .destroy_logical_tables_metadata(&self.tables)
+ .await?;
+ let idents = self
+ .tables
+ .iter()
+ .flat_map(|(id, name)| {
+ [
+ CacheIdent::TableId(*id),
+ CacheIdent::TableName(name.clone()),
+ ]
+ })
+ .collect::>();
+ ddl_ctx
+ .cache_invalidator
+ .invalidate(
+ &Context {
+ subject: Some("Invalidate logical tables by dropping database".to_string()),
+ },
+ &idents,
+ )
+ .await?;
+ Ok((
+ Box::new(DropDatabaseCursor::new(DropTableTarget::Logical)),
+ Status::executing(false),
+ ))
+ }
+
+ fn as_any(&self) -> &dyn Any {
+ self
+ }
+}
+
#[cfg(test)]
mod tests {
use std::collections::HashSet;
@@ -448,10 +498,13 @@ mod tests {
state.recover(&ddl_context).unwrap();
- let roles = ddl_context
+ let operating_regions = ddl_context
.memory_region_keeper
- .extract_operating_region_roles(7, &HashSet::from([region_id]));
- assert_eq!(roles.get(®ion_id), Some(&RegionRole::DowngradingLeader));
+ .extract_operating_regions(7, &HashSet::from([region_id]));
+ assert_eq!(
+ operating_regions.get(®ion_id).map(|region| region.role),
+ Some(RegionRole::DowngradingLeader)
+ );
}
#[tokio::test]
diff --git a/src/common/meta/src/ddl/tests/alter_logical_tables.rs b/src/common/meta/src/ddl/tests/alter_logical_tables.rs
index 619e02bb9b9..4dd915d1505 100644
--- a/src/common/meta/src/ddl/tests/alter_logical_tables.rs
+++ b/src/common/meta/src/ddl/tests/alter_logical_tables.rs
@@ -713,21 +713,27 @@ async fn test_on_prepare_rejects_table_outside_locked_set() {
let phy_id = create_physical_table(&ddl_context, "phy").await;
create_logical_table(ddl_context.clone(), phy_id, "table1").await;
- let tasks = vec![make_alter_logical_table_add_column_task(
- None,
- "table1",
- vec!["column1".to_string()],
- )];
-
// The table resolved at prepare time is not in the locked set, as if it
// had been dropped and recreated after submission.
let stale_locked_id = phy_id + 1000;
- let mut procedure =
- AlterLogicalTablesProcedure::new(tasks, phy_id, vec![stale_locked_id], ddl_context);
- let err = procedure.on_prepare().await.unwrap_err();
- assert!(
- err.to_string()
- .contains("not covered by the procedure locks"),
- "{err}"
- );
+ // A completed ADD must also reject rebinding, even when no schema changes are needed.
+ for column in ["column1", "host"] {
+ let tasks = vec![make_alter_logical_table_add_column_task(
+ None,
+ "table1",
+ vec![column.into()],
+ )];
+ let mut procedure = AlterLogicalTablesProcedure::new(
+ tasks,
+ phy_id,
+ vec![stale_locked_id],
+ ddl_context.clone(),
+ );
+ let err = procedure.on_prepare().await.unwrap_err();
+ assert!(
+ err.to_string()
+ .contains("not covered by the procedure locks"),
+ "{err}"
+ );
+ }
}
diff --git a/src/common/meta/src/ddl/tests/create_table.rs b/src/common/meta/src/ddl/tests/create_table.rs
index d39346e02da..e1c880fbf32 100644
--- a/src/common/meta/src/ddl/tests/create_table.rs
+++ b/src/common/meta/src/ddl/tests/create_table.rs
@@ -382,10 +382,13 @@ async fn test_memory_region_keeper_guard_dropped_on_procedure_done() {
.memory_region_keeper
.contains(datanode_id, region_id)
);
- let roles = ddl_context
+ let operating_regions = ddl_context
.memory_region_keeper
- .extract_operating_region_roles(datanode_id, &HashSet::from([region_id]));
- assert_eq!(roles.get(®ion_id), Some(&RegionRole::Leader));
+ .extract_operating_regions(datanode_id, &HashSet::from([region_id]));
+ assert_eq!(
+ operating_regions.get(®ion_id).map(|region| region.role),
+ Some(RegionRole::Leader)
+ );
execute_procedure_until_done(&mut procedure).await;
diff --git a/src/common/meta/src/ddl/tests/drop_database.rs b/src/common/meta/src/ddl/tests/drop_database.rs
index 05a70962bf0..049eb82e551 100644
--- a/src/common/meta/src/ddl/tests/drop_database.rs
+++ b/src/common/meta/src/ddl/tests/drop_database.rs
@@ -22,7 +22,7 @@ use common_procedure_test::{
use futures::TryStreamExt;
use crate::ddl::drop_database::DropDatabaseProcedure;
-use crate::ddl::drop_database::executor::DropDatabaseExecutor;
+use crate::ddl::drop_database::executor::{DropDatabaseBatchExecutor, DropDatabaseExecutor};
use crate::ddl::test_util::datanode_handler::{NaiveDatanodeHandler, RetryErrorDatanodeHandler};
use crate::ddl::test_util::{create_logical_table, create_physical_table};
use crate::key::schema_name::SchemaNameKey;
@@ -151,24 +151,15 @@ async fn test_drop_database_recover() {
ddl_context.clone(),
);
let num_operating_regions = 1;
- // Before dropping the logical table
+ // Recover the persisted logical batch before its metadata is removed.
execute_procedure_until(&mut procedure, |p| {
- p.state()
- .as_any()
- .downcast_ref::()
- .is_some()
+ p.state().as_any().is::()
})
.await;
- // Dump data
let data = procedure.dump().unwrap();
- assert_eq!(ddl_context.memory_region_keeper.len(), 0);
let mut procedure = DropDatabaseProcedure::from_json(&data, ddl_context.clone()).unwrap();
procedure.recover().unwrap();
- assert_eq!(
- ddl_context.memory_region_keeper.len(),
- num_operating_regions
- );
- ddl_context.memory_region_keeper.clear();
+ assert_eq!(ddl_context.memory_region_keeper.len(), 0);
// Before dropping the physical table
execute_procedure_until(&mut procedure, |p| {
p.state()
@@ -197,3 +188,304 @@ async fn test_drop_database_recover() {
.unwrap();
assert!(tables.is_empty());
}
+
+#[tokio::test]
+async fn test_drop_database_batches_recover_after_metadata_deletion() {
+ use crate::ddl::test_util::datanode_handler::DatanodeWatcher;
+ use api::v1::region::region_request::Body;
+ use store_api::storage::RegionId;
+
+ // A full batch, multiple batches, and a trailing partial batch.
+ for (count, name_padding, expected_batches) in
+ [(0, 0, 0), (1, 0, 1), (64, 0, 1), (129, 0, 1), (20, 8192, 2)]
+ {
+ let (tx, mut rx) = tokio::sync::mpsc::channel(16);
+ let ddl = new_ddl_context(Arc::new(MockDatanodeManager::new(DatanodeWatcher::new(tx))));
+ ddl.table_metadata_manager
+ .schema_manager()
+ .create(
+ SchemaNameKey::new(DEFAULT_CATALOG_NAME, DEFAULT_SCHEMA_NAME),
+ None,
+ false,
+ )
+ .await
+ .unwrap();
+ let physical = create_physical_table(&ddl, "z_physical").await;
+ let mut ids = Vec::new();
+ for i in 0..count {
+ create_logical_table(
+ ddl.clone(),
+ physical,
+ &format!("logical_{i:04}{}", "x".repeat(name_padding)),
+ )
+ .await;
+ }
+ let mut procedure = DropDatabaseProcedure::new(
+ DEFAULT_CATALOG_NAME.into(),
+ DEFAULT_SCHEMA_NAME.into(),
+ false,
+ ddl.clone(),
+ );
+ let ctx = ProcedureContext {
+ procedure_id: ProcedureId::random(),
+ provider: Arc::new(MockContextProvider::default()),
+ event_context: None,
+ };
+ let mut batches = 0;
+ loop {
+ if let Some(batch) = procedure
+ .state()
+ .as_any()
+ .downcast_ref::()
+ {
+ ids.extend(batch.tables.iter().map(|(id, _)| *id));
+ // Crash after keys are gone but before cache invalidation and cursor advancement.
+ let dump = procedure.dump().unwrap();
+ ddl.table_metadata_manager
+ .destroy_logical_tables_metadata(&batch.tables)
+ .await
+ .unwrap();
+ procedure = DropDatabaseProcedure::from_json(&dump, ddl.clone()).unwrap();
+ procedure.recover().unwrap();
+ batches += 1;
+ }
+ if procedure.execute(&ctx).await.unwrap().is_done() {
+ break;
+ }
+ }
+ assert_eq!(ids.len(), count);
+ assert_eq!(batches, expected_batches);
+ let (_, request) = rx.try_recv().unwrap();
+ let Some(Body::Drop(drop)) = request.body else {
+ panic!("expected physical drop")
+ };
+ assert_eq!(RegionId::from_u64(drop.region_id).table_id(), physical);
+ assert!(drop.force);
+ assert!(
+ rx.try_recv().is_err(),
+ "logical tables must not send region RPCs"
+ );
+ assert!(
+ ddl.table_metadata_manager
+ .table_info_manager()
+ .batch_get(&ids)
+ .await
+ .unwrap()
+ .is_empty()
+ );
+ assert!(
+ ddl.table_metadata_manager
+ .table_name_manager()
+ .tables(DEFAULT_CATALOG_NAME, DEFAULT_SCHEMA_NAME)
+ .try_collect::>()
+ .await
+ .unwrap()
+ .is_empty()
+ );
+ }
+}
+
+#[tokio::test]
+async fn test_drop_database_legacy_state_fixture() {
+ let ddl = new_ddl_context(Arc::new(MockDatanodeManager::new(NaiveDatanodeHandler)));
+ // Single-table executor state from f8d8fe1071, before logical-table batching.
+ let fixture = r#"{
+ "catalog": "greptime",
+ "schema": "public",
+ "drop_if_exists": false,
+ "state": {
+ "drop_database_state": "DropDatabaseExecutor",
+ "table_id": 1025,
+ "physical_table_id": 1025,
+ "table_name": {
+ "catalog_name": "greptime",
+ "schema_name": "public",
+ "table_name": "logical"
+ },
+ "physical_region_routes": [],
+ "target": "Logical"
+ }
+}"#;
+ let mut procedure = DropDatabaseProcedure::from_json(fixture, ddl).unwrap();
+ procedure.recover().unwrap();
+ assert!(procedure.state().as_any().is::());
+ assert_eq!(
+ serde_json::from_str::(fixture).unwrap(),
+ serde_json::from_str::(&procedure.dump().unwrap()).unwrap()
+ );
+}
+
+#[tokio::test]
+async fn test_drop_database_batch_cache_failure_recovery() {
+ use crate::cache_invalidator::{CacheInvalidator, Context};
+ use crate::instruction::CacheIdent;
+ use std::sync::Mutex;
+ use std::sync::atomic::{AtomicBool, Ordering};
+
+ struct FailingInvalidator {
+ fail: AtomicBool,
+ calls: Mutex>>,
+ }
+ #[async_trait::async_trait]
+ impl CacheInvalidator for FailingInvalidator {
+ async fn invalidate(&self, _: &Context, caches: &[CacheIdent]) -> crate::error::Result<()> {
+ self.calls.lock().unwrap().push(caches.to_vec());
+ if self.fail.swap(false, Ordering::Relaxed) {
+ return crate::error::UnexpectedSnafu {
+ err_msg: "injected cache failure",
+ }
+ .fail();
+ }
+ Ok(())
+ }
+ fn invalidate_all(&self) -> crate::error::Result<()> {
+ // This test invalidator owns only call records, not cached metadata.
+ Ok(())
+ }
+ }
+ let invalidator = Arc::new(FailingInvalidator {
+ fail: AtomicBool::new(false),
+ calls: Mutex::new(Vec::new()),
+ });
+ let mut ddl = new_ddl_context(Arc::new(MockDatanodeManager::new(NaiveDatanodeHandler)));
+ ddl.cache_invalidator = invalidator.clone();
+ ddl.table_metadata_manager
+ .schema_manager()
+ .create(
+ SchemaNameKey::new(DEFAULT_CATALOG_NAME, DEFAULT_SCHEMA_NAME),
+ None,
+ false,
+ )
+ .await
+ .unwrap();
+ let physical = create_physical_table(&ddl, "physical").await;
+ create_logical_table(ddl.clone(), physical, "logical").await;
+ let mut procedure = DropDatabaseProcedure::new(
+ DEFAULT_CATALOG_NAME.into(),
+ DEFAULT_SCHEMA_NAME.into(),
+ false,
+ ddl.clone(),
+ );
+ execute_procedure_until(&mut procedure, |p| {
+ p.state().as_any().is::()
+ })
+ .await;
+ let dump = procedure.dump().unwrap();
+ invalidator.calls.lock().unwrap().clear();
+ invalidator.fail.store(true, Ordering::Relaxed);
+ let ctx = ProcedureContext {
+ procedure_id: ProcedureId::random(),
+ provider: Arc::new(MockContextProvider::default()),
+ event_context: None,
+ };
+ assert!(procedure.execute(&ctx).await.is_err());
+ assert_eq!(procedure.dump().unwrap(), dump);
+ let mut restored = DropDatabaseProcedure::from_json(&dump, ddl).unwrap();
+ restored.recover().unwrap();
+ restored.execute(&ctx).await.unwrap();
+ let calls = invalidator.calls.lock().unwrap();
+ assert_eq!(calls.len(), 2);
+ assert_eq!(calls[0], calls[1]);
+ assert_eq!(calls[0].len(), 2);
+}
+
+#[tokio::test]
+async fn test_drop_database_mixed_table_order_and_recovery() {
+ use crate::ddl::test_util::create_table::test_create_table_task;
+ use crate::ddl::tests::create_view::{test_create_view_task, test_table_names};
+ use crate::key::table_route::TableRouteValue;
+ use itertools::Itertools;
+ use std::collections::HashMap;
+
+ // Every relative ordering of metric physical, logical, mito and view names.
+ for names in ["a", "b", "c", "d"].into_iter().permutations(4) {
+ for recover in [false, true] {
+ let ddl = new_ddl_context(Arc::new(MockDatanodeManager::new(NaiveDatanodeHandler)));
+ let manager = &ddl.table_metadata_manager;
+ manager
+ .schema_manager()
+ .create(
+ SchemaNameKey::new(DEFAULT_CATALOG_NAME, DEFAULT_SCHEMA_NAME),
+ None,
+ false,
+ )
+ .await
+ .unwrap();
+ let physical = create_physical_table(&ddl, names[0]).await;
+ let logical = create_logical_table(ddl.clone(), physical, names[1]).await;
+ let mito = test_create_table_task(names[2], 20000);
+ manager
+ .create_table_metadata(
+ mito.table_info,
+ TableRouteValue::physical(vec![]),
+ HashMap::new(),
+ )
+ .await
+ .unwrap();
+ let mut view = test_create_view_task(names[3]);
+ view.view_info.ident.table_id = 20001;
+ manager
+ .create_view_metadata(
+ view.view_info,
+ view.create_view.logical_plan,
+ test_table_names(),
+ vec![],
+ vec![],
+ "definition".into(),
+ )
+ .await
+ .unwrap();
+ let mut procedure = DropDatabaseProcedure::new(
+ DEFAULT_CATALOG_NAME.into(),
+ DEFAULT_SCHEMA_NAME.into(),
+ false,
+ ddl.clone(),
+ );
+ let ctx = ProcedureContext {
+ procedure_id: ProcedureId::random(),
+ provider: Arc::new(MockContextProvider::default()),
+ event_context: None,
+ };
+ let mut done = false;
+ for _ in 0..40 {
+ let status = procedure.execute(&ctx).await.unwrap();
+ if status.is_done() {
+ done = true;
+ break;
+ }
+ if recover && status.need_persist() {
+ let dump = procedure.dump().unwrap();
+ drop(procedure);
+ procedure = DropDatabaseProcedure::from_json(&dump, ddl.clone()).unwrap();
+ procedure.recover().unwrap();
+ }
+ }
+ assert!(done, "{names:?}, recovery={recover}");
+ assert!(
+ manager
+ .table_name_manager()
+ .tables(DEFAULT_CATALOG_NAME, DEFAULT_SCHEMA_NAME)
+ .try_collect::>()
+ .await
+ .unwrap()
+ .is_empty()
+ );
+ assert!(
+ manager
+ .table_info_manager()
+ .batch_get(&[physical, logical, 20000, 20001])
+ .await
+ .unwrap()
+ .is_empty()
+ );
+ assert!(
+ manager
+ .view_info_manager()
+ .get(20001)
+ .await
+ .unwrap()
+ .is_none()
+ );
+ }
+ }
+}
diff --git a/src/common/meta/src/ddl/tests/drop_table.rs b/src/common/meta/src/ddl/tests/drop_table.rs
index a278b951dd5..40505c28fa2 100644
--- a/src/common/meta/src/ddl/tests/drop_table.rs
+++ b/src/common/meta/src/ddl/tests/drop_table.rs
@@ -2782,10 +2782,13 @@ async fn test_memory_region_keeper_guard_dropped_on_procedure_done() {
.memory_region_keeper
.contains(datanode_id, region_id)
);
- let roles = ddl_context
+ let operating_regions = ddl_context
.memory_region_keeper
- .extract_operating_region_roles(datanode_id, &HashSet::from([region_id]));
- assert_eq!(roles.get(®ion_id), Some(&RegionRole::Leader));
+ .extract_operating_regions(datanode_id, &HashSet::from([region_id]));
+ assert_eq!(
+ operating_regions.get(®ion_id).map(|region| region.role),
+ Some(RegionRole::Leader)
+ );
execute_procedure_until_done(&mut procedure).await;
diff --git a/src/common/meta/src/ddl_manager.rs b/src/common/meta/src/ddl_manager.rs
index 5078328443d..87a0ddae91b 100644
--- a/src/common/meta/src/ddl_manager.rs
+++ b/src/common/meta/src/ddl_manager.rs
@@ -625,13 +625,22 @@ impl DdlManager {
&self,
alter_table_tasks: Vec,
physical_table_id: TableId,
+ expected_table_ids: Option>,
procedure_context: ProcedureContext,
) -> Result<(ProcedureId, Option