chore: merge latest main into JSONL COPY branch

Signed-off-by: Ning Sun <sunning@greptime.com>
This commit is contained in:
Ning Sun
2026-11-17 14:16:28 -08:00
192 changed files with 16362 additions and 1922 deletions
Generated
+5 -1
View File
@@ -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",
+3 -1
View File
@@ -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"
+14 -12
View File
@@ -13,11 +13,12 @@
| Key | Type | Default | Descriptions |
| --- | -----| ------- | ----------- |
| `default_timezone` | String | Unset | The default timezone of the server. |
| `default_column_prefix` | String | Unset | The default column prefix for auto-created time index, value, and native histogram columns.<br/>Legacy OTLP summary columns keep their historical `greptime_` prefix. |
| `default_column_prefix` | String | Unset | The default column prefix for auto-created time index, value, native histogram, and exemplar-label columns.<br/>Legacy OTLP summary columns keep their historical `greptime_` prefix. |
| `auto_create_table` | Bool | `true` | Server-side global switch for auto table creation on write.<br/>When `false`, a missing table is never auto-created even if the request sets the `auto_create_table` hint to `true`. Default: `true`. |
| `auto_create_physical_table_timestamp_unit` | String | Unset | Time index unit for physical metric tables created by auto table creation<br/>(Prometheus remote write, OTLP metrics, and other metric-engine ingestion).<br/>New logical tables created under such a physical table inherit its unit.<br/>Options: "Second", "Millisecond" (default), "Microsecond", "Nanosecond". |
| `user_provider` | String | Unset | The user provider for authentication.<br/>Examples: "static_user_provider:file:/path/to/users", "static_user_provider:cmd:greptime_user=greptime_pwd"<br/>Password verifier formats: "plain:<password>", "pbkdf2_sha256:<iterations>:<hex_salt>:<hex_hash>",<br/>"mysql_native_password:<hex_sha1_sha1_password>",<br/>"pg_scram_sha256:<iterations>:<hex_salt>:<hex_stored_key>:<hex_server_key>"<br/>"pbkdf2_sha256" and "pg_scram_sha256" protect passwords at rest, but such users cannot log in over MySQL:<br/>`static_user_provider` and `watch_file_user_provider` only negotiate `mysql_native_password`, which cannot verify these formats.<br/>"mysql_native_password" is MySQL-specific and cannot authenticate over PostgreSQL at all.<br/>PostgreSQL SCRAM only covers "plain" and "pg_scram_sha256" users; if any user is "pbkdf2_sha256" or<br/>"mysql_native_password", PostgreSQL falls back to cleartext password auth for every user.<br/>For "pg_scram_sha256" users, keep the default iteration count (4096) and salt length (16): both are<br/>observable in the SCRAM server-first message, and non-default values weaken resistance to username<br/>enumeration. |
| `max_in_flight_write_bytes` | String | 0 | Maximum total memory for all concurrent write request bodies and messages (HTTP, gRPC, Flight).<br/>Set to 0 to disable the limit. Default: "0" (unlimited) |
| `write_bytes_exhausted_policy` | String | `wait` | Policy when write bytes quota is exhausted.<br/>Options: "wait" (default, 10s timeout), "wait(<duration>)" (e.g., "wait(30s)"), "fail" |
| `max_in_flight_write_bytes` | String | 0 | Shared quota for concurrent write request bodies and messages (HTTP, gRPC, Flight)<br/>plus retained decoder memory and estimated PB-to-Arrow conversion memory for ordinary-table batching.<br/>A batch must fit together with its request's existing reservations; only additional memory is acquired.<br/>Set to 0 to disable the limit. Default: "0" (unlimited) |
| `write_bytes_exhausted_policy` | String | `wait` | Policy when write bytes quota is exhausted.<br/>Options: "wait" (default, 10s timeout), "wait(<duration>)" (e.g., "wait(30s)"), "fail"<br/>Table-batch conversion never waits for additional memory. Under a wait policy,<br/>temporary contention returns a retryable error; requests that cannot fit are rejected. |
| `init_regions_in_background` | Bool | `false` | Initialize all regions in the background during the startup.<br/>By default, it provides services after all regions have been initialized. |
| `init_regions_parallelism` | Integer | `16` | Parallelism of initializing regions. |
| `max_concurrent_queries` | Integer | `0` | The maximum concurrent region-read streams. Zero means unlimited.<br/>A single query can consume multiple permits. |
@@ -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`.<br/>Old closed log files are removed before writing when necessary. Active files may exceed it. Set to `0B` to disable. |
| `logging.max_log_dir_size` | String | `0B` | The maximum total size of managed log files in `dir`.<br/>Old closed log files are removed before writing when necessary. Active files may exceed it. Set to `0B` to disable.<br/>Requires symbolic links in the log directory; initialization fails if they cannot be created.<br/>On Windows, enable Developer Mode or leave this at `0B`. |
| `logging.enable_per_region_metrics` | Bool | `false` | Whether to enable per-region metrics.<br/>Default to false. |
| `logging.otlp_export_protocol` | String | `http` | The OTLP tracing export protocol. Can be `grpc`/`http`. |
| `logging.otlp_headers` | -- | -- | Additional OTLP headers, only valid when using OTLP http |
@@ -291,11 +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.<br/>Legacy OTLP summary columns keep their historical `greptime_` prefix. |
| `default_column_prefix` | String | Unset | The default column prefix for auto-created time index, value, native histogram, and exemplar-label columns.<br/>Legacy OTLP summary columns keep their historical `greptime_` prefix. |
| `auto_create_table` | Bool | `true` | Server-side global switch for auto table creation on write.<br/>When `false`, a missing table is never auto-created even if the request sets the `auto_create_table` hint to `true`. Default: `true`. |
| `auto_create_physical_table_timestamp_unit` | String | Unset | Time index unit for physical metric tables created by auto table creation<br/>(Prometheus remote write, OTLP metrics, and other metric-engine ingestion).<br/>New logical tables created under such a physical table inherit its unit.<br/>Options: "Second", "Millisecond" (default), "Microsecond", "Nanosecond". |
| `user_provider` | String | Unset | The user provider for authentication.<br/>Examples: "static_user_provider:file:/path/to/users", "static_user_provider:cmd:greptime_user=greptime_pwd"<br/>Password verifier formats: "plain:<password>", "pbkdf2_sha256:<iterations>:<hex_salt>:<hex_hash>",<br/>"mysql_native_password:<hex_sha1_sha1_password>",<br/>"pg_scram_sha256:<iterations>:<hex_salt>:<hex_stored_key>:<hex_server_key>"<br/>"pbkdf2_sha256" and "pg_scram_sha256" protect passwords at rest, but such users cannot log in over MySQL:<br/>`static_user_provider` and `watch_file_user_provider` only negotiate `mysql_native_password`, which cannot verify these formats.<br/>"mysql_native_password" is MySQL-specific and cannot authenticate over PostgreSQL at all.<br/>PostgreSQL SCRAM only covers "plain" and "pg_scram_sha256" users; if any user is "pbkdf2_sha256" or<br/>"mysql_native_password", PostgreSQL falls back to cleartext password auth for every user.<br/>For "pg_scram_sha256" users, keep the default iteration count (4096) and salt length (16): both are<br/>observable in the SCRAM server-first message, and non-default values weaken resistance to username<br/>enumeration. |
| `max_in_flight_write_bytes` | String | 0 | Maximum total memory for all concurrent write request bodies and messages (HTTP, gRPC, Flight).<br/>Set to 0 to disable the limit. Default: "0" (unlimited) |
| `write_bytes_exhausted_policy` | String | `wait` | Policy when write bytes quota is exhausted.<br/>Options: "wait" (default, 10s timeout), "wait(<duration>)" (e.g., "wait(30s)"), "fail" |
| `max_in_flight_write_bytes` | String | 0 | Shared quota for concurrent write request bodies and messages (HTTP, gRPC, Flight)<br/>plus retained decoder memory and estimated PB-to-Arrow conversion memory for ordinary-table batching.<br/>A batch must fit together with its request's existing reservations; only additional memory is acquired.<br/>Set to 0 to disable the limit. Default: "0" (unlimited) |
| `write_bytes_exhausted_policy` | String | `wait` | Policy when write bytes quota is exhausted.<br/>Options: "wait" (default, 10s timeout), "wait(<duration>)" (e.g., "wait(30s)"), "fail"<br/>Table-batch conversion never waits for additional memory. Under a wait policy,<br/>temporary contention returns a retryable error; requests that cannot fit are rejected. |
| `runtime` | -- | -- | The runtime options. |
| `runtime.global_rt_size` | Integer | Auto | The number of threads to execute the runtime for global read operations.<br/>Defaults to max(num_cpus, 2). |
| `runtime.compact_rt_size` | Integer | Auto | The number of threads to execute compact operations.<br/>Defaults to max(num_cpus / 2, 2). |
@@ -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`.<br/>Old closed log files are removed before writing when necessary. Active files may exceed it. Set to `0B` to disable. |
| `logging.max_log_dir_size` | String | `0B` | The maximum total size of managed log files in `dir`.<br/>Old closed log files are removed before writing when necessary. Active files may exceed it. Set to `0B` to disable.<br/>Requires symbolic links in the log directory; initialization fails if they cannot be created.<br/>On Windows, enable Developer Mode or leave this at `0B`. |
| `logging.enable_per_region_metrics` | Bool | `false` | Whether to enable per-region metrics.<br/>Default to false. |
| `logging.otlp_export_protocol` | String | `http` | The OTLP tracing export protocol. Can be `grpc`/`http`. |
| `logging.otlp_headers` | -- | -- | Additional OTLP headers, only valid when using OTLP http |
@@ -539,7 +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`.<br/>Old closed log files are removed before writing when necessary. Active files may exceed it. Set to `0B` to disable. |
| `logging.max_log_dir_size` | String | `0B` | The maximum total size of managed log files in `dir`.<br/>Old closed log files are removed before writing when necessary. Active files may exceed it. Set to `0B` to disable.<br/>Requires symbolic links in the log directory; initialization fails if they cannot be created.<br/>On Windows, enable Developer Mode or leave this at `0B`. |
| `logging.otlp_export_protocol` | String | `http` | The OTLP tracing export protocol. Can be `grpc`/`http`. |
| `logging.otlp_headers` | -- | -- | Additional OTLP headers, only valid when using OTLP http |
| `logging.tracing_sample_ratio` | -- | Unset | The percentage of tracing will be sampled and exported.<br/>Valid range `[0, 1]`, 1 means all traces are sampled, 0 means all traces are not sampled, the default value is 1.<br/>ratio > 1 are treated as 1. Fractions < 0 are treated as 0 |
@@ -555,7 +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.<br/>Legacy OTLP summary columns keep their historical `greptime_` prefix. |
| `default_column_prefix` | String | Unset | The default column prefix for auto-created time index, value, native histogram, and exemplar-label columns.<br/>Legacy OTLP summary columns keep their historical `greptime_` prefix. |
| `require_lease_before_startup` | Bool | `false` | Start services after regions have obtained leases.<br/>It will block the datanode start if it can't receive leases in the heartbeat from metasrv. |
| `init_regions_in_background` | Bool | `false` | Initialize all regions in the background during the startup.<br/>By default, it provides services after all regions have been initialized. |
| `init_regions_parallelism` | Integer | `16` | Parallelism of initializing regions. |
@@ -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`.<br/>Old closed log files are removed before writing when necessary. Active files may exceed it. Set to `0B` to disable. |
| `logging.max_log_dir_size` | String | `0B` | The maximum total size of managed log files in `dir`.<br/>Old closed log files are removed before writing when necessary. Active files may exceed it. Set to `0B` to disable.<br/>Requires symbolic links in the log directory; initialization fails if they cannot be created.<br/>On Windows, enable Developer Mode or leave this at `0B`. |
| `logging.otlp_export_protocol` | String | `http` | The OTLP tracing export protocol. Can be `grpc`/`http`. |
| `logging.otlp_headers` | -- | -- | Additional OTLP headers, only valid when using OTLP http |
| `logging.tracing_sample_ratio` | -- | Unset | The percentage of tracing will be sampled and exported.<br/>Valid range `[0, 1]`, 1 means all traces are sampled, 0 means all traces are not sampled, the default value is 1.<br/>ratio > 1 are treated as 1. Fractions < 0 are treated as 0 |
@@ -807,7 +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`.<br/>Old closed log files are removed before writing when necessary. Active files may exceed it. Set to `0B` to disable. |
| `logging.max_log_dir_size` | String | `0B` | The maximum total size of managed log files in `dir`.<br/>Old closed log files are removed before writing when necessary. Active files may exceed it. Set to `0B` to disable.<br/>Requires symbolic links in the log directory; initialization fails if they cannot be created.<br/>On Windows, enable Developer Mode or leave this at `0B`. |
| `logging.otlp_export_protocol` | String | `http` | The OTLP tracing export protocol. Can be `grpc`/`http`. |
| `logging.otlp_headers` | -- | -- | Additional OTLP headers, only valid when using OTLP http |
| `logging.tracing_sample_ratio` | -- | Unset | The percentage of tracing will be sampled and exported.<br/>Valid range `[0, 1]`, 1 means all traces are sampled, 0 means all traces are not sampled, the default value is 1.<br/>ratio > 1 are treated as 1. Fractions < 0 are treated as 0 |
+3 -1
View File
@@ -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`.
+2
View File
@@ -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`.
+15 -2
View File
@@ -2,7 +2,7 @@
## @toml2docs:none-default
default_timezone = "UTC"
## The default column prefix for auto-created time index, value, and native histogram columns.
## The default column prefix for auto-created time index, value, native histogram, and exemplar-label columns.
## Legacy OTLP summary columns keep their historical `greptime_` prefix.
## @toml2docs:none-default
default_column_prefix = "greptime"
@@ -11,6 +11,13 @@ default_column_prefix = "greptime"
## When `false`, a missing table is never auto-created even if the request sets the `auto_create_table` hint to `true`. Default: `true`.
#+ auto_create_table = true
## Time index unit for physical metric tables created by auto table creation
## (Prometheus remote write, OTLP metrics, and other metric-engine ingestion).
## New logical tables created under such a physical table inherit its unit.
## Options: "Second", "Millisecond" (default), "Microsecond", "Nanosecond".
## @toml2docs:none-default
#+ auto_create_physical_table_timestamp_unit = "Millisecond"
## The user provider for authentication.
## Examples: "static_user_provider:file:/path/to/users", "static_user_provider:cmd:greptime_user=greptime_pwd"
## Password verifier formats: "plain:<password>", "pbkdf2_sha256:<iterations>:<hex_salt>:<hex_hash>",
@@ -27,13 +34,17 @@ default_column_prefix = "greptime"
## @toml2docs:none-default
#+ user_provider = "static_user_provider:file:/path/to/users"
## Maximum total memory for all concurrent write request bodies and messages (HTTP, gRPC, Flight).
## Shared quota for concurrent write request bodies and messages (HTTP, gRPC, Flight)
## plus retained decoder memory and estimated PB-to-Arrow conversion memory for ordinary-table batching.
## A batch must fit together with its request's existing reservations; only additional memory is acquired.
## Set to 0 to disable the limit. Default: "0" (unlimited)
## @toml2docs:none-default="0"
#+ max_in_flight_write_bytes = "1GB"
## Policy when write bytes quota is exhausted.
## Options: "wait" (default, 10s timeout), "wait(<duration>)" (e.g., "wait(30s)"), "fail"
## Table-batch conversion never waits for additional memory. Under a wait policy,
## temporary contention returns a retryable error; requests that cannot fit are rejected.
#+ write_bytes_exhausted_policy = "wait"
## The runtime options.
@@ -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.
+2
View File
@@ -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`.
+15 -2
View File
@@ -2,7 +2,7 @@
## @toml2docs:none-default
default_timezone = "UTC"
## The default column prefix for auto-created time index, value, and native histogram columns.
## The default column prefix for auto-created time index, value, native histogram, and exemplar-label columns.
## Legacy OTLP summary columns keep their historical `greptime_` prefix.
## @toml2docs:none-default
default_column_prefix = "greptime"
@@ -11,6 +11,13 @@ default_column_prefix = "greptime"
## When `false`, a missing table is never auto-created even if the request sets the `auto_create_table` hint to `true`. Default: `true`.
#+ auto_create_table = true
## Time index unit for physical metric tables created by auto table creation
## (Prometheus remote write, OTLP metrics, and other metric-engine ingestion).
## New logical tables created under such a physical table inherit its unit.
## Options: "Second", "Millisecond" (default), "Microsecond", "Nanosecond".
## @toml2docs:none-default
#+ auto_create_physical_table_timestamp_unit = "Millisecond"
## The user provider for authentication.
## Examples: "static_user_provider:file:/path/to/users", "static_user_provider:cmd:greptime_user=greptime_pwd"
## Password verifier formats: "plain:<password>", "pbkdf2_sha256:<iterations>:<hex_salt>:<hex_hash>",
@@ -27,13 +34,17 @@ default_column_prefix = "greptime"
## @toml2docs:none-default
#+ user_provider = "static_user_provider:file:/path/to/users"
## Maximum total memory for all concurrent write request bodies and messages (HTTP, gRPC, Flight).
## Shared quota for concurrent write request bodies and messages (HTTP, gRPC, Flight)
## plus retained decoder memory and estimated PB-to-Arrow conversion memory for ordinary-table batching.
## A batch must fit together with its request's existing reservations; only additional memory is acquired.
## Set to 0 to disable the limit. Default: "0" (unlimited)
## @toml2docs:none-default="0"
#+ max_in_flight_write_bytes = "1GB"
## Policy when write bytes quota is exhausted.
## Options: "wait" (default, 10s timeout), "wait(<duration>)" (e.g., "wait(30s)"), "fail"
## Table-batch conversion never waits for additional memory. Under a wait policy,
## temporary contention returns a retryable error; requests that cannot fit are rejected.
#+ write_bytes_exhausted_policy = "wait"
## Initialize all regions in the background during the startup.
@@ -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.
+43 -2
View File
@@ -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
+2 -1
View File
@@ -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 {
+2 -1
View File
@@ -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);
+8
View File
@@ -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<T> = std::result::Result<T, Error>;
impl ErrorExt for Error {
fn status_code(&self) -> StatusCode {
match self {
Error::InitLogging { source, .. } => source.status_code(),
Error::StartDatanode { source, .. } => source.status_code(),
Error::StartFrontend { source, .. } => source.status_code(),
Error::ShutdownDatanode { source, .. } => source.status_code(),
+2 -1
View File
@@ -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);
+5 -2
View File
@@ -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());
}
+2 -1
View File
@@ -324,7 +324,8 @@ impl StartCommand {
&opts.component.tracing,
None,
None,
);
)
.context(crate::error::InitLoggingSnafu)?;
common_runtime::init_global_runtimes(&opts.runtime);
+5 -4
View File
@@ -54,7 +54,7 @@ use common_telemetry::{info, warn};
use common_time::timezone::set_default_timezone;
use common_version::{short_version, verbose_version};
use common_wal::config::DatanodeWalConfig;
use common_wal::config::object_store::STANDALONE_GENERATION;
use common_wal::config::object_store::FIXED_DIRECTORY_GENERATION;
use datanode::config::{DatanodeOptions, StorageConfig};
use datanode::datanode::{Datanode, DatanodeBuilder};
use datanode::region_server::RegionServer;
@@ -98,7 +98,7 @@ pub async fn build_standalone_wal_provider(
) -> Result<WalProvider> {
match wal {
DatanodeWalConfig::ObjectStore(config) => Ok(WalProvider::ObjectStore {
prefix: config.node_prefix(node_id.unwrap_or(0), STANDALONE_GENERATION),
prefix: config.node_prefix(node_id.unwrap_or(0), FIXED_DIRECTORY_GENERATION),
}),
DatanodeWalConfig::RaftEngine(_)
| DatanodeWalConfig::Kafka(_)
@@ -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),
+3
View File
@@ -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)),
+2
View File
@@ -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")
+4
View File
@@ -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
+4
View File
@@ -173,6 +173,10 @@ where
let key = NodeAddressKey::with_flownode(*node_id);
self.invalidate_key(&key.to_bytes()).await;
}
#[cfg(feature = "enterprise")]
CacheIdent::TriggerId(_) => {
// Trigger keys are owned by enterprise cache invalidators.
}
CacheIdent::User(_) => {
// User cache invalidation is handled by external
// CacheInvalidator implementations.
@@ -24,7 +24,7 @@ use common_procedure::{Context, EventContext, EventTrigger, LockKey, Procedure,
use common_telemetry::{debug, error, info, warn};
pub use executor::make_alter_region_request;
use serde::{Deserialize, Serialize};
use snafu::{ResultExt, ensure};
use snafu::ResultExt;
use store_api::metadata::ColumnMetadata;
use store_api::metric_engine_consts::ALTER_PHYSICAL_EXTENSION_KEY;
use strum::AsRefStr;
@@ -40,7 +40,7 @@ use crate::ddl::event::table::{
TableDdlEvent, TableDdlEventType, TableDdlLocator, alter_table_kind_name,
};
use crate::ddl::utils::{extract_column_metadatas, map_to_procedure_error, sync_follower_regions};
use crate::error::{self, Result};
use crate::error::Result;
use crate::instruction::CacheIdent;
use crate::key::DeserializedValueWithBytes;
use crate::key::table_info::TableInfoValue;
@@ -67,7 +67,7 @@ fn build_validator_from_alter_table_data<'a>(
.iter()
.map(|task| &task.alter_table)
.collect::<Vec<_>>();
AlterLogicalTableValidator::new(physical_table_id, alters)
AlterLogicalTableValidator::new(physical_table_id, alters, &data.logical_table_ids)
}
/// Builds the executor from the [`AlterTablesData`].
@@ -149,26 +149,6 @@ impl AlterLogicalTablesProcedure {
);
}
// Locks are fixed at submission. A logical table that resolves to an
// id outside the locked set here was dropped and recreated in between,
// so this procedure holds no lock for it. Procedures restored from
// pre-upgrade state have no recorded ids and keep the old behavior.
if !self.data.logical_table_ids.is_empty() {
for value in &table_info_values {
let table_id = value.get_inner_ref().table_info.ident.table_id;
ensure!(
self.data.logical_table_ids.contains(&table_id),
error::UnexpectedSnafu {
err_msg: format!(
"logical table {} (id {table_id}) is not covered by the \
procedure locks; retry the statement",
value.get_inner_ref().table_info.name
),
}
);
}
}
// Updates the procedure state.
retain_unskipped(&mut self.data.tasks, &skip_alter);
self.data.physical_table_info = Some(physical_table_info);
@@ -26,7 +26,7 @@ use crate::ddl::utils::table_info::{
};
use crate::error::{
AlterLogicalTablesInvalidArgumentsSnafu, Result, TableInfoNotFoundSnafu,
TableRouteNotFoundSnafu,
TableRouteNotFoundSnafu, UnexpectedSnafu,
};
use crate::key::table_info::TableInfoValue;
use crate::key::table_route::{PhysicalTableRouteValue, TableRouteManager, TableRouteValue};
@@ -36,13 +36,19 @@ use crate::key::{DeserializedValueWithBytes, TableMetadataManagerRef};
pub struct AlterLogicalTableValidator<'a> {
physical_table_id: TableId,
alters: Vec<&'a AlterTableExpr>,
expected_table_ids: &'a [TableId],
}
impl<'a> AlterLogicalTableValidator<'a> {
pub fn new(physical_table_id: TableId, alters: Vec<&'a AlterTableExpr>) -> Self {
pub fn new(
physical_table_id: TableId,
alters: Vec<&'a AlterTableExpr>,
expected_table_ids: &'a [TableId],
) -> Self {
Self {
physical_table_id,
alters,
expected_table_ids,
}
}
@@ -187,6 +193,14 @@ impl<'a> AlterLogicalTableValidator<'a> {
let table_ids =
get_all_table_ids_by_names(table_metadata_manager.table_name_manager(), &table_names)
.await?;
// Check before skipping completed ALTERs, while the procedure holds the pinned ID locks.
// Old persisted procedures have no pinned IDs and retain their previous behavior.
ensure!(
self.expected_table_ids.is_empty() || self.expected_table_ids == table_ids,
UnexpectedSnafu {
err_msg: "logical tables changed and are not covered by the procedure locks; retry the statement",
}
);
let mut table_info_values = get_all_table_info_values_by_table_ids(
table_metadata_manager.table_info_manager(),
&table_ids,
+4 -2
View File
@@ -26,7 +26,7 @@ use common_procedure::{
Context as ProcedureContext, EventContext, EventTrigger, LockKey, Procedure,
Result as ProcedureResult, Status,
};
use futures::stream::BoxStream;
use futures::stream::{BoxStream, Peekable};
use serde::{Deserialize, Serialize};
use snafu::ResultExt;
use tonic::async_trait;
@@ -54,12 +54,14 @@ pub(crate) enum DropTableTarget {
Physical,
}
type TableStream = Peekable<BoxStream<'static, Result<(String, TableNameValue)>>>;
/// Context of [DropDatabaseProcedure] execution.
pub(crate) struct DropDatabaseContext {
catalog: String,
schema: String,
drop_if_exists: bool,
tables: Option<BoxStream<'static, Result<(String, TableNameValue)>>>,
tables: Option<TableStream>,
retrying: bool,
}
+322 -67
View File
@@ -13,21 +13,24 @@
// limitations under the License.
use std::any::Any;
use std::collections::HashSet;
use std::pin::Pin;
use common_base::readable_size::ReadableSize;
use common_catalog::format_full_table_name;
use common_procedure::Status;
use futures::TryStreamExt;
use futures::{StreamExt, TryStreamExt};
use serde::{Deserialize, Serialize};
use snafu::OptionExt;
use snafu::{OptionExt, ensure};
use table::metadata::{TableId, TableType};
use table::table_name::TableName;
use crate::cache_invalidator::Context;
use crate::ddl::DdlContext;
use crate::ddl::drop_database::executor::DropDatabaseExecutor;
use crate::ddl::drop_database::executor::{DropDatabaseBatchExecutor, DropDatabaseExecutor};
use crate::ddl::drop_database::metadata::DropDatabaseRemoveMetadata;
use crate::ddl::drop_database::{DropDatabaseContext, DropTableTarget, State};
use crate::error::{Result, TableInfoNotFoundSnafu};
use crate::error::{Result, TableInfoNotFoundSnafu, UnexpectedSnafu};
use crate::instruction::CacheIdent;
use crate::key::table_route::TableRouteValue;
@@ -42,6 +45,123 @@ impl DropDatabaseCursor {
Self { target }
}
/// Collects a bounded page without mutating metadata. Only the executor's batch is durable.
async fn collect_logical_tables(
&mut self,
ddl_ctx: &DdlContext,
ctx: &mut DropDatabaseContext,
) -> Result<(Box<dyn State>, Status)> {
let page = Self::collect_page(ctx).await?;
if page.is_empty() {
return self.handle_reach_end(ctx);
}
let tables = Self::logical_tables(ddl_ctx, ctx, page).await?;
if tables.is_empty() {
return Ok((Box::new(Self::new(self.target)), Status::executing(false)));
}
Ok((
Box::new(DropDatabaseBatchExecutor { tables }),
Status::executing(true),
))
}
// Leave headroom below etcd's default 1.5 MiB request limit.
const MAX_BATCH_BYTES: usize = ReadableSize::mb(1).as_bytes() as usize;
fn estimated_table_bytes(catalog: &str, schema: &str, name: &str) -> usize {
// A control byte can expand to 6 JSON bytes, then 7 inside ProcedureMessage's
// JSON string. Round up to 8x and allow 128 bytes for fixed per-table JSON/key overhead.
128 + 8 * (catalog.len() + schema.len() + name.len())
}
async fn collect_page(ctx: &mut DropDatabaseContext) -> Result<Vec<(String, TableId)>> {
let mut page = Vec::new();
let mut bytes: usize = 0;
let tables = ctx.tables.as_mut().unwrap();
loop {
match Pin::new(&mut *tables).peek().await {
Some(Ok((name, _))) => {
let size = Self::estimated_table_bytes(&ctx.catalog, &ctx.schema, name);
if !page.is_empty() && bytes.saturating_add(size) > Self::MAX_BATCH_BYTES {
break;
}
// A single oversized name must still make progress. Procedure storage
// already splits oversized values; never strand an existing table here.
bytes = bytes.saturating_add(size);
}
Some(Err(_)) => {} // Consume below to propagate the owned error.
None => break,
}
let (name, value) = tables.try_next().await?.unwrap();
page.push((name, value.table_id()));
}
Ok(page)
}
async fn logical_tables(
ddl_ctx: &DdlContext,
ctx: &mut DropDatabaseContext,
page: Vec<(String, TableId)>,
) -> Result<Vec<(TableId, TableName)>> {
let manager = &ddl_ctx.table_metadata_manager;
let ids = page.iter().map(|(_, id)| *id).collect::<Vec<_>>();
let infos = manager.table_info_manager().batch_get(&ids).await?;
let routes = manager
.table_route_manager()
.table_route_storage()
.batch_get(&ids)
.await?;
let physical_ids = routes
.iter()
.filter_map(|route| match route {
Some(TableRouteValue::Logical(route)) => Some(route.physical_table_id()),
_ => None,
})
.collect::<HashSet<_>>()
.into_iter()
.collect::<Vec<_>>();
let physical_infos = manager
.table_info_manager()
.batch_get(&physical_ids)
.await?;
let mut tables = Vec::new();
for ((name, id), route) in page.into_iter().zip(routes) {
let info = infos.get(&id).with_context(|| TableInfoNotFoundSnafu {
table: format_full_table_name(&ctx.catalog, &ctx.schema, &name),
})?;
if info.table_info.table_type == TableType::View {
// Views are handled in the physical phase so collecting a batch has no side effects.
continue;
}
if let Some(TableRouteValue::Logical(route)) = route {
let physical = physical_infos
.get(&route.physical_table_id())
.with_context(|| TableInfoNotFoundSnafu {
table: route.physical_table_id().to_string(),
})?;
// Metadata-only deletion is safe only when the backing table is dropped with us.
ensure!(
physical.table_info.catalog_name == ctx.catalog
&& physical.table_info.schema_name == ctx.schema,
UnexpectedSnafu {
err_msg: format!(
"Logical table {} references physical table {} (id {}) outside the dropped database",
format_full_table_name(&ctx.catalog, &ctx.schema, &name),
format_full_table_name(
&physical.table_info.catalog_name,
&physical.table_info.schema_name,
&physical.table_info.name,
),
route.physical_table_id(),
),
}
);
tables.push((id, TableName::new(&ctx.catalog, &ctx.schema, name)));
}
}
Ok(tables)
}
fn handle_reach_end(
&mut self,
ctx: &mut DropDatabaseContext,
@@ -62,32 +182,12 @@ impl DropDatabaseCursor {
async fn handle_table(
&mut self,
ddl_ctx: &DdlContext,
ctx: &mut DropDatabaseContext,
table_name: String,
table_id: TableId,
table_route_value: TableRouteValue,
) -> Result<(Box<dyn State>, Status)> {
match (self.target, table_route_value) {
(DropTableTarget::Logical, TableRouteValue::Logical(route)) => {
let physical_table_id = route.physical_table_id();
let (_, table_route) = ddl_ctx
.table_metadata_manager
.table_route_manager()
.get_physical_table_route(physical_table_id)
.await?;
Ok((
Box::new(DropDatabaseExecutor::new(
table_id,
table_id,
TableName::new(&ctx.catalog, &ctx.schema, &table_name),
table_route.region_routes,
self.target,
)),
Status::executing(true),
))
}
(DropTableTarget::Physical, TableRouteValue::Physical(table_route)) => Ok((
Box::new(DropDatabaseExecutor::new(
table_id,
@@ -104,7 +204,6 @@ impl DropDatabaseCursor {
)),
}
}
async fn handle_view(
&self,
ddl_ctx: &DdlContext,
@@ -148,50 +247,61 @@ impl State for DropDatabaseCursor {
ddl_ctx: &DdlContext,
ctx: &mut DropDatabaseContext,
) -> Result<(Box<dyn State>, Status)> {
if ctx.tables.as_deref().is_none() {
if ctx.tables.is_none() {
let tables = ddl_ctx
.table_metadata_manager
.table_name_manager()
.tables(&ctx.catalog, &ctx.schema);
ctx.tables = Some(tables);
ctx.tables = Some(tables.peekable());
}
// Safety: must exist
match ctx.tables.as_mut().unwrap().try_next().await? {
Some((table_name, table_name_value)) => {
let table_id = table_name_value.table_id();
let result = async {
if self.target == DropTableTarget::Logical {
return self.collect_logical_tables(ddl_ctx, ctx).await;
}
// Safety: must exist
match ctx.tables.as_mut().unwrap().try_next().await? {
Some((table_name, table_name_value)) => {
let table_id = table_name_value.table_id();
let table_info_value = ddl_ctx
.table_metadata_manager
.table_info_manager()
.get(table_id)
.await?
.with_context(|| TableInfoNotFoundSnafu {
table: format_full_table_name(&ctx.catalog, &ctx.schema, &table_name),
})?;
let table_info_value = ddl_ctx
.table_metadata_manager
.table_info_manager()
.get(table_id)
.await?
.with_context(|| TableInfoNotFoundSnafu {
table: format_full_table_name(&ctx.catalog, &ctx.schema, &table_name),
})?;
if table_info_value.table_info.table_type == TableType::View {
return self.handle_view(ddl_ctx, ctx, table_name, table_id).await;
}
if table_info_value.table_info.table_type == TableType::View {
return self.handle_view(ddl_ctx, ctx, table_name, table_id).await;
}
match ddl_ctx
.table_metadata_manager
.table_route_manager()
.table_route_storage()
.get(table_id)
.await?
{
Some(table_route_value) => {
self.handle_table(ddl_ctx, ctx, table_name, table_id, table_route_value)
.await
match ddl_ctx
.table_metadata_manager
.table_route_manager()
.table_route_storage()
.get(table_id)
.await?
{
Some(table_route_value) => {
self.handle_table(ctx, table_name, table_id, table_route_value)
.await
}
None => Ok((
Box::new(DropDatabaseCursor::new(self.target)),
Status::executing(false),
)),
}
None => Ok((
Box::new(DropDatabaseCursor::new(self.target)),
Status::executing(false),
)),
}
None => self.handle_reach_end(ctx),
}
None => self.handle_reach_end(ctx),
}
.await;
if result.is_err() {
// The entry was consumed but no deletion plan was persisted. Rescan on retry.
ctx.tables.take();
}
result
}
fn as_any(&self) -> &dyn Any {
@@ -206,12 +316,163 @@ mod tests {
use common_catalog::consts::{DEFAULT_CATALOG_NAME, DEFAULT_SCHEMA_NAME};
use crate::ddl::drop_database::cursor::DropDatabaseCursor;
use crate::ddl::drop_database::executor::DropDatabaseExecutor;
use crate::ddl::drop_database::executor::{DropDatabaseBatchExecutor, DropDatabaseExecutor};
use crate::ddl::drop_database::metadata::DropDatabaseRemoveMetadata;
use crate::ddl::drop_database::{DropDatabaseContext, DropTableTarget, State};
use crate::ddl::test_util::{create_logical_table, create_physical_table};
use crate::test_util::{MockDatanodeManager, new_ddl_context};
#[tokio::test]
async fn test_cursor_read_failure_rescans() {
use crate::key::table_name::TableNameValue;
use futures::StreamExt;
for target in [DropTableTarget::Logical, DropTableTarget::Physical] {
let ddl = new_ddl_context(Arc::new(MockDatanodeManager::new(())));
let physical = create_physical_table(&ddl, "physical").await;
let mut ctx = DropDatabaseContext {
catalog: DEFAULT_CATALOG_NAME.into(),
schema: DEFAULT_SCHEMA_NAME.into(),
drop_if_exists: false,
retrying: false,
tables: Some(
futures::stream::iter(vec![Ok(("missing".into(), TableNameValue::new(99999)))])
.boxed()
.peekable(),
),
};
let mut cursor = DropDatabaseCursor::new(target);
assert!(cursor.next(&ddl, &mut ctx).await.is_err());
assert!(ctx.tables.is_none());
let (state, _) = cursor.next(&ddl, &mut ctx).await.unwrap();
if target == DropTableTarget::Physical {
assert!(state.as_any().is::<DropDatabaseExecutor>());
} else {
assert!(state.as_any().is::<DropDatabaseCursor>());
}
assert!(
ddl.table_metadata_manager
.table_info_manager()
.get(physical)
.await
.unwrap()
.is_some()
);
}
}
#[tokio::test]
async fn test_collect_page_oversized_singleton_makes_progress() {
use crate::key::table_name::TableNameValue;
use futures::StreamExt;
let mut ctx = DropDatabaseContext {
catalog: DEFAULT_CATALOG_NAME.into(),
schema: DEFAULT_SCHEMA_NAME.into(),
drop_if_exists: false,
retrying: false,
tables: Some(
futures::stream::iter(vec![
Ok((
"x".repeat(DropDatabaseCursor::MAX_BATCH_BYTES),
TableNameValue::new(1),
)),
Ok(("small".into(), TableNameValue::new(2))),
])
.boxed()
.peekable(),
),
};
let page = DropDatabaseCursor::collect_page(&mut ctx).await.unwrap();
assert_eq!(page.len(), 1);
assert_eq!(page[0].1, 1);
assert_eq!(
DropDatabaseCursor::collect_page(&mut ctx).await.unwrap(),
vec![("small".into(), 2)]
);
assert!(
DropDatabaseCursor::collect_page(&mut ctx)
.await
.unwrap()
.is_empty()
);
}
#[tokio::test]
async fn test_collect_page_limits_and_request_headroom() {
use common_procedure::store::ProcedureMessage;
use futures::StreamExt;
use table::table_name::TableName;
use crate::ddl::drop_database::DropDatabaseProcedure;
use crate::key::TableMetadataManager;
use crate::key::table_name::TableNameValue;
for name in [
"short".to_string(),
"x".repeat(64 * 1024),
"\"\\\n\u{0001}中文".repeat(4096),
] {
let ddl = new_ddl_context(Arc::new(MockDatanodeManager::new(())));
let count = if name.len() < 1024 { 5000 } else { 65 };
let entries = (0..count)
.map(|id| Ok((name.clone(), TableNameValue::new(id))))
.collect::<Vec<_>>();
let mut ctx = DropDatabaseContext {
catalog: DEFAULT_CATALOG_NAME.into(),
schema: DEFAULT_SCHEMA_NAME.into(),
drop_if_exists: false,
tables: Some(futures::stream::iter(entries).boxed().peekable()),
retrying: false,
};
let mut collected = Vec::new();
loop {
let page = DropDatabaseCursor::collect_page(&mut ctx).await.unwrap();
if page.is_empty() {
break;
}
let estimated = page
.iter()
.map(|(name, _)| {
DropDatabaseCursor::estimated_table_bytes(&ctx.catalog, &ctx.schema, name)
})
.sum::<usize>();
assert!(estimated <= DropDatabaseCursor::MAX_BATCH_BYTES);
let tables = page
.iter()
.map(|(name, id)| (*id, TableName::new(&ctx.catalog, &ctx.schema, name)))
.collect::<Vec<_>>();
// Each delete has one bytes field nested in two messages. Allow
// 32 bytes per key for tags and length varints, plus a txn envelope.
let delete_bytes = 64
+ tables
.iter()
.flat_map(|(id, name)| TableMetadataManager::table_identity_keys(*id, name))
.map(|key| key.len() + 32)
.sum::<usize>();
assert!(delete_bytes <= estimated);
let mut procedure = DropDatabaseProcedure::new(
ctx.catalog.clone(),
ctx.schema.clone(),
false,
ddl.clone(),
);
procedure.state = Box::new(DropDatabaseBatchExecutor { tables });
let message = ProcedureMessage {
type_name: DropDatabaseProcedure::TYPE_NAME.into(),
data: common_procedure::Procedure::dump(&procedure).unwrap(),
parent_id: None,
subprocedure_recovery: common_procedure::SubprocedureRecovery::Discard,
step: u32::MAX,
error: None,
context: Default::default(),
};
let serialized = serde_json::to_vec(&message).unwrap();
assert!(serialized.len() <= estimated);
assert!(serialized.len() + 512 * 1024 < 1536 * 1024);
collected.extend(page.into_iter().map(|(_, id)| id));
}
assert_eq!(collected, (0..count).collect::<Vec<_>>());
}
}
#[tokio::test]
async fn test_next_without_logical_tables() {
let node_manager = Arc::new(MockDatanodeManager::new(()));
@@ -267,16 +528,10 @@ mod tests {
assert!(status.need_persist());
let executor = state
.as_any()
.downcast_ref::<DropDatabaseExecutor>()
.downcast_ref::<DropDatabaseBatchExecutor>()
.unwrap();
let (_, table_route) = ddl_context
.table_metadata_manager
.table_route_manager()
.get_physical_table_route(physical_table_id)
.await
.unwrap();
assert_eq!(table_route.region_routes, executor.physical_region_routes);
assert_eq!(executor.target, DropTableTarget::Logical);
assert_eq!(executor.tables.len(), 1);
assert_eq!(executor.tables[0].1.table_name, "metric_0");
}
#[tokio::test]
@@ -21,12 +21,14 @@ use snafu::OptionExt;
use table::metadata::TableId;
use table::table_name::TableName;
use crate::cache_invalidator::Context;
use crate::ddl::DdlContext;
use crate::ddl::drop_database::cursor::DropDatabaseCursor;
use crate::ddl::drop_database::{DropDatabaseContext, DropTableTarget, State};
use crate::ddl::drop_table::executor::DropTableExecutor;
use crate::ddl::utils::get_region_wal_options;
use crate::error::{self, Result};
use crate::instruction::CacheIdent;
use crate::key::table_route::TableRouteValue;
use crate::region_keeper::OperatingRegionGuard;
use crate::rpc::router::{RegionRoute, operating_leader_region_roles};
@@ -140,7 +142,7 @@ impl State for DropDatabaseExecutor {
&ddl_ctx.leader_region_registry,
&self.physical_region_routes,
true,
false,
self.target == DropTableTarget::Physical,
false,
)
.await?;
@@ -157,6 +159,54 @@ impl State for DropDatabaseExecutor {
}
}
/// A durable logical-table deletion batch. Physical regions are removed in the next phase.
#[derive(Debug, Serialize, Deserialize)]
pub(crate) struct DropDatabaseBatchExecutor {
pub(crate) tables: Vec<(TableId, TableName)>,
}
#[async_trait::async_trait]
#[typetag::serde]
impl State for DropDatabaseBatchExecutor {
async fn next(
&mut self,
ddl_ctx: &DdlContext,
_ctx: &mut DropDatabaseContext,
) -> Result<(Box<dyn State>, Status)> {
ddl_ctx
.table_metadata_manager
.destroy_logical_tables_metadata(&self.tables)
.await?;
let idents = self
.tables
.iter()
.flat_map(|(id, name)| {
[
CacheIdent::TableId(*id),
CacheIdent::TableName(name.clone()),
]
})
.collect::<Vec<_>>();
ddl_ctx
.cache_invalidator
.invalidate(
&Context {
subject: Some("Invalidate logical tables by dropping database".to_string()),
},
&idents,
)
.await?;
Ok((
Box::new(DropDatabaseCursor::new(DropTableTarget::Logical)),
Status::executing(false),
))
}
fn as_any(&self) -> &dyn Any {
self
}
}
#[cfg(test)]
mod tests {
use std::collections::HashSet;
@@ -448,10 +498,13 @@ mod tests {
state.recover(&ddl_context).unwrap();
let roles = ddl_context
let operating_regions = ddl_context
.memory_region_keeper
.extract_operating_region_roles(7, &HashSet::from([region_id]));
assert_eq!(roles.get(&region_id), Some(&RegionRole::DowngradingLeader));
.extract_operating_regions(7, &HashSet::from([region_id]));
assert_eq!(
operating_regions.get(&region_id).map(|region| region.role),
Some(RegionRole::DowngradingLeader)
);
}
#[tokio::test]
@@ -713,21 +713,27 @@ async fn test_on_prepare_rejects_table_outside_locked_set() {
let phy_id = create_physical_table(&ddl_context, "phy").await;
create_logical_table(ddl_context.clone(), phy_id, "table1").await;
let tasks = vec![make_alter_logical_table_add_column_task(
None,
"table1",
vec!["column1".to_string()],
)];
// The table resolved at prepare time is not in the locked set, as if it
// had been dropped and recreated after submission.
let stale_locked_id = phy_id + 1000;
let mut procedure =
AlterLogicalTablesProcedure::new(tasks, phy_id, vec![stale_locked_id], ddl_context);
let err = procedure.on_prepare().await.unwrap_err();
assert!(
err.to_string()
.contains("not covered by the procedure locks"),
"{err}"
);
// A completed ADD must also reject rebinding, even when no schema changes are needed.
for column in ["column1", "host"] {
let tasks = vec![make_alter_logical_table_add_column_task(
None,
"table1",
vec![column.into()],
)];
let mut procedure = AlterLogicalTablesProcedure::new(
tasks,
phy_id,
vec![stale_locked_id],
ddl_context.clone(),
);
let err = procedure.on_prepare().await.unwrap_err();
assert!(
err.to_string()
.contains("not covered by the procedure locks"),
"{err}"
);
}
}
@@ -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(&region_id), Some(&RegionRole::Leader));
.extract_operating_regions(datanode_id, &HashSet::from([region_id]));
assert_eq!(
operating_regions.get(&region_id).map(|region| region.role),
Some(RegionRole::Leader)
);
execute_procedure_until_done(&mut procedure).await;
+305 -13
View File
@@ -22,7 +22,7 @@ use common_procedure_test::{
use futures::TryStreamExt;
use crate::ddl::drop_database::DropDatabaseProcedure;
use crate::ddl::drop_database::executor::DropDatabaseExecutor;
use crate::ddl::drop_database::executor::{DropDatabaseBatchExecutor, DropDatabaseExecutor};
use crate::ddl::test_util::datanode_handler::{NaiveDatanodeHandler, RetryErrorDatanodeHandler};
use crate::ddl::test_util::{create_logical_table, create_physical_table};
use crate::key::schema_name::SchemaNameKey;
@@ -151,24 +151,15 @@ async fn test_drop_database_recover() {
ddl_context.clone(),
);
let num_operating_regions = 1;
// Before dropping the logical table
// Recover the persisted logical batch before its metadata is removed.
execute_procedure_until(&mut procedure, |p| {
p.state()
.as_any()
.downcast_ref::<DropDatabaseExecutor>()
.is_some()
p.state().as_any().is::<DropDatabaseBatchExecutor>()
})
.await;
// Dump data
let data = procedure.dump().unwrap();
assert_eq!(ddl_context.memory_region_keeper.len(), 0);
let mut procedure = DropDatabaseProcedure::from_json(&data, ddl_context.clone()).unwrap();
procedure.recover().unwrap();
assert_eq!(
ddl_context.memory_region_keeper.len(),
num_operating_regions
);
ddl_context.memory_region_keeper.clear();
assert_eq!(ddl_context.memory_region_keeper.len(), 0);
// Before dropping the physical table
execute_procedure_until(&mut procedure, |p| {
p.state()
@@ -197,3 +188,304 @@ async fn test_drop_database_recover() {
.unwrap();
assert!(tables.is_empty());
}
#[tokio::test]
async fn test_drop_database_batches_recover_after_metadata_deletion() {
use crate::ddl::test_util::datanode_handler::DatanodeWatcher;
use api::v1::region::region_request::Body;
use store_api::storage::RegionId;
// A full batch, multiple batches, and a trailing partial batch.
for (count, name_padding, expected_batches) in
[(0, 0, 0), (1, 0, 1), (64, 0, 1), (129, 0, 1), (20, 8192, 2)]
{
let (tx, mut rx) = tokio::sync::mpsc::channel(16);
let ddl = new_ddl_context(Arc::new(MockDatanodeManager::new(DatanodeWatcher::new(tx))));
ddl.table_metadata_manager
.schema_manager()
.create(
SchemaNameKey::new(DEFAULT_CATALOG_NAME, DEFAULT_SCHEMA_NAME),
None,
false,
)
.await
.unwrap();
let physical = create_physical_table(&ddl, "z_physical").await;
let mut ids = Vec::new();
for i in 0..count {
create_logical_table(
ddl.clone(),
physical,
&format!("logical_{i:04}{}", "x".repeat(name_padding)),
)
.await;
}
let mut procedure = DropDatabaseProcedure::new(
DEFAULT_CATALOG_NAME.into(),
DEFAULT_SCHEMA_NAME.into(),
false,
ddl.clone(),
);
let ctx = ProcedureContext {
procedure_id: ProcedureId::random(),
provider: Arc::new(MockContextProvider::default()),
event_context: None,
};
let mut batches = 0;
loop {
if let Some(batch) = procedure
.state()
.as_any()
.downcast_ref::<DropDatabaseBatchExecutor>()
{
ids.extend(batch.tables.iter().map(|(id, _)| *id));
// Crash after keys are gone but before cache invalidation and cursor advancement.
let dump = procedure.dump().unwrap();
ddl.table_metadata_manager
.destroy_logical_tables_metadata(&batch.tables)
.await
.unwrap();
procedure = DropDatabaseProcedure::from_json(&dump, ddl.clone()).unwrap();
procedure.recover().unwrap();
batches += 1;
}
if procedure.execute(&ctx).await.unwrap().is_done() {
break;
}
}
assert_eq!(ids.len(), count);
assert_eq!(batches, expected_batches);
let (_, request) = rx.try_recv().unwrap();
let Some(Body::Drop(drop)) = request.body else {
panic!("expected physical drop")
};
assert_eq!(RegionId::from_u64(drop.region_id).table_id(), physical);
assert!(drop.force);
assert!(
rx.try_recv().is_err(),
"logical tables must not send region RPCs"
);
assert!(
ddl.table_metadata_manager
.table_info_manager()
.batch_get(&ids)
.await
.unwrap()
.is_empty()
);
assert!(
ddl.table_metadata_manager
.table_name_manager()
.tables(DEFAULT_CATALOG_NAME, DEFAULT_SCHEMA_NAME)
.try_collect::<Vec<_>>()
.await
.unwrap()
.is_empty()
);
}
}
#[tokio::test]
async fn test_drop_database_legacy_state_fixture() {
let ddl = new_ddl_context(Arc::new(MockDatanodeManager::new(NaiveDatanodeHandler)));
// Single-table executor state from f8d8fe1071, before logical-table batching.
let fixture = r#"{
"catalog": "greptime",
"schema": "public",
"drop_if_exists": false,
"state": {
"drop_database_state": "DropDatabaseExecutor",
"table_id": 1025,
"physical_table_id": 1025,
"table_name": {
"catalog_name": "greptime",
"schema_name": "public",
"table_name": "logical"
},
"physical_region_routes": [],
"target": "Logical"
}
}"#;
let mut procedure = DropDatabaseProcedure::from_json(fixture, ddl).unwrap();
procedure.recover().unwrap();
assert!(procedure.state().as_any().is::<DropDatabaseExecutor>());
assert_eq!(
serde_json::from_str::<serde_json::Value>(fixture).unwrap(),
serde_json::from_str::<serde_json::Value>(&procedure.dump().unwrap()).unwrap()
);
}
#[tokio::test]
async fn test_drop_database_batch_cache_failure_recovery() {
use crate::cache_invalidator::{CacheInvalidator, Context};
use crate::instruction::CacheIdent;
use std::sync::Mutex;
use std::sync::atomic::{AtomicBool, Ordering};
struct FailingInvalidator {
fail: AtomicBool,
calls: Mutex<Vec<Vec<CacheIdent>>>,
}
#[async_trait::async_trait]
impl CacheInvalidator for FailingInvalidator {
async fn invalidate(&self, _: &Context, caches: &[CacheIdent]) -> crate::error::Result<()> {
self.calls.lock().unwrap().push(caches.to_vec());
if self.fail.swap(false, Ordering::Relaxed) {
return crate::error::UnexpectedSnafu {
err_msg: "injected cache failure",
}
.fail();
}
Ok(())
}
fn invalidate_all(&self) -> crate::error::Result<()> {
// This test invalidator owns only call records, not cached metadata.
Ok(())
}
}
let invalidator = Arc::new(FailingInvalidator {
fail: AtomicBool::new(false),
calls: Mutex::new(Vec::new()),
});
let mut ddl = new_ddl_context(Arc::new(MockDatanodeManager::new(NaiveDatanodeHandler)));
ddl.cache_invalidator = invalidator.clone();
ddl.table_metadata_manager
.schema_manager()
.create(
SchemaNameKey::new(DEFAULT_CATALOG_NAME, DEFAULT_SCHEMA_NAME),
None,
false,
)
.await
.unwrap();
let physical = create_physical_table(&ddl, "physical").await;
create_logical_table(ddl.clone(), physical, "logical").await;
let mut procedure = DropDatabaseProcedure::new(
DEFAULT_CATALOG_NAME.into(),
DEFAULT_SCHEMA_NAME.into(),
false,
ddl.clone(),
);
execute_procedure_until(&mut procedure, |p| {
p.state().as_any().is::<DropDatabaseBatchExecutor>()
})
.await;
let dump = procedure.dump().unwrap();
invalidator.calls.lock().unwrap().clear();
invalidator.fail.store(true, Ordering::Relaxed);
let ctx = ProcedureContext {
procedure_id: ProcedureId::random(),
provider: Arc::new(MockContextProvider::default()),
event_context: None,
};
assert!(procedure.execute(&ctx).await.is_err());
assert_eq!(procedure.dump().unwrap(), dump);
let mut restored = DropDatabaseProcedure::from_json(&dump, ddl).unwrap();
restored.recover().unwrap();
restored.execute(&ctx).await.unwrap();
let calls = invalidator.calls.lock().unwrap();
assert_eq!(calls.len(), 2);
assert_eq!(calls[0], calls[1]);
assert_eq!(calls[0].len(), 2);
}
#[tokio::test]
async fn test_drop_database_mixed_table_order_and_recovery() {
use crate::ddl::test_util::create_table::test_create_table_task;
use crate::ddl::tests::create_view::{test_create_view_task, test_table_names};
use crate::key::table_route::TableRouteValue;
use itertools::Itertools;
use std::collections::HashMap;
// Every relative ordering of metric physical, logical, mito and view names.
for names in ["a", "b", "c", "d"].into_iter().permutations(4) {
for recover in [false, true] {
let ddl = new_ddl_context(Arc::new(MockDatanodeManager::new(NaiveDatanodeHandler)));
let manager = &ddl.table_metadata_manager;
manager
.schema_manager()
.create(
SchemaNameKey::new(DEFAULT_CATALOG_NAME, DEFAULT_SCHEMA_NAME),
None,
false,
)
.await
.unwrap();
let physical = create_physical_table(&ddl, names[0]).await;
let logical = create_logical_table(ddl.clone(), physical, names[1]).await;
let mito = test_create_table_task(names[2], 20000);
manager
.create_table_metadata(
mito.table_info,
TableRouteValue::physical(vec![]),
HashMap::new(),
)
.await
.unwrap();
let mut view = test_create_view_task(names[3]);
view.view_info.ident.table_id = 20001;
manager
.create_view_metadata(
view.view_info,
view.create_view.logical_plan,
test_table_names(),
vec![],
vec![],
"definition".into(),
)
.await
.unwrap();
let mut procedure = DropDatabaseProcedure::new(
DEFAULT_CATALOG_NAME.into(),
DEFAULT_SCHEMA_NAME.into(),
false,
ddl.clone(),
);
let ctx = ProcedureContext {
procedure_id: ProcedureId::random(),
provider: Arc::new(MockContextProvider::default()),
event_context: None,
};
let mut done = false;
for _ in 0..40 {
let status = procedure.execute(&ctx).await.unwrap();
if status.is_done() {
done = true;
break;
}
if recover && status.need_persist() {
let dump = procedure.dump().unwrap();
drop(procedure);
procedure = DropDatabaseProcedure::from_json(&dump, ddl.clone()).unwrap();
procedure.recover().unwrap();
}
}
assert!(done, "{names:?}, recovery={recover}");
assert!(
manager
.table_name_manager()
.tables(DEFAULT_CATALOG_NAME, DEFAULT_SCHEMA_NAME)
.try_collect::<Vec<_>>()
.await
.unwrap()
.is_empty()
);
assert!(
manager
.table_info_manager()
.batch_get(&[physical, logical, 20000, 20001])
.await
.unwrap()
.is_empty()
);
assert!(
manager
.view_info_manager()
.get(20001)
.await
.unwrap()
.is_none()
);
}
}
}
+6 -3
View File
@@ -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(&region_id), Some(&RegionRole::Leader));
.extract_operating_regions(datanode_id, &HashSet::from([region_id]));
assert_eq!(
operating_regions.get(&region_id).map(|region| region.role),
Some(RegionRole::Leader)
);
execute_procedure_until_done(&mut procedure).await;
+78 -4
View File
@@ -625,13 +625,22 @@ impl DdlManager {
&self,
alter_table_tasks: Vec<AlterTableTask>,
physical_table_id: TableId,
expected_table_ids: Option<Vec<TableId>>,
procedure_context: ProcedureContext,
) -> Result<(ProcedureId, Option<Output>)> {
let context = self.create_context();
// Resolve the logical table ids up front: procedure locks are fixed
// at submission, so `lock_key` cannot derive them during `Prepare`.
let logical_table_ids = {
let logical_table_ids = if let Some(ids) = expected_table_ids {
ensure!(
ids.len() == alter_table_tasks.len(),
error::AlterLogicalTablesInvalidArgumentsSnafu {
err_msg: "Expected one pinned table ID per logical ALTER task",
}
);
ids
} else {
let table_refs = alter_table_tasks
.iter()
.map(|task| task.table_ref())
@@ -1043,8 +1052,13 @@ impl DdlManager {
.await
}
AlterLogicalTables(alter_table_tasks) => {
handle_alter_logical_table_tasks(self, alter_table_tasks, procedure_context)
.await
handle_alter_logical_table_tasks(
self,
alter_table_tasks,
query_context,
procedure_context,
)
.await
}
DropLogicalTables(_) => todo!(),
CreateDatabase(create_database_task) => {
@@ -1598,6 +1612,7 @@ async fn handle_create_trigger_task(
async fn handle_alter_logical_table_tasks(
ddl_manager: &DdlManager,
alter_table_tasks: Vec<AlterTableTask>,
query_context: QueryContext,
procedure_context: ProcedureContext,
) -> Result<SubmitDdlTaskResponse> {
ensure!(
@@ -1616,9 +1631,15 @@ async fn handle_alter_logical_table_tasks(
let physical_table_id =
utils::get_physical_table_id(ddl_manager.table_metadata_manager(), first_table).await?;
let num_logical_tables = alter_table_tasks.len();
let expected_table_ids = query_context.pinned_logical_table_ids()?;
let (id, _) = ddl_manager
.submit_alter_logical_table_tasks(alter_table_tasks, physical_table_id, procedure_context)
.submit_alter_logical_table_tasks(
alter_table_tasks,
physical_table_id,
expected_table_ids,
procedure_context,
)
.await?;
info!(
@@ -2061,6 +2082,59 @@ mod tests {
)
}
#[tokio::test]
async fn test_alter_logical_tables_preserves_caller_pinned_ids() {
use crate::ddl::test_util::alter_table::TestAlterTableExprBuilder;
use crate::ddl::test_util::{create_logical_table, create_physical_table};
use crate::rpc::ddl::ALTER_LOGICAL_TABLE_IDS_EXTENSION_KEY;
let manager = build_soft_drop_test_ddl_manager();
manager.register_loaders().unwrap();
manager.procedure_manager.start().await.unwrap();
let context = manager.create_context();
let physical_id = create_physical_table(&context, "physical").await;
let logical_id = create_logical_table(context, physical_id, "logical").await;
let expr: api::v1::AlterTableExpr = TestAlterTableExprBuilder::default()
.table_name("logical")
.add_columns(vec![api::v1::ColumnDef {
name: "host".into(),
data_type: api::v1::ColumnDataType::String as i32,
semantic_type: api::v1::SemanticType::Tag as i32,
is_nullable: true,
..Default::default()
}])
.add_if_not_exists(true)
.build()
.unwrap()
.into();
for (ids, succeeds) in [
(Some((logical_id + 1000).to_string()), false),
(Some(format!("{logical_id},{logical_id}")), false),
(Some(logical_id.to_string()), true),
(None, true),
] {
let mut context = QueryContext::default();
if let Some(ids) = ids {
context
.extensions
.insert(ALTER_LOGICAL_TABLE_IDS_EXTENSION_KEY.into(), ids);
}
let result = manager
.submit_ddl_task(
ExecutorContext {
query_context: Some(context),
..Default::default()
},
SubmitDdlTaskRequest::new(DdlTask::new_alter_logical_tables(vec![
expr.clone(),
])),
)
.await;
assert_eq!(result.is_ok(), succeeds, "{result:?}");
}
manager.procedure_manager.stop().await.unwrap();
}
#[cfg(feature = "enterprise")]
#[tokio::test]
async fn test_reserved_sequence_range_is_rejected_before_custom_handler() {
+24
View File
@@ -388,6 +388,9 @@ pub struct UpgradeRegion {
pub replay_entry_id: Option<u64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub metadata_replay_entry_id: Option<u64>,
/// The candidate lease id of the migration's registration of this target region.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub candidate_lease_id: Option<u64>,
}
impl UpgradeRegion {
@@ -408,6 +411,9 @@ impl UpgradeRegion {
/// The identifier of cache.
pub enum CacheIdent {
FlowId(FlowId),
/// Indicates a change of trigger metadata; invalidated by enterprise plugins.
#[cfg(feature = "enterprise")]
TriggerId(u64),
/// Indicate change of address of flownode.
FlowNodeAddressChange(u64),
FlowName(FlowName),
@@ -1559,6 +1565,7 @@ mod tests {
location_id: None,
replay_entry_id: None,
metadata_replay_entry_id: None,
candidate_lease_id: None,
}]);
let serialized = serde_json::to_string(&upgrade_region).unwrap();
@@ -1656,10 +1663,27 @@ mod tests {
location_id: None,
replay_entry_id: None,
metadata_replay_entry_id: None,
candidate_lease_id: None,
}]);
assert_eq!(upgrade_region_instruction, upgrade_region);
}
#[test]
fn test_upgrade_region_candidate_lease_id_json() {
let upgrade_region = UpgradeRegion {
region_id: RegionId::new(1024, 1),
replay_timeout: Duration::from_millis(1000),
candidate_lease_id: Some(7),
..Default::default()
};
let json = serde_json::to_value(&upgrade_region).unwrap();
assert_eq!(json["candidate_lease_id"], 7);
assert_eq!(
serde_json::from_value::<UpgradeRegion>(json).unwrap(),
upgrade_region
);
}
#[test]
fn test_deserialize_instruction_reply() {
// legacy close region reply
+118 -13
View File
@@ -994,6 +994,26 @@ impl TableMetadataManager {
Ok(())
}
const TABLE_IDENTITY_KEYS: usize = 4;
/// Keys shared by physical and logical tables, independent of region placement.
pub(crate) fn table_identity_keys(
table_id: TableId,
table_name: &TableName,
) -> [Vec<u8>; Self::TABLE_IDENTITY_KEYS] {
[
TableNameKey::new(
&table_name.catalog_name,
&table_name.schema_name,
&table_name.table_name,
)
.to_bytes(),
TableInfoKey::new(table_id).to_bytes(),
TableRouteKey::new(table_id).to_bytes(),
TableRepartKey::new(table_id).to_bytes(),
]
}
fn table_metadata_keys(
&self,
table_id: TableId,
@@ -1009,15 +1029,7 @@ impl TableMetadataManager {
} else {
vec![]
};
let mut keys = Vec::with_capacity(3 + datanode_ids.len());
let table_name = TableNameKey::new(
&table_name.catalog_name,
&table_name.schema_name,
&table_name.table_name,
);
let table_info_key = TableInfoKey::new(table_id);
let table_route_key = TableRouteKey::new(table_id);
let table_repart_key = TableRepartKey::new(table_id);
let mut keys = Vec::from(Self::table_identity_keys(table_id, table_name));
let datanode_table_keys = datanode_ids
.into_iter()
.map(|datanode_id| DatanodeTableKey::new(datanode_id, table_id))
@@ -1029,10 +1041,6 @@ impl TableMetadataManager {
.iter()
.map(|(region_id, topic)| TopicRegionKey::new(*region_id, topic))
.collect::<Vec<_>>();
keys.push(table_name.to_bytes());
keys.push(table_info_key.to_bytes());
keys.push(table_route_key.to_bytes());
keys.push(table_repart_key.to_bytes());
for key in &datanode_table_keys {
keys.push(key.to_bytes());
}
@@ -1321,6 +1329,30 @@ impl TableMetadataManager {
Ok(())
}
/// Permanently deletes a batch of logical tables. The caller holds their schema write lock
/// and persists the deletion plan before calling, since backend requests may partially succeed.
pub(crate) async fn destroy_logical_tables_metadata(
&self,
tables: &[(TableId, TableName)],
) -> Result<()> {
let max_ops = self.kv_backend.max_txn_ops().max(1);
let tables_per_request = (max_ops / Self::TABLE_IDENTITY_KEYS).max(1);
// Keep a table's keys together whenever they fit in one backend request. A backend
// limit smaller than a single table still requires splitting, as with single-table drop.
for tables in tables.chunks(tables_per_request) {
let keys = tables
.iter()
.flat_map(|(id, name)| Self::table_identity_keys(*id, name))
.collect::<Vec<_>>();
for keys in keys.chunks(max_ops) {
self.kv_backend
.batch_delete(BatchDeleteRequest::new().with_keys(keys.to_vec()))
.await?;
}
}
Ok(())
}
/// Rebuilds dropped table metadata from tombstoned keys.
async fn get_dropped_table_metadata<T>(
&self,
@@ -3094,6 +3126,79 @@ mod tests {
);
}
#[tokio::test]
async fn test_destroy_logical_tables_metadata_limits_and_partial_failure() {
use crate::kv_backend::test_util::MockKvBackendBuilder;
use crate::rpc::store::{BatchDeleteRequest, BatchDeleteResponse};
use std::sync::Mutex;
use std::sync::atomic::{AtomicUsize, Ordering};
for limit in [1, 3, 127, 128, 129] {
let tables = (0..65)
.map(|id| {
(
id,
TableName::new("greptime", "public", format!("logical_{id}")),
)
})
.collect::<Vec<_>>();
let remaining = Arc::new(Mutex::new(
tables
.iter()
.flat_map(|(id, name)| TableMetadataManager::table_identity_keys(*id, name))
.collect::<HashSet<_>>(),
));
let requests = Arc::new(AtomicUsize::new(0));
let backend = MockKvBackendBuilder::default()
.max_txn_ops(limit)
.batch_delete_fn({
let remaining = remaining.clone();
let requests = requests.clone();
Arc::new(move |req: BatchDeleteRequest| {
assert!(!req.keys.is_empty());
assert!(req.keys.len() <= limit);
if limit >= 4 {
assert_eq!(req.keys.len() % 4, 0, "single-table keys stay together");
}
for key in &req.keys {
remaining.lock().unwrap().remove(key);
}
// Simulate a response lost after the second chunk committed.
if requests.fetch_add(1, Ordering::Relaxed) == 1 {
return crate::error::UnexpectedSnafu {
err_msg: "injected lost response",
}
.fail();
}
Ok(BatchDeleteResponse::default())
})
})
.build()
.unwrap();
let manager = TableMetadataManager::new(Arc::new(backend));
assert!(
manager
.destroy_logical_tables_metadata(&tables)
.await
.is_err()
);
assert!(!remaining.lock().unwrap().is_empty());
manager
.destroy_logical_tables_metadata(&tables)
.await
.unwrap();
assert!(remaining.lock().unwrap().is_empty());
assert_eq!(
requests.load(Ordering::Relaxed),
2 + if limit < 4 {
65_usize * 4_usize.div_ceil(limit)
} else {
65_usize.div_ceil(limit / 4)
}
);
}
}
#[tokio::test]
async fn test_destroy_table_metadata() {
let mem_kv = Arc::new(MemoryKvBackend::default());
+59 -2
View File
@@ -22,8 +22,8 @@ use crate::error::Result;
use crate::kv_backend::txn::{Txn, TxnResponse};
use crate::kv_backend::{
BatchDeleteRequest, BatchDeleteResponse, BatchGetRequest, BatchGetResponse, BatchPutRequest,
BatchPutResponse, DeleteRangeRequest, DeleteRangeResponse, KvBackend, PutRequest, PutResponse,
RangeRequest, RangeResponse, TxnService,
BatchPutResponse, DeleteRangeRequest, DeleteRangeResponse, KvBackend, KvBackendRef, PutRequest,
PutResponse, RangeRequest, RangeResponse, TxnService,
};
pub type MockFn<Req, Resp> = Arc<dyn Fn(Req) -> Result<Resp> + Send + Sync>;
@@ -133,3 +133,60 @@ impl KvBackend for MockKvBackend {
}
}
}
/// A [KvBackend] that runs `before_txn` before each transaction of `inner`.
pub struct TxnObservingKvBackend {
/// The kv backend every request is forwarded to.
pub inner: KvBackendRef,
/// Runs before each transaction is forwarded to `inner`.
pub before_txn: Box<dyn Fn() + Send + Sync>,
}
#[async_trait::async_trait]
impl TxnService for TxnObservingKvBackend {
type Error = crate::error::Error;
async fn txn(&self, txn: Txn) -> Result<TxnResponse> {
(self.before_txn)();
self.inner.txn(txn).await
}
fn max_txn_ops(&self) -> usize {
self.inner.max_txn_ops()
}
}
#[async_trait::async_trait]
impl KvBackend for TxnObservingKvBackend {
fn name(&self) -> &str {
self.inner.name()
}
fn as_any(&self) -> &dyn Any {
self
}
async fn range(&self, req: RangeRequest) -> Result<RangeResponse> {
self.inner.range(req).await
}
async fn put(&self, req: PutRequest) -> Result<PutResponse> {
self.inner.put(req).await
}
async fn batch_put(&self, req: BatchPutRequest) -> Result<BatchPutResponse> {
self.inner.batch_put(req).await
}
async fn batch_get(&self, req: BatchGetRequest) -> Result<BatchGetResponse> {
self.inner.batch_get(req).await
}
async fn delete_range(&self, req: DeleteRangeRequest) -> Result<DeleteRangeResponse> {
self.inner.delete_range(req).await
}
async fn batch_delete(&self, req: BatchDeleteRequest) -> Result<BatchDeleteResponse> {
self.inner.batch_delete(req).await
}
}
+136 -23
View File
@@ -21,12 +21,25 @@ use store_api::storage::RegionId;
use crate::DatanodeId;
/// An operating region on a datanode.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct OperatingRegion {
/// The role of a lease granted because of this registration, when the region route grants
/// none.
pub role: RegionRole,
/// The random non-zero id of a region migration's registration of its target region. A lease
/// granted because of this registration carries it while the table route exists. `None` for
/// other operations.
pub candidate_lease_id: Option<u64>,
}
/// Tracks the operating(i.e., creating, opening, dropping) regions.
#[derive(Debug, Clone)]
pub struct OperatingRegionGuard {
datanode_id: DatanodeId,
region_id: RegionId,
inner: Arc<RwLock<HashMap<(DatanodeId, RegionId), RegionRole>>>,
candidate_lease_id: Option<u64>,
inner: Arc<RwLock<HashMap<(DatanodeId, RegionId), OperatingRegion>>>,
}
impl Drop for OperatingRegionGuard {
@@ -41,6 +54,11 @@ impl OperatingRegionGuard {
pub fn info(&self) -> (DatanodeId, RegionId) {
(self.datanode_id, self.region_id)
}
/// Returns the candidate lease id of a region migration's target region registration.
pub fn candidate_lease_id(&self) -> Option<u64> {
self.candidate_lease_id
}
}
pub type MemoryRegionKeeperRef = Arc<MemoryRegionKeeper>;
@@ -52,7 +70,7 @@ pub type MemoryRegionKeeperRef = Arc<MemoryRegionKeeper>;
/// - Tracks the deleting regions after the corresponding metadata is deleted.
#[derive(Debug, Clone, Default)]
pub struct MemoryRegionKeeper {
inner: Arc<RwLock<HashMap<(DatanodeId, RegionId), RegionRole>>>,
inner: Arc<RwLock<HashMap<(DatanodeId, RegionId), OperatingRegion>>>,
}
impl MemoryRegionKeeper {
@@ -67,19 +85,32 @@ impl MemoryRegionKeeper {
region_id: RegionId,
role: RegionRole,
) -> Option<OperatingRegionGuard> {
let mut inner = self.inner.write().unwrap();
self.register(
datanode_id,
region_id,
OperatingRegion {
role,
candidate_lease_id: None,
},
)
}
match inner.entry((datanode_id, region_id)) {
Entry::Occupied(_) => None,
Entry::Vacant(vacant_entry) => {
vacant_entry.insert(role);
Some(OperatingRegionGuard {
datanode_id,
region_id,
inner: self.inner.clone(),
})
}
}
/// Registers the target region of a region migration as a follower with a new random
/// candidate lease id. Returns [OperatingRegionGuard] if Region(`region_id`) on
/// Peer(`datanode_id`) does not exist.
pub fn register_candidate_region(
&self,
datanode_id: DatanodeId,
region_id: RegionId,
) -> Option<OperatingRegionGuard> {
self.register(
datanode_id,
region_id,
OperatingRegion {
role: RegionRole::Follower,
candidate_lease_id: Some(new_candidate_lease_id(rand::random)),
},
)
}
/// Returns true if the keeper contains a (`datanoe_id`, `region_id`) tuple.
@@ -88,19 +119,19 @@ impl MemoryRegionKeeper {
inner.contains_key(&(datanode_id, region_id))
}
/// Extracts all operating regions with roles from `region_ids`.
pub fn extract_operating_region_roles(
/// Extracts all operating regions from `region_ids`.
pub fn extract_operating_regions(
&self,
datanode_id: DatanodeId,
region_ids: &HashSet<RegionId>,
) -> HashMap<RegionId, RegionRole> {
) -> HashMap<RegionId, OperatingRegion> {
let inner = self.inner.read().unwrap();
region_ids
.iter()
.filter_map(|region_id| {
inner
.get(&(datanode_id, *region_id))
.map(|role| (*region_id, *role))
.map(|region| (*region_id, *region))
})
.collect()
}
@@ -121,6 +152,38 @@ impl MemoryRegionKeeper {
let mut inner = self.inner.write().unwrap();
inner.clear();
}
fn register(
&self,
datanode_id: DatanodeId,
region_id: RegionId,
operating_region: OperatingRegion,
) -> Option<OperatingRegionGuard> {
let mut inner = self.inner.write().unwrap();
match inner.entry((datanode_id, region_id)) {
Entry::Occupied(_) => None,
Entry::Vacant(vacant_entry) => {
vacant_entry.insert(operating_region);
Some(OperatingRegionGuard {
datanode_id,
region_id,
candidate_lease_id: operating_region.candidate_lease_id,
inner: self.inner.clone(),
})
}
}
}
}
/// Returns the first non-zero value of `random`, since 0 means no candidate lease id on the wire.
fn new_candidate_lease_id(mut random: impl FnMut() -> u64) -> u64 {
loop {
let candidate_lease_id = random();
if candidate_lease_id != 0 {
return candidate_lease_id;
}
}
}
#[cfg(test)]
@@ -130,7 +193,7 @@ mod tests {
use store_api::region_engine::RegionRole;
use store_api::storage::RegionId;
use crate::region_keeper::MemoryRegionKeeper;
use crate::region_keeper::{MemoryRegionKeeper, OperatingRegion, new_candidate_lease_id};
#[test]
fn test_opening_region_keeper() {
@@ -153,7 +216,7 @@ mod tests {
RegionId::from_u64(2),
RegionId::from_u64(3),
]);
let output = keeper.extract_operating_region_roles(1, &regions);
let output = keeper.extract_operating_regions(1, &regions);
assert_eq!(output.len(), 2);
assert!(output.contains_key(&RegionId::from_u64(1)));
@@ -165,12 +228,24 @@ mod tests {
RegionId::from_u64(2),
RegionId::from_u64(3),
]);
let output = keeper.extract_operating_region_roles(1, &regions);
let output = keeper.extract_operating_regions(1, &regions);
assert_eq!(
output,
HashMap::from([
(RegionId::from_u64(1), RegionRole::Leader),
(RegionId::from_u64(2), RegionRole::Follower),
(
RegionId::from_u64(1),
OperatingRegion {
role: RegionRole::Leader,
candidate_lease_id: None,
}
),
(
RegionId::from_u64(2),
OperatingRegion {
role: RegionRole::Follower,
candidate_lease_id: None,
}
),
])
);
assert_eq!(keeper.len(), 2);
@@ -182,4 +257,42 @@ mod tests {
drop(guard2);
assert!(keeper.is_empty());
}
#[test]
fn test_register_candidate_region_uses_new_candidate_lease_id() {
let keeper = MemoryRegionKeeper::new();
let region_id = RegionId::from_u64(1);
let regions = HashSet::from([region_id]);
let guard = keeper
.register_with_role(1, region_id, RegionRole::Follower)
.unwrap();
assert_eq!(guard.candidate_lease_id(), None);
assert_eq!(
keeper.extract_operating_regions(1, &regions)[&region_id].candidate_lease_id,
None
);
drop(guard);
let guard = keeper.register_candidate_region(1, region_id).unwrap();
let first = guard.candidate_lease_id().unwrap();
assert!(keeper.register_candidate_region(1, region_id).is_none());
assert_eq!(
keeper.extract_operating_regions(1, &regions)[&region_id],
OperatingRegion {
role: RegionRole::Follower,
candidate_lease_id: Some(first),
}
);
drop(guard);
let guard = keeper.register_candidate_region(1, region_id).unwrap();
assert_ne!(guard.candidate_lease_id().unwrap(), first);
}
#[test]
fn test_new_candidate_lease_id_skips_zero() {
let mut values = [0, 0, 7].into_iter();
assert_eq!(new_candidate_lease_id(|| values.next().unwrap()), 7);
}
}
+46
View File
@@ -68,6 +68,8 @@ use crate::key::table_name::{TableNameKey, TableNameManager};
/// Reserved query-context extension key for the frontend peer address that submitted a DDL request.
pub const ORIGIN_FRONTEND_ADDR_EXTENSION_KEY: &str = "__greptime_origin_frontend.addr";
/// Ordered source table IDs pinned by the caller of an automatic logical-table ALTER.
pub const ALTER_LOGICAL_TABLE_IDS_EXTENSION_KEY: &str = "__greptime_alter_logical_tables.ids";
/// Reserved query-context extension key for the authenticated database creator.
pub const CREATE_DATABASE_CREATOR_EXTENSION_KEY: &str = "__greptime_create_database.creator";
/// Internal gRPC metadata key for the authenticated database creator.
@@ -1707,6 +1709,24 @@ impl QueryContext {
&self.extensions
}
pub(crate) fn pinned_logical_table_ids(&self) -> Result<Option<Vec<TableId>>> {
self.extensions
.get(ALTER_LOGICAL_TABLE_IDS_EXTENSION_KEY)
.map(|ids| {
ids.split(',')
.map(|id| {
id.parse::<TableId>().map_err(|error| {
error::AlterLogicalTablesInvalidArgumentsSnafu {
err_msg: format!("Invalid pinned logical table ID: {error}"),
}
.build()
})
})
.collect()
})
.transpose()
}
/// Get the channel
pub fn channel(&self) -> u8 {
self.channel
@@ -1891,6 +1911,32 @@ mod tests {
use super::{AlterTableTask, CreateTableTask, *};
#[test]
fn test_pinned_logical_table_ids_wire_compatibility() {
let legacy = include_bytes!(
"../../../../../tests/compatibility/wire/read_preference/legacy_query_context.pb"
);
let mut context = QueryContext::from(PbQueryContext::decode(legacy.as_slice()).unwrap());
assert_eq!(context.pinned_logical_table_ids().unwrap(), None);
context.extensions.insert(
"__greptime_alter_logical_tables.ids".into(),
"1025,1024".into(),
);
let wire = PbQueryContext::from(context.clone()).encode_to_vec();
let decoded = QueryContext::from(PbQueryContext::decode(wire.as_slice()).unwrap());
assert_eq!(decoded, context);
assert_eq!(
decoded.pinned_logical_table_ids().unwrap(),
Some(vec![1025, 1024])
);
for invalid in ["", "1024,", "1024,no", "-1", "4294967296"] {
context
.extensions
.insert(ALTER_LOGICAL_TABLE_IDS_EXTENSION_KEY.into(), invalid.into());
assert!(context.pinned_logical_table_ids().is_err(), "{invalid}");
}
}
#[test]
fn test_ddl_timeout_secs() {
assert_eq!(ddl_timeout_secs(Duration::ZERO), 0);
+19 -1
View File
@@ -30,6 +30,9 @@ static GREPTIME_VALUE_CELL: OnceCell<String> = OnceCell::new();
/// Default native histogram column name.
static GREPTIME_NATIVE_HISTOGRAM_CELL: OnceCell<String> = OnceCell::new();
/// Default exemplar labels column name.
static GREPTIME_EXEMPLAR_LABELS_CELL: OnceCell<String> = OnceCell::new();
pub fn set_default_prefix(prefix: Option<&str>) -> Result<()> {
// Strip surrounding double quotes as a defensive measure against upstream
// sources (scripts, CI, template engines, incorrect shell escaping) that may
@@ -46,12 +49,14 @@ pub fn set_default_prefix(prefix: Option<&str>) -> Result<()> {
GREPTIME_TIMESTAMP_CELL.get_or_init(|| GREPTIME_TIMESTAMP.to_string());
GREPTIME_VALUE_CELL.get_or_init(|| GREPTIME_VALUE.to_string());
GREPTIME_NATIVE_HISTOGRAM_CELL.get_or_init(|| NATIVE_HISTOGRAM_FIELD.to_string());
GREPTIME_EXEMPLAR_LABELS_CELL.get_or_init(|| GREPTIME_EXEMPLAR_LABELS.to_string());
}
Some(s) if s.trim().is_empty() => {
// use "" to disable prefix
GREPTIME_TIMESTAMP_CELL.get_or_init(|| "timestamp".to_string());
GREPTIME_VALUE_CELL.get_or_init(|| "value".to_string());
GREPTIME_NATIVE_HISTOGRAM_CELL.get_or_init(|| "native_histogram".to_string());
GREPTIME_EXEMPLAR_LABELS_CELL.get_or_init(|| "exemplar_labels".to_string());
}
Some(x) => {
ensure!(
@@ -61,6 +66,7 @@ pub fn set_default_prefix(prefix: Option<&str>) -> Result<()> {
GREPTIME_TIMESTAMP_CELL.get_or_init(|| format!("{}_timestamp", x));
GREPTIME_VALUE_CELL.get_or_init(|| format!("{}_value", x));
GREPTIME_NATIVE_HISTOGRAM_CELL.get_or_init(|| format!("{}_native_histogram", x));
GREPTIME_EXEMPLAR_LABELS_CELL.get_or_init(|| format!("{}_exemplar_labels", x));
}
}
Ok(())
@@ -87,6 +93,14 @@ pub fn greptime_native_histogram() -> &'static str {
.map_or(NATIVE_HISTOGRAM_FIELD, String::as_str)
}
/// Returns the configured exemplar labels column name, or `greptime_exemplar_labels` if not set.
#[inline]
pub fn greptime_exemplar_labels() -> &'static str {
GREPTIME_EXEMPLAR_LABELS_CELL
.get()
.map_or(GREPTIME_EXEMPLAR_LABELS, String::as_str)
}
/// Default timestamp column name constant for backward compatibility.
const GREPTIME_TIMESTAMP: &str = "greptime_timestamp";
/// Default value column name constant for backward compatibility.
@@ -94,7 +108,7 @@ const GREPTIME_VALUE: &str = "greptime_value";
/// Query-visible source metric name stored in the exemplar table.
pub const EXEMPLAR_METRIC_COLUMN: &str = "greptime_metric";
/// JSON2 object containing exemplar-owned labels.
pub const EXEMPLAR_LABELS_COLUMN: &str = "exemplar_labels";
const GREPTIME_EXEMPLAR_LABELS: &str = "greptime_exemplar_labels";
/// Stored series label that opts ordinary float samples into raw-delta math.
pub const OTLP_AGGREGATION_TEMPORALITY_LABEL: &str = "otlp_aggregation_temporality";
/// Authoritative raw-delta value for [`OTLP_AGGREGATION_TEMPORALITY_LABEL`].
@@ -115,6 +129,7 @@ mod tests {
assert_eq!(greptime_timestamp(), "greptime_timestamp");
assert_eq!(greptime_value(), "greptime_value");
assert_eq!(greptime_native_histogram(), "greptime_native_histogram");
assert_eq!(greptime_exemplar_labels(), "greptime_exemplar_labels");
}
#[test]
@@ -123,6 +138,7 @@ mod tests {
assert_eq!(greptime_timestamp(), "timestamp");
assert_eq!(greptime_value(), "value");
assert_eq!(greptime_native_histogram(), "native_histogram");
assert_eq!(greptime_exemplar_labels(), "exemplar_labels");
}
#[test]
@@ -132,6 +148,7 @@ mod tests {
assert_eq!(greptime_timestamp(), "timestamp");
assert_eq!(greptime_value(), "value");
assert_eq!(greptime_native_histogram(), "native_histogram");
assert_eq!(greptime_exemplar_labels(), "exemplar_labels");
}
#[test]
@@ -140,6 +157,7 @@ mod tests {
assert_eq!(greptime_timestamp(), "mydb_timestamp");
assert_eq!(greptime_value(), "mydb_value");
assert_eq!(greptime_native_histogram(), "mydb_native_histogram");
assert_eq!(greptime_exemplar_labels(), "mydb_exemplar_labels");
}
#[test]
+2
View File
@@ -15,6 +15,7 @@ workspace = true
backtrace = "0.3"
common-base.workspace = true
common-error.workspace = true
common-macro.workspace = true
common-version.workspace = true
console-subscriber = { version = "0.1", optional = true }
greptime-proto.workspace = true
@@ -31,6 +32,7 @@ parking_lot.workspace = true
prometheus.workspace = true
serde.workspace = true
serde_json.workspace = true
snafu.workspace = true
tokio.workspace = true
tracing = "0.1"
tracing-appender.workspace = true
+164 -29
View File
@@ -15,6 +15,7 @@
//! logging stuffs, inspired by databend
mod file_retention;
use std::any::Any;
use std::collections::HashMap;
use std::env;
use std::io::IsTerminal;
@@ -24,6 +25,9 @@ use std::time::Duration;
use common_base::readable_size::ReadableSize;
use common_base::serde::empty_string_as_default;
use common_error::ext::ErrorExt;
use common_error::status_code::StatusCode;
use common_macro::stack_trace_debug;
use file_retention::{DirectoryRetention, LogFileKind, build_file_appender};
use once_cell::sync::{Lazy, OnceCell};
use opentelemetry::trace::TracerProvider;
@@ -33,6 +37,7 @@ use opentelemetry_sdk::propagation::TraceContextPropagator;
use opentelemetry_sdk::trace::{Sampler, Tracer};
use opentelemetry_semantic_conventions::resource;
use serde::{Deserialize, Serialize};
use snafu::{Location, Snafu};
use tracing::callsite;
use tracing::metadata::LevelFilter;
use tracing_appender::non_blocking::{NonBlocking, WorkerGuard};
@@ -45,6 +50,31 @@ use tracing_subscriber::{EnvFilter, Registry, filter};
use crate::tracing_sampler::{TracingSampleOptions, create_sampler};
/// Failure to initialize a file appender.
#[derive(Snafu)]
#[stack_trace_debug]
pub enum InitLoggingError {
#[snafu(display("Failed to initialize file logging in {directory}: {error}.{hint}"))]
FileAppender {
directory: String,
#[snafu(source)]
error: tracing_appender::rolling::InitError,
hint: &'static str,
#[snafu(implicit)]
location: Location,
},
}
impl ErrorExt for InitLoggingError {
fn status_code(&self) -> StatusCode {
StatusCode::InvalidArguments
}
fn as_any(&self) -> &dyn Any {
self
}
}
/// The default endpoint when use gRPC exporter protocol.
pub const DEFAULT_OTLP_GRPC_ENDPOINT: &str = "http://localhost:4317";
@@ -474,13 +504,16 @@ pub fn init_default_ut_logging() {
level: Some(level),
..Default::default()
};
*g = Some(init_global_logging(
"unittest",
&opts,
&TracingOptions::default(),
None,
None,
));
*g = Some(
init_global_logging(
"unittest",
&opts,
&TracingOptions::default(),
None,
None,
)
.expect("failed to initialize test logging"),
);
crate::info!("logs dir = {}", dir);
});
@@ -498,15 +531,12 @@ pub fn init_global_logging(
tracing_opts: &TracingOptions,
node_id: Option<String>,
slow_query_opts: Option<&SlowQueryOptions>,
) -> Vec<WorkerGuard> {
static START: Once = Once::new();
) -> Result<Vec<WorkerGuard>, InitLoggingError> {
static START: OnceCell<()> = OnceCell::new();
let mut guards = vec![];
let node_id = node_id.unwrap_or_else(|| "none".to_string());
START.call_once(|| {
// Enable log compatible layer to convert log record to tracing span.
LogTracer::init().expect("log tracer must be valid");
START.get_or_try_init(|| -> Result<(), InitLoggingError> {
let stdout_writer = if opts.append_stdout {
let (writer, guard) = tracing_appender::non_blocking(std::io::stdout());
guards.push(guard);
@@ -531,7 +561,7 @@ pub fn init_global_logging(
// Configure the file logging layer with rolling policy.
let file_logging_layer = if file_logging_enabled {
let rolling_appender =
build_file_appender(opts, LogFileKind::Default, retention.as_ref());
build_file_appender(opts, LogFileKind::Default, retention.as_ref())?;
let (writer, guard) = tracing_appender::non_blocking(rolling_appender);
guards.push(guard);
@@ -543,7 +573,7 @@ pub fn init_global_logging(
// Configure the error file logging layer with rolling policy.
let err_file_logging_layer = if file_logging_enabled {
let rolling_appender =
build_file_appender(opts, LogFileKind::Error, retention.as_ref());
build_file_appender(opts, LogFileKind::Error, retention.as_ref())?;
let (writer, guard) = tracing_appender::non_blocking(rolling_appender);
guards.push(guard);
@@ -555,14 +585,23 @@ pub fn init_global_logging(
None
};
if slow_query_logging_enabled {
let slow_query_logger = if slow_query_logging_enabled {
Some(build_slow_query_logger(
opts,
stdout_writer,
retention.as_ref(),
&mut guards,
)?)
} else {
None
};
// Build all file appenders before installing any global logging state.
// A filesystem failure can then be returned without poisoning initialization.
LogTracer::init().expect("log tracer must be valid");
if let Some(logger) = slow_query_logger {
SLOW_QUERY_LOGGER
.set(build_slow_query_logger(
opts,
stdout_writer,
retention.as_ref(),
&mut guards,
))
.set(logger)
.expect("slow query logger already initialized");
}
@@ -659,9 +698,10 @@ pub fn init_global_logging(
tracing::subscriber::set_global_default(subscriber)
.expect("error setting global tracing subscriber");
});
Ok(())
})?;
guards
Ok(guards)
}
fn create_tracer(app_name: &str, node_id: &str, opts: &LoggingOptions) -> Tracer {
@@ -747,12 +787,12 @@ fn build_slow_query_logger(
stdout_writer: Option<NonBlocking>,
retention: Option<&DirectoryRetention>,
guards: &mut Vec<WorkerGuard>,
) -> tracing::Dispatch {
) -> Result<tracing::Dispatch, InitLoggingError> {
let stdout_layer = stdout_writer.map(|writer| {
build_logging_layer(writer, opts.log_format, std::io::stdout().is_terminal())
});
let file_layer = if opts.enable_file_logging && !opts.dir.is_empty() {
let rolling_appender = build_file_appender(opts, LogFileKind::SlowQuery, retention);
let rolling_appender = build_file_appender(opts, LogFileKind::SlowQuery, retention)?;
let (writer, guard) = tracing_appender::non_blocking(rolling_appender);
guards.push(guard);
Some(build_logging_layer(writer, opts.log_format, false))
@@ -764,12 +804,12 @@ fn build_slow_query_logger(
*metadata.level() == tracing::Level::INFO && metadata.fields().field("slow").is_some()
})
.with_max_level_hint(LevelFilter::INFO);
tracing::Dispatch::new(
Ok(tracing::Dispatch::new(
Registry::default()
.with(filter)
.with(stdout_layer)
.with(file_layer),
)
))
}
fn build_logging_layer<S>(
@@ -802,6 +842,100 @@ mod tests {
use super::*;
#[test]
fn test_file_logging_initialization_failure() {
const CHILD_ENV: &str = "GREPTIME_TEST_LOGGING_INIT_FAILURE";
if env::var_os(CHILD_ENV).is_none() {
let output = std::process::Command::new(env::current_exe().unwrap())
.args([
"--exact",
"logging::tests::test_file_logging_initialization_failure",
"--nocapture",
])
.env(CHILD_ENV, "1")
.output()
.unwrap();
assert!(
output.status.success(),
"{}",
String::from_utf8_lossy(&output.stderr)
);
return;
}
let dir = tempfile::tempdir().unwrap();
let mut opts = LoggingOptions {
dir: dir.path().to_str().unwrap().to_string(),
max_log_dir_size: ReadableSize::mb(1),
append_stdout: false,
..Default::default()
};
let slow_opts = SlowQueryOptions {
enable: true,
record_type: SlowQueriesRecordType::Log,
..Default::default()
};
for link in [
".greptimedb.current",
".greptimedb-err.current",
".greptimedb-slow-queries.current",
] {
let path = dir.path().join(link);
// A directory collision fails even on runners allowed to create symlinks.
std::fs::create_dir(&path).unwrap();
let error = init_global_logging(
"test",
&opts,
&TracingOptions::default(),
None,
Some(&slow_opts),
)
.unwrap_err();
let message = error.to_string();
assert!(message.contains("logging.max_log_dir_size"), "{message}");
assert!(message.contains(&opts.dir), "{message}");
assert!(message.contains("Developer Mode"), "{message}");
assert!(LOG_RELOAD_HANDLE.get().is_none());
assert!(SLOW_QUERY_LOGGER.get().is_none());
std::fs::remove_dir(path).unwrap();
for entry in std::fs::read_dir(dir.path()).unwrap() {
let entry = entry.unwrap();
if entry.file_type().unwrap().is_symlink() {
std::fs::remove_file(entry.path()).unwrap();
}
}
}
// Disabling retention succeeds with the same collision and after failed attempts.
std::fs::create_dir(dir.path().join(".greptimedb.current")).unwrap();
opts.max_log_dir_size = ReadableSize::default();
let guards = init_global_logging(
"test",
&opts,
&TracingOptions::default(),
None,
Some(&slow_opts),
)
.unwrap();
crate::error!("logging works after initialization failures");
drop(guards);
let error_log = std::fs::read_dir(dir.path())
.unwrap()
.map(|entry| entry.unwrap().path())
.find(|path| {
path.file_name()
.unwrap()
.to_string_lossy()
.starts_with("greptimedb-err.")
})
.unwrap();
assert!(
std::fs::read_to_string(error_log)
.unwrap()
.contains("logging works after initialization failures")
);
}
#[test]
fn test_slow_query_logging() {
const CASE_ENV: &str = "GREPTIME_TEST_SLOW_QUERY_LOGGING";
@@ -915,7 +1049,8 @@ mod tests {
&TracingOptions::default(),
None,
(case != "no_options").then_some(&slow_opts),
);
)
.unwrap();
for level in ["warn", "error", "off", "info"] {
LOG_RELOAD_HANDLE
@@ -24,9 +24,10 @@ use std::time::SystemTime;
use common_base::readable_size::ReadableSize;
use parking_lot::Mutex;
use snafu::ResultExt;
use tracing_appender::rolling::{RollingFileAppender, Rotation};
use crate::logging::LoggingOptions;
use crate::logging::{FileAppenderSnafu, InitLoggingError, LoggingOptions};
/// A managed file-log kind.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
@@ -421,7 +422,7 @@ pub(crate) fn build_file_appender(
opts: &LoggingOptions,
kind: LogFileKind,
retention: Option<&DirectoryRetention>,
) -> Box<dyn Write + Send> {
) -> Result<Box<dyn Write + Send>, InitLoggingError> {
// Directory retention owns size and count pruning so its index remains authoritative.
let upstream_max_log_files = if retention.is_some() {
0
@@ -440,18 +441,24 @@ pub(crate) fn build_file_appender(
// before creating it, so a missing directory prints a misleading error. If this fails,
// `build` reports it.
let _ = fs::create_dir_all(&opts.dir);
let appender = builder.build(&opts.dir).unwrap_or_else(|error| {
panic!(
"initializing rolling file appender at {} failed: {}",
opts.dir, error
)
});
let appender = builder.build(&opts.dir).with_context(|_| FileAppenderSnafu {
directory: opts.dir.clone(),
hint: if retention.is_some() {
" logging.max_log_dir_size requires creating symbolic links in this directory. Check directory permissions and conflicting paths; on Windows, enable Developer Mode or set logging.max_log_dir_size = \"0B\" to disable size-based retention."
} else {
""
},
})?;
if let Some(retention) = retention {
retention.register(kind);
Box::new(RetentionAppender::new(appender, retention.clone(), kind))
Ok(Box::new(RetentionAppender::new(
appender,
retention.clone(),
kind,
)))
} else {
Box::new(appender)
Ok(Box::new(appender))
}
}
@@ -521,7 +528,7 @@ mod tests {
};
let retention = DirectoryRetention::new(directory.path(), ReadableSize::mb(1), 0).unwrap();
let _appender = build_file_appender(&opts, LogFileKind::Default, Some(&retention));
let _appender = build_file_appender(&opts, LogFileKind::Default, Some(&retention)).unwrap();
let symlink = directory.path().join(".greptimedb.current");
assert!(symlink.is_symlink());
@@ -542,7 +549,8 @@ mod tests {
..Default::default()
};
let retention = DirectoryRetention::new(directory.path(), ReadableSize(1024), 0).unwrap();
let mut appender = build_file_appender(&opts, LogFileKind::Default, Some(&retention));
let mut appender =
build_file_appender(&opts, LogFileKind::Default, Some(&retention)).unwrap();
retention.initialize();
appender.write_all(b"current").unwrap();
@@ -570,7 +578,8 @@ mod tests {
..Default::default()
};
let retention = DirectoryRetention::new(directory.path(), ReadableSize(1024), 0).unwrap();
let mut appender = build_file_appender(&opts, LogFileKind::Default, Some(&retention));
let mut appender =
build_file_appender(&opts, LogFileKind::Default, Some(&retention)).unwrap();
retention.initialize();
appender.write_all(b"current").unwrap();
@@ -593,7 +602,8 @@ mod tests {
..Default::default()
};
let retention = DirectoryRetention::new(directory.path(), ReadableSize::gb(1), 2).unwrap();
let mut appender = build_file_appender(&opts, LogFileKind::Default, Some(&retention));
let mut appender =
build_file_appender(&opts, LogFileKind::Default, Some(&retention)).unwrap();
retention.initialize();
appender.write_all(b"current").unwrap();
@@ -616,7 +626,8 @@ mod tests {
..Default::default()
};
let retention = DirectoryRetention::new(directory.path(), ReadableSize(1), 0).unwrap();
let mut appender = build_file_appender(&opts, LogFileKind::Default, Some(&retention));
let mut appender =
build_file_appender(&opts, LogFileKind::Default, Some(&retention)).unwrap();
retention.initialize();
appender.write_all(b"current").unwrap();
+13 -6
View File
@@ -17,12 +17,19 @@ use std::time::Duration;
use common_base::readable_size::ReadableSize;
use serde::{Deserialize, Serialize};
/// Generation of the node prefix in standalone mode.
/// Fixed directory generation used by standalone and distributed WAL stores.
///
/// Standalone runs a single datanode that never changes generation, so the
/// prefix layout carries the constant. Distributed mode will take both the
/// node id and the generation from the metasrv.
pub const STANDALONE_GENERATION: u64 = 0;
/// The directory remains stable across process restarts. This is distinct from
/// both the heartbeat node epoch and the store epoch carried in object headers.
pub const FIXED_DIRECTORY_GENERATION: u64 = 0;
/// Plugin marker allowing a metasrv-controlled datanode to use object-store WAL.
///
/// OSS does not register this marker. Cluster integration registers it only after
/// the distributed WAL prerequisites are available; it does not itself configure
/// metasrv or enable region failover.
#[derive(Debug, Clone, Copy)]
pub struct EnableObjectStoreWal;
/// When an append to the object store WAL returns.
#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)]
@@ -124,7 +131,7 @@ mod tests {
fn test_node_prefix() {
let config = ObjectStoreWalConfig::default();
assert_eq!(
config.node_prefix(0, STANDALONE_GENERATION),
config.node_prefix(0, FIXED_DIRECTORY_GENERATION),
"wal/datanodes/0/epochs/0"
);
+76 -42
View File
@@ -16,7 +16,7 @@ use std::collections::HashMap;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use api::v1::meta::GrantedRegion;
use api::v1::meta::GrantedRegion as PbGrantedRegion;
use async_trait::async_trait;
use common_error::ext::ErrorExt;
use common_error::status_code::StatusCode;
@@ -26,7 +26,7 @@ use common_meta::heartbeat::handler::{
};
use common_telemetry::{debug, error, info, trace, warn};
use snafu::OptionExt;
use store_api::region_engine::{RegionRole, SettableRegionRoleState};
use store_api::region_engine::{GrantedRegion, RegionRole, SettableRegionRoleState};
use store_api::region_request::{RegionCloseRequest, RegionRequest};
use store_api::storage::RegionId;
#[cfg(test)]
@@ -137,15 +137,22 @@ impl RegionAliveKeeper {
/// Renews the lease of regions to `deadline`, granted for a heartbeat sent at `sent_at`.
async fn renew_region_leases(
&self,
regions: &[GrantedRegion],
regions: &[PbGrantedRegion],
sent_at: Instant,
deadline: Instant,
) {
for region in regions {
let (role, region_id) = (region.role().into(), RegionId::from(region.region_id));
let region = GrantedRegion::from(region.clone());
let region_id = region.region_id;
if let Some(handle) = self.find_handle(region_id).await {
handle
.reset_deadline(role, sent_at, deadline, region.extensions.clone())
.reset_deadline(ResetLease {
role: region.region_role,
sent_at,
deadline,
candidate_lease_id: region.candidate_lease_id,
extensions: region.extensions,
})
.await;
} else {
warn!(
@@ -301,13 +308,23 @@ enum CountdownCommand {
/// 4 * `heartbeat_interval_millis`
Start(u64),
/// Reset countdown deadline to the given instance.
/// (NextRole, HeartbeatSentAt, Deadline, ExtensionInfo)
Reset((RegionRole, Instant, Instant, HashMap<String, Vec<u8>>)),
Reset(ResetLease),
/// Returns the current deadline of the countdown task.
#[cfg(test)]
Deadline(oneshot::Sender<Instant>),
}
/// A region lease received in a heartbeat response.
#[derive(Debug)]
struct ResetLease {
role: RegionRole,
/// When the heartbeat was sent.
sent_at: Instant,
deadline: Instant,
candidate_lease_id: Option<u64>,
extensions: HashMap<String, Vec<u8>>,
}
pub type CountdownTaskHandlerExtRef = Arc<dyn CountdownTaskHandlerExt>;
/// Extension trait for [CountdownTaskHandlerExt] to reset deadline of a region.
@@ -319,7 +336,7 @@ pub trait CountdownTaskHandlerExt: Send + Sync {
region_id: RegionId,
role: RegionRole,
deadline: Instant,
extension_info: HashMap<String, Vec<u8>>,
extensions: HashMap<String, Vec<u8>>,
);
}
@@ -379,23 +396,8 @@ impl CountdownTaskHandle {
None
}
async fn reset_deadline(
&self,
role: RegionRole,
sent_at: Instant,
deadline: Instant,
extension_info: HashMap<String, Vec<u8>>,
) {
if let Err(e) = self
.tx
.send(CountdownCommand::Reset((
role,
sent_at,
deadline,
extension_info,
)))
.await
{
async fn reset_deadline(&self, lease: ResetLease) {
if let Err(e) = self.tx.send(CountdownCommand::Reset(lease)).await {
warn!(
"Failed to reset region alive keeper deadline: {e}. \
Maybe the task is stopped due to region been closed."
@@ -447,9 +449,9 @@ impl CountdownTask {
started = true;
}
},
Some(CountdownCommand::Reset((role, sent_at, deadline, extension_info))) => {
Some(CountdownCommand::Reset(ResetLease { role, sent_at, deadline, candidate_lease_id, extensions })) => {
let prev_role_leader = self.region_server.is_region_leader(self.region_id).unwrap_or(false);
let applied = match self.region_server.set_region_role_with_lease(self.region_id, role, sent_at.into_std(), deadline.into_std()) {
let applied = match self.region_server.set_region_role_with_lease(self.region_id, role, sent_at.into_std(), deadline.into_std(), candidate_lease_id) {
Ok(applied) => applied,
Err(err) => {
if err.status_code() == StatusCode::RegionNotFound {
@@ -480,7 +482,7 @@ impl CountdownTask {
self.region_id,
role,
deadline,
extension_info,
extensions,
).await;
}
trace!(
@@ -538,7 +540,10 @@ mod test {
use crate::tests::{MockRegionEngine, mock_region_server};
/// Handles a heartbeat response that grants `regions` for a heartbeat sent now.
async fn handle_lease_response(alive_keeper: &RegionAliveKeeper, regions: Vec<GrantedRegion>) {
async fn handle_lease_response(
alive_keeper: &RegionAliveKeeper,
regions: Vec<PbGrantedRegion>,
) {
let sent_at = alive_keeper.epoch().elapsed();
handle_lease_response_sent_at(alive_keeper, sent_at, regions).await;
}
@@ -548,7 +553,7 @@ mod test {
async fn handle_lease_response_sent_at(
alive_keeper: &RegionAliveKeeper,
sent_at: Duration,
regions: Vec<GrantedRegion>,
regions: Vec<PbGrantedRegion>,
) {
let (tx, _rx) = mpsc::channel(1);
let response = HeartbeatResponse {
@@ -587,9 +592,10 @@ mod test {
let alive_keeper =
RegionAliveKeeper::new(region_server.clone(), None, Duration::from_millis(100));
alive_keeper.register_region(region_id).await;
let grant = GrantedRegion {
let grant = PbGrantedRegion {
region_id: region_id.as_u64(),
role: api::v1::meta::RegionRole::Leader.into(),
candidate_lease_id: 0,
extensions: HashMap::new(),
};
handle_lease_response(&alive_keeper, vec![grant]).await;
@@ -598,6 +604,28 @@ mod test {
assert_eq!(0, finalized.load(Ordering::Relaxed));
}
#[tokio::test(flavor = "multi_thread")]
async fn lease_response_passes_candidate_lease_id_to_engine() {
common_telemetry::init_default_ut_logging();
let region_server = mock_region_server();
let (engine, _) = MockRegionEngine::new(MITO_ENGINE_NAME);
let region_id = RegionId::new(1024, 1);
region_server.register_test_region(region_id, engine.clone());
let alive_keeper =
RegionAliveKeeper::new(region_server.clone(), None, Duration::from_millis(100));
alive_keeper.register_region(region_id).await;
let grant = PbGrantedRegion {
region_id: region_id.as_u64(),
role: api::v1::meta::RegionRole::Follower.into(),
candidate_lease_id: 7,
extensions: HashMap::new(),
};
handle_lease_response(&alive_keeper, vec![grant]).await;
// The countdown task has handled the grant once it answers.
alive_keeper.deadline(region_id).await.unwrap();
assert_eq!(*engine.candidate_lease_ids.lock().unwrap(), vec![Some(7)]);
}
#[tokio::test(flavor = "multi_thread")]
async fn lease_responses_let_regions_write() {
common_telemetry::init_default_ut_logging();
@@ -642,9 +670,10 @@ mod test {
// A Leader grant renews the lease of the region.
alive_keeper.register_region(region_id).await;
let grant = GrantedRegion {
let grant = PbGrantedRegion {
region_id: region_id.as_u64(),
role: api::v1::meta::RegionRole::Leader.into(),
candidate_lease_id: 0,
extensions: HashMap::new(),
};
handle_lease_response(&alive_keeper, vec![grant.clone()]).await;
@@ -716,9 +745,10 @@ mod test {
// Renew lease then sleep.
alive_keeper
.renew_region_leases(
&[GrantedRegion {
&[PbGrantedRegion {
region_id: region_id.as_u64(),
role: api::v1::meta::RegionRole::Leader.into(),
candidate_lease_id: 0,
extensions: HashMap::new(),
}],
Instant::now(),
@@ -773,12 +803,13 @@ mod test {
// Reset deadline.
countdown_handle
.reset_deadline(
RegionRole::Leader,
Instant::now(),
Instant::now() + Duration::from_millis(heartbeat_interval_millis * 5),
HashMap::new(),
)
.reset_deadline(ResetLease {
role: RegionRole::Leader,
sent_at: Instant::now(),
deadline: Instant::now() + Duration::from_millis(heartbeat_interval_millis * 5),
candidate_lease_id: None,
extensions: HashMap::new(),
})
.await;
assert!(
countdown_handle.deadline().await.unwrap()
@@ -821,9 +852,10 @@ mod test {
alive_keeper.register_region(region_id).await;
alive_keeper
.renew_region_leases(
&[GrantedRegion {
&[PbGrantedRegion {
region_id: region_id.as_u64(),
role: api::v1::meta::RegionRole::StagingLeader.into(),
candidate_lease_id: 0,
extensions: HashMap::new(),
}],
Instant::now(),
@@ -870,9 +902,10 @@ mod test {
alive_keeper.register_region(region_id).await;
alive_keeper
.renew_region_leases(
&[GrantedRegion {
&[PbGrantedRegion {
region_id: region_id.as_u64(),
role: api::v1::meta::RegionRole::Leader.into(),
candidate_lease_id: 0,
extensions: HashMap::new(),
}],
Instant::now(),
@@ -913,9 +946,10 @@ mod test {
alive_keeper.register_region(region_id).await;
alive_keeper
.renew_region_leases(
&[GrantedRegion {
&[PbGrantedRegion {
region_id: region_id.as_u64(),
role: api::v1::meta::RegionRole::StagingLeader.into(),
candidate_lease_id: 0,
extensions: HashMap::new(),
}],
Instant::now(),
+125 -18
View File
@@ -41,7 +41,9 @@ use common_stat::ResourceStatImpl;
use common_telemetry::{error, info, warn};
use common_wal::config::DatanodeWalConfig;
use common_wal::config::kafka::DatanodeKafkaConfig;
use common_wal::config::object_store::{ObjectStoreWalConfig, STANDALONE_GENERATION};
use common_wal::config::object_store::{
EnableObjectStoreWal, FIXED_DIRECTORY_GENERATION, ObjectStoreWalConfig,
};
use common_wal::config::raft_engine::RaftEngineConfig;
use file_engine::engine::FileRegionEngine;
use futures::future::join_all;
@@ -162,15 +164,6 @@ impl Datanode {
);
let _ = self.greptimedb_telemetry_task.stop().await;
if let Some(heartbeat_task) = &self.heartbeat_task {
record_shutdown_error(
&mut first_error,
heartbeat_task
.close()
.map_err(BoxedError::new)
.context(ShutdownInstanceSnafu),
);
}
// The object store WAL stops before the regions close: its stop
// uploads the backlog or drops it, and answers every wait for its
// entries, so a flush that waits for the WAL, queued or run by the
@@ -185,6 +178,16 @@ impl Datanode {
.context(ShutdownInstanceSnafu),
);
}
// WAL draining still needs heartbeat renewal; stop it before the heartbeat.
if let Some(heartbeat_task) = &self.heartbeat_task {
record_shutdown_error(
&mut first_error,
heartbeat_task
.close()
.map_err(BoxedError::new)
.context(ShutdownInstanceSnafu),
);
}
record_shutdown_error(&mut first_error, self.region_server.stop().await);
// The stopped engines no longer hold the raft-engine WAL, so it can be closed.
if let Some(log_store) = self.raft_engine_log_store.take() {
@@ -358,7 +361,10 @@ impl DatanodeBuilder {
// writable upon open.
let controlled_by_metasrv = meta_client.is_some();
if let DatanodeWalConfig::ObjectStore(config) = &self.opts.wal {
ensure!(!controlled_by_metasrv, ObjectStoreWalNotStandaloneSnafu);
ensure!(
!controlled_by_metasrv || self.plugins.get::<EnableObjectStoreWal>().is_some(),
ObjectStoreWalNotStandaloneSnafu
);
validate_object_store_wal_config(config)?;
}
@@ -405,6 +411,12 @@ impl DatanodeBuilder {
// the metasrv.
if controlled_by_metasrv && let Some(mito) = region_server.mito_engine() {
mito.require_write_lease();
if let Some(log_store) = &self.object_store_log_store {
log_store
.set_io_permit(mito.object_store_wal_io_permit())
.map_err(Box::new)
.context(OpenLogStoreSnafu)?;
}
}
// TODO(weny): Considering introducing a readonly kv_backend trait.
@@ -887,7 +899,7 @@ impl DatanodeBuilder {
}
/// Builds [ObjectStoreLogStore] under the node prefix of `node_id` in the
/// standalone generation, the prefix the regions persist in their WAL options.
/// fixed directory generation, the prefix the regions persist in their WAL options.
async fn build_object_store_log_store(
object_store: ObjectStore,
config: &ObjectStoreWalConfig,
@@ -897,7 +909,7 @@ impl DatanodeBuilder {
"Creating object store logstore with config: {:?}, node id: {}",
config, node_id
);
ObjectStoreLogStore::try_new(object_store, config, node_id, STANDALONE_GENERATION)
ObjectStoreLogStore::try_new(object_store, config, node_id, FIXED_DIRECTORY_GENERATION)
.await
.map_err(Box::new)
.context(OpenLogStoreSnafu)
@@ -1207,7 +1219,7 @@ mod tests {
use std::path::Path;
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::time::Duration;
use std::time::{Duration, Instant};
use api::v1::{ColumnSchema, Rows};
use cache::build_datanode_layered_cache_registry;
@@ -1226,7 +1238,9 @@ mod tests {
use common_meta::node_manager::NodeManagerRef;
use common_test_util::temp_dir::{create_named_temp_file, create_temp_dir};
use common_wal::config::DatanodeWalConfig;
use common_wal::config::object_store::{AckMode, ObjectStoreWalConfig, STANDALONE_GENERATION};
use common_wal::config::object_store::{
AckMode, EnableObjectStoreWal, FIXED_DIRECTORY_GENERATION, ObjectStoreWalConfig,
};
use common_wal::config::raft_engine::RaftEngineConfig;
use common_wal::options::{ObjectStoreWalOptions, WAL_OPTIONS_KEY, WalOptions};
use log_store::ObjectStoreLogStore;
@@ -1555,6 +1569,99 @@ mod tests {
assert!(is_empty_dir(data_home.path()));
}
#[tokio::test]
async fn test_cluster_object_store_wal_builder_installs_node_lease() {
let data_home = create_temp_dir("cluster-wal-node-lease");
let config = ObjectStoreWalConfig {
prefix: "cluster-a/wal".to_string(),
..enqueued_wal_config(Duration::from_secs(3600))
};
let mut builder =
object_store_wal_builder(data_home.path().to_str().unwrap(), config.clone());
builder.opts.node_id = Some(7);
builder.plugins.insert(EnableObjectStoreWal);
builder.with_meta_client(Arc::new(
MetaClientBuilder::datanode_default_options(7).build(),
));
let mut datanode = builder.build().await.unwrap();
assert!(datanode.heartbeat_task.is_some());
let log_store = datanode.object_store_log_store().unwrap();
let engine = datanode.region_server.mito_engine().unwrap();
let prefix = config.node_prefix(7, FIXED_DIRECTORY_GENERATION);
assert_eq!("cluster-a/wal/datanodes/7/epochs/0", prefix);
let provider = Provider::object_store_provider(REGION, prefix);
let entry = log_store.entry(vec![1], 0, REGION, &provider).unwrap();
let response = log_store.append_batch(vec![entry]).await.unwrap();
let entry_id = response.last_entry_ids[&REGION];
// The builder installs the permit: no test-side set_io_permit call.
assert_matches!(
log_store.seal_open_batch().await.unwrap_err(),
LogStoreError::ObjectStoreWalLeaseExpired { .. }
);
assert_eq!(0, log_store.latest_entry_id(&provider).unwrap());
let deadline = Instant::now() + Duration::from_secs(60);
engine.renew_node_lease(deadline);
log_store.seal_open_batch().await.unwrap();
assert_eq!(entry_id, log_store.latest_entry_id(&provider).unwrap());
engine.freeze_lease_clock(deadline);
assert_matches!(
log_store.seal_open_batch().await.unwrap_err(),
LogStoreError::ObjectStoreWalLeaseExpired { .. }
);
engine.renew_node_lease(deadline + Duration::from_secs(60));
log_store.seal_open_batch().await.unwrap();
datanode.shutdown().await.unwrap();
}
#[tokio::test]
async fn test_cluster_object_store_wal_shutdown_keeps_heartbeat_until_drained() {
let data_home = create_temp_dir("cluster-wal-shutdown");
let config = enqueued_wal_config(Duration::from_secs(3600));
let mut builder =
object_store_wal_builder(data_home.path().to_str().unwrap(), config.clone());
builder.plugins.insert(EnableObjectStoreWal);
builder.with_meta_client(Arc::new(
MetaClientBuilder::datanode_default_options(0).build(),
));
let mut datanode = builder.build().await.unwrap();
let log_store = datanode.object_store_log_store().unwrap();
let engine = datanode.region_server.mito_engine().unwrap();
engine.renew_node_lease(Instant::now() + WAIT);
// Observe the real close flag without starting network heartbeats.
let heartbeat_running = datanode
.heartbeat_task
.as_ref()
.unwrap()
.running_flag_for_test();
heartbeat_running.store(true, Ordering::Release);
let provider = Provider::object_store_provider(
REGION,
config.node_prefix(0, FIXED_DIRECTORY_GENERATION),
);
let entry = log_store.entry(vec![1], 0, REGION, &provider).unwrap();
let response = log_store.append_batch(vec![entry]).await.unwrap();
log_store.hold_creates();
let shutdown = tokio::spawn(async move { datanode.shutdown().await });
tokio::time::timeout(WAIT, log_store.wait_for_parked_creates(1))
.await
.unwrap()
.unwrap();
assert!(!shutdown.is_finished());
assert!(heartbeat_running.load(Ordering::Acquire));
log_store.release_creates();
tokio::time::timeout(WAIT, shutdown)
.await
.unwrap()
.unwrap()
.unwrap();
assert!(!heartbeat_running.load(Ordering::Acquire));
assert_eq!(
response.last_entry_ids[&REGION],
log_store.latest_entry_id(&provider).unwrap()
);
}
#[tokio::test]
async fn test_build_rejects_unknown_wal_storage_provider() {
let data_home = create_temp_dir("object-store-wal-unknown-provider");
@@ -1913,7 +2020,7 @@ mod tests {
/// The options that put a region on the WAL of a datanode with `config`.
fn region_wal_options(config: &ObjectStoreWalConfig) -> HashMap<String, String> {
let prefix = config.node_prefix(0, STANDALONE_GENERATION);
let prefix = config.node_prefix(0, FIXED_DIRECTORY_GENERATION);
let wal_options =
serde_json::to_string(&WalOptions::ObjectStore(ObjectStoreWalOptions::new(prefix)))
.unwrap();
@@ -1961,7 +2068,7 @@ mod tests {
skipped_rows: usize,
) -> (Datanode, Arc<ObjectStoreLogStore>) {
let config = enqueued_wal_config(flush_interval);
let prefix = config.node_prefix(0, STANDALONE_GENERATION);
let prefix = config.node_prefix(0, FIXED_DIRECTORY_GENERATION);
let mut request = CreateRequestBuilder::new().build();
request.options.extend(region_wal_options(&config));
let datanode = object_store_wal_builder(data_home, config)
@@ -2162,7 +2269,7 @@ mod tests {
fn test_node_prefix_passes_validation() {
let config = ObjectStoreWalConfig::default();
let derived = ObjectStoreWalConfig {
prefix: config.node_prefix(0, STANDALONE_GENERATION),
prefix: config.node_prefix(0, FIXED_DIRECTORY_GENERATION),
..config
};
validate_object_store_wal_config(&derived).unwrap();
+3 -1
View File
@@ -330,7 +330,9 @@ pub enum Error {
location: Location,
},
#[snafu(display("Object store WAL is only supported in standalone mode"))]
#[snafu(display(
"Object store WAL supports standalone only in this build; metasrv-controlled deployment requires a build with distributed object-store WAL integration"
))]
ObjectStoreWalNotStandalone {
#[snafu(implicit)]
location: Location,
+6
View File
@@ -501,6 +501,12 @@ impl HeartbeatTask {
.collect()
}
/// Exposes the lifecycle flag for shutdown-order tests without a network task.
#[cfg(test)]
pub(crate) fn running_flag_for_test(&self) -> Arc<AtomicBool> {
self.running.clone()
}
pub fn close(&self) -> Result<()> {
let running = self.running.clone();
if running
+252 -4
View File
@@ -498,6 +498,7 @@ impl RegionServer {
role: RegionRole,
sent_at: std::time::Instant,
deadline: std::time::Instant,
candidate_lease_id: Option<u64>,
) -> Result<bool> {
let engine = self
.inner
@@ -505,7 +506,7 @@ impl RegionServer {
.get(&region_id)
.with_context(|| RegionNotFoundSnafu { region_id })?;
engine
.set_region_role_with_lease(region_id, role, sent_at, deadline)
.set_region_role_with_lease(region_id, role, sent_at, deadline, candidate_lease_id)
.with_context(|_| HandleRegionRequestSnafu { region_id })
}
@@ -1865,6 +1866,20 @@ impl RegionServerInner {
&self,
batch_request: BatchRegionDdlRequest,
) -> Result<RegionResponse> {
// Drops may remove dependent regions and may partially succeed. Complete each
// request's registration changes before proceeding to the next request.
if let BatchRegionDdlRequest::Drop(requests) = batch_request {
let mut response = RegionResponse::new(0);
for (region_id, request) in requests {
let result = self
.handle_request(region_id, RegionRequest::Drop(request))
.await?;
response.affected_rows += result.affected_rows;
response.extensions.extend(result.extensions);
}
return Ok(response);
}
let region_changes = match &batch_request {
BatchRegionDdlRequest::Create(requests) => requests
.iter()
@@ -1985,6 +2000,12 @@ impl RegionServerInner {
CurrentEngine::EarlyReturn(rows) => return Ok(RegionResponse::new(rows)),
};
let logical_regions = if matches!(region_change, RegionChange::Deregisters) {
self.prepare_logical_regions_for_deregistration(&engine, region_id)
} else {
Vec::new()
};
// Sets corresponding region status to registering/deregistering before the operation.
self.set_region_status_not_ready(region_id, &engine, &region_change);
@@ -1997,6 +2018,14 @@ impl RegionServerInner {
}
match result {
Ok(result) => {
for (logical_region, _) in logical_regions {
self.set_region_status_ready(
logical_region,
engine.clone(),
RegionChange::Deregisters,
)
.await?;
}
// Sets corresponding region status to ready.
self.set_region_status_ready(region_id, engine.clone(), region_change)
.await?;
@@ -2008,6 +2037,9 @@ impl RegionServerInner {
})
}
Err(err) => {
for (logical_region, status) in logical_regions {
self.region_map.insert(logical_region, status);
}
// Removes the region status if the operation fails.
self.unset_region_status(region_id, &engine, region_change);
Err(err)
@@ -2143,6 +2175,26 @@ impl RegionServerInner {
Ok(())
}
/// Captures only existing registrations so failures cannot resurrect closed logical regions.
fn prepare_logical_regions_for_deregistration(
&self,
engine: &RegionEngineRef,
physical_region_id: RegionId,
) -> Vec<(RegionId, RegionEngineWithStatus)> {
let Some(metric_engine) = engine.as_any().downcast_ref::<MetricEngine>() else {
return Vec::new();
};
let logical_regions = metric_engine
.loaded_logical_regions(physical_region_id)
.into_iter()
.filter_map(|id| self.region_map.get(&id).map(|status| (id, status.clone())))
.collect::<Vec<_>>();
for (region_id, _) in &logical_regions {
self.set_region_status_not_ready(*region_id, engine, &RegionChange::Deregisters);
}
logical_regions
}
async fn register_logical_regions(
&self,
engine: &RegionEngineRef,
@@ -2418,7 +2470,7 @@ mod tests {
use common_error::ext::{ErrorExt, RetryHint};
use common_recordbatch::RecordBatches;
use common_recordbatch::adapter::{RecordBatchMetrics, RegionWatermarkEntry};
use common_wal::config::object_store::{ObjectStoreWalConfig, STANDALONE_GENERATION};
use common_wal::config::object_store::{FIXED_DIRECTORY_GENERATION, ObjectStoreWalConfig};
use common_wal::options::{ObjectStoreWalOptions, WAL_OPTIONS_KEY, WalOptions};
use datatypes::prelude::{ConcreteDataType, VectorRef};
use datatypes::schema::{ColumnSchema, Schema};
@@ -3684,7 +3736,7 @@ mod tests {
ObjectStore::new(Memory::default()).unwrap(),
&wal_config,
0,
STANDALONE_GENERATION,
FIXED_DIRECTORY_GENERATION,
)
.await
.unwrap();
@@ -3694,7 +3746,7 @@ mod tests {
let mut region_server = mock_region_server();
region_server.register_engine(Arc::new(engine));
let wal_options = serde_json::to_string(&WalOptions::ObjectStore(
ObjectStoreWalOptions::new(wal_config.node_prefix(0, STANDALONE_GENERATION)),
ObjectStoreWalOptions::new(wal_config.node_prefix(0, FIXED_DIRECTORY_GENERATION)),
))
.unwrap();
(region_server, log_store, wal_options)
@@ -3725,6 +3777,202 @@ mod tests {
}
}
#[tokio::test]
async fn test_metric_physical_drop_and_close_unregister_logical_regions() {
for mode in ["drop", "close", "batch_drop"] {
let mut env = TestEnv::with_prefix("region-server-metric-drop").await;
let mito = env.create_engine(MitoConfig::default()).await;
let metric = Arc::new(
MetricEngine::try_new(mito.clone(), metric_engine::config::EngineConfig::default())
.unwrap(),
);
let mut server = mock_region_server();
server.register_engine(metric.clone());
// Keep a second physical group alive to catch overbroad unregistering.
for table in [10, 20] {
let physical = RegionId::new(table, 0);
let logical = RegionId::new(table + 1, 0);
let mut create = CreateRequestBuilder::new().build();
create.engine = METRIC_ENGINE_NAME.to_string();
create.column_metadatas = vec![
store_api::metadata::ColumnMetadata {
column_id: 0,
semantic_type: SemanticType::Timestamp,
column_schema: ColumnSchema::new(
"greptime_timestamp",
ConcreteDataType::timestamp_millisecond_datatype(),
false,
),
},
store_api::metadata::ColumnMetadata {
column_id: 1,
semantic_type: SemanticType::Field,
column_schema: ColumnSchema::new(
"greptime_value",
ConcreteDataType::float64_datatype(),
false,
),
},
];
create.primary_key.clear();
create.table_dir = format!("metric-drop/{table}/");
create.options = HashMap::from([(
store_api::metric_engine_consts::PHYSICAL_TABLE_METADATA_KEY.to_string(),
String::new(),
)]);
server
.handle_request(physical, RegionRequest::Create(create.clone()))
.await
.unwrap();
create.table_dir = format!("metric-drop/{}/", table + 1);
create.options = HashMap::from([(
store_api::metric_engine_consts::LOGICAL_TABLE_METADATA_KEY.to_string(),
physical.as_u64().to_string(),
)]);
server
.handle_request(logical, RegionRequest::Create(create.clone()))
.await
.unwrap();
if table == 10 {
let closed = RegionId::new(12, 0);
server
.handle_request(closed, RegionRequest::Create(create.clone()))
.await
.unwrap();
server
.handle_request(closed, RegionRequest::Close(RegionCloseRequest::default()))
.await
.unwrap();
}
}
let physical = RegionId::new(10, 0);
let logical = RegionId::new(11, 0);
let mut dependents = metric.loaded_logical_regions(physical);
dependents.sort_unstable();
assert_eq!(dependents, vec![logical, RegionId::new(12, 0)]);
assert!(metric.loaded_logical_regions(logical).is_empty());
// Rejection must leave both registrations usable for a subsequent forced drop.
assert!(
server
.handle_request(
physical,
RegionRequest::Drop(RegionDropRequest {
fast_path: false,
force: false,
partial_drop: false,
})
)
.await
.is_err()
);
assert!(!server.inner.region_map.contains_key(&RegionId::new(12, 0)));
for id in [physical, logical] {
assert!(matches!(
server.inner.region_map.get(&id).unwrap().value(),
RegionEngineWithStatus::Ready(_)
));
}
server
.inner
.region_map
.insert(logical, RegionEngineWithStatus::Registering(metric.clone()));
assert!(
server
.handle_request(
physical,
RegionRequest::Drop(RegionDropRequest {
fast_path: false,
force: false,
partial_drop: false,
})
)
.await
.is_err()
);
assert!(matches!(
server.inner.region_map.get(&logical).unwrap().value(),
RegionEngineWithStatus::Registering(_)
));
server
.inner
.region_map
.insert(logical, RegionEngineWithStatus::Ready(metric.clone()));
if mode == "batch_drop" {
// First group commits, second rejects. Retrying must not resurrect the first.
for _ in 0..2 {
assert!(
server
.inner
.handle_batch_ddl_requests(BatchRegionDdlRequest::Drop(vec![
(
physical,
RegionDropRequest {
fast_path: false,
force: true,
partial_drop: false
}
),
(
RegionId::new(20, 0),
RegionDropRequest {
fast_path: false,
force: false,
partial_drop: false
}
),
]))
.await
.is_err()
);
assert!(!server.inner.region_map.contains_key(&physical));
assert!(!server.inner.region_map.contains_key(&logical));
}
}
let request = || {
if mode == "close" {
RegionRequest::Close(RegionCloseRequest::default())
} else {
RegionRequest::Drop(RegionDropRequest {
fast_path: false,
force: true,
partial_drop: false,
})
}
};
// A retry of an already completed removal remains harmless.
for _ in 0..2 {
if mode == "batch_drop" {
server
.inner
.handle_batch_ddl_requests(BatchRegionDdlRequest::Drop(vec![(
physical,
RegionDropRequest {
fast_path: false,
force: true,
partial_drop: false,
},
)]))
.await
.unwrap();
} else {
server.handle_request(physical, request()).await.unwrap();
}
}
for id in [physical, logical] {
assert!(!server.inner.region_map.contains_key(&id));
}
assert!(metric.loaded_logical_regions(physical).is_empty());
for id in [RegionId::new(20, 0), RegionId::new(21, 0)] {
assert!(server.inner.region_map.contains_key(&id));
}
assert_eq!(
metric.loaded_logical_regions(RegionId::new(20, 0)),
vec![RegionId::new(21, 0)]
);
server.stop().await.unwrap();
}
}
#[tokio::test]
async fn test_metric_batch_failure_indices() {
let mut env = TestEnv::with_prefix("region-server-metric-results").await;
+12 -1
View File
@@ -13,7 +13,7 @@
// limitations under the License.
use std::any::Any;
use std::sync::Arc;
use std::sync::{Arc, Mutex};
use std::time::Duration;
use api::region::RegionResponse;
@@ -135,6 +135,8 @@ pub struct MockRegionEngine {
pub(crate) handle_sync_region_mock_fn: Option<MockSyncRegionHandler>,
pub(crate) handle_stop_mock_fn: Option<MockStopHandler>,
pub(crate) mock_role: Option<Option<RegionRole>>,
/// The candidate lease ids of the leases the engine received.
pub(crate) candidate_lease_ids: Mutex<Vec<Option<u64>>>,
engine: String,
}
@@ -152,6 +154,7 @@ impl MockRegionEngine {
handle_sync_region_mock_fn: None,
handle_stop_mock_fn: None,
mock_role: None,
candidate_lease_ids: Mutex::default(),
engine: engine.to_string(),
}),
rx,
@@ -174,6 +177,7 @@ impl MockRegionEngine {
handle_sync_region_mock_fn: None,
handle_stop_mock_fn: None,
mock_role: None,
candidate_lease_ids: Mutex::default(),
engine: engine.to_string(),
}),
rx,
@@ -196,6 +200,7 @@ impl MockRegionEngine {
handle_sync_region_mock_fn: None,
handle_stop_mock_fn: None,
mock_role: None,
candidate_lease_ids: Mutex::default(),
engine: engine.to_string(),
}),
rx,
@@ -219,6 +224,7 @@ impl MockRegionEngine {
handle_sync_region_mock_fn: None,
handle_stop_mock_fn: None,
mock_role: None,
candidate_lease_ids: Mutex::default(),
engine: engine.to_string(),
};
@@ -295,7 +301,12 @@ impl RegionEngine for MockRegionEngine {
role: RegionRole,
_sent_at: std::time::Instant,
_deadline: std::time::Instant,
candidate_lease_id: Option<u64>,
) -> Result<bool, BoxedError> {
self.candidate_lease_ids
.lock()
.unwrap()
.push(candidate_lease_id);
// A mocked role stays, so a grant of another role is not applied.
Ok(self.mock_role.flatten().is_none_or(|mocked| mocked == role))
}
+5
View File
@@ -379,6 +379,11 @@ impl JsonValue {
self.json_variant
}
/// Borrows the JSON representation without constructing a tree of value references.
pub fn variant(&self) -> &JsonVariant {
&self.json_variant
}
pub(crate) fn into_value(self) -> Value {
fn helper(v: JsonVariant) -> Value {
match v {
+1
View File
@@ -139,6 +139,7 @@ impl RegionEngine for FileRegionEngine {
role: RegionRole,
_sent_at: Instant,
_deadline: Instant,
_candidate_lease_id: Option<u64>,
) -> Result<bool, BoxedError> {
self.set_region_role(region_id, role).map(|_| true)
}
+14 -2
View File
@@ -48,8 +48,12 @@ including caches owned by pipeline and protocol handlers.
planning or executing SQL, including prepared statements; unqualified targets
fail without falling back to `public`.
- **Exemplar query** (`instance/exemplar.rs`): authorize all selector branches
before calling `PromQueryInterceptor::pre_execute_exemplars` for each resolved
exemplar table, with that table's schema context, before scanning it.
before resolving logical schemas or calling
`PromQueryInterceptor::pre_execute_exemplars`. Exact metric selectors project
the union of current logical-table tags; broad or unresolved selectors retain
all tags. Responses include the stored `__table_id` and `__tsid` as string labels.
The process ticket retains the configured slow-query timer through collection;
its query text includes the expression and inclusive nanosecond scan bounds.
- **Logical-table batch DDL** (`instance.rs`): dedicated SQL handler → bounded
parse/interception → all-member permissions → operator CREATE preparation →
one logical-table batch procedure. Keep pre-submission validation side-effect free.
@@ -70,6 +74,8 @@ including caches owned by pipeline and protocol handlers.
- **Flight bulk insert** (`instance/grpc.rs`): initializes on the first batch after
the lazy schema handshake; checks permissions and reconciles missing columns
through `Inserter` once per stream, then reuses the refreshed table.
PostgreSQL Arrow COPY delegates to this same handler via `instance/copy_in.rs`;
keep bulk authorization, interceptors, schema-on-write, and writes shared.
- **OTLP trace lookup tables** (`instance/otlp/trace_ingest.rs`): `Instance` owns
a shared cache of confirmed service/operation writes, which bypass batching.
@@ -90,6 +96,8 @@ including caches owned by pipeline and protocol handlers.
Reserve exemplar expansion with the transport's memory limiter before building
rows; retain the permit through `WriteProgress` until writes complete.
Expansion must not wait while the request holds transport memory permits.
Confirm source metric writes before inserting their exemplars; unrelated
metric writes remain concurrent and their completions must still be observed.
- **Logical-table batching** (`instance/logical_batcher.rs`): `Services` initializes
one shared batcher for opted-in Prom remote-write (HTTP and PostgreSQL COPY)
@@ -103,6 +111,10 @@ including caches owned by pipeline and protocol handlers.
for `servers::batcher::table::TablePendingRowsBatcher`. A separate execution-only
inserter, with no batcher attached, sends the prepared bulk writes to datanodes,
avoiding recursive batching. The batcher handles successful-write Flow notifications.
`FrontendBuilder` creates the write memory limiter shared by conversion admission
and the protocol servers wired by `Services`. Conversion admission includes the
request's live transport and retained decoder reservations in its fit check;
previously queued Arrow batches remain transient contention.
## Public surface
+12 -1
View File
@@ -23,6 +23,7 @@ use common_memory_manager::OnExhaustedPolicy;
use common_options::datanode::DatanodeClientOptions;
use common_options::memory::MemoryOptions;
use common_telemetry::logging::{LoggingOptions, SlowQueryOptions, TracingOptions};
use common_time::timestamp::TimeUnit;
use meta_client::{MetaClientOptions, MetaClientRef};
use pipeline::PipelineOptions;
use query::options::QueryOptions;
@@ -53,11 +54,20 @@ pub struct FrontendOptions {
/// even if a request sets the `auto_create_table` hint to `true`. When `true`
/// (default), the per-request hint still applies. Default: `true`.
pub auto_create_table: bool,
/// Maximum total memory for all concurrent write request bodies and messages (HTTP, gRPC, Flight).
/// 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".
pub auto_create_physical_table_timestamp_unit: TimeUnit,
/// Shared quota for write bodies/messages, retained decoder memory, and estimated
/// ordinary-table batch conversion memory. A batch must fit alongside its request's
/// existing reservations; only additional memory is acquired.
/// Set to 0 to disable the limit. Default: "0" (unlimited)
pub max_in_flight_write_bytes: ReadableSize,
/// Policy when write bytes quota is exhausted.
/// Options: "wait" (default, 10s), "wait(<duration>)", "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.
pub write_bytes_exhausted_policy: OnExhaustedPolicy,
pub http: HttpOptions,
pub grpc: GrpcOptions,
@@ -105,6 +115,7 @@ impl Default for FrontendOptions {
default_timezone: None,
default_column_prefix: None,
auto_create_table: true,
auto_create_physical_table_timestamp_unit: TimeUnit::Millisecond,
max_in_flight_write_bytes: ReadableSize(0),
write_bytes_exhausted_policy: OnExhaustedPolicy::default(),
http: HttpOptions::default(),
+63
View File
@@ -64,6 +64,7 @@ use common_recordbatch::RecordBatchStreamWrapper;
use common_recordbatch::error::StreamTimeoutSnafu;
use common_telemetry::logging::SlowQueryOptions;
use common_telemetry::{debug, error, tracing};
use common_time::timestamp::TimeUnit;
use datafusion::dataframe::DataFrame;
use datafusion::physical_plan::ExecutionPlan;
use datafusion_expr::LogicalPlan;
@@ -89,6 +90,7 @@ use servers::prometheus_handler::{
ParsedPromQuery, PrometheusHandler, resolve_schema_from_matchers,
};
use servers::query_handler::sql::SqlQueryHandler;
use servers::request_memory_limiter::ServerMemoryLimiter;
use session::context::{Channel, QueryContextRef};
use session::table_name::table_idents_to_full_name;
use snafu::prelude::*;
@@ -116,6 +118,7 @@ use crate::stream_wrapper::CancellableStreamWrapper;
/// [`servers::query_handler::sql::SqlQueryHandler`], etc.
#[derive(Clone)]
pub struct Instance {
server_memory_limiter: ServerMemoryLimiter,
frontend_peer_addr: String,
catalog_manager: CatalogManagerRef,
pipeline_operator: Arc<PipelineOperator>,
@@ -131,6 +134,9 @@ pub struct Instance {
process_manager: ProcessManagerRef,
slow_query_options: SlowQueryOptions,
influxdb_default_merge_mode: InfluxdbMergeMode,
/// Time index unit for physical metric tables created by auto table creation
/// through the frontend instance (e.g., batched logical-table flushes).
auto_create_physical_table_timestamp_unit: TimeUnit,
trace_ingest_chunk_size: usize,
trace_aux_cache: otlp::TraceAuxCache,
trace_aux_limiter: Option<RequestLimiter>,
@@ -139,6 +145,11 @@ pub struct Instance {
}
impl Instance {
/// Returns the memory pool shared by protocol admission and table-batch conversion.
pub fn server_memory_limiter(&self) -> &ServerMemoryLimiter {
&self.server_memory_limiter
}
pub fn frontend_peer_addr(&self) -> &str {
&self.frontend_peer_addr
}
@@ -4345,6 +4356,58 @@ mod tests {
assert!(!should_track_plan_process(None, &insert_dml_plan()));
}
#[tokio::test]
async fn test_exemplar_slow_query() -> TestResult<()> {
use common_catalog::consts::METRICS_EXEMPLARS_TABLE;
use servers::exemplar::query::Query as ExemplarQuery;
for invalid_destination in [false, true] {
let table_name = if invalid_destination {
METRICS_EXEMPLARS_TABLE
} else {
"source"
};
let mut instance = test_instance_with_tables(
test_table(1024, table_name)?,
test_table(1025, "target")?,
)
.await?;
let recorder = Arc::new(RecordingSlowQueryEventRecorder::default());
instance.slow_query_recorder = recorder.clone();
instance.slow_query_options.sample_ratio = 1.0;
instance.slow_query_options.record_type = SlowQueriesRecordType::SystemTable;
for (enabled, threshold, should_record) in [
(true, Duration::ZERO, true),
(false, Duration::ZERO, false),
(true, Duration::from_secs(3600), false),
] {
instance.slow_query_options.enable = enabled;
instance.slow_query_options.threshold = threshold;
let query =
ExemplarQuery::parse("source".into(), "-0.001", "0.001", "public").unwrap();
let result = instance.query_exemplars(query, QueryContext::arc()).await;
if invalid_destination {
assert!(result.is_err());
} else {
assert!(result.unwrap().is_empty());
}
let queries = std::mem::take(&mut *recorder.queries.lock().unwrap());
let expected = if should_record {
vec!["query_exemplars(source, start_ns=-1000000, end_ns=1999999)"]
} else {
vec![]
};
assert_eq!(
queries, expected,
"invalid_destination={invalid_destination}, enabled={enabled}, threshold={threshold:?}"
);
}
}
Ok(())
}
#[tokio::test]
async fn test_insert_select_slow_query() -> TestResult<()> {
let mut instance =
+13
View File
@@ -53,6 +53,7 @@ use query::QueryEngineFactory;
use query::region_query::RegionQueryHandlerFactoryRef;
use servers::batcher::table::TablePendingRowsBatcher;
use servers::batcher::{BatchingProtocol, pending_rows_batch_sync_enabled};
use servers::request_memory_limiter::ServerMemoryLimiter;
use snafu::{OptionExt, ResultExt};
use crate::error::{self, DataFusionSnafu, ExternalSnafu, Result};
@@ -252,10 +253,17 @@ impl FrontendBuilder {
table_flownode_cache.clone(),
self.options.auto_create_table,
)
.with_auto_create_physical_table_timestamp_unit(
self.options.auto_create_physical_table_timestamp_unit,
)
.with_write_dispatcher(write_dispatcher.clone())
};
// The execution-only inserter owns no batchers, avoiding an Arc cycle.
let bulk_inserter = Arc::new(create_inserter());
let server_memory_limiter = ServerMemoryLimiter::new(
self.options.max_in_flight_write_bytes.as_bytes(),
self.options.write_bytes_exhausted_policy,
);
let build_batcher = |options: &BatcherOptions| -> Option<Arc<dyn PendingRowsBatcher>> {
if !options.pending_rows_batching_enabled()
|| (self.options.prom_store.with_metric_engine
@@ -273,6 +281,7 @@ impl FrontendBuilder {
options.worker_channel_capacity,
options.max_inflight_requests,
options.flow_notification_queue_capacity,
server_memory_limiter.clone(),
bulk_inserter.clone(),
)
.map(|batcher| batcher as Arc<dyn PendingRowsBatcher>)
@@ -417,6 +426,7 @@ impl FrontendBuilder {
};
Ok(Instance {
server_memory_limiter,
logical_batcher: Default::default(),
frontend_peer_addr,
catalog_manager: self.catalog_manager,
@@ -432,6 +442,9 @@ impl FrontendBuilder {
process_manager,
slow_query_options: self.options.slow_query.clone(),
influxdb_default_merge_mode: self.options.influxdb.default_merge_mode,
auto_create_physical_table_timestamp_unit: self
.options
.auto_create_physical_table_timestamp_unit,
trace_ingest_chunk_size: self.options.otlp.trace_ingest_chunk_size,
trace_aux_cache: TraceAuxCache::new(self.options.otlp.trace_aux_cache_size.as_bytes()),
trace_aux_limiter,
+14
View File
@@ -94,6 +94,20 @@ impl CopyInHandler for Instance {
Ok(table_info)
}
fn copy_in_arrow(
&self,
stream: servers::grpc::flight::PutRecordBatchRequestStream,
query_ctx: QueryContextRef,
) -> Result<
futures::stream::BoxStream<'static, Result<common_grpc::flight::do_put::DoPutResponse>>,
> {
Ok(
servers::query_handler::grpc::GrpcQueryHandler::handle_put_record_batch_stream(
self, stream, query_ctx,
),
)
}
async fn copy_in_insert(
&self,
requests: RowInsertRequests,
+286 -35
View File
@@ -16,12 +16,13 @@ use std::collections::{BTreeMap, BTreeSet};
use std::sync::Arc;
use auth::{PermissionTableTarget, PermissionTableTargets};
use catalog::process_manager::{QueryStatement as CatalogQueryStatement, SlowQueryTimer};
use common_base::cancellation::CancellableFuture;
use common_catalog::consts::METRICS_EXEMPLARS_TABLE;
use common_error::ext::BoxedError;
use common_query::OutputData;
use common_query::prelude::{
EXEMPLAR_LABELS_COLUMN, EXEMPLAR_METRIC_COLUMN, greptime_timestamp, greptime_value,
EXEMPLAR_METRIC_COLUMN, greptime_exemplar_labels, greptime_timestamp, greptime_value,
};
use common_query::prometheus::format_prometheus_float;
use common_recordbatch::RecordBatch;
@@ -43,7 +44,8 @@ use servers::prometheus_handler::PrometheusHandler;
use session::context::QueryContextRef;
use snafu::{OptionExt, ResultExt, ensure};
use store_api::metric_engine_consts::{
DATA_SCHEMA_TABLE_ID_COLUMN_NAME, DATA_SCHEMA_TSID_COLUMN_NAME,
DATA_SCHEMA_TABLE_ID_COLUMN_NAME, DATA_SCHEMA_TSID_COLUMN_NAME, LOGICAL_TABLE_METADATA_KEY,
METRIC_ENGINE_NAME,
};
use table::metadata::TableInfo;
@@ -100,13 +102,27 @@ impl Instance {
self.check_query_target_permission(PermissionTableTargets::resolved(targets), &local)
.await?;
}
let raw_query = format!(
"query_exemplars({}, start_ns={}, end_ns={})",
query.expression, query.bounds.0, query.bounds.1
);
let slow_query_timer = self.slow_query_options.enable.then(|| {
SlowQueryTimer::new(
CatalogQueryStatement::Plan(raw_query.clone()),
ctx.current_schema(),
self.slow_query_options.threshold,
self.slow_query_options.sample_ratio,
self.slow_query_options.record_type,
self.slow_query_recorder.clone(),
)
});
let ticket = self.process_manager.register_query(
ctx.current_catalog().to_string(),
groups.keys().cloned().collect(),
format!("query_exemplars({})", query.expression),
raw_query,
ctx.conn_info().to_string(),
Some(ctx.process_id()),
None,
slow_query_timer,
);
let cancellation = ticket.cancellation_handle.clone();
let future = async {
@@ -144,6 +160,8 @@ impl Instance {
.map_err(BoxedError::new)
.context(error::ExecuteQuerySnafu)?;
let filter = filter(&info, &selectors, query.bounds)?;
let source_tags = self.exemplar_source_tags(&selectors, &local).await?;
let (projection, tags) = exemplar_projection(&info, source_tags.as_ref());
let frame = self
.query_engine
.read_table(table)
@@ -152,6 +170,8 @@ impl Instance {
let plan = frame
.filter(filter)
.context(error::DataFusionSnafu)?
.select(projection)
.context(error::DataFusionSnafu)?
.into_unoptimized_plan();
interceptor.pre_execute_exemplars(&query, info.table_ref(), local.clone())?;
let output = self
@@ -165,7 +185,7 @@ impl Instance {
while let Some(batch) = stream.next().await {
skipped += collect(
batch.context(error::CollectRecordbatchSnafu)?,
&info,
&tags,
&mut observations,
&mut reservation,
)?;
@@ -174,7 +194,7 @@ impl Instance {
}
OutputData::RecordBatches(batches) => {
for batch in batches.take() {
skipped += collect(batch, &info, &mut observations, &mut reservation)?;
skipped += collect(batch, &tags, &mut observations, &mut reservation)?;
tokio::task::yield_now().await;
}
}
@@ -207,6 +227,61 @@ impl Instance {
drop(ticket);
result
}
async fn exemplar_source_tags(
&self,
selectors: &[&Selector],
ctx: &QueryContextRef,
) -> Result<Option<BTreeSet<String>>> {
let Some(metrics) = selectors
.iter()
.map(|selector| {
selector.matchers.iter().find_map(|matcher| {
(matcher.name == METRIC_NAME
&& matches!(matcher.op, MatchOp::Equal)
&& !matcher.value.is_empty())
.then_some(matcher.value.as_str())
})
})
.collect::<Option<BTreeSet<_>>>()
else {
return Ok(None);
};
let mut tags = BTreeSet::new();
for metric in metrics {
let Some(table) = self
.catalog_manager
.table(
ctx.current_catalog(),
&ctx.current_schema(),
metric,
Some(ctx),
)
.await
.map_err(BoxedError::new)
.context(error::ExecuteQuerySnafu)?
else {
return Ok(None);
};
let info = table.table_info();
if info.meta.engine != METRIC_ENGINE_NAME
|| !info
.meta
.options
.extra_options
.contains_key(LOGICAL_TABLE_METADATA_KEY)
{
return Ok(None);
}
tags.extend(
info.meta
.primary_key_indices
.iter()
.map(|&index| info.meta.schema.column_schemas()[index].name.clone()),
);
}
Ok(Some(tags))
}
}
fn column(name: &str) -> Expr {
@@ -310,9 +385,44 @@ fn matcher_filter(matcher: &Matcher, tags: &BTreeSet<&str>) -> Expr {
}
}
fn exemplar_projection<'a>(
info: &'a TableInfo,
source_tags: Option<&BTreeSet<String>>,
) -> (Vec<Expr>, Vec<&'a str>) {
// Exact metric queries use current logical schemas, including for historical rows.
let tags = info
.meta
.primary_key_indices
.iter()
.map(|&index| info.meta.schema.column_schemas()[index].name.as_str())
.filter(|name| {
![
EXEMPLAR_METRIC_COLUMN,
DATA_SCHEMA_TABLE_ID_COLUMN_NAME,
DATA_SCHEMA_TSID_COLUMN_NAME,
]
.contains(name)
&& source_tags.is_none_or(|tags| tags.contains(*name))
})
.collect::<Vec<_>>();
let projection = [
EXEMPLAR_METRIC_COLUMN,
greptime_timestamp(),
greptime_value(),
greptime_exemplar_labels(),
DATA_SCHEMA_TABLE_ID_COLUMN_NAME,
DATA_SCHEMA_TSID_COLUMN_NAME,
]
.into_iter()
.chain(tags.iter().copied())
.map(column)
.collect();
(projection, tags)
}
fn collect(
batch: RecordBatch,
info: &TableInfo,
tag_names: &[&str],
observations: &mut Observations,
reservation: &mut MemoryReservation,
) -> Result<usize> {
@@ -331,6 +441,12 @@ fn collect(
let value = Helper::try_into_vector(batch.column(index(greptime_value())?))
.map_err(BoxedError::new)
.context(error::ExecuteQuerySnafu)?;
let table_id = Helper::try_into_vector(batch.column(index(DATA_SCHEMA_TABLE_ID_COLUMN_NAME)?))
.map_err(BoxedError::new)
.context(error::ExecuteQuerySnafu)?;
let tsid = Helper::try_into_vector(batch.column(index(DATA_SCHEMA_TSID_COLUMN_NAME)?))
.map_err(BoxedError::new)
.context(error::ExecuteQuerySnafu)?;
let value_type = |vector: &VectorRef| {
let mut data_type = vector.data_type();
// Storage may dictionary-encode tags; Vector::get returns their decoded values.
@@ -342,37 +458,30 @@ fn collect(
ensure!(
value_type(&metric).is_string()
&& value_type(&time).is_timestamp()
&& value_type(&value) == ConcreteDataType::float64_datatype(),
&& value_type(&value) == ConcreteDataType::float64_datatype()
&& value_type(&table_id) == ConcreteDataType::uint32_datatype()
&& value_type(&tsid) == ConcreteDataType::uint64_datatype(),
error::UnexpectedResultSnafu {
reason: "exemplar scan returned incompatible column types",
}
);
let label_index = index(EXEMPLAR_LABELS_COLUMN)?;
let label_index = index(greptime_exemplar_labels())?;
let labels = JsonArray::from(batch.column(label_index))
.project_to_v2(schema.field(label_index), &DataType::Binary)
.map_err(BoxedError::new)
.context(error::ExecuteQuerySnafu)?;
let mut tags = Vec::<(&str, VectorRef)>::new();
for tag in &info.meta.primary_key_indices {
let name = info.meta.schema.column_schemas()[*tag].name.as_str();
if ![
EXEMPLAR_METRIC_COLUMN,
DATA_SCHEMA_TABLE_ID_COLUMN_NAME,
DATA_SCHEMA_TSID_COLUMN_NAME,
]
.contains(&name)
{
let values = Helper::try_into_vector(batch.column(index(name)?))
.map_err(BoxedError::new)
.context(error::ExecuteQuerySnafu)?;
ensure!(
value_type(&values).is_string(),
error::UnexpectedResultSnafu {
reason: "exemplar scan returned a non-string tag",
}
);
tags.push((name, values));
}
for &name in tag_names {
let values = Helper::try_into_vector(batch.column(index(name)?))
.map_err(BoxedError::new)
.context(error::ExecuteQuerySnafu)?;
ensure!(
value_type(&values).is_string(),
error::UnexpectedResultSnafu {
reason: "exemplar scan returned a non-string tag",
}
);
tags.push((name, values));
}
let mut skipped = 0;
'rows: for row in 0..batch.num_rows() {
@@ -393,7 +502,19 @@ fn collect(
skipped += 1;
continue;
};
let mut series = BTreeMap::from([(METRIC_NAME.to_string(), metric.into_string())]);
let (Value::UInt32(table_id), Value::UInt64(tsid)) = (table_id.get(row), tsid.get(row))
else {
skipped += 1;
continue;
};
let mut series = BTreeMap::from([
(METRIC_NAME.to_string(), metric.into_string()),
(
DATA_SCHEMA_TABLE_ID_COLUMN_NAME.to_string(),
table_id.to_string(),
),
(DATA_SCHEMA_TSID_COLUMN_NAME.to_string(), tsid.to_string()),
]);
for (name, values) in &tags {
if let Value::String(value) = values.get(row) {
series.insert((*name).to_string(), value.into_string());
@@ -449,13 +570,146 @@ fn collect(
#[cfg(test)]
mod tests {
use datafusion::execution::memory_pool::{GreedyMemoryPool, MemoryPool};
use datatypes::arrow::array::{
ArrayRef, Float64Array, StringArray, StructArray, TimestampNanosecondArray, UInt32Array,
UInt64Array,
};
use datatypes::arrow::datatypes::Field;
use datatypes::extension::json::Json2ExtensionType;
use datatypes::prelude::ConcreteDataType;
use datatypes::schema::{ColumnSchema, Schema};
use datatypes::vectors::Float64Vector;
use table::metadata::{TableInfoBuilder, TableMeta};
use table::metadata::{TableInfoBuilder, TableMetaBuilder};
use super::*;
#[test]
fn test_exemplar_projection_prunes_tags_and_preserves_source_ids() {
let labels = StructArray::from(vec![(
Arc::new(Field::new("trace_id", DataType::Utf8, false)),
Arc::new(StringArray::from(vec!["trace"; 4])) as ArrayRef,
)]);
let columns: Vec<(&str, ArrayRef)> = vec![
(
DATA_SCHEMA_TABLE_ID_COLUMN_NAME,
Arc::new(UInt32Array::from(vec![1, 1, 2, 2])),
),
(
DATA_SCHEMA_TSID_COLUMN_NAME,
Arc::new(UInt64Array::from(vec![u64::MAX, u64::MAX, u64::MAX, 2])),
),
(
EXEMPLAR_METRIC_COLUMN,
Arc::new(StringArray::from(vec!["metric"; 4])),
),
(
"job",
Arc::new(StringArray::from(vec![Some(""), Some(""), Some(""), None])),
),
(
greptime_timestamp(),
Arc::new(TimestampNanosecondArray::from(vec![1; 4])),
),
(greptime_value(), Arc::new(Float64Array::from(vec![1.0; 4]))),
(greptime_exemplar_labels(), Arc::new(labels)),
(
"unrelated_tag",
Arc::new(StringArray::from(vec!["other"; 4])),
),
];
let schema = Arc::new(Schema::new(
columns
.iter()
.map(|(name, values)| {
let mut column = ColumnSchema::new(
*name,
ConcreteDataType::from_arrow_type(values.data_type()),
true,
);
if *name == greptime_exemplar_labels() {
column.with_extension_type(&Json2ExtensionType::default());
}
column
})
.collect::<Vec<_>>(),
));
let batch = RecordBatch::new(
schema.clone(),
columns
.into_iter()
.map(|(_, array)| Helper::try_into_vector(&array).unwrap()),
)
.unwrap();
let info = TableInfoBuilder::new(
METRICS_EXEMPLARS_TABLE,
TableMetaBuilder::empty()
.schema(schema)
.primary_key_indices(vec![0, 1, 2, 3, 7])
.next_column_id(8)
.build()
.unwrap(),
)
.build()
.unwrap();
let source_tags = BTreeSet::from(["job".into(), "sample_only_tag".into()]);
let (projection, tags) = exemplar_projection(&info, Some(&source_tags));
assert_eq!(tags, ["job"]);
assert_eq!(
projection,
[
EXEMPLAR_METRIC_COLUMN,
greptime_timestamp(),
greptime_value(),
greptime_exemplar_labels(),
DATA_SCHEMA_TABLE_ID_COLUMN_NAME,
DATA_SCHEMA_TSID_COLUMN_NAME,
"job",
]
.map(column)
);
let (full_projection, full_tags) = exemplar_projection(&info, None);
let mut expected_full = projection.clone();
expected_full.push(column("unrelated_tag"));
assert_eq!(full_projection, expected_full);
assert_eq!(full_tags, ["job", "unrelated_tag"]);
let (no_tag_projection, no_tags) = exemplar_projection(&info, Some(&BTreeSet::new()));
assert_eq!(no_tag_projection, projection[..6]);
assert!(no_tags.is_empty());
let projected = batch.try_project(&[2, 4, 5, 6, 0, 1, 3]).unwrap();
let pool: Arc<dyn MemoryPool> = Arc::new(GreedyMemoryPool::new(1 << 20));
let mut reservation = MemoryConsumer::new("projection test").register(&pool);
let mut full = Observations::new();
let mut narrow = Observations::new();
assert_eq!(
collect(batch, &tags, &mut full, &mut reservation).unwrap(),
0
);
assert_eq!(
collect(projected, &tags, &mut narrow, &mut reservation).unwrap(),
0
);
assert_eq!(full.len(), 3);
assert_eq!(full.values().map(BTreeMap::len).sum::<usize>(), 3);
assert_eq!(full, narrow);
for table_id in ["1", "2"] {
assert!(narrow.keys().any(|labels| {
labels[DATA_SCHEMA_TABLE_ID_COLUMN_NAME] == table_id
&& labels[DATA_SCHEMA_TSID_COLUMN_NAME] == u64::MAX.to_string()
&& labels.get("job").is_some_and(String::is_empty)
}));
}
assert!(narrow.keys().any(|labels| {
labels[DATA_SCHEMA_TABLE_ID_COLUMN_NAME] == "2"
&& labels[DATA_SCHEMA_TSID_COLUMN_NAME] == "2"
&& !labels.contains_key("job")
}));
assert!(
narrow
.keys()
.all(|labels| !labels.contains_key("unrelated_tag"))
);
}
#[test]
fn test_exemplar_scan_batch_respects_query_memory_budget() {
let schema = Arc::new(Schema::new(vec![ColumnSchema::new(
@@ -468,13 +722,10 @@ mod tests {
vec![Arc::new(Float64Vector::from_vec(vec![1.0; 128])) as VectorRef],
)
.unwrap();
let info = TableInfoBuilder::new(METRICS_EXEMPLARS_TABLE, TableMeta::empty())
.build()
.unwrap();
let pool: Arc<dyn MemoryPool> = Arc::new(GreedyMemoryPool::new(1));
let mut reservation = MemoryConsumer::new("exemplar test").register(&pool);
let mut observations = Observations::new();
let error = collect(batch, &info, &mut observations, &mut reservation).unwrap_err();
let error = collect(batch, &[], &mut observations, &mut reservation).unwrap_err();
assert!(matches!(
error,
error::Error::DataFusion {
@@ -53,6 +53,7 @@ impl Instance {
self.table_flownode_set_cache().clone(),
true,
Arc::new(LogicalTables(Arc::downgrade(self))),
options.auto_create_physical_table_timestamp_unit,
options_batcher.pending_rows_flush_interval,
options_batcher.max_batch_rows,
options_batcher.max_concurrent_flushes,
+34 -28
View File
@@ -226,7 +226,10 @@ impl OpenTelemetryProtocolHandler for Instance {
});
let mut ctx = ctx.fork();
// Queued and detached writes retain the reservation after caller cancellation.
ctx.set_write_progress(Arc::new(WriteProgress::with_reservation(reservation)));
ctx.set_write_progress(Arc::new(WriteProgress::with_reservation(
reservation.granted_bytes(),
reservation,
)));
Arc::new(ctx)
} else {
ctx
@@ -297,18 +300,34 @@ impl OpenTelemetryProtocolHandler for Instance {
.await
.map_err(BoxedError::new)
.context(error::ExecuteGrpcQuerySnafu);
let source_ready = prepared.is_ok();
let sources = prepared
.as_ref()
.map(|request| request.source_tables().cloned().collect::<Vec<_>>())
.unwrap_or_default();
let (metric_output, other_output, exemplar_output) = tokio::join!(
let mut exemplar_output = Ok(Output::new_with_affected_rows(0));
let (metric_progress, other_output) = tokio::join!(
async {
self.inserter
.handle_prepared_metric_inserts(prepared?, confirmed.clone())
let prepared = prepared?;
let sources = prepared.source_tables().cloned().collect::<Vec<_>>();
let output = self
.inserter
.handle_prepared_metric_inserts(prepared, confirmed.clone())
.await
.map_err(BoxedError::new)
.context(error::ExecuteGrpcQuerySnafu)
.context(error::ExecuteGrpcQuerySnafu)?;
outcome.write_cost += output.meta.cost;
// Successful insertion outputs can still carry storage failures.
let progress = output.write_progress().await;
if progress.error.is_none() {
exemplar_output = self
.inserter
.handle_exemplar_inserts(
exemplars,
confirmed.clone(),
&self.statement_executor,
&sources,
)
.await
.map_err(BoxedError::new)
.context(error::ExecuteGrpcQuerySnafu);
}
Ok::<_, error::Error>(progress)
},
async {
if other.is_empty() {
@@ -322,25 +341,12 @@ impl OpenTelemetryProtocolHandler for Instance {
.await
}
},
async {
// Failed source preparation must not bind exemplars to a later replacement table.
if !source_ready {
return Ok(Output::new_with_affected_rows(0));
}
self.inserter
.handle_exemplar_inserts(
exemplars,
confirmed.clone(),
&self.statement_executor,
&sources,
)
.await
.map_err(BoxedError::new)
.context(error::ExecuteGrpcQuerySnafu)
},
);
let mut progress = common_query::WriteProgress::default();
for output in [metric_output, other_output, exemplar_output] {
let mut progress = match metric_progress {
Ok(progress) => progress,
Err(error) => common_query::WriteProgress::failed(BoxedError::new(error)),
};
for output in [other_output, exemplar_output] {
match output {
Ok(output) => {
outcome.write_cost += output.meta.cost;
+3 -1
View File
@@ -788,7 +788,9 @@ impl Instance {
let default_schema = vec![
api::v1::ColumnSchema {
column_name: common_query::prelude::greptime_timestamp().to_string(),
datatype: api::v1::ColumnDataType::TimestampMillisecond as i32,
datatype: api::helper::timestamp_datatype(
self.auto_create_physical_table_timestamp_unit,
) as i32,
semantic_type: api::v1::SemanticType::Timestamp as i32,
datatype_extension: None,
options: None,
+1 -5
View File
@@ -73,11 +73,7 @@ where
pub fn new(opts: T, instance: Arc<Instance>, plugins: Plugins) -> Self {
let feopts = opts.clone().into();
instance.init_logical_batcher(&feopts);
// Create server request memory limiter for all server protocols
let server_memory_limiter = ServerMemoryLimiter::new(
feopts.max_in_flight_write_bytes.as_bytes(),
feopts.write_bytes_exhausted_policy,
);
let server_memory_limiter = instance.server_memory_limiter().clone();
Self {
opts,
+17 -1
View File
@@ -93,6 +93,12 @@ pub enum Error {
location: Location,
},
#[snafu(display("Object store WAL I/O permit is already installed"))]
WalIoPermitAlreadyInstalled {
#[snafu(implicit)]
location: Location,
},
#[snafu(display("Log store not started yet"))]
IllegalState {
#[snafu(implicit)]
@@ -482,6 +488,12 @@ pub enum Error {
location: Location,
},
#[snafu(display("Object store WAL node lease is unavailable or expired"))]
ObjectStoreWalLeaseExpired {
#[snafu(implicit)]
location: Location,
},
#[snafu(display("Object store WAL operation failed"))]
ObjectStoreWal {
source: Arc<Error>,
@@ -556,11 +568,14 @@ impl ErrorExt for Error {
| WalObjectConflict { .. }
| WalObjectSequenceExhausted { .. }
| WalEntryPositionExhausted { .. } => StatusCode::Unexpected,
WalObjectSequenceUnsettled { .. } => StatusCode::IllegalState,
WalObjectSequenceUnsettled { .. } | WalIoPermitAlreadyInstalled { .. } => {
StatusCode::IllegalState
}
InvalidWalObject { source, .. } => source.status_code(),
ObjectStoreWal { source, .. } => source.status_code(),
ObjectStoreWalFailing { .. } => StatusCode::StorageUnavailable,
ObjectStoreWalLeaseExpired { .. } => StatusCode::RegionNotReady,
// Object store related errors
WalObjectStore { .. }
@@ -602,6 +617,7 @@ impl ErrorExt for Error {
| StaleWalObject { .. }
| UnconfirmedWalEpochStart { .. }
| ObjectStoreWalFailing { .. } => RetryHint::Retryable,
ObjectStoreWalLeaseExpired { .. } => RetryHint::RetryAfterRouteRefresh,
ProduceRecord { error, .. } => match error {
rskafka::client::producer::Error::Client(error) => {
rskafka_client_error_to_retry_hint(error)
+9
View File
@@ -299,6 +299,15 @@ lazy_static! {
)
.unwrap();
/// Number of live object store logstores observed without permission to
/// initiate I/O, including before the first grant and while idle. This
/// measures permission availability, not retained backlog size.
pub static ref METRIC_OBJECT_STORE_WAL_IO_PERMISSION_UNAVAILABLE: IntGauge = register_int_gauge!(
"greptime_logstore_object_store_wal_io_permission_unavailable",
"live object store logstores observed without permission to initiate I/O, including idle stores and those awaiting their first grant",
)
.unwrap();
/// Number of object store logstores in the `enqueued` mode whose backlog
/// the object store refuses with an error that repeating the create
/// cannot settle, such as denied access or a missing bucket. Such a store
+16 -1
View File
@@ -47,6 +47,21 @@
//! accepts writes, and its epoch is one above the sequence of that object, so
//! no two instances share an epoch and a late object of an earlier instance
//! never ends the chain.
//! Opening rejects a selected chain below the maximum listed epoch before
//! writing its start object. `accept_missing_history` permits an explicit
//! recovery with possible acknowledged data loss; remote readers never accept
//! this fallback.
//!
//! With the cluster acceptance plugin registered, the datanode installs a
//! node-lease I/O permit before opening regions. OSS registers no such plugin.
//! New creates and deletes check the permit immediately before issuance;
//! already issued operations may finish. Expiry fails unacknowledged durable
//! batches and pauses the acknowledged enqueued backlog until renewal. Stop
//! drops that backlog if the lease expires and still waits for issued deletes.
//! The next flush timer tick detects expiry, including during stop; detection
//! can take one configured flush interval plus actor scheduling delay.
//! Standalone stores do not install a permit. Startup's initial create and its
//! withdrawal on missing history are exempt, so startup needs no heartbeat.
//!
//! The reclaim boundary of an object states that every object with a lower
//! sequence was fully flushed when the object was sealed, so the chain need
@@ -79,7 +94,7 @@
//! per source prefix. Listing an upper bound reads no object indexes; preparing
//! a range refreshes the listing and reuses cached indexes. Known last-entry
//! bounds anchor their own chains, while listed bounds use the complete-chain
//! selection of startup recovery with an additional maximum-epoch check.
//! selection of startup recovery, requiring the maximum listed epoch.
//! Neither path opens a writable store or modifies the source. The caller owns
//! the lifetime of pending recovery ranges and
//! publishes progress only after a successful read.
+675 -16
View File
@@ -19,7 +19,7 @@ use std::fmt;
#[cfg(any(test, feature = "testing"))]
use std::ops::Range;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex, PoisonError, RwLock};
use std::sync::{Arc, Mutex, OnceLock, PoisonError, RwLock};
use std::time::{Duration, Instant};
use async_stream::try_stream;
@@ -33,7 +33,9 @@ use object_store::{ErrorKind, ObjectStore};
use snafu::{IntoError, OptionExt, ResultExt, ensure};
use store_api::logstore::entry::{Entry, NaiveEntry};
use store_api::logstore::provider::{ObjectStoreProvider, Provider};
use store_api::logstore::{AppendBatchResponse, EntryId, LogStore, SendableEntryStream};
use store_api::logstore::{
AppendBatchResponse, EntryId, LogStore, ObjectStoreWalIoPermit, SendableEntryStream,
};
use store_api::storage::RegionId;
use tokio::sync::{Semaphore, mpsc, oneshot, watch};
use tokio::time::MissedTickBehavior;
@@ -42,8 +44,8 @@ use crate::error::{
CorruptedWalObjectSnafu, Error, IncompleteWalEntrySnafu, InvalidProviderSnafu,
InvalidWalObjectSnafu, InvalidWalObjectStoreSnafu, MismatchedWalPrefixSnafu,
MismatchedWalRegionSnafu, MissingWalHistorySnafu, ObjectStoreWalFailingSnafu,
ObjectStoreWalSnafu, ObjectStoreWalStoppedSnafu, Result, StaleWalObjectSnafu,
UnconfirmedWalEpochStartSnafu, WalObjectSequenceExhaustedSnafu,
ObjectStoreWalLeaseExpiredSnafu, ObjectStoreWalSnafu, ObjectStoreWalStoppedSnafu, Result,
StaleWalObjectSnafu, UnconfirmedWalEpochStartSnafu, WalObjectSequenceExhaustedSnafu,
WalObjectSequenceUnsettledSnafu, WalStartWithdrawnSnafu,
};
use crate::metrics::{
@@ -51,7 +53,7 @@ use crate::metrics::{
METRIC_OBJECT_STORE_WAL_CREATE_FAILURES_TOTAL, METRIC_OBJECT_STORE_WAL_CREATED_OBJECTS_TOTAL,
METRIC_OBJECT_STORE_WAL_DELETED_OBJECTS_TOTAL, METRIC_OBJECT_STORE_WAL_FAILED_DELETES_TOTAL,
METRIC_OBJECT_STORE_WAL_FAILING, METRIC_OBJECT_STORE_WAL_INDEXED_BYTES,
METRIC_OBJECT_STORE_WAL_INDEXED_OBJECTS,
METRIC_OBJECT_STORE_WAL_INDEXED_OBJECTS, METRIC_OBJECT_STORE_WAL_IO_PERMISSION_UNAVAILABLE,
METRIC_OBJECT_STORE_WAL_MISSING_HISTORY_ACCEPTED_TOTAL, METRIC_OBJECT_STORE_WAL_OBJECT_BYTES,
METRIC_OBJECT_STORE_WAL_OBJECT_ENTRIES, METRIC_OBJECT_STORE_WAL_POISONED_TOTAL,
METRIC_OBJECT_STORE_WAL_READ_SECONDS, METRIC_OBJECT_STORE_WAL_RECOVERED_OBJECTS_TOTAL,
@@ -155,6 +157,9 @@ pub struct ObjectStoreLogStore {
read_prefetch_budget: Arc<Semaphore>,
terminal_error: TerminalError,
stopped: Arc<AtomicBool>,
/// Permission for new object-store creates and deletes. It is absent for
/// standalone stores and installed by a metasrv-controlled datanode.
io_permit: IoPermitSlot,
command_tx: mpsc::Sender<Command>,
append_tx: mpsc::Sender<QueuedAppend>,
#[cfg(any(test, feature = "testing"))]
@@ -180,6 +185,7 @@ type ObsoleteEntryIds = Arc<Mutex<HashMap<RegionId, EntryId>>>;
type StartedRegions = Arc<Mutex<HashSet<RegionId>>>;
type WalHoles = Arc<Mutex<HashMap<RegionId, BTreeMap<u64, WalHole>>>>;
type IoPermitSlot = Arc<OnceLock<Arc<dyn ObjectStoreWalIoPermit>>>;
/// A segment a read skipped because it did not decode: the entries of one
/// region in one object are missing from every read of that region.
@@ -330,7 +336,32 @@ impl ObjectStoreLogStore {
unindexed,
released_entry_ids,
recovered_objects,
skipped_epochs,
} = recover(io.as_ref()).await?;
if let Some(tip) = tip
&& tip.epoch < max_epoch
{
let skipped = skipped_epochs
.iter()
.map(|(epoch, objects)| {
format!(
"epoch {epoch}: {} objects, sequences {}..={}",
objects.objects, objects.first_object_seq, objects.last_object_seq
)
})
.collect::<Vec<_>>()
.join("; ");
let reason = format!(
"WAL chain in {prefix} would fall back from epoch {max_epoch} to {}; skipped objects after the selected tip: {skipped}. Recover the missing objects, or set accept_missing_history only after all previous writers have exited and acknowledged unflushed data loss is accepted",
tip.epoch,
);
if !config.accept_missing_history {
return CorruptedWalObjectSnafu { reason }.fail();
}
warn!(
"{reason}; accepting the fallback because accept_missing_history is enabled; acknowledged unflushed data may be lost"
);
}
// Every epoch is one above the sequence of the start object its
// instance created, and every object is at or above its start object,
// so an epoch above the next sequence names no instance that ran.
@@ -389,6 +420,7 @@ impl ObjectStoreLogStore {
let deleting = Arc::new(DeletingObjects::default());
let terminal_error = TerminalError::default();
let stopped = Arc::new(AtomicBool::new(false));
let io_permit = Arc::new(OnceLock::new());
let (command_tx, command_rx) = mpsc::channel(COMMAND_BUFFER);
let (append_tx, append_rx) = mpsc::channel(APPEND_BUFFER);
#[cfg(any(test, feature = "testing"))]
@@ -414,6 +446,9 @@ impl ObjectStoreLogStore {
wal_holes: wal_holes.clone(),
terminal_error: terminal_error.clone(),
stopped: stopped.clone(),
io_permit: io_permit.clone(),
io_blocked: false,
io_permission_unavailable: false,
command_rx,
append_rx,
ack_mode: config.ack_mode,
@@ -486,6 +521,7 @@ impl ObjectStoreLogStore {
read_prefetch_budget: Arc::new(Semaphore::new(READ_PREFETCH_BYTES)),
terminal_error,
stopped,
io_permit,
command_tx,
append_tx,
#[cfg(any(test, feature = "testing"))]
@@ -518,6 +554,18 @@ impl ObjectStoreLogStore {
catalog.region_max_entry_id(region_id).unwrap_or(0)
}
/// Fences new object-store creates and deletes with `permit`.
///
/// The current in-flight operation is not revoked. Supplying a permit is
/// a cluster integration concern; standalone stores keep the default
/// unrestricted behavior.
/// Installation is allowed once; renewals update the installed permit itself.
pub fn set_io_permit(&self, permit: Arc<dyn ObjectStoreWalIoPermit>) -> Result<()> {
self.io_permit
.set(permit)
.map_err(|_| crate::error::WalIoPermitAlreadyInstalledSnafu.build())
}
/// Returns the segments of the provider's region that reads of this store
/// skipped because they did not decode, ordered by object sequence. Holes
/// are kept in memory only: a store opened later on the same prefix
@@ -731,6 +779,7 @@ impl ObjectStoreLogStore {
/// Seals the open batch regardless of its size and age and returns once
/// its object is durable and indexed, or with the error that failed it.
/// An empty batch does not wait for previously sealed objects.
pub async fn seal_open_batch(&self) -> Result<()> {
ensure!(
!self.stopped.load(Ordering::Acquire),
@@ -879,9 +928,13 @@ impl LogStore for ObjectStoreLogStore {
.flush_candidates(FLUSH_OBJECT_THRESHOLD)
}
/// Stops the store. Creates in flight run to completion and acknowledge
/// their entries if they succeed; in the `enqueued` mode the remaining
/// Stops the store. While the I/O permit remains valid, creates in flight
/// run to completion and acknowledge their entries if they succeed; in
/// the `enqueued` mode the remaining
/// backlog is uploaded first, and a failure of that upload is returned.
/// If permission expires, unindexed batches are dropped without waiting
/// for uploads; discarded enqueued data or release records report an error.
/// Issued deletes are still awaited.
async fn stop(&self) -> Result<()> {
self.stopped.store(true, Ordering::Release);
let (response_tx, response_rx) = oneshot::channel();
@@ -1494,7 +1547,9 @@ impl Failing {
/// nothing is admitted and no create starts, except that the `enqueued` mode
/// uploads its backlog and the `durable` mode creates one object with the
/// pending bounded releases and release records of failed batches. Creates in
/// flight run to completion and acknowledge if they succeed.
/// flight run to completion and acknowledge if they succeed, while the I/O
/// permit remains valid. On expiry during stop, unindexed batches are dropped
/// without waiting for uploads; issued deletes are still awaited.
///
/// Appends arrive on their own channel. The actor holds one back while the
/// sealed batches leave no room for the two an admission can seal, or at a
@@ -1522,6 +1577,11 @@ struct Actor {
wal_holes: WalHoles,
terminal_error: TerminalError,
stopped: Arc<AtomicBool>,
io_permit: IoPermitSlot,
/// Work that must be retried on a timer tick after permission returns.
io_blocked: bool,
/// Whether this actor is counted as lacking I/O permission, even when idle.
io_permission_unavailable: bool,
command_rx: mpsc::Receiver<Command>,
append_rx: mpsc::Receiver<QueuedAppend>,
ack_mode: AckMode,
@@ -1607,10 +1667,20 @@ impl Actor {
let probe_at = self.failing.as_ref().and_then(|failing| failing.retry.at);
tokio::select! {
_ = interval.tick() => {
// Nothing starts after stop began; the `enqueued` mode
// sealed its backlog when stop was requested.
if !self.is_stopped() {
self.flush_open_batch();
if !self.io_allowed() {
self.expire_io_permission();
} else {
if std::mem::take(&mut self.io_permission_unavailable) {
METRIC_OBJECT_STORE_WAL_IO_PERMISSION_UNAVAILABLE.dec();
info!("Object store WAL I/O permission available; {} sealed batches retained", self.sealed.len());
}
if !self.is_stopped() {
self.flush_open_batch();
}
if std::mem::take(&mut self.io_blocked) {
self.start_creates();
self.start_deletes();
}
}
}
Some((object_seq, result)) = self.creates.next(), if !self.creates.is_empty() => {
@@ -1684,6 +1754,10 @@ impl Actor {
return;
}
if self.should_hold_back() {
if !self.io_allowed() {
let _ = response.send(Err(ObjectStoreWalLeaseExpiredSnafu.build()));
return;
}
METRIC_OBJECT_STORE_WAL_STALLED_APPENDS_TOTAL.inc();
self.stalled = Some(((entries, response), Instant::now()));
self.ensure_create_in_flight();
@@ -1822,7 +1896,8 @@ impl Actor {
/// Seals the open batch together with `releases` and pending release
/// records as the object `next_object_seq`, even when the open
/// batch holds no entry, and starts its create when a slot is free.
/// Returns whether a batch was sealed.
/// Returns whether a batch was sealed. An invalid I/O permit keeps
/// release records pending and applies the lease-expiry policy to entries.
///
/// A failing store or one at a backlog threshold keeps pending releases
/// coalesced instead of sealing them alone on every tick. Stop seals them
@@ -1832,6 +1907,13 @@ impl Actor {
/// Ordinary entries bypass this delay; indexing a batch carrying releases
/// resets it.
fn seal(&mut self, releases: Vec<Release>) -> bool {
if !self.io_allowed() {
for release in releases {
self.keep_release(release);
}
self.expire_io_permission();
return false;
}
if self.open_batch.is_empty()
&& releases.is_empty()
&& (self.pending_releases.is_empty()
@@ -1934,6 +2016,10 @@ impl Actor {
/// next attempt once nothing is in flight, see [`Failing`]; after stop
/// began it uploads its backlog at once.
fn start_creates(&mut self) {
if !self.io_allowed() {
self.io_blocked = true;
return;
}
if self.is_stopped() && self.ack_mode == AckMode::Durable && self.stop.is_empty() {
return;
}
@@ -1974,6 +2060,10 @@ impl Actor {
if self.is_stopped() {
return;
}
if !self.io_allowed() {
self.io_blocked = true;
return;
}
if let Some(index) = self
.sealed
.iter()
@@ -1995,6 +2085,7 @@ impl Actor {
self.creating.insert(object_seq);
let epoch = self.epoch;
let ack_mode = self.ack_mode;
let io_permit = self.io_permit.clone();
#[cfg(any(test, feature = "testing"))]
let mut creates_held = self.creates_held.clone();
#[cfg(any(test, feature = "testing"))]
@@ -2023,6 +2114,9 @@ impl Actor {
record_create(&result, Some(sealed_at));
return (object_seq, result);
}
if !io_allowed(&io_permit) {
return (object_seq, Err(ObjectStoreWalLeaseExpiredSnafu.build()));
}
let created = io.put_if_absent(object_seq, bytes).await;
#[cfg(any(test, feature = "testing"))]
let created = match created {
@@ -2048,6 +2142,9 @@ impl Actor {
fn on_create_completed(&mut self, object_seq: u64, result: Result<PutResult>) {
self.creating.remove(&object_seq);
if !self.io_allowed() {
self.expire_io_permission();
}
// A batch that already failed, or that the store gave up on when it
// poisoned itself: the object may exist, but it is off the chain, and
// collection may delete it now.
@@ -2061,6 +2158,13 @@ impl Actor {
return;
};
match result {
Err(Error::ObjectStoreWalLeaseExpired { .. }) => {
// No request was issued, so this is not a storage retry.
self.sealed[index].attempts -= 1;
self.sealed[index].state = CreateState::Pending;
self.io_blocked = true;
return;
}
Ok(_) => {
self.sealed[index].state = CreateState::Created;
self.leave_failing("a create succeeded");
@@ -2274,6 +2378,7 @@ impl Actor {
/// the next release-only seal. Failures are logged at a limited rate.
fn roll_back(&mut self, error: Arc<Error>) {
let stopped = self.is_stopped();
let backlog_dropped = !self.open_batch.is_empty() || !self.sealed.is_empty();
let failure = || {
if stopped {
ObjectStoreWalStoppedSnafu.build()
@@ -2286,7 +2391,13 @@ impl Actor {
self.keep_releases(&mut batch);
batch.fail(failure);
}
if self.ack_mode == AckMode::Durable && !stopped && !self.pending_releases.is_empty() {
// Lease checks can repeat without attempting storage I/O. They must not
// extend the retry delay of retained releases on every expired tick.
if self.ack_mode == AckMode::Durable
&& !stopped
&& !self.pending_releases.is_empty()
&& !matches!(error.as_ref(), Error::ObjectStoreWalLeaseExpired { .. })
{
let now = Instant::now();
if self
.release_retry_logged_at
@@ -2309,9 +2420,12 @@ impl Actor {
// An acknowledged backlog was dropped: `stop` reports it, whether
// its caller has arrived yet or not. So it does release records once
// stop began, which no later create carries.
if self.ack_mode == AckMode::Enqueued
if (self.ack_mode == AckMode::Enqueued && backlog_dropped)
|| (!self.stop.is_empty() && !self.pending_releases.is_empty())
{
if stopped && self.stop_error.is_none() {
warn!(error; "Object store WAL discarded unpersisted backlog during stop");
}
self.stop_error.get_or_insert(error);
}
self.leave_failing("its backlog was dropped");
@@ -2616,9 +2730,11 @@ impl Actor {
batch.release_waiters.push(response);
return;
}
// Sealing failed and poisoned the store.
// Sealing either poisoned the store or was held back by its lease.
if let Some(error) = terminal(&self.terminal_error) {
let _ = response.send(Err(shared(&error)));
} else {
let _ = response.send(Err(ObjectStoreWalLeaseExpiredSnafu.build()));
}
}
@@ -2647,6 +2763,10 @@ impl Actor {
if self.is_stopped() || terminal(&self.terminal_error).is_some() {
return;
}
if !self.io_allowed() {
self.io_blocked = true;
return;
}
let free = MAX_IN_FLIGHT_DELETES.saturating_sub(self.deletes.len());
let boundary = self.durable_reclaim_boundary;
let candidates = {
@@ -2667,7 +2787,13 @@ impl Actor {
for object_seq in candidates {
self.deleting.start(object_seq);
let io = self.io.clone();
let permit = self.io_permit.clone();
// Pushing does not poll the future; the lease may expire before
// the actor first polls it, even without an await inside the body.
self.deletes.push(Box::pin(async move {
if !io_allowed(&permit) {
return (object_seq, Err(ObjectStoreWalLeaseExpiredSnafu.build()));
}
(object_seq, io.delete(object_seq).await)
}));
}
@@ -2727,6 +2853,7 @@ impl Actor {
}
METRIC_OBJECT_STORE_WAL_DELETED_OBJECTS_TOTAL.inc();
}
Err(Error::ObjectStoreWalLeaseExpired { .. }) => self.io_blocked = true,
Err(error) => {
warn!(
error;
@@ -2801,6 +2928,10 @@ impl Actor {
/// [`finish_stop`](Self::finish_stop) once nothing is in flight.
fn handle_stop(&mut self, response: oneshot::Sender<Result<()>>) {
self.stop.push(response);
if !self.io_allowed() {
self.expire_io_permission();
return;
}
if let Some((_, response)) = self.take_stalled() {
let _ = response.send(Err(ObjectStoreWalStoppedSnafu.build()));
}
@@ -2860,6 +2991,11 @@ impl Actor {
let _ = response.send(Err(ObjectStoreWalStoppedSnafu.build()));
return;
}
if !self.io_allowed() {
self.expire_io_permission();
let _ = response.send(Err(ObjectStoreWalLeaseExpiredSnafu.build()));
return;
}
if self.flush_open_batch()
&& let Some(batch) = self.sealed.back_mut()
{
@@ -2888,6 +3024,59 @@ impl Actor {
fn is_stopped(&self) -> bool {
self.stopped.load(Ordering::Acquire)
}
/// Releases waiters while preserving the acknowledged enqueued backlog,
/// unless stop began: then the backlog is dropped and `stop_error` reports it.
/// Durable batches abandoned here must never be indexed by late completions.
fn expire_io_permission(&mut self) {
if !std::mem::replace(&mut self.io_permission_unavailable, true) {
METRIC_OBJECT_STORE_WAL_IO_PERMISSION_UNAVAILABLE.inc();
info!(
"Object store WAL I/O permission unavailable; {} sealed batches, open batch empty: {}, {} pending releases",
self.sealed.len(),
self.open_batch.is_empty(),
self.pending_releases.len()
);
}
self.io_blocked = true;
let stopped = self.is_stopped();
if stopped || self.ack_mode == AckMode::Durable {
if !self.open_batch.is_empty() {
self.next_object_seq = self
.next_object_seq
.and_then(|seq| seq.checked_add(1))
.filter(|seq| *seq < OBJECT_SEQ_LIMIT);
}
self.roll_back(Arc::new(ObjectStoreWalLeaseExpiredSnafu.build()));
} else {
for batch in &mut self.sealed {
for waiter in batch.release_waiters.drain(..) {
let _ = waiter.send(Err(ObjectStoreWalLeaseExpiredSnafu.build()));
}
}
}
self.fail_unacknowledged(|| {
if stopped {
ObjectStoreWalStoppedSnafu.build()
} else {
ObjectStoreWalLeaseExpiredSnafu.build()
}
});
if stopped {
self.creates.clear();
self.creating.clear();
}
}
fn io_allowed(&self) -> bool {
io_allowed(&self.io_permit)
}
}
fn io_allowed(permit: &IoPermitSlot) -> bool {
permit
.get()
.is_none_or(|permit| permit.allows_object_store_io())
}
impl Drop for Actor {
@@ -2898,6 +3087,9 @@ impl Drop for Actor {
self.deleting.abandon_all();
self.take_stalled();
self.leave_failing("its actor exited");
if self.io_permission_unavailable {
METRIC_OBJECT_STORE_WAL_IO_PERMISSION_UNAVAILABLE.dec();
}
#[cfg(test)]
LIVE_ACTORS.fetch_sub(1, Ordering::SeqCst);
}
@@ -3107,6 +3299,17 @@ struct Recovered {
released_entry_ids: HashMap<RegionId, EntryId>,
/// Number of objects whose header and footer were read.
recovered_objects: u64,
/// Objects after the selected tip in (epoch, object sequence) order,
/// grouped by epoch, including incomplete branches in the selected epoch.
skipped_epochs: BTreeMap<u64, SkippedEpoch>,
}
/// Listed objects in one epoch after the selected recovery tip.
#[derive(Debug)]
struct SkippedEpoch {
first_object_seq: u64,
last_object_seq: u64,
objects: usize,
}
/// Rebuilds the catalog from object headers and footers,
@@ -3227,6 +3430,20 @@ fn finish_recovery(fetched: FetchedObjects) -> Result<Recovered> {
.map(|header| header.epoch)
.max()
.unwrap_or(0);
let mut skipped_epochs = BTreeMap::<u64, SkippedEpoch>::new();
if let Some(tip) = tip {
for (&seq, header) in &headers {
if header.epoch > tip.epoch || (header.epoch == tip.epoch && seq > tip.object_seq) {
let skipped = skipped_epochs.entry(header.epoch).or_insert(SkippedEpoch {
first_object_seq: seq,
last_object_seq: seq,
objects: 0,
});
skipped.last_object_seq = seq;
skipped.objects += 1;
}
}
}
let last_listed = headers
.keys()
.copied()
@@ -3271,6 +3488,7 @@ fn finish_recovery(fetched: FetchedObjects) -> Result<Recovered> {
unindexed,
released_entry_ids: HashMap::new(),
recovered_objects,
skipped_epochs,
})
}
@@ -3455,6 +3673,368 @@ mod tests {
config(Duration::from_secs(3600), u64::MAX)
}
#[derive(Default)]
struct TestIoPermit(AtomicBool);
impl ObjectStoreWalIoPermit for TestIoPermit {
fn allows_object_store_io(&self) -> bool {
self.0.load(Ordering::Acquire)
}
}
#[tokio::test]
async fn test_node_lease_permission_metric_lifecycle() {
let _serialized = SERIALIZED.lock().await;
wait_until(|| LIVE_ACTORS.load(Ordering::SeqCst) == 0).await;
let unavailable = || METRIC_OBJECT_STORE_WAL_IO_PERMISSION_UNAVAILABLE.get();
assert_eq!(0, unavailable());
let config = config(MIN_FLUSH_INTERVAL, u64::MAX);
for config in [config.clone(), enqueued(config)] {
for stop in [false, true] {
let store = open(memory_store(), &config).await;
assert_eq!(0, unavailable());
// The first heartbeat has not granted permission yet. This
// counts an idle store too, without calling the lease expired.
let permit = Arc::new(TestIoPermit::default());
store.set_io_permit(permit.clone()).unwrap();
wait_until(|| unavailable() == 1).await;
for _ in 0..3 {
assert!(store.seal_open_batch().await.is_err());
assert_eq!(1, unavailable());
}
permit.0.store(true, Ordering::Release);
wait_until(|| unavailable() == 0).await;
// Expiry after a renewal has the same permission contract.
permit.0.store(false, Ordering::Release);
wait_until(|| unavailable() == 1).await;
if stop {
store.stop().await.unwrap();
}
drop(store);
wait_until(|| LIVE_ACTORS.load(Ordering::SeqCst) == 0).await;
assert_eq!(0, unavailable());
}
}
}
#[tokio::test]
async fn test_node_lease_retains_enqueued_entries_until_renewed() {
let _serialized = SERIALIZED.lock().await;
let store = open(memory_store(), &enqueued(manual())).await;
let permit = Arc::new(TestIoPermit::default());
store.set_io_permit(permit.clone()).unwrap();
let admitted = append(&store, region(1), "retained").await.unwrap();
assert_eq!(id(1, 1), admitted.last_entry_ids[&region(1)]);
assert!(matches!(
store.seal_open_batch().await,
Err(Error::ObjectStoreWalLeaseExpired { .. })
));
assert_eq!(vec![0], object_seqs(store.io.as_ref()).await);
assert_eq!(0, latest(&store, region(1)));
permit.0.store(true, Ordering::Release);
store.seal_open_batch().await.unwrap();
assert_eq!(id(1, 1), latest(&store, region(1)));
assert_eq!(
expected_entries(region(1), &[(id(1, 1), "retained")]),
read_entries(&store, region(1), 0).await
);
store.stop().await.unwrap();
}
#[tokio::test]
async fn test_node_lease_rejects_durable_batch_without_reusing_ids() {
let _serialized = SERIALIZED.lock().await;
let store = open(memory_store(), &manual()).await;
let permit = Arc::new(TestIoPermit::default());
store.set_io_permit(permit.clone()).unwrap();
let first = spawn_append_batch(&store, vec![entry(&store, region(1), "expired")]);
store.wait_for_admitted_appends(1).await.unwrap();
assert!(store.seal_open_batch().await.is_err());
let error = timeout(WAIT, first).await.unwrap().unwrap().unwrap_err();
assert_eq!(RetryHint::RetryAfterRouteRefresh, error.retry_hint());
assert_eq!(vec![0], object_seqs(store.io.as_ref()).await);
permit.0.store(true, Ordering::Release);
let next = spawn_append_batch(&store, vec![entry(&store, region(1), "new")]);
store.wait_for_admitted_appends(2).await.unwrap();
store.seal_open_batch().await.unwrap();
assert_eq!(
id(2, 1),
next.await.unwrap().unwrap().last_entry_ids[&region(1)]
);
store.stop().await.unwrap();
}
#[tokio::test]
async fn test_node_lease_empty_stop_and_single_permit_installation() {
let _serialized = SERIALIZED.lock().await;
for config in [manual(), enqueued(manual())] {
let store = open(memory_store(), &config).await;
store
.set_io_permit(Arc::new(TestIoPermit::default()))
.unwrap();
let error = store
.set_io_permit(Arc::new(TestIoPermit(AtomicBool::new(true))))
.unwrap_err();
assert!(matches!(error, Error::WalIoPermitAlreadyInstalled { .. }));
let error = store.seal_open_batch().await.unwrap_err();
assert_eq!(StatusCode::RegionNotReady, error.status_code());
assert_eq!(RetryHint::RetryAfterRouteRefresh, error.retry_hint());
store.stop().await.unwrap();
}
}
#[tokio::test]
async fn test_node_lease_denied_create_preserves_attempt_count() {
let _serialized = SERIALIZED.lock().await;
for previous_attempts in [0, 2] {
let store = open(memory_store(), &enqueued(eager())).await;
let permit = Arc::new(TestIoPermit(AtomicBool::new(true)));
store.set_io_permit(permit.clone()).unwrap();
store.hold_creates();
append(&store, region(1), "queued").await.unwrap();
timeout(WAIT, store.wait_for_parked_creates(1))
.await
.unwrap()
.unwrap();
inspect_actor(&store, move |actor| {
// Model earlier issued attempts, then the current queued attempt.
actor.sealed[0].attempts = previous_attempts + 1;
})
.await;
permit.0.store(false, Ordering::Release);
store.release_creates();
timeout(WAIT, async {
loop {
let pending = inspect_actor(&store, move |actor| {
let batch = &actor.sealed[0];
if matches!(batch.state, CreateState::Pending) {
assert_eq!(previous_attempts, batch.attempts);
true
} else {
false
}
})
.await;
if pending {
break;
}
tokio::task::yield_now().await;
}
})
.await
.unwrap();
assert_eq!(vec![0], object_seqs(store.io.as_ref()).await);
permit.0.store(true, Ordering::Release);
inspect_actor(&store, |actor| actor.start_creates()).await;
store
.wait_durable(&provider(region(1)), id(1, 1))
.await
.unwrap();
store.stop().await.unwrap();
}
}
#[tokio::test]
async fn test_node_lease_rechecks_before_polling_delete() {
let _serialized = SERIALIZED.lock().await;
let store = open(memory_store(), &enqueued(manual())).await;
let permit = Arc::new(TestIoPermit(AtomicBool::new(true)));
store.set_io_permit(permit.clone()).unwrap();
let pending_permit = permit.clone();
inspect_actor(&store, move |actor| {
// Queue collection of the empty start object, then expire the
// permit before returning control to the actor's select loop.
actor.durable_reclaim_boundary = 1;
actor.start_deletes();
assert_eq!(1, actor.deletes.len());
pending_permit.0.store(false, Ordering::Release);
})
.await;
timeout(WAIT, async {
while !inspect_actor(&store, |actor| actor.deletes.is_empty()).await {
tokio::task::yield_now().await;
}
})
.await
.unwrap();
assert_eq!(vec![0], object_seqs(store.io.as_ref()).await);
inspect_actor(&store, |actor| {
assert!(actor.io_blocked);
actor.durable_reclaim_boundary = 0;
})
.await;
permit.0.store(true, Ordering::Release);
store.stop().await.unwrap();
}
#[tokio::test]
async fn test_node_lease_stopped_probe_does_not_mark_io_blocked() {
let _serialized = SERIALIZED.lock().await;
let store = open(memory_store(), &enqueued(manual())).await;
inspect_actor(&store, |actor| {
actor.enter_failing(ObjectStoreWalStoppedSnafu.build());
actor.stopped.store(true, Ordering::Release);
actor.probe();
assert!(!actor.io_blocked);
actor.stopped.store(false, Ordering::Release);
actor.leave_failing("test finished");
})
.await;
store.stop().await.unwrap();
}
#[tokio::test]
async fn test_node_lease_stop_drops_unpersisted_backlog() {
let _serialized = SERIALIZED.lock().await;
let object_store = memory_store();
let store = open(object_store.clone(), &enqueued(manual())).await;
append(&store, region(1), "queued").await.unwrap();
store
.set_io_permit(Arc::new(TestIoPermit::default()))
.unwrap();
assert!(timeout(WAIT, store.stop()).await.unwrap().is_err());
assert_eq!(vec![0], object_seqs(store.io.as_ref()).await);
let reopened = open(object_store, &eager()).await;
assert!(read_entries(&reopened, region(1), 0).await.is_empty());
reopened.stop().await.unwrap();
}
#[tokio::test]
async fn test_node_lease_keeps_release_for_renewal() {
let _serialized = SERIALIZED.lock().await;
let store = open(memory_store(), &manual()).await;
let permit = Arc::new(TestIoPermit::default());
store.set_io_permit(permit.clone()).unwrap();
let error = store
.release_region(&provider(region(1)), region(1))
.await
.unwrap_err();
assert!(matches!(error, Error::ObjectStoreWalLeaseExpired { .. }));
// Repeated expiry checks must not accumulate storage retry backoff:
// renewal can seal the retained record immediately.
for _ in 0..8 {
assert!(matches!(
store.seal_open_batch().await,
Err(Error::ObjectStoreWalLeaseExpired { .. })
));
}
assert_eq!(vec![0], object_seqs(store.io.as_ref()).await);
permit.0.store(true, Ordering::Release);
store.seal_open_batch().await.unwrap();
assert_eq!(
vec![release(region(1), 0)],
releases_of(store.io.as_ref(), 1).await
);
store.stop().await.unwrap();
}
#[tokio::test]
async fn test_node_lease_discards_late_durable_upload() {
let _serialized = SERIALIZED.lock().await;
let (store, io, mut parked) = open_parking_creates(memory_store(), &eager()).await;
let permit = Arc::new(TestIoPermit(AtomicBool::new(true)));
store.set_io_permit(permit.clone()).unwrap();
let first = spawn_append_batch(&store, vec![entry(&store, region(1), "late")]);
let (seq, release) = next_parked_operation(&mut parked).await;
assert_eq!(1, seq);
permit.0.store(false, Ordering::Release);
assert!(store.seal_open_batch().await.is_err());
assert!(
first
.await
.unwrap()
.unwrap_err()
.retry_hint()
.is_retryable()
);
// The issued create is allowed to finish, even after renewal. Its batch
// was already failed and must not become part of the live chain.
permit.0.store(true, Ordering::Release);
release.send(true).unwrap();
io.creates_parked.store(false, Ordering::SeqCst);
let next = append(&store, region(1), "current").await.unwrap();
assert_eq!(id(2, 1), next.last_entry_ids[&region(1)]);
assert_eq!(
expected_entries(region(1), &[(id(2, 1), "current")]),
read_entries(&store, region(1), 0).await
);
store.stop().await.unwrap();
}
#[tokio::test]
async fn test_node_lease_rejects_backpressure_without_waiting() {
let _serialized = SERIALIZED.lock().await;
let config = ObjectStoreWalConfig {
max_unpersisted_bytes: ReadableSize(1),
..enqueued(manual())
};
let store = open(memory_store(), &config).await;
store
.set_io_permit(Arc::new(TestIoPermit::default()))
.unwrap();
append(&store, region(1), "queued").await.unwrap();
let error = timeout(WAIT, append(&store, region(1), "blocked"))
.await
.unwrap()
.unwrap_err();
assert!(matches!(error, Error::ObjectStoreWalLeaseExpired { .. }));
assert_eq!(vec![0], object_seqs(store.io.as_ref()).await);
assert!(store.stop().await.is_err());
}
#[tokio::test]
async fn test_node_lease_expires_during_stop_without_waiting_for_upload() {
let _serialized = SERIALIZED.lock().await;
let config = enqueued(config(MIN_FLUSH_INTERVAL, 1));
let (store, _, mut parked) = open_parking_creates(memory_store(), &config).await;
let permit = Arc::new(TestIoPermit(AtomicBool::new(true)));
store.set_io_permit(permit.clone()).unwrap();
append(&store, region(1), "queued").await.unwrap();
let (_, release) = next_parked_operation(&mut parked).await;
let stop = {
let store = store.clone();
tokio::spawn(async move { store.stop().await })
};
wait_until(|| store.stopped.load(Ordering::Acquire)).await;
permit.0.store(false, Ordering::Release);
assert!(timeout(WAIT, stop).await.unwrap().unwrap().is_err());
assert!(release.is_closed());
}
#[tokio::test]
async fn test_node_lease_defers_collection_and_stop_waits_for_issued_delete() {
let _serialized = SERIALIZED.lock().await;
let config = enqueued(config(MIN_FLUSH_INTERVAL, 1));
let (store, io, mut parked) = open_parking_creates(memory_store(), &config).await;
let permit = Arc::new(TestIoPermit(AtomicBool::new(true)));
store.set_io_permit(permit.clone()).unwrap();
io.deletes_parked.store(true, Ordering::SeqCst);
append(&store, region(1), "first").await.unwrap();
let (seq, release) = next_parked_operation(&mut parked).await;
assert_eq!(1, seq);
permit.0.store(false, Ordering::Release);
release.send(true).unwrap();
// An issued enqueued create may finish, but its advanced reclaim
// boundary must not issue a delete under the expired lease.
wait_until(|| latest(&store, region(1)) == id(1, 1)).await;
assert_nothing_parks(&mut parked).await;
assert_eq!(vec![0, 1], object_seqs(io.as_ref()).await);
permit.0.store(true, Ordering::Release);
let (seq, release) = next_parked_operation(&mut parked).await;
assert_eq!(0, seq);
permit.0.store(false, Ordering::Release);
let stop = {
let store = store.clone();
tokio::spawn(async move { store.stop().await })
};
wait_until(|| store.stopped.load(Ordering::Acquire)).await;
assert!(!stop.is_finished());
release.send(true).unwrap();
// All entries were indexed: expiry alone is not a shutdown failure.
timeout(WAIT, stop).await.unwrap().unwrap().unwrap();
assert_eq!(vec![1], object_seqs(io.as_ref()).await);
}
async fn open(
object_store: ObjectStore,
config: &ObjectStoreWalConfig,
@@ -5074,6 +5654,7 @@ mod tests {
read_prefetch_budget: Arc::new(Semaphore::new(READ_PREFETCH_BYTES)),
terminal_error: Arc::default(),
stopped: Arc::new(AtomicBool::new(false)),
io_permit: Arc::default(),
command_tx,
append_tx,
admitted_appends: watch::channel(0).1,
@@ -7404,6 +7985,84 @@ mod tests {
}
}
#[tokio::test]
async fn test_recovery_rejects_older_epoch_until_explicitly_accepted() {
let _serialized = SERIALIZED.lock().await;
let object_store = memory_store();
let io = ObjectStoreIo::new(object_store.clone(), PREFIX).unwrap();
put_object_with_header(&io, chain_header(0, 1, None), &[]).await;
// Both branches have missing predecessors; epoch 1 remains complete
// only through object 0.
put_object_with_header(&io, chain_header(2, 1, Some((1, 1))), &[]).await;
put_object_with_header(&io, chain_header(3, 3, Some((2, 3))), &[]).await;
let before = io.list().await.unwrap();
for _ in 0..2 {
let error = ObjectStoreLogStore::try_new(object_store.clone(), &eager(), 1, 2)
.await
.unwrap_err();
assert!(matches!(error, Error::CorruptedWalObject { reason, .. }
if reason.contains("fall back from epoch 3 to 1")
&& reason.contains("epoch 1: 1 objects, sequences 2..=2")
&& reason.contains("epoch 3: 1 objects, sequences 3..=3")));
assert_eq!(before, io.list().await.unwrap());
}
let accepted = ObjectStoreWalConfig {
accept_missing_history: true,
..eager()
};
let store = open(object_store.clone(), &accepted).await;
store.stop().await.unwrap();
let reopened = open(object_store, &eager()).await;
reopened.stop().await.unwrap();
}
#[tokio::test]
async fn test_recovery_accepts_incomplete_branch_in_selected_epoch() {
let _serialized = SERIALIZED.lock().await;
let object_store = memory_store();
let io = ObjectStoreIo::new(object_store.clone(), PREFIX).unwrap();
put_object_with_header(&io, chain_header(0, 1, None), &[]).await;
// A failed upload of object 1 can leave a later, incomplete branch
// without evidence that a newer writer's complete history was lost.
put_object_with_header(&io, chain_header(2, 1, Some((1, 1))), &[]).await;
let store = open(object_store, &eager()).await;
let header = decode_header(&io.get(3).await.unwrap()).unwrap();
assert_eq!(4, header.epoch);
assert_eq!(
Some(ChainLink {
object_seq: 0,
epoch: 1
}),
header.prev
);
store.stop().await.unwrap();
}
#[tokio::test]
async fn test_node_lease_rechecks_before_parked_upload() {
let _serialized = SERIALIZED.lock().await;
let store = open(memory_store(), &enqueued(config(MIN_FLUSH_INTERVAL, 1))).await;
let permit = Arc::new(TestIoPermit(AtomicBool::new(true)));
store.set_io_permit(permit.clone()).unwrap();
store.hold_creates();
append(&store, region(1), "queued").await.unwrap();
timeout(WAIT, store.wait_for_parked_creates(1))
.await
.unwrap()
.unwrap();
permit.0.store(false, Ordering::Release);
store.release_creates();
assert!(store.seal_open_batch().await.is_err());
assert_eq!(vec![0], object_seqs(store.io.as_ref()).await);
permit.0.store(true, Ordering::Release);
timeout(WAIT, store.wait_durable(&provider(region(1)), id(1, 1)))
.await
.unwrap()
.unwrap();
assert_eq!(id(1, 1), latest(&store, region(1)));
store.stop().await.unwrap();
}
fn chain_of(headers: &[Header]) -> Vec<u64> {
select_chain(
&headers
@@ -40,6 +40,11 @@ pub struct RegionLeaseHandler {
pub type CustomizedRegionLeaseRenewerRef = Arc<dyn CustomizedRegionLeaseRenewer>;
pub trait CustomizedRegionLeaseRenewer: Send + Sync {
/// Returns the leases to grant for the renewed `regions`.
///
/// The handler sets the `candidate_lease_id` of each returned lease from the entry of
/// `regions` with the same region id, or to `None` if there is no such entry. The value set
/// by the renewer is ignored.
fn renew(
&self,
ctx: &mut Context,
@@ -94,17 +99,31 @@ impl HeartbeatHandler for RegionLeaseHandler {
renewed,
}) => {
let renewed = if let Some(renewer) = &self.customized_region_lease_renewer {
let candidate_lease_ids = renewed
.iter()
.filter_map(|(region_id, region_lease_info)| {
region_lease_info
.candidate_lease_id
.map(|candidate_lease_id| (*region_id, candidate_lease_id))
})
.collect::<HashMap<_, _>>();
renewer
.renew(ctx, renewed)
.into_iter()
.map(|region| region.into())
.map(|region| {
GrantedRegion {
candidate_lease_id: candidate_lease_ids
.get(&region.region_id)
.copied(),
..region
}
.into()
})
.collect()
} else {
renewed
.into_iter()
.map(|(region_id, region_lease_info)| {
GrantedRegion::new(region_id, region_lease_info.role).into()
})
.into_values()
.map(|region_lease_info| GrantedRegion::from(region_lease_info).into())
.collect::<Vec<_>>()
};
@@ -288,6 +307,10 @@ mod test {
let _guard = opening_region_keeper
.register_with_role(follower_peer.id, opening_region_id, RegionRole::Follower)
.unwrap();
let candidate_region_id = RegionId::new(table_id, region_number + 3);
let candidate_guard = opening_region_keeper
.register_candidate_region(follower_peer.id, candidate_region_id)
.unwrap();
let acc = &mut HeartbeatAccumulator::default();
@@ -297,6 +320,7 @@ mod test {
new_empty_region_stat(region_id, RegionRole::Follower),
new_empty_region_stat(another_region_id, RegionRole::Follower),
new_empty_region_stat(opening_region_id, RegionRole::Follower),
new_empty_region_stat(candidate_region_id, RegionRole::Follower),
],
..Default::default()
});
@@ -313,6 +337,10 @@ mod test {
vec![
GrantedRegion::new(region_id, RegionRole::Follower),
GrantedRegion::new(opening_region_id, RegionRole::Follower),
GrantedRegion {
candidate_lease_id: Some(candidate_guard.candidate_lease_id().unwrap()),
..GrantedRegion::new(candidate_region_id, RegionRole::Follower)
},
],
);
assert_eq!(acc.inactive_region_ids, HashSet::from([another_region_id]));
@@ -322,6 +350,106 @@ mod test {
);
}
/// Grants every renewed region except `skipped`, plus `extra`, which is not in the heartbeat.
/// Each lease has a candidate lease id the handler must not keep.
struct StubRegionLeaseRenewer {
skipped: RegionId,
extra: RegionId,
}
impl CustomizedRegionLeaseRenewer for StubRegionLeaseRenewer {
fn renew(
&self,
_ctx: &mut Context,
regions: HashMap<RegionId, RegionLeaseInfo>,
) -> Vec<GrantedRegion> {
regions
.into_values()
.filter(|info| info.region_id != self.skipped)
.map(|info| (info.region_id, info.role))
.chain([(self.extra, RegionRole::Follower)])
.map(|(region_id, role)| GrantedRegion {
candidate_lease_id: Some(u64::MAX),
..GrantedRegion::new(region_id, role)
})
.collect()
}
}
#[tokio::test]
async fn test_customized_renewer_leases_carry_candidate_lease_id() {
let table_id = 10;
let region_id = RegionId::new(table_id, 1);
let candidate_region_id = RegionId::new(table_id, 2);
let skipped_region_id = RegionId::new(table_id, 3);
let extra_region_id = RegionId::new(table_id, 4);
let leader_peer = Peer::empty(1);
let follower_peer = Peer::empty(2);
let keeper = new_test_keeper();
let table_metadata_manager = keeper.table_metadata_manager();
table_metadata_manager
.create_table_metadata(
new_test_table_info(table_id),
TableRouteValue::physical(vec![RegionRoute {
region: Region::new_test(region_id),
leader_peer: Some(leader_peer),
follower_peers: vec![follower_peer.clone()],
..Default::default()
}]),
HashMap::default(),
)
.await
.unwrap();
let opening_region_keeper = Arc::new(MemoryRegionKeeper::default());
let candidate_guard = opening_region_keeper
.register_candidate_region(follower_peer.id, candidate_region_id)
.unwrap();
let _skipped_guard = opening_region_keeper
.register_candidate_region(follower_peer.id, skipped_region_id)
.unwrap();
let handler = RegionLeaseHandler::new(
default_distributed_time_constants().region_lease.as_secs(),
table_metadata_manager.clone(),
opening_region_keeper,
Some(Arc::new(StubRegionLeaseRenewer {
skipped: skipped_region_id,
extra: extra_region_id,
})),
);
let metasrv = MetasrvBuilder::new().build().await.unwrap();
let ctx = &mut metasrv.new_ctx();
let acc = &mut HeartbeatAccumulator::default();
acc.stat = Some(Stat {
id: follower_peer.id,
region_stats: vec![
new_empty_region_stat(region_id, RegionRole::Follower),
new_empty_region_stat(candidate_region_id, RegionRole::Follower),
new_empty_region_stat(skipped_region_id, RegionRole::Follower),
],
..Default::default()
});
handler
.handle(&HeartbeatRequest::default(), ctx, acc)
.await
.unwrap();
assert_region_lease(
acc,
vec![
GrantedRegion::new(region_id, RegionRole::Follower),
GrantedRegion {
candidate_lease_id: Some(candidate_guard.candidate_lease_id().unwrap()),
..GrantedRegion::new(candidate_region_id, RegionRole::Follower)
},
GrantedRegion::new(extra_region_id, RegionRole::Follower),
],
);
}
#[tokio::test]
async fn test_handle_downgradable_leader() {
+31 -3
View File
@@ -330,9 +330,11 @@ pub struct VolatileContext {
/// `opening_region_guard` will be set after the
/// [OpenCandidateRegion](crate::procedure::region_migration::open_candidate_region::OpenCandidateRegion) step.
///
/// `opening_region_guards` should be consumed after
/// the corresponding [RegionRoute](common_meta::rpc::router::RegionRoute) of the opening region
/// was written into [TableRouteValue](common_meta::key::table_route::TableRouteValue).
/// On success, `opening_region_guards` is consumed after the
/// [RegionRoute](common_meta::rpc::router::RegionRoute) of the opening region is written into
/// the [TableRouteValue](common_meta::key::table_route::TableRouteValue). On a rollback it is
/// consumed before the route is restored, so the target leaves the candidate registration
/// before the source can lead again.
opening_region_guards: Vec<OperatingRegionGuard>,
/// The deadline of leader region lease.
leader_region_lease_deadline: Option<Instant>,
@@ -812,6 +814,9 @@ pub struct RegionMigrationData<'a> {
pub(crate) struct RegionMigrationProcedure {
state: Box<dyn State>,
/// Declared before `_guards`: a procedure that ends without a rollback (e.g. it fails to
/// record the rollback, or the manager stops) drops the candidate registration in `context`
/// before the region leaves the tracker, so another migration cannot start meanwhile.
context: Context,
_guards: Vec<RegionMigrationProcedureGuard>,
}
@@ -877,6 +882,8 @@ impl RegionMigrationProcedure {
let _timer = METRIC_META_REGION_MIGRATION_EXECUTE
.with_label_values(&["rollback"])
.start_timer();
// Before the source can lead again, the target leaves the candidate registration.
self.context.volatile_ctx.opening_region_guards.clear();
let ctx = &self.context;
let to_peer_id = ctx.persistent_ctx.to_peer.id;
let table_regions = ctx.persistent_ctx.table_regions();
@@ -1119,6 +1126,27 @@ mod tests {
assert_eq!(table_route.region_routes().unwrap()[0].leader_state, None);
}
#[tokio::test]
async fn test_rollback_drops_candidate_registration_before_route_write() {
let env = TestingEnv::new();
let persistent_ctx = new_persistent_context();
let rollback = CandidateRollback::new(&env, &persistent_ctx).await;
let mut procedure =
RegionMigrationProcedure::new(persistent_ctx, rollback.context_factory, vec![]);
procedure
.context
.volatile_ctx
.opening_region_guards
.push(rollback.guard);
procedure
.rollback_inner(&new_procedure_context())
.await
.unwrap();
assert_registration_dropped_before_route_write(&rollback.keeper_empty_at_txn);
}
#[test]
fn test_lock_key() {
let persistent_context = new_persistent_context();
@@ -672,7 +672,7 @@ mod test {
use tokio::sync::Notify;
use super::*;
use crate::procedure::region_migration::test_util::TestingEnv;
use crate::procedure::region_migration::test_util::{TestingEnv, new_persistent_context};
#[derive(Default)]
struct SubmissionGate {
@@ -1324,4 +1324,47 @@ mod test {
assert!(result.procedure_id.is_some());
env.procedure_manager().stop().await.unwrap();
}
#[test]
fn test_dropped_procedure_releases_candidate_registration_before_tracker() {
let env = TestingEnv::new();
let keeper = env.opening_region_keeper().clone();
let tracker = RegionMigrationProcedureTracker::default();
let region_id = RegionId::new(1024, 1);
let task = RegionMigrationProcedureTask::new(
region_id,
Peer::empty(1),
Peer::empty(2),
Duration::from_secs(1),
RegionMigrationTriggerReason::Manual,
);
let tracker_guard = tracker.insert_running_procedure(&task).unwrap();
let mut procedure = RegionMigrationProcedure::new(
new_persistent_context(1, 2, region_id),
env.context_factory(),
vec![tracker_guard],
);
procedure
.context
.volatile_ctx
.opening_region_guards
.push(keeper.register_candidate_region(2, region_id).unwrap());
// While this read lock is held, the tracker entry cannot be removed, so the registration
// has to go first.
let running_procedures = tracker.running_procedures.read().unwrap();
let dropper = std::thread::spawn(move || drop(procedure));
let deadline = std::time::Instant::now() + Duration::from_secs(10);
while !keeper.is_empty() {
assert!(
std::time::Instant::now() < deadline,
"the candidate registration outlives the tracker entry"
);
std::thread::sleep(Duration::from_millis(1));
}
assert!(running_procedures.contains_key(&region_id));
drop(running_procedures);
dropper.join().unwrap();
assert!(tracker.running_procedures.read().unwrap().is_empty());
}
}
@@ -27,7 +27,6 @@ use common_telemetry::info;
use common_telemetry::tracing_context::TracingContext;
use serde::{Deserialize, Serialize};
use snafu::{OptionExt, ResultExt};
use store_api::region_engine::RegionRole;
use store_api::region_request::RegionRequirements;
use tokio::time::Instant;
@@ -147,7 +146,7 @@ impl OpenCandidateRegion {
// Registers the opening region.
let guard = ctx
.opening_region_keeper
.register_with_role(candidate.id, *region_id, RegionRole::Follower)
.register_candidate_region(candidate.id, *region_id)
.context(error::RegionOperatingRaceSnafu {
peer_id: candidate.id,
region_id: *region_id,
@@ -236,7 +235,7 @@ impl OpenCandidateRegion {
#[cfg(test)]
mod tests {
use std::assert_matches;
use std::collections::HashMap;
use std::collections::{HashMap, HashSet};
use common_catalog::consts::MITO2_ENGINE;
use common_error::ext::RetryHint;
@@ -247,6 +246,7 @@ mod tests {
use common_meta::key::test_utils::new_test_table_info;
use common_meta::peer::Peer;
use common_meta::rpc::router::{Region, RegionRoute};
use store_api::region_engine::RegionRole;
use store_api::storage::RegionId;
use super::*;
@@ -623,8 +623,24 @@ mod tests {
send_mock_reply(mailbox, rx, |id| Ok(new_open_region_reply(id, true, None)));
let procedure_ctx = new_procedure_context();
let (next, _) = state.next(&mut ctx, &procedure_ctx).await.unwrap();
let vc = ctx.volatile_ctx;
assert_eq!(vc.opening_region_guards[0].info(), (to_peer_id, region_id));
let candidate_lease_id = {
let vc = &ctx.volatile_ctx;
assert_eq!(vc.opening_region_guards[0].info(), (to_peer_id, region_id));
vc.opening_region_guards[0].candidate_lease_id()
};
assert!(candidate_lease_id.is_some_and(|id| id != 0));
let regions = HashSet::from([region_id]);
let registered = |ctx: &Context| {
ctx.opening_region_keeper
.extract_operating_regions(to_peer_id, &regions)[&region_id]
.candidate_lease_id
};
assert_eq!(registered(&ctx), candidate_lease_id);
// A retry of the step keeps the registration and its id.
state.next(&mut ctx, &procedure_ctx).await.unwrap();
assert_eq!(ctx.volatile_ctx.opening_region_guards.len(), 1);
assert_eq!(registered(&ctx), candidate_lease_id);
let flush_leader_region = next.as_any().downcast_ref::<PreFlushRegion>().unwrap();
assert_matches!(flush_leader_region, PreFlushRegion);
@@ -14,20 +14,22 @@
use std::assert_matches;
use std::collections::HashMap;
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};
use std::time::Duration;
use api::v1::meta::MailboxMessage;
use common_meta::DatanodeId;
use common_meta::ddl::NoopRegionFailureDetectorControl;
use common_meta::key::table_route::TableRouteValue;
use common_meta::key::test_utils::new_test_table_info;
use common_meta::key::{TableMetadataManager, TableMetadataManagerRef};
use common_meta::kv_backend::KvBackendRef;
use common_meta::kv_backend::memory::MemoryKvBackend;
use common_meta::kv_backend::test_util::TxnObservingKvBackend;
use common_meta::peer::Peer;
use common_meta::region_keeper::{MemoryRegionKeeper, MemoryRegionKeeperRef};
use common_meta::rpc::router::RegionRoute;
use common_meta::region_keeper::{MemoryRegionKeeper, MemoryRegionKeeperRef, OperatingRegionGuard};
use common_meta::rpc::router::{LeaderState, Region, RegionRoute};
use common_meta::sequence::SequenceBuilder;
use common_meta::state_store::KvStateStore;
use common_procedure::local::{LocalManager, ManagerConfig};
@@ -592,3 +594,74 @@ pub fn new_procedure_context() -> ProcedureContext {
event_context: None,
}
}
/// A migration about to roll back: its region is led by the source peer in the downgrading state,
/// and registered on the target peer as the migration's candidate.
pub(crate) struct CandidateRollback {
/// Creates contexts on the table metadata whose transactions are observed.
pub(crate) context_factory: DefaultContextFactory,
/// The candidate registration of the region on the target peer.
pub(crate) guard: OperatingRegionGuard,
/// Whether the keeper held no registration before each transaction since the setup.
pub(crate) keeper_empty_at_txn: Arc<Mutex<Vec<bool>>>,
}
impl CandidateRollback {
/// Creates the table of `persistent_ctx` and the candidate registration of its region.
pub(crate) async fn new(env: &TestingEnv, persistent_ctx: &PersistentContext) -> Self {
let (table_metadata_manager, keeper_empty_at_txn) =
table_metadata_manager_observing_keeper(env.opening_region_keeper().clone());
let region_id = persistent_ctx.region_ids[0];
let region_routes = vec![RegionRoute {
region: Region::new_test(region_id),
leader_peer: Some(persistent_ctx.from_peer.clone()),
leader_state: Some(LeaderState::Downgrading),
..Default::default()
}];
table_metadata_manager
.create_table_metadata(
new_test_table_info(region_id.table_id()),
TableRouteValue::physical(region_routes),
HashMap::default(),
)
.await
.unwrap();
keeper_empty_at_txn.lock().unwrap().clear();
let guard = env
.opening_region_keeper()
.register_candidate_region(persistent_ctx.to_peer.id, region_id)
.unwrap();
Self {
context_factory: env.context_factory_with_metadata(table_metadata_manager),
guard,
keeper_empty_at_txn,
}
}
}
/// Asserts that the table metadata was written at least once after the setup, and that the
/// candidate registration was gone before every such write.
pub(crate) fn assert_registration_dropped_before_route_write(
keeper_empty_at_txn: &Mutex<Vec<bool>>,
) {
let keeper_empty_at_txn = keeper_empty_at_txn.lock().unwrap();
assert!(!keeper_empty_at_txn.is_empty());
assert!(keeper_empty_at_txn.iter().all(|empty| *empty));
}
/// Returns a table metadata manager that records, before each of its transactions, whether
/// `keeper` holds no registration.
fn table_metadata_manager_observing_keeper(
keeper: MemoryRegionKeeperRef,
) -> (TableMetadataManagerRef, Arc<Mutex<Vec<bool>>>) {
let keeper_empty_at_txn = Arc::new(Mutex::new(Vec::new()));
let recorded = keeper_empty_at_txn.clone();
let kv_backend = Arc::new(TxnObservingKvBackend {
inner: Arc::new(MemoryKvBackend::new()),
before_txn: Box::new(move || recorded.lock().unwrap().push(keeper.is_empty())),
});
(
Arc::new(TableMetadataManager::new(kv_backend)),
keeper_empty_at_txn,
)
}
@@ -69,6 +69,8 @@ impl State for UpdateMetadata {
Ok((Box::new(CloseDowngradedRegion), Status::executing(false)))
}
UpdateMetadata::Rollback => {
// Before the source can lead again, the target leaves the candidate registration.
ctx.volatile_ctx.opening_region_guards.clear();
self.rollback_downgraded_region(ctx, &procedure_ctx.provider)
.await?;
@@ -85,7 +85,9 @@ mod tests {
use crate::error::Error;
use crate::procedure::region_migration::migration_abort::RegionMigrationAbort;
use crate::procedure::region_migration::test_util::{self, TestingEnv, new_procedure_context};
use crate::procedure::region_migration::test_util::{
self, CandidateRollback, TestingEnv, new_procedure_context,
};
use crate::procedure::region_migration::update_metadata::UpdateMetadata;
use crate::procedure::region_migration::{ContextFactory, PersistentContext, State};
@@ -173,4 +175,20 @@ mod tests {
table_route.region_routes().unwrap()
);
}
#[tokio::test]
async fn test_next_drops_candidate_registration_before_route_write() {
let env = TestingEnv::new();
let persistent_context = new_persistent_context();
let rollback = CandidateRollback::new(&env, &persistent_context).await;
let mut ctx = rollback.context_factory.new_context(persistent_context);
ctx.volatile_ctx.opening_region_guards.push(rollback.guard);
UpdateMetadata::Rollback
.next(&mut ctx, &new_procedure_context())
.await
.unwrap();
test_util::assert_registration_dropped_before_route_write(&rollback.keeper_empty_at_txn);
}
}
@@ -154,6 +154,12 @@ impl UpgradeCandidateRegion {
.get(&region_id)
.copied();
let checkpoint = replay_checkpoints.get(&region_id).copied();
let candidate_lease_id = ctx
.volatile_ctx
.opening_region_guards
.iter()
.find(|guard| guard.info().1 == region_id)
.and_then(|guard| guard.candidate_lease_id());
upgrade_regions.push(UpgradeRegion {
region_id,
last_entry_id,
@@ -162,6 +168,7 @@ impl UpgradeCandidateRegion {
location_id: Some(ctx.persistent_ctx.from_peer.id),
replay_entry_id: checkpoint.map(|c| c.entry_id),
metadata_replay_entry_id: checkpoint.and_then(|c| c.metadata_entry_id),
candidate_lease_id,
});
}
@@ -466,6 +473,46 @@ mod tests {
assert_eq!(upgrade_regions[0].metadata_replay_entry_id, None);
}
#[tokio::test]
async fn test_build_upgrade_region_instruction_carries_candidate_lease_id() {
let state = UpgradeCandidateRegion::default();
let env = TestingEnv::new();
let mut persistent_context = new_persistent_context();
let region_ids = vec![RegionId::new(1024, 1), RegionId::new(1024, 2)];
persistent_context.region_ids = region_ids.clone();
let mut ctx = env.context_factory().new_context(persistent_context);
prepare_table_metadata(&ctx, RegionWalOptions::default()).await;
let to_peer_id = ctx.persistent_ctx.to_peer.id;
let mut expected = HashMap::new();
// The guards are stored in the opposite order of the regions.
for region_id in region_ids.iter().rev() {
let guard = env
.opening_region_keeper()
.register_candidate_region(to_peer_id, *region_id)
.unwrap();
expected.insert(*region_id, guard.candidate_lease_id().unwrap());
ctx.volatile_ctx.opening_region_guards.push(guard);
}
// Retries send the same ids.
for _ in 0..2 {
let instruction = state
.build_upgrade_region_instruction(&mut ctx, Duration::from_secs(1))
.await
.unwrap();
let Instruction::UpgradeRegions(upgrade_regions) = instruction else {
unreachable!()
};
assert_eq!(upgrade_regions.len(), 2);
for upgrade_region in upgrade_regions {
assert_eq!(
upgrade_region.candidate_lease_id,
Some(expected[&upgrade_region.region_id])
);
}
}
}
#[tokio::test]
async fn test_build_upgrade_region_instruction_merges_metric_metadata_pruned_entry_id() {
let state = UpgradeCandidateRegion::default();
+18 -12
View File
@@ -1370,24 +1370,30 @@ mod tests {
let _guards = Context::register_operating_regions(&keeper, &region_routes).unwrap();
let leader_roles =
keeper.extract_operating_region_roles(1, &HashSet::from([RegionId::new(1024, 1)]));
let staging_roles =
keeper.extract_operating_region_roles(2, &HashSet::from([RegionId::new(1024, 2)]));
let downgrading_roles =
keeper.extract_operating_region_roles(3, &HashSet::from([RegionId::new(1024, 3)]));
let leader_regions =
keeper.extract_operating_regions(1, &HashSet::from([RegionId::new(1024, 1)]));
let staging_regions =
keeper.extract_operating_regions(2, &HashSet::from([RegionId::new(1024, 2)]));
let downgrading_regions =
keeper.extract_operating_regions(3, &HashSet::from([RegionId::new(1024, 3)]));
assert_eq!(
leader_roles.get(&RegionId::new(1024, 1)),
Some(&RegionRole::Leader)
leader_regions
.get(&RegionId::new(1024, 1))
.map(|region| region.role),
Some(RegionRole::Leader)
);
assert_eq!(
staging_roles.get(&RegionId::new(1024, 2)),
Some(&RegionRole::StagingLeader)
staging_regions
.get(&RegionId::new(1024, 2))
.map(|region| region.role),
Some(RegionRole::StagingLeader)
);
assert_eq!(
downgrading_roles.get(&RegionId::new(1024, 3)),
Some(&RegionRole::DowngradingLeader)
downgrading_regions
.get(&RegionId::new(1024, 3))
.map(|region| region.role),
Some(RegionRole::DowngradingLeader)
);
}
+132 -12
View File
@@ -18,11 +18,11 @@ use std::sync::Arc;
use common_meta::DatanodeId;
use common_meta::key::TableMetadataManagerRef;
use common_meta::key::table_route::TableRouteValue;
use common_meta::region_keeper::MemoryRegionKeeperRef;
use common_meta::region_keeper::{MemoryRegionKeeperRef, OperatingRegion};
use common_meta::rpc::router::RegionRoute;
use common_telemetry::{info, warn};
use snafu::ResultExt;
use store_api::region_engine::RegionRole;
use store_api::region_engine::{GrantedRegion, RegionRole};
use store_api::storage::{RegionId, TableId};
use crate::error::{self, Result};
@@ -81,16 +81,22 @@ fn renew_region_lease_via_region_route(
}
fn renew_region_lease_via_operating_regions(
operating_regions: &HashMap<RegionId, RegionRole>,
operating_regions: &HashMap<RegionId, OperatingRegion>,
datanode_id: DatanodeId,
region_id: RegionId,
reported_role: RegionRole,
table_route_exists: bool,
) -> Option<RegionLeaseInfo> {
// `operating_regions` is filtered by the current datanode in `collect_metadata`,
// so looking up by `region_id` is sufficient here.
if let Some(role) = operating_regions.get(&region_id) {
let region_lease_info = RegionLeaseInfo::operating(region_id, *role);
if *role != reported_role {
if let Some(operating_region) = operating_regions.get(&region_id) {
let role = operating_region.role;
let mut region_lease_info = RegionLeaseInfo::operating(region_id, role);
// Without the table route, the registration alone must not vouch for a migration.
if table_route_exists {
region_lease_info.candidate_lease_id = operating_region.candidate_lease_id;
}
if role != reported_role {
info!(
"The region {} on datanode {} is operating with role {:?}, but reported as {:?}",
region_id, datanode_id, role, reported_role
@@ -112,6 +118,9 @@ pub struct RegionLeaseInfo {
pub is_operating: bool,
/// The role of region.
pub role: RegionRole,
/// The candidate lease id of the region migration that registered this region as its
/// target, if the lease is granted because of that registration and the table route exists.
pub candidate_lease_id: Option<u64>,
}
impl RegionLeaseInfo {
@@ -121,6 +130,7 @@ impl RegionLeaseInfo {
region_id,
is_operating: true,
role,
candidate_lease_id: None,
}
}
}
@@ -131,6 +141,16 @@ impl From<(RegionId, RegionRole)> for RegionLeaseInfo {
region_id,
is_operating: false,
role,
candidate_lease_id: None,
}
}
}
impl From<RegionLeaseInfo> for GrantedRegion {
fn from(value: RegionLeaseInfo) -> Self {
GrantedRegion {
candidate_lease_id: value.candidate_lease_id,
..GrantedRegion::new(value.region_id, value.role)
}
}
}
@@ -165,13 +185,14 @@ impl RegionLeaseKeeper {
fn renew_region_lease(
&self,
table_metadata: &HashMap<TableId, TableRouteValue>,
operating_regions: &HashMap<RegionId, RegionRole>,
operating_regions: &HashMap<RegionId, OperatingRegion>,
datanode_id: DatanodeId,
region_id: RegionId,
reported_role: RegionRole,
) -> Option<RegionLeaseInfo> {
let table_route = table_metadata.get(&region_id.table_id());
// First try to renew via region route
if let Some(table_route) = table_metadata.get(&region_id.table_id())
if let Some(table_route) = table_route
&& let Ok(Some(region_route)) = table_route.region_route(region_id)
&& let Some(region_lease) =
renew_region_lease_via_region_route(&region_route, datanode_id, region_id)
@@ -184,6 +205,7 @@ impl RegionLeaseKeeper {
datanode_id,
region_id,
reported_role,
table_route.is_some(),
) {
return Some(region_lease_info);
}
@@ -200,11 +222,11 @@ impl RegionLeaseKeeper {
region_ids: HashSet<RegionId>,
) -> Result<(
HashMap<TableId, TableRouteValue>,
HashMap<RegionId, RegionRole>,
HashMap<RegionId, OperatingRegion>,
)> {
let operating_regions = self
.memory_region_keeper
.extract_operating_region_roles(datanode_id, &region_ids);
.extract_operating_regions(datanode_id, &region_ids);
let table_ids = region_ids
.into_iter()
.map(|region_id| region_id.table_id())
@@ -271,12 +293,13 @@ mod tests {
use std::collections::{HashMap, HashSet};
use std::sync::Arc;
use common_meta::DatanodeId;
use common_meta::key::TableMetadataManager;
use common_meta::key::table_route::{LogicalTableRouteValue, TableRouteValue};
use common_meta::key::test_utils::new_test_table_info;
use common_meta::kv_backend::memory::MemoryKvBackend;
use common_meta::peer::Peer;
use common_meta::region_keeper::MemoryRegionKeeper;
use common_meta::region_keeper::{MemoryRegionKeeper, OperatingRegion, OperatingRegionGuard};
use common_meta::rpc::router::{LeaderState, Region, RegionRouteBuilder};
use store_api::region_engine::RegionRole;
use store_api::storage::RegionId;
@@ -414,7 +437,13 @@ mod tests {
);
assert_eq!(
regions,
HashMap::from([(opening_region_id, RegionRole::Leader)])
HashMap::from([(
opening_region_id,
OperatingRegion {
role: RegionRole::Leader,
candidate_lease_id: None,
}
)])
);
}
@@ -817,4 +846,95 @@ mod tests {
)])
);
}
/// Creates a table whose route has the region led by `leader_peer_id`, and registers the region
/// on `candidate_peer_id` as the target of a migration.
async fn register_candidate_with_route(
keeper: &RegionLeaseKeeper,
region_id: RegionId,
leader_peer_id: DatanodeId,
candidate_peer_id: DatanodeId,
) -> OperatingRegionGuard {
let region_route = RegionRouteBuilder::default()
.region(Region::new_test(region_id))
.leader_peer(Peer::empty(leader_peer_id))
.build()
.unwrap();
keeper
.table_metadata_manager()
.create_table_metadata(
new_test_table_info(region_id.table_id()),
TableRouteValue::physical(vec![region_route]),
HashMap::default(),
)
.await
.unwrap();
keeper
.memory_region_keeper
.register_candidate_region(candidate_peer_id, region_id)
.unwrap()
}
#[tokio::test]
async fn test_renew_region_lease_from_registration_carries_candidate_lease_id() {
let keeper = new_test_keeper();
let region_id = RegionId::new(2048, 1);
let guard = register_candidate_with_route(&keeper, region_id, 1, 2).await;
let RenewRegionLeasesResponse { renewed, .. } = keeper
.renew_region_leases(2, &[(region_id, RegionRole::Follower)])
.await
.unwrap();
let expected = RegionLeaseInfo {
candidate_lease_id: guard.candidate_lease_id(),
..RegionLeaseInfo::operating(region_id, RegionRole::Follower)
};
assert!(expected.candidate_lease_id.is_some());
assert_eq!(renewed, HashMap::from([(region_id, expected)]));
}
#[tokio::test]
async fn test_renew_region_leases_route_lease_has_no_candidate_lease_id() {
let keeper = new_test_keeper();
let region_id = RegionId::new(2048, 1);
// The route already names the candidate as the leader.
let _guard = register_candidate_with_route(&keeper, region_id, 2, 2).await;
let RenewRegionLeasesResponse { renewed, .. } = keeper
.renew_region_leases(2, &[(region_id, RegionRole::Follower)])
.await
.unwrap();
assert_eq!(
renewed,
HashMap::from([(
region_id,
RegionLeaseInfo::from((region_id, RegionRole::Leader))
)])
);
}
#[tokio::test]
async fn test_renew_region_leases_without_table_route_has_no_candidate_lease_id() {
let keeper = new_test_keeper();
let region_id = RegionId::new(2048, 1);
let _guard = keeper
.memory_region_keeper
.register_candidate_region(2, region_id)
.unwrap();
let RenewRegionLeasesResponse { renewed, .. } = keeper
.renew_region_leases(2, &[(region_id, RegionRole::Follower)])
.await
.unwrap();
assert_eq!(
renewed,
HashMap::from([(
region_id,
RegionLeaseInfo::operating(region_id, RegionRole::Follower)
)])
);
}
}
+3
View File
@@ -83,6 +83,9 @@ cargo nextest run -p metric-engine
write lock and invalidate the cache after the Mito2 write succeeds; preserve
that ordering when adding a metadata mutation path.
- Always convert ids via `utils::to_data_region_id` / `to_metadata_region_id`.
- `MetricEngine::loaded_logical_regions` exposes physical regions' loaded logical
children. RegionServer captures them before drop/close and unregisters them
after success; physical removal must also clear logical column caches.
## Maintenance contract
+1
View File
@@ -53,6 +53,7 @@ log-store = { workspace = true, features = ["testing"] }
mito2 = { workspace = true, features = ["test"] }
mur3 = "0.1"
partition = { workspace = true }
rstest = { workspace = true }
[[bench]]
name = "bench_tsid_generator"
+105 -16
View File
@@ -390,20 +390,34 @@ impl RegionEngine for MetricEngine {
role: RegionRole,
sent_at: Instant,
deadline: Instant,
candidate_lease_id: Option<u64>,
) -> Result<bool, BoxedError> {
// The metadata region goes first. If it ignores the grant, the data region, whose role the
// engine reports, must not take it either. A region that is not found is ignored.
for x in [
utils::to_metadata_region_id(region_id),
utils::to_data_region_id(region_id),
] {
match self
.inner
.mito
.set_region_role_with_lease(x, role, sent_at, deadline)
{
let metadata_region_id = utils::to_metadata_region_id(region_id);
let data_region_id = utils::to_data_region_id(region_id);
for x in [metadata_region_id, data_region_id] {
match self.inner.mito.set_region_role_with_lease(
x,
role,
sent_at,
deadline,
candidate_lease_id,
) {
Ok(true) => {}
Ok(false) => return Ok(false),
Ok(false) => {
// If the metadata region ignored the grant, the data region is not handed it, so
// record it for the data region. If the data region ignored it, the data region
// has already recorded it.
if x == metadata_region_id {
self.inner.mito.record_granted_lease(
data_region_id,
sent_at,
candidate_lease_id,
);
}
return Ok(false);
}
Err(e) if e.status_code() != StatusCode::RegionNotFound => return Err(e),
Err(_) => {}
}
@@ -567,6 +581,20 @@ impl MetricEngine {
self.inner.put_regions_batch(requests).await
}
/// Returns the physical region's logical regions from the loaded engine state.
/// Unlike `logical_regions`, this does not read the metadata region and remains usable
/// while a partially completed drop or close is being retried.
pub fn loaded_logical_regions(&self, physical_region_id: RegionId) -> Vec<RegionId> {
self.inner
.state
.read()
.unwrap()
.physical_region_states()
.get(&utils::to_data_region_id(physical_region_id))
.map(|state| state.logical_regions().iter().copied().collect())
.unwrap_or_default()
}
/// Returns all logical regions associated with the physical region.
pub async fn logical_regions(&self, physical_region_id: RegionId) -> Result<Vec<RegionId>> {
self.inner
@@ -694,6 +722,7 @@ mod test {
use common_wal::options::{KafkaWalOptions, WalOptions};
use mito2::sst::location::region_dir_from_table_dir;
use mito2::test_util::{kafka_log_store_factory, prepare_test_for_kafka_log_store};
use rstest::rstest;
use store_api::metric_engine_consts::PHYSICAL_TABLE_METADATA_KEY;
use store_api::mito_engine_options::WAL_OPTIONS_KEY;
use store_api::region_request::{
@@ -956,22 +985,54 @@ mod test {
assert!(!object_store.exists(&data_region_dir).await.unwrap());
}
const LEASE: std::time::Duration = std::time::Duration::from_secs(10);
/// Asserts that both the metadata and the data region of `physical_region_id` recorded
/// `expected` as the candidate lease id of their latest lease.
fn assert_candidate_lease_id_recorded(
mito: &MitoEngine,
physical_region_id: RegionId,
expected: Option<u64>,
) {
for region_id in [
utils::to_metadata_region_id(physical_region_id),
utils::to_data_region_id(physical_region_id),
] {
assert_eq!(mito.granted_candidate_lease_id(region_id), expected);
}
}
/// The region that ignores a Leader grant is the one downgraded after the heartbeat is sent;
/// the other one is downgraded before it.
#[rstest]
#[case::metadata_region_ignores(
utils::to_data_region_id,
utils::to_metadata_region_id,
RegionRole::Follower
)]
#[case::data_region_ignores(
utils::to_metadata_region_id,
utils::to_data_region_id,
RegionRole::Leader
)]
#[tokio::test]
async fn test_leader_grant_ignored_by_metadata_region_leaves_data_region() {
async fn test_leader_grant_ignored_by_one_region(
#[case] downgraded_before_sent: fn(RegionId) -> RegionId,
#[case] downgraded_after_sent: fn(RegionId) -> RegionId,
#[case] metadata_role: RegionRole,
) {
let env = TestEnv::new().await;
env.init_metric_region().await;
let (engine, mito) = (env.metric(), env.mito());
let physical_region_id = env.default_physical_region_id();
let lease = std::time::Duration::from_secs(10);
// The data region is downgraded before the heartbeat is sent, the metadata region after it.
let downgrade = |region_id| {
mito.set_region_role_state_gracefully(region_id, SettableRegionRoleState::Follower)
};
downgrade(utils::to_data_region_id(physical_region_id))
downgrade(downgraded_before_sent(physical_region_id))
.await
.unwrap();
let sent_at = Instant::now();
downgrade(utils::to_metadata_region_id(physical_region_id))
downgrade(downgraded_after_sent(physical_region_id))
.await
.unwrap();
@@ -981,17 +1042,45 @@ mod test {
physical_region_id,
RegionRole::Leader,
sent_at,
sent_at + lease,
sent_at + LEASE,
Some(7),
)
.unwrap()
};
assert!(!grant(sent_at));
assert_eq!(engine.role(physical_region_id), Some(RegionRole::Follower));
assert_eq!(
mito.role(utils::to_metadata_region_id(physical_region_id)),
Some(metadata_role)
);
// Both regions record the grant, including the one that is not handed it.
assert_candidate_lease_id_recorded(&mito, physical_region_id, Some(7));
assert!(grant(Instant::now()));
assert_eq!(engine.role(physical_region_id), Some(RegionRole::Leader));
}
#[tokio::test]
async fn test_candidate_lease_id_reaches_metadata_and_data_regions() {
let env = TestEnv::new().await;
env.init_metric_region().await;
let (engine, mito) = (env.metric(), env.mito());
let physical_region_id = env.default_physical_region_id();
let sent_at = Instant::now();
engine
.set_region_role_with_lease(
physical_region_id,
RegionRole::Follower,
sent_at,
sent_at + LEASE,
Some(7),
)
.unwrap();
assert_candidate_lease_id_recorded(&mito, physical_region_id, Some(7));
}
#[tokio::test]
async fn test_role() {
let env = TestEnv::new().await;
+2 -2
View File
@@ -189,7 +189,7 @@ impl MetricEngineInner {
#[cfg(test)]
mod tests {
use api::v1::Rows;
use common_wal::config::object_store::{ObjectStoreWalConfig, STANDALONE_GENERATION};
use common_wal::config::object_store::{FIXED_DIRECTORY_GENERATION, ObjectStoreWalConfig};
use common_wal::options::{ObjectStoreWalOptions, WAL_OPTIONS_KEY, WalOptions};
use log_store::ObjectStoreLogStore;
use mito2::config::MitoConfig;
@@ -238,7 +238,7 @@ mod tests {
object_store.clone(),
&config,
0,
STANDALONE_GENERATION,
FIXED_DIRECTORY_GENERATION,
)
};
let wal = open_wal().await.unwrap();
+7 -1
View File
@@ -2379,7 +2379,13 @@ mod tests {
let at = |n| start + n * Duration::from_secs(10);
let grant = |n| {
engine
.set_region_role_with_lease(physical_region_id, RegionRole::Leader, start, at(n))
.set_region_role_with_lease(
physical_region_id,
RegionRole::Leader,
start,
at(n),
None,
)
.unwrap()
};
let expire = |n| mito.freeze_lease_clock(at(n));
+1
View File
@@ -278,6 +278,7 @@ impl MetricEngineState {
for logical_region in logical_regions {
self.logical_regions.remove(logical_region);
self.logical_columns.remove(logical_region);
}
self.physical_regions.remove(&physical_region_id);
Ok(())
+15 -3
View File
@@ -87,6 +87,9 @@ pending. DDL cancellation retains its existing scheduling fence and priority.
`tests/compatibility/manifest/table_compaction/` and
`tests/compatibility/manifest/pending_tails/`.
- **SST/Parquet layout** (`sst/`): readers must stay compatible with existing files.
- **Index extensions**: shared contracts and provider validation live in `sst/index/registry.rs`;
typed sketch options are enterprise-gated. Lifecycle and failure tests live in
`engine/index_build_test.rs` and `compaction/`.
- **Series-index disk limit**: tasks estimate usage from entry sizes in open-region snapshots
and defer new builds when the shared estimate is full. Cleanup still prunes obsolete
range entries and expires series indexes to reclaim published usage. Concurrent builds may
@@ -122,7 +125,9 @@ Tests live next to the code as `*_test.rs` (e.g. `src/mito2/src/engine/flush_tes
- In those regions a commit after the region's Leader deadline sends nothing, and a version
conflict fences the region (`ManifestContext::fence_for_reload`): no lease or catchup promotes
it until the worker swaps in an instance reloaded from the new manifest
(`worker/handle_reload.rs`). Never await a worker sender while holding a manifest guard.
(`worker/handle_reload.rs`). A tail replay round that fails while the storage holds a newer
manifest fences a writable leader the same way. Never await a worker sender while holding a
manifest guard.
- Pending tails (`RegionManifest::pending_tails`) are WAL ranges a region still has
to recover; the flushed entry id never prunes them. Opening a region replays its
WAL after `RegionManifest::wal_replay_start`. The WAL releases at open, after
@@ -146,8 +151,10 @@ Tests live next to the code as `*_test.rs` (e.g. `src/mito2/src/engine/flush_tes
tails must raise the committed sequence to theirs, or writes accepted during the replay
lose to replayed rows. This node's later entry ids must be above every tail's `upto`, and
its unflushed entries at or below one must be in its own tails, or the tail commit's
flushed entry id skips them. Replays have no admission or concurrency limit. Their SSTs
build indexes as flushed ones (`IndexBuildType::Flush`), under `create_on_flush`.
flushed entry id skips them. A node bounds its replays' concurrency and SST writes apart
from flushes, and their chunk memory within the global write buffer (`TailReplayLimits`).
Replayed SSTs build indexes as flushed ones (`IndexBuildType::Flush`), under
`create_on_flush`.
- Lock ordering: take the manifest lock before updating `version_control`; the
reverse deadlocks against concurrent flush/compaction.
- All region I/O runs on tokio workers; never `block_on` inside a worker.
@@ -191,6 +198,11 @@ Tests live next to the code as `*_test.rs` (e.g. `src/mito2/src/engine/flush_tes
- Direct SST imports without a staging binding cannot publish into staging.
`worker/handle_manifest.rs` seals edit admission while EnterStaging drains accepted
edits. Scheduler-owned DDLs resume through execution, bypassing initial admission.
- The latest lease each region received (`GrantedLeases` in `lease.rs`) lives outside the
region instance, so a reopen during catchup keeps it. Every path that removes a region from
a worker's region map must also remove its record: `RegionWorkerLoop::remove_region`
(`worker/handle_close.rs`, also used after a close-time flush), `drop_region`
(`worker/handle_drop.rs`) and `RegionWorkerLoop::clean` (`worker.rs`).
## Maintenance contract
+153 -62
View File
@@ -26,12 +26,14 @@ use object_store::services::Fs;
use object_store::util::{join_dir, with_instrument_layers};
use object_store::{ATOMIC_WRITE_DIR, ErrorKind, OLD_ATOMIC_WRITE_DIR, ObjectStore};
use parquet::file::metadata::PageIndexPolicy;
use prometheus::HistogramVec;
use smallvec::SmallVec;
use snafu::ResultExt;
use store_api::metadata::RegionMetadataRef;
use store_api::region_request::PathType;
use store_api::sst_entry::StorageSstEntry;
use store_api::storage::{FileId, RegionId, SequenceNumber};
use strum::IntoStaticStr;
use crate::cache::file_cache::{FileCacheRef, FileType, IndexKey};
use crate::cache::write_cache::SstUploadRequest;
@@ -40,7 +42,7 @@ use crate::config::{BloomFilterConfig, FulltextIndexConfig, IndexConfig, Inverte
use crate::error::{
CleanDirSnafu, DeleteIndexSnafu, DeleteIndexesSnafu, DeleteSstsSnafu, OpenDalSnafu, Result,
};
use crate::metrics::{COMPACTION_STAGE_ELAPSED, FLUSH_ELAPSED};
use crate::metrics::{COMPACTION_STAGE_ELAPSED, FLUSH_ELAPSED, TAIL_REPLAY_ELAPSED};
use crate::read::FlatSource;
use crate::region::options::IndexOptions;
use crate::sst::file::{FileHandle, RegionFileId, RegionIndexId};
@@ -51,7 +53,7 @@ use crate::sst::index::registry::IndexRegistry;
use crate::sst::index::{IndexerBuilderImpl, build_index_from_parquet_bytes};
use crate::sst::location::{self, region_dir_from_table_dir};
use crate::sst::parquet::reader::ParquetReaderBuilder;
use crate::sst::parquet::writer::ParquetWriter;
use crate::sst::parquet::writer::{ParquetWriter, SstWriteContext};
use crate::sst::parquet::{SstInfo, WriteOptions};
use crate::sst::{DEFAULT_WRITE_CONCURRENCY, FormatType};
@@ -60,12 +62,14 @@ pub type AccessLayerRef = Arc<AccessLayer>;
pub type SstInfoArray = SmallVec<[SstInfo; 2]>;
/// Write operation type.
#[derive(Eq, PartialEq, Debug)]
#[derive(Eq, PartialEq, Debug, Clone, Copy, IntoStaticStr)]
pub enum WriteType {
/// Writes from flush
Flush,
/// Writes from compaction.
Compaction,
/// Writes from the replay of pending WAL tails.
TailReplay,
}
#[derive(Debug)]
@@ -104,47 +108,28 @@ impl Metrics {
}
pub(crate) fn observe(self) {
match self.write_type {
WriteType::Flush => {
FLUSH_ELAPSED
.with_label_values(&["iter_source"])
.observe(self.iter_source.as_secs_f64());
FLUSH_ELAPSED
.with_label_values(&["write_batch"])
.observe(self.write_batch.as_secs_f64());
FLUSH_ELAPSED
.with_label_values(&["update_index"])
.observe(self.update_index.as_secs_f64());
FLUSH_ELAPSED
.with_label_values(&["upload_parquet"])
.observe(self.upload_parquet.as_secs_f64());
FLUSH_ELAPSED
.with_label_values(&["upload_puffin"])
.observe(self.upload_puffin.as_secs_f64());
if !self.compact_memtable.is_zero() {
FLUSH_ELAPSED
.with_label_values(&["compact_memtable"])
.observe(self.upload_puffin.as_secs_f64());
}
}
WriteType::Compaction => {
COMPACTION_STAGE_ELAPSED
.with_label_values(&["iter_source"])
.observe(self.iter_source.as_secs_f64());
COMPACTION_STAGE_ELAPSED
.with_label_values(&["write_batch"])
.observe(self.write_batch.as_secs_f64());
COMPACTION_STAGE_ELAPSED
.with_label_values(&["update_index"])
.observe(self.update_index.as_secs_f64());
COMPACTION_STAGE_ELAPSED
.with_label_values(&["upload_parquet"])
.observe(self.upload_parquet.as_secs_f64());
COMPACTION_STAGE_ELAPSED
.with_label_values(&["upload_puffin"])
.observe(self.upload_puffin.as_secs_f64());
}
let elapsed: &HistogramVec = match self.write_type {
WriteType::Flush => &FLUSH_ELAPSED,
WriteType::Compaction => &COMPACTION_STAGE_ELAPSED,
WriteType::TailReplay => &TAIL_REPLAY_ELAPSED,
};
let stages = [
("iter_source", self.iter_source),
("write_batch", self.write_batch),
("update_index", self.update_index),
("upload_parquet", self.upload_parquet),
("upload_puffin", self.upload_puffin),
];
for (stage, duration) in stages {
elapsed
.with_label_values(&[stage])
.observe(duration.as_secs_f64());
}
if !self.compact_memtable.is_zero() {
elapsed
.with_label_values(&["compact_memtable"])
.observe(self.compact_memtable.as_secs_f64());
}
}
}
@@ -376,18 +361,13 @@ impl AccessLayer {
.await
}
/// Writes an SST whose output is registered with `context.guard`.
///
/// The write cache is bypassed, upload concurrency is fixed to one, and
/// the guard runs before either the SST or its index becomes visible.
/// `context.limits` bounds the encoder and footer workspace.
#[cfg(feature = "enterprise")]
pub(crate) async fn write_sst_with_guard(
/// Writes SSTs with explicit ownership and cooperative cancellation.
pub(crate) async fn write_sst_with_context(
&self,
request: SstWriteRequest,
write_opts: &WriteOptions,
metrics: &mut Metrics,
context: crate::sst::parquet::writer::SstWriteContext,
context: SstWriteContext,
) -> Result<SstInfoArray> {
self.write_sst_inner(request, write_opts, metrics, Some(context))
.await
@@ -395,13 +375,20 @@ impl AccessLayer {
async fn write_sst_inner(
&self,
request: SstWriteRequest,
mut request: SstWriteRequest,
write_opts: &WriteOptions,
metrics: &mut Metrics,
context: Option<crate::sst::parquet::writer::SstWriteContext>,
context: Option<SstWriteContext>,
) -> Result<SstInfoArray> {
let limits = context.as_ref().map(|context| context.limits);
let guard = context.map(|context| context.guard);
// Rollover can create multiple SSTs from this request, so no output may
// reuse summaries covering the complete input set.
if let Some(provider) = &mut request.index_build_inputs {
provider.can_merge_inputs &= write_opts.max_file_size.is_none();
}
let context = context.unwrap_or_default();
let limits = context.limits;
let guard = context.guard.clone();
let cancellation = context.cancellation.clone();
let op_type = request.op_type;
let region_id = request.metadata.region_id;
let region_metadata = request.metadata.clone();
@@ -413,11 +400,11 @@ impl AccessLayer {
};
let sst_info = if let Some(write_cache) = cache_manager.write_cache()
&& guard.is_none()
&& limits.is_none()
{
// Write to the write cache.
write_cache
.write_and_upload_sst(
.write_and_upload_sst_with_context(
request,
SstUploadRequest {
dest_path_provider: RegionFilePathFactory::new(
@@ -428,10 +415,12 @@ impl AccessLayer {
},
write_opts,
metrics,
context,
)
.await?
} else {
// Write cache is disabled, or bypassed by an SST write guard.
// The write cache does not enforce SstWriteLimits, so bounded writes
// bypass it.
let store = self.object_store.clone();
let path_provider = RegionFilePathFactory::new(self.table_dir.clone(), self.path_type);
let puffin_factory = if limits.is_some() {
@@ -469,12 +458,13 @@ impl AccessLayer {
)
.await
.with_file_cleaner(cleaner)
.with_write_concurrency(if guard.is_some() {
.with_write_concurrency(if limits.is_some() {
1
} else {
crate::sst::DEFAULT_WRITE_CONCURRENCY
})
.with_write_guard(guard)
.with_cancellation(cancellation)
.with_memory_limits(limits);
match request.sst_write_format {
FormatType::PrimaryKey => {
@@ -553,6 +543,7 @@ impl AccessLayer {
///
/// Builds the SST's indexes from `data` into `sst_info.index_metadata` when
/// `index_build_params` is set.
#[allow(clippy::too_many_arguments)]
pub(crate) async fn put_sst(
&self,
data: &bytes::Bytes,
@@ -561,7 +552,8 @@ impl AccessLayer {
cache_manager: &CacheManagerRef,
write_buffer_size: ReadableSize,
index_build_params: Option<EncodedSstIndexBuildParams>,
) -> Result<Metrics> {
metrics: &mut Metrics,
) -> Result<()> {
let region_file_id = RegionFileId::new(region_id, sst_info.file_id);
if let Some(write_cache) = cache_manager.write_cache() {
// Write to cache and upload to remote store
@@ -580,6 +572,7 @@ impl AccessLayer {
upload_request,
write_buffer_size,
index_build_params,
metrics,
)
.await
} else {
@@ -603,7 +596,6 @@ impl AccessLayer {
cleaner.clean_by_file_id(region_file_id.file_id()).await;
return Err(err);
}
let mut metrics = Metrics::new(WriteType::Flush);
metrics.write_batch = start.elapsed();
if let Some(params) = index_build_params {
@@ -618,7 +610,7 @@ impl AccessLayer {
build_index_from_parquet_bytes(&builder, region_file_id, data).await;
metrics.update_index = start.elapsed();
}
Ok(metrics)
Ok(())
}
}
@@ -972,6 +964,7 @@ mod tests {
&cache_manager,
ReadableSize(chunk_size as u64),
None,
&mut Metrics::new(WriteType::Flush),
)
.await
.unwrap();
@@ -1104,6 +1097,104 @@ mod tests {
assert_eq!(1, warm.mem_cache_hit);
}
#[rstest::rstest]
#[tokio::test]
async fn test_cancelled_write_cleans_rolled_ssts(
#[values(false, true)] enable_write_cache: bool,
#[values(FormatType::Flat, FormatType::PrimaryKey)] format: FormatType,
) {
use crate::read::FlatSource;
use crate::sst::file::UncommittedSsts;
use crate::test_util::sst_util::{new_record_batch_by_range, sst_region_metadata};
use tokio_util::sync::CancellationToken;
let mut env = TestEnv::new().await;
let store = env.init_object_store_manager();
let local_dir = create_temp_dir("cancelled-sst-cache");
let local_store = new_fs_store(local_dir.path().to_str().unwrap());
let write_cache = if enable_write_cache {
Some(
env.create_write_cache(local_store.clone(), ReadableSize::mb(10))
.await,
)
} else {
None
};
let cache = Arc::new(CacheManager::builder().write_cache(write_cache).build());
let layer = Arc::new(AccessLayer::new(
"cancelled",
PathType::Bare,
store.clone(),
env.get_puffin_manager(),
env.get_intermediate_manager(),
));
let metadata = Arc::new(sst_region_metadata());
let uncommitted =
UncommittedSsts::new(metadata.region_id, layer.clone(), Some(cache.clone()));
let cancellation = CancellationToken::new();
let signal = cancellation.clone();
let tracked = uncommitted.clone();
let schema = new_record_batch_by_range(&["a", "b"], 0, 8).schema();
let source = FlatSource::new_stream(
schema,
Box::pin(async_stream::try_stream! {
for i in 0..64 {
if tracked.num_tracked_files() >= 3 {
signal.cancel();
}
let tag = format!("{i:04}");
yield new_record_batch_by_range(&[&tag, "b"], 0, 4096);
}
}),
);
let result = layer
.write_sst_with_context(
SstWriteRequest {
index_build_inputs: None,
op_type: OperationType::Compact,
metadata,
source,
cache_manager: cache,
max_sequence: None,
sst_write_format: format,
preserve_row_sequence: false,
index_options: Default::default(),
index_config: Default::default(),
inverted_index_config: Default::default(),
fulltext_index_config: Default::default(),
bloom_filter_index_config: Default::default(),
},
&WriteOptions {
max_file_size: Some(1),
row_group_size: 8,
..Default::default()
},
&mut Metrics::new(WriteType::Compaction),
SstWriteContext {
guard: Some(Arc::new(uncommitted.clone())),
cancellation: Some(cancellation),
..Default::default()
},
)
.await;
assert!(matches!(
result,
Err(crate::error::Error::SstWriteCancelled { .. })
));
assert!(
uncommitted.num_tracked_files() >= 2,
"must cover files finalized before cancellation"
);
uncommitted.cleanup_for_test().await.unwrap();
for object_store in [&store, &local_store] {
let entries = object_store.list_with("/").recursive(true).await.unwrap();
assert!(
entries.iter().all(|entry| entry.metadata().is_dir()),
"uncommitted files remain: {entries:?}"
);
}
}
#[tokio::test]
async fn test_new_fs_cache_store() {
let root = common_test_util::temp_dir::create_temp_dir("fs-cache-store");
+350 -33
View File
@@ -19,16 +19,15 @@ use std::time::{Duration, Instant};
use common_base::readable_size::ReadableSize;
use common_telemetry::{debug, info};
use futures::AsyncWriteExt;
use object_store::ObjectStore;
use snafu::ResultExt;
use snafu::{IntoError, ResultExt};
use store_api::storage::RegionId;
use tokio::sync::mpsc::{UnboundedSender, unbounded_channel};
use tokio_util::sync::CancellationToken;
use crate::access_layer::{
EncodedSstIndexBuildParams, FilePathProvider, Metrics, OperationType, RegionFilePathFactory,
SstInfoArray, SstWriteRequest, TempFileCleaner, WriteCachePathProvider, WriteType,
new_fs_cache_store,
SstInfoArray, SstWriteRequest, TempFileCleaner, WriteCachePathProvider, new_fs_cache_store,
};
use crate::cache::file_cache::{FileCache, FileCacheRef, FileType, IndexKey, IndexValue};
use crate::cache::manifest_cache::ManifestCache;
@@ -40,8 +39,9 @@ use crate::sst::index::intermediate::IntermediateManager;
use crate::sst::index::puffin_manager::{PuffinManagerFactory, SstPuffinManager};
use crate::sst::index::registry::IndexRegistry;
use crate::sst::index::{IndexerBuilderImpl, build_index_from_parquet_bytes};
use crate::sst::parquet::writer::ParquetWriter;
use crate::sst::parquet::writer::{ParquetWriter, SstWriteContext};
use crate::sst::parquet::{SstInfo, WriteOptions};
use crate::sst::upload::{self, UploadError};
use crate::sst::{DEFAULT_WRITE_BUFFER_SIZE, DEFAULT_WRITE_CONCURRENCY};
/// Wraps the remote object store used by write cache uploads.
@@ -178,6 +178,7 @@ impl WriteCache {
///
/// Builds the SST's indexes from `data` when `index_build_params` is set and uploads them
/// with the SST.
#[allow(clippy::too_many_arguments)]
pub(crate) async fn put_and_upload_sst(
&self,
data: &bytes::Bytes,
@@ -186,10 +187,10 @@ impl WriteCache {
upload_request: SstUploadRequest,
write_buffer_size: ReadableSize,
index_build_params: Option<EncodedSstIndexBuildParams>,
) -> Result<Metrics> {
metrics: &mut Metrics,
) -> Result<()> {
let file_id = sst_info.file_id;
let region_file_id = RegionFileId::new(region_id, file_id);
let mut metrics = Metrics::new(WriteType::Flush);
// Create index key for the SST file
let parquet_key = IndexKey::new(region_id, file_id, FileType::Parquet);
@@ -275,7 +276,7 @@ impl WriteCache {
.await;
return Err(e);
}
Ok(metrics)
Ok(())
}
/// Returns the intermediate manager of the write cache.
@@ -283,13 +284,14 @@ impl WriteCache {
&self.intermediate_manager
}
/// Writes SST to the cache and then uploads it to the remote object store.
pub(crate) async fn write_and_upload_sst(
/// Preserves write ownership and cancellation through local encoding and upload.
pub(crate) async fn write_and_upload_sst_with_context(
&self,
write_request: SstWriteRequest,
upload_request: SstUploadRequest,
write_opts: &WriteOptions,
metrics: &mut Metrics,
context: SstWriteContext,
) -> Result<SstInfoArray> {
let region_id = write_request.metadata.region_id;
let override_sequence = if write_request.preserve_row_sequence {
@@ -328,7 +330,9 @@ impl WriteCache {
metrics,
)
.await
.with_file_cleaner(cleaner);
.with_file_cleaner(cleaner)
.with_write_guard(context.guard)
.with_cancellation(context.cancellation.clone());
let sst_info = match write_request.sst_write_format {
crate::sst::FormatType::PrimaryKey => {
@@ -357,13 +361,21 @@ impl WriteCache {
let op_type = write_request.op_type;
let remote_store = &upload_request.remote_store;
for sst in &sst_info {
if context
.cancellation
.as_ref()
.is_some_and(|handle| handle.is_cancelled())
{
err = Some(error::SstWriteCancelledSnafu.build());
break;
}
let parquet_key = IndexKey::new(region_id, sst.file_id, FileType::Parquet);
let parquet_path = upload_request
.dest_path_provider
.build_sst_file_path(RegionFileId::new(region_id, sst.file_id));
let start = Instant::now();
if let Err(e) = self
.upload(
.upload_with_cancellation(
parquet_key,
&parquet_path,
remote_store,
@@ -371,6 +383,7 @@ impl WriteCache {
op_type,
write_buffer_size: write_opts.write_buffer_size,
},
context.cancellation.as_ref(),
)
.await
{
@@ -387,7 +400,7 @@ impl WriteCache {
.build_index_file_path(RegionFileId::new(region_id, sst.file_id));
let start = Instant::now();
if let Err(e) = self
.upload(
.upload_with_cancellation(
puffin_key,
&puffin_path,
remote_store,
@@ -395,6 +408,7 @@ impl WriteCache {
op_type,
write_buffer_size: DEFAULT_WRITE_BUFFER_SIZE,
},
context.cancellation.as_ref(),
)
.await
{
@@ -467,10 +481,21 @@ impl WriteCache {
upload_path: &str,
remote_store: &ObjectStore,
options: UploadOptions,
) -> Result<()> {
self.upload_with_cancellation(index_key, upload_path, remote_store, options, None)
.await
}
async fn upload_with_cancellation(
&self,
index_key: IndexKey,
upload_path: &str,
remote_store: &ObjectStore,
options: UploadOptions,
cancellation: Option<&CancellationToken>,
) -> Result<()> {
let region_id = index_key.region_id;
let file_id = index_key.file_id;
let file_type = index_key.file_type;
let cache_path = self.file_cache.cache_file_path(index_key);
let start = Instant::now();
@@ -480,13 +505,14 @@ impl WriteCache {
.stat(&cache_path)
.await
.context(error::OpenDalSnafu)?;
let reader = self
let mut reader = self
.file_cache
.local_store()
.reader(&cache_path)
.reader_with(&cache_path)
.chunk(options.write_buffer_size.as_bytes().max(1) as usize)
.await
.context(error::OpenDalSnafu)?
.into_futures_async_read(0..cached_value.content_length())
.into_stream(0..cached_value.content_length())
.await
.context(error::OpenDalSnafu)?;
@@ -499,24 +525,50 @@ impl WriteCache {
.chunk(options.write_buffer_size.as_bytes() as usize)
.concurrent(DEFAULT_WRITE_CONCURRENCY)
.await
.context(error::OpenDalSnafu)?
.into_futures_async_write();
.context(error::OpenDalSnafu)?;
let bytes_written =
futures::io::copy(reader, &mut writer)
let result = async {
let bytes_written = upload::copy(
&mut reader,
&mut writer,
options.write_buffer_size.as_bytes() as usize,
cancellation,
)
.await
.map_err(|error| match error {
UploadError::Cancelled => error::SstWriteCancelledSnafu.build(),
UploadError::Read { source } => error::OpenDalSnafu.into_error(source),
UploadError::Write { source } => error::UploadSnafu {
region_id,
file_id,
file_type: index_key.file_type,
}
.into_error(std::io::Error::from(source)),
})?;
if cancellation.is_some_and(CancellationToken::is_cancelled) {
return error::SstWriteCancelledSnafu.fail();
}
writer
.close()
.await
.map_err(std::io::Error::from)
.context(error::UploadSnafu {
region_id,
file_id,
file_type,
file_type: index_key.file_type,
})?;
// Must close to upload all data.
writer.close().await.context(error::UploadSnafu {
region_id,
file_id,
file_type,
})?;
Ok(bytes_written)
}
.await;
let bytes_written = match result {
Ok(bytes_written) => bytes_written,
Err(error) => {
if let Err(abort_error) = writer.abort().await {
common_telemetry::warn!(abort_error; "Failed to abort SST upload, region: {}, file: {}", region_id, file_id);
}
return Err(error);
}
};
UPLOAD_BYTES_TOTAL.inc_by(bytes_written);
@@ -633,7 +685,7 @@ mod tests {
use store_api::storage::FileId;
use super::*;
use crate::access_layer::OperationType;
use crate::access_layer::{OperationType, WriteType};
use crate::cache::file_cache::IndexValue;
use crate::cache::test_util::{assert_parquet_metadata_equal, new_fs_store};
use crate::cache::{CacheManager, CacheStrategy};
@@ -647,6 +699,253 @@ mod tests {
sst_file_handle_with_file_id, sst_region_metadata,
};
struct CancellingUploadWriter {
inner: object_store::layers::mock::oio::Writer,
cancellation: CancellationToken,
bytes_written: Arc<std::sync::atomic::AtomicUsize>,
aborted: Arc<std::sync::atomic::AtomicBool>,
}
impl object_store::layers::mock::oio::Write for CancellingUploadWriter {
async fn write(&mut self, buffer: object_store::Buffer) -> object_store::Result<()> {
let len = buffer.len();
self.inner.write(buffer).await?;
self.bytes_written
.fetch_add(len, std::sync::atomic::Ordering::Relaxed);
self.cancellation.cancel();
Ok(())
}
async fn close(
&mut self,
) -> object_store::layers::mock::Result<object_store::layers::mock::Metadata> {
self.inner.close().await
}
async fn abort(&mut self) -> object_store::Result<()> {
self.aborted
.store(true, std::sync::atomic::Ordering::Relaxed);
self.inner.abort().await
}
}
#[tokio::test]
async fn test_cancel_upload_aborts_incomplete_object() {
use object_store::layers::mock::MockLayerBuilder;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
let env = TestEnv::new().await;
let local_store = ObjectStore::new(Memory::default()).unwrap();
let cancellation = CancellationToken::new();
let bytes_written = Arc::new(AtomicUsize::new(0));
let aborted = Arc::new(AtomicBool::new(false));
let signal = cancellation.clone();
let bytes = bytes_written.clone();
let abort = aborted.clone();
let layer = MockLayerBuilder::default()
.writer_factory(Arc::new(move |_, _, inner| {
Box::new(CancellingUploadWriter {
inner,
cancellation: signal.clone(),
bytes_written: bytes.clone(),
aborted: abort.clone(),
})
}))
.build()
.unwrap();
let remote_store = ObjectStore::new(Memory::default()).unwrap().layer(layer);
let cache = env
.create_write_cache(local_store.clone(), ReadableSize::mb(10))
.await;
let key = IndexKey::new(RegionId::new(1024, 1), FileId::random(), FileType::Parquet);
let data = vec![42; 1024 * 1024];
local_store
.write(&cache.file_cache.cache_file_path(key), data.clone())
.await
.unwrap();
let result = cache
.upload_with_cancellation(
key,
"cancelled.parquet",
&remote_store,
UploadOptions {
op_type: OperationType::Compact,
write_buffer_size: ReadableSize::kb(1),
},
Some(&cancellation),
)
.await;
assert!(matches!(
result,
Err(error::Error::SstWriteCancelled { .. })
));
assert!(aborted.load(Ordering::Relaxed));
let bytes = bytes_written.load(Ordering::Relaxed);
assert!(
bytes > 0 && bytes < data.len(),
"wrote {bytes} bytes before cancelling"
);
assert!(!remote_store.exists("cancelled.parquet").await.unwrap());
}
struct FailingUploadWriter {
inner: object_store::layers::mock::oio::Writer,
fail_close: bool,
fail_abort: bool,
successful_writes: usize,
}
impl object_store::layers::mock::oio::Write for FailingUploadWriter {
async fn write(&mut self, bytes: object_store::Buffer) -> object_store::Result<()> {
if !self.fail_close && self.successful_writes == 1 {
return Err(object_store::Error::new(
object_store::ErrorKind::NotFound,
"injected write failure",
));
}
self.inner.write(bytes).await?;
self.successful_writes += 1;
Ok(())
}
async fn close(&mut self) -> object_store::Result<object_store::layers::mock::Metadata> {
Err(object_store::Error::new(
object_store::ErrorKind::NotFound,
"injected close failure",
))
}
async fn abort(&mut self) -> object_store::Result<()> {
if self.fail_abort {
return Err(object_store::Error::new(
object_store::ErrorKind::Unexpected,
"injected abort failure",
));
}
self.inner.abort().await
}
}
#[rstest::rstest]
#[case::write(false, false)]
#[case::close(true, false)]
#[case::write_and_abort(false, true)]
#[tokio::test]
async fn test_upload_error_preserves_file_context(
#[case] fail_close: bool,
#[case] fail_abort: bool,
) {
use object_store::layers::mock::{MockLayerBuilder, ObservedWriter, WriterObservations};
let env = TestEnv::new().await;
let local_store = ObjectStore::new(Memory::default()).unwrap();
let observations = Arc::new(std::sync::Mutex::new(WriterObservations::default()));
let observed = observations.clone();
let layer = MockLayerBuilder::default()
.writer_factory(Arc::new(move |_, _, inner| {
Box::new(ObservedWriter::new(
Box::new(FailingUploadWriter {
inner,
fail_close,
fail_abort,
successful_writes: 0,
}),
observed.clone(),
))
}))
.build()
.unwrap();
let remote_store = ObjectStore::new(Memory::default()).unwrap().layer(layer);
let cache = env
.create_write_cache(local_store.clone(), ReadableSize::mb(10))
.await;
let key = IndexKey::new(RegionId::new(1024, 1), FileId::random(), FileType::Parquet);
local_store
.write(&cache.file_cache.cache_file_path(key), vec![42; 4096])
.await
.unwrap();
assert!(!cache.file_cache.contains_key(&key));
let err = cache
.upload(
key,
"failed.parquet",
&remote_store,
UploadOptions {
op_type: OperationType::Compact,
write_buffer_size: ReadableSize::kb(1),
},
)
.await
.unwrap_err();
assert!(!err.is_object_not_found());
assert!(err.may_have_persisted_manifest_update());
match err {
error::Error::Upload {
region_id,
file_id,
file_type,
error,
..
} => {
assert_eq!(key.region_id, region_id);
assert_eq!(key.file_id, file_id);
assert_eq!(key.file_type, file_type);
assert_eq!(std::io::ErrorKind::NotFound, error.kind());
let message = if fail_close {
"injected close failure"
} else {
"injected write failure"
};
assert!(error.to_string().contains(message));
}
err => panic!("expected Upload error, got {err:?}"),
}
assert!(!cache.file_cache.contains_key(&key));
assert!(!remote_store.exists("failed.parquet").await.unwrap());
let observations = observations.lock().unwrap();
// The write failure follows one completed chunk, so partial progress is exercised.
assert_eq!(
vec![1024; if fail_close { 4 } else { 2 }],
observations.write_sizes
);
assert_eq!(1, observations.abort_calls);
assert_eq!(usize::from(fail_close), observations.close_calls);
}
#[tokio::test]
async fn test_upload_local_read_error() {
use object_store::layers::mock::MockLayerBuilder;
let env = TestEnv::new().await;
// The unit reader rejects reads after stat and reader creation succeed.
let layer = MockLayerBuilder::default()
.reader_factory(Arc::new(|_, _, _| Box::new(())))
.build()
.unwrap();
let local_store = ObjectStore::new(Memory::default()).unwrap().layer(layer);
let remote_store = ObjectStore::new(Memory::default()).unwrap();
let cache = env
.create_write_cache(local_store.clone(), ReadableSize::mb(10))
.await;
let key = IndexKey::new(RegionId::new(1024, 1), FileId::random(), FileType::Parquet);
local_store
.write(&cache.file_cache.cache_file_path(key), vec![42; 4096])
.await
.unwrap();
let err = cache
.upload(
key,
"failed.parquet",
&remote_store,
UploadOptions {
op_type: OperationType::Compact,
write_buffer_size: ReadableSize::kb(1),
},
)
.await
.unwrap_err();
assert!(matches!(err, error::Error::OpenDal { .. }));
assert!(!remote_store.exists("failed.parquet").await.unwrap());
}
struct RedirectUploadStoreWrapper {
target_store: ObjectStore,
last_op_type: Mutex<Option<OperationType>>,
@@ -776,7 +1075,13 @@ mod tests {
// Write to cache and upload sst to mock remote store
let mut metrics = Metrics::new(WriteType::Flush);
let mut sst_infos = write_cache
.write_and_upload_sst(write_request, upload_request, &write_opts, &mut metrics)
.write_and_upload_sst_with_context(
write_request,
upload_request,
&write_opts,
&mut metrics,
SstWriteContext::default(),
)
.await
.unwrap();
let sst_info = sst_infos.remove(0);
@@ -890,7 +1195,13 @@ mod tests {
let mut metrics = Metrics::new(WriteType::Flush);
let mut sst_infos = write_cache
.write_and_upload_sst(write_request, upload_request, &write_opts, &mut metrics)
.write_and_upload_sst_with_context(
write_request,
upload_request,
&write_opts,
&mut metrics,
SstWriteContext::default(),
)
.await
.unwrap();
let sst_info = sst_infos.remove(0);
@@ -983,7 +1294,13 @@ mod tests {
let mut metrics = Metrics::new(WriteType::Flush);
write_cache
.write_and_upload_sst(write_request, upload_request, &write_opts, &mut metrics)
.write_and_upload_sst_with_context(
write_request,
upload_request,
&write_opts,
&mut metrics,
SstWriteContext::default(),
)
.await
.unwrap_err();
let atomic_write_dir = write_cache_dir.path().join(ATOMIC_WRITE_DIR);
File diff suppressed because it is too large Load Diff
+23 -6
View File
@@ -28,19 +28,22 @@ use std::collections::{BTreeMap, HashMap, HashSet};
use std::sync::Arc;
use std::sync::atomic::AtomicU64;
use common_base::cancellation::{CancellableFuture, CancellationHandle};
use common_time::Timestamp;
use partition::PartitionRuleRef;
use snafu::{OptionExt, ensure};
use store_api::metadata::RegionMetadataRef;
use store_api::storage::RegionId;
use tokio_util::sync::CancellationToken;
use crate::access_layer::AccessLayerRef;
use crate::cache::CacheManagerRef;
use crate::config::MitoConfig;
use crate::error::CompactionCancelledSnafu;
use crate::error::{InvalidMultiRegionCompactionSnafu, Result};
use crate::region::options::RegionOptions;
use crate::sst::file::{FileMeta, RegionFileId};
use crate::sst::index::handler::IndexKindProviderRef;
use crate::sst::index::registry::IndexRegistry;
use crate::sst::parquet::SstInfo;
use crate::sst::parquet::writer::SstWriteGuard;
@@ -78,11 +81,13 @@ pub struct MultiRegionCompactionPlan {
/// Shared storage services and attempt-owned output resources.
pub struct MultiRegionCompactionContext {
/// Optional enterprise index implementation. Each routed output builds its own state.
pub index_kind_provider: Option<IndexKindProviderRef>,
pub access_layer: AccessLayerRef,
pub cache: CacheManagerRef,
pub config: Arc<MitoConfig>,
pub protection: Arc<dyn SstWriteGuard>,
pub cancellation: Arc<CancellationHandle>,
pub cancellation: CancellationToken,
}
/// Source I/O and lossless output accounting, excluding footer and query reads.
@@ -127,8 +132,18 @@ pub async fn compact_regions(
context: MultiRegionCompactionContext,
) -> Result<MultiRegionCompactionOutput> {
let metadata = validate_plan(&plan)?;
// Invalid registrations still fail, but unavailable sketches only warn so
// compaction can continue after a downgrade.
let registry =
IndexRegistry::from_config(&context.config, context.index_kind_provider.clone())?;
for target in plan.targets.values() {
registry.warn_missing_compaction_handlers(
&target.metadata,
plan.sources.iter().chain(target.inputs.values()),
);
}
if context.cancellation.is_cancelled() {
return crate::error::CompactionCancelledSnafu.fail();
return CompactionCancelledSnafu.fail();
}
let cancellation = context.cancellation.clone();
let execution = async move {
@@ -137,9 +152,11 @@ pub async fn compact_regions(
source::SharedSource::build(&plan, &context, metadata, counters.clone()).await?;
worker::execute(plan, context, source, counters).await
};
CancellableFuture::new(execution, cancellation)
.await
.map_err(|_| crate::error::CompactionCancelledSnafu.build())?
tokio::select! {
biased;
_ = cancellation.cancelled() => crate::error::CompactionCancelledSnafu.fail(),
result = execution => result,
}
}
fn validate_plan(plan: &MultiRegionCompactionPlan) -> Result<RegionMetadataRef> {
@@ -43,6 +43,8 @@ pub(crate) struct MemoryLimits {
pub(crate) batch: usize,
pub(crate) group: usize,
pub(crate) index: usize,
/// Reuses index allocation only when the optional working set fits admission.
pub(crate) extension_index_memory_limit: Option<usize>,
pub(crate) writer: SstWriteLimits,
pub(crate) estimated: u64,
}
@@ -60,6 +62,7 @@ impl MemoryLimits {
batch,
group: plan.memory_limit / 16,
index: plan.memory_limit / (64 * plan.targets.len()),
extension_index_memory_limit: None,
writer: SstWriteLimits {
// Parquet 59 preallocates a 1 MiB bit writer for each of the
// timestamp/sequence delta encoders. Dictionary interner tables
@@ -78,6 +81,7 @@ impl MemoryLimits {
plan: &MultiRegionCompactionPlan,
context: &MultiRegionCompactionContext,
footers: &[Arc<ParquetMetaData>],
extension_targets: usize,
) -> Result<()> {
self.check_upload_minimum(context)?;
let mut extra_delta = 0;
@@ -105,7 +109,12 @@ impl MemoryLimits {
),
}
);
self.estimated = bytes;
// Optional indexes must not turn an admitted data compaction into a
// resource failure. Reserve all resident target states together or skip.
let admission =
admit_extension_indexes(bytes, plan.memory_limit, self.index, extension_targets);
self.extension_index_memory_limit = admission.limit;
self.estimated = admission.estimated;
Ok(())
}
@@ -212,10 +221,83 @@ fn reader_bytes(footer: &ParquetMetaData) -> u64 {
.iter()
.map(|group| {
(group.total_byte_size().max(0) as u64)
.saturating_mul(2)
.saturating_mul(RETAINED_AND_FINISH_SCRATCH_FACTOR)
.saturating_add(group.compressed_size().max(0) as u64)
})
.max()
.unwrap_or(0);
pages.saturating_add(footer.memory_size() as u64)
}
/// Retained state and temporary finish allocations share the admission budget.
const RETAINED_AND_FINISH_SCRATCH_FACTOR: u64 = 2;
#[derive(Debug, PartialEq, Eq)]
struct ExtensionIndexAdmission {
limit: Option<usize>,
estimated: u64,
}
/// Reserves all target states together, or preserves the admitted data budget.
fn admit_extension_indexes(
base: u64,
budget: usize,
index: usize,
targets: usize,
) -> ExtensionIndexAdmission {
let with_extension_indexes = base.saturating_add(
(index as u64)
.saturating_mul(RETAINED_AND_FINISH_SCRATCH_FACTOR)
.saturating_mul(targets as u64),
);
if targets > 0 && index > 0 && with_extension_indexes <= budget as u64 {
ExtensionIndexAdmission {
limit: Some(index),
estimated: with_extension_indexes,
}
} else {
ExtensionIndexAdmission {
limit: None,
estimated: base,
}
}
}
#[cfg(test)]
mod tests {
use super::{ExtensionIndexAdmission, admit_extension_indexes};
#[test]
fn test_extension_indexes_do_not_reject_admitted_data() {
// Both target writers are resident. Insufficient extra room leaves the
// already-admitted data budget unchanged and explicitly disables optional indexes.
assert_eq!(
admit_extension_indexes(900, 1000, 30, 2),
ExtensionIndexAdmission {
limit: None,
estimated: 900
}
);
assert_eq!(
admit_extension_indexes(880, 1000, 30, 2),
ExtensionIndexAdmission {
limit: Some(30),
estimated: 1000
}
);
assert_eq!(
admit_extension_indexes(900, 1000, 30, 0),
ExtensionIndexAdmission {
limit: None,
estimated: 900
}
);
assert_eq!(
admit_extension_indexes(900, 1000, 0, 2),
ExtensionIndexAdmission {
limit: None,
estimated: 900
}
);
}
}
@@ -15,6 +15,7 @@ use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
use arrow_schema::extension::EXTENSION_TYPE_METADATA_KEY;
use common_base::readable_size::ReadableSize;
use common_time::Timestamp;
use datatypes::arrow::array::{
Array, ArrayRef, BinaryArray, GenericByteArray, GenericByteDictionaryBuilder, UInt64Array,
@@ -38,9 +39,10 @@ use crate::compaction::multi_region::memory::{BATCH_SIZE, MemoryLimits};
use crate::compaction::multi_region::{
MultiRegionCompactionContext, MultiRegionCompactionPlan, MultiRegionTarget, SourceCounters,
};
use crate::config::MemoryThreshold;
use crate::error::{
ComputeArrowSnafu, InvalidMultiRegionCompactionSnafu, MultiRegionCompactionResourceSnafu,
NewRecordBatchSnafu, Result,
ComputeArrowSnafu, ExternalSnafu, InvalidMultiRegionCompactionSnafu,
MultiRegionCompactionResourceSnafu, NewRecordBatchSnafu, Result,
};
use crate::read::compat::FlatCompatBatch;
use crate::read::flat_merge::FlatMergeReader;
@@ -49,6 +51,9 @@ use crate::read::read_columns::ReadColumns;
use crate::read::{BoxedRecordBatchStream, timestamp_array_to_i64_slice};
use crate::sst::file::{FileHandle, FileMeta};
use crate::sst::file_purger::NoopFilePurger;
use crate::sst::index::IndexBuildType;
use crate::sst::index::handler::PlanContext;
use crate::sst::index::registry::{IndexBuildPlan, IndexRegistry};
use crate::sst::parquet::flat_format::{
primary_key_column_index, sequence_column_index, time_index_column_index,
};
@@ -108,8 +113,9 @@ pub(crate) struct SharedSource {
partition_rule: PartitionRuleRef,
window: (Timestamp, Timestamp),
pub(crate) limits: MemoryLimits,
pub(crate) index_plans: BTreeMap<RegionId, Arc<IndexBuildPlan>>,
peak_group_bytes: AtomicU64,
cancellation: Arc<common_base::cancellation::CancellationHandle>,
cancellation: CancellationToken,
stop: CancellationToken,
counters: Arc<SourceCounters>,
}
@@ -205,7 +211,47 @@ impl SharedSource {
)?;
let schema = mapper.input_arrow_schema(false);
let mut limits = MemoryLimits::new(plan, &schema)?;
limits.admit(plan, context, &footers)?;
let mut inverted = context.config.inverted_index.clone();
inverted.mem_threshold_on_create =
admitted_index_threshold(inverted.mem_threshold_on_create(), limits.index);
let mut fulltext = context.config.fulltext_index.clone();
fulltext.mem_threshold_on_create =
admitted_index_threshold(Some(fulltext.mem_threshold_on_create()), limits.index);
let mut bloom = context.config.bloom_filter_index.clone();
bloom.mem_threshold_on_create =
admitted_index_threshold(bloom.mem_threshold_on_create(), limits.index);
let registry = IndexRegistry::new(inverted, fulltext, bloom)
.with_provider(context.index_kind_provider.clone())
.with_context(|_| ExternalSnafu {
context: "registering index handlers".to_string(),
})?;
let mut index_plans = plan
.targets
.iter()
.map(|(id, target)| {
let work = registry.plan(&PlanContext {
metadata: &target.metadata,
index_options: &target.options.index_options,
build_type: IndexBuildType::Compact,
existing_indexes: &[],
});
(*id, Arc::new(work))
})
.collect::<BTreeMap<_, _>>();
limits.admit(
plan,
context,
&footers,
index_plans
.values()
.filter(|work| work.entries().any(|entry| !entry.kind.is_builtin()))
.count(),
)?;
if limits.extension_index_memory_limit.is_none() {
for (region_id, work) in &mut index_plans {
Arc::make_mut(work).omit_extensions_for_budget(*region_id);
}
}
// Compute routing/version annotations on bounded reader batches, but
// keep physical __sequence as the merge key. The annotations are not
// persisted and fixed-position time/PK/sequence/op columns stay last.
@@ -233,6 +279,7 @@ impl SharedSource {
Timestamp::new_second(plan.window_start + plan.window_seconds),
),
limits,
index_plans,
peak_group_bytes: AtomicU64::new(0),
cancellation: context.cancellation.clone(),
stop: CancellationToken::new(),
@@ -752,3 +799,7 @@ fn key_at(batch: &RecordBatch, row: usize) -> Result<&[u8]> {
);
Ok(values.value(index))
}
fn admitted_index_threshold(configured: Option<usize>, limit: usize) -> MemoryThreshold {
MemoryThreshold::Size(ReadableSize(configured.unwrap_or(limit).min(limit) as u64))
}
+170 -2
View File
@@ -15,6 +15,7 @@ use std::sync::{Arc, Mutex};
use std::time::Duration;
use api::v1::{OpType, SemanticType};
use common_error::ext::BoxedError;
use datatypes::arrow::array::{
Array, ArrayRef, BinaryArray, BinaryDictionaryBuilder, BooleanArray, DictionaryArray,
StringArray, StringDictionaryBuilder, TimestampMillisecondArray, UInt8Array, UInt64Array,
@@ -48,7 +49,9 @@ use crate::error::InvalidMultiRegionCompactionSnafu;
use crate::read::FlatSource;
use crate::sst::file::{FileHandle, RegionFileId};
use crate::sst::file_purger::NoopFilePurger;
use crate::sst::index::handler::{IndexKindHandler, IndexKindProvider, PlanContext, PlannedIndex};
use crate::sst::index::intermediate::IntermediateManager;
use crate::sst::index::kind::{ExtensionIndexKind, IndexKind};
use crate::sst::index::puffin_manager::PuffinManagerFactory;
use crate::sst::parquet::WriteOptions;
use crate::sst::parquet::flat_format::{
@@ -273,11 +276,12 @@ impl Fixture {
});
(
MultiRegionCompactionContext {
index_kind_provider: None,
access_layer: self.layer.clone(),
cache: Arc::new(CacheManager::default()),
config: self.config.clone(),
protection: protection.clone(),
cancellation: Arc::new(CancellationHandle::default()),
cancellation: CancellationToken::new(),
},
protection,
)
@@ -2002,7 +2006,7 @@ async fn test_interrupted_indexed_worker_cleans_tantivy_files(#[case] fail_sibli
}
}
struct CancelBeforeCreate(Arc<CancellationHandle>);
struct CancelBeforeCreate(CancellationToken);
#[async_trait::async_trait]
impl SstWriteGuard for CancelBeforeCreate {
@@ -2327,6 +2331,7 @@ async fn test_limited_writer_fails_instead_of_publishing_over_budget(#[case] kin
&context,
&limits,
plan.max_output_file_size,
Arc::default(),
)
.write(source)
.await
@@ -2455,3 +2460,166 @@ async fn test_invalid_plan_is_rejected_before_creating_outputs(
);
assert!(protection.files.lock().unwrap().is_empty());
}
#[derive(Debug)]
struct InvalidOptionalIndexHandler;
impl IndexKindProvider for InvalidOptionalIndexHandler {
fn handlers(&self) -> Vec<Arc<dyn IndexKindHandler>> {
vec![Arc::new(Self)]
}
}
impl IndexKindHandler for InvalidOptionalIndexHandler {
fn validate(&self, context: &PlanContext<'_>) -> std::result::Result<(), BoxedError> {
self.plan(context).map(|_| ())
}
fn kinds(&self) -> &[IndexKind] {
&[IndexKind::Extension(ExtensionIndexKind::Hll)]
}
fn plan(
&self,
context: &PlanContext<'_>,
) -> std::result::Result<Option<Arc<dyn PlannedIndex>>, BoxedError> {
assert!(
context.metadata.column_metadatas[0]
.column_schema
.hll_options()
.is_err()
);
Err(BoxedError::new(
crate::error::InvalidConfigSnafu {
reason: "invalid optional index configuration",
}
.build(),
))
}
}
#[derive(Debug, Default)]
struct ConflictingRegistrationProvider(std::sync::atomic::AtomicUsize);
impl IndexKindProvider for ConflictingRegistrationProvider {
fn handlers(&self) -> Vec<Arc<dyn IndexKindHandler>> {
// Preflight succeeds; source preparation must propagate its own failure too.
let calls = self.0.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let handler: Arc<dyn IndexKindHandler> = Arc::new(InvalidOptionalIndexHandler);
if calls == 0 {
vec![handler]
} else {
vec![handler.clone(), handler]
}
}
}
#[tokio::test]
async fn test_source_index_registration_failure_does_not_fall_back() {
let fixture = Fixture::new(PrimaryKeyEncoding::Dense, FormatType::Flat, 0).await;
let (mut context, protection) = fixture.context(None);
context.index_kind_provider = Some(Arc::new(ConflictingRegistrationProvider::default()));
let error = compact_regions(fixture.plan(2), context)
.await
.err()
.expect("conflicting registration must fail");
assert!(
format!("{error:?}").contains("registering index handlers"),
"unexpected registration error: {error:?}"
);
assert!(protection.files.lock().unwrap().is_empty());
}
#[tokio::test]
async fn test_invalid_optional_index_options_do_not_block_routed_compaction() {
let fixture = Fixture::new(PrimaryKeyEncoding::Dense, FormatType::Flat, 0).await;
for invalid_value in ["missing-column", "bad-capacity"] {
let mut plan = fixture.plan(2);
for target in plan.targets.values_mut() {
Arc::make_mut(&mut target.metadata).column_metadatas[0]
.column_schema
.mut_metadata()
.insert(datatypes::schema::HLL_KEY.into(), invalid_value.into());
}
let (mut context, _) = fixture.context(None);
context.index_kind_provider = Some(Arc::new(InvalidOptionalIndexHandler));
let output = compact_regions(plan, context).await.unwrap();
assert_eq!(output.stats.source_rows, output.stats.output_rows);
assert!(output.stats.output_rows > 0);
assert!(
output
.files
.values()
.flatten()
.all(|file| file
.indexes
.iter()
.all(|index| index.created_indexes.iter().all(|kind| !matches!(
kind,
crate::sst::file::IndexType::HllIndex
| crate::sst::file::IndexType::KllIndex
| crate::sst::file::IndexType::MgIndex
))))
);
}
}
#[tokio::test]
async fn test_missing_index_handler_does_not_block_routed_compaction() {
use crate::sst::file::{ColumnIndexMetadata, IndexType};
let fixture = Fixture::new(PrimaryKeyEncoding::Dense, FormatType::Flat, 0).await;
for required_by in ["schema", "file", "column", "target"] {
let mut plan = fixture.plan(2);
match required_by {
"schema" => {
for target in plan.targets.values_mut() {
Arc::make_mut(&mut target.metadata).column_metadatas[0]
.column_schema
.set_hll_options(&datatypes::schema::HllOptions::default())
.unwrap();
}
}
"file" => plan.sources[0].available_indexes.push(IndexType::HllIndex),
"column" => plan.sources[0].indexes.push(ColumnIndexMetadata {
column_id: 0,
created_indexes: [IndexType::HllIndex].into_iter().collect(),
..Default::default()
}),
_ => {
plan.targets
.values_mut()
.next()
.unwrap()
.inputs
.values_mut()
.next()
.unwrap()
.available_indexes
.push(IndexType::HllIndex);
}
}
let (context, _) = fixture.context(None);
let output = compact_regions(plan, context)
.await
.unwrap_or_else(|error| panic!("{required_by}: {error}"));
assert_eq!(output.stats.source_rows, output.stats.output_rows);
assert!(output.stats.output_rows > 0);
assert!(!output.files.is_empty());
for file in output.files.values().flatten() {
assert!(file.num_rows > 0);
assert!(file.available_indexes.iter().all(|kind| !matches!(
kind,
IndexType::HllIndex | IndexType::KllIndex | IndexType::MgIndex
)));
assert!(
file.indexes
.iter()
.all(|index| index.created_indexes.iter().all(|kind| !matches!(
kind,
IndexType::HllIndex | IndexType::KllIndex | IndexType::MgIndex
)))
);
}
}
}
@@ -55,6 +55,14 @@ pub(crate) async fn execute(
senders.insert(id, sender);
let schema = source.schema();
let limits = source.limits.clone();
let index_plan =
source
.index_plans
.get(&id)
.cloned()
.context(InvalidMultiRegionCompactionSnafu {
reason: "Missing index plan for compaction target",
})?;
let plan = plan.clone();
let context = context.clone();
workers.push(AbortOnDropHandle::new(common_runtime::spawn_compact(
@@ -76,6 +84,7 @@ pub(crate) async fn execute(
&context,
&limits,
plan.max_output_file_size,
index_plan,
)
.write(input)
.await?;
+27 -25
View File
@@ -16,23 +16,27 @@ use common_base::readable_size::ReadableSize;
use partition::expr::PartitionExpr;
use snafu::{ResultExt, ensure};
use store_api::codec::PrimaryKeyEncoding;
use tokio_util::sync::CancellationToken;
use crate::access_layer::{Metrics, OperationType, SstWriteRequest, WriteType};
use crate::compaction::multi_region::memory::{self, MemoryLimits};
use crate::compaction::multi_region::{MultiRegionCompactionContext, MultiRegionTarget};
use crate::config::MemoryThreshold;
use crate::error::{ComputeArrowSnafu, Result};
use crate::read::FlatSource;
use crate::sst::FormatType;
use crate::sst::file::FileMeta;
use crate::sst::index::build::IndexBuildInputs;
use crate::sst::index::registry::IndexBuildPlan;
use crate::sst::parquet::metadata::extract_primary_key_range;
use crate::sst::parquet::parallel_writer::EncodeRuntime;
use crate::sst::parquet::writer::SstWriteContext;
use crate::sst::parquet::{SstInfo, WriteOptions};
pub(crate) struct TargetWriter<'a> {
target: &'a MultiRegionTarget,
context: &'a MultiRegionCompactionContext,
limits: &'a MemoryLimits,
index_plan: Arc<IndexBuildPlan>,
max_file_size: usize,
sequence: Option<NonZeroU64>,
preserve_row_sequence: bool,
@@ -44,6 +48,7 @@ impl<'a> TargetWriter<'a> {
context: &'a MultiRegionCompactionContext,
limits: &'a MemoryLimits,
max_file_size: usize,
index_plan: Arc<IndexBuildPlan>,
) -> Self {
let sequence = crate::sst::file::known_max_input_sequence(target.inputs.values());
let preserve_row_sequence = target.options.preserve_row_sequence
@@ -55,6 +60,7 @@ impl<'a> TargetWriter<'a> {
target,
context,
limits,
index_plan,
max_file_size,
sequence,
preserve_row_sequence,
@@ -71,13 +77,14 @@ impl<'a> TargetWriter<'a> {
let infos = self
.context
.access_layer
.write_sst_with_guard(
.write_sst_with_context(
request,
&self.options(),
&mut metrics,
crate::sst::parquet::writer::SstWriteContext {
guard: self.context.protection.clone(),
limits: self.limits.writer,
SstWriteContext {
guard: Some(self.context.protection.clone()),
limits: Some(self.limits.writer),
..Default::default()
},
)
.await?;
@@ -96,16 +103,19 @@ impl<'a> TargetWriter<'a> {
fn request(&self, source: FlatSource) -> Result<SstWriteRequest> {
let config = &self.context.config;
let mut inverted = config.inverted_index.clone();
inverted.mem_threshold_on_create = self.index_threshold(inverted.mem_threshold_on_create());
let mut fulltext = config.fulltext_index.clone();
fulltext.mem_threshold_on_create =
self.index_threshold(Some(fulltext.mem_threshold_on_create()));
let mut bloom = config.bloom_filter_index.clone();
bloom.mem_threshold_on_create = self.index_threshold(bloom.mem_threshold_on_create());
// The shared source plan already applies the admitted index thresholds.
let source = output_projection(self.target, source, self.context.cancellation.clone())?;
let index_build_inputs = Some(IndexBuildInputs {
output_rows: None,
plan: self.index_plan.clone(),
input_puffin_manager: self.context.access_layer.build_puffin_manager(),
// Routing and file rollover change coverage. Consume only actual output rows.
inputs: Arc::from([]),
can_merge_inputs: false,
memory_limit: self.limits.extension_index_memory_limit,
});
Ok(SstWriteRequest {
index_build_inputs: None,
index_build_inputs,
op_type: OperationType::Compact,
metadata: self.target.metadata.clone(),
source,
@@ -121,20 +131,12 @@ impl<'a> TargetWriter<'a> {
preserve_row_sequence: self.preserve_row_sequence,
index_options: self.target.options.index_options.clone(),
index_config: config.index.clone(),
inverted_index_config: inverted,
fulltext_index_config: fulltext,
bloom_filter_index_config: bloom,
inverted_index_config: config.inverted_index.clone(),
fulltext_index_config: config.fulltext_index.clone(),
bloom_filter_index_config: config.bloom_filter_index.clone(),
})
}
fn index_threshold(&self, configured: Option<usize>) -> MemoryThreshold {
MemoryThreshold::Size(ReadableSize(
configured
.unwrap_or(self.limits.index)
.min(self.limits.index) as u64,
))
}
fn options(&self) -> WriteOptions {
WriteOptions {
write_buffer_size: ReadableSize(self.limits.batch as u64),
@@ -207,7 +209,7 @@ impl<'a> TargetWriter<'a> {
fn output_projection(
target: &MultiRegionTarget,
mut source: FlatSource,
cancellation: Arc<common_base::cancellation::CancellationHandle>,
cancellation: CancellationToken,
) -> Result<FlatSource> {
let projection: Vec<_> = source
.schema()
+4 -4
View File
@@ -31,7 +31,7 @@ use crate::compaction::scheduler::{
};
use crate::compaction::task::CompactionTask;
use crate::compaction::unit::CompactionUnit;
use crate::error::{self, Error};
use crate::error::{self, Error, Result};
use crate::metrics::INFLIGHT_COMPACTION_COUNT;
use crate::region::ManifestContextRef;
use crate::request::{
@@ -260,7 +260,7 @@ impl CompactionScheduler {
region: CompactionRegion,
units: Vec<CompactionUnit>,
reserved: CompactingFiles,
) -> CompactionPhase {
) -> Result<CompactionPhase> {
// Memory admission may have removed oversized units from the picker output.
// Report only the inputs that this local cycle will actually execute.
if let Some(info) = self
@@ -286,7 +286,7 @@ impl CompactionScheduler {
made_progress: false,
cancellation_requested: false,
};
let context = CompactionContext::from(&region);
let context = CompactionContext::try_from(&region)?;
// Planning is complete; unit tasks must not pin the other units' inputs.
drop(region);
for unit in units {
@@ -320,7 +320,7 @@ impl CompactionScheduler {
});
}
local.unit_states = local.units.values().cloned().collect();
CompactionPhase::Units(local)
Ok(CompactionPhase::Units(local))
}
/// Returns local unit state only while the region is in a local execution phase.
@@ -629,7 +629,7 @@ impl CompactionScheduler {
compaction_region,
units,
files,
)))
)?))
}
fn exceeds_compaction_memory_limit(&self, estimated_bytes: u64) -> Option<u64> {
+1 -1
View File
@@ -2519,7 +2519,7 @@ async fn test_request_cancel_state_transitions() {
let state = status.start_local_task();
assert_eq!(status.request_cancel(), RequestCancelResult::CancelIssued);
assert!(state.cancel_handle().is_cancelled());
assert!(state.cancel_token().is_cancelled());
assert_eq!(
status.request_cancel(),
RequestCancelResult::AlreadyCancelling
+13 -15
View File
@@ -15,7 +15,6 @@
use std::fmt::{Debug, Formatter};
use std::sync::Arc;
use common_base::cancellation::CancellableFuture;
use common_memory_manager::OnExhaustedPolicy;
use common_telemetry::error;
use futures::FutureExt;
@@ -91,25 +90,24 @@ impl CompactionTask {
None
} else {
let _wait_timer = crate::metrics::COMPACTION_MEMORY_WAIT.start_timer();
let cancellation = self.state.cancel_token();
Some(
CancellableFuture::new(
self.memory_manager
.acquire_with_policy(bytes, self.memory_policy),
self.state.cancel_handle(),
)
.await
.map_err(|_| CompactionCancelledSnafu.build())?
.context(CompactionMemoryExhaustedSnafu {
region_id,
policy: format!("{:?}", self.memory_policy),
})?,
tokio::select! {
biased;
_ = cancellation.cancelled() => return CompactionCancelledSnafu.fail(),
memory = self.memory_manager.acquire_with_policy(bytes, self.memory_policy) => memory,
}
.context(CompactionMemoryExhaustedSnafu {
region_id,
policy: format!("{:?}", self.memory_policy),
})?,
)
};
let _timer = COMPACTION_STAGE_ELAPSED
.with_label_values(&["merge"])
.start_timer();
let compactor = DefaultCompactor::with_cancel_handle(
self.state.cancel_handle(),
let compactor = DefaultCompactor::with_cancel_token(
self.state.cancel_token(),
self.uncommitted.clone(),
);
let context = self.compaction_context.clone();
@@ -242,7 +240,7 @@ mod tests {
let mut task = CompactionTask {
state: CancellableTaskState::new(),
execution: CompactionExecution::for_test(7),
compaction_context: CompactionContext::from(&region),
compaction_context: CompactionContext::try_from(&region).unwrap(),
request_sender,
listener: WorkerListener::new(Some(Arc::new(PanicOnUnitMergeBegin))),
unit: CompactionUnit {
+57 -5
View File
@@ -132,8 +132,8 @@ use snafu::{OptionExt, ResultExt, ensure};
use store_api::ManifestVersion;
use store_api::codec::PrimaryKeyEncoding;
use store_api::compaction_task::{self, CompactionTaskEntry};
use store_api::logstore::LogStore;
use store_api::logstore::provider::{KafkaProvider, Provider};
use store_api::logstore::{LogStore, ObjectStoreWalIoPermit};
use store_api::metadata::{ColumnMetadata, RegionMetadataRef};
use store_api::metric_engine_consts::{
MANIFEST_INFO_EXTENSION_KEY, TABLE_COLUMN_METADATA_EXTENSION_KEY,
@@ -175,7 +175,7 @@ use crate::read::scan_region::{ScanRegion, Scanner, exact_sequence_range};
use crate::read::stream::ScanBatchStream;
use crate::region::opener::PartitionExprFetcherRef;
use crate::region::options::parse_wal_options;
use crate::region::{MitoRegion, MitoRegionRef};
use crate::region::{MitoRegionRef, RegionRoleState};
use crate::request::{RegionEditRequest, WorkerRequest};
use crate::sst::file::{FileMeta, RegionFileId, RegionIndexId};
use crate::sst::file_ref::FileReferenceManagerRef;
@@ -346,17 +346,50 @@ impl MitoEngine {
self.inner.workers.node_lease().enable();
}
/// Returns the node-lease permission used to fence object-store WAL I/O.
pub fn object_store_wal_io_permit(&self) -> Arc<dyn ObjectStoreWalIoPermit> {
self.inner.workers.node_lease_permit()
}
/// Renews the lease of this node from a heartbeat response that carries region leases.
pub fn renew_node_lease(&self, deadline: Instant) {
self.inner.workers.node_lease().renew(deadline);
}
/// Records a lease of a heartbeat sent at `sent_at` as the latest one the region received, if
/// it is the latest. The region may also be a region of a group that received the lease as a
/// whole, such as the data region of a metric engine region. Only records it: the region's role
/// does not change. Does nothing if the region is not open.
pub fn record_granted_lease(
&self,
region_id: RegionId,
sent_at: Instant,
candidate_lease_id: Option<u64>,
) {
self.inner
.workers
.granted_leases()
.record(region_id, sent_at, candidate_lease_id, || {
self.inner.find_region(region_id).is_ok()
});
}
/// Freezes the clock of the lease checks at `at`.
#[cfg(any(test, feature = "test"))]
pub fn freeze_lease_clock(&self, at: Instant) {
self.inner.workers.node_lease().freeze_clock(at);
}
/// Returns the candidate lease id of the latest lease granted to the region.
#[cfg(any(test, feature = "test"))]
pub fn granted_candidate_lease_id(&self, region_id: RegionId) -> Option<u64> {
self.inner
.workers
.granted_leases()
.get(region_id)
.and_then(|lease| lease.candidate_lease_id)
}
pub fn object_store_manager(&self) -> &ObjectStoreManagerRef {
self.inner.workers.object_store_manager()
}
@@ -1328,18 +1361,33 @@ impl EngineInner {
let region = self.find_region(region_id)?;
let was_leader = region.region_role() == RegionRole::Leader;
let was_writable = region.is_writable();
region.set_role(role);
let previous = region.set_role(role);
if role == RegionRole::Leader && !was_leader {
// No lease comes for a direct promotion, so it counts as one. A leader is not promoted.
region.manifest_ctx.record_leader_lease(Instant::now());
}
self.notify_if_can_no_longer_replay(&region, previous);
self.notify_if_became_writable(&region, was_writable);
Ok(())
}
/// Asks the worker to cancel the tail replay of `region` if a role change left it unable to
/// replay. `previous` is the state the change replaced; a later state could come from a
/// concurrent promotion. A change to Leader only replaces states that cannot replay. A replay
/// may wait on I/O that never notices the role change.
fn notify_if_can_no_longer_replay(
&self,
region: &MitoRegionRef,
previous: Option<RegionRoleState>,
) {
if previous.is_some_and(RegionRoleState::can_replay_tails) {
self.workers.notify_cannot_replay(region);
}
}
/// Asks the worker to replay the pending tails of `region` if a role change made it
/// writable. The worker may already have started an ALTER or an edit of the region.
fn notify_if_became_writable(&self, region: &MitoRegion, was_writable: bool) {
fn notify_if_became_writable(&self, region: &MitoRegionRef, was_writable: bool) {
if !was_writable && region.can_replay_tails() {
self.workers.notify_writable(region);
}
@@ -1683,7 +1731,10 @@ impl RegionEngine for MitoEngine {
role: RegionRole,
sent_at: Instant,
deadline: Instant,
candidate_lease_id: Option<u64>,
) -> Result<bool, BoxedError> {
// Before the role, so a lease the region ignores still counts.
self.record_granted_lease(region_id, sent_at, candidate_lease_id);
let region = self.inner.find_region(region_id).map_err(BoxedError::new)?;
// Before the role, and even if the role leaves the region's state unchanged.
if role.writable() {
@@ -1697,7 +1748,8 @@ impl RegionEngine for MitoEngine {
self.inner.notify_if_became_writable(&region, was_writable);
return Ok(promoted);
}
region.set_role(role);
let previous = region.set_role(role);
self.inner.notify_if_can_no_longer_replay(&region, previous);
Ok(true)
}
+77 -2
View File
@@ -14,12 +14,13 @@
use std::sync::Arc;
use std::sync::atomic::Ordering;
use std::time::Duration;
use api::v1::Rows;
use common_base::Plugins;
use common_recordbatch::RecordBatches;
use store_api::region_engine::RegionEngine;
use store_api::region_request::{RegionCloseRequest, RegionRequest};
use store_api::region_request::{PathType, RegionCloseRequest, RegionOpenRequest, RegionRequest};
use store_api::storage::{RegionId, ScanRequest};
use crate::config::MitoConfig;
@@ -27,7 +28,8 @@ use crate::engine::flush_test::MockRegionHook;
use crate::engine::listener::AlterFlushListener;
use crate::engine::region_hook::RegionHookRef;
use crate::test_util::{
CreateRequestBuilder, TestEnv, build_rows, flush_region, put_rows, rows_schema,
CheckpointTaskBlocker, CreateRequestBuilder, TestEnv, build_rows, flush_region, put_rows,
rows_schema,
};
#[tokio::test]
@@ -411,3 +413,76 @@ async fn test_repeated_close_during_edit_preserves_flush_requirement(
);
engine.stop().await.unwrap();
}
#[tokio::test(flavor = "multi_thread")]
async fn test_engine_stop_waits_for_checkpoint() {
let (blocker, mock_layer) = CheckpointTaskBlocker::block_last_checkpoint_write();
let mut env = TestEnv::with_prefix("stop-waits-for-checkpoint")
.await
.with_mock_layer(mock_layer);
let config = MitoConfig {
manifest_checkpoint_distance: 1,
..Default::default()
};
let engine = env.create_engine(config.clone()).await;
let region_id = RegionId::new(1, 1);
let request = CreateRequestBuilder::new().build();
let table_dir = request.table_dir.clone();
let column_schemas = rows_schema(&request);
engine
.handle_request(region_id, RegionRequest::Create(request))
.await
.unwrap();
put_rows(
&engine,
region_id,
Rows {
schema: column_schemas,
rows: build_rows(0, 3),
},
)
.await;
// The flush starts a checkpoint, which blocks after it has created `_last_checkpoint`
// and before it has written the pointer.
flush_region(&engine, region_id, None).await;
blocker.wait_until_blocked().await;
let wait_started = engine
.get_region(region_id)
.unwrap()
.manifest_ctx
.manifest_manager
.read()
.await
.checkpointer()
.pending_checkpoint_wait_started();
let mut reopen = tokio::spawn(async move {
let engine = env.reopen_engine(engine, config).await;
let open = RegionRequest::Open(RegionOpenRequest {
engine: String::new(),
table_dir,
path_type: PathType::Bare,
options: Default::default(),
skip_wal_replay: false,
checkpoint: None,
requirements: Default::default(),
});
let result = engine.handle_request(region_id, open).await;
(env, result)
});
tokio::time::timeout(Duration::from_secs(10), wait_started.notified())
.await
.expect("the engine stop does not wait for the checkpoint");
// The new engine would read the empty pointer while the old checkpoint is blocked.
assert!(
tokio::time::timeout(Duration::from_millis(500), &mut reopen)
.await
.is_err()
);
blocker.release();
let (_env, result) = tokio::time::timeout(Duration::from_secs(10), reopen)
.await
.unwrap()
.unwrap();
result.unwrap();
}
+157
View File
@@ -49,6 +49,163 @@ use crate::test_util::{
CreateRequestBuilder, TestEnv, build_rows, flush_region, put_rows, reopen_region, rows_schema,
};
#[tokio::test]
async fn test_engine_create_validates_extension_options_before_manifest() {
use crate::sst::index::IndexBuildType;
use crate::sst::index::handler::{
IndexKindHandler, IndexKindProvider, IndexKindProviderRef, PlanContext, PlannedIndex,
};
use crate::sst::index::kind::{ExtensionIndexKind, IndexKind};
use common_base::Plugins;
use common_error::ext::BoxedError;
#[derive(Debug)]
struct ValidatingHandler;
impl IndexKindHandler for ValidatingHandler {
fn kinds(&self) -> &[IndexKind] {
&[IndexKind::Extension(ExtensionIndexKind::Hll)]
}
fn validate(&self, context: &PlanContext<'_>) -> Result<(), BoxedError> {
for column in &context.metadata.column_metadatas {
if column
.column_schema
.metadata()
.get(datatypes::schema::HLL_KEY)
.map(String::as_str)
== Some(r#"{"precision":0}"#)
{
return Err(BoxedError::new(common_error::ext::PlainError::new(
"injected invalid extension option".into(),
StatusCode::InvalidArguments,
)));
}
}
Ok(())
}
fn plan(
&self,
context: &PlanContext<'_>,
) -> Result<Option<Arc<dyn PlannedIndex>>, BoxedError> {
// Creation must validate options even though this provider skips flush work.
if context.build_type == IndexBuildType::Flush {
return Ok(None);
}
self.validate(context)?;
Ok(None)
}
}
#[derive(Debug)]
struct Provider;
impl IndexKindProvider for Provider {
fn handlers(&self) -> Vec<Arc<dyn IndexKindHandler>> {
vec![Arc::new(ValidatingHandler)]
}
}
let mut env = TestEnv::new().await;
let plugins = Plugins::new();
plugins.insert::<IndexKindProviderRef>(Arc::new(Provider));
let engine = env
.create_engine_with_plugins(MitoConfig::default(), plugins)
.await;
let region_id = RegionId::new(1, 1);
let mut request = CreateRequestBuilder::new().build();
request.column_metadatas[0]
.column_schema
.mut_metadata()
.insert(
datatypes::schema::HLL_KEY.into(),
r#"{"precision":0}"#.into(),
);
let dir = manifest_dir(&region_dir_from_table_dir(
&request.table_dir,
region_id,
request.path_type,
));
let error = engine
.handle_request(region_id, RegionRequest::Create(request))
.await
.unwrap_err();
assert_eq!(error.status_code(), StatusCode::InvalidArguments);
assert!(engine.get_region(region_id).is_none());
assert!(
env.get_object_store()
.unwrap()
.list(&dir)
.await
.unwrap()
.is_empty()
);
// A failed plugin validation must leave a clean path for a subsequent create.
let mut request = CreateRequestBuilder::new().build();
request.column_metadatas[0]
.column_schema
.mut_metadata()
.insert(
datatypes::schema::HLL_KEY.into(),
r#"{"precision":10}"#.into(),
);
engine
.handle_request(region_id, RegionRequest::Create(request.clone()))
.await
.unwrap();
assert!(engine.get_region(region_id).is_some());
// Recovery and an idempotent Create do not require an optional provider.
let engine = env.reopen_engine(engine, MitoConfig::default()).await;
engine
.handle_request(region_id, RegionRequest::Create(request.clone()))
.await
.unwrap();
reopen_region(
&engine,
region_id,
request.table_dir,
true,
Default::default(),
)
.await;
assert!(engine.get_region(region_id).is_some());
}
#[tokio::test]
async fn test_engine_create_rejects_missing_sketch_provider_before_manifest() {
let mut env = TestEnv::new().await;
let engine = env.create_engine(MitoConfig::default()).await;
let region_id = RegionId::new(1, 1);
for (key, value) in [
(datatypes::schema::HLL_KEY, r#"{"precision":10}"#),
(datatypes::schema::KLL_KEY, r#"{"capacity":64}"#),
(datatypes::schema::MG_KEY, r#"{"max-counters":64}"#),
(datatypes::schema::HLL_KEY, "invalid"),
] {
let mut request = CreateRequestBuilder::new().build();
request.column_metadatas[0]
.column_schema
.mut_metadata()
.insert(key.into(), value.into());
let dir = manifest_dir(&region_dir_from_table_dir(
&request.table_dir,
region_id,
request.path_type,
));
let error = engine
.handle_request(region_id, RegionRequest::Create(request))
.await
.unwrap_err();
assert_eq!(error.status_code(), StatusCode::InvalidArguments);
assert!(error.to_string().contains("no registered handler"));
assert!(engine.get_region(region_id).is_none());
assert!(
env.get_object_store()
.unwrap()
.list(&dir)
.await
.unwrap()
.is_empty()
);
}
}
#[tokio::test]
async fn test_engine_column_compression_validation() {
use datatypes::schema::COMPRESSION_KEY;
File diff suppressed because it is too large Load Diff
+123 -11
View File
@@ -28,8 +28,8 @@ use rstest::rstest;
use rstest_reuse::apply;
use store_api::region_engine::{RegionEngine, RegionRole, SettableRegionRoleState};
use store_api::region_request::{
EnterStagingRequest, RegionCatchupRequest, RegionPutRequest, RegionRequest,
StagingPartitionDirective,
EnterStagingRequest, RegionCatchupRequest, RegionCloseRequest, RegionDropRequest,
RegionPutRequest, RegionRequest, StagingPartitionDirective,
};
use store_api::storage::{RegionId, ScanRequest};
use tokio::task::JoinHandle;
@@ -39,6 +39,7 @@ use crate::engine::MitoEngine;
use crate::engine::basic_test::build_bulk_insert_request;
use crate::engine::listener::WriteWalListener;
use crate::error::Error;
use crate::lease::GrantedLease;
use crate::region::{RegionLeaderState, RegionRoleState};
use crate::test_util::{
CreateRequestBuilder, LogStoreFactory, TestEnv, build_rows, kafka_log_store_factory,
@@ -72,18 +73,34 @@ async fn create_region(
fn grant(engine: &MitoEngine, role: RegionRole, deadline: Instant) {
engine
.set_region_role_with_lease(REGION_ID, role, Instant::now(), deadline)
.set_region_role_with_lease(REGION_ID, role, Instant::now(), deadline, None)
.unwrap();
}
/// Grants Leader for a heartbeat sent at `sent_at`, and returns whether the role was applied.
fn grant_leader_at(engine: &MitoEngine, sent_at: Instant) -> bool {
let deadline = Instant::now() + LEASE;
/// Grants `role` with `candidate_lease_id` for a heartbeat sent at `sent_at`, and returns whether
/// the region applied the role.
fn grant_at(
engine: &MitoEngine,
role: RegionRole,
sent_at: Instant,
candidate_lease_id: Option<u64>,
) -> bool {
engine
.set_region_role_with_lease(REGION_ID, RegionRole::Leader, sent_at, deadline)
.set_region_role_with_lease(
REGION_ID,
role,
sent_at,
Instant::now() + LEASE,
candidate_lease_id,
)
.unwrap()
}
/// Returns the latest lease the region recorded.
fn granted_lease(engine: &MitoEngine) -> Option<GrantedLease> {
engine.inner.workers.granted_leases().get(REGION_ID)
}
/// Returns a request that writes rows `start..start + 3`.
fn put_request(schema: &[ColumnSchema], start: usize) -> RegionRequest {
let rows = Rows {
@@ -319,11 +336,11 @@ async fn test_stale_leader_grant_after_downgrade(#[case] downgraded_to: Settable
.unwrap();
// Grants for heartbeats sent before either downgrade arrive late.
assert!(!grant_leader_at(&engine, sent_before));
assert!(!grant_leader_at(&engine, sent_between));
assert!(!grant_at(&engine, RegionRole::Leader, sent_before, None));
assert!(!grant_at(&engine, RegionRole::Leader, sent_between, None));
assert_eq!(downgraded, engine.get_region(REGION_ID).unwrap().state());
assert!(grant_leader_at(&engine, Instant::now()));
assert!(grant_at(&engine, RegionRole::Leader, Instant::now(), None));
assert!(engine.get_region(REGION_ID).unwrap().is_writable());
}
@@ -356,7 +373,7 @@ async fn test_reopened_region_ignores_earlier_grants(#[case] close: bool) {
&engine.get_region(REGION_ID).unwrap()
));
assert!(!grant_leader_at(&engine, sent_before));
assert!(!grant_at(&engine, RegionRole::Leader, sent_before, None));
assert!(!engine.get_region(REGION_ID).unwrap().is_writable());
grant(&engine, RegionRole::Leader, Instant::now() + LEASE);
@@ -384,3 +401,98 @@ async fn test_leader_grant_exits_staging() {
state()
);
}
#[tokio::test]
async fn test_granted_lease_keeps_latest_heartbeat_across_catchup_reopen() {
common_telemetry::init_default_ut_logging();
let mut env = TestEnv::with_prefix("granted-lease-reopen").await;
let (_listener, engine, schema) = create_region(&mut env, None).await;
grant(&engine, RegionRole::Leader, Instant::now() + LEASE);
// The memtable is not empty, so the catchup below reopens the region.
put(&engine, REGION_ID, &schema, 0).await.unwrap().unwrap();
// After the first grant and before the downgrade.
let sent_before = Instant::now();
engine
.set_region_role_state_gracefully(REGION_ID, SettableRegionRoleState::Follower)
.await
.unwrap();
// A Leader lease the region ignores still counts as the latest one received.
assert!(!grant_at(&engine, RegionRole::Leader, sent_before, Some(9)));
let latest = GrantedLease {
candidate_lease_id: Some(9),
sent_at: sent_before,
};
assert_eq!(granted_lease(&engine), Some(latest));
// A lease of an earlier or the same heartbeat that arrives late does not replace it.
let earlier = sent_before - Duration::from_millis(1);
grant_at(&engine, RegionRole::Follower, earlier, Some(1));
assert_eq!(granted_lease(&engine), Some(latest));
grant_at(&engine, RegionRole::Follower, sent_before, None);
assert_eq!(granted_lease(&engine), Some(latest));
let region = engine.get_region(REGION_ID).unwrap();
let request = RegionRequest::Catchup(RegionCatchupRequest::default());
engine.handle_request(REGION_ID, request).await.unwrap();
assert!(!Arc::ptr_eq(
&region,
&engine.get_region(REGION_ID).unwrap()
));
assert_eq!(granted_lease(&engine), Some(latest));
let later = Instant::now();
grant_at(&engine, RegionRole::Follower, later, None);
assert_eq!(
granted_lease(&engine),
Some(GrantedLease {
candidate_lease_id: None,
sent_at: later,
})
);
}
#[rstest]
#[case::close(RegionRequest::Close(RegionCloseRequest::default()))]
#[case::close_after_flush(RegionRequest::Close(RegionCloseRequest { flush_on_close: true }))]
#[case::drop(RegionRequest::Drop(RegionDropRequest {
fast_path: false,
force: false,
partial_drop: false,
}))]
#[tokio::test]
async fn test_granted_lease_removed_with_region(#[case] request: RegionRequest) {
common_telemetry::init_default_ut_logging();
let mut env = TestEnv::with_prefix("granted-lease-removed").await;
let (_listener, engine, schema) = create_region(&mut env, None).await;
grant(&engine, RegionRole::Leader, Instant::now() + LEASE);
// The memtable is not empty, so a close with `flush_on_close` closes after the flush.
put(&engine, REGION_ID, &schema, 0).await.unwrap().unwrap();
assert!(granted_lease(&engine).is_some());
engine.handle_request(REGION_ID, request).await.unwrap();
assert!(!engine.is_region_exists(REGION_ID));
assert_eq!(granted_lease(&engine), None);
// A lease that arrives after the removal is not recorded.
let _ = engine.set_region_role_with_lease(
REGION_ID,
RegionRole::Follower,
Instant::now(),
Instant::now() + LEASE,
Some(3),
);
assert_eq!(granted_lease(&engine), None);
}
#[tokio::test]
async fn test_granted_lease_removed_on_engine_stop() {
common_telemetry::init_default_ut_logging();
let mut env = TestEnv::with_prefix("granted-lease-stop").await;
let (_listener, engine, _schema) = create_region(&mut env, None).await;
grant_at(&engine, RegionRole::Follower, Instant::now(), Some(7));
assert!(granted_lease(&engine).is_some());
engine.stop().await.unwrap();
assert_eq!(granted_lease(&engine), None);
}
+9 -1
View File
@@ -44,7 +44,11 @@ pub trait EventListener: Send + Sync {
/// Notifies the listener each time a tail replay checks for a Leader lease while it waits.
fn on_tail_lease_check(&self, _region_id: RegionId) {}
/// Notifies the listener that a round of tail replay failed and will be retried.
/// Notifies the listener before a tail replay that found a newer manifest waits to fence
/// the region.
fn on_tail_fence_begin(&self, _region_id: RegionId) {}
/// Notifies the listener that a round of tail replay failed.
fn on_tail_replay_failed(&self, _region_id: RegionId, _error: &Error) {}
/// Notifies the listener after the worker learns that a tail replay ended.
@@ -141,6 +145,10 @@ pub trait EventListener: Send + Sync {
/// Notifies the listener that the index build task is aborted.
async fn on_index_build_abort(&self, _region_file_id: RegionFileId) {}
/// Notifies the listener that the worker learned an index build task stopped, after it
/// handled any completion the task reported before.
async fn on_index_build_stopped(&self, _region_file_id: RegionFileId) {}
/// Notifies the listener after the final source check and before manifest publication.
async fn on_index_build_before_manifest_commit(&self, _region_file_id: RegionFileId) {}
@@ -31,7 +31,7 @@ use common_error::ext::{BoxedError, ErrorExt, RetryHint};
use common_error::status_code::StatusCode;
use common_recordbatch::RecordBatches;
use common_wal::config::object_store::{
AckMode, CorruptedSegmentAction, ObjectStoreWalConfig, STANDALONE_GENERATION,
AckMode, CorruptedSegmentAction, FIXED_DIRECTORY_GENERATION, ObjectStoreWalConfig,
};
use common_wal::options::{ObjectStoreWalOptions, WAL_OPTIONS_KEY, WalOptions};
use futures::TryStreamExt;
@@ -99,7 +99,7 @@ async fn open_store(object_store: &ObjectStore, ack_mode: AckMode) -> Arc<Object
object_store.clone(),
&store_config(ack_mode),
0,
STANDALONE_GENERATION,
FIXED_DIRECTORY_GENERATION,
)
.await
.unwrap()
@@ -568,7 +568,7 @@ async fn test_reopen_with_a_corrupted_segment(
..store_config(AckMode::Durable)
};
let store =
ObjectStoreLogStore::try_new(object_store.clone(), &config, 0, STANDALONE_GENERATION)
ObjectStoreLogStore::try_new(object_store.clone(), &config, 0, FIXED_DIRECTORY_GENERATION)
.await
.unwrap();
let engine = new_engine(&mut env, store.clone()).await;
@@ -639,11 +639,15 @@ async fn test_open_region_rejects_mismatched_wal_prefix() {
// The process now runs its store under the next generation while the
// region still persists the prefix it was created with.
let config = store_config(AckMode::Durable);
let other_prefix = config.node_prefix(0, STANDALONE_GENERATION + 1);
let store =
ObjectStoreLogStore::try_new(object_store.clone(), &config, 0, STANDALONE_GENERATION + 1)
.await
.unwrap();
let other_prefix = config.node_prefix(0, FIXED_DIRECTORY_GENERATION + 1);
let store = ObjectStoreLogStore::try_new(
object_store.clone(),
&config,
0,
FIXED_DIRECTORY_GENERATION + 1,
)
.await
.unwrap();
let engine = new_engine(&mut env, store).await;
let err = open_region(&engine, REGION_A, &table_dir, &[])
.await
@@ -666,7 +670,7 @@ async fn open_store_accepting_missing_history(
accept_missing_history: true,
..store_config(AckMode::Durable)
};
ObjectStoreLogStore::try_new(object_store.clone(), &config, 0, STANDALONE_GENERATION)
ObjectStoreLogStore::try_new(object_store.clone(), &config, 0, FIXED_DIRECTORY_GENERATION)
.await
.unwrap()
}
+91 -6
View File
@@ -29,7 +29,7 @@ use common_error::ext::ErrorExt;
use common_error::status_code::StatusCode;
use common_recordbatch::RecordBatches;
use common_time::util::current_time_millis;
use common_wal::config::object_store::{AckMode, ObjectStoreWalConfig, STANDALONE_GENERATION};
use common_wal::config::object_store::{AckMode, FIXED_DIRECTORY_GENERATION, ObjectStoreWalConfig};
use common_wal::options::{ObjectStoreWalOptions, WAL_OPTIONS_KEY, WalOptions};
use datatypes::value::Value;
use futures::TryStreamExt;
@@ -82,7 +82,7 @@ pub(crate) fn wal_config() -> ObjectStoreWalConfig {
/// The node prefix a standalone datanode derives from the configured root,
/// which the regions persist in their WAL options.
fn node_prefix() -> String {
wal_config().node_prefix(0, STANDALONE_GENERATION)
wal_config().node_prefix(0, FIXED_DIRECTORY_GENERATION)
}
pub(crate) fn wal_options() -> HashMap<String, String> {
@@ -449,7 +449,13 @@ pub(crate) async fn create_leased_region_on(
let (table_dir, schema) = create_region(engine, region_id).await;
let deadline = Instant::now() + Duration::from_secs(10);
engine
.set_region_role_with_lease(region_id, RegionRole::Leader, Instant::now(), deadline)
.set_region_role_with_lease(
region_id,
RegionRole::Leader,
Instant::now(),
deadline,
None,
)
.unwrap();
(table_dir, schema, deadline)
}
@@ -618,12 +624,48 @@ fn held_wal_config() -> ObjectStoreWalConfig {
}
}
#[tokio::test]
async fn test_node_lease_fences_wal_and_renews_without_region_grants() {
let mut env = TestEnv::with_prefix("wal-node-lease").await;
let (engine, log_store) = env
.create_engine_with_object_store_wal(MitoConfig::default(), &held_wal_config())
.await;
engine.require_write_lease();
log_store
.set_io_permit(engine.object_store_wal_io_permit())
.unwrap();
let region_id = RegionId::new(1, 1);
let (_, schema, deadline) = create_leased_region_on(&engine, region_id).await;
engine.renew_node_lease(deadline);
put_range(&engine, region_id, &schema, 0, 3).await;
engine.freeze_lease_clock(deadline);
let error = log_store.seal_open_batch().await.unwrap_err();
assert_eq!(
common_error::status_code::StatusCode::RegionNotReady,
error.status_code()
);
assert_eq!(
common_error::ext::RetryHint::RetryAfterRouteRefresh,
error.retry_hint()
);
assert!(stored_entry_ids(&log_store, region_id).await.is_empty());
// Node renewal, including an empty heartbeat grant list, unblocks WAL I/O
// independently of this region's expired Leader grant.
engine.renew_node_lease(deadline + Duration::from_secs(10));
log_store.seal_open_batch().await.unwrap();
assert_eq!(1, stored_entry_ids(&log_store, region_id).await.len());
assert_eq!(3, count_rows(&engine, region_id).await);
log_store.stop().await.unwrap();
engine.stop().await.unwrap();
}
async fn new_log_store() -> Arc<ObjectStoreLogStore> {
ObjectStoreLogStore::try_new(
ObjectStore::new(Memory::default()).unwrap(),
&wal_config(),
0,
STANDALONE_GENERATION,
FIXED_DIRECTORY_GENERATION,
)
.await
.unwrap()
@@ -953,7 +995,7 @@ async fn test_lease_on_fenced_region_only_extends_deadline() {
let later = deadline + Duration::from_secs(10);
let promoted = engine
.set_region_role_with_lease(region_id, RegionRole::Leader, Instant::now(), later)
.set_region_role_with_lease(region_id, RegionRole::Leader, Instant::now(), later, None)
.unwrap();
assert!(!promoted);
@@ -1092,6 +1134,49 @@ async fn test_reload_waits_for_held_upload() {
assert_eq!(3, count_rows(&engine, region_id).await);
}
#[tokio::test]
async fn test_reload_waits_for_running_checkpoint() {
let (blocker, layer) = CheckpointTaskBlocker::block_last_checkpoint_write();
let mut env = TestEnv::with_prefix("reload-waits-for-running-checkpoint")
.await
.with_mock_layer(layer);
let region_id = RegionId::new(1, 1);
let (engine, _log_store, _, schema, _) = create_leased_region(&mut env, region_id).await;
put_range(&engine, region_id, &schema, 0, 3).await;
// The flush starts a checkpoint, which blocks after it has created `_last_checkpoint`
// and before it has written the pointer.
flush_region(&engine, region_id, None).await;
blocker.wait_until_blocked().await;
let old = engine.get_region(region_id).unwrap();
let wait_started = old
.manifest_ctx
.manifest_manager
.read()
.await
.checkpointer()
.pending_checkpoint_wait_started();
fence(&old).await;
notify_fenced(&engine, region_id).await;
tokio::time::timeout(Duration::from_secs(10), wait_started.notified())
.await
.expect("the reload does not wait for the checkpoint");
// The worker takes the manifest lock of the fenced instance, for example to close it,
// while the reload waits.
let manager = tokio::time::timeout(
Duration::from_secs(10),
old.manifest_ctx.manifest_manager.write(),
)
.await
.expect("the reload holds the manifest lock while it waits");
drop(manager);
assert!(!is_replaced(&engine, &old));
blocker.release();
wait_until(|| is_replaced(&engine, &old)).await;
assert_eq!(3, count_rows(&engine, region_id).await);
}
#[tokio::test]
async fn test_reload_waits_for_running_flush() {
let mut env = TestEnv::with_prefix("reload-waits-for-flush").await;
@@ -1310,7 +1395,7 @@ async fn test_reload_ignores_leases_sent_before_swap() {
wait_until(|| is_replaced(&engine, &old)).await;
let lease = |sent_at| {
engine.set_region_role_with_lease(region_id, RegionRole::Leader, sent_at, deadline)
engine.set_region_role_with_lease(region_id, RegionRole::Leader, sent_at, deadline, None)
};
assert!(!lease(sent_before_swap).unwrap());
assert!(engine.get_region(region_id).unwrap().is_follower());

Some files were not shown because too many files have changed in this diff Show More