diff --git a/Cargo.lock b/Cargo.lock index c80f9d761a5..c716ca8c81a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2931,6 +2931,7 @@ dependencies = [ "backtrace", "common-base", "common-error", + "common-macro", "common-version", "console-subscriber", "greptime-proto", @@ -2945,6 +2946,7 @@ dependencies = [ "prometheus 0.14.0", "serde", "serde_json", + "snafu 0.8.6", "tempfile", "tokio", "tracing", @@ -6160,7 +6162,7 @@ dependencies = [ [[package]] name = "greptime-proto" version = "0.1.0" -source = "git+https://github.com/GreptimeTeam/greptime-proto.git?rev=5870f5adc4d601173e742888e7db2032a690b583#5870f5adc4d601173e742888e7db2032a690b583" +source = "git+https://github.com/GreptimeTeam/greptime-proto.git?rev=c46f7ee9c82ff90f5762ae192fcf8bb2b0d6046f#c46f7ee9c82ff90f5762ae192fcf8bb2b0d6046f" dependencies = [ "prost 0.14.1", "prost-types 0.14.1", @@ -8711,6 +8713,7 @@ dependencies = [ "object-store", "partition", "prometheus 0.14.0", + "rstest", "serde", "serde_json", "smallvec", @@ -13776,6 +13779,7 @@ dependencies = [ "local-ip-address", "log-query", "loki-proto", + "lz4_flex 0.14.0", "meter-core", "meter-macros", "metric-engine", diff --git a/Cargo.toml b/Cargo.toml index 1e327fc30d4..71c6d3308ea 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -164,7 +164,7 @@ fs2 = "0.4" fst = "0.4.7" futures = "0.3" futures-util = "0.3" -greptime-proto = { git = "https://github.com/GreptimeTeam/greptime-proto.git", rev = "5870f5adc4d601173e742888e7db2032a690b583" } +greptime-proto = { git = "https://github.com/GreptimeTeam/greptime-proto.git", rev = "c46f7ee9c82ff90f5762ae192fcf8bb2b0d6046f" } hdfs-native = "0.14.6" hex = "0.4" hostname = "0.4.0" @@ -183,6 +183,8 @@ jsonb = { git = "https://github.com/GreptimeTeam/jsonb", rev = "5a6472858d860ac0 lazy_static = "1.4" local-ip-address = "0.6" loki-proto = { git = "https://github.com/GreptimeTeam/loki-proto.git", rev = "f69c8924c4babe516373e26a4118be82d976629c" } +# Keep in sync with Arrow IPC's decoder; COPY bounds its output before Arrow decoding. +lz4_flex = { version = "=0.14.0", default-features = false, features = ["frame", "std"] } meter-core = { git = "https://github.com/GreptimeTeam/greptime-meter.git", rev = "f743c3a5fe8c1f57363eac5866c356b7d91f9b39" } mockall = "0.13" moka = "0.12" diff --git a/config/config.md b/config/config.md index 9bbed619ab3..16e98f77aea 100644 --- a/config/config.md +++ b/config/config.md @@ -13,11 +13,12 @@ | Key | Type | Default | Descriptions | | --- | -----| ------- | ----------- | | `default_timezone` | String | Unset | The default timezone of the server. | -| `default_column_prefix` | String | Unset | The default column prefix for auto-created time index, value, and native histogram columns.
Legacy OTLP summary columns keep their historical `greptime_` prefix. | +| `default_column_prefix` | String | Unset | The default column prefix for auto-created time index, value, native histogram, and exemplar-label columns.
Legacy OTLP summary columns keep their historical `greptime_` prefix. | | `auto_create_table` | Bool | `true` | Server-side global switch for auto table creation on write.
When `false`, a missing table is never auto-created even if the request sets the `auto_create_table` hint to `true`. Default: `true`. | +| `auto_create_physical_table_timestamp_unit` | String | Unset | Time index unit for physical metric tables created by auto table creation
(Prometheus remote write, OTLP metrics, and other metric-engine ingestion).
New logical tables created under such a physical table inherit its unit.
Options: "Second", "Millisecond" (default), "Microsecond", "Nanosecond". | | `user_provider` | String | Unset | The user provider for authentication.
Examples: "static_user_provider:file:/path/to/users", "static_user_provider:cmd:greptime_user=greptime_pwd"
Password verifier formats: "plain:", "pbkdf2_sha256:::",
"mysql_native_password:",
"pg_scram_sha256::::"
"pbkdf2_sha256" and "pg_scram_sha256" protect passwords at rest, but such users cannot log in over MySQL:
`static_user_provider` and `watch_file_user_provider` only negotiate `mysql_native_password`, which cannot verify these formats.
"mysql_native_password" is MySQL-specific and cannot authenticate over PostgreSQL at all.
PostgreSQL SCRAM only covers "plain" and "pg_scram_sha256" users; if any user is "pbkdf2_sha256" or
"mysql_native_password", PostgreSQL falls back to cleartext password auth for every user.
For "pg_scram_sha256" users, keep the default iteration count (4096) and salt length (16): both are
observable in the SCRAM server-first message, and non-default values weaken resistance to username
enumeration. | -| `max_in_flight_write_bytes` | String | 0 | Maximum total memory for all concurrent write request bodies and messages (HTTP, gRPC, Flight).
Set to 0 to disable the limit. Default: "0" (unlimited) | -| `write_bytes_exhausted_policy` | String | `wait` | Policy when write bytes quota is exhausted.
Options: "wait" (default, 10s timeout), "wait()" (e.g., "wait(30s)"), "fail" | +| `max_in_flight_write_bytes` | String | 0 | Shared quota for concurrent write request bodies and messages (HTTP, gRPC, Flight)
plus retained decoder memory and estimated PB-to-Arrow conversion memory for ordinary-table batching.
A batch must fit together with its request's existing reservations; only additional memory is acquired.
Set to 0 to disable the limit. Default: "0" (unlimited) | +| `write_bytes_exhausted_policy` | String | `wait` | Policy when write bytes quota is exhausted.
Options: "wait" (default, 10s timeout), "wait()" (e.g., "wait(30s)"), "fail"
Table-batch conversion never waits for additional memory. Under a wait policy,
temporary contention returns a retryable error; requests that cannot fit are rejected. | | `init_regions_in_background` | Bool | `false` | Initialize all regions in the background during the startup.
By default, it provides services after all regions have been initialized. | | `init_regions_parallelism` | Integer | `16` | Parallelism of initializing regions. | | `max_concurrent_queries` | Integer | `0` | The maximum concurrent region-read streams. Zero means unlimited.
A single query can consume multiple permits. | @@ -259,7 +260,7 @@ | `logging.enable_file_logging` | Bool | `true` | Whether to write logs to files in `dir`. | | `logging.log_format` | String | `text` | The log format. Can be `text`/`json`. | | `logging.max_log_files` | Integer | `720` | The maximum amount of log files. | -| `logging.max_log_dir_size` | String | `0B` | The maximum total size of managed log files in `dir`.
Old closed log files are removed before writing when necessary. Active files may exceed it. Set to `0B` to disable. | +| `logging.max_log_dir_size` | String | `0B` | The maximum total size of managed log files in `dir`.
Old closed log files are removed before writing when necessary. Active files may exceed it. Set to `0B` to disable.
Requires symbolic links in the log directory; initialization fails if they cannot be created.
On Windows, enable Developer Mode or leave this at `0B`. | | `logging.enable_per_region_metrics` | Bool | `false` | Whether to enable per-region metrics.
Default to false. | | `logging.otlp_export_protocol` | String | `http` | The OTLP tracing export protocol. Can be `grpc`/`http`. | | `logging.otlp_headers` | -- | -- | Additional OTLP headers, only valid when using OTLP http | @@ -291,11 +292,12 @@ | Key | Type | Default | Descriptions | | --- | -----| ------- | ----------- | | `default_timezone` | String | Unset | The default timezone of the server. | -| `default_column_prefix` | String | Unset | The default column prefix for auto-created time index, value, and native histogram columns.
Legacy OTLP summary columns keep their historical `greptime_` prefix. | +| `default_column_prefix` | String | Unset | The default column prefix for auto-created time index, value, native histogram, and exemplar-label columns.
Legacy OTLP summary columns keep their historical `greptime_` prefix. | | `auto_create_table` | Bool | `true` | Server-side global switch for auto table creation on write.
When `false`, a missing table is never auto-created even if the request sets the `auto_create_table` hint to `true`. Default: `true`. | +| `auto_create_physical_table_timestamp_unit` | String | Unset | Time index unit for physical metric tables created by auto table creation
(Prometheus remote write, OTLP metrics, and other metric-engine ingestion).
New logical tables created under such a physical table inherit its unit.
Options: "Second", "Millisecond" (default), "Microsecond", "Nanosecond". | | `user_provider` | String | Unset | The user provider for authentication.
Examples: "static_user_provider:file:/path/to/users", "static_user_provider:cmd:greptime_user=greptime_pwd"
Password verifier formats: "plain:", "pbkdf2_sha256:::",
"mysql_native_password:",
"pg_scram_sha256::::"
"pbkdf2_sha256" and "pg_scram_sha256" protect passwords at rest, but such users cannot log in over MySQL:
`static_user_provider` and `watch_file_user_provider` only negotiate `mysql_native_password`, which cannot verify these formats.
"mysql_native_password" is MySQL-specific and cannot authenticate over PostgreSQL at all.
PostgreSQL SCRAM only covers "plain" and "pg_scram_sha256" users; if any user is "pbkdf2_sha256" or
"mysql_native_password", PostgreSQL falls back to cleartext password auth for every user.
For "pg_scram_sha256" users, keep the default iteration count (4096) and salt length (16): both are
observable in the SCRAM server-first message, and non-default values weaken resistance to username
enumeration. | -| `max_in_flight_write_bytes` | String | 0 | Maximum total memory for all concurrent write request bodies and messages (HTTP, gRPC, Flight).
Set to 0 to disable the limit. Default: "0" (unlimited) | -| `write_bytes_exhausted_policy` | String | `wait` | Policy when write bytes quota is exhausted.
Options: "wait" (default, 10s timeout), "wait()" (e.g., "wait(30s)"), "fail" | +| `max_in_flight_write_bytes` | String | 0 | Shared quota for concurrent write request bodies and messages (HTTP, gRPC, Flight)
plus retained decoder memory and estimated PB-to-Arrow conversion memory for ordinary-table batching.
A batch must fit together with its request's existing reservations; only additional memory is acquired.
Set to 0 to disable the limit. Default: "0" (unlimited) | +| `write_bytes_exhausted_policy` | String | `wait` | Policy when write bytes quota is exhausted.
Options: "wait" (default, 10s timeout), "wait()" (e.g., "wait(30s)"), "fail"
Table-batch conversion never waits for additional memory. Under a wait policy,
temporary contention returns a retryable error; requests that cannot fit are rejected. | | `runtime` | -- | -- | The runtime options. | | `runtime.global_rt_size` | Integer | Auto | The number of threads to execute the runtime for global read operations.
Defaults to max(num_cpus, 2). | | `runtime.compact_rt_size` | Integer | Auto | The number of threads to execute compact operations.
Defaults to max(num_cpus / 2, 2). | @@ -420,7 +422,7 @@ | `logging.enable_file_logging` | Bool | `true` | Whether to write logs to files in `dir`. | | `logging.log_format` | String | `text` | The log format. Can be `text`/`json`. | | `logging.max_log_files` | Integer | `720` | The maximum amount of log files. | -| `logging.max_log_dir_size` | String | `0B` | The maximum total size of managed log files in `dir`.
Old closed log files are removed before writing when necessary. Active files may exceed it. Set to `0B` to disable. | +| `logging.max_log_dir_size` | String | `0B` | The maximum total size of managed log files in `dir`.
Old closed log files are removed before writing when necessary. Active files may exceed it. Set to `0B` to disable.
Requires symbolic links in the log directory; initialization fails if they cannot be created.
On Windows, enable Developer Mode or leave this at `0B`. | | `logging.enable_per_region_metrics` | Bool | `false` | Whether to enable per-region metrics.
Default to false. | | `logging.otlp_export_protocol` | String | `http` | The OTLP tracing export protocol. Can be `grpc`/`http`. | | `logging.otlp_headers` | -- | -- | Additional OTLP headers, only valid when using OTLP http | @@ -539,7 +541,7 @@ | `logging.enable_file_logging` | Bool | `true` | Whether to write logs to files in `dir`. | | `logging.log_format` | String | `text` | The log format. Can be `text`/`json`. | | `logging.max_log_files` | Integer | `720` | The maximum amount of log files. | -| `logging.max_log_dir_size` | String | `0B` | The maximum total size of managed log files in `dir`.
Old closed log files are removed before writing when necessary. Active files may exceed it. Set to `0B` to disable. | +| `logging.max_log_dir_size` | String | `0B` | The maximum total size of managed log files in `dir`.
Old closed log files are removed before writing when necessary. Active files may exceed it. Set to `0B` to disable.
Requires symbolic links in the log directory; initialization fails if they cannot be created.
On Windows, enable Developer Mode or leave this at `0B`. | | `logging.otlp_export_protocol` | String | `http` | The OTLP tracing export protocol. Can be `grpc`/`http`. | | `logging.otlp_headers` | -- | -- | Additional OTLP headers, only valid when using OTLP http | | `logging.tracing_sample_ratio` | -- | Unset | The percentage of tracing will be sampled and exported.
Valid range `[0, 1]`, 1 means all traces are sampled, 0 means all traces are not sampled, the default value is 1.
ratio > 1 are treated as 1. Fractions < 0 are treated as 0 | @@ -555,7 +557,7 @@ | Key | Type | Default | Descriptions | | --- | -----| ------- | ----------- | | `node_id` | Integer | Unset | The datanode identifier and should be unique in the cluster. | -| `default_column_prefix` | String | Unset | The default column prefix for auto-created time index, value, and native histogram columns.
Legacy OTLP summary columns keep their historical `greptime_` prefix. | +| `default_column_prefix` | String | Unset | The default column prefix for auto-created time index, value, native histogram, and exemplar-label columns.
Legacy OTLP summary columns keep their historical `greptime_` prefix. | | `require_lease_before_startup` | Bool | `false` | Start services after regions have obtained leases.
It will block the datanode start if it can't receive leases in the heartbeat from metasrv. | | `init_regions_in_background` | Bool | `false` | Initialize all regions in the background during the startup.
By default, it provides services after all regions have been initialized. | | `init_regions_parallelism` | Integer | `16` | Parallelism of initializing regions. | @@ -746,7 +748,7 @@ | `logging.enable_file_logging` | Bool | `true` | Whether to write logs to files in `dir`. | | `logging.log_format` | String | `text` | The log format. Can be `text`/`json`. | | `logging.max_log_files` | Integer | `720` | The maximum amount of log files. | -| `logging.max_log_dir_size` | String | `0B` | The maximum total size of managed log files in `dir`.
Old closed log files are removed before writing when necessary. Active files may exceed it. Set to `0B` to disable. | +| `logging.max_log_dir_size` | String | `0B` | The maximum total size of managed log files in `dir`.
Old closed log files are removed before writing when necessary. Active files may exceed it. Set to `0B` to disable.
Requires symbolic links in the log directory; initialization fails if they cannot be created.
On Windows, enable Developer Mode or leave this at `0B`. | | `logging.otlp_export_protocol` | String | `http` | The OTLP tracing export protocol. Can be `grpc`/`http`. | | `logging.otlp_headers` | -- | -- | Additional OTLP headers, only valid when using OTLP http | | `logging.tracing_sample_ratio` | -- | Unset | The percentage of tracing will be sampled and exported.
Valid range `[0, 1]`, 1 means all traces are sampled, 0 means all traces are not sampled, the default value is 1.
ratio > 1 are treated as 1. Fractions < 0 are treated as 0 | @@ -807,7 +809,7 @@ | `logging.enable_file_logging` | Bool | `true` | Whether to write logs to files in `dir`. | | `logging.log_format` | String | `text` | The log format. Can be `text`/`json`. | | `logging.max_log_files` | Integer | `720` | The maximum amount of log files. | -| `logging.max_log_dir_size` | String | `0B` | The maximum total size of managed log files in `dir`.
Old closed log files are removed before writing when necessary. Active files may exceed it. Set to `0B` to disable. | +| `logging.max_log_dir_size` | String | `0B` | The maximum total size of managed log files in `dir`.
Old closed log files are removed before writing when necessary. Active files may exceed it. Set to `0B` to disable.
Requires symbolic links in the log directory; initialization fails if they cannot be created.
On Windows, enable Developer Mode or leave this at `0B`. | | `logging.otlp_export_protocol` | String | `http` | The OTLP tracing export protocol. Can be `grpc`/`http`. | | `logging.otlp_headers` | -- | -- | Additional OTLP headers, only valid when using OTLP http | | `logging.tracing_sample_ratio` | -- | Unset | The percentage of tracing will be sampled and exported.
Valid range `[0, 1]`, 1 means all traces are sampled, 0 means all traces are not sampled, the default value is 1.
ratio > 1 are treated as 1. Fractions < 0 are treated as 0 | diff --git a/config/datanode.example.toml b/config/datanode.example.toml index 45f1d93d39a..342ceb0a17a 100644 --- a/config/datanode.example.toml +++ b/config/datanode.example.toml @@ -2,7 +2,7 @@ ## @toml2docs:none-default node_id = 42 -## The default column prefix for auto-created time index, value, and native histogram columns. +## The default column prefix for auto-created time index, value, native histogram, and exemplar-label columns. ## Legacy OTLP summary columns keep their historical `greptime_` prefix. ## @toml2docs:none-default default_column_prefix = "greptime" @@ -906,6 +906,8 @@ max_log_files = 720 ## The maximum total size of managed log files in `dir`. ## Old closed log files are removed before writing when necessary. Active files may exceed it. Set to `0B` to disable. +## Requires symbolic links in the log directory; initialization fails if they cannot be created. +## On Windows, enable Developer Mode or leave this at `0B`. max_log_dir_size = "0B" ## The OTLP tracing export protocol. Can be `grpc`/`http`. diff --git a/config/flownode.example.toml b/config/flownode.example.toml index fab31fed510..8faeb2cc227 100644 --- a/config/flownode.example.toml +++ b/config/flownode.example.toml @@ -126,6 +126,8 @@ max_log_files = 720 ## The maximum total size of managed log files in `dir`. ## Old closed log files are removed before writing when necessary. Active files may exceed it. Set to `0B` to disable. +## Requires symbolic links in the log directory; initialization fails if they cannot be created. +## On Windows, enable Developer Mode or leave this at `0B`. max_log_dir_size = "0B" ## The OTLP tracing export protocol. Can be `grpc`/`http`. diff --git a/config/frontend.example.toml b/config/frontend.example.toml index f0c1402327f..d5638b66f58 100644 --- a/config/frontend.example.toml +++ b/config/frontend.example.toml @@ -2,7 +2,7 @@ ## @toml2docs:none-default default_timezone = "UTC" -## The default column prefix for auto-created time index, value, and native histogram columns. +## The default column prefix for auto-created time index, value, native histogram, and exemplar-label columns. ## Legacy OTLP summary columns keep their historical `greptime_` prefix. ## @toml2docs:none-default default_column_prefix = "greptime" @@ -11,6 +11,13 @@ default_column_prefix = "greptime" ## When `false`, a missing table is never auto-created even if the request sets the `auto_create_table` hint to `true`. Default: `true`. #+ auto_create_table = true +## Time index unit for physical metric tables created by auto table creation +## (Prometheus remote write, OTLP metrics, and other metric-engine ingestion). +## New logical tables created under such a physical table inherit its unit. +## Options: "Second", "Millisecond" (default), "Microsecond", "Nanosecond". +## @toml2docs:none-default +#+ auto_create_physical_table_timestamp_unit = "Millisecond" + ## The user provider for authentication. ## Examples: "static_user_provider:file:/path/to/users", "static_user_provider:cmd:greptime_user=greptime_pwd" ## Password verifier formats: "plain:", "pbkdf2_sha256:::", @@ -27,13 +34,17 @@ default_column_prefix = "greptime" ## @toml2docs:none-default #+ user_provider = "static_user_provider:file:/path/to/users" -## Maximum total memory for all concurrent write request bodies and messages (HTTP, gRPC, Flight). +## Shared quota for concurrent write request bodies and messages (HTTP, gRPC, Flight) +## plus retained decoder memory and estimated PB-to-Arrow conversion memory for ordinary-table batching. +## A batch must fit together with its request's existing reservations; only additional memory is acquired. ## Set to 0 to disable the limit. Default: "0" (unlimited) ## @toml2docs:none-default="0" #+ max_in_flight_write_bytes = "1GB" ## Policy when write bytes quota is exhausted. ## Options: "wait" (default, 10s timeout), "wait()" (e.g., "wait(30s)"), "fail" +## Table-batch conversion never waits for additional memory. Under a wait policy, +## temporary contention returns a retryable error; requests that cannot fit are rejected. #+ write_bytes_exhausted_policy = "wait" ## The runtime options. @@ -453,6 +464,8 @@ max_log_files = 720 ## The maximum total size of managed log files in `dir`. ## Old closed log files are removed before writing when necessary. Active files may exceed it. Set to `0B` to disable. +## Requires symbolic links in the log directory; initialization fails if they cannot be created. +## On Windows, enable Developer Mode or leave this at `0B`. max_log_dir_size = "0B" ## Whether to enable per-region metrics. diff --git a/config/metasrv.example.toml b/config/metasrv.example.toml index fe4c38d02f9..35ba3ae0a98 100644 --- a/config/metasrv.example.toml +++ b/config/metasrv.example.toml @@ -392,6 +392,8 @@ max_log_files = 720 ## The maximum total size of managed log files in `dir`. ## Old closed log files are removed before writing when necessary. Active files may exceed it. Set to `0B` to disable. +## Requires symbolic links in the log directory; initialization fails if they cannot be created. +## On Windows, enable Developer Mode or leave this at `0B`. max_log_dir_size = "0B" ## The OTLP tracing export protocol. Can be `grpc`/`http`. diff --git a/config/standalone.example.toml b/config/standalone.example.toml index 7682e537861..237f106992b 100644 --- a/config/standalone.example.toml +++ b/config/standalone.example.toml @@ -2,7 +2,7 @@ ## @toml2docs:none-default default_timezone = "UTC" -## The default column prefix for auto-created time index, value, and native histogram columns. +## The default column prefix for auto-created time index, value, native histogram, and exemplar-label columns. ## Legacy OTLP summary columns keep their historical `greptime_` prefix. ## @toml2docs:none-default default_column_prefix = "greptime" @@ -11,6 +11,13 @@ default_column_prefix = "greptime" ## When `false`, a missing table is never auto-created even if the request sets the `auto_create_table` hint to `true`. Default: `true`. #+ auto_create_table = true +## Time index unit for physical metric tables created by auto table creation +## (Prometheus remote write, OTLP metrics, and other metric-engine ingestion). +## New logical tables created under such a physical table inherit its unit. +## Options: "Second", "Millisecond" (default), "Microsecond", "Nanosecond". +## @toml2docs:none-default +#+ auto_create_physical_table_timestamp_unit = "Millisecond" + ## The user provider for authentication. ## Examples: "static_user_provider:file:/path/to/users", "static_user_provider:cmd:greptime_user=greptime_pwd" ## Password verifier formats: "plain:", "pbkdf2_sha256:::", @@ -27,13 +34,17 @@ default_column_prefix = "greptime" ## @toml2docs:none-default #+ user_provider = "static_user_provider:file:/path/to/users" -## Maximum total memory for all concurrent write request bodies and messages (HTTP, gRPC, Flight). +## Shared quota for concurrent write request bodies and messages (HTTP, gRPC, Flight) +## plus retained decoder memory and estimated PB-to-Arrow conversion memory for ordinary-table batching. +## A batch must fit together with its request's existing reservations; only additional memory is acquired. ## Set to 0 to disable the limit. Default: "0" (unlimited) ## @toml2docs:none-default="0" #+ max_in_flight_write_bytes = "1GB" ## Policy when write bytes quota is exhausted. ## Options: "wait" (default, 10s timeout), "wait()" (e.g., "wait(30s)"), "fail" +## Table-batch conversion never waits for additional memory. Under a wait policy, +## temporary contention returns a retryable error; requests that cannot fit are rejected. #+ write_bytes_exhausted_policy = "wait" ## Initialize all regions in the background during the startup. @@ -1099,6 +1110,8 @@ max_log_files = 720 ## The maximum total size of managed log files in `dir`. ## Old closed log files are removed before writing when necessary. Active files may exceed it. Set to `0B` to disable. +## Requires symbolic links in the log directory; initialization fails if they cannot be created. +## On Windows, enable Developer Mode or leave this at `0B`. max_log_dir_size = "0B" ## Whether to enable per-region metrics. diff --git a/docs/rfcs/2026-09-06-object-store-wal.md b/docs/rfcs/2026-09-06-object-store-wal.md index c94abc073aa..be152130289 100644 --- a/docs/rfcs/2026-09-06-object-store-wal.md +++ b/docs/rfcs/2026-09-06-object-store-wal.md @@ -174,10 +174,51 @@ To move the WAL to another location, stop the instance, copy every object under The check does not catch every change of location. A location whose prefix already holds objects passes a region that never flushed, and a region whose watermark names an object at or below the newest object holding entries there, whatever history those objects hold. A refused start on an empty prefix leaves its start object behind when the process ends before the delete completes or when the delete fails, which is logged; the next start then finds a prefix with only start objects and passes a region that never flushed, while it still refuses every region whose watermark names an object. The same holds when the store created a region before the refusal. When it admitted an append or a release before the refusal, as it can when regions open while the instance already serves, the store withdraws nothing and the prefix keeps an object holding entries, which may already have collected the start object; the next start then also passes every region whose watermark names an object at or below that one. -**Metrics.** The store exports metrics under `greptime_logstore_object_store_wal_`. The write path reports `seal_to_durable_seconds`, the time from sealing a batch until its object is durable, `append_ack_seconds`, the time an append waits for its acknowledgement in the `durable` mode, `object_bytes` and `object_entries`, the size and the entry count of every object sealed, and `created_objects_total`, the creates that succeeded, an identical retry included; a create is counted and timed whether or not its batch is still there to be indexed, since an object a poisoned store gave up on is as durable as any other. `indexed_objects` and `indexed_bytes` are the objects and the bytes the catalog holds, set by a recovery that succeeded and moved by every object indexed or unindexed afterwards, so a collection takes the object it deleted off both, and a recovery that is abandoned publishes neither. A recovery that succeeds reports `recovery_seconds` and the objects it read footers from in `recovered_objects_total`, both of the same recoveries, so one that is abandoned at a fetch or rejected by the catalog contributes to neither; a read stream reports `read_seconds` once it has been read to its end, and one that fails or is dropped part way reports nothing. The failure paths are counted: `create_conflicts_total` for a create that found a conflicting object, `create_failures_total` for one the object store did not confirm, `poisoned_total` for a store that recorded a terminal error, `skipped_segments_total` for a segment a read skipped, `missing_history_accepted_total` for a region that `accept_missing_history` let open without its history, and `stalled_appends_total` with `stalled_append_seconds` for an append held back because the sealed batches were full, in either mode, or by the `enqueued` backlog thresholds, timed until it is admitted or refused, a stop, a terminal error, a failing store or the teardown of the actor releasing it included. The gauge `failing` counts the stores whose backlog the object store refuses with an error that requires intervention, and `rejected_appends_total` the appends and releases such a store rejected; the attempts of a failing store are counted in `create_failures_total`. The delete counters of a collection and the release record counter are described under *Entry ids*. The histogram buckets are chosen for the default flush interval of 100 ms and the default `max_batch_bytes` of 8 MiB. +**Metrics.** The store exports metrics under `greptime_logstore_object_store_wal_`. The write path reports `seal_to_durable_seconds`, the time from sealing a batch until its object is durable, `append_ack_seconds`, the time an append waits for its acknowledgement in the `durable` mode, `object_bytes` and `object_entries`, the size and the entry count of every object sealed, and `created_objects_total`, the creates that succeeded, an identical retry included; a create is counted and timed whether or not its batch is still there to be indexed, since an object a poisoned store gave up on is as durable as any other. `indexed_objects` and `indexed_bytes` are the objects and the bytes the catalog holds, set by a recovery that succeeded and moved by every object indexed or unindexed afterwards, so a collection takes the object it deleted off both, and a recovery that is abandoned publishes neither. A recovery that succeeds reports `recovery_seconds` and the objects it read footers from in `recovered_objects_total`, both of the same recoveries, so one that is abandoned at a fetch or rejected by the catalog contributes to neither; a read stream reports `read_seconds` once it has been read to its end, and one that fails or is dropped part way reports nothing. The failure paths are counted: `create_conflicts_total` for a create that found a conflicting object, `create_failures_total` for one the object store did not confirm, `poisoned_total` for a store that recorded a terminal error, `skipped_segments_total` for a segment a read skipped, `missing_history_accepted_total` for a region that `accept_missing_history` let open without its history, and `stalled_appends_total` with `stalled_append_seconds` for an append held back because the sealed batches were full, in either mode, or by the `enqueued` backlog thresholds, timed until it is admitted or refused, a stop, a terminal error, a failing store or the teardown of the actor releasing it included. The gauge `failing` counts the stores whose backlog the object store refuses with an error that requires intervention, and `rejected_appends_total` the appends and releases such a store rejected; the attempts of a failing store are counted in `create_failures_total`. The gauge `io_permission_unavailable` counts live stores observed without permission to initiate object-store I/O, including idle stores and those awaiting their first grant. Each store is counted once while permission is unavailable and removed from the count when permission returns or its actor exits; the gauge measures permission availability, not backlog size. The delete counters of a collection and the release record counter are described under *Entry ids*. The histogram buckets are chosen for the default flush interval of 100 ms and the default `max_batch_bytes` of 8 MiB. A `testing` cargo feature exposes hooks to wait for admitted appends, to seal the open batch, to hold and release creates and to make creates fail, so engine tests can flush deterministically and observe entries that are admitted but not durable. +### Node lease and recovery fencing + +A metasrv-controlled datanode accepts object-store WAL only when its plugins +contain `EnableObjectStoreWal`; OSS does not register this marker. The builder +installs an I/O permit backed by Mito's node lease before opening regions. The +permit exposes only whether new object-store I/O is allowed; the WAL does not +own deadlines or heartbeat renewal. Standalone installs no permit. The node +prefix retains the fixed `epochs/0` directory across restarts, independently of +the heartbeat node epoch and the store epoch in object headers. Metasrv +configuration, failover integration and Enterprise registration remain separate +prerequisites for enabling the distributed WAL. +Startup's initial object and its withdrawal after a missing-history failure are +exempt so startup does not depend on a heartbeat that has not started yet. + +Every new upload, including a retry or release-only object, and every collection +delete checks the permit immediately before issuance. Issued operations may +finish, including their transport retries. The flush timer checks expiry and +renewal without sealing while expired. Expiry fails durable open and unindexed +batches with a retryable error, ignores their late upload results and never +reuses their ids. Enqueued batches already acknowledged remain pending until +renewal. Release records remain available for a later batch, while their current +waiters fail. An admission that would wait for upload capacity fails immediately +while expired; ordinary admissions continue to rely on the region write lease. + +The datanode keeps the heartbeat running until the object-store WAL stops, then +closes the heartbeat and regions. If the lease expires during shutdown, the WAL +drops its unindexed backlog without waiting for uploads, and still waits for +issued deletes. Expiry is checked on the next flush timer tick, including during +shutdown, so detection can take one configured flush interval plus actor +scheduling delay. Dropping acknowledged enqueued entries has crash semantics. + +Recovery still selects the latest complete chain, but before writing its initial +object checks that the selected tip carries the maximum epoch among all listed +headers. Falling back to an older epoch fails without modifying storage, with +the skipped epochs, object counts and sequence ranges in the error. Explicit +`accept_missing_history` permits this fallback only as an operator recovery: +previous writers must have exited and acknowledged unflushed data may be lost. +The new initial object's epoch exceeds every listed epoch. An incomplete branch +within the selected epoch does not trigger this rejection. Remote readers always +reject an older-epoch fallback, independent of this setting. + ## Mito integration Mito maps `WalOptions::ObjectStore { prefix }` to `Provider::object_store_provider(region_id, prefix)`; resolving object store options against a Raft Engine or Kafka log store reports the existing incompatible-provider error. Reads go through the region-scoped reader used for Kafka, so a namespace shared by many regions never leaks entries across regions even if a log store returned them. Object store regions are opened individually rather than grouped by topic. After replay, `topic_latest_entry_id` follows the existing remote-WAL rule: it is taken from the store's latest entry id only when the region's memtables are empty, otherwise it stays at the replay start, because that value feeds pruning and must never advance past unflushed data. Before a flush, a full truncate or a discard of unflushed data publishes a manifest watermark, Mito waits on the durability barrier described under *Acknowledgement*; with the `durable` mode and with every other provider the wait returns at once. When Mito drops a region it calls `release_region` after `obsolete`, as described under *Entry ids*; the default of that method does nothing, so the other providers handle a dropped region as before. Neither a release nor an `obsolete` of an object store region that fails, the latter for instance on a store that the release of another region poisoned, fails the drop, since nothing sends the drop of a removed region again and a caller that drops several regions, such as the metric engine with its data and metadata regions, would leave the others undone: the region's runtime state is cleaned up and its files are scheduled for deletion as for any drop, and the failure is logged; an `obsolete` that fails for another provider fails the drop as before. A store that is neither stopped nor poisoned keeps the record and writes it with its next object; a stopped or poisoned store keeps none, and the region stays unreleased after a restart. The store carries the record in a later object, as described under *Entry ids*; a crash before any later create succeeds loses it, and the dropped region's segments then hold the reclaim boundary after the restart. Before Mito replays an existing region on open, on catch-up or for a create that finds the region present, it runs the history check described under *Log store*. @@ -271,7 +312,7 @@ The reference implementation was validated on the following evidence; the tests - Object store access: an unwritable store; a listing, a trailer fetch, a footer fetch, a segment fetch and a delete that fail; a delete that fails and is retried by the next collection; an object collected between the listing and its fetch, below and at the tip's reclaim boundary; an object store that answers slowly. - Store state: an object the catalog rejects, per-region entry id exhaustion, the catalog refusing a next sequence past the maximum, every stop path with several creates in flight that succeed, fail transiently or conflict after stop began, a stop with a delete in flight, an append held back by full sealed batches, and the appends the backlog thresholds were holding back released by admission, by a stop, by a terminal error and by the teardown of the actor. - Pipelined uploader: concurrent creates acknowledged in sequence order, every sealed batch linked to its pipeline predecessor, the open batch sealing at the threshold while creates are in flight, a transient failure failing every batch that is not indexed, created ones included, a permanent failure poisoning the store. -- Chain recovery: a linear chain, orphans below and above the tip, a broken tip falling back to the latest complete object, a late object of an earlier epoch next to the chain of a later one, a missing predecessor, objects present without a complete chain, orphans raising the next sequence, and the start object on an empty prefix and meeting objects of an earlier and of a later epoch. +- Chain recovery: a linear chain, orphans below and above the tip, an incomplete branch within the selected epoch, rejection of an older-epoch fallback before any mutation and its explicit acceptance with `accept_missing_history`, a late object of an earlier epoch next to the chain of a later one, a missing predecessor, objects present without a complete chain, orphans raising the next sequence, and the start object on an empty prefix and meeting objects of an earlier and of a later epoch. ### What the evidence does not cover diff --git a/src/cmd/src/cli.rs b/src/cmd/src/cli.rs index 3739d4cc4fc..92aca3a5625 100644 --- a/src/cmd/src/cli.rs +++ b/src/cmd/src/cli.rs @@ -77,7 +77,8 @@ impl Command { &TracingOptions::default(), None, None, - ); + ) + .context(crate::error::InitLoggingSnafu)?; let tool = self.cmd.build().await.context(error::BuildCliSnafu)?; let instance = Instance { diff --git a/src/cmd/src/datanode/builder.rs b/src/cmd/src/datanode/builder.rs index 6df7ac728e8..fc933a9c5be 100644 --- a/src/cmd/src/datanode/builder.rs +++ b/src/cmd/src/datanode/builder.rs @@ -67,7 +67,8 @@ impl InstanceBuilder { &dn_opts.tracing, dn_opts.node_id.map(|x| x.to_string()), None, - ); + ) + .context(crate::error::InitLoggingSnafu)?; common_runtime::init_datanode_runtimes(&opts.runtime); diff --git a/src/cmd/src/error.rs b/src/cmd/src/error.rs index 7b0decf05ca..84553439ab1 100644 --- a/src/cmd/src/error.rs +++ b/src/cmd/src/error.rs @@ -23,6 +23,13 @@ use snafu::{Location, Snafu}; #[snafu(visibility(pub))] #[stack_trace_debug] pub enum Error { + #[snafu(display("Failed to initialize logging"))] + InitLogging { + #[snafu(implicit)] + location: Location, + source: common_telemetry::logging::InitLoggingError, + }, + #[snafu(display("Failed to install ring crypto provider: {}", msg))] InitTlsProvider { #[snafu(implicit)] @@ -337,6 +344,7 @@ pub type Result = std::result::Result; impl ErrorExt for Error { fn status_code(&self) -> StatusCode { match self { + Error::InitLogging { source, .. } => source.status_code(), Error::StartDatanode { source, .. } => source.status_code(), Error::StartFrontend { source, .. } => source.status_code(), Error::ShutdownDatanode { source, .. } => source.status_code(), diff --git a/src/cmd/src/flownode.rs b/src/cmd/src/flownode.rs index 0dfcf85e2e7..91faf313dc3 100644 --- a/src/cmd/src/flownode.rs +++ b/src/cmd/src/flownode.rs @@ -251,7 +251,8 @@ impl StartCommand { &opts.component.tracing, opts.component.node_id.map(|x| x.to_string()), None, - ); + ) + .context(crate::error::InitLoggingSnafu)?; common_runtime::init_global_runtimes(&opts.runtime); diff --git a/src/cmd/src/frontend.rs b/src/cmd/src/frontend.rs index b9aa76f0f49..7a430d7619d 100644 --- a/src/cmd/src/frontend.rs +++ b/src/cmd/src/frontend.rs @@ -384,7 +384,8 @@ impl StartCommand { &opts.component.tracing, opts.component.node_id.clone(), Some(&opts.component.slow_query), - ); + ) + .context(crate::error::InitLoggingSnafu)?; common_runtime::init_global_runtimes(&opts.runtime); @@ -464,7 +465,9 @@ impl StartCommand { ) .context(error::BuildCacheRegistrySnafu)?; - if let Some(plugin_cache_builder) = plugins::frontend::configure_cache_registry(&plugins) { + if let Some(plugin_cache_builder) = + plugins::frontend::configure_cache_registry(&plugins, cached_meta_backend.clone()) + { layered_cache_builder = layered_cache_builder.add_cache_registry(plugin_cache_builder.build()); } diff --git a/src/cmd/src/metasrv.rs b/src/cmd/src/metasrv.rs index 369f5c428d1..7df4b92ab00 100644 --- a/src/cmd/src/metasrv.rs +++ b/src/cmd/src/metasrv.rs @@ -324,7 +324,8 @@ impl StartCommand { &opts.component.tracing, None, None, - ); + ) + .context(crate::error::InitLoggingSnafu)?; common_runtime::init_global_runtimes(&opts.runtime); diff --git a/src/cmd/src/standalone.rs b/src/cmd/src/standalone.rs index 0521aa9404f..934429517f4 100644 --- a/src/cmd/src/standalone.rs +++ b/src/cmd/src/standalone.rs @@ -54,7 +54,7 @@ use common_telemetry::{info, warn}; use common_time::timezone::set_default_timezone; use common_version::{short_version, verbose_version}; use common_wal::config::DatanodeWalConfig; -use common_wal::config::object_store::STANDALONE_GENERATION; +use common_wal::config::object_store::FIXED_DIRECTORY_GENERATION; use datanode::config::{DatanodeOptions, StorageConfig}; use datanode::datanode::{Datanode, DatanodeBuilder}; use datanode::region_server::RegionServer; @@ -98,7 +98,7 @@ pub async fn build_standalone_wal_provider( ) -> Result { match wal { DatanodeWalConfig::ObjectStore(config) => Ok(WalProvider::ObjectStore { - prefix: config.node_prefix(node_id.unwrap_or(0), STANDALONE_GENERATION), + prefix: config.node_prefix(node_id.unwrap_or(0), FIXED_DIRECTORY_GENERATION), }), DatanodeWalConfig::RaftEngine(_) | DatanodeWalConfig::Kafka(_) @@ -498,7 +498,8 @@ impl StartCommand { &opts.component.tracing, None, Some(&opts.component.slow_query), - ); + ) + .context(crate::error::InitLoggingSnafu)?; common_runtime::init_standalone_runtimes(&opts.runtime); @@ -1220,7 +1221,7 @@ mod tests { ..Default::default() }; // The regions persist the node prefix the datanode runs its store under. - let node_prefix = config.node_prefix(0, STANDALONE_GENERATION); + let node_prefix = config.node_prefix(0, FIXED_DIRECTORY_GENERATION); assert_eq!(node_prefix, "cluster-a/wal/datanodes/0/epochs/0"); let provider = build_standalone_wal_provider( &DatanodeWalConfig::ObjectStore(config), diff --git a/src/cmd/tests/load_config_test.rs b/src/cmd/tests/load_config_test.rs index 129fbc5a81c..4f2a68ba988 100644 --- a/src/cmd/tests/load_config_test.rs +++ b/src/cmd/tests/load_config_test.rs @@ -25,6 +25,7 @@ use common_options::datanode::{ClientOptions, DatanodeClientOptions}; use common_runtime::global::RuntimeOptions; use common_telemetry::logging::{DEFAULT_LOGGING_DIR, DEFAULT_OTLP_HTTP_ENDPOINT, LoggingOptions}; use common_test_util::temp_dir::create_named_temp_file; +use common_time::timestamp::TimeUnit; use common_wal::config::DatanodeWalConfig; use common_wal::config::raft_engine::RaftEngineConfig; use datanode::config::{DatanodeOptions, RegionEngineConfig, StorageConfig}; @@ -249,6 +250,7 @@ fn test_load_frontend_example_config() { default_timezone: Some("UTC".to_string()), default_column_prefix: Some("greptime".to_string()), auto_create_table: true, + auto_create_physical_table_timestamp_unit: TimeUnit::Millisecond, meta_client: Some(MetaClientOptions { metasrv_addrs: vec!["127.0.0.1:3002".to_string()], timeout: Duration::from_secs(3), @@ -430,6 +432,7 @@ fn test_load_standalone_example_config() { default_timezone: Some("UTC".to_string()), default_column_prefix: Some("greptime".to_string()), auto_create_table: true, + auto_create_physical_table_timestamp_unit: TimeUnit::Millisecond, wal: DatanodeWalConfig::RaftEngine(RaftEngineConfig { dir: Some(format!("{}/{}", DEFAULT_DATA_HOME, WAL_DIR)), sync_period: Some(Duration::from_secs(5)), diff --git a/src/common/base/src/cancellation.rs b/src/common/base/src/cancellation.rs index 94aa872834c..d08a1ba7b03 100644 --- a/src/common/base/src/cancellation.rs +++ b/src/common/base/src/cancellation.rs @@ -104,6 +104,8 @@ where #[derive(Copy, Clone, Debug)] pub struct Cancelled; +impl std::error::Error for Cancelled {} + impl Display for Cancelled { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { write!(f, "Future has been cancelled") diff --git a/src/common/meta/AGENTS.md b/src/common/meta/AGENTS.md index 69d76d3c5ca..1be24b2ee9a 100644 --- a/src/common/meta/AGENTS.md +++ b/src/common/meta/AGENTS.md @@ -27,6 +27,10 @@ and durable DDL procedures. Metasrv process and service wiring live in invalidation. - Procedure changes must preserve persisted state and `TYPE_NAME`; new procedures need loader registration in `src/common/meta/src/ddl_manager.rs`. +- Database drops persist bounded logical-table batches before deleting metadata. + Replays must finish cache invalidation even after table-name keys are gone; + physical-region removal follows the logical phase. Keep the legacy single-table + executor readable for in-flight procedures from older versions. - Marker-style table options that no region consumes (`greptime.semantic.*`, `repartition.column.hint`) go through `AnnotationFamily` in `src/table/src/requests.rs` — classification, validation, logical-table diff --git a/src/common/meta/src/cache_invalidator.rs b/src/common/meta/src/cache_invalidator.rs index edf84b00b83..5e781e9c7da 100644 --- a/src/common/meta/src/cache_invalidator.rs +++ b/src/common/meta/src/cache_invalidator.rs @@ -173,6 +173,10 @@ where let key = NodeAddressKey::with_flownode(*node_id); self.invalidate_key(&key.to_bytes()).await; } + #[cfg(feature = "enterprise")] + CacheIdent::TriggerId(_) => { + // Trigger keys are owned by enterprise cache invalidators. + } CacheIdent::User(_) => { // User cache invalidation is handled by external // CacheInvalidator implementations. diff --git a/src/common/meta/src/ddl/alter_logical_tables.rs b/src/common/meta/src/ddl/alter_logical_tables.rs index ccf130cec8c..ac70980329a 100644 --- a/src/common/meta/src/ddl/alter_logical_tables.rs +++ b/src/common/meta/src/ddl/alter_logical_tables.rs @@ -24,7 +24,7 @@ use common_procedure::{Context, EventContext, EventTrigger, LockKey, Procedure, use common_telemetry::{debug, error, info, warn}; pub use executor::make_alter_region_request; use serde::{Deserialize, Serialize}; -use snafu::{ResultExt, ensure}; +use snafu::ResultExt; use store_api::metadata::ColumnMetadata; use store_api::metric_engine_consts::ALTER_PHYSICAL_EXTENSION_KEY; use strum::AsRefStr; @@ -40,7 +40,7 @@ use crate::ddl::event::table::{ TableDdlEvent, TableDdlEventType, TableDdlLocator, alter_table_kind_name, }; use crate::ddl::utils::{extract_column_metadatas, map_to_procedure_error, sync_follower_regions}; -use crate::error::{self, Result}; +use crate::error::Result; use crate::instruction::CacheIdent; use crate::key::DeserializedValueWithBytes; use crate::key::table_info::TableInfoValue; @@ -67,7 +67,7 @@ fn build_validator_from_alter_table_data<'a>( .iter() .map(|task| &task.alter_table) .collect::>(); - AlterLogicalTableValidator::new(physical_table_id, alters) + AlterLogicalTableValidator::new(physical_table_id, alters, &data.logical_table_ids) } /// Builds the executor from the [`AlterTablesData`]. @@ -149,26 +149,6 @@ impl AlterLogicalTablesProcedure { ); } - // Locks are fixed at submission. A logical table that resolves to an - // id outside the locked set here was dropped and recreated in between, - // so this procedure holds no lock for it. Procedures restored from - // pre-upgrade state have no recorded ids and keep the old behavior. - if !self.data.logical_table_ids.is_empty() { - for value in &table_info_values { - let table_id = value.get_inner_ref().table_info.ident.table_id; - ensure!( - self.data.logical_table_ids.contains(&table_id), - error::UnexpectedSnafu { - err_msg: format!( - "logical table {} (id {table_id}) is not covered by the \ - procedure locks; retry the statement", - value.get_inner_ref().table_info.name - ), - } - ); - } - } - // Updates the procedure state. retain_unskipped(&mut self.data.tasks, &skip_alter); self.data.physical_table_info = Some(physical_table_info); diff --git a/src/common/meta/src/ddl/alter_logical_tables/validator.rs b/src/common/meta/src/ddl/alter_logical_tables/validator.rs index 7e6c130351f..af0c642d919 100644 --- a/src/common/meta/src/ddl/alter_logical_tables/validator.rs +++ b/src/common/meta/src/ddl/alter_logical_tables/validator.rs @@ -26,7 +26,7 @@ use crate::ddl::utils::table_info::{ }; use crate::error::{ AlterLogicalTablesInvalidArgumentsSnafu, Result, TableInfoNotFoundSnafu, - TableRouteNotFoundSnafu, + TableRouteNotFoundSnafu, UnexpectedSnafu, }; use crate::key::table_info::TableInfoValue; use crate::key::table_route::{PhysicalTableRouteValue, TableRouteManager, TableRouteValue}; @@ -36,13 +36,19 @@ use crate::key::{DeserializedValueWithBytes, TableMetadataManagerRef}; pub struct AlterLogicalTableValidator<'a> { physical_table_id: TableId, alters: Vec<&'a AlterTableExpr>, + expected_table_ids: &'a [TableId], } impl<'a> AlterLogicalTableValidator<'a> { - pub fn new(physical_table_id: TableId, alters: Vec<&'a AlterTableExpr>) -> Self { + pub fn new( + physical_table_id: TableId, + alters: Vec<&'a AlterTableExpr>, + expected_table_ids: &'a [TableId], + ) -> Self { Self { physical_table_id, alters, + expected_table_ids, } } @@ -187,6 +193,14 @@ impl<'a> AlterLogicalTableValidator<'a> { let table_ids = get_all_table_ids_by_names(table_metadata_manager.table_name_manager(), &table_names) .await?; + // Check before skipping completed ALTERs, while the procedure holds the pinned ID locks. + // Old persisted procedures have no pinned IDs and retain their previous behavior. + ensure!( + self.expected_table_ids.is_empty() || self.expected_table_ids == table_ids, + UnexpectedSnafu { + err_msg: "logical tables changed and are not covered by the procedure locks; retry the statement", + } + ); let mut table_info_values = get_all_table_info_values_by_table_ids( table_metadata_manager.table_info_manager(), &table_ids, diff --git a/src/common/meta/src/ddl/drop_database.rs b/src/common/meta/src/ddl/drop_database.rs index 5bbd229ec5b..d083d4402b0 100644 --- a/src/common/meta/src/ddl/drop_database.rs +++ b/src/common/meta/src/ddl/drop_database.rs @@ -26,7 +26,7 @@ use common_procedure::{ Context as ProcedureContext, EventContext, EventTrigger, LockKey, Procedure, Result as ProcedureResult, Status, }; -use futures::stream::BoxStream; +use futures::stream::{BoxStream, Peekable}; use serde::{Deserialize, Serialize}; use snafu::ResultExt; use tonic::async_trait; @@ -54,12 +54,14 @@ pub(crate) enum DropTableTarget { Physical, } +type TableStream = Peekable>>; + /// Context of [DropDatabaseProcedure] execution. pub(crate) struct DropDatabaseContext { catalog: String, schema: String, drop_if_exists: bool, - tables: Option>>, + tables: Option, retrying: bool, } diff --git a/src/common/meta/src/ddl/drop_database/cursor.rs b/src/common/meta/src/ddl/drop_database/cursor.rs index e060567be58..7e300efde86 100644 --- a/src/common/meta/src/ddl/drop_database/cursor.rs +++ b/src/common/meta/src/ddl/drop_database/cursor.rs @@ -13,21 +13,24 @@ // limitations under the License. use std::any::Any; +use std::collections::HashSet; +use std::pin::Pin; +use common_base::readable_size::ReadableSize; use common_catalog::format_full_table_name; use common_procedure::Status; -use futures::TryStreamExt; +use futures::{StreamExt, TryStreamExt}; use serde::{Deserialize, Serialize}; -use snafu::OptionExt; +use snafu::{OptionExt, ensure}; use table::metadata::{TableId, TableType}; use table::table_name::TableName; use crate::cache_invalidator::Context; use crate::ddl::DdlContext; -use crate::ddl::drop_database::executor::DropDatabaseExecutor; +use crate::ddl::drop_database::executor::{DropDatabaseBatchExecutor, DropDatabaseExecutor}; use crate::ddl::drop_database::metadata::DropDatabaseRemoveMetadata; use crate::ddl::drop_database::{DropDatabaseContext, DropTableTarget, State}; -use crate::error::{Result, TableInfoNotFoundSnafu}; +use crate::error::{Result, TableInfoNotFoundSnafu, UnexpectedSnafu}; use crate::instruction::CacheIdent; use crate::key::table_route::TableRouteValue; @@ -42,6 +45,123 @@ impl DropDatabaseCursor { Self { target } } + /// Collects a bounded page without mutating metadata. Only the executor's batch is durable. + async fn collect_logical_tables( + &mut self, + ddl_ctx: &DdlContext, + ctx: &mut DropDatabaseContext, + ) -> Result<(Box, Status)> { + let page = Self::collect_page(ctx).await?; + if page.is_empty() { + return self.handle_reach_end(ctx); + } + let tables = Self::logical_tables(ddl_ctx, ctx, page).await?; + if tables.is_empty() { + return Ok((Box::new(Self::new(self.target)), Status::executing(false))); + } + Ok(( + Box::new(DropDatabaseBatchExecutor { tables }), + Status::executing(true), + )) + } + + // Leave headroom below etcd's default 1.5 MiB request limit. + const MAX_BATCH_BYTES: usize = ReadableSize::mb(1).as_bytes() as usize; + + fn estimated_table_bytes(catalog: &str, schema: &str, name: &str) -> usize { + // A control byte can expand to 6 JSON bytes, then 7 inside ProcedureMessage's + // JSON string. Round up to 8x and allow 128 bytes for fixed per-table JSON/key overhead. + 128 + 8 * (catalog.len() + schema.len() + name.len()) + } + + async fn collect_page(ctx: &mut DropDatabaseContext) -> Result> { + let mut page = Vec::new(); + let mut bytes: usize = 0; + let tables = ctx.tables.as_mut().unwrap(); + loop { + match Pin::new(&mut *tables).peek().await { + Some(Ok((name, _))) => { + let size = Self::estimated_table_bytes(&ctx.catalog, &ctx.schema, name); + if !page.is_empty() && bytes.saturating_add(size) > Self::MAX_BATCH_BYTES { + break; + } + // A single oversized name must still make progress. Procedure storage + // already splits oversized values; never strand an existing table here. + bytes = bytes.saturating_add(size); + } + Some(Err(_)) => {} // Consume below to propagate the owned error. + None => break, + } + let (name, value) = tables.try_next().await?.unwrap(); + page.push((name, value.table_id())); + } + Ok(page) + } + + async fn logical_tables( + ddl_ctx: &DdlContext, + ctx: &mut DropDatabaseContext, + page: Vec<(String, TableId)>, + ) -> Result> { + let manager = &ddl_ctx.table_metadata_manager; + let ids = page.iter().map(|(_, id)| *id).collect::>(); + let infos = manager.table_info_manager().batch_get(&ids).await?; + let routes = manager + .table_route_manager() + .table_route_storage() + .batch_get(&ids) + .await?; + let physical_ids = routes + .iter() + .filter_map(|route| match route { + Some(TableRouteValue::Logical(route)) => Some(route.physical_table_id()), + _ => None, + }) + .collect::>() + .into_iter() + .collect::>(); + let physical_infos = manager + .table_info_manager() + .batch_get(&physical_ids) + .await?; + let mut tables = Vec::new(); + for ((name, id), route) in page.into_iter().zip(routes) { + let info = infos.get(&id).with_context(|| TableInfoNotFoundSnafu { + table: format_full_table_name(&ctx.catalog, &ctx.schema, &name), + })?; + if info.table_info.table_type == TableType::View { + // Views are handled in the physical phase so collecting a batch has no side effects. + continue; + } + if let Some(TableRouteValue::Logical(route)) = route { + let physical = physical_infos + .get(&route.physical_table_id()) + .with_context(|| TableInfoNotFoundSnafu { + table: route.physical_table_id().to_string(), + })?; + // Metadata-only deletion is safe only when the backing table is dropped with us. + ensure!( + physical.table_info.catalog_name == ctx.catalog + && physical.table_info.schema_name == ctx.schema, + UnexpectedSnafu { + err_msg: format!( + "Logical table {} references physical table {} (id {}) outside the dropped database", + format_full_table_name(&ctx.catalog, &ctx.schema, &name), + format_full_table_name( + &physical.table_info.catalog_name, + &physical.table_info.schema_name, + &physical.table_info.name, + ), + route.physical_table_id(), + ), + } + ); + tables.push((id, TableName::new(&ctx.catalog, &ctx.schema, name))); + } + } + Ok(tables) + } + fn handle_reach_end( &mut self, ctx: &mut DropDatabaseContext, @@ -62,32 +182,12 @@ impl DropDatabaseCursor { async fn handle_table( &mut self, - ddl_ctx: &DdlContext, ctx: &mut DropDatabaseContext, table_name: String, table_id: TableId, table_route_value: TableRouteValue, ) -> Result<(Box, Status)> { match (self.target, table_route_value) { - (DropTableTarget::Logical, TableRouteValue::Logical(route)) => { - let physical_table_id = route.physical_table_id(); - - let (_, table_route) = ddl_ctx - .table_metadata_manager - .table_route_manager() - .get_physical_table_route(physical_table_id) - .await?; - Ok(( - Box::new(DropDatabaseExecutor::new( - table_id, - table_id, - TableName::new(&ctx.catalog, &ctx.schema, &table_name), - table_route.region_routes, - self.target, - )), - Status::executing(true), - )) - } (DropTableTarget::Physical, TableRouteValue::Physical(table_route)) => Ok(( Box::new(DropDatabaseExecutor::new( table_id, @@ -104,7 +204,6 @@ impl DropDatabaseCursor { )), } } - async fn handle_view( &self, ddl_ctx: &DdlContext, @@ -148,50 +247,61 @@ impl State for DropDatabaseCursor { ddl_ctx: &DdlContext, ctx: &mut DropDatabaseContext, ) -> Result<(Box, Status)> { - if ctx.tables.as_deref().is_none() { + if ctx.tables.is_none() { let tables = ddl_ctx .table_metadata_manager .table_name_manager() .tables(&ctx.catalog, &ctx.schema); - ctx.tables = Some(tables); + ctx.tables = Some(tables.peekable()); } - // Safety: must exist - match ctx.tables.as_mut().unwrap().try_next().await? { - Some((table_name, table_name_value)) => { - let table_id = table_name_value.table_id(); + let result = async { + if self.target == DropTableTarget::Logical { + return self.collect_logical_tables(ddl_ctx, ctx).await; + } + // Safety: must exist + match ctx.tables.as_mut().unwrap().try_next().await? { + Some((table_name, table_name_value)) => { + let table_id = table_name_value.table_id(); - let table_info_value = ddl_ctx - .table_metadata_manager - .table_info_manager() - .get(table_id) - .await? - .with_context(|| TableInfoNotFoundSnafu { - table: format_full_table_name(&ctx.catalog, &ctx.schema, &table_name), - })?; + let table_info_value = ddl_ctx + .table_metadata_manager + .table_info_manager() + .get(table_id) + .await? + .with_context(|| TableInfoNotFoundSnafu { + table: format_full_table_name(&ctx.catalog, &ctx.schema, &table_name), + })?; - if table_info_value.table_info.table_type == TableType::View { - return self.handle_view(ddl_ctx, ctx, table_name, table_id).await; - } + if table_info_value.table_info.table_type == TableType::View { + return self.handle_view(ddl_ctx, ctx, table_name, table_id).await; + } - match ddl_ctx - .table_metadata_manager - .table_route_manager() - .table_route_storage() - .get(table_id) - .await? - { - Some(table_route_value) => { - self.handle_table(ddl_ctx, ctx, table_name, table_id, table_route_value) - .await + match ddl_ctx + .table_metadata_manager + .table_route_manager() + .table_route_storage() + .get(table_id) + .await? + { + Some(table_route_value) => { + self.handle_table(ctx, table_name, table_id, table_route_value) + .await + } + None => Ok(( + Box::new(DropDatabaseCursor::new(self.target)), + Status::executing(false), + )), } - None => Ok(( - Box::new(DropDatabaseCursor::new(self.target)), - Status::executing(false), - )), } + None => self.handle_reach_end(ctx), } - None => self.handle_reach_end(ctx), } + .await; + if result.is_err() { + // The entry was consumed but no deletion plan was persisted. Rescan on retry. + ctx.tables.take(); + } + result } fn as_any(&self) -> &dyn Any { @@ -206,12 +316,163 @@ mod tests { use common_catalog::consts::{DEFAULT_CATALOG_NAME, DEFAULT_SCHEMA_NAME}; use crate::ddl::drop_database::cursor::DropDatabaseCursor; - use crate::ddl::drop_database::executor::DropDatabaseExecutor; + use crate::ddl::drop_database::executor::{DropDatabaseBatchExecutor, DropDatabaseExecutor}; use crate::ddl::drop_database::metadata::DropDatabaseRemoveMetadata; use crate::ddl::drop_database::{DropDatabaseContext, DropTableTarget, State}; use crate::ddl::test_util::{create_logical_table, create_physical_table}; use crate::test_util::{MockDatanodeManager, new_ddl_context}; + #[tokio::test] + async fn test_cursor_read_failure_rescans() { + use crate::key::table_name::TableNameValue; + use futures::StreamExt; + for target in [DropTableTarget::Logical, DropTableTarget::Physical] { + let ddl = new_ddl_context(Arc::new(MockDatanodeManager::new(()))); + let physical = create_physical_table(&ddl, "physical").await; + let mut ctx = DropDatabaseContext { + catalog: DEFAULT_CATALOG_NAME.into(), + schema: DEFAULT_SCHEMA_NAME.into(), + drop_if_exists: false, + retrying: false, + tables: Some( + futures::stream::iter(vec![Ok(("missing".into(), TableNameValue::new(99999)))]) + .boxed() + .peekable(), + ), + }; + let mut cursor = DropDatabaseCursor::new(target); + assert!(cursor.next(&ddl, &mut ctx).await.is_err()); + assert!(ctx.tables.is_none()); + let (state, _) = cursor.next(&ddl, &mut ctx).await.unwrap(); + if target == DropTableTarget::Physical { + assert!(state.as_any().is::()); + } else { + assert!(state.as_any().is::()); + } + assert!( + ddl.table_metadata_manager + .table_info_manager() + .get(physical) + .await + .unwrap() + .is_some() + ); + } + } + + #[tokio::test] + async fn test_collect_page_oversized_singleton_makes_progress() { + use crate::key::table_name::TableNameValue; + use futures::StreamExt; + let mut ctx = DropDatabaseContext { + catalog: DEFAULT_CATALOG_NAME.into(), + schema: DEFAULT_SCHEMA_NAME.into(), + drop_if_exists: false, + retrying: false, + tables: Some( + futures::stream::iter(vec![ + Ok(( + "x".repeat(DropDatabaseCursor::MAX_BATCH_BYTES), + TableNameValue::new(1), + )), + Ok(("small".into(), TableNameValue::new(2))), + ]) + .boxed() + .peekable(), + ), + }; + let page = DropDatabaseCursor::collect_page(&mut ctx).await.unwrap(); + assert_eq!(page.len(), 1); + assert_eq!(page[0].1, 1); + assert_eq!( + DropDatabaseCursor::collect_page(&mut ctx).await.unwrap(), + vec![("small".into(), 2)] + ); + assert!( + DropDatabaseCursor::collect_page(&mut ctx) + .await + .unwrap() + .is_empty() + ); + } + + #[tokio::test] + async fn test_collect_page_limits_and_request_headroom() { + use common_procedure::store::ProcedureMessage; + use futures::StreamExt; + use table::table_name::TableName; + + use crate::ddl::drop_database::DropDatabaseProcedure; + use crate::key::TableMetadataManager; + use crate::key::table_name::TableNameValue; + for name in [ + "short".to_string(), + "x".repeat(64 * 1024), + "\"\\\n\u{0001}中文".repeat(4096), + ] { + let ddl = new_ddl_context(Arc::new(MockDatanodeManager::new(()))); + let count = if name.len() < 1024 { 5000 } else { 65 }; + let entries = (0..count) + .map(|id| Ok((name.clone(), TableNameValue::new(id)))) + .collect::>(); + let mut ctx = DropDatabaseContext { + catalog: DEFAULT_CATALOG_NAME.into(), + schema: DEFAULT_SCHEMA_NAME.into(), + drop_if_exists: false, + tables: Some(futures::stream::iter(entries).boxed().peekable()), + retrying: false, + }; + let mut collected = Vec::new(); + loop { + let page = DropDatabaseCursor::collect_page(&mut ctx).await.unwrap(); + if page.is_empty() { + break; + } + let estimated = page + .iter() + .map(|(name, _)| { + DropDatabaseCursor::estimated_table_bytes(&ctx.catalog, &ctx.schema, name) + }) + .sum::(); + assert!(estimated <= DropDatabaseCursor::MAX_BATCH_BYTES); + let tables = page + .iter() + .map(|(name, id)| (*id, TableName::new(&ctx.catalog, &ctx.schema, name))) + .collect::>(); + // Each delete has one bytes field nested in two messages. Allow + // 32 bytes per key for tags and length varints, plus a txn envelope. + let delete_bytes = 64 + + tables + .iter() + .flat_map(|(id, name)| TableMetadataManager::table_identity_keys(*id, name)) + .map(|key| key.len() + 32) + .sum::(); + assert!(delete_bytes <= estimated); + let mut procedure = DropDatabaseProcedure::new( + ctx.catalog.clone(), + ctx.schema.clone(), + false, + ddl.clone(), + ); + procedure.state = Box::new(DropDatabaseBatchExecutor { tables }); + let message = ProcedureMessage { + type_name: DropDatabaseProcedure::TYPE_NAME.into(), + data: common_procedure::Procedure::dump(&procedure).unwrap(), + parent_id: None, + subprocedure_recovery: common_procedure::SubprocedureRecovery::Discard, + step: u32::MAX, + error: None, + context: Default::default(), + }; + let serialized = serde_json::to_vec(&message).unwrap(); + assert!(serialized.len() <= estimated); + assert!(serialized.len() + 512 * 1024 < 1536 * 1024); + collected.extend(page.into_iter().map(|(_, id)| id)); + } + assert_eq!(collected, (0..count).collect::>()); + } + } + #[tokio::test] async fn test_next_without_logical_tables() { let node_manager = Arc::new(MockDatanodeManager::new(())); @@ -267,16 +528,10 @@ mod tests { assert!(status.need_persist()); let executor = state .as_any() - .downcast_ref::() + .downcast_ref::() .unwrap(); - let (_, table_route) = ddl_context - .table_metadata_manager - .table_route_manager() - .get_physical_table_route(physical_table_id) - .await - .unwrap(); - assert_eq!(table_route.region_routes, executor.physical_region_routes); - assert_eq!(executor.target, DropTableTarget::Logical); + assert_eq!(executor.tables.len(), 1); + assert_eq!(executor.tables[0].1.table_name, "metric_0"); } #[tokio::test] diff --git a/src/common/meta/src/ddl/drop_database/executor.rs b/src/common/meta/src/ddl/drop_database/executor.rs index 1c01060c5ed..84d2eafe5fd 100644 --- a/src/common/meta/src/ddl/drop_database/executor.rs +++ b/src/common/meta/src/ddl/drop_database/executor.rs @@ -21,12 +21,14 @@ use snafu::OptionExt; use table::metadata::TableId; use table::table_name::TableName; +use crate::cache_invalidator::Context; use crate::ddl::DdlContext; use crate::ddl::drop_database::cursor::DropDatabaseCursor; use crate::ddl::drop_database::{DropDatabaseContext, DropTableTarget, State}; use crate::ddl::drop_table::executor::DropTableExecutor; use crate::ddl::utils::get_region_wal_options; use crate::error::{self, Result}; +use crate::instruction::CacheIdent; use crate::key::table_route::TableRouteValue; use crate::region_keeper::OperatingRegionGuard; use crate::rpc::router::{RegionRoute, operating_leader_region_roles}; @@ -140,7 +142,7 @@ impl State for DropDatabaseExecutor { &ddl_ctx.leader_region_registry, &self.physical_region_routes, true, - false, + self.target == DropTableTarget::Physical, false, ) .await?; @@ -157,6 +159,54 @@ impl State for DropDatabaseExecutor { } } +/// A durable logical-table deletion batch. Physical regions are removed in the next phase. +#[derive(Debug, Serialize, Deserialize)] +pub(crate) struct DropDatabaseBatchExecutor { + pub(crate) tables: Vec<(TableId, TableName)>, +} + +#[async_trait::async_trait] +#[typetag::serde] +impl State for DropDatabaseBatchExecutor { + async fn next( + &mut self, + ddl_ctx: &DdlContext, + _ctx: &mut DropDatabaseContext, + ) -> Result<(Box, Status)> { + ddl_ctx + .table_metadata_manager + .destroy_logical_tables_metadata(&self.tables) + .await?; + let idents = self + .tables + .iter() + .flat_map(|(id, name)| { + [ + CacheIdent::TableId(*id), + CacheIdent::TableName(name.clone()), + ] + }) + .collect::>(); + ddl_ctx + .cache_invalidator + .invalidate( + &Context { + subject: Some("Invalidate logical tables by dropping database".to_string()), + }, + &idents, + ) + .await?; + Ok(( + Box::new(DropDatabaseCursor::new(DropTableTarget::Logical)), + Status::executing(false), + )) + } + + fn as_any(&self) -> &dyn Any { + self + } +} + #[cfg(test)] mod tests { use std::collections::HashSet; @@ -448,10 +498,13 @@ mod tests { state.recover(&ddl_context).unwrap(); - let roles = ddl_context + let operating_regions = ddl_context .memory_region_keeper - .extract_operating_region_roles(7, &HashSet::from([region_id])); - assert_eq!(roles.get(®ion_id), Some(&RegionRole::DowngradingLeader)); + .extract_operating_regions(7, &HashSet::from([region_id])); + assert_eq!( + operating_regions.get(®ion_id).map(|region| region.role), + Some(RegionRole::DowngradingLeader) + ); } #[tokio::test] diff --git a/src/common/meta/src/ddl/tests/alter_logical_tables.rs b/src/common/meta/src/ddl/tests/alter_logical_tables.rs index 619e02bb9b9..4dd915d1505 100644 --- a/src/common/meta/src/ddl/tests/alter_logical_tables.rs +++ b/src/common/meta/src/ddl/tests/alter_logical_tables.rs @@ -713,21 +713,27 @@ async fn test_on_prepare_rejects_table_outside_locked_set() { let phy_id = create_physical_table(&ddl_context, "phy").await; create_logical_table(ddl_context.clone(), phy_id, "table1").await; - let tasks = vec![make_alter_logical_table_add_column_task( - None, - "table1", - vec!["column1".to_string()], - )]; - // The table resolved at prepare time is not in the locked set, as if it // had been dropped and recreated after submission. let stale_locked_id = phy_id + 1000; - let mut procedure = - AlterLogicalTablesProcedure::new(tasks, phy_id, vec![stale_locked_id], ddl_context); - let err = procedure.on_prepare().await.unwrap_err(); - assert!( - err.to_string() - .contains("not covered by the procedure locks"), - "{err}" - ); + // A completed ADD must also reject rebinding, even when no schema changes are needed. + for column in ["column1", "host"] { + let tasks = vec![make_alter_logical_table_add_column_task( + None, + "table1", + vec![column.into()], + )]; + let mut procedure = AlterLogicalTablesProcedure::new( + tasks, + phy_id, + vec![stale_locked_id], + ddl_context.clone(), + ); + let err = procedure.on_prepare().await.unwrap_err(); + assert!( + err.to_string() + .contains("not covered by the procedure locks"), + "{err}" + ); + } } diff --git a/src/common/meta/src/ddl/tests/create_table.rs b/src/common/meta/src/ddl/tests/create_table.rs index d39346e02da..e1c880fbf32 100644 --- a/src/common/meta/src/ddl/tests/create_table.rs +++ b/src/common/meta/src/ddl/tests/create_table.rs @@ -382,10 +382,13 @@ async fn test_memory_region_keeper_guard_dropped_on_procedure_done() { .memory_region_keeper .contains(datanode_id, region_id) ); - let roles = ddl_context + let operating_regions = ddl_context .memory_region_keeper - .extract_operating_region_roles(datanode_id, &HashSet::from([region_id])); - assert_eq!(roles.get(®ion_id), Some(&RegionRole::Leader)); + .extract_operating_regions(datanode_id, &HashSet::from([region_id])); + assert_eq!( + operating_regions.get(®ion_id).map(|region| region.role), + Some(RegionRole::Leader) + ); execute_procedure_until_done(&mut procedure).await; diff --git a/src/common/meta/src/ddl/tests/drop_database.rs b/src/common/meta/src/ddl/tests/drop_database.rs index 05a70962bf0..049eb82e551 100644 --- a/src/common/meta/src/ddl/tests/drop_database.rs +++ b/src/common/meta/src/ddl/tests/drop_database.rs @@ -22,7 +22,7 @@ use common_procedure_test::{ use futures::TryStreamExt; use crate::ddl::drop_database::DropDatabaseProcedure; -use crate::ddl::drop_database::executor::DropDatabaseExecutor; +use crate::ddl::drop_database::executor::{DropDatabaseBatchExecutor, DropDatabaseExecutor}; use crate::ddl::test_util::datanode_handler::{NaiveDatanodeHandler, RetryErrorDatanodeHandler}; use crate::ddl::test_util::{create_logical_table, create_physical_table}; use crate::key::schema_name::SchemaNameKey; @@ -151,24 +151,15 @@ async fn test_drop_database_recover() { ddl_context.clone(), ); let num_operating_regions = 1; - // Before dropping the logical table + // Recover the persisted logical batch before its metadata is removed. execute_procedure_until(&mut procedure, |p| { - p.state() - .as_any() - .downcast_ref::() - .is_some() + p.state().as_any().is::() }) .await; - // Dump data let data = procedure.dump().unwrap(); - assert_eq!(ddl_context.memory_region_keeper.len(), 0); let mut procedure = DropDatabaseProcedure::from_json(&data, ddl_context.clone()).unwrap(); procedure.recover().unwrap(); - assert_eq!( - ddl_context.memory_region_keeper.len(), - num_operating_regions - ); - ddl_context.memory_region_keeper.clear(); + assert_eq!(ddl_context.memory_region_keeper.len(), 0); // Before dropping the physical table execute_procedure_until(&mut procedure, |p| { p.state() @@ -197,3 +188,304 @@ async fn test_drop_database_recover() { .unwrap(); assert!(tables.is_empty()); } + +#[tokio::test] +async fn test_drop_database_batches_recover_after_metadata_deletion() { + use crate::ddl::test_util::datanode_handler::DatanodeWatcher; + use api::v1::region::region_request::Body; + use store_api::storage::RegionId; + + // A full batch, multiple batches, and a trailing partial batch. + for (count, name_padding, expected_batches) in + [(0, 0, 0), (1, 0, 1), (64, 0, 1), (129, 0, 1), (20, 8192, 2)] + { + let (tx, mut rx) = tokio::sync::mpsc::channel(16); + let ddl = new_ddl_context(Arc::new(MockDatanodeManager::new(DatanodeWatcher::new(tx)))); + ddl.table_metadata_manager + .schema_manager() + .create( + SchemaNameKey::new(DEFAULT_CATALOG_NAME, DEFAULT_SCHEMA_NAME), + None, + false, + ) + .await + .unwrap(); + let physical = create_physical_table(&ddl, "z_physical").await; + let mut ids = Vec::new(); + for i in 0..count { + create_logical_table( + ddl.clone(), + physical, + &format!("logical_{i:04}{}", "x".repeat(name_padding)), + ) + .await; + } + let mut procedure = DropDatabaseProcedure::new( + DEFAULT_CATALOG_NAME.into(), + DEFAULT_SCHEMA_NAME.into(), + false, + ddl.clone(), + ); + let ctx = ProcedureContext { + procedure_id: ProcedureId::random(), + provider: Arc::new(MockContextProvider::default()), + event_context: None, + }; + let mut batches = 0; + loop { + if let Some(batch) = procedure + .state() + .as_any() + .downcast_ref::() + { + ids.extend(batch.tables.iter().map(|(id, _)| *id)); + // Crash after keys are gone but before cache invalidation and cursor advancement. + let dump = procedure.dump().unwrap(); + ddl.table_metadata_manager + .destroy_logical_tables_metadata(&batch.tables) + .await + .unwrap(); + procedure = DropDatabaseProcedure::from_json(&dump, ddl.clone()).unwrap(); + procedure.recover().unwrap(); + batches += 1; + } + if procedure.execute(&ctx).await.unwrap().is_done() { + break; + } + } + assert_eq!(ids.len(), count); + assert_eq!(batches, expected_batches); + let (_, request) = rx.try_recv().unwrap(); + let Some(Body::Drop(drop)) = request.body else { + panic!("expected physical drop") + }; + assert_eq!(RegionId::from_u64(drop.region_id).table_id(), physical); + assert!(drop.force); + assert!( + rx.try_recv().is_err(), + "logical tables must not send region RPCs" + ); + assert!( + ddl.table_metadata_manager + .table_info_manager() + .batch_get(&ids) + .await + .unwrap() + .is_empty() + ); + assert!( + ddl.table_metadata_manager + .table_name_manager() + .tables(DEFAULT_CATALOG_NAME, DEFAULT_SCHEMA_NAME) + .try_collect::>() + .await + .unwrap() + .is_empty() + ); + } +} + +#[tokio::test] +async fn test_drop_database_legacy_state_fixture() { + let ddl = new_ddl_context(Arc::new(MockDatanodeManager::new(NaiveDatanodeHandler))); + // Single-table executor state from f8d8fe1071, before logical-table batching. + let fixture = r#"{ + "catalog": "greptime", + "schema": "public", + "drop_if_exists": false, + "state": { + "drop_database_state": "DropDatabaseExecutor", + "table_id": 1025, + "physical_table_id": 1025, + "table_name": { + "catalog_name": "greptime", + "schema_name": "public", + "table_name": "logical" + }, + "physical_region_routes": [], + "target": "Logical" + } +}"#; + let mut procedure = DropDatabaseProcedure::from_json(fixture, ddl).unwrap(); + procedure.recover().unwrap(); + assert!(procedure.state().as_any().is::()); + assert_eq!( + serde_json::from_str::(fixture).unwrap(), + serde_json::from_str::(&procedure.dump().unwrap()).unwrap() + ); +} + +#[tokio::test] +async fn test_drop_database_batch_cache_failure_recovery() { + use crate::cache_invalidator::{CacheInvalidator, Context}; + use crate::instruction::CacheIdent; + use std::sync::Mutex; + use std::sync::atomic::{AtomicBool, Ordering}; + + struct FailingInvalidator { + fail: AtomicBool, + calls: Mutex>>, + } + #[async_trait::async_trait] + impl CacheInvalidator for FailingInvalidator { + async fn invalidate(&self, _: &Context, caches: &[CacheIdent]) -> crate::error::Result<()> { + self.calls.lock().unwrap().push(caches.to_vec()); + if self.fail.swap(false, Ordering::Relaxed) { + return crate::error::UnexpectedSnafu { + err_msg: "injected cache failure", + } + .fail(); + } + Ok(()) + } + fn invalidate_all(&self) -> crate::error::Result<()> { + // This test invalidator owns only call records, not cached metadata. + Ok(()) + } + } + let invalidator = Arc::new(FailingInvalidator { + fail: AtomicBool::new(false), + calls: Mutex::new(Vec::new()), + }); + let mut ddl = new_ddl_context(Arc::new(MockDatanodeManager::new(NaiveDatanodeHandler))); + ddl.cache_invalidator = invalidator.clone(); + ddl.table_metadata_manager + .schema_manager() + .create( + SchemaNameKey::new(DEFAULT_CATALOG_NAME, DEFAULT_SCHEMA_NAME), + None, + false, + ) + .await + .unwrap(); + let physical = create_physical_table(&ddl, "physical").await; + create_logical_table(ddl.clone(), physical, "logical").await; + let mut procedure = DropDatabaseProcedure::new( + DEFAULT_CATALOG_NAME.into(), + DEFAULT_SCHEMA_NAME.into(), + false, + ddl.clone(), + ); + execute_procedure_until(&mut procedure, |p| { + p.state().as_any().is::() + }) + .await; + let dump = procedure.dump().unwrap(); + invalidator.calls.lock().unwrap().clear(); + invalidator.fail.store(true, Ordering::Relaxed); + let ctx = ProcedureContext { + procedure_id: ProcedureId::random(), + provider: Arc::new(MockContextProvider::default()), + event_context: None, + }; + assert!(procedure.execute(&ctx).await.is_err()); + assert_eq!(procedure.dump().unwrap(), dump); + let mut restored = DropDatabaseProcedure::from_json(&dump, ddl).unwrap(); + restored.recover().unwrap(); + restored.execute(&ctx).await.unwrap(); + let calls = invalidator.calls.lock().unwrap(); + assert_eq!(calls.len(), 2); + assert_eq!(calls[0], calls[1]); + assert_eq!(calls[0].len(), 2); +} + +#[tokio::test] +async fn test_drop_database_mixed_table_order_and_recovery() { + use crate::ddl::test_util::create_table::test_create_table_task; + use crate::ddl::tests::create_view::{test_create_view_task, test_table_names}; + use crate::key::table_route::TableRouteValue; + use itertools::Itertools; + use std::collections::HashMap; + + // Every relative ordering of metric physical, logical, mito and view names. + for names in ["a", "b", "c", "d"].into_iter().permutations(4) { + for recover in [false, true] { + let ddl = new_ddl_context(Arc::new(MockDatanodeManager::new(NaiveDatanodeHandler))); + let manager = &ddl.table_metadata_manager; + manager + .schema_manager() + .create( + SchemaNameKey::new(DEFAULT_CATALOG_NAME, DEFAULT_SCHEMA_NAME), + None, + false, + ) + .await + .unwrap(); + let physical = create_physical_table(&ddl, names[0]).await; + let logical = create_logical_table(ddl.clone(), physical, names[1]).await; + let mito = test_create_table_task(names[2], 20000); + manager + .create_table_metadata( + mito.table_info, + TableRouteValue::physical(vec![]), + HashMap::new(), + ) + .await + .unwrap(); + let mut view = test_create_view_task(names[3]); + view.view_info.ident.table_id = 20001; + manager + .create_view_metadata( + view.view_info, + view.create_view.logical_plan, + test_table_names(), + vec![], + vec![], + "definition".into(), + ) + .await + .unwrap(); + let mut procedure = DropDatabaseProcedure::new( + DEFAULT_CATALOG_NAME.into(), + DEFAULT_SCHEMA_NAME.into(), + false, + ddl.clone(), + ); + let ctx = ProcedureContext { + procedure_id: ProcedureId::random(), + provider: Arc::new(MockContextProvider::default()), + event_context: None, + }; + let mut done = false; + for _ in 0..40 { + let status = procedure.execute(&ctx).await.unwrap(); + if status.is_done() { + done = true; + break; + } + if recover && status.need_persist() { + let dump = procedure.dump().unwrap(); + drop(procedure); + procedure = DropDatabaseProcedure::from_json(&dump, ddl.clone()).unwrap(); + procedure.recover().unwrap(); + } + } + assert!(done, "{names:?}, recovery={recover}"); + assert!( + manager + .table_name_manager() + .tables(DEFAULT_CATALOG_NAME, DEFAULT_SCHEMA_NAME) + .try_collect::>() + .await + .unwrap() + .is_empty() + ); + assert!( + manager + .table_info_manager() + .batch_get(&[physical, logical, 20000, 20001]) + .await + .unwrap() + .is_empty() + ); + assert!( + manager + .view_info_manager() + .get(20001) + .await + .unwrap() + .is_none() + ); + } + } +} diff --git a/src/common/meta/src/ddl/tests/drop_table.rs b/src/common/meta/src/ddl/tests/drop_table.rs index a278b951dd5..40505c28fa2 100644 --- a/src/common/meta/src/ddl/tests/drop_table.rs +++ b/src/common/meta/src/ddl/tests/drop_table.rs @@ -2782,10 +2782,13 @@ async fn test_memory_region_keeper_guard_dropped_on_procedure_done() { .memory_region_keeper .contains(datanode_id, region_id) ); - let roles = ddl_context + let operating_regions = ddl_context .memory_region_keeper - .extract_operating_region_roles(datanode_id, &HashSet::from([region_id])); - assert_eq!(roles.get(®ion_id), Some(&RegionRole::Leader)); + .extract_operating_regions(datanode_id, &HashSet::from([region_id])); + assert_eq!( + operating_regions.get(®ion_id).map(|region| region.role), + Some(RegionRole::Leader) + ); execute_procedure_until_done(&mut procedure).await; diff --git a/src/common/meta/src/ddl_manager.rs b/src/common/meta/src/ddl_manager.rs index 5078328443d..87a0ddae91b 100644 --- a/src/common/meta/src/ddl_manager.rs +++ b/src/common/meta/src/ddl_manager.rs @@ -625,13 +625,22 @@ impl DdlManager { &self, alter_table_tasks: Vec, physical_table_id: TableId, + expected_table_ids: Option>, procedure_context: ProcedureContext, ) -> Result<(ProcedureId, Option)> { let context = self.create_context(); // Resolve the logical table ids up front: procedure locks are fixed // at submission, so `lock_key` cannot derive them during `Prepare`. - let logical_table_ids = { + let logical_table_ids = if let Some(ids) = expected_table_ids { + ensure!( + ids.len() == alter_table_tasks.len(), + error::AlterLogicalTablesInvalidArgumentsSnafu { + err_msg: "Expected one pinned table ID per logical ALTER task", + } + ); + ids + } else { let table_refs = alter_table_tasks .iter() .map(|task| task.table_ref()) @@ -1043,8 +1052,13 @@ impl DdlManager { .await } AlterLogicalTables(alter_table_tasks) => { - handle_alter_logical_table_tasks(self, alter_table_tasks, procedure_context) - .await + handle_alter_logical_table_tasks( + self, + alter_table_tasks, + query_context, + procedure_context, + ) + .await } DropLogicalTables(_) => todo!(), CreateDatabase(create_database_task) => { @@ -1598,6 +1612,7 @@ async fn handle_create_trigger_task( async fn handle_alter_logical_table_tasks( ddl_manager: &DdlManager, alter_table_tasks: Vec, + query_context: QueryContext, procedure_context: ProcedureContext, ) -> Result { ensure!( @@ -1616,9 +1631,15 @@ async fn handle_alter_logical_table_tasks( let physical_table_id = utils::get_physical_table_id(ddl_manager.table_metadata_manager(), first_table).await?; let num_logical_tables = alter_table_tasks.len(); + let expected_table_ids = query_context.pinned_logical_table_ids()?; let (id, _) = ddl_manager - .submit_alter_logical_table_tasks(alter_table_tasks, physical_table_id, procedure_context) + .submit_alter_logical_table_tasks( + alter_table_tasks, + physical_table_id, + expected_table_ids, + procedure_context, + ) .await?; info!( @@ -2061,6 +2082,59 @@ mod tests { ) } + #[tokio::test] + async fn test_alter_logical_tables_preserves_caller_pinned_ids() { + use crate::ddl::test_util::alter_table::TestAlterTableExprBuilder; + use crate::ddl::test_util::{create_logical_table, create_physical_table}; + use crate::rpc::ddl::ALTER_LOGICAL_TABLE_IDS_EXTENSION_KEY; + + let manager = build_soft_drop_test_ddl_manager(); + manager.register_loaders().unwrap(); + manager.procedure_manager.start().await.unwrap(); + let context = manager.create_context(); + let physical_id = create_physical_table(&context, "physical").await; + let logical_id = create_logical_table(context, physical_id, "logical").await; + let expr: api::v1::AlterTableExpr = TestAlterTableExprBuilder::default() + .table_name("logical") + .add_columns(vec![api::v1::ColumnDef { + name: "host".into(), + data_type: api::v1::ColumnDataType::String as i32, + semantic_type: api::v1::SemanticType::Tag as i32, + is_nullable: true, + ..Default::default() + }]) + .add_if_not_exists(true) + .build() + .unwrap() + .into(); + for (ids, succeeds) in [ + (Some((logical_id + 1000).to_string()), false), + (Some(format!("{logical_id},{logical_id}")), false), + (Some(logical_id.to_string()), true), + (None, true), + ] { + let mut context = QueryContext::default(); + if let Some(ids) = ids { + context + .extensions + .insert(ALTER_LOGICAL_TABLE_IDS_EXTENSION_KEY.into(), ids); + } + let result = manager + .submit_ddl_task( + ExecutorContext { + query_context: Some(context), + ..Default::default() + }, + SubmitDdlTaskRequest::new(DdlTask::new_alter_logical_tables(vec![ + expr.clone(), + ])), + ) + .await; + assert_eq!(result.is_ok(), succeeds, "{result:?}"); + } + manager.procedure_manager.stop().await.unwrap(); + } + #[cfg(feature = "enterprise")] #[tokio::test] async fn test_reserved_sequence_range_is_rejected_before_custom_handler() { diff --git a/src/common/meta/src/instruction.rs b/src/common/meta/src/instruction.rs index 0291f3a0946..2fba5a24f48 100644 --- a/src/common/meta/src/instruction.rs +++ b/src/common/meta/src/instruction.rs @@ -388,6 +388,9 @@ pub struct UpgradeRegion { pub replay_entry_id: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub metadata_replay_entry_id: Option, + /// The candidate lease id of the migration's registration of this target region. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub candidate_lease_id: Option, } impl UpgradeRegion { @@ -408,6 +411,9 @@ impl UpgradeRegion { /// The identifier of cache. pub enum CacheIdent { FlowId(FlowId), + /// Indicates a change of trigger metadata; invalidated by enterprise plugins. + #[cfg(feature = "enterprise")] + TriggerId(u64), /// Indicate change of address of flownode. FlowNodeAddressChange(u64), FlowName(FlowName), @@ -1559,6 +1565,7 @@ mod tests { location_id: None, replay_entry_id: None, metadata_replay_entry_id: None, + candidate_lease_id: None, }]); let serialized = serde_json::to_string(&upgrade_region).unwrap(); @@ -1656,10 +1663,27 @@ mod tests { location_id: None, replay_entry_id: None, metadata_replay_entry_id: None, + candidate_lease_id: None, }]); assert_eq!(upgrade_region_instruction, upgrade_region); } + #[test] + fn test_upgrade_region_candidate_lease_id_json() { + let upgrade_region = UpgradeRegion { + region_id: RegionId::new(1024, 1), + replay_timeout: Duration::from_millis(1000), + candidate_lease_id: Some(7), + ..Default::default() + }; + let json = serde_json::to_value(&upgrade_region).unwrap(); + assert_eq!(json["candidate_lease_id"], 7); + assert_eq!( + serde_json::from_value::(json).unwrap(), + upgrade_region + ); + } + #[test] fn test_deserialize_instruction_reply() { // legacy close region reply diff --git a/src/common/meta/src/key.rs b/src/common/meta/src/key.rs index 189c427e9ec..61b171b8bfe 100644 --- a/src/common/meta/src/key.rs +++ b/src/common/meta/src/key.rs @@ -994,6 +994,26 @@ impl TableMetadataManager { Ok(()) } + const TABLE_IDENTITY_KEYS: usize = 4; + + /// Keys shared by physical and logical tables, independent of region placement. + pub(crate) fn table_identity_keys( + table_id: TableId, + table_name: &TableName, + ) -> [Vec; Self::TABLE_IDENTITY_KEYS] { + [ + TableNameKey::new( + &table_name.catalog_name, + &table_name.schema_name, + &table_name.table_name, + ) + .to_bytes(), + TableInfoKey::new(table_id).to_bytes(), + TableRouteKey::new(table_id).to_bytes(), + TableRepartKey::new(table_id).to_bytes(), + ] + } + fn table_metadata_keys( &self, table_id: TableId, @@ -1009,15 +1029,7 @@ impl TableMetadataManager { } else { vec![] }; - let mut keys = Vec::with_capacity(3 + datanode_ids.len()); - let table_name = TableNameKey::new( - &table_name.catalog_name, - &table_name.schema_name, - &table_name.table_name, - ); - let table_info_key = TableInfoKey::new(table_id); - let table_route_key = TableRouteKey::new(table_id); - let table_repart_key = TableRepartKey::new(table_id); + let mut keys = Vec::from(Self::table_identity_keys(table_id, table_name)); let datanode_table_keys = datanode_ids .into_iter() .map(|datanode_id| DatanodeTableKey::new(datanode_id, table_id)) @@ -1029,10 +1041,6 @@ impl TableMetadataManager { .iter() .map(|(region_id, topic)| TopicRegionKey::new(*region_id, topic)) .collect::>(); - keys.push(table_name.to_bytes()); - keys.push(table_info_key.to_bytes()); - keys.push(table_route_key.to_bytes()); - keys.push(table_repart_key.to_bytes()); for key in &datanode_table_keys { keys.push(key.to_bytes()); } @@ -1321,6 +1329,30 @@ impl TableMetadataManager { Ok(()) } + /// Permanently deletes a batch of logical tables. The caller holds their schema write lock + /// and persists the deletion plan before calling, since backend requests may partially succeed. + pub(crate) async fn destroy_logical_tables_metadata( + &self, + tables: &[(TableId, TableName)], + ) -> Result<()> { + let max_ops = self.kv_backend.max_txn_ops().max(1); + let tables_per_request = (max_ops / Self::TABLE_IDENTITY_KEYS).max(1); + // Keep a table's keys together whenever they fit in one backend request. A backend + // limit smaller than a single table still requires splitting, as with single-table drop. + for tables in tables.chunks(tables_per_request) { + let keys = tables + .iter() + .flat_map(|(id, name)| Self::table_identity_keys(*id, name)) + .collect::>(); + for keys in keys.chunks(max_ops) { + self.kv_backend + .batch_delete(BatchDeleteRequest::new().with_keys(keys.to_vec())) + .await?; + } + } + Ok(()) + } + /// Rebuilds dropped table metadata from tombstoned keys. async fn get_dropped_table_metadata( &self, @@ -3094,6 +3126,79 @@ mod tests { ); } + #[tokio::test] + async fn test_destroy_logical_tables_metadata_limits_and_partial_failure() { + use crate::kv_backend::test_util::MockKvBackendBuilder; + use crate::rpc::store::{BatchDeleteRequest, BatchDeleteResponse}; + use std::sync::Mutex; + use std::sync::atomic::{AtomicUsize, Ordering}; + + for limit in [1, 3, 127, 128, 129] { + let tables = (0..65) + .map(|id| { + ( + id, + TableName::new("greptime", "public", format!("logical_{id}")), + ) + }) + .collect::>(); + let remaining = Arc::new(Mutex::new( + tables + .iter() + .flat_map(|(id, name)| TableMetadataManager::table_identity_keys(*id, name)) + .collect::>(), + )); + let requests = Arc::new(AtomicUsize::new(0)); + let backend = MockKvBackendBuilder::default() + .max_txn_ops(limit) + .batch_delete_fn({ + let remaining = remaining.clone(); + let requests = requests.clone(); + Arc::new(move |req: BatchDeleteRequest| { + assert!(!req.keys.is_empty()); + assert!(req.keys.len() <= limit); + if limit >= 4 { + assert_eq!(req.keys.len() % 4, 0, "single-table keys stay together"); + } + for key in &req.keys { + remaining.lock().unwrap().remove(key); + } + // Simulate a response lost after the second chunk committed. + if requests.fetch_add(1, Ordering::Relaxed) == 1 { + return crate::error::UnexpectedSnafu { + err_msg: "injected lost response", + } + .fail(); + } + Ok(BatchDeleteResponse::default()) + }) + }) + .build() + .unwrap(); + let manager = TableMetadataManager::new(Arc::new(backend)); + assert!( + manager + .destroy_logical_tables_metadata(&tables) + .await + .is_err() + ); + assert!(!remaining.lock().unwrap().is_empty()); + manager + .destroy_logical_tables_metadata(&tables) + .await + .unwrap(); + assert!(remaining.lock().unwrap().is_empty()); + assert_eq!( + requests.load(Ordering::Relaxed), + 2 + if limit < 4 { + 65_usize * 4_usize.div_ceil(limit) + } else { + 65_usize.div_ceil(limit / 4) + } + ); + } + } + #[tokio::test] async fn test_destroy_table_metadata() { let mem_kv = Arc::new(MemoryKvBackend::default()); diff --git a/src/common/meta/src/kv_backend/test_util.rs b/src/common/meta/src/kv_backend/test_util.rs index 589c6c699ef..0f19476eced 100644 --- a/src/common/meta/src/kv_backend/test_util.rs +++ b/src/common/meta/src/kv_backend/test_util.rs @@ -22,8 +22,8 @@ use crate::error::Result; use crate::kv_backend::txn::{Txn, TxnResponse}; use crate::kv_backend::{ BatchDeleteRequest, BatchDeleteResponse, BatchGetRequest, BatchGetResponse, BatchPutRequest, - BatchPutResponse, DeleteRangeRequest, DeleteRangeResponse, KvBackend, PutRequest, PutResponse, - RangeRequest, RangeResponse, TxnService, + BatchPutResponse, DeleteRangeRequest, DeleteRangeResponse, KvBackend, KvBackendRef, PutRequest, + PutResponse, RangeRequest, RangeResponse, TxnService, }; pub type MockFn = Arc Result + Send + Sync>; @@ -133,3 +133,60 @@ impl KvBackend for MockKvBackend { } } } + +/// A [KvBackend] that runs `before_txn` before each transaction of `inner`. +pub struct TxnObservingKvBackend { + /// The kv backend every request is forwarded to. + pub inner: KvBackendRef, + /// Runs before each transaction is forwarded to `inner`. + pub before_txn: Box, +} + +#[async_trait::async_trait] +impl TxnService for TxnObservingKvBackend { + type Error = crate::error::Error; + + async fn txn(&self, txn: Txn) -> Result { + (self.before_txn)(); + self.inner.txn(txn).await + } + + fn max_txn_ops(&self) -> usize { + self.inner.max_txn_ops() + } +} + +#[async_trait::async_trait] +impl KvBackend for TxnObservingKvBackend { + fn name(&self) -> &str { + self.inner.name() + } + + fn as_any(&self) -> &dyn Any { + self + } + + async fn range(&self, req: RangeRequest) -> Result { + self.inner.range(req).await + } + + async fn put(&self, req: PutRequest) -> Result { + self.inner.put(req).await + } + + async fn batch_put(&self, req: BatchPutRequest) -> Result { + self.inner.batch_put(req).await + } + + async fn batch_get(&self, req: BatchGetRequest) -> Result { + self.inner.batch_get(req).await + } + + async fn delete_range(&self, req: DeleteRangeRequest) -> Result { + self.inner.delete_range(req).await + } + + async fn batch_delete(&self, req: BatchDeleteRequest) -> Result { + self.inner.batch_delete(req).await + } +} diff --git a/src/common/meta/src/region_keeper.rs b/src/common/meta/src/region_keeper.rs index aca0b958385..d40e4158ff6 100644 --- a/src/common/meta/src/region_keeper.rs +++ b/src/common/meta/src/region_keeper.rs @@ -21,12 +21,25 @@ use store_api::storage::RegionId; use crate::DatanodeId; +/// An operating region on a datanode. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct OperatingRegion { + /// The role of a lease granted because of this registration, when the region route grants + /// none. + pub role: RegionRole, + /// The random non-zero id of a region migration's registration of its target region. A lease + /// granted because of this registration carries it while the table route exists. `None` for + /// other operations. + pub candidate_lease_id: Option, +} + /// Tracks the operating(i.e., creating, opening, dropping) regions. #[derive(Debug, Clone)] pub struct OperatingRegionGuard { datanode_id: DatanodeId, region_id: RegionId, - inner: Arc>>, + candidate_lease_id: Option, + inner: Arc>>, } impl Drop for OperatingRegionGuard { @@ -41,6 +54,11 @@ impl OperatingRegionGuard { pub fn info(&self) -> (DatanodeId, RegionId) { (self.datanode_id, self.region_id) } + + /// Returns the candidate lease id of a region migration's target region registration. + pub fn candidate_lease_id(&self) -> Option { + self.candidate_lease_id + } } pub type MemoryRegionKeeperRef = Arc; @@ -52,7 +70,7 @@ pub type MemoryRegionKeeperRef = Arc; /// - Tracks the deleting regions after the corresponding metadata is deleted. #[derive(Debug, Clone, Default)] pub struct MemoryRegionKeeper { - inner: Arc>>, + inner: Arc>>, } impl MemoryRegionKeeper { @@ -67,19 +85,32 @@ impl MemoryRegionKeeper { region_id: RegionId, role: RegionRole, ) -> Option { - let mut inner = self.inner.write().unwrap(); + self.register( + datanode_id, + region_id, + OperatingRegion { + role, + candidate_lease_id: None, + }, + ) + } - match inner.entry((datanode_id, region_id)) { - Entry::Occupied(_) => None, - Entry::Vacant(vacant_entry) => { - vacant_entry.insert(role); - Some(OperatingRegionGuard { - datanode_id, - region_id, - inner: self.inner.clone(), - }) - } - } + /// Registers the target region of a region migration as a follower with a new random + /// candidate lease id. Returns [OperatingRegionGuard] if Region(`region_id`) on + /// Peer(`datanode_id`) does not exist. + pub fn register_candidate_region( + &self, + datanode_id: DatanodeId, + region_id: RegionId, + ) -> Option { + self.register( + datanode_id, + region_id, + OperatingRegion { + role: RegionRole::Follower, + candidate_lease_id: Some(new_candidate_lease_id(rand::random)), + }, + ) } /// Returns true if the keeper contains a (`datanoe_id`, `region_id`) tuple. @@ -88,19 +119,19 @@ impl MemoryRegionKeeper { inner.contains_key(&(datanode_id, region_id)) } - /// Extracts all operating regions with roles from `region_ids`. - pub fn extract_operating_region_roles( + /// Extracts all operating regions from `region_ids`. + pub fn extract_operating_regions( &self, datanode_id: DatanodeId, region_ids: &HashSet, - ) -> HashMap { + ) -> HashMap { let inner = self.inner.read().unwrap(); region_ids .iter() .filter_map(|region_id| { inner .get(&(datanode_id, *region_id)) - .map(|role| (*region_id, *role)) + .map(|region| (*region_id, *region)) }) .collect() } @@ -121,6 +152,38 @@ impl MemoryRegionKeeper { let mut inner = self.inner.write().unwrap(); inner.clear(); } + + fn register( + &self, + datanode_id: DatanodeId, + region_id: RegionId, + operating_region: OperatingRegion, + ) -> Option { + let mut inner = self.inner.write().unwrap(); + + match inner.entry((datanode_id, region_id)) { + Entry::Occupied(_) => None, + Entry::Vacant(vacant_entry) => { + vacant_entry.insert(operating_region); + Some(OperatingRegionGuard { + datanode_id, + region_id, + candidate_lease_id: operating_region.candidate_lease_id, + inner: self.inner.clone(), + }) + } + } + } +} + +/// Returns the first non-zero value of `random`, since 0 means no candidate lease id on the wire. +fn new_candidate_lease_id(mut random: impl FnMut() -> u64) -> u64 { + loop { + let candidate_lease_id = random(); + if candidate_lease_id != 0 { + return candidate_lease_id; + } + } } #[cfg(test)] @@ -130,7 +193,7 @@ mod tests { use store_api::region_engine::RegionRole; use store_api::storage::RegionId; - use crate::region_keeper::MemoryRegionKeeper; + use crate::region_keeper::{MemoryRegionKeeper, OperatingRegion, new_candidate_lease_id}; #[test] fn test_opening_region_keeper() { @@ -153,7 +216,7 @@ mod tests { RegionId::from_u64(2), RegionId::from_u64(3), ]); - let output = keeper.extract_operating_region_roles(1, ®ions); + let output = keeper.extract_operating_regions(1, ®ions); assert_eq!(output.len(), 2); assert!(output.contains_key(&RegionId::from_u64(1))); @@ -165,12 +228,24 @@ mod tests { RegionId::from_u64(2), RegionId::from_u64(3), ]); - let output = keeper.extract_operating_region_roles(1, ®ions); + let output = keeper.extract_operating_regions(1, ®ions); assert_eq!( output, HashMap::from([ - (RegionId::from_u64(1), RegionRole::Leader), - (RegionId::from_u64(2), RegionRole::Follower), + ( + RegionId::from_u64(1), + OperatingRegion { + role: RegionRole::Leader, + candidate_lease_id: None, + } + ), + ( + RegionId::from_u64(2), + OperatingRegion { + role: RegionRole::Follower, + candidate_lease_id: None, + } + ), ]) ); assert_eq!(keeper.len(), 2); @@ -182,4 +257,42 @@ mod tests { drop(guard2); assert!(keeper.is_empty()); } + + #[test] + fn test_register_candidate_region_uses_new_candidate_lease_id() { + let keeper = MemoryRegionKeeper::new(); + let region_id = RegionId::from_u64(1); + let regions = HashSet::from([region_id]); + + let guard = keeper + .register_with_role(1, region_id, RegionRole::Follower) + .unwrap(); + assert_eq!(guard.candidate_lease_id(), None); + assert_eq!( + keeper.extract_operating_regions(1, ®ions)[®ion_id].candidate_lease_id, + None + ); + drop(guard); + + let guard = keeper.register_candidate_region(1, region_id).unwrap(); + let first = guard.candidate_lease_id().unwrap(); + assert!(keeper.register_candidate_region(1, region_id).is_none()); + assert_eq!( + keeper.extract_operating_regions(1, ®ions)[®ion_id], + OperatingRegion { + role: RegionRole::Follower, + candidate_lease_id: Some(first), + } + ); + drop(guard); + + let guard = keeper.register_candidate_region(1, region_id).unwrap(); + assert_ne!(guard.candidate_lease_id().unwrap(), first); + } + + #[test] + fn test_new_candidate_lease_id_skips_zero() { + let mut values = [0, 0, 7].into_iter(); + assert_eq!(new_candidate_lease_id(|| values.next().unwrap()), 7); + } } diff --git a/src/common/meta/src/rpc/ddl.rs b/src/common/meta/src/rpc/ddl.rs index 9e88527f935..496060e2f52 100644 --- a/src/common/meta/src/rpc/ddl.rs +++ b/src/common/meta/src/rpc/ddl.rs @@ -68,6 +68,8 @@ use crate::key::table_name::{TableNameKey, TableNameManager}; /// Reserved query-context extension key for the frontend peer address that submitted a DDL request. pub const ORIGIN_FRONTEND_ADDR_EXTENSION_KEY: &str = "__greptime_origin_frontend.addr"; +/// Ordered source table IDs pinned by the caller of an automatic logical-table ALTER. +pub const ALTER_LOGICAL_TABLE_IDS_EXTENSION_KEY: &str = "__greptime_alter_logical_tables.ids"; /// Reserved query-context extension key for the authenticated database creator. pub const CREATE_DATABASE_CREATOR_EXTENSION_KEY: &str = "__greptime_create_database.creator"; /// Internal gRPC metadata key for the authenticated database creator. @@ -1707,6 +1709,24 @@ impl QueryContext { &self.extensions } + pub(crate) fn pinned_logical_table_ids(&self) -> Result>> { + self.extensions + .get(ALTER_LOGICAL_TABLE_IDS_EXTENSION_KEY) + .map(|ids| { + ids.split(',') + .map(|id| { + id.parse::().map_err(|error| { + error::AlterLogicalTablesInvalidArgumentsSnafu { + err_msg: format!("Invalid pinned logical table ID: {error}"), + } + .build() + }) + }) + .collect() + }) + .transpose() + } + /// Get the channel pub fn channel(&self) -> u8 { self.channel @@ -1891,6 +1911,32 @@ mod tests { use super::{AlterTableTask, CreateTableTask, *}; + #[test] + fn test_pinned_logical_table_ids_wire_compatibility() { + let legacy = include_bytes!( + "../../../../../tests/compatibility/wire/read_preference/legacy_query_context.pb" + ); + let mut context = QueryContext::from(PbQueryContext::decode(legacy.as_slice()).unwrap()); + assert_eq!(context.pinned_logical_table_ids().unwrap(), None); + context.extensions.insert( + "__greptime_alter_logical_tables.ids".into(), + "1025,1024".into(), + ); + let wire = PbQueryContext::from(context.clone()).encode_to_vec(); + let decoded = QueryContext::from(PbQueryContext::decode(wire.as_slice()).unwrap()); + assert_eq!(decoded, context); + assert_eq!( + decoded.pinned_logical_table_ids().unwrap(), + Some(vec![1025, 1024]) + ); + for invalid in ["", "1024,", "1024,no", "-1", "4294967296"] { + context + .extensions + .insert(ALTER_LOGICAL_TABLE_IDS_EXTENSION_KEY.into(), invalid.into()); + assert!(context.pinned_logical_table_ids().is_err(), "{invalid}"); + } + } + #[test] fn test_ddl_timeout_secs() { assert_eq!(ddl_timeout_secs(Duration::ZERO), 0); diff --git a/src/common/query/src/prelude.rs b/src/common/query/src/prelude.rs index 8d950d77096..beafb83f30b 100644 --- a/src/common/query/src/prelude.rs +++ b/src/common/query/src/prelude.rs @@ -30,6 +30,9 @@ static GREPTIME_VALUE_CELL: OnceCell = OnceCell::new(); /// Default native histogram column name. static GREPTIME_NATIVE_HISTOGRAM_CELL: OnceCell = OnceCell::new(); +/// Default exemplar labels column name. +static GREPTIME_EXEMPLAR_LABELS_CELL: OnceCell = OnceCell::new(); + pub fn set_default_prefix(prefix: Option<&str>) -> Result<()> { // Strip surrounding double quotes as a defensive measure against upstream // sources (scripts, CI, template engines, incorrect shell escaping) that may @@ -46,12 +49,14 @@ pub fn set_default_prefix(prefix: Option<&str>) -> Result<()> { GREPTIME_TIMESTAMP_CELL.get_or_init(|| GREPTIME_TIMESTAMP.to_string()); GREPTIME_VALUE_CELL.get_or_init(|| GREPTIME_VALUE.to_string()); GREPTIME_NATIVE_HISTOGRAM_CELL.get_or_init(|| NATIVE_HISTOGRAM_FIELD.to_string()); + GREPTIME_EXEMPLAR_LABELS_CELL.get_or_init(|| GREPTIME_EXEMPLAR_LABELS.to_string()); } Some(s) if s.trim().is_empty() => { // use "" to disable prefix GREPTIME_TIMESTAMP_CELL.get_or_init(|| "timestamp".to_string()); GREPTIME_VALUE_CELL.get_or_init(|| "value".to_string()); GREPTIME_NATIVE_HISTOGRAM_CELL.get_or_init(|| "native_histogram".to_string()); + GREPTIME_EXEMPLAR_LABELS_CELL.get_or_init(|| "exemplar_labels".to_string()); } Some(x) => { ensure!( @@ -61,6 +66,7 @@ pub fn set_default_prefix(prefix: Option<&str>) -> Result<()> { GREPTIME_TIMESTAMP_CELL.get_or_init(|| format!("{}_timestamp", x)); GREPTIME_VALUE_CELL.get_or_init(|| format!("{}_value", x)); GREPTIME_NATIVE_HISTOGRAM_CELL.get_or_init(|| format!("{}_native_histogram", x)); + GREPTIME_EXEMPLAR_LABELS_CELL.get_or_init(|| format!("{}_exemplar_labels", x)); } } Ok(()) @@ -87,6 +93,14 @@ pub fn greptime_native_histogram() -> &'static str { .map_or(NATIVE_HISTOGRAM_FIELD, String::as_str) } +/// Returns the configured exemplar labels column name, or `greptime_exemplar_labels` if not set. +#[inline] +pub fn greptime_exemplar_labels() -> &'static str { + GREPTIME_EXEMPLAR_LABELS_CELL + .get() + .map_or(GREPTIME_EXEMPLAR_LABELS, String::as_str) +} + /// Default timestamp column name constant for backward compatibility. const GREPTIME_TIMESTAMP: &str = "greptime_timestamp"; /// Default value column name constant for backward compatibility. @@ -94,7 +108,7 @@ const GREPTIME_VALUE: &str = "greptime_value"; /// Query-visible source metric name stored in the exemplar table. pub const EXEMPLAR_METRIC_COLUMN: &str = "greptime_metric"; /// JSON2 object containing exemplar-owned labels. -pub const EXEMPLAR_LABELS_COLUMN: &str = "exemplar_labels"; +const GREPTIME_EXEMPLAR_LABELS: &str = "greptime_exemplar_labels"; /// Stored series label that opts ordinary float samples into raw-delta math. pub const OTLP_AGGREGATION_TEMPORALITY_LABEL: &str = "otlp_aggregation_temporality"; /// Authoritative raw-delta value for [`OTLP_AGGREGATION_TEMPORALITY_LABEL`]. @@ -115,6 +129,7 @@ mod tests { assert_eq!(greptime_timestamp(), "greptime_timestamp"); assert_eq!(greptime_value(), "greptime_value"); assert_eq!(greptime_native_histogram(), "greptime_native_histogram"); + assert_eq!(greptime_exemplar_labels(), "greptime_exemplar_labels"); } #[test] @@ -123,6 +138,7 @@ mod tests { assert_eq!(greptime_timestamp(), "timestamp"); assert_eq!(greptime_value(), "value"); assert_eq!(greptime_native_histogram(), "native_histogram"); + assert_eq!(greptime_exemplar_labels(), "exemplar_labels"); } #[test] @@ -132,6 +148,7 @@ mod tests { assert_eq!(greptime_timestamp(), "timestamp"); assert_eq!(greptime_value(), "value"); assert_eq!(greptime_native_histogram(), "native_histogram"); + assert_eq!(greptime_exemplar_labels(), "exemplar_labels"); } #[test] @@ -140,6 +157,7 @@ mod tests { assert_eq!(greptime_timestamp(), "mydb_timestamp"); assert_eq!(greptime_value(), "mydb_value"); assert_eq!(greptime_native_histogram(), "mydb_native_histogram"); + assert_eq!(greptime_exemplar_labels(), "mydb_exemplar_labels"); } #[test] diff --git a/src/common/telemetry/Cargo.toml b/src/common/telemetry/Cargo.toml index 1e146a5a75e..33be63ed92e 100644 --- a/src/common/telemetry/Cargo.toml +++ b/src/common/telemetry/Cargo.toml @@ -15,6 +15,7 @@ workspace = true backtrace = "0.3" common-base.workspace = true common-error.workspace = true +common-macro.workspace = true common-version.workspace = true console-subscriber = { version = "0.1", optional = true } greptime-proto.workspace = true @@ -31,6 +32,7 @@ parking_lot.workspace = true prometheus.workspace = true serde.workspace = true serde_json.workspace = true +snafu.workspace = true tokio.workspace = true tracing = "0.1" tracing-appender.workspace = true diff --git a/src/common/telemetry/src/logging.rs b/src/common/telemetry/src/logging.rs index 491b84f3fab..5154f7dc67e 100644 --- a/src/common/telemetry/src/logging.rs +++ b/src/common/telemetry/src/logging.rs @@ -15,6 +15,7 @@ //! logging stuffs, inspired by databend mod file_retention; +use std::any::Any; use std::collections::HashMap; use std::env; use std::io::IsTerminal; @@ -24,6 +25,9 @@ use std::time::Duration; use common_base::readable_size::ReadableSize; use common_base::serde::empty_string_as_default; +use common_error::ext::ErrorExt; +use common_error::status_code::StatusCode; +use common_macro::stack_trace_debug; use file_retention::{DirectoryRetention, LogFileKind, build_file_appender}; use once_cell::sync::{Lazy, OnceCell}; use opentelemetry::trace::TracerProvider; @@ -33,6 +37,7 @@ use opentelemetry_sdk::propagation::TraceContextPropagator; use opentelemetry_sdk::trace::{Sampler, Tracer}; use opentelemetry_semantic_conventions::resource; use serde::{Deserialize, Serialize}; +use snafu::{Location, Snafu}; use tracing::callsite; use tracing::metadata::LevelFilter; use tracing_appender::non_blocking::{NonBlocking, WorkerGuard}; @@ -45,6 +50,31 @@ use tracing_subscriber::{EnvFilter, Registry, filter}; use crate::tracing_sampler::{TracingSampleOptions, create_sampler}; +/// Failure to initialize a file appender. +#[derive(Snafu)] +#[stack_trace_debug] +pub enum InitLoggingError { + #[snafu(display("Failed to initialize file logging in {directory}: {error}.{hint}"))] + FileAppender { + directory: String, + #[snafu(source)] + error: tracing_appender::rolling::InitError, + hint: &'static str, + #[snafu(implicit)] + location: Location, + }, +} + +impl ErrorExt for InitLoggingError { + fn status_code(&self) -> StatusCode { + StatusCode::InvalidArguments + } + + fn as_any(&self) -> &dyn Any { + self + } +} + /// The default endpoint when use gRPC exporter protocol. pub const DEFAULT_OTLP_GRPC_ENDPOINT: &str = "http://localhost:4317"; @@ -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, slow_query_opts: Option<&SlowQueryOptions>, -) -> Vec { - static START: Once = Once::new(); +) -> Result, InitLoggingError> { + static START: OnceCell<()> = OnceCell::new(); let mut guards = vec![]; let node_id = node_id.unwrap_or_else(|| "none".to_string()); - START.call_once(|| { - // Enable log compatible layer to convert log record to tracing span. - LogTracer::init().expect("log tracer must be valid"); - + START.get_or_try_init(|| -> Result<(), InitLoggingError> { let stdout_writer = if opts.append_stdout { let (writer, guard) = tracing_appender::non_blocking(std::io::stdout()); guards.push(guard); @@ -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, retention: Option<&DirectoryRetention>, guards: &mut Vec, -) -> tracing::Dispatch { +) -> Result { let stdout_layer = stdout_writer.map(|writer| { build_logging_layer(writer, opts.log_format, std::io::stdout().is_terminal()) }); let file_layer = if opts.enable_file_logging && !opts.dir.is_empty() { - let rolling_appender = build_file_appender(opts, LogFileKind::SlowQuery, retention); + let rolling_appender = build_file_appender(opts, LogFileKind::SlowQuery, retention)?; let (writer, guard) = tracing_appender::non_blocking(rolling_appender); guards.push(guard); Some(build_logging_layer(writer, opts.log_format, false)) @@ -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( @@ -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 diff --git a/src/common/telemetry/src/logging/file_retention.rs b/src/common/telemetry/src/logging/file_retention.rs index 0a79468851f..d2a962ad748 100644 --- a/src/common/telemetry/src/logging/file_retention.rs +++ b/src/common/telemetry/src/logging/file_retention.rs @@ -24,9 +24,10 @@ use std::time::SystemTime; use common_base::readable_size::ReadableSize; use parking_lot::Mutex; +use snafu::ResultExt; use tracing_appender::rolling::{RollingFileAppender, Rotation}; -use crate::logging::LoggingOptions; +use crate::logging::{FileAppenderSnafu, InitLoggingError, LoggingOptions}; /// A managed file-log kind. #[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)] @@ -421,7 +422,7 @@ pub(crate) fn build_file_appender( opts: &LoggingOptions, kind: LogFileKind, retention: Option<&DirectoryRetention>, -) -> Box { +) -> Result, InitLoggingError> { // Directory retention owns size and count pruning so its index remains authoritative. let upstream_max_log_files = if retention.is_some() { 0 @@ -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(); diff --git a/src/common/wal/src/config/object_store.rs b/src/common/wal/src/config/object_store.rs index 9e4a371baae..c41adadcb69 100644 --- a/src/common/wal/src/config/object_store.rs +++ b/src/common/wal/src/config/object_store.rs @@ -17,12 +17,19 @@ use std::time::Duration; use common_base::readable_size::ReadableSize; use serde::{Deserialize, Serialize}; -/// Generation of the node prefix in standalone mode. +/// Fixed directory generation used by standalone and distributed WAL stores. /// -/// Standalone runs a single datanode that never changes generation, so the -/// prefix layout carries the constant. Distributed mode will take both the -/// node id and the generation from the metasrv. -pub const STANDALONE_GENERATION: u64 = 0; +/// The directory remains stable across process restarts. This is distinct from +/// both the heartbeat node epoch and the store epoch carried in object headers. +pub const FIXED_DIRECTORY_GENERATION: u64 = 0; + +/// Plugin marker allowing a metasrv-controlled datanode to use object-store WAL. +/// +/// OSS does not register this marker. Cluster integration registers it only after +/// the distributed WAL prerequisites are available; it does not itself configure +/// metasrv or enable region failover. +#[derive(Debug, Clone, Copy)] +pub struct EnableObjectStoreWal; /// When an append to the object store WAL returns. #[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)] @@ -124,7 +131,7 @@ mod tests { fn test_node_prefix() { let config = ObjectStoreWalConfig::default(); assert_eq!( - config.node_prefix(0, STANDALONE_GENERATION), + config.node_prefix(0, FIXED_DIRECTORY_GENERATION), "wal/datanodes/0/epochs/0" ); diff --git a/src/datanode/src/alive_keeper.rs b/src/datanode/src/alive_keeper.rs index 13af76202d5..30e27929a29 100644 --- a/src/datanode/src/alive_keeper.rs +++ b/src/datanode/src/alive_keeper.rs @@ -16,7 +16,7 @@ use std::collections::HashMap; use std::sync::Arc; use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; -use api::v1::meta::GrantedRegion; +use api::v1::meta::GrantedRegion as PbGrantedRegion; use async_trait::async_trait; use common_error::ext::ErrorExt; use common_error::status_code::StatusCode; @@ -26,7 +26,7 @@ use common_meta::heartbeat::handler::{ }; use common_telemetry::{debug, error, info, trace, warn}; use snafu::OptionExt; -use store_api::region_engine::{RegionRole, SettableRegionRoleState}; +use store_api::region_engine::{GrantedRegion, RegionRole, SettableRegionRoleState}; use store_api::region_request::{RegionCloseRequest, RegionRequest}; use store_api::storage::RegionId; #[cfg(test)] @@ -137,15 +137,22 @@ impl RegionAliveKeeper { /// Renews the lease of regions to `deadline`, granted for a heartbeat sent at `sent_at`. async fn renew_region_leases( &self, - regions: &[GrantedRegion], + regions: &[PbGrantedRegion], sent_at: Instant, deadline: Instant, ) { for region in regions { - let (role, region_id) = (region.role().into(), RegionId::from(region.region_id)); + let region = GrantedRegion::from(region.clone()); + let region_id = region.region_id; if let Some(handle) = self.find_handle(region_id).await { handle - .reset_deadline(role, sent_at, deadline, region.extensions.clone()) + .reset_deadline(ResetLease { + role: region.region_role, + sent_at, + deadline, + candidate_lease_id: region.candidate_lease_id, + extensions: region.extensions, + }) .await; } else { warn!( @@ -301,13 +308,23 @@ enum CountdownCommand { /// 4 * `heartbeat_interval_millis` Start(u64), /// Reset countdown deadline to the given instance. - /// (NextRole, HeartbeatSentAt, Deadline, ExtensionInfo) - Reset((RegionRole, Instant, Instant, HashMap>)), + Reset(ResetLease), /// Returns the current deadline of the countdown task. #[cfg(test)] Deadline(oneshot::Sender), } +/// A region lease received in a heartbeat response. +#[derive(Debug)] +struct ResetLease { + role: RegionRole, + /// When the heartbeat was sent. + sent_at: Instant, + deadline: Instant, + candidate_lease_id: Option, + extensions: HashMap>, +} + pub type CountdownTaskHandlerExtRef = Arc; /// Extension trait for [CountdownTaskHandlerExt] to reset deadline of a region. @@ -319,7 +336,7 @@ pub trait CountdownTaskHandlerExt: Send + Sync { region_id: RegionId, role: RegionRole, deadline: Instant, - extension_info: HashMap>, + extensions: HashMap>, ); } @@ -379,23 +396,8 @@ impl CountdownTaskHandle { None } - async fn reset_deadline( - &self, - role: RegionRole, - sent_at: Instant, - deadline: Instant, - extension_info: HashMap>, - ) { - if let Err(e) = self - .tx - .send(CountdownCommand::Reset(( - role, - sent_at, - deadline, - extension_info, - ))) - .await - { + async fn reset_deadline(&self, lease: ResetLease) { + if let Err(e) = self.tx.send(CountdownCommand::Reset(lease)).await { warn!( "Failed to reset region alive keeper deadline: {e}. \ Maybe the task is stopped due to region been closed." @@ -447,9 +449,9 @@ impl CountdownTask { started = true; } }, - Some(CountdownCommand::Reset((role, sent_at, deadline, extension_info))) => { + Some(CountdownCommand::Reset(ResetLease { role, sent_at, deadline, candidate_lease_id, extensions })) => { let prev_role_leader = self.region_server.is_region_leader(self.region_id).unwrap_or(false); - let applied = match self.region_server.set_region_role_with_lease(self.region_id, role, sent_at.into_std(), deadline.into_std()) { + let applied = match self.region_server.set_region_role_with_lease(self.region_id, role, sent_at.into_std(), deadline.into_std(), candidate_lease_id) { Ok(applied) => applied, Err(err) => { if err.status_code() == StatusCode::RegionNotFound { @@ -480,7 +482,7 @@ impl CountdownTask { self.region_id, role, deadline, - extension_info, + extensions, ).await; } trace!( @@ -538,7 +540,10 @@ mod test { use crate::tests::{MockRegionEngine, mock_region_server}; /// Handles a heartbeat response that grants `regions` for a heartbeat sent now. - async fn handle_lease_response(alive_keeper: &RegionAliveKeeper, regions: Vec) { + async fn handle_lease_response( + alive_keeper: &RegionAliveKeeper, + regions: Vec, + ) { let sent_at = alive_keeper.epoch().elapsed(); handle_lease_response_sent_at(alive_keeper, sent_at, regions).await; } @@ -548,7 +553,7 @@ mod test { async fn handle_lease_response_sent_at( alive_keeper: &RegionAliveKeeper, sent_at: Duration, - regions: Vec, + regions: Vec, ) { let (tx, _rx) = mpsc::channel(1); let response = HeartbeatResponse { @@ -587,9 +592,10 @@ mod test { let alive_keeper = RegionAliveKeeper::new(region_server.clone(), None, Duration::from_millis(100)); alive_keeper.register_region(region_id).await; - let grant = GrantedRegion { + let grant = PbGrantedRegion { region_id: region_id.as_u64(), role: api::v1::meta::RegionRole::Leader.into(), + candidate_lease_id: 0, extensions: HashMap::new(), }; handle_lease_response(&alive_keeper, vec![grant]).await; @@ -598,6 +604,28 @@ mod test { assert_eq!(0, finalized.load(Ordering::Relaxed)); } + #[tokio::test(flavor = "multi_thread")] + async fn lease_response_passes_candidate_lease_id_to_engine() { + common_telemetry::init_default_ut_logging(); + let region_server = mock_region_server(); + let (engine, _) = MockRegionEngine::new(MITO_ENGINE_NAME); + let region_id = RegionId::new(1024, 1); + region_server.register_test_region(region_id, engine.clone()); + let alive_keeper = + RegionAliveKeeper::new(region_server.clone(), None, Duration::from_millis(100)); + alive_keeper.register_region(region_id).await; + let grant = PbGrantedRegion { + region_id: region_id.as_u64(), + role: api::v1::meta::RegionRole::Follower.into(), + candidate_lease_id: 7, + extensions: HashMap::new(), + }; + handle_lease_response(&alive_keeper, vec![grant]).await; + // The countdown task has handled the grant once it answers. + alive_keeper.deadline(region_id).await.unwrap(); + assert_eq!(*engine.candidate_lease_ids.lock().unwrap(), vec![Some(7)]); + } + #[tokio::test(flavor = "multi_thread")] async fn lease_responses_let_regions_write() { common_telemetry::init_default_ut_logging(); @@ -642,9 +670,10 @@ mod test { // A Leader grant renews the lease of the region. alive_keeper.register_region(region_id).await; - let grant = GrantedRegion { + let grant = PbGrantedRegion { region_id: region_id.as_u64(), role: api::v1::meta::RegionRole::Leader.into(), + candidate_lease_id: 0, extensions: HashMap::new(), }; handle_lease_response(&alive_keeper, vec![grant.clone()]).await; @@ -716,9 +745,10 @@ mod test { // Renew lease then sleep. alive_keeper .renew_region_leases( - &[GrantedRegion { + &[PbGrantedRegion { region_id: region_id.as_u64(), role: api::v1::meta::RegionRole::Leader.into(), + candidate_lease_id: 0, extensions: HashMap::new(), }], Instant::now(), @@ -773,12 +803,13 @@ mod test { // Reset deadline. countdown_handle - .reset_deadline( - RegionRole::Leader, - Instant::now(), - Instant::now() + Duration::from_millis(heartbeat_interval_millis * 5), - HashMap::new(), - ) + .reset_deadline(ResetLease { + role: RegionRole::Leader, + sent_at: Instant::now(), + deadline: Instant::now() + Duration::from_millis(heartbeat_interval_millis * 5), + candidate_lease_id: None, + extensions: HashMap::new(), + }) .await; assert!( countdown_handle.deadline().await.unwrap() @@ -821,9 +852,10 @@ mod test { alive_keeper.register_region(region_id).await; alive_keeper .renew_region_leases( - &[GrantedRegion { + &[PbGrantedRegion { region_id: region_id.as_u64(), role: api::v1::meta::RegionRole::StagingLeader.into(), + candidate_lease_id: 0, extensions: HashMap::new(), }], Instant::now(), @@ -870,9 +902,10 @@ mod test { alive_keeper.register_region(region_id).await; alive_keeper .renew_region_leases( - &[GrantedRegion { + &[PbGrantedRegion { region_id: region_id.as_u64(), role: api::v1::meta::RegionRole::Leader.into(), + candidate_lease_id: 0, extensions: HashMap::new(), }], Instant::now(), @@ -913,9 +946,10 @@ mod test { alive_keeper.register_region(region_id).await; alive_keeper .renew_region_leases( - &[GrantedRegion { + &[PbGrantedRegion { region_id: region_id.as_u64(), role: api::v1::meta::RegionRole::StagingLeader.into(), + candidate_lease_id: 0, extensions: HashMap::new(), }], Instant::now(), diff --git a/src/datanode/src/datanode.rs b/src/datanode/src/datanode.rs index f035ecb92ea..f33188a8208 100644 --- a/src/datanode/src/datanode.rs +++ b/src/datanode/src/datanode.rs @@ -41,7 +41,9 @@ use common_stat::ResourceStatImpl; use common_telemetry::{error, info, warn}; use common_wal::config::DatanodeWalConfig; use common_wal::config::kafka::DatanodeKafkaConfig; -use common_wal::config::object_store::{ObjectStoreWalConfig, STANDALONE_GENERATION}; +use common_wal::config::object_store::{ + EnableObjectStoreWal, FIXED_DIRECTORY_GENERATION, ObjectStoreWalConfig, +}; use common_wal::config::raft_engine::RaftEngineConfig; use file_engine::engine::FileRegionEngine; use futures::future::join_all; @@ -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::().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[®ION]; + + // The builder installs the permit: no test-side set_io_permit call. + assert_matches!( + log_store.seal_open_batch().await.unwrap_err(), + LogStoreError::ObjectStoreWalLeaseExpired { .. } + ); + assert_eq!(0, log_store.latest_entry_id(&provider).unwrap()); + let deadline = Instant::now() + Duration::from_secs(60); + engine.renew_node_lease(deadline); + log_store.seal_open_batch().await.unwrap(); + assert_eq!(entry_id, log_store.latest_entry_id(&provider).unwrap()); + engine.freeze_lease_clock(deadline); + assert_matches!( + log_store.seal_open_batch().await.unwrap_err(), + LogStoreError::ObjectStoreWalLeaseExpired { .. } + ); + engine.renew_node_lease(deadline + Duration::from_secs(60)); + log_store.seal_open_batch().await.unwrap(); + datanode.shutdown().await.unwrap(); + } + + #[tokio::test] + async fn test_cluster_object_store_wal_shutdown_keeps_heartbeat_until_drained() { + let data_home = create_temp_dir("cluster-wal-shutdown"); + let config = enqueued_wal_config(Duration::from_secs(3600)); + let mut builder = + object_store_wal_builder(data_home.path().to_str().unwrap(), config.clone()); + builder.plugins.insert(EnableObjectStoreWal); + builder.with_meta_client(Arc::new( + MetaClientBuilder::datanode_default_options(0).build(), + )); + let mut datanode = builder.build().await.unwrap(); + let log_store = datanode.object_store_log_store().unwrap(); + let engine = datanode.region_server.mito_engine().unwrap(); + engine.renew_node_lease(Instant::now() + WAIT); + // Observe the real close flag without starting network heartbeats. + let heartbeat_running = datanode + .heartbeat_task + .as_ref() + .unwrap() + .running_flag_for_test(); + heartbeat_running.store(true, Ordering::Release); + let provider = Provider::object_store_provider( + REGION, + config.node_prefix(0, FIXED_DIRECTORY_GENERATION), + ); + let entry = log_store.entry(vec![1], 0, REGION, &provider).unwrap(); + let response = log_store.append_batch(vec![entry]).await.unwrap(); + log_store.hold_creates(); + let shutdown = tokio::spawn(async move { datanode.shutdown().await }); + tokio::time::timeout(WAIT, log_store.wait_for_parked_creates(1)) + .await + .unwrap() + .unwrap(); + assert!(!shutdown.is_finished()); + assert!(heartbeat_running.load(Ordering::Acquire)); + log_store.release_creates(); + tokio::time::timeout(WAIT, shutdown) + .await + .unwrap() + .unwrap() + .unwrap(); + assert!(!heartbeat_running.load(Ordering::Acquire)); + assert_eq!( + response.last_entry_ids[®ION], + log_store.latest_entry_id(&provider).unwrap() + ); + } + #[tokio::test] async fn test_build_rejects_unknown_wal_storage_provider() { let data_home = create_temp_dir("object-store-wal-unknown-provider"); @@ -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 { - 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) { 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(); diff --git a/src/datanode/src/error.rs b/src/datanode/src/error.rs index d5037c2874e..2a560393ad7 100644 --- a/src/datanode/src/error.rs +++ b/src/datanode/src/error.rs @@ -330,7 +330,9 @@ pub enum Error { location: Location, }, - #[snafu(display("Object store WAL is only supported in standalone mode"))] + #[snafu(display( + "Object store WAL supports standalone only in this build; metasrv-controlled deployment requires a build with distributed object-store WAL integration" + ))] ObjectStoreWalNotStandalone { #[snafu(implicit)] location: Location, diff --git a/src/datanode/src/heartbeat.rs b/src/datanode/src/heartbeat.rs index a00e3487f5a..7127dbbd6a1 100644 --- a/src/datanode/src/heartbeat.rs +++ b/src/datanode/src/heartbeat.rs @@ -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 { + self.running.clone() + } + pub fn close(&self) -> Result<()> { let running = self.running.clone(); if running diff --git a/src/datanode/src/region_server.rs b/src/datanode/src/region_server.rs index 6755510a293..fbfa7ad57de 100644 --- a/src/datanode/src/region_server.rs +++ b/src/datanode/src/region_server.rs @@ -498,6 +498,7 @@ impl RegionServer { role: RegionRole, sent_at: std::time::Instant, deadline: std::time::Instant, + candidate_lease_id: Option, ) -> Result { let engine = self .inner @@ -505,7 +506,7 @@ impl RegionServer { .get(®ion_id) .with_context(|| RegionNotFoundSnafu { region_id })?; engine - .set_region_role_with_lease(region_id, role, sent_at, deadline) + .set_region_role_with_lease(region_id, role, sent_at, deadline, candidate_lease_id) .with_context(|_| HandleRegionRequestSnafu { region_id }) } @@ -1865,6 +1866,20 @@ impl RegionServerInner { &self, batch_request: BatchRegionDdlRequest, ) -> Result { + // Drops may remove dependent regions and may partially succeed. Complete each + // request's registration changes before proceeding to the next request. + if let BatchRegionDdlRequest::Drop(requests) = batch_request { + let mut response = RegionResponse::new(0); + for (region_id, request) in requests { + let result = self + .handle_request(region_id, RegionRequest::Drop(request)) + .await?; + response.affected_rows += result.affected_rows; + response.extensions.extend(result.extensions); + } + return Ok(response); + } + let region_changes = match &batch_request { BatchRegionDdlRequest::Create(requests) => requests .iter() @@ -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, ®ion_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::() else { + return Vec::new(); + }; + let logical_regions = metric_engine + .loaded_logical_regions(physical_region_id) + .into_iter() + .filter_map(|id| self.region_map.get(&id).map(|status| (id, status.clone()))) + .collect::>(); + for (region_id, _) in &logical_regions { + self.set_region_status_not_ready(*region_id, engine, &RegionChange::Deregisters); + } + logical_regions + } + async fn register_logical_regions( &self, engine: &RegionEngineRef, @@ -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; diff --git a/src/datanode/src/tests.rs b/src/datanode/src/tests.rs index a126d3429fd..0ee830af535 100644 --- a/src/datanode/src/tests.rs +++ b/src/datanode/src/tests.rs @@ -13,7 +13,7 @@ // limitations under the License. use std::any::Any; -use std::sync::Arc; +use std::sync::{Arc, Mutex}; use std::time::Duration; use api::region::RegionResponse; @@ -135,6 +135,8 @@ pub struct MockRegionEngine { pub(crate) handle_sync_region_mock_fn: Option, pub(crate) handle_stop_mock_fn: Option, pub(crate) mock_role: Option>, + /// The candidate lease ids of the leases the engine received. + pub(crate) candidate_lease_ids: Mutex>>, engine: String, } @@ -152,6 +154,7 @@ impl MockRegionEngine { handle_sync_region_mock_fn: None, handle_stop_mock_fn: None, mock_role: None, + candidate_lease_ids: Mutex::default(), engine: engine.to_string(), }), rx, @@ -174,6 +177,7 @@ impl MockRegionEngine { handle_sync_region_mock_fn: None, handle_stop_mock_fn: None, mock_role: None, + candidate_lease_ids: Mutex::default(), engine: engine.to_string(), }), rx, @@ -196,6 +200,7 @@ impl MockRegionEngine { handle_sync_region_mock_fn: None, handle_stop_mock_fn: None, mock_role: None, + candidate_lease_ids: Mutex::default(), engine: engine.to_string(), }), rx, @@ -219,6 +224,7 @@ impl MockRegionEngine { handle_sync_region_mock_fn: None, handle_stop_mock_fn: None, mock_role: None, + candidate_lease_ids: Mutex::default(), engine: engine.to_string(), }; @@ -295,7 +301,12 @@ impl RegionEngine for MockRegionEngine { role: RegionRole, _sent_at: std::time::Instant, _deadline: std::time::Instant, + candidate_lease_id: Option, ) -> Result { + self.candidate_lease_ids + .lock() + .unwrap() + .push(candidate_lease_id); // A mocked role stays, so a grant of another role is not applied. Ok(self.mock_role.flatten().is_none_or(|mocked| mocked == role)) } diff --git a/src/datatypes/src/json/value.rs b/src/datatypes/src/json/value.rs index 7bcb1ecc2b9..5d115f99441 100644 --- a/src/datatypes/src/json/value.rs +++ b/src/datatypes/src/json/value.rs @@ -379,6 +379,11 @@ impl JsonValue { self.json_variant } + /// Borrows the JSON representation without constructing a tree of value references. + pub fn variant(&self) -> &JsonVariant { + &self.json_variant + } + pub(crate) fn into_value(self) -> Value { fn helper(v: JsonVariant) -> Value { match v { diff --git a/src/file-engine/src/engine.rs b/src/file-engine/src/engine.rs index 98ad7409f43..a49b79fa65e 100644 --- a/src/file-engine/src/engine.rs +++ b/src/file-engine/src/engine.rs @@ -139,6 +139,7 @@ impl RegionEngine for FileRegionEngine { role: RegionRole, _sent_at: Instant, _deadline: Instant, + _candidate_lease_id: Option, ) -> Result { self.set_region_role(region_id, role).map(|_| true) } diff --git a/src/frontend/AGENTS.md b/src/frontend/AGENTS.md index 8a841c9a487..e108c5d3f4a 100644 --- a/src/frontend/AGENTS.md +++ b/src/frontend/AGENTS.md @@ -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 diff --git a/src/frontend/src/frontend.rs b/src/frontend/src/frontend.rs index 7e74d079d97..dc669313a55 100644 --- a/src/frontend/src/frontend.rs +++ b/src/frontend/src/frontend.rs @@ -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()", "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(), diff --git a/src/frontend/src/instance.rs b/src/frontend/src/instance.rs index e2d061167a7..6d8f98fdc0c 100644 --- a/src/frontend/src/instance.rs +++ b/src/frontend/src/instance.rs @@ -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, @@ -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, @@ -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 = diff --git a/src/frontend/src/instance/builder.rs b/src/frontend/src/instance/builder.rs index 395d9a8af26..3703c5bedea 100644 --- a/src/frontend/src/instance/builder.rs +++ b/src/frontend/src/instance/builder.rs @@ -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> { 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) @@ -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, diff --git a/src/frontend/src/instance/copy_in.rs b/src/frontend/src/instance/copy_in.rs index 6ffa3dfe27f..9b0f948e937 100644 --- a/src/frontend/src/instance/copy_in.rs +++ b/src/frontend/src/instance/copy_in.rs @@ -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>, + > { + Ok( + servers::query_handler::grpc::GrpcQueryHandler::handle_put_record_batch_stream( + self, stream, query_ctx, + ), + ) + } + async fn copy_in_insert( &self, requests: RowInsertRequests, diff --git a/src/frontend/src/instance/exemplar.rs b/src/frontend/src/instance/exemplar.rs index fc0f4862cff..e3b74388c4f 100644 --- a/src/frontend/src/instance/exemplar.rs +++ b/src/frontend/src/instance/exemplar.rs @@ -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>> { + 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::>>() + 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>, +) -> (Vec, 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::>(); + 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 { @@ -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::>(), + )); + 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 = 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::(), 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 = 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 { diff --git a/src/frontend/src/instance/logical_batcher.rs b/src/frontend/src/instance/logical_batcher.rs index b4755ebc974..3d1d7165179 100644 --- a/src/frontend/src/instance/logical_batcher.rs +++ b/src/frontend/src/instance/logical_batcher.rs @@ -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, diff --git a/src/frontend/src/instance/otlp.rs b/src/frontend/src/instance/otlp.rs index 5cc406a45dd..8afc1d99836 100644 --- a/src/frontend/src/instance/otlp.rs +++ b/src/frontend/src/instance/otlp.rs @@ -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::>()) - .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::>(); + 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; diff --git a/src/frontend/src/instance/prom_store.rs b/src/frontend/src/instance/prom_store.rs index 963a8ae22ed..4d13d391843 100644 --- a/src/frontend/src/instance/prom_store.rs +++ b/src/frontend/src/instance/prom_store.rs @@ -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, diff --git a/src/frontend/src/server.rs b/src/frontend/src/server.rs index 6eb63a0c910..bc16a4cfa10 100644 --- a/src/frontend/src/server.rs +++ b/src/frontend/src/server.rs @@ -73,11 +73,7 @@ where pub fn new(opts: T, instance: Arc, 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, diff --git a/src/log-store/src/error.rs b/src/log-store/src/error.rs index 3215db2ce21..8da6f8b71bb 100644 --- a/src/log-store/src/error.rs +++ b/src/log-store/src/error.rs @@ -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, @@ -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) diff --git a/src/log-store/src/metrics.rs b/src/log-store/src/metrics.rs index bdb123759eb..602db03147c 100644 --- a/src/log-store/src/metrics.rs +++ b/src/log-store/src/metrics.rs @@ -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 diff --git a/src/log-store/src/object_store_wal.rs b/src/log-store/src/object_store_wal.rs index 6a24a756475..d99c1df1a7a 100644 --- a/src/log-store/src/object_store_wal.rs +++ b/src/log-store/src/object_store_wal.rs @@ -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. diff --git a/src/log-store/src/object_store_wal/store.rs b/src/log-store/src/object_store_wal/store.rs index 46e76afdec5..7d58a8e2ba9 100644 --- a/src/log-store/src/object_store_wal/store.rs +++ b/src/log-store/src/object_store_wal/store.rs @@ -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, terminal_error: TerminalError, stopped: Arc, + /// 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, append_tx: mpsc::Sender, #[cfg(any(test, feature = "testing"))] @@ -180,6 +185,7 @@ type ObsoleteEntryIds = Arc>>; type StartedRegions = Arc>>; type WalHoles = Arc>>>; +type IoPermitSlot = Arc>>; /// 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::>() + .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) -> 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, + 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, append_rx: mpsc::Receiver, 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) -> 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) { 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) { 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>) { 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, /// 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, +} + +/// 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 { .map(|header| header.epoch) .max() .unwrap_or(0); + let mut skipped_epochs = BTreeMap::::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 { 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[®ion(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[®ion(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[®ion(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 { select_chain( &headers diff --git a/src/meta-srv/src/handler/region_lease_handler.rs b/src/meta-srv/src/handler/region_lease_handler.rs index a859bf18327..4f27b8f48e7 100644 --- a/src/meta-srv/src/handler/region_lease_handler.rs +++ b/src/meta-srv/src/handler/region_lease_handler.rs @@ -40,6 +40,11 @@ pub struct RegionLeaseHandler { pub type CustomizedRegionLeaseRenewerRef = Arc; 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::>(); renewer .renew(ctx, renewed) .into_iter() - .map(|region| region.into()) + .map(|region| { + GrantedRegion { + candidate_lease_id: candidate_lease_ids + .get(®ion.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::>() }; @@ -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, + ) -> Vec { + 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() { diff --git a/src/meta-srv/src/procedure/region_migration.rs b/src/meta-srv/src/procedure/region_migration.rs index 4f7967dd3c4..5210d3c7154 100644 --- a/src/meta-srv/src/procedure/region_migration.rs +++ b/src/meta-srv/src/procedure/region_migration.rs @@ -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, /// The deadline of leader region lease. leader_region_lease_deadline: Option, @@ -812,6 +814,9 @@ pub struct RegionMigrationData<'a> { pub(crate) struct RegionMigrationProcedure { state: Box, + /// 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, } @@ -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(); diff --git a/src/meta-srv/src/procedure/region_migration/manager.rs b/src/meta-srv/src/procedure/region_migration/manager.rs index 75bd28d6b9e..19553edb003 100644 --- a/src/meta-srv/src/procedure/region_migration/manager.rs +++ b/src/meta-srv/src/procedure/region_migration/manager.rs @@ -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(®ion_id)); + drop(running_procedures); + dropper.join().unwrap(); + assert!(tracker.running_procedures.read().unwrap().is_empty()); + } } diff --git a/src/meta-srv/src/procedure/region_migration/open_candidate_region.rs b/src/meta-srv/src/procedure/region_migration/open_candidate_region.rs index bc21746a046..670baae6875 100644 --- a/src/meta-srv/src/procedure/region_migration/open_candidate_region.rs +++ b/src/meta-srv/src/procedure/region_migration/open_candidate_region.rs @@ -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, ®ions)[®ion_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::().unwrap(); assert_matches!(flush_leader_region, PreFlushRegion); diff --git a/src/meta-srv/src/procedure/region_migration/test_util.rs b/src/meta-srv/src/procedure/region_migration/test_util.rs index ecee2eae0c5..49cb0f4b119 100644 --- a/src/meta-srv/src/procedure/region_migration/test_util.rs +++ b/src/meta-srv/src/procedure/region_migration/test_util.rs @@ -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>>, +} + +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>, +) { + 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>>) { + 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, + ) +} diff --git a/src/meta-srv/src/procedure/region_migration/update_metadata.rs b/src/meta-srv/src/procedure/region_migration/update_metadata.rs index e96a025c5de..42d28c06f6d 100644 --- a/src/meta-srv/src/procedure/region_migration/update_metadata.rs +++ b/src/meta-srv/src/procedure/region_migration/update_metadata.rs @@ -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?; diff --git a/src/meta-srv/src/procedure/region_migration/update_metadata/rollback_downgraded_region.rs b/src/meta-srv/src/procedure/region_migration/update_metadata/rollback_downgraded_region.rs index 1c9c12a9bc1..a8f94c3018b 100644 --- a/src/meta-srv/src/procedure/region_migration/update_metadata/rollback_downgraded_region.rs +++ b/src/meta-srv/src/procedure/region_migration/update_metadata/rollback_downgraded_region.rs @@ -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); + } } diff --git a/src/meta-srv/src/procedure/region_migration/upgrade_candidate_region.rs b/src/meta-srv/src/procedure/region_migration/upgrade_candidate_region.rs index dbd870076af..9b879962378 100644 --- a/src/meta-srv/src/procedure/region_migration/upgrade_candidate_region.rs +++ b/src/meta-srv/src/procedure/region_migration/upgrade_candidate_region.rs @@ -154,6 +154,12 @@ impl UpgradeCandidateRegion { .get(®ion_id) .copied(); let checkpoint = replay_checkpoints.get(®ion_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(); diff --git a/src/meta-srv/src/procedure/repartition.rs b/src/meta-srv/src/procedure/repartition.rs index 9011a122b90..30aaa93bc98 100644 --- a/src/meta-srv/src/procedure/repartition.rs +++ b/src/meta-srv/src/procedure/repartition.rs @@ -1370,24 +1370,30 @@ mod tests { let _guards = Context::register_operating_regions(&keeper, ®ion_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) ); } diff --git a/src/meta-srv/src/region/lease_keeper.rs b/src/meta-srv/src/region/lease_keeper.rs index d4a899d002d..97c22e50a1f 100644 --- a/src/meta-srv/src/region/lease_keeper.rs +++ b/src/meta-srv/src/region/lease_keeper.rs @@ -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, + operating_regions: &HashMap, datanode_id: DatanodeId, region_id: RegionId, reported_role: RegionRole, + table_route_exists: bool, ) -> Option { // `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(®ion_id) { - let region_lease_info = RegionLeaseInfo::operating(region_id, *role); - if *role != reported_role { + if let Some(operating_region) = operating_regions.get(®ion_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, } 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 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, - operating_regions: &HashMap, + operating_regions: &HashMap, datanode_id: DatanodeId, region_id: RegionId, reported_role: RegionRole, ) -> Option { + let table_route = table_metadata.get(®ion_id.table_id()); // First try to renew via region route - if let Some(table_route) = table_metadata.get(®ion_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(®ion_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, ) -> Result<( HashMap, - HashMap, + HashMap, )> { let operating_regions = self .memory_region_keeper - .extract_operating_region_roles(datanode_id, ®ion_ids); + .extract_operating_regions(datanode_id, ®ion_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) + )]) + ); + } } diff --git a/src/metric-engine/AGENTS.md b/src/metric-engine/AGENTS.md index 9c3820a0cc3..5efd43d82f6 100644 --- a/src/metric-engine/AGENTS.md +++ b/src/metric-engine/AGENTS.md @@ -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 diff --git a/src/metric-engine/Cargo.toml b/src/metric-engine/Cargo.toml index 0cc39dc5add..89c8ce3daef 100644 --- a/src/metric-engine/Cargo.toml +++ b/src/metric-engine/Cargo.toml @@ -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" diff --git a/src/metric-engine/src/engine.rs b/src/metric-engine/src/engine.rs index 3d3494ec7e7..ea307a21053 100644 --- a/src/metric-engine/src/engine.rs +++ b/src/metric-engine/src/engine.rs @@ -390,20 +390,34 @@ impl RegionEngine for MetricEngine { role: RegionRole, sent_at: Instant, deadline: Instant, + candidate_lease_id: Option, ) -> Result { // 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 { + 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> { 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, + ) { + 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; diff --git a/src/metric-engine/src/engine/drop.rs b/src/metric-engine/src/engine/drop.rs index f7db294478c..37868d4dfe6 100644 --- a/src/metric-engine/src/engine/drop.rs +++ b/src/metric-engine/src/engine/drop.rs @@ -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(); diff --git a/src/metric-engine/src/engine/put.rs b/src/metric-engine/src/engine/put.rs index eac38d0ab39..9b9295f02cd 100644 --- a/src/metric-engine/src/engine/put.rs +++ b/src/metric-engine/src/engine/put.rs @@ -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)); diff --git a/src/metric-engine/src/engine/state.rs b/src/metric-engine/src/engine/state.rs index cdc78fc3d00..0333bd75410 100644 --- a/src/metric-engine/src/engine/state.rs +++ b/src/metric-engine/src/engine/state.rs @@ -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(()) diff --git a/src/mito2/AGENTS.md b/src/mito2/AGENTS.md index 63cd2e19c1d..d5d3a04dda8 100644 --- a/src/mito2/AGENTS.md +++ b/src/mito2/AGENTS.md @@ -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 diff --git a/src/mito2/src/access_layer.rs b/src/mito2/src/access_layer.rs index 3a572b395bd..bb3b85de8aa 100644 --- a/src/mito2/src/access_layer.rs +++ b/src/mito2/src/access_layer.rs @@ -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; 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 { 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, + context: Option, ) -> Result { - 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, - ) -> Result { + 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"); diff --git a/src/mito2/src/cache/write_cache.rs b/src/mito2/src/cache/write_cache.rs index 37a4964a20e..ac4d4f6b3b2 100644 --- a/src/mito2/src/cache/write_cache.rs +++ b/src/mito2/src/cache/write_cache.rs @@ -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, - ) -> Result { + 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 { 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, + aborted: Arc, + } + + 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 { + 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 { + 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>, @@ -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); diff --git a/src/mito2/src/compaction/compactor.rs b/src/mito2/src/compaction/compactor.rs index 65404215175..0765a9273a4 100644 --- a/src/mito2/src/compaction/compactor.rs +++ b/src/mito2/src/compaction/compactor.rs @@ -12,16 +12,17 @@ // See the License for the specific language governing permissions and // limitations under the License. +use std::collections::HashSet; use std::num::NonZeroU64; use std::sync::Arc; use std::time::Duration; use common_base::Plugins; -use common_base::cancellation::CancellationHandle; use common_meta::key::SchemaMetadataManagerRef; use common_telemetry::{info, warn}; use common_time::TimeToLive; use either::Either; +use futures::{StreamExt, stream}; use itertools::Itertools; use object_store::manager::ObjectStoreManagerRef; use partition::expr::PartitionExpr; @@ -31,6 +32,7 @@ use store_api::ManifestVersion; use store_api::metadata::RegionMetadataRef; use store_api::region_request::PathType; use store_api::storage::{RegionId, SequenceNumber}; +use tokio_util::sync::CancellationToken; use crate::access_layer::{ AccessLayer, AccessLayerRef, Metrics, OperationType, SstWriteRequest, WriteType, @@ -53,14 +55,19 @@ use crate::region::version::VersionRef; use crate::region::{ManifestContext, RegionLeaderState, RegionRoleState}; use crate::schedule::scheduler::LocalScheduler; use crate::sst::FormatType; -use crate::sst::file::{self, FileHandle, FileMeta, UncommittedSsts}; +use crate::sst::file::{self, FileHandle, FileMeta, RegionFileId, UncommittedSsts}; use crate::sst::file_metadata::{FileMetadataInterner, FileMetadataInternerRef}; use crate::sst::file_purger::LocalFilePurger; +use crate::sst::index::IndexBuildType; +use crate::sst::index::build::IndexBuildInputs; +use crate::sst::index::handler::{IndexKindProviderRef, PlanContext}; use crate::sst::index::intermediate::IntermediateManager; use crate::sst::index::puffin_manager::PuffinManagerFactory; +use crate::sst::index::registry::{IndexBuildPlan, IndexRegistry}; use crate::sst::location::region_dir_from_table_dir; 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}; use crate::sst::version::{SstVersion, SstVersionRef}; @@ -144,11 +151,26 @@ pub struct CompactionContext { pub(crate) access_layer: AccessLayerRef, manifest_ctx: Arc, plugins: Plugins, + index_plan: Arc, + index_registry: Arc, + existing_index_inputs: Option>>, } -impl From<&CompactionRegion> for CompactionContext { - fn from(region: &CompactionRegion) -> Self { - Self { +impl TryFrom<&CompactionRegion> for CompactionContext { + type Error = error::Error; + + fn try_from(region: &CompactionRegion) -> Result { + let registry = IndexRegistry::from_config( + ®ion.engine_config, + region.plugins.get::(), + )?; + let index_plan = Arc::new(registry.plan(&PlanContext { + metadata: ®ion.region_metadata, + index_options: ®ion.current_version.options.index_options, + build_type: IndexBuildType::Compact, + existing_indexes: &[], + })); + Ok(Self { region_id: region.region_id, region_options: region.region_options.clone(), version_options: region.current_version.options.clone(), @@ -158,7 +180,10 @@ impl From<&CompactionRegion> for CompactionContext { access_layer: region.access_layer.clone(), manifest_ctx: region.manifest_ctx.clone(), plugins: region.plugins.clone(), - } + index_plan, + index_registry: Arc::new(registry), + existing_index_inputs: None, + }) } } @@ -391,57 +416,118 @@ impl CompactionRegion { /// before this unit's [`Compactor::update_manifest`] so its committed edit /// can be associated with the SST metadata reported here. pub async fn invoke_sst_hook(&self, merge_output: &MergeOutput) { - CompactionContext::from(self) - .invoke_sst_hook(merge_output) - .await; + invoke_sst_hook( + &self.plugins, + self.region_id, + &self.region_metadata, + merge_output, + ) + .await; } } -impl CompactionContext { - /// Reports this unit's output metadata before publishing its manifest edit. - pub(crate) async fn invoke_sst_hook(&self, merge_output: &MergeOutput) { - let Some(hook) = self.plugins.get::() else { - return; - }; +async fn invoke_sst_hook( + plugins: &Plugins, + region_id: RegionId, + metadata: &RegionMetadataRef, + merge_output: &MergeOutput, +) { + let Some(hook) = plugins.get::() else { + return; + }; - // Remote compaction deserializes `MergeOutput` over gRPC, where - // `sst_infos` is `#[serde(skip)]`. Rebuild each `SstInfo` from the - // matching `FileMeta` so the hook observes real ids/rows/sizes rather - // than zeros — see [`sst_info_from_file_meta`] for what stays default. - let synthesized: Vec; - let infos: &[SstInfo] = if merge_output.sst_infos.is_empty() { - synthesized = merge_output - .files_to_add - .iter() - .map(sst_info_from_file_meta) - .collect(); - &synthesized - } else { - // `sst_infos` and `files_to_add` are documented as 1:1. If they - // ever diverge, `zip` below would silently truncate; warn so the - // mismatch is observable rather than dropping files from the hook. - if merge_output.sst_infos.len() != merge_output.files_to_add.len() { - warn!( - "sst_infos length ({}) does not match files_to_add length ({}) for region {}", - merge_output.sst_infos.len(), - merge_output.files_to_add.len(), - self.region_id - ); - } - &merge_output.sst_infos - }; - - let files: Vec> = merge_output + // Remote compaction deserializes `MergeOutput` over gRPC, where + // `sst_infos` is `#[serde(skip)]`. Rebuild each `SstInfo` from the + // matching `FileMeta` so the hook observes real ids/rows/sizes rather + // than zeros — see [`sst_info_from_file_meta`] for what stays default. + let synthesized: Vec; + let infos: &[SstInfo] = if merge_output.sst_infos.is_empty() { + synthesized = merge_output .files_to_add .iter() - .zip(infos) - .map(|(meta, info)| SstFileInfo { - sst_info_ref: info, - file_meta: meta, - }) + .map(sst_info_from_file_meta) .collect(); - hook.on_sst_files_written(self.region_id, &self.region_metadata, &files) - .await; + &synthesized + } else { + // `sst_infos` and `files_to_add` are documented as 1:1. If they + // ever diverge, `zip` below would silently truncate; warn so the + // mismatch is observable rather than dropping files from the hook. + if merge_output.sst_infos.len() != merge_output.files_to_add.len() { + warn!( + "sst_infos length ({}) does not match files_to_add length ({}) for region {}", + merge_output.sst_infos.len(), + merge_output.files_to_add.len(), + region_id + ); + } + &merge_output.sst_infos + }; + + let files: Vec> = merge_output + .files_to_add + .iter() + .zip(infos) + .map(|(meta, info)| SstFileInfo { + sst_info_ref: info, + file_meta: meta, + }) + .collect(); + hook.on_sst_files_written(region_id, metadata, &files).await; +} + +impl CompactionContext { + /// Missing sketch implementations must not block compaction after a downgrade. + fn warn_missing_index_handlers<'a>(&self, inputs: impl Iterator) { + self.index_registry.warn_missing_compaction_handlers( + &self.region_metadata, + inputs.map(FileHandle::meta_ref), + ); + } + + /// Checks each physical input once before output tasks begin. Missing inputs + /// disable imported summaries without changing the reader's tolerant behavior. + async fn prepare_index_inputs<'a>( + &mut self, + inputs: impl Iterator, + cancellation: &CancellationToken, + ) -> Result<()> { + if !self.index_plan.needs_input_reuse() { + return Ok(()); + } + let ids: HashSet<_> = inputs.map(FileHandle::file_id).collect(); + let access_layer = &self.access_layer; + let existing = stream::iter(ids) + .map(|id| async move { + let path = crate::sst::location::sst_file_path( + access_layer.table_dir(), + id, + access_layer.path_type(), + ); + matches!(access_layer.object_store().exists(&path).await, Ok(true)).then_some(id) + }) + .buffer_unordered(8) + .filter_map(|id| async move { id }) + .collect::>(); + // Read-only probes can be dropped without waiting for writer cleanup. + let existing = tokio::select! { + biased; + _ = cancellation.cancelled() => return error::CompactionCancelledSnafu.fail(), + existing = existing => existing, + }; + // FileHandles protect ordinary purge; external object-store deletion can race. + self.existing_index_inputs = Some(Arc::new(existing)); + Ok(()) + } + + /// Reports this unit's output metadata before publishing its manifest edit. + pub(crate) async fn invoke_sst_hook(&self, merge_output: &MergeOutput) { + invoke_sst_hook( + &self.plugins, + self.region_id, + &self.region_metadata, + merge_output, + ) + .await; } /// Publishes outputs through the existing manifest validation and hook path. @@ -555,11 +641,14 @@ pub trait Compactor: Send + Sync + 'static { /// implementations in tests. #[async_trait::async_trait] pub trait SstMerger: Send + Sync + 'static { + /// Merges an output, observing cancellation at safe boundaries and draining + /// in-flight writers before returning. async fn merge_single_output( &self, context: CompactionContext, output: CompactionOutput, write_opts: WriteOptions, + cancellation: CancellationToken, ) -> Result<(Vec, Vec)>; } @@ -596,6 +685,33 @@ fn known_max_input_sequence(inputs: &[FileHandle]) -> Option { crate::sst::file::known_max_input_sequence(inputs.iter().map(FileHandle::meta_ref)) } +/// Whole-input summaries require a complete output without file rollover. +fn can_reuse_output_inputs(output: &CompactionOutput, has_rollover: bool) -> bool { + !has_rollover && output.output_time_range.is_none() +} + +/// Whole-file summaries are usable only when reading needs no partition filtering. +fn output_matches_partition( + output: &CompactionOutput, + partition_expr: Option<&PartitionExpr>, +) -> bool { + partition_expr.is_none() + || output + .inputs + .iter() + .all(|input| input.meta_ref().partition_expr.as_deref() == partition_expr) +} + +fn reusable_index_inputs( + outputs: &[CompactionOutput], + has_rollover: bool, +) -> impl Iterator { + outputs + .iter() + .filter(move |output| can_reuse_output_inputs(output, has_rollover)) + .flat_map(|output| output.inputs.iter()) +} + fn validate_region_compaction_output(region_id: RegionId, output: &CompactionOutput) -> Result<()> { ensure!( output.output_level < file::LEVEL_SHARED @@ -618,6 +734,37 @@ impl SstMerger for DefaultSstMerger { context: CompactionContext, output: CompactionOutput, write_opts: WriteOptions, + cancellation: CancellationToken, + ) -> Result<(Vec, Vec)> { + let uncommitted = UncommittedSsts::new( + context.region_id, + context.access_layer.clone(), + Some(context.cache_manager.clone()), + ); + let result = self + .merge_output(context, output, write_opts, &uncommitted, cancellation) + .await; + if result.is_err() { + uncommitted.cleanup().await; + } else { + // Successful outputs are transferred to the caller for publication. + uncommitted.disarm_cleanup(); + } + match result { + Err(error::Error::SstWriteCancelled { .. }) => error::CompactionCancelledSnafu.fail(), + result => result, + } + } +} + +impl DefaultSstMerger { + async fn merge_output( + &self, + context: CompactionContext, + output: CompactionOutput, + write_opts: WriteOptions, + uncommitted: &UncommittedSsts, + cancellation: CancellationToken, ) -> Result<(Vec, Vec)> { let region_id = context.region_id; validate_region_compaction_output(region_id, &output)?; @@ -652,15 +799,56 @@ impl SstMerger for DefaultSstMerger { merge_mode, read_parallelism: write_opts.encode_parallelism, }; - let source = spawn_merge(builder.build_flat_sst_reader().await?); + // Matching file scopes need no additional region filtering. Rollover and + // time slicing still require output-scoped accumulation. + let partition_expr = match context.region_metadata.partition_expr.as_deref() { + None | Some("") => None, + Some(expr) => { + PartitionExpr::from_json_str(expr).with_context(|_| InvalidPartitionExprSnafu { + expr: expr.to_string(), + })? + } + }; + let can_merge_inputs = can_reuse_output_inputs(&output, write_opts.max_file_size.is_some()) + && output_matches_partition(&output, partition_expr.as_ref()) + && context + .existing_index_inputs + .as_ref() + .is_some_and(|existing| { + output + .inputs + .iter() + .all(|input| existing.contains(&input.file_id())) + }); + let index_build_inputs = Some(IndexBuildInputs { + output_rows: None, + plan: context.index_plan.clone(), + memory_limit: None, + inputs: if context.index_plan.needs_input_reuse() { + output.inputs.clone().into() + } else { + Arc::from([]) + }, + input_puffin_manager: context + .access_layer + .build_puffin_manager() + .with_puffin_metadata_cache(context.cache_manager.puffin_metadata_cache().cloned()), + can_merge_inputs, + }); + let source = tokio::select! { + biased; + _ = cancellation.cancelled() => return error::CompactionCancelledSnafu.fail(), + source = builder.build_flat_sst_reader() => source?, + }; + let source = spawn_merge(source); let mut metrics = Metrics::new(WriteType::Compaction); let region_metadata = context.region_metadata.clone(); let sst_infos = context .access_layer - .write_sst( + .write_sst_with_context( SstWriteRequest { - index_build_inputs: None, + index_build_inputs, op_type: OperationType::Compact, metadata: region_metadata.clone(), source, @@ -683,19 +871,13 @@ impl SstMerger for DefaultSstMerger { }, &write_opts, &mut metrics, + SstWriteContext { + guard: Some(Arc::new(uncommitted.clone())), + cancellation: Some(cancellation), + ..Default::default() + }, ) .await?; - // Convert partition expression once outside the map - let partition_expr = match ®ion_metadata.partition_expr { - None => None, - Some(json_str) if json_str.is_empty() => None, - Some(json_str) => PartitionExpr::from_json_str(json_str).with_context(|_| { - InvalidPartitionExprSnafu { - expr: json_str.clone(), - } - })?, - }; - let output_files = sst_infos .iter() .map(|sst_info| { @@ -746,7 +928,7 @@ impl SstMerger for DefaultSstMerger { /// implementations in tests. pub struct DefaultCompactor { merger: M, - cancel_handle: Arc, + cancel_token: CancellationToken, uncommitted: Option, } @@ -755,37 +937,37 @@ impl DefaultCompactor { pub fn with_merger(merger: M) -> Self { Self { merger, - cancel_handle: Arc::new(CancellationHandle::default()), + cancel_token: CancellationToken::new(), uncommitted: None, } } } impl DefaultCompactor { - /// Creates a new `DefaultCompactor` with the given cancel handle and no + /// Creates a new `DefaultCompactor` with the given cancellation token and no /// uncommitted SSTs tracking. /// /// This is the public entry point for external crates that want a /// cancellable compactor without opting into uncommitted-SST tracking. /// - /// Cancellation stops new output batches. Already spawned outputs finish, - /// and their successful SSTs remain in the returned [`MergeOutput`]. This - /// can delay cancellation until the current batch completes. - pub fn new_with_cancel_handle(cancel_handle: Arc) -> Self { + /// Cancellation stops new output batches and interrupts active outputs at + /// batch and upload-chunk boundaries. Successful complete outputs remain in + /// the returned [`MergeOutput`]; incomplete outputs are cleaned up. + pub fn new_with_cancel_token(cancel_token: CancellationToken) -> Self { Self { merger: DefaultSstMerger, - cancel_handle, + cancel_token, uncommitted: None, } } - pub(crate) fn with_cancel_handle( - cancel_handle: Arc, + pub(crate) fn with_cancel_token( + cancel_token: CancellationToken, uncommitted: UncommittedSsts, ) -> Self { Self { merger: DefaultSstMerger, - cancel_handle, + cancel_token, uncommitted: Some(uncommitted), } } @@ -798,17 +980,25 @@ impl DefaultCompactor { context: &CompactionContext, unit: &CompactionUnit, ) -> Result { + context.warn_missing_index_handlers(unit.inputs.iter()); + let mut context = context.clone(); + context + .prepare_index_inputs( + reusable_index_inputs(&unit.outputs, unit.max_file_size.is_some()), + &self.cancel_token, + ) + .await?; let mut result = MergeOutput { files_to_remove: unit.inputs.iter().map(|f| f.meta_ref().clone()).collect(), compaction_time_window: Some(unit.time_window_size), ..Default::default() }; for output in &unit.outputs { - if self.cancel_handle.is_cancelled() { + if self.cancel_token.is_cancelled() { return error::CompactionCancelledSnafu.fail(); } - // Let the writer finish and register its files before observing cancellation. - // Dropping it mid-write can lose ownership of already finalized SSTs. + // The merger observes cancellation and drains its writers before returning. + // Keep awaiting it so cleanup cannot race with a late finalized SST. let (files, infos) = self .merger .merge_single_output( @@ -828,6 +1018,7 @@ impl DefaultCompactor { ), encode_runtime: EncodeRuntime::Compact, }, + self.cancel_token.clone(), ) .await?; if let Some(uncommitted) = &self.uncommitted { @@ -836,7 +1027,7 @@ impl DefaultCompactor { result.files_to_add.extend(files); result.sst_infos.extend(infos); } - if self.cancel_handle.is_cancelled() { + if self.cancel_token.is_cancelled() { return error::CompactionCancelledSnafu.fail(); } Ok(result) @@ -869,7 +1060,22 @@ where let internal_parallelism = compaction_region.max_parallelism.max(1); let compaction_time_window = picker_output.time_window_size; let region_id = compaction_region.region_id; - let context = CompactionContext::from(compaction_region); + let mut context = CompactionContext::try_from(compaction_region)?; + context.warn_missing_index_handlers( + picker_output + .outputs + .iter() + .flat_map(|output| output.inputs.iter()), + ); + context + .prepare_index_inputs( + reusable_index_inputs( + &picker_output.outputs, + picker_output.max_file_size.is_some(), + ), + &self.cancel_token, + ) + .await?; // Build tasks along with their input file metas so we can track which // inputs correspond to each task. @@ -895,9 +1101,10 @@ where let merger = self.merger.clone(); let context = context.clone(); let uncommitted = self.uncommitted.clone(); + let cancellation = self.cancel_token.clone(); let fut = async move { let result = merger - .merge_single_output(context, output, write_opts) + .merge_single_output(context, output, write_opts, cancellation) .await; if let (Some(uncommitted), Ok((_, infos))) = (&uncommitted, &result) { uncommitted.track(infos); @@ -915,7 +1122,7 @@ where + picker_output.expired_ssts.len(), ); - while !tasks.is_empty() && !self.cancel_handle.is_cancelled() { + while !tasks.is_empty() && !self.cancel_token.is_cancelled() { let mut chunk: Vec<(Vec, _)> = Vec::with_capacity(internal_parallelism); for _ in 0..internal_parallelism { if let Some(task) = tasks.pop() { @@ -930,9 +1137,8 @@ where }) .collect(); - // Like merge_unit, cancellation must not drop a writer mid-output: - // its blocking encoders would detach and finalized SSTs could lose - // their owner. Join the whole batch and retain every successful output. + // Each merger cancels cooperatively and owns its incomplete outputs. + // Join every sibling before returning so writers and cleanup cannot race. let mut join_error = None; while let Some((inputs, handle)) = spawned.pop() { match handle.await { @@ -943,6 +1149,7 @@ where } compacted_inputs.extend(inputs); } + Ok(Err(error::Error::CompactionCancelled { .. })) => {} Ok(Err(e)) => { warn!( e; "Failed to merge compaction output for region: {}, inputs: [{}]", @@ -966,7 +1173,7 @@ where return Err(e).context(error::JoinSnafu); } - if self.cancel_handle.is_cancelled() { + if self.cancel_token.is_cancelled() { info!("Compaction merge cancelled for region: {}", region_id); break; } @@ -993,7 +1200,7 @@ where compaction_region: &CompactionRegion, merge_output: MergeOutput, ) -> Result<(RegionEdit, ManifestVersion)> { - CompactionContext::from(compaction_region) + CompactionContext::try_from(compaction_region)? .update_manifest(merge_output) .await } @@ -1005,10 +1212,16 @@ mod tests { use std::sync::{Arc, Mutex, Weak}; use std::time::Duration; + use common_error::ext::BoxedError; + use common_time::Timestamp; + use common_time::range::TimestampRange; use datatypes::arrow::record_batch::RecordBatch; + use object_store::ObjectStore; + use object_store::layers::mock::{self, MockLayerBuilder}; + use object_store::services::Memory; use parquet::arrow::ArrowWriter; use store_api::storage::{FileId, RegionId}; - use tokio::sync::{mpsc, oneshot}; + use tokio::sync::{Notify, mpsc, oneshot}; use tokio::time::timeout; use super::{DefaultCompactor, *}; @@ -1017,6 +1230,10 @@ mod tests { use crate::error::Result; use crate::sst::file::FileHandle; use crate::sst::file_purger::NoopFilePurger; + use crate::sst::index::handler::{ + BuildContext, IndexCreator, IndexKindHandler, IndexKindProvider, PlanEntry, PlannedIndex, + }; + use crate::sst::index::kind::{ExtensionIndexKind, IndexKind}; use crate::test_util::sst_util::new_record_batch_by_range; fn dummy_file_meta() -> FileMeta { @@ -1032,6 +1249,371 @@ mod tests { FileHandle::new(meta, Arc::new(NoopFilePurger)) } + struct PendingCompactionReader { + started: Arc, + } + + impl mock::oio::Read for PendingCompactionReader { + async fn open( + &self, + _: mock::BytesRange, + ) -> object_store::Result<(mock::RpRead, Box)> { + self.started.notify_one(); + std::future::pending().await + } + + async fn read( + &self, + _: mock::BytesRange, + ) -> object_store::Result<(mock::RpRead, object_store::Buffer)> { + self.started.notify_one(); + std::future::pending().await + } + } + + #[rstest::rstest] + #[case::unit(true)] + #[case::outputs(false)] + #[tokio::test] + async fn test_default_merger_observes_compactor_cancellation(#[case] merge_unit: bool) { + let mut region = new_test_compaction_region().await; + let started = Arc::new(Notify::new()); + let signal = started.clone(); + let layer = MockLayerBuilder::default() + .reader_factory(Arc::new(move |_, _, _| { + Box::new(PendingCompactionReader { + started: signal.clone(), + }) + })) + .build() + .unwrap(); + let store = ObjectStore::new(Memory::default()).unwrap().layer(layer); + let access = ®ion.access_layer; + region.access_layer = Arc::new(AccessLayer::new( + access.table_dir(), + access.path_type(), + store.clone(), + access.puffin_manager_factory().clone(), + access.intermediate_manager().clone(), + )); + let input = new_file_handle(dummy_file_meta()); + store + .write( + &input.file_path( + region.access_layer.table_dir(), + region.access_layer.path_type(), + ), + vec![0; input.meta_ref().file_size as usize], + ) + .await + .unwrap(); + let picker_output = PickerOutput { + outputs: vec![CompactionOutput { + output_level: 1, + inputs: vec![input], + filter_deleted: false, + output_time_range: None, + }], + ..Default::default() + }; + let compactor = DefaultCompactor::with_merger(DefaultSstMerger); + let context = CompactionContext::try_from(®ion).unwrap(); + let mut merge = Box::pin(async { + if merge_unit { + let unit = CompactionUnit::from_picker(picker_output) + .unwrap() + .pop() + .unwrap(); + compactor.merge_unit(&context, &unit).await + } else { + compactor.merge_ssts(®ion, picker_output).await + } + }); + tokio::select! { + _ = started.notified() => {}, + result = &mut merge => panic!("merge returned before cancellation: {result:?}"), + _ = tokio::time::sleep(Duration::from_secs(10)) => panic!("merge did not reach the reader"), + } + compactor.cancel_token.cancel(); + let result = timeout(Duration::from_secs(10), merge).await.unwrap(); + if merge_unit { + assert!(matches!( + result, + Err(error::Error::CompactionCancelled { .. }) + )); + } else { + let result = result.unwrap(); + assert!(result.files_to_add.is_empty()); + assert!(result.files_to_remove.is_empty()); + } + } + + #[derive(Debug)] + struct InputReusePlan; + + impl IndexKindHandler for InputReusePlan { + fn validate(&self, _context: &PlanContext<'_>) -> std::result::Result<(), BoxedError> { + Ok(()) + } + + fn kinds(&self) -> &[IndexKind] { + &[IndexKind::Extension(ExtensionIndexKind::Hll)] + } + + fn plan( + &self, + _context: &PlanContext<'_>, + ) -> std::result::Result>, BoxedError> { + Ok(Some(Arc::new(Self))) + } + } + + #[async_trait::async_trait] + impl PlannedIndex for InputReusePlan { + fn kinds(&self) -> &[IndexKind] { + IndexKindHandler::kinds(self) + } + + fn entries(&self) -> &[PlanEntry] { + &[] + } + + fn needs_input_reuse(&self) -> bool { + true + } + + async fn build( + &self, + _context: &BuildContext<'_>, + ) -> std::result::Result>, BoxedError> { + Ok(None) + } + + fn is_current(&self, _file: &FileMeta, _context: &PlanContext<'_>) -> bool { + true + } + } + + impl IndexKindProvider for InputReusePlan { + fn handlers(&self) -> Vec> { + vec![Arc::new(Self)] + } + } + + #[rstest::rstest] + #[case::unit(true)] + #[case::outputs(false)] + #[tokio::test] + async fn test_index_input_probes_observe_cancellation( + #[case] merge_unit: bool, + #[values(false, true)] cancelled_before_start: bool, + ) { + let mut region = new_test_compaction_region().await; + region + .plugins + .insert::(Arc::new(InputReusePlan)); + let started = Arc::new(Notify::new()); + let probes = Arc::new(AtomicUsize::new(0)); + let signal = started.clone(); + let observed = probes.clone(); + let layer = MockLayerBuilder::default() + .stat_interceptor(Arc::new(move |_| { + let signal = signal.clone(); + let observed = observed.clone(); + Box::pin(async move { + observed.fetch_add(1, Ordering::Relaxed); + signal.notify_one(); + std::future::pending().await + }) + })) + .build() + .unwrap(); + let store = ObjectStore::new(Memory::default()).unwrap().layer(layer); + let access = ®ion.access_layer; + region.access_layer = Arc::new(AccessLayer::new( + access.table_dir(), + access.path_type(), + store, + access.puffin_manager_factory().clone(), + access.intermediate_manager().clone(), + )); + let picker_output = PickerOutput { + outputs: vec![CompactionOutput { + output_level: 1, + inputs: vec![new_file_handle(dummy_file_meta())], + filter_deleted: false, + output_time_range: None, + }], + ..Default::default() + }; + let compactor = DefaultCompactor::with_merger(DefaultSstMerger); + let context = CompactionContext::try_from(®ion).unwrap(); + let mut merge = Box::pin(async { + if merge_unit { + let unit = CompactionUnit::from_picker(picker_output) + .unwrap() + .pop() + .unwrap(); + compactor.merge_unit(&context, &unit).await + } else { + compactor.merge_ssts(®ion, picker_output).await + } + }); + if !cancelled_before_start { + tokio::select! { + _ = started.notified() => {}, + result = &mut merge => panic!("merge returned before cancellation: {result:?}"), + _ = tokio::time::sleep(Duration::from_secs(10)) => panic!("merge did not reach input probes"), + } + } + compactor.cancel_token.cancel(); + let result = timeout(Duration::from_secs(10), merge).await.unwrap(); + assert!(matches!( + result, + Err(error::Error::CompactionCancelled { .. }) + )); + assert_eq!( + probes.load(Ordering::Relaxed), + usize::from(!cancelled_before_start) + ); + assert!(context.existing_index_inputs.is_none()); + } + + #[derive(Debug)] + struct DuplicateIndexProvider; + + impl IndexKindProvider for DuplicateIndexProvider { + fn handlers(&self) -> Vec> { + vec![Arc::new(InputReusePlan), Arc::new(InputReusePlan)] + } + } + + #[tokio::test] + async fn test_context_rejects_duplicate_provider_before_merge() { + let region = new_test_compaction_region().await; + region + .plugins + .insert::(Arc::new(DuplicateIndexProvider)); + assert!(CompactionContext::try_from(®ion).is_err()); + } + + #[test] + fn test_reusable_inputs_exclude_sliced_outputs_and_rollover() { + let whole = new_file_handle(dummy_file_meta()); + let sliced = new_file_handle(dummy_file_meta()); + let outputs = vec![ + CompactionOutput { + output_level: 1, + inputs: vec![whole.clone()], + filter_deleted: true, + output_time_range: None, + }, + CompactionOutput { + output_level: 1, + inputs: vec![sliced], + filter_deleted: false, + output_time_range: TimestampRange::new( + Timestamp::new_second(0), + Timestamp::new_second(1), + ), + }, + ]; + assert_eq!( + reusable_index_inputs(&outputs, false) + .map(FileHandle::file_id) + .collect::>(), + vec![whole.file_id()], + ); + assert_eq!(reusable_index_inputs(&outputs, true).count(), 0); + } + + #[test] + fn test_reuse_requires_all_input_partition_scopes_to_match() { + use datatypes::value::Value; + use partition::expr::{RestrictedOp, col}; + + let scope = PartitionExpr::new(col("tag_0"), RestrictedOp::GtEq, Value::UInt32(10).into()); + let other = PartitionExpr::new(col("tag_0"), RestrictedOp::GtEq, Value::UInt32(20).into()); + for (scopes, expected) in [ + (vec![Some(scope.clone()), Some(scope.clone())], true), + (vec![Some(scope.clone()), None], false), + (vec![Some(scope.clone()), Some(other)], false), + ] { + let output = CompactionOutput { + output_level: 1, + inputs: scopes + .into_iter() + .map(|partition_expr| { + let mut meta = dummy_file_meta(); + meta.partition_expr = partition_expr.map(Into::into); + new_file_handle(meta) + }) + .collect(), + filter_deleted: true, + output_time_range: None, + }; + assert_eq!(output_matches_partition(&output, Some(&scope)), expected); + assert!(output_matches_partition(&output, None)); + } + } + + #[tokio::test] + async fn test_index_input_preparation_tracks_physical_files() { + let mut region = new_test_compaction_region().await; + Arc::make_mut(&mut region.region_metadata).column_metadatas[0] + .column_schema + .set_inverted_index(true); + let mut context = CompactionContext::try_from(®ion).unwrap(); + assert!(context.existing_index_inputs.is_none()); + // Builtin plans do not probe physical inputs solely for optional reuse. + context + .prepare_index_inputs(std::iter::empty(), &CancellationToken::new()) + .await + .unwrap(); + assert!(context.existing_index_inputs.is_none()); + let mut registry = + IndexRegistry::new(Default::default(), Default::default(), Default::default()); + registry.register(Arc::new(InputReusePlan)).unwrap(); + context.index_plan = Arc::new(registry.plan(&PlanContext { + metadata: &context.region_metadata, + index_options: &context.version_options.index_options, + build_type: IndexBuildType::Compact, + existing_indexes: &[], + })); + let present = new_file_handle(dummy_file_meta()); + let missing = new_file_handle(dummy_file_meta()); + let path = crate::sst::location::sst_file_path( + context.access_layer.table_dir(), + present.file_id(), + context.access_layer.path_type(), + ); + context + .access_layer + .object_store() + .write(&path, vec![1]) + .await + .unwrap(); + // Duplicate references are checked as one physical input. Only successfully + // probed files can contribute imported summaries to an output. + context + .prepare_index_inputs( + [&present, &missing, &present].into_iter(), + &CancellationToken::new(), + ) + .await + .unwrap(); + assert_eq!( + context.existing_index_inputs.as_deref(), + Some(&HashSet::from([present.file_id()])) + ); + let prepared = context.clone(); + assert!(Arc::ptr_eq( + context.existing_index_inputs.as_ref().unwrap(), + prepared.existing_index_inputs.as_ref().unwrap() + )); + assert!(Arc::ptr_eq(&context.index_plan, &prepared.index_plan)); + } + #[test] fn test_effective_target_trust_and_max_sequence() { let target = RegionId::new(1, 1); @@ -1162,8 +1744,10 @@ mod tests { for preserve in [false, true] { region.region_options.preserve_row_sequence = preserve; for (inputs, known_bound, inputs_trusted) in &cases { - let metadata = - output_sequence_metadata(&CompactionContext::from(®ion), inputs); + let metadata = output_sequence_metadata( + &CompactionContext::try_from(®ion).unwrap(), + inputs, + ); let trusted = preserve && *inputs_trusted; assert_eq!(trusted, metadata.exact_sequence_trusted); assert_eq!( @@ -1409,6 +1993,13 @@ mod tests { access_layer: region.access_layer.clone(), manifest_ctx: region.manifest_ctx.clone(), plugins: Plugins::new(), + index_plan: Arc::default(), + index_registry: Arc::new(IndexRegistry::new( + Default::default(), + Default::default(), + Default::default(), + )), + existing_index_inputs: None, }; region .access_layer @@ -1420,7 +2011,12 @@ mod tests { .await .unwrap(); let (files, _) = DefaultSstMerger - .merge_single_output(context, output, WriteOptions::default()) + .merge_single_output( + context, + output, + WriteOptions::default(), + CancellationToken::new(), + ) .await .unwrap(); assert_eq!(1, files.len()); @@ -1481,6 +2077,7 @@ mod tests { _context: CompactionContext, _output: CompactionOutput, _write_opts: WriteOptions, + _cancellation: CancellationToken, ) -> Result<(Vec, Vec)> { let idx = self.call_idx.fetch_add(1, Ordering::SeqCst); match self.results.lock().unwrap().get(idx) { @@ -1496,7 +2093,7 @@ mod tests { #[tokio::test] async fn test_compaction_unit_group_failure_is_atomic() { - let context = CompactionContext::from(&new_test_compaction_region().await); + let context = CompactionContext::try_from(&new_test_compaction_region().await).unwrap(); let input = new_file_handle(dummy_file_meta()); let unit = CompactionUnit::from_picker(PickerOutput { outputs: (0..2) @@ -1544,6 +2141,111 @@ mod tests { } } + #[tokio::test] + async fn test_missing_index_handler_does_not_block_builtin_compaction() { + use api::v1::SemanticType; + use datatypes::prelude::ConcreteDataType; + use datatypes::schema::{ + ColumnSchema, FulltextOptions, SkippingIndexOptions, SkippingIndexType, + }; + use store_api::metadata::{ColumnMetadata, RegionMetadataBuilder}; + + use crate::sst::file::{ColumnIndexMetadata, IndexType}; + + #[derive(Debug, PartialEq, Eq)] + enum RequiredBy { + None, + Schema, + File, + Column, + } + for required_by in [ + RequiredBy::None, + RequiredBy::Schema, + RequiredBy::File, + RequiredBy::Column, + ] { + let mut region = new_test_compaction_region().await; + Arc::make_mut(&mut region.region_metadata).column_metadatas[0] + .column_schema + .set_inverted_index(true); + let mut metadata = + RegionMetadataBuilder::from_existing((*region.region_metadata).clone()); + metadata.push_column_metadata(ColumnMetadata { + column_schema: ColumnSchema::new("text", ConcreteDataType::string_datatype(), true) + .with_fulltext_options(FulltextOptions { + enable: true, + ..Default::default() + }) + .unwrap() + .with_skipping_options(SkippingIndexOptions::new_unchecked( + 42, + 0.01, + SkippingIndexType::BloomFilter, + )) + .unwrap(), + semantic_type: SemanticType::Field, + column_id: 5, + }); + region.region_metadata = Arc::new(metadata.build().unwrap()); + let mut input = dummy_file_meta(); + match required_by { + RequiredBy::Schema => { + Arc::make_mut(&mut region.region_metadata).column_metadatas[0] + .column_schema + .mut_metadata() + .insert( + datatypes::schema::HLL_KEY.into(), + r#"{"precision":10}"#.into(), + ); + } + RequiredBy::File => input.available_indexes.push(IndexType::HllIndex), + RequiredBy::Column => input.indexes.push(ColumnIndexMetadata { + column_id: 0, + created_indexes: [IndexType::HllIndex].into_iter().collect(), + ..Default::default() + }), + _ => {} + } + let context = CompactionContext::try_from(®ion).unwrap(); + assert_eq!( + context + .index_plan + .planned() + .iter() + .flat_map(|plan| plan.kinds().iter().copied()) + .collect::>(), + [IndexKind::Inverted, IndexKind::Fulltext, IndexKind::Bloom] + ); + let output = PickerOutput { + outputs: vec![CompactionOutput { + output_level: 1, + inputs: vec![new_file_handle(input)], + filter_deleted: false, + output_time_range: None, + }], + ..Default::default() + }; + for local in [false, true] { + let merger = MockMerger::new(vec![Ok(Vec::new())]); + let calls = merger.call_idx.clone(); + let compactor = DefaultCompactor::with_merger(merger); + let result = if local { + let context = CompactionContext::try_from(®ion).unwrap(); + let unit = CompactionUnit::from_picker(output.clone()) + .unwrap() + .pop() + .unwrap(); + compactor.merge_unit(&context, &unit).await + } else { + compactor.merge_ssts(®ion, output.clone()).await + }; + assert!(result.is_ok(), "{required_by:?}, local={local}: {result:?}"); + assert_eq!(calls.load(Ordering::SeqCst), 1); + } + } + } + #[tokio::test] async fn test_partial_merge_failure_collects_only_successful_outputs() { common_telemetry::init_default_ut_logging(); @@ -1713,6 +2415,7 @@ mod tests { _context: CompactionContext, output: CompactionOutput, _write_opts: WriteOptions, + _cancellation: CancellationToken, ) -> Result<(Vec, Vec)> { let input_id = output.inputs[0].meta_ref().file_id; let mut file = dummy_file_meta(); @@ -1765,7 +2468,7 @@ mod tests { .collect(), ..Default::default() }; - let cancel_handle = Arc::new(CancellationHandle::default()); + let cancel_token = CancellationToken::new(); let (started_tx, mut started_rx) = mpsc::unbounded_channel(); let compactor = DefaultCompactor { merger: GatedEncodingMerger { @@ -1773,7 +2476,7 @@ mod tests { // Outputs are popped from the back, then joined in reverse order. panic_input: panic_merge.then_some(inputs[1].file_id), }, - cancel_handle: cancel_handle.clone(), + cancel_token: cancel_token.clone(), uncommitted: None, }; let memory = new_compaction_memory_manager(1024 * 1024); @@ -1792,7 +2495,7 @@ mod tests { .unwrap(), ); } - cancel_handle.cancel(); + cancel_token.cancel(); assert!(futures::poll!(merge.as_mut()).is_pending()); assert!(memory.try_acquire(memory.limit_bytes()).is_none()); assert!( @@ -1855,7 +2558,7 @@ mod tests { let merger = MockMerger::new(vec![Ok(vec![dummy_file_meta()])]); let calls = merger.call_idx.clone(); let compactor = DefaultCompactor::with_merger(merger); - compactor.cancel_handle.cancel(); + compactor.cancel_token.cancel(); let picker_output = PickerOutput { outputs: vec![CompactionOutput { output_level: 1, diff --git a/src/mito2/src/compaction/multi_region.rs b/src/mito2/src/compaction/multi_region.rs index de4549a4c5c..19df7c03969 100644 --- a/src/mito2/src/compaction/multi_region.rs +++ b/src/mito2/src/compaction/multi_region.rs @@ -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, pub access_layer: AccessLayerRef, pub cache: CacheManagerRef, pub config: Arc, pub protection: Arc, - pub cancellation: Arc, + 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 { 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 { diff --git a/src/mito2/src/compaction/multi_region/memory.rs b/src/mito2/src/compaction/multi_region/memory.rs index 1bc774d7313..00c985f4be7 100644 --- a/src/mito2/src/compaction/multi_region/memory.rs +++ b/src/mito2/src/compaction/multi_region/memory.rs @@ -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, 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], + 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, + 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 + } + ); + } +} diff --git a/src/mito2/src/compaction/multi_region/source.rs b/src/mito2/src/compaction/multi_region/source.rs index 313f57778f5..95ff2065453 100644 --- a/src/mito2/src/compaction/multi_region/source.rs +++ b/src/mito2/src/compaction/multi_region/source.rs @@ -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>, peak_group_bytes: AtomicU64, - cancellation: Arc, + cancellation: CancellationToken, stop: CancellationToken, counters: Arc, } @@ -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::>(); + 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, limit: usize) -> MemoryThreshold { + MemoryThreshold::Size(ReadableSize(configured.unwrap_or(limit).min(limit) as u64)) +} diff --git a/src/mito2/src/compaction/multi_region/tests.rs b/src/mito2/src/compaction/multi_region/tests.rs index 67709443086..4bbe9bfaad0 100644 --- a/src/mito2/src/compaction/multi_region/tests.rs +++ b/src/mito2/src/compaction/multi_region/tests.rs @@ -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); +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> { + 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>, 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> { + // 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 = 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 + ))) + ); + } + } +} diff --git a/src/mito2/src/compaction/multi_region/worker.rs b/src/mito2/src/compaction/multi_region/worker.rs index b52bda6367c..384c9a4be7f 100644 --- a/src/mito2/src/compaction/multi_region/worker.rs +++ b/src/mito2/src/compaction/multi_region/worker.rs @@ -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?; diff --git a/src/mito2/src/compaction/multi_region/writer.rs b/src/mito2/src/compaction/multi_region/writer.rs index 6e20cefcfe2..4423c423d2f 100644 --- a/src/mito2/src/compaction/multi_region/writer.rs +++ b/src/mito2/src/compaction/multi_region/writer.rs @@ -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, max_file_size: usize, sequence: Option, 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, ) -> 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 { 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) -> 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, + cancellation: CancellationToken, ) -> Result { let projection: Vec<_> = source .schema() diff --git a/src/mito2/src/compaction/scheduler/local.rs b/src/mito2/src/compaction/scheduler/local.rs index 9286c1232f5..d938267cda9 100644 --- a/src/mito2/src/compaction/scheduler/local.rs +++ b/src/mito2/src/compaction/scheduler/local.rs @@ -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, reserved: CompactingFiles, - ) -> CompactionPhase { + ) -> Result { // 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(®ion); + let context = CompactionContext::try_from(®ion)?; // 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. diff --git a/src/mito2/src/compaction/scheduler/planning.rs b/src/mito2/src/compaction/scheduler/planning.rs index 47a99b682b4..dc8175559a4 100644 --- a/src/mito2/src/compaction/scheduler/planning.rs +++ b/src/mito2/src/compaction/scheduler/planning.rs @@ -629,7 +629,7 @@ impl CompactionScheduler { compaction_region, units, files, - ))) + )?)) } fn exceeds_compaction_memory_limit(&self, estimated_bytes: u64) -> Option { diff --git a/src/mito2/src/compaction/scheduler_test.rs b/src/mito2/src/compaction/scheduler_test.rs index 27b126ff843..bb9276d2b80 100644 --- a/src/mito2/src/compaction/scheduler_test.rs +++ b/src/mito2/src/compaction/scheduler_test.rs @@ -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 diff --git a/src/mito2/src/compaction/task.rs b/src/mito2/src/compaction/task.rs index 666601fcf85..2394ed5fa18 100644 --- a/src/mito2/src/compaction/task.rs +++ b/src/mito2/src/compaction/task.rs @@ -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(®ion), + compaction_context: CompactionContext::try_from(®ion).unwrap(), request_sender, listener: WorkerListener::new(Some(Arc::new(PanicOnUnitMergeBegin))), unit: CompactionUnit { diff --git a/src/mito2/src/engine.rs b/src/mito2/src/engine.rs index ac3c3144d2d..e257b046989 100644 --- a/src/mito2/src/engine.rs +++ b/src/mito2/src/engine.rs @@ -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 { + 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, + ) { + 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 { + 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(®ion, previous); self.notify_if_became_writable(®ion, 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, + ) { + 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, ) -> Result { + // 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(®ion, was_writable); return Ok(promoted); } - region.set_role(role); + let previous = region.set_role(role); + self.inner.notify_if_can_no_longer_replay(®ion, previous); Ok(true) } diff --git a/src/mito2/src/engine/close_test.rs b/src/mito2/src/engine/close_test.rs index dd9ea8cf710..f113bb1e611 100644 --- a/src/mito2/src/engine/close_test.rs +++ b/src/mito2/src/engine/close_test.rs @@ -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(); +} diff --git a/src/mito2/src/engine/create_test.rs b/src/mito2/src/engine/create_test.rs index 895d15b4195..219757a4f5e 100644 --- a/src/mito2/src/engine/create_test.rs +++ b/src/mito2/src/engine/create_test.rs @@ -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>, 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> { + vec![Arc::new(ValidatingHandler)] + } + } + let mut env = TestEnv::new().await; + let plugins = Plugins::new(); + plugins.insert::(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(®ion_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(®ion_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; diff --git a/src/mito2/src/engine/index_build_test.rs b/src/mito2/src/engine/index_build_test.rs index d586eedff7f..b156076b405 100644 --- a/src/mito2/src/engine/index_build_test.rs +++ b/src/mito2/src/engine/index_build_test.rs @@ -15,25 +15,28 @@ //! Index build tests for mito engine. //! use std::collections::{HashMap, HashSet}; -use std::sync::Arc; -use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; +use std::sync::{Arc, Mutex}; use std::time::Duration; use api::v1::region::{StrictWindow, compact_request}; use api::v1::{Rows, SemanticType}; use async_trait::async_trait; +use common_base::Plugins; use common_base::readable_size::ReadableSize; -use common_error::ext::ErrorExt; +use common_error::ext::{BoxedError, ErrorExt, PlainError}; use common_error::status_code::StatusCode; use common_recordbatch::RecordBatches; use datafusion_expr::expr::InList; use datafusion_expr::{Expr, col, lit}; use datatypes::arrow::array::AsArray; use datatypes::arrow::datatypes::TimestampMillisecondType; +use datatypes::arrow::record_batch::RecordBatch; use datatypes::prelude::ConcreteDataType; -use datatypes::schema::{ColumnSchema, SkippingIndexOptions, SkippingIndexType}; +use datatypes::schema::{ColumnSchema, FulltextOptions, SkippingIndexOptions, SkippingIndexType}; +use puffin::puffin_manager::{PuffinManager, PuffinReader, PuffinWriter}; use store_api::metadata::ColumnMetadata; -use store_api::region_engine::RegionEngine; +use store_api::region_engine::{RegionEngine, SetRegionRoleStateResponse, SettableRegionRoleState}; use store_api::region_request::{ AddColumn, AlterKind, RegionAlterRequest, RegionBuildIndexRequest, RegionCloseRequest, RegionCompactRequest, RegionFlushRequest, RegionRequest, RegionTruncateRequest, SetIndexOption, @@ -48,15 +51,24 @@ use crate::engine::MitoEngine; use crate::engine::compaction_test::put_and_flush; use crate::engine::listener::{EventListener, GateIndexBuildListener, IndexBuildListener}; use crate::manifest::action::RegionEdit; +use crate::read::Batch; use crate::read::scan_region::{ScanRegion, Scanner}; -use crate::sst::file::{FileMeta, RegionFileId, RegionIndexId}; +use crate::sst::file::{FileMeta, IndexType, RegionFileId, RegionIndexId}; +use crate::sst::index::handler::{ + BuildContext, IndexCreator, IndexKindHandler, IndexKindProvider, IndexKindProviderRef, + PlanContext, PlanEntry, PlannedIndex, +}; +use crate::sst::index::kind::{ExtensionIndexKind, IndexKind}; +use crate::sst::index::puffin_manager::SstPuffinWriter; +use crate::sst::index::{CompletedEntry, IndexBuildType}; use crate::sst::location; use crate::test_util::batch_util::sort_batches_and_print; use crate::test_util::{ - CreateRequestBuilder, TestEnv, build_rows, flush_region, put_rows, reopen_region, rows_schema, + CheckpointTaskBlocker, CreateRequestBuilder, TestEnv, build_rows, flush_region, put_rows, + reopen_region, rows_schema, }; -fn async_build_mode_config(is_create_on_flush: bool) -> MitoConfig { +pub(crate) fn async_build_mode_config(is_create_on_flush: bool) -> MitoConfig { let mut config = MitoConfig::default(); config.index.build_mode = IndexBuildMode::Async; if !is_create_on_flush { @@ -1179,22 +1191,23 @@ async fn test_consecutive_schema_changes_publish_latest_index_generation() { )); } +#[rstest::rstest] +#[case(IndexBuildType::Flush)] +#[case(IndexBuildType::Compact)] #[tokio::test] -async fn test_unrelated_schema_change_retries_stale_flush_index_build() { +async fn test_unrelated_schema_change_retries_background_index_without_provider( + #[case] build_type: IndexBuildType, +) { let mut env = TestEnv::with_prefix("test_unrelated_schema_change_retries_stale_index_build_").await; let gate = Arc::new(IndexPublicationGate::new( IndexPublicationPhase::BeforeManifestCommit, )); - let engine = Arc::new( - env.create_engine_with( - async_build_mode_config(true), - None, - Some(gate.clone()), - None, - ) - .await, - ); + let plugins = Plugins::new(); + plugins.insert::(Arc::new(RebuildSketchProvider::default())); + let mut setup_config = async_build_mode_config(false); + setup_config.index.build_mode = IndexBuildMode::Sync; + let setup_engine = env.create_engine_with_plugins(setup_config, plugins).await; let region_id = RegionId::new(1, 1); env.get_schema_metadata_manager() @@ -1208,16 +1221,60 @@ async fn test_unrelated_schema_change_retries_stale_flush_index_build() { ) .await; - let request = CreateRequestBuilder::new().build_with_index(); + let mut request = CreateRequestBuilder::new() + .insert_option("compaction.type", "twcs") + .insert_option("compaction.twcs.trigger_file_num", "4") + .build_with_index(); + request.column_metadatas[0] + .column_schema + .mut_metadata() + .insert( + datatypes::schema::HLL_KEY.into(), + r#"{"precision":10}"#.into(), + ); + let table_dir = request.table_dir.clone(); + let options = request.options.clone(); let column_schemas = rows_schema(&request); - engine + setup_engine .handle_request(region_id, RegionRequest::Create(request)) .await .unwrap(); - put_and_flush(&engine, region_id, &column_schemas, 0..20).await; + if build_type == IndexBuildType::Compact { + put_and_flush(&setup_engine, region_id, &column_schemas, 0..10).await; + put_and_flush(&setup_engine, region_id, &column_schemas, 10..20).await; + } + setup_engine.stop().await.unwrap(); + drop(setup_engine); + env.log_store = None; + let engine = Arc::new( + env.create_engine_with( + async_build_mode_config(build_type == IndexBuildType::Flush), + None, + Some(gate.clone()), + None, + ) + .await, + ); + reopen_region(&engine, region_id, table_dir, true, options).await; + if build_type == IndexBuildType::Flush { + put_and_flush(&engine, region_id, &column_schemas, 0..20).await; + } else { + engine + .handle_request( + region_id, + RegionRequest::Compact(RegionCompactRequest { + options: compact_request::Options::StrictWindow(StrictWindow { + window_seconds: 3600, + }), + ..Default::default() + }), + ) + .await + .unwrap(); + } tokio::time::timeout(Duration::from_secs(10), gate.wait_entered(1)) .await - .expect("flush index build did not reach manifest publication"); + .expect("background index build did not reach manifest publication"); engine .handle_request( @@ -1245,7 +1302,7 @@ async fn test_unrelated_schema_change_retries_stale_flush_index_build() { gate.release(1); tokio::time::timeout(Duration::from_secs(10), gate.wait_entered(2)) .await - .expect("stale flush index build was not retried"); + .expect("stale background index build was not retried"); gate.release(1); tokio::time::timeout(Duration::from_secs(10), gate.wait_stopped(2)) .await @@ -1267,6 +1324,11 @@ async fn test_unrelated_schema_change_retries_stale_flush_index_build() { .await .unwrap(); assert_eq!(num_of_index_files(&engine, &scanner, region_id).await, 1); + assert_eq!( + files[0].available_indexes.as_slice(), + &[IndexType::InvertedIndex] + ); + engine.stop().await.unwrap(); } #[tokio::test] @@ -2578,3 +2640,1186 @@ async fn test_truncate_while_indexing_encoded_bulk_part_removes_uploaded_sst() { .collect::>(); assert!(leftovers.is_empty(), "{leftovers:?}"); } + +#[derive(Debug, Default, Clone)] +struct RebuildSketchProvider { + fail_manual_plan: bool, + memory_limit: Option, + manual_build: bool, + manual_finished: Arc, + manual_plans: Arc, + compact_plans: Arc, + creates: Arc, + readable_inputs: Arc>>, +} + +impl IndexKindProvider for RebuildSketchProvider { + fn handlers(&self) -> Vec> { + vec![Arc::new(self.clone())] + } +} + +impl IndexKindHandler for RebuildSketchProvider { + fn kinds(&self) -> &[IndexKind] { + &[IndexKind::Extension(ExtensionIndexKind::Hll)] + } + + fn validate(&self, _: &PlanContext<'_>) -> Result<(), BoxedError> { + Ok(()) + } + + fn plan(&self, context: &PlanContext<'_>) -> Result>, BoxedError> { + if context.build_type == IndexBuildType::Compact { + self.compact_plans.fetch_add(1, Ordering::Relaxed); + } + if context.build_type == IndexBuildType::Manual { + self.manual_plans.fetch_add(1, Ordering::Relaxed); + if self.fail_manual_plan { + return Err(BoxedError::new(PlainError::new( + "injected manual plan failure".into(), + StatusCode::Internal, + ))); + } + } + if context.build_type == IndexBuildType::Flush { + return Ok(None); + } + if matches!( + context.build_type, + IndexBuildType::Manual | IndexBuildType::SchemaChange + ) && self.memory_limit.is_none() + && !context + .existing_indexes + .iter() + .any(|column| column.created_indexes.contains(&IndexType::HllIndex)) + { + return Ok(None); + } + assert!( + context + .metadata + .column_by_id(0) + .unwrap() + .column_schema + .metadata() + .contains_key(datatypes::schema::HLL_KEY) + ); + Ok(Some(Arc::new(Self { + manual_build: context.build_type == IndexBuildType::Manual, + ..self.clone() + }))) + } +} + +#[async_trait] +impl PlannedIndex for RebuildSketchProvider { + fn kinds(&self) -> &[IndexKind] { + IndexKindHandler::kinds(self) + } + fn entries(&self) -> &[PlanEntry] { + &[PlanEntry { + column_id: 0, + kind: IndexKind::Extension(ExtensionIndexKind::Hll), + format_version: 1, + }] + } + fn is_current(&self, file: &FileMeta, _: &PlanContext<'_>) -> bool { + self.manual_finished.load(Ordering::Relaxed) + && file + .indexes + .iter() + .any(|column| column.created_indexes.contains(&IndexType::HllIndex)) + } + + fn memory_limit(&self) -> Option { + self.memory_limit + } + + async fn build( + &self, + context: &BuildContext<'_>, + ) -> Result>, BoxedError> { + for input in context.inputs.iter() { + // Initial compaction may read flush files that have no sketches yet. + if !input.meta_ref().indexes.iter().any(|column| { + column.created_indexes.iter().any(|kind| { + matches!( + kind, + IndexType::HllIndex | IndexType::KllIndex | IndexType::MgIndex + ) + }) + }) { + continue; + } + let reader = context + .input_puffin_manager + .reader(&input.index_id()) + .await + .unwrap(); + let metadata = reader.metadata().await.unwrap(); + assert!( + metadata + .blobs + .iter() + .any(|blob| blob.blob_type == "test.sketch") + ); + self.readable_inputs + .lock() + .unwrap() + .push((input.index_id(), context.can_merge_inputs)); + } + self.creates.fetch_add(1, Ordering::Relaxed); + Ok(Some(Box::new(RebuildSketchCreator { + rows: 0, + manual_finished: self.manual_build.then(|| self.manual_finished.clone()), + }))) + } +} + +#[derive(Debug)] +struct RebuildSketchCreator { + rows: usize, + manual_finished: Option>, +} + +#[async_trait] +impl IndexCreator for RebuildSketchCreator { + async fn update(&mut self, batch: &mut Batch) -> Result<(), BoxedError> { + self.rows += batch.num_rows(); + Ok(()) + } + + async fn update_flat(&mut self, batch: &RecordBatch) -> Result<(), BoxedError> { + self.rows += batch.num_rows(); + Ok(()) + } + + async fn finish( + &mut self, + writer: &mut SstPuffinWriter, + ) -> Result, BoxedError> { + writer + .put_blob( + "test.sketch", + futures::io::Cursor::new(self.rows.to_le_bytes().to_vec()), + Default::default(), + HashMap::new(), + ) + .await + .map_err(BoxedError::new)?; + if let Some(finished) = &self.manual_finished { + finished.store(true, Ordering::Relaxed); + } + Ok(vec![CompletedEntry { + column_id: Some(0), + kind: IndexKind::Extension(ExtensionIndexKind::Hll), + format_version: 1, + }]) + } + + async fn abort(&mut self) -> Result<(), BoxedError> { + Ok(()) + } + + fn memory_usage(&self) -> usize { + self.rows * std::mem::size_of::() + } +} + +#[rstest::rstest] +#[case(false)] +#[case(true)] +#[tokio::test] +async fn test_async_compaction_respects_optional_sketch_provider(#[case] registered: bool) { + let mut env = TestEnv::new().await; + let provider = Arc::new(RebuildSketchProvider::default()); + let plugins = Plugins::new(); + plugins.insert::(provider.clone()); + let mut setup_config = async_build_mode_config(false); + setup_config.index.build_mode = IndexBuildMode::Sync; + let engine = env.create_engine_with_plugins(setup_config, plugins).await; + let region_id = RegionId::new(1, 1); + env.get_schema_metadata_manager() + .register_region_table_info( + region_id.table_id(), + "test_table", + "test_catalog", + "test_schema", + None, + env.get_kv_backend(), + ) + .await; + let mut request = CreateRequestBuilder::new() + .insert_option("compaction.type", "twcs") + .insert_option("compaction.twcs.trigger_file_num", "4") + .build_with_index(); + request.column_metadatas[0] + .column_schema + .mut_metadata() + .insert( + datatypes::schema::HLL_KEY.into(), + r#"{"precision":10}"#.into(), + ); + let table_dir = request.table_dir.clone(); + let options = request.options.clone(); + let schema = rows_schema(&request); + engine + .handle_request(region_id, RegionRequest::Create(request)) + .await + .unwrap(); + for start in [0, 2] { + put_rows( + &engine, + region_id, + Rows { + schema: schema.clone(), + rows: build_rows(start, start + 2), + }, + ) + .await; + flush_region(&engine, region_id, None).await; + } + let inputs = engine + .get_region(region_id) + .unwrap() + .all_manifest_files() + .await + .0; + assert_eq!(inputs.len(), 2); + assert!(inputs.iter().all(|file| file.available_indexes.is_empty())); + engine.stop().await.unwrap(); + + let plugins = Plugins::new(); + if registered { + plugins.insert::(provider.clone()); + } + let engine = env + .new_mito_engine_with_plugins(async_build_mode_config(false), plugins) + .await; + reopen_region(&engine, region_id, table_dir, true, options).await; + engine + .handle_request( + region_id, + RegionRequest::Compact(RegionCompactRequest { + options: compact_request::Options::StrictWindow(StrictWindow { + window_seconds: 3600, + }), + ..Default::default() + }), + ) + .await + .unwrap(); + + let region = engine.get_region(region_id).unwrap(); + tokio::time::timeout(Duration::from_secs(10), async { + loop { + let files = region.all_manifest_files().await.0; + if let [output] = files.as_slice() + && !inputs.iter().any(|input| input.file_id == output.file_id) + && output.available_indexes.contains(&IndexType::InvertedIndex) + { + let expected: &[IndexType] = if registered { + &[IndexType::InvertedIndex, IndexType::HllIndex] + } else { + &[IndexType::InvertedIndex] + }; + assert_eq!(output.available_indexes.as_slice(), expected); + assert_eq!(output.num_rows, 4); + assert_tag_inverted_index(®ion.access_layer, output.index_id()).await; + if registered { + assert_eq!(output.index_version, 0); + assert_sketch_rows(®ion.access_layer, output.index_id(), 4).await; + } + break; + } + tokio::time::sleep(Duration::from_millis(10)).await; + } + }) + .await + .expect("async compaction did not publish built-in indexes"); + if registered { + assert!(provider.compact_plans.load(Ordering::Relaxed) > 0); + assert_eq!(provider.creates.load(Ordering::Relaxed), 1); + } else { + assert_eq!(provider.compact_plans.load(Ordering::Relaxed), 0); + assert_eq!(provider.creates.load(Ordering::Relaxed), 0); + } + engine.stop().await.unwrap(); +} + +/// Reads the rebuilt inverted blob rather than trusting its manifest descriptor. +async fn assert_tag_inverted_index( + layer: &crate::access_layer::AccessLayer, + index_id: RegionIndexId, +) { + use index::inverted_index::format::reader::{InvertedIndexBlobReader, InvertedIndexReader}; + use puffin::puffin_manager::{PuffinManager, PuffinReader}; + + let manager = layer.build_puffin_manager(); + let reader = manager.reader(&index_id).await.unwrap(); + let blob = reader + .blob(crate::sst::index::inverted_index::INDEX_BLOB_TYPE) + .await + .unwrap() + .reader() + .await + .unwrap(); + let reader = InvertedIndexBlobReader::new(blob); + let metadata = reader.metadata(None).await.unwrap(); + let target = index::target::IndexTarget::ColumnId(0); + let meta = &metadata.metas[&target.encode()]; + assert_eq!(metadata.total_row_count, 4); + let fst = reader + .fst( + meta.base_offset + u64::from(meta.relative_fst_offset), + meta.fst_size, + None, + ) + .await + .unwrap(); + assert_eq!(fst.len(), 4); + for value in ["0", "1", "2", "3"] { + let mut encoded = Vec::new(); + mito_codec::index::IndexValueCodec::encode_nonnull_value( + datatypes::value::ValueRef::String(value), + &mito_codec::row_converter::SortField::new(ConcreteDataType::string_datatype()), + &mut encoded, + ) + .unwrap(); + assert!(fst.get(&encoded).is_some(), "missing tag {value}"); + } +} + +async fn assert_sketch_rows( + layer: &crate::access_layer::AccessLayer, + index_id: RegionIndexId, + expected_rows: usize, +) { + use common_base::range_read::RangeReader; + + let manager = layer.build_puffin_manager(); + let reader = manager.reader(&index_id).await.unwrap(); + let blob = reader.blob("test.sketch").await.unwrap(); + let reader = blob.reader().await.unwrap(); + let metadata = reader.metadata().await.unwrap(); + let bytes = reader.read(0..metadata.content_length).await.unwrap(); + assert_eq!(bytes.as_ref(), expected_rows.to_le_bytes().as_slice()); +} + +#[tokio::test] +async fn test_async_compaction_builds_and_manual_rebuild_maintains_sketch() { + use common_base::Plugins; + let mut env = TestEnv::new().await; + let plugins = Plugins::new(); + let provider = Arc::new(RebuildSketchProvider::default()); + plugins.insert::(provider.clone()); + let engine = env + .create_engine_with_plugins(async_build_mode_config(false), plugins) + .await; + let region_id = RegionId::new(1, 1); + let mut request = CreateRequestBuilder::new() + .insert_option("sst_format", "flat") + .build(); + request.column_metadatas[0] + .column_schema + .set_inverted_index(true); + request + .column_metadatas + .iter_mut() + .find(|column| column.column_id == 0) + .unwrap() + .column_schema + .mut_metadata() + .insert( + datatypes::schema::HLL_KEY.into(), + r#"{"precision":10}"#.into(), + ); + let schema = rows_schema(&request); + engine + .handle_request(region_id, RegionRequest::Create(request)) + .await + .unwrap(); + for start in [0, 2] { + let rows = build_rows(start, start + 2); + put_rows( + &engine, + region_id, + Rows { + schema: schema.clone(), + rows, + }, + ) + .await; + flush_region(&engine, region_id, None).await; + } + engine + .handle_request( + region_id, + RegionRequest::BuildIndex(RegionBuildIndexRequest::default()), + ) + .await + .unwrap(); + assert_eq!( + 0, + provider.creates.load(Ordering::Relaxed), + "manual rebuild must not introduce sketches on flush files" + ); + engine + .handle_request( + region_id, + RegionRequest::Compact(RegionCompactRequest::default()), + ) + .await + .unwrap(); + let region = engine.get_region(region_id).unwrap(); + tokio::time::timeout(Duration::from_secs(10), async { + loop { + let files = region.all_manifest_files().await.0; + if files.len() == 1 + && files[0].indexes.iter().any(|column| { + column.created_indexes.iter().any(|kind| { + matches!( + kind, + crate::sst::file::IndexType::HllIndex + | crate::sst::file::IndexType::KllIndex + | crate::sst::file::IndexType::MgIndex + ) + }) + }) + { + break; + } + tokio::time::sleep(Duration::from_millis(10)).await; + } + }) + .await + .unwrap(); + let before = region.all_manifest_files().await.0[0].clone(); + assert_eq!(before.index_version, 0); + assert_tag_inverted_index(®ion.access_layer, before.index_id()).await; + assert_sketch_rows(®ion.access_layer, before.index_id(), 4).await; + let before_inputs = provider.readable_inputs.lock().unwrap().len(); + let before_creates = provider.creates.load(Ordering::Relaxed); + engine + .handle_request( + region_id, + RegionRequest::BuildIndex(RegionBuildIndexRequest::default()), + ) + .await + .unwrap(); + let files = region.all_manifest_files().await.0; + assert_eq!(before_creates + 1, provider.creates.load(Ordering::Relaxed)); + assert!(files[0].index_version > before.index_version); + assert_eq!( + &provider.readable_inputs.lock().unwrap()[before_inputs..], + &[(before.index_id(), true)], + "manual rebuild must read the current manifest's committed Puffin version" + ); + assert!(files[0].indexes.iter().any(|column| { + column + .created_indexes + .contains(&crate::sst::file::IndexType::HllIndex) + })); + assert_tag_inverted_index(®ion.access_layer, files[0].index_id()).await; + assert_sketch_rows(®ion.access_layer, files[0].index_id(), 4).await; + engine.stop().await.unwrap(); +} + +#[tokio::test] +async fn test_rebuild_column_only_index_advances_zero_generation() { + use crate::sst::file::{ColumnIndexMetadata, IndexType}; + use common_base::Plugins; + + let mut env = TestEnv::new().await; + let plugins = Plugins::new(); + let provider = Arc::new(RebuildSketchProvider::default()); + plugins.insert::(provider.clone()); + 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":10}"#.into(), + ); + let table_dir = request.table_dir.clone(); + let schema = rows_schema(&request); + engine + .handle_request(region_id, RegionRequest::Create(request)) + .await + .unwrap(); + for start in [0, 2] { + put_and_flush(&engine, region_id, &schema, start..start + 2).await; + } + engine + .handle_request( + region_id, + RegionRequest::Compact(RegionCompactRequest::default()), + ) + .await + .unwrap(); + let region = engine.get_region(region_id).unwrap(); + let mut files = region.all_manifest_files().await.0; + assert_eq!(files.len(), 1); + let mut before = files.pop().unwrap(); + assert_eq!(before.index_version, 0); + assert!(before.index_file_size > 0); + before.available_indexes.clear(); + before.indexes = vec![ColumnIndexMetadata { + column_id: 0, + created_indexes: [IndexType::HllIndex].into_iter().collect(), + ..Default::default() + }]; + let old_path = location::index_file_path( + region.access_layer.table_dir(), + before.index_id(), + region.access_layer.path_type(), + ); + let store = region.access_layer.object_store().clone(); + let old_bytes = store.read(&old_path).await.unwrap().to_vec(); + engine + .edit_region( + region_id, + RegionEdit { + files_to_add: vec![before.clone()], + ..Default::default() + }, + ) + .await + .unwrap(); + reopen_region(&engine, region_id, table_dir, true, HashMap::new()).await; + let inputs_before = provider.readable_inputs.lock().unwrap().len(); + engine + .handle_request( + region_id, + RegionRequest::BuildIndex(RegionBuildIndexRequest::default()), + ) + .await + .unwrap(); + let region = engine.get_region(region_id).unwrap(); + let files = region.all_manifest_files().await.0; + assert_eq!(files.len(), 1); + assert_eq!(files[0].file_id, before.file_id); + assert_eq!(files[0].index_version, 1); + assert!( + files[0] + .indexes + .iter() + .any(|column| column.created_indexes.contains(&IndexType::HllIndex)) + ); + assert_eq!( + &provider.readable_inputs.lock().unwrap()[inputs_before..], + &[(before.index_id(), true)] + ); + let new_path = location::index_file_path( + region.access_layer.table_dir(), + files[0].index_id(), + region.access_layer.path_type(), + ); + assert_ne!(old_path, new_path); + assert!(store.exists(&new_path).await.unwrap()); + assert_eq!(store.read(&old_path).await.unwrap().to_vec(), old_bytes); + engine.stop().await.unwrap(); +} + +#[tokio::test] +async fn test_compaction_without_provider_drops_historical_sketch_indexes() { + use crate::sst::file::{ColumnIndexMetadata, IndexType}; + + let mut env = TestEnv::new().await; + let engine = env.create_engine(MitoConfig::default()).await; + let region_id = RegionId::new(1, 1); + let request = CreateRequestBuilder::new().build_with_index(); + let schema = rows_schema(&request); + let table_dir = request.table_dir.clone(); + engine + .handle_request(region_id, RegionRequest::Create(request)) + .await + .unwrap(); + for start in [0, 2] { + put_rows( + &engine, + region_id, + Rows { + schema: schema.clone(), + rows: build_rows(start, start + 2), + }, + ) + .await; + flush_region(&engine, region_id, None).await; + } + let region = engine.get_region(region_id).unwrap(); + let mut inputs = region.all_manifest_files().await.0; + for file in &mut inputs { + file.available_indexes.push(IndexType::HllIndex); + file.indexes.push(ColumnIndexMetadata { + column_id: 0, + created_indexes: [IndexType::HllIndex].into_iter().collect(), + ..Default::default() + }); + } + engine + .edit_region( + region_id, + RegionEdit { + files_to_add: inputs, + ..Default::default() + }, + ) + .await + .unwrap(); + // Reload handles so compaction sees the persisted descriptors as well as the manifest. + reopen_region(&engine, region_id, table_dir, true, HashMap::new()).await; + let region = engine.get_region(region_id).unwrap(); + let version = region.version(); + let files: Vec<_> = version + .ssts + .levels() + .iter() + .flat_map(|level| level.files()) + .collect(); + assert_eq!(files.len(), 2); + assert!(files.iter().all(|file| { + file.meta_ref() + .available_indexes + .contains(&IndexType::HllIndex) + })); + drop(version); + let before: HashMap<_, _> = region + .all_manifest_files() + .await + .0 + .into_iter() + .map(|file| (file.file_id, file)) + .collect(); + engine + .handle_request( + region_id, + RegionRequest::Compact(RegionCompactRequest::default()), + ) + .await + .unwrap(); + let outputs = region.all_manifest_files().await.0; + assert_eq!(outputs.len(), 1); + let output = &outputs[0]; + assert!(!before.contains_key(&output.file_id)); + assert_eq!(output.num_rows, 4); + assert_eq!( + output.available_indexes.as_slice(), + &[IndexType::InvertedIndex] + ); + assert!( + output + .indexes + .iter() + .all(|column| !column.created_indexes.contains(&IndexType::HllIndex)) + ); + assert_tag_inverted_index(®ion.access_layer, output.index_id()).await; + engine.stop().await.unwrap(); +} + +#[tokio::test] +async fn test_async_flush_without_sketch_provider_builds_builtin_indexes() { + let mut env = TestEnv::new().await; + let plugins = Plugins::new(); + plugins.insert::(Arc::new(RebuildSketchProvider::default())); + let mut setup_config = async_build_mode_config(false); + setup_config.index.build_mode = IndexBuildMode::Sync; + let engine = env.create_engine_with_plugins(setup_config, plugins).await; + let region_id = RegionId::new(1, 1); + let mut request = CreateRequestBuilder::new().build_with_index(); + request.column_metadatas[0] + .column_schema + .mut_metadata() + .insert( + datatypes::schema::HLL_KEY.into(), + r#"{"precision":10}"#.into(), + ); + request.column_metadatas[0] + .column_schema + .set_skipping_options(&SkippingIndexOptions::new_unchecked( + 1, + 0.0001, + SkippingIndexType::BloomFilter, + )) + .unwrap(); + request.column_metadatas[1].column_schema = + ColumnSchema::new("field_0", ConcreteDataType::string_datatype(), true); + request.column_metadatas[1] + .column_schema + .set_fulltext_options(&FulltextOptions { + enable: true, + ..Default::default() + }) + .unwrap(); + let rows = |start, end| { + let mut rows = build_rows(start, end); + for row in &mut rows { + row.values[1] = api::v1::Value { + value_data: Some(api::v1::value::ValueData::StringValue("sample text".into())), + }; + } + rows + }; + let table_dir = request.table_dir.clone(); + let schema = rows_schema(&request); + engine + .handle_request(region_id, RegionRequest::Create(request)) + .await + .unwrap(); + put_rows( + &engine, + region_id, + Rows { + schema: schema.clone(), + rows: rows(0, 2), + }, + ) + .await; + flush_region(&engine, region_id, None).await; + let region = engine.get_region(region_id).unwrap(); + let mut historical = region.all_manifest_files().await.0.pop().unwrap(); + historical.available_indexes.push(IndexType::HllIndex); + engine + .edit_region( + region_id, + RegionEdit { + files_to_add: vec![historical.clone()], + ..Default::default() + }, + ) + .await + .unwrap(); + let historical = region.all_manifest_files().await.0.pop().unwrap(); + + // Reopen without the provider. Neither schema options nor an unrelated + // historical sketch may prevent built-in indexes on the next flushed file. + let engine = env + .reopen_engine(engine, async_build_mode_config(true)) + .await; + reopen_region(&engine, region_id, table_dir, true, HashMap::new()).await; + put_rows( + &engine, + region_id, + Rows { + schema, + rows: rows(2, 4), + }, + ) + .await; + flush_region(&engine, region_id, None).await; + let region = engine.get_region(region_id).unwrap(); + tokio::time::timeout(Duration::from_secs(10), async { + loop { + let files = region.all_manifest_files().await.0; + if let Some(file) = files.iter().find(|file| file.file_id != historical.file_id) + && [ + IndexType::InvertedIndex, + IndexType::FulltextIndex, + IndexType::BloomFilterIndex, + ] + .iter() + .all(|kind| file.available_indexes.contains(kind)) + { + assert_eq!( + files.iter().find(|file| file.file_id == historical.file_id), + Some(&historical) + ); + break; + } + tokio::time::sleep(Duration::from_millis(10)).await; + } + }) + .await + .expect("async flush did not publish built-in indexes"); + engine.stop().await.unwrap(); +} + +#[tokio::test] +async fn test_manual_rebuild_without_required_provider_preserves_sketch_metadata() { + let mut env = TestEnv::new().await; + let plugins = Plugins::new(); + plugins.insert::(Arc::new(RebuildSketchProvider { + memory_limit: Some(1024 * 1024), + ..Default::default() + })); + let mut config = async_build_mode_config(false); + config.index.build_mode = IndexBuildMode::Sync; + let engine = env + .create_engine_with_plugins(config.clone(), plugins) + .await; + let region_id = RegionId::new(1, 1); + let mut request = CreateRequestBuilder::new().build_with_index(); + request.column_metadatas[0] + .column_schema + .mut_metadata() + .insert( + datatypes::schema::HLL_KEY.into(), + r#"{"precision":10}"#.into(), + ); + let table_dir = request.table_dir.clone(); + let schema = rows_schema(&request); + engine + .handle_request(region_id, RegionRequest::Create(request)) + .await + .unwrap(); + put_and_flush(&engine, region_id, &schema, 0..2).await; + engine + .handle_request( + region_id, + RegionRequest::BuildIndex(RegionBuildIndexRequest::default()), + ) + .await + .unwrap(); + let file = engine + .get_region(region_id) + .unwrap() + .all_manifest_files() + .await + .0 + .pop() + .unwrap(); + assert!(file.available_indexes.contains(&IndexType::HllIndex)); + + let engine = env.reopen_engine(engine, config).await; + reopen_region(&engine, region_id, table_dir, true, HashMap::new()).await; + for _ in 0..2 { + let error = engine + .handle_request( + region_id, + RegionRequest::BuildIndex(RegionBuildIndexRequest::default()), + ) + .await + .unwrap_err(); + assert!(format!("{error:?}").contains("no registered handler")); + assert_eq!( + engine + .get_region(region_id) + .unwrap() + .all_manifest_files() + .await + .0, + vec![file.clone()] + ); + } + engine.stop().await.unwrap(); +} + +#[tokio::test] +async fn test_targeted_rebuild_drops_unconfigured_sketch_metadata() { + let mut env = TestEnv::new().await; + let mut config = async_build_mode_config(false); + config.index.build_mode = IndexBuildMode::Sync; + let engine = env.create_engine(config).await; + let region_id = RegionId::new(1, 1); + let request = CreateRequestBuilder::new().build_with_index(); + let schema = rows_schema(&request); + engine + .handle_request(region_id, RegionRequest::Create(request)) + .await + .unwrap(); + for start in [0, 2] { + put_rows( + &engine, + region_id, + Rows { + schema: schema.clone(), + rows: build_rows(start, start + 2), + }, + ) + .await; + flush_region(&engine, region_id, None).await; + } + let region = engine.get_region(region_id).unwrap(); + let mut files = region.all_manifest_files().await.0; + assert_eq!(files.len(), 2); + let target = files.pop().unwrap(); + let mut historical = files.pop().unwrap(); + historical.available_indexes.push(IndexType::HllIndex); + engine + .edit_region( + region_id, + RegionEdit { + files_to_add: vec![historical.clone()], + ..Default::default() + }, + ) + .await + .unwrap(); + + for file in [&target, &historical] { + let (result_tx, mut result_rx) = tokio::sync::mpsc::channel(1); + engine + .inner + .workers + .submit_to_worker( + region_id, + crate::request::WorkerRequest::Background { + region_id, + notify: crate::request::BackgroundNotify::IndexBuildRetry( + crate::request::BuildIndexRequest { + region_id, + build_type: IndexBuildType::SchemaChange, + file_metas: vec![file.clone()], + result_senders: vec![result_tx], + }, + ), + }, + ) + .await + .unwrap(); + let outcome = tokio::time::timeout(Duration::from_secs(10), result_rx.recv()) + .await + .unwrap() + .unwrap(); + outcome.unwrap(); + if file.file_id == target.file_id { + let current = region.all_manifest_files().await.0; + let unrelated = current + .iter() + .find(|file| file.file_id == historical.file_id) + .unwrap(); + assert_eq!(unrelated.available_indexes, historical.available_indexes); + assert_eq!(unrelated.index_version, historical.index_version); + } + } + let current = region.all_manifest_files().await.0; + assert!( + current + .iter() + .find(|file| file.file_id == target.file_id) + .unwrap() + .available_indexes + .contains(&IndexType::InvertedIndex) + ); + let historical_current = current + .iter() + .find(|file| file.file_id == historical.file_id) + .unwrap(); + assert_eq!( + historical_current.available_indexes.as_slice(), + &[IndexType::InvertedIndex] + ); + assert!(historical_current.index_version > historical.index_version); + engine.stop().await.unwrap(); +} + +#[tokio::test] +async fn test_manual_rebuild_plan_failure_returns_before_scheduling() { + let mut env = TestEnv::new().await; + let plugins = Plugins::new(); + let provider = Arc::new(RebuildSketchProvider { + fail_manual_plan: true, + ..Default::default() + }); + plugins.insert::(provider.clone()); + let engine = env + .create_engine_with_plugins(async_build_mode_config(false), plugins) + .await; + let region_id = RegionId::new(1, 1); + let request = CreateRequestBuilder::new().build(); + let schema = rows_schema(&request); + engine + .handle_request(region_id, RegionRequest::Create(request)) + .await + .unwrap(); + put_rows( + &engine, + region_id, + Rows { + schema, + rows: build_rows(0, 2), + }, + ) + .await; + flush_region(&engine, region_id, None).await; + let region = engine.get_region(region_id).unwrap(); + let before = region.all_manifest_files().await.0; + assert_eq!(before.len(), 1); + let error = engine + .handle_request( + region_id, + RegionRequest::BuildIndex(RegionBuildIndexRequest::default()), + ) + .await + .unwrap_err(); + assert!(format!("{error:?}").contains("injected manual plan failure")); + // Selection and task preparation would each plan again; only entry preflight ran. + assert_eq!(provider.manual_plans.load(Ordering::Relaxed), 1); + assert_eq!(provider.creates.load(Ordering::Relaxed), 0); + assert_eq!(region.all_manifest_files().await.0, before); + engine.stop().await.unwrap(); +} + +#[tokio::test] +async fn test_manual_rebuild_reports_budget_discard_of_new_plugin() { + let mut env = TestEnv::new().await; + let plugins = Plugins::new(); + let provider = Arc::new(RebuildSketchProvider { + memory_limit: Some(1), + ..Default::default() + }); + plugins.insert::(provider.clone()); + let engine = env + .create_engine_with_plugins(async_build_mode_config(false), plugins) + .await; + let region_id = RegionId::new(1, 1); + let mut request = CreateRequestBuilder::new().build(); + request.column_metadatas[0] + .column_schema + .set_inverted_index(true); + request.column_metadatas[0] + .column_schema + .mut_metadata() + .insert( + datatypes::schema::HLL_KEY.into(), + r#"{"precision":10}"#.into(), + ); + let schema = rows_schema(&request); + engine + .handle_request(region_id, RegionRequest::Create(request)) + .await + .unwrap(); + put_rows( + &engine, + region_id, + Rows { + schema, + rows: build_rows(0, 2), + }, + ) + .await; + flush_region(&engine, region_id, None).await; + let error = engine + .handle_request( + region_id, + RegionRequest::BuildIndex(RegionBuildIndexRequest::default()), + ) + .await + .unwrap_err(); + assert!( + error.to_string().contains("Index build did not complete"), + "{error:?}" + ); + assert_eq!(error.status_code(), StatusCode::IllegalState); + assert_eq!(provider.creates.load(Ordering::Relaxed), 1); + let region = engine.get_region(region_id).unwrap(); + let files = region.all_manifest_files().await.0; + assert_eq!(files.len(), 1); + assert!(!files[0].available_indexes.contains(&IndexType::HllIndex)); + assert!( + files[0] + .available_indexes + .contains(&IndexType::InvertedIndex) + ); + engine.stop().await.unwrap(); +} + +/// Tests that the worker applies an index publication of a region, and serves other regions, +/// while a graceful downgrade of that region waits for the pending checkpoint. +#[tokio::test(flavor = "multi_thread")] +async fn test_worker_serves_regions_while_downgrade_waits_for_checkpoint() { + let (blocker, mock_layer) = CheckpointTaskBlocker::block_cleanup(); + let mut env = + TestEnv::with_prefix("test_worker_serves_regions_while_downgrade_waits_for_checkpoint_") + .await + .with_mock_layer(mock_layer); + let gate = Arc::new(IndexPublicationGate::new( + IndexPublicationPhase::AfterManifestCommit, + )); + let mut config = async_build_mode_config(true); + config.num_workers = 1; + config.manifest_checkpoint_distance = 1; + let engine = env + .create_engine_with(config, None, Some(gate.clone()), None) + .await; + + let region_id = RegionId::new(1, 1); + let other_region_id = RegionId::new(2, 1); + for (id, table_dir) in [(region_id, "test"), (other_region_id, "other")] { + env.get_schema_metadata_manager() + .register_region_table_info( + id.table_id(), + "test_table", + "test_catalog", + "test_schema", + None, + env.get_kv_backend(), + ) + .await; + let request = CreateRequestBuilder::new() + .table_dir(table_dir) + .build_with_index(); + engine + .handle_request(id, RegionRequest::Create(request)) + .await + .unwrap(); + } + let column_schemas = rows_schema(&CreateRequestBuilder::new().build_with_index()); + + // The flush commit starts a checkpoint whose cleanup blocks. The index build of the flushed + // file then commits its own manifest version and stops before notifying the worker. + put_and_flush(&engine, region_id, &column_schemas, 0..20).await; + tokio::time::timeout(Duration::from_secs(10), blocker.wait_until_blocked()) + .await + .expect("checkpoint cleanup did not start"); + tokio::time::timeout(Duration::from_secs(10), gate.wait_entered(1)) + .await + .expect("index build did not commit the manifest"); + + let region = engine.get_region(region_id).unwrap(); + let wait_started = region + .manifest_ctx + .manifest_manager + .read() + .await + .checkpointer() + .pending_checkpoint_wait_started(); + // Register before starting the transition so the notification cannot be lost. + let wait_started = wait_started.notified(); + let engine_for_downgrade = engine.clone(); + let downgrade = tokio::spawn(async move { + engine_for_downgrade + .set_region_role_state_gracefully(region_id, SettableRegionRoleState::DowngradingLeader) + .await + }); + tokio::time::timeout(Duration::from_secs(5), wait_started) + .await + .expect("downgrade did not start waiting for the checkpoint"); + + // The worker handles the index publication of the downgrading region, which reads its + // manifest, and then a write to the other region. + gate.release(1); + tokio::time::timeout(Duration::from_secs(10), gate.wait_finished(1)) + .await + .expect("worker did not apply the index publication"); + tokio::time::timeout( + Duration::from_secs(5), + put_rows( + &engine, + other_region_id, + Rows { + schema: column_schemas.clone(), + rows: build_rows(0, 1), + }, + ), + ) + .await + .expect("write to another region on the same worker blocked"); + assert!( + !downgrade.is_finished(), + "downgrade returned before checkpoint cleanup finished" + ); + + blocker.release(); + let response = tokio::time::timeout(Duration::from_secs(10), downgrade) + .await + .expect("downgrade did not finish") + .unwrap() + .unwrap(); + assert!(matches!(response, SetRegionRoleStateResponse::Success(_))); +} diff --git a/src/mito2/src/engine/lease_test.rs b/src/mito2/src/engine/lease_test.rs index 5fa0a897d63..dcce6b57e1a 100644 --- a/src/mito2/src/engine/lease_test.rs +++ b/src/mito2/src/engine/lease_test.rs @@ -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, +) -> 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 { + 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( + ®ion, + &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); +} diff --git a/src/mito2/src/engine/listener.rs b/src/mito2/src/engine/listener.rs index cfbc6020a09..e34fdcd6975 100644 --- a/src/mito2/src/engine/listener.rs +++ b/src/mito2/src/engine/listener.rs @@ -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) {} diff --git a/src/mito2/src/engine/object_store_wal_recovery_test.rs b/src/mito2/src/engine/object_store_wal_recovery_test.rs index bd2cad053ee..8aaf938e296 100644 --- a/src/mito2/src/engine/object_store_wal_recovery_test.rs +++ b/src/mito2/src/engine/object_store_wal_recovery_test.rs @@ -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 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 { @@ -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::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()); diff --git a/src/mito2/src/engine/set_role_state_test.rs b/src/mito2/src/engine/set_role_state_test.rs index 0900a117a1f..2d11b867f92 100644 --- a/src/mito2/src/engine/set_role_state_test.rs +++ b/src/mito2/src/engine/set_role_state_test.rs @@ -309,6 +309,10 @@ async fn test_downgrading_waits_for_checkpoint_and_stops_new_checkpoints() { !downgrade.is_finished(), "downgrade returned before checkpoint cleanup finished" ); + assert!( + region.manifest_ctx.manifest_manager.try_read().is_ok(), + "downgrade held the manifest lock while waiting for the checkpoint" + ); blocker.release(); assert_success_response(&downgrade.await.unwrap().unwrap(), 2); @@ -441,9 +445,47 @@ async fn test_direct_follower_waits_for_pending_checkpoint() { !set_follower.is_finished(), "follower transition returned before checkpoint cleanup finished" ); + assert!( + region.manifest_ctx.manifest_manager.try_read().is_ok(), + "follower transition held the manifest lock while waiting for the checkpoint" + ); + + // Requests that observe the region as a follower wait for the same checkpoint. + let mut concurrent_requests = Vec::new(); + for state in [ + SettableRegionRoleState::Follower, + SettableRegionRoleState::DowngradingLeader, + ] { + let wait_started = region + .manifest_ctx + .manifest_manager + .read() + .await + .checkpointer() + .pending_checkpoint_wait_started(); + let wait_started = wait_started.notified(); + let cloned_engine = engine.clone(); + let request = tokio::spawn(async move { + cloned_engine + .set_region_role_state_gracefully(region_id, state) + .await + }); + tokio::time::timeout(Duration::from_secs(5), wait_started) + .await + .expect("concurrent request did not start waiting for the checkpoint"); + assert!( + !request.is_finished(), + "concurrent request returned before checkpoint cleanup finished" + ); + concurrent_requests.push(request); + } + assert_eq!(RegionRoleState::Follower, region.state()); blocker.release(); assert_success_response(&set_follower.await.unwrap().unwrap(), 1); + for request in concurrent_requests { + assert_success_response(&request.await.unwrap().unwrap(), 1); + } } #[tokio::test(flavor = "multi_thread")] @@ -514,9 +556,9 @@ async fn test_retried_downgrade_waits_after_first_request_is_cancelled() { "first downgrade did not wait for checkpoint cleanup" ); - // Cancelling the first caller must not remove the checkpoint handle from - // the manifest manager. A retried migration request observes Downgrading - // and must wait for the same checkpoint task before it can proceed. + // Cancelling the first caller does not cancel the checkpoint. A retried + // migration request observes Downgrading and waits for the same checkpoint + // task before it proceeds. first_downgrade.abort(); assert!(first_downgrade.await.unwrap_err().is_cancelled()); assert_eq!( @@ -546,6 +588,10 @@ async fn test_retried_downgrade_waits_after_first_request_is_cancelled() { !retry_downgrade.is_finished(), "retried downgrade did not wait for checkpoint cleanup" ); + assert!( + region.manifest_ctx.manifest_manager.try_read().is_ok(), + "retried downgrade held the manifest lock while waiting for the checkpoint" + ); blocker.release(); retry_downgrade.await.unwrap().unwrap(); diff --git a/src/mito2/src/engine/tail_replay_test.rs b/src/mito2/src/engine/tail_replay_test.rs index 895ad768c7f..9d2f18c3a8e 100644 --- a/src/mito2/src/engine/tail_replay_test.rs +++ b/src/mito2/src/engine/tail_replay_test.rs @@ -21,10 +21,11 @@ use std::time::{Duration, Instant}; use api::v1::{Mutation, OpType, Rows, WalEntry}; use async_trait::async_trait; use common_base::Plugins; +use common_base::readable_size::ReadableSize; use common_error::ext::ErrorExt; use common_error::status_code::StatusCode; use common_recordbatch::RecordBatches; -use common_wal::config::object_store::STANDALONE_GENERATION; +use common_wal::config::object_store::FIXED_DIRECTORY_GENERATION; use common_wal::options::WAL_OPTIONS_KEY; use datatypes::arrow::array::Array; use log_store::ObjectStoreLogStore; @@ -43,13 +44,14 @@ use store_api::region_engine::{ }; use store_api::region_request::{ PathType, RegionAlterRequest, RegionCatchupRequest, RegionCloseRequest, RegionDropRequest, - RegionRequest, RegionTruncateRequest, + RegionFlushRequest, RegionRequest, RegionTruncateRequest, }; use store_api::storage::{RegionId, ScanRequest}; use crate::config::MitoConfig; use crate::engine::MitoEngine; use crate::engine::flush_test::MockRegionHook; +use crate::engine::index_build_test::async_build_mode_config; use crate::engine::listener::EventListener; use crate::engine::object_store_wal_test::{ count_rows, count_ssts, create_leased_region_on, create_region, encode_delta, is_replaced, @@ -68,10 +70,11 @@ use crate::manifest::storage::delta_file; use crate::region::version::VersionRef; use crate::region::{MitoRegion, RegionLeaderState}; use crate::request::{BackgroundNotify, WorkerRequest}; +use crate::sst::file::RegionFileId; use crate::sst::location::region_dir_from_table_dir; use crate::test_util::{ - CreateRequestBuilder, TestEnv, build_rows, build_rows_for_key, flush_region, nop_action, - put_rows, reopen_region, rows_schema, + CreateRequestBuilder, DeltaFaults, TestEnv, build_rows, build_rows_for_key, flush_region, + nop_action, put_rows, reopen_region, rows_schema, }; use crate::time_provider::StdTimeProvider; use crate::wal::{EntryId, Wal}; @@ -90,6 +93,9 @@ struct TailReplayListener { failures: Mutex>, ended: AtomicUsize, lease_checks: AtomicUsize, + fence_begins: AtomicUsize, + /// Index builds the worker learned stopped. + index_builds_stopped: AtomicUsize, } #[async_trait] @@ -105,6 +111,10 @@ impl EventListener for TailReplayListener { self.lease_checks.fetch_add(1, Ordering::Relaxed); } + fn on_tail_fence_begin(&self, _region_id: RegionId) { + self.fence_begins.fetch_add(1, Ordering::Relaxed); + } + fn on_tail_replay_failed(&self, _region_id: RegionId, error: &Error) { let failure = (error.status_code(), format!("{error:?}")); self.failures.lock().unwrap().push(failure); @@ -113,6 +123,10 @@ impl EventListener for TailReplayListener { fn on_tail_replay_ended(&self, _region_id: RegionId) { self.ended.fetch_add(1, Ordering::Relaxed); } + + async fn on_index_build_stopped(&self, _region_file_id: RegionFileId) { + self.index_builds_stopped.fetch_add(1, Ordering::Relaxed); + } } impl TailReplayListener { @@ -146,6 +160,14 @@ impl TailReplayListener { fn lease_checks(&self) -> usize { self.lease_checks.load(Ordering::Relaxed) } + + fn index_builds_stopped(&self) -> usize { + self.index_builds_stopped.load(Ordering::Relaxed) + } + + fn fence_begins(&self) -> usize { + self.fence_begins.load(Ordering::Relaxed) + } } struct TestRegion { @@ -165,7 +187,7 @@ impl TestRegion { /// Creates a region on the object store WAL of node [NODE_ID], with leases when /// `leased`, and writes rows `[0, 3)` and `[3, 6)` in two WAL entries. async fn new(prefix: &str, leased: bool, mock_layer: Option) -> Self { - Self::with_wal_layer(prefix, leased, mock_layer, None).await + Self::build(prefix, leased, mock_layer, None, MitoConfig::default()).await } /// As [Self::new], with `wal_layer` over the WAL storage of every node. @@ -174,6 +196,21 @@ impl TestRegion { leased: bool, mock_layer: Option, wal_layer: Option, + ) -> Self { + Self::build(prefix, leased, mock_layer, wal_layer, MitoConfig::default()).await + } + + /// As [Self::new] without leases, with an engine of `config`. + async fn with_config(prefix: &str, mock_layer: Option, config: MitoConfig) -> Self { + Self::build(prefix, false, mock_layer, None, config).await + } + + async fn build( + prefix: &str, + leased: bool, + mock_layer: Option, + wal_layer: Option, + config: MitoConfig, ) -> Self { let mut env = TestEnv::with_prefix(prefix).await.with_node_id(NODE_ID); if let Some(mock_layer) = mock_layer { @@ -187,14 +224,14 @@ impl TestRegion { wal_store.clone(), &wal_config(), NODE_ID, - STANDALONE_GENERATION, + FIXED_DIRECTORY_GENERATION, ) .await .unwrap(); let listener = Arc::new(TailReplayListener::default()); let engine = env .create_engine_with_log_store_and_time( - MitoConfig::default(), + config, log_store.clone(), Arc::new(StdTimeProvider), Some(listener.clone()), @@ -261,6 +298,7 @@ impl TestRegion { RegionRole::Leader, now, now + Duration::from_secs(10), + None, ) .unwrap(); } @@ -318,7 +356,7 @@ impl TestRegion { self.wal_store.clone(), &wal_config(), REMOTE_NODE_ID, - STANDALONE_GENERATION, + FIXED_DIRECTORY_GENERATION, ) .await .unwrap(); @@ -343,6 +381,28 @@ impl TestRegion { response.last_entry_ids[®ion_id] } + /// Reopens the region with a tail in the WAL of [REMOTE_NODE_ID], deletes that WAL and + /// promotes the region, so its replay keeps failing. + async fn start_failing_remote_replay(&self) { + let last = self.write_remote_rows(self.region_id, 6, 9).await; + self.reopen_with_tails(vec![remote_tail(0, last, UptoKind::Reported)]) + .await; + self.delete_remote_objects().await; + self.catchup().await; + } + + /// Deletes every object of the WAL of [REMOTE_NODE_ID], so reading it fails. + async fn delete_remote_objects(&self) { + let objects = self + .wal_store + .list(&format!("{}/objects/", remote_prefix())) + .await + .unwrap(); + for object in objects { + self.wal_store.delete(object.path()).await.unwrap(); + } + } + /// Returns the bound a takeover would record for the WAL of [REMOTE_NODE_ID]. async fn remote_listed_bound(&self) -> EntryId { let readers = ObjectStoreWalReaders::new(self.wal_store.clone()); @@ -420,7 +480,7 @@ fn remote_tail(after: EntryId, upto: EntryId, upto_kind: UptoKind) -> PendingTai } fn remote_prefix() -> String { - wal_config().node_prefix(REMOTE_NODE_ID, STANDALONE_GENERATION) + wal_config().node_prefix(REMOTE_NODE_ID, FIXED_DIRECTORY_GENERATION) } #[tokio::test] @@ -564,7 +624,7 @@ async fn test_tail_read_stops_at_its_upto(#[case] upto_kind: UptoKind) { .reopen_with_tails(vec![own_tail(0, upto, upto_kind)]) .await; // Makes the entry after the tail unreadable. - let prefix = wal_config().node_prefix(NODE_ID, STANDALONE_GENERATION); + let prefix = wal_config().node_prefix(NODE_ID, FIXED_DIRECTORY_GENERATION); let objects = region .wal_store .list(&format!("{prefix}/objects/")) @@ -1233,11 +1293,15 @@ async fn test_late_tail_commit_notice_keeps_synced_tails() { assert!(!region.has_pending_tails()); } -/// Parks every listing of the WAL of [REMOTE_NODE_ID] once `stall` is set, and counts them. -fn stall_remote_listings(stall: Arc, stalled: Arc) -> MockLayer { +/// Parks every listing of a path `is_target` accepts once `stall` is set, and counts them. +fn stall_listings( + is_target: fn(&str) -> bool, + stall: Arc, + stalled: Arc, +) -> MockLayer { MockLayerBuilder::default() .lister_factory(Arc::new(move |path, _args, inner| { - if path.starts_with(&remote_prefix()) && stall.load(Ordering::Relaxed) { + if is_target(path) && stall.load(Ordering::Relaxed) { stalled.fetch_add(1, Ordering::Relaxed); Box::new(StalledLister) } else { @@ -1248,6 +1312,16 @@ fn stall_remote_listings(stall: Arc, stalled: Arc) -> M .unwrap() } +/// Whether `path` is in the WAL of [REMOTE_NODE_ID]. +fn is_remote_wal(path: &str) -> bool { + path.starts_with(&remote_prefix()) +} + +/// Whether `path` is in a manifest directory. +fn is_manifest(path: &str) -> bool { + path.contains("/manifest/") +} + struct StalledLister; impl List for StalledLister { @@ -1263,7 +1337,7 @@ impl List for StalledLister { async fn test_stalled_remote_read_ends_when_region_stops(#[case] stop_engine: bool) { let stall = Arc::new(AtomicBool::new(false)); let stalled = Arc::new(AtomicUsize::new(0)); - let layer = stall_remote_listings(stall.clone(), stalled.clone()); + let layer = stall_listings(is_remote_wal, stall.clone(), stalled.clone()); let region = TestRegion::with_wal_layer("tail-replay-stalled-read", false, None, Some(layer)).await; let last = region.write_remote_rows(region.region_id, 6, 9).await; @@ -1293,7 +1367,7 @@ async fn test_stalled_remote_read_ends_when_region_stops(#[case] stop_engine: bo async fn test_replacing_region_cancels_its_replay() { let stall = Arc::new(AtomicBool::new(false)); let stalled = Arc::new(AtomicUsize::new(0)); - let layer = stall_remote_listings(stall.clone(), stalled.clone()); + let layer = stall_listings(is_remote_wal, stall.clone(), stalled.clone()); let region = TestRegion::with_wal_layer("tail-replay-replaced", false, None, Some(layer)).await; let last = region.write_remote_rows(region.region_id, 6, 9).await; region @@ -1304,10 +1378,12 @@ async fn test_replacing_region_cancels_its_replay() { wait_until(|| stalled.load(Ordering::Relaxed) > 0).await; let replaying = Arc::downgrade(®ion.engine.get_region(region.region_id).unwrap()); + // Demotes without telling the worker, so only the replacement cancels the replay. region .engine - .set_region_role(region.region_id, RegionRole::Follower) - .unwrap(); + .get_region(region.region_id) + .unwrap() + .set_role(RegionRole::Follower); region.replace_follower().await; wait_until(|| replaying.strong_count() == 0).await; @@ -1459,10 +1535,14 @@ async fn test_replay_chunks_fire_sst_written_hook() { .await .with_node_id(NODE_ID); let wal_store = ObjectStore::new(Memory::default()).unwrap(); - let log_store = - ObjectStoreLogStore::try_new(wal_store, &wal_config(), NODE_ID, STANDALONE_GENERATION) - .await - .unwrap(); + let log_store = ObjectStoreLogStore::try_new( + wal_store, + &wal_config(), + NODE_ID, + FIXED_DIRECTORY_GENERATION, + ) + .await + .unwrap(); let hook = Arc::new(MockRegionHook::new()); let plugins = Plugins::new(); plugins.insert(hook.clone() as RegionHookRef); @@ -1487,3 +1567,384 @@ async fn test_replay_chunks_fire_sst_written_hook() { // Nothing else wrote an SST: the region never flushed. assert_eq!(1, hook.sst_written_count.load(Ordering::Relaxed)); } + +#[tokio::test] +async fn test_replay_writes_chunk_when_memory_budget_is_exhausted() { + // The replay budget is 8 KiB: a 256 B floor and a 4 KiB pool, which a few hundred rows + // exceed. The engine flushes at 32 KiB, above what the region itself writes. + let config = MitoConfig { + global_write_buffer_size: ReadableSize::kb(64), + ..Default::default() + }; + let region = TestRegion::with_config("tail-replay-chunk-budget", None, config).await; + let first = region.write_remote_rows(region.region_id, 6, 300).await; + let last = region.write_remote_rows(region.region_id, 300, 600).await; + assert!(first < last); + region + .reopen_with_tails(vec![remote_tail(0, last, UptoKind::Reported)]) + .await; + assert_eq!(0, region.stored_ssts().await); + + region.catchup().await; + region.wait_until_replayed().await; + + // Each entry of the tail went to its own chunk. + assert_eq!(2, region.version().ssts.levels()[0].files.len()); + assert_eq!(600, count_rows(®ion.engine, region.region_id).await); +} + +#[tokio::test] +async fn test_failed_replay_reloads_region_from_newer_manifest() { + let region = TestRegion::new("tail-replay-failed-reload", false, None).await; + region.start_failing_remote_replay().await; + wait_until(|| region.listener.failed()).await; + + // Another writer clears the tails, which nothing can replay any more. + let old = region.engine.get_region(region.region_id).unwrap(); + let action_list = + RegionMetaActionList::with_action(RegionMetaAction::Edit(pending_tails_edit(vec![]))); + publish_delta( + ®ion.env.get_object_store().unwrap(), + ®ion.region_dir(), + next_manifest_version(&old).await, + encode_delta(action_list).await, + ) + .await; + wait_until(|| is_replaced(®ion.engine, &old)).await; + + assert!(!region.has_pending_tails()); + assert_eq!(1, region.listener.ended()); + // The region's own rows survive the fence and the reload. + assert_eq!(6, count_rows(®ion.engine, region.region_id).await); +} + +#[rstest] +#[case::create_on_flush(true)] +#[case::no_create_on_flush(false)] +#[tokio::test] +async fn test_replayed_ssts_build_index_as_flushed(#[case] create_on_flush: bool) { + let region = TestRegion::with_config( + "tail-replay-index", + None, + async_build_mode_config(create_on_flush), + ) + .await; + let region_id = RegionId::new(1, 2); + let request = CreateRequestBuilder::new() + .insert_option(WAL_OPTIONS_KEY, &wal_options()[WAL_OPTIONS_KEY]) + .build_with_index(); + let table_dir = request.table_dir.clone(); + region + .engine + .handle_request(region_id, RegionRequest::Create(request)) + .await + .unwrap(); + let last = region.write_remote_rows(region_id, 0, 3).await; + let tails = vec![remote_tail(0, last, UptoKind::Reported)]; + commit_edit(®ion.engine, region_id, pending_tails_edit(tails)).await; + reopen_region(®ion.engine, region_id, table_dir, false, wal_options()).await; + + let catchup = RegionRequest::Catchup(RegionCatchupRequest { + set_writable: true, + ..Default::default() + }); + region + .engine + .handle_request(region_id, catchup) + .await + .unwrap(); + let replayed = region.engine.get_region(region_id).unwrap(); + wait_until(|| !replayed.version().has_pending_tails()).await; + + wait_until(|| region.listener.index_builds_stopped() == 1).await; + let version = replayed.version(); + let files = &version.ssts.levels()[0].files; + let has_index = files.values().any(|file| file.meta_ref().exists_index()); + assert_eq!(create_on_flush, has_index); +} + +#[tokio::test] +async fn test_stalled_manifest_check_ends_when_region_closes() { + let stall = Arc::new(AtomicBool::new(false)); + let stalled = Arc::new(AtomicUsize::new(0)); + let layer = stall_listings(is_manifest, stall.clone(), stalled.clone()); + let region = TestRegion::new("tail-replay-stalled-check", false, Some(layer)).await; + region.start_failing_remote_replay().await; + // A failed round checks the manifest for an update, which stalls. + stall.store(true, Ordering::Relaxed); + wait_until(|| stalled.load(Ordering::Relaxed) > 0).await; + let mito_region = region.engine.get_region(region.region_id).unwrap(); + // The stalled listing holds no manifest lock. + let write = tokio::time::timeout( + Duration::from_secs(5), + mito_region.manifest_ctx.manifest_manager.write(), + ) + .await + .unwrap(); + drop(write); + let replaying = Arc::downgrade(&mito_region); + drop(mito_region); + + let close = RegionRequest::Close(RegionCloseRequest::default()); + tokio::time::timeout( + Duration::from_secs(10), + region.engine.handle_request(region.region_id, close), + ) + .await + .unwrap() + .unwrap(); + + wait_until(|| replaying.strong_count() == 0).await; +} + +/// Parks the first SST write once `stall` is set, and counts the parked writes. +fn stall_first_sst_write(stall: Arc, stalled: Arc) -> MockLayer { + MockLayerBuilder::default() + .writer_factory(Arc::new(move |path, _args, inner| { + if path.ends_with(".parquet") && stall.swap(false, Ordering::Relaxed) { + stalled.fetch_add(1, Ordering::Relaxed); + Box::new(StalledWriter) + } else { + inner + } + })) + .build() + .unwrap() +} + +struct StalledWriter; + +impl Write for StalledWriter { + async fn write(&mut self, _bs: Buffer) -> MockResult<()> { + std::future::pending().await + } + + async fn close(&mut self) -> MockResult { + std::future::pending().await + } + + async fn abort(&mut self) -> MockResult<()> { + Ok(()) + } +} + +#[tokio::test] +async fn test_flush_runs_while_replay_writes_are_saturated() { + let stall = Arc::new(AtomicBool::new(false)); + let stalled = Arc::new(AtomicUsize::new(0)); + let layer = stall_first_sst_write(stall.clone(), stalled.clone()); + // One replay SST write takes every replay write permit. + let config = MitoConfig { + max_background_flushes: 1, + ..Default::default() + }; + let region = TestRegion::with_config("tail-replay-saturated", Some(layer), config).await; + let last = region.write_remote_rows(region.region_id, 6, 9).await; + region + .reopen_with_tails(vec![remote_tail(0, last, UptoKind::Reported)]) + .await; + stall.store(true, Ordering::Relaxed); + region.catchup().await; + wait_until(|| stalled.load(Ordering::Relaxed) == 1).await; + + // The memtable holds rows `[0, 6)`, which the reopen replayed from this node's WAL. + tokio::time::timeout( + Duration::from_secs(10), + flush_region(®ion.engine, region.region_id, None), + ) + .await + .unwrap(); + + assert_eq!(1, region.stored_ssts().await); + assert!(region.has_pending_tails()); +} + +#[tokio::test] +async fn test_replay_waiting_to_fence_ends_when_demoted() { + let region = TestRegion::new("tail-replay-fence-wait", false, None).await; + region.start_failing_remote_replay().await; + wait_until(|| region.listener.failed()).await; + + // The next failed round finds the newer manifest and waits for the write lock behind + // this read guard, unless the replay is cancelled. + let mito_region = region.engine.get_region(region.region_id).unwrap(); + let version = next_manifest_version(&mito_region).await; + let guard = mito_region.manifest_ctx.manifest_manager.read().await; + publish_delta( + ®ion.env.get_object_store().unwrap(), + ®ion.region_dir(), + version, + encode_delta(nop_action()).await, + ) + .await; + wait_until(|| region.listener.fence_begins() == 1).await; + // The worker cancels the replay before the downgrade waits for the manifest lock. + let engine = region.engine.clone(); + let region_id = region.region_id; + let downgrade = tokio::spawn(async move { + engine + .set_region_role_state_gracefully(region_id, SettableRegionRoleState::Follower) + .await + }); + + wait_until(|| region.listener.ended() == 1).await; + drop(guard); + downgrade.await.unwrap().unwrap(); + + assert!(mito_region.is_follower()); +} + +#[rstest] +#[case::fences(false, false)] +#[case::version_changed(true, false)] +#[case::not_writable(false, true)] +#[tokio::test] +async fn test_fence_for_reload_rechecks_version_and_role( + #[case] version_changed: bool, + #[case] demoted: bool, +) { + let region = TestRegion::new("tail-replay-fence-recheck", false, None).await; + if demoted { + region + .engine + .set_region_role(region.region_id, RegionRole::Follower) + .unwrap(); + } + let mito_region = region.engine.get_region(region.region_id).unwrap(); + let manifest_ctx = &mito_region.manifest_ctx; + let mut manager = manifest_ctx.manifest_manager.write().await; + let installed = manager.manifest().manifest_version + u64::from(version_changed); + + let fenced = manifest_ctx + .fence_for_reload_if_unchanged(&mut manager, region.region_id, installed) + .await; + + let expected = !version_changed && !demoted; + assert_eq!(expected, fenced); + assert_eq!(expected, manifest_ctx.is_reload_pending()); +} + +#[rstest] +#[case::set_role(false)] +#[case::set_role_with_lease(true)] +#[tokio::test] +async fn test_direct_demotion_ends_stalled_replay(#[case] with_lease: bool) { + let stall = Arc::new(AtomicBool::new(false)); + let stalled = Arc::new(AtomicUsize::new(0)); + let layer = stall_listings(is_remote_wal, stall.clone(), stalled.clone()); + let region = + TestRegion::with_wal_layer("tail-replay-direct-demotion", false, None, Some(layer)).await; + let last = region.write_remote_rows(region.region_id, 6, 9).await; + region + .reopen_with_tails(vec![remote_tail(0, last, UptoKind::Reported)]) + .await; + stall.store(true, Ordering::Relaxed); + region.catchup().await; + wait_until(|| stalled.load(Ordering::Relaxed) > 0).await; + + if with_lease { + let now = Instant::now(); + region + .engine + .set_region_role_with_lease( + region.region_id, + RegionRole::Follower, + now, + now + Duration::from_secs(10), + None, + ) + .unwrap(); + } else { + region + .engine + .set_region_role(region.region_id, RegionRole::Follower) + .unwrap(); + } + wait_until(|| region.listener.ended() == 1).await; + + // A later promotion replays the tails again. + stall.store(false, Ordering::Relaxed); + region.promote(); + region.wait_until_replayed().await; + assert_eq!(9, count_rows(®ion.engine, region.region_id).await); +} + +#[tokio::test] +async fn test_late_demotion_notice_of_replaced_instance_keeps_replay() { + let region = TestRegion::new("tail-replay-stale-notice", false, None).await; + region + .reopen_with_tails(vec![own_tail(0, region.entries[1], UptoKind::Reported)]) + .await; + let old = region.engine.get_region(region.region_id).unwrap(); + region.replace_follower().await; + region.listener.hold_from(1); + region.promote(); + wait_until(|| region.listener.commits() == 1).await; + + // A demotion notice of the replaced instance arrives late. + let request = WorkerRequest::Background { + region_id: region.region_id, + notify: BackgroundNotify::RegionCannotReplay { region: old }, + }; + region + .engine + .inner + .workers + .submit_to_worker(region.region_id, request) + .await + .unwrap(); + // The worker handles the notice before this write. + region.overwrite_remote_row().await; + region.listener.hold_from(0); + region.wait_until_replayed().await; + + assert_eq!(1, region.listener.commits()); +} + +#[tokio::test] +async fn test_failed_replay_reloads_region_after_failed_commit() { + let faults = DeltaFaults::default(); + let region = TestRegion::new( + "tail-replay-failed-commit-reload", + false, + Some(faults.layer()), + ) + .await; + region.start_failing_remote_replay().await; + wait_until(|| region.listener.failed()).await; + + // A failed flush commit takes the next version number without installing it. + let old = region.engine.get_region(region.region_id).unwrap(); + let next = next_manifest_version(&old).await; + faults.fail_next_write(); + let flush = RegionRequest::Flush(RegionFlushRequest::default()); + assert!( + region + .engine + .handle_request(region.region_id, flush) + .await + .is_err() + ); + assert_eq!( + next, + old.manifest_ctx + .manifest_manager + .read() + .await + .last_version() + ); + + // Another writer then publishes that version, clearing the tails. + let action_list = + RegionMetaActionList::with_action(RegionMetaAction::Edit(pending_tails_edit(vec![]))); + publish_delta( + ®ion.env.get_object_store().unwrap(), + ®ion.region_dir(), + next, + encode_delta(action_list).await, + ) + .await; + wait_until(|| is_replaced(®ion.engine, &old)).await; + + assert!(!region.has_pending_tails()); +} diff --git a/src/mito2/src/error.rs b/src/mito2/src/error.rs index 7066bca0412..27f3282ecc5 100644 --- a/src/mito2/src/error.rs +++ b/src/mito2/src/error.rs @@ -1398,6 +1398,9 @@ pub enum Error { #[snafu(display("Compaction is cancelled."))] CompactionCancelled {}, + #[snafu(display("SST write is cancelled."))] + SstWriteCancelled {}, + #[snafu(display("Flush is cancelled."))] FlushCancelled {}, @@ -1818,9 +1821,10 @@ impl ErrorExt for Error { source.status_code() } - ManualCompactionOverride {} | CompactionCancelled {} | FlushCancelled {} => { - StatusCode::Cancelled - } + ManualCompactionOverride {} + | CompactionCancelled {} + | FlushCancelled {} + | SstWriteCancelled {} => StatusCode::Cancelled, // A concurrent manual compaction fails fast instead of being queued; // the conflict is reported to the caller, which decides whether to diff --git a/src/mito2/src/flush.rs b/src/mito2/src/flush.rs index 0874e8e4433..1a2dd13ad4f 100644 --- a/src/mito2/src/flush.rs +++ b/src/mito2/src/flush.rs @@ -21,10 +21,10 @@ use std::sync::{Arc, Mutex}; use std::time::Instant; use bytes::Bytes; -use common_base::cancellation::CancellableFuture; use common_telemetry::{debug, error, info}; use datatypes::arrow::datatypes::SchemaRef; use partition::expr::PartitionExpr; +use prometheus::{Histogram, IntCounter}; use smallvec::{SmallVec, smallvec}; use snafu::{ResultExt, ensure}; use store_api::metadata::RegionMetadataRef; @@ -40,7 +40,7 @@ use crate::access_layer::{ use crate::cache::CacheManagerRef; use crate::compaction::{collect_json2_rewrite_plans, rewrite_json2_batch, rewrite_json2_schema}; use crate::config::{IndexBuildMode, MitoConfig}; -use crate::engine::region_hook::SstFileInfo; +use crate::engine::region_hook::{RegionHookRef, SstFileInfo}; use crate::error::{ Error, FlushCancelledSnafu, FlushRegionSnafu, JoinSnafu, RegionBusySnafu, RegionClosedSnafu, RegionDroppedSnafu, RegionTruncatedSnafu, Result, UnexpectedSnafu, @@ -53,14 +53,14 @@ use crate::memtable::{ }; use crate::metrics::{ FLUSH_BYTES_TOTAL, FLUSH_ELAPSED, FLUSH_FAILURE_TOTAL, FLUSH_FILE_TOTAL, FLUSH_REQUESTS_TOTAL, - INFLIGHT_FLUSH_COUNT, + INFLIGHT_FLUSH_COUNT, TAIL_REPLAY_BYTES_TOTAL, TAIL_REPLAY_ELAPSED, TAIL_REPLAY_FILE_TOTAL, }; use crate::read::FlatSource; use crate::read::flat_dedup::{FlatDedupIterator, FlatLastNonNull, FlatLastRow}; use crate::read::flat_merge::FlatMergeIterator; use crate::region::options::{IndexOptions, MergeMode, RegionOptions}; use crate::region::version::{VersionControlData, VersionControlRef, VersionRef}; -use crate::region::{ManifestContextRef, RegionLeaderState, parse_partition_expr}; +use crate::region::{ManifestContextRef, MitoRegion, RegionLeaderState, parse_partition_expr}; use crate::request::{ BackgroundNotify, DdlRequest, FlushFailed, FlushFinished, OnFailure, OptionOutputTx, OutputTx, SenderBulkRequest, SenderDdlRequest, SenderWriteRequest, WorkerRequest, WorkerRequestWithTime, @@ -240,8 +240,6 @@ pub enum FlushReason { RemoteWalPrune, /// Flush before closing a region. Closing, - /// Writes a chunk of pending WAL tails replayed in the background. - TailReplay, } impl FlushReason { @@ -273,24 +271,53 @@ pub(crate) struct RegionFlushTask { pub(crate) senders: Vec, /// Request sender to notify the worker. pub(crate) request_sender: mpsc::Sender, - - pub(crate) access_layer: AccessLayerRef, pub(crate) listener: WorkerListener, - pub(crate) engine_config: Arc, - pub(crate) row_group_size: Option, - pub(crate) cache_manager: CacheManagerRef, pub(crate) manifest_ctx: ManifestContextRef, + /// Writes the immutable memtables to SSTs. + pub(crate) sst_writer: MemtableSstWriter, + /// Waits until the WAL is durable through the entry id the flush records. + pub(crate) durability_barrier: DurabilityBarrier, +} + +/// Writes the immutable memtables of a version to level 0 SSTs, for a flush or a tail replay. +pub(crate) struct MemtableSstWriter { + region_id: RegionId, + /// Kind of the writes, which selects their metrics. + kind: MemtableWriteKind, + access_layer: AccessLayerRef, + engine_config: Arc, + row_group_size: Option, + cache_manager: CacheManagerRef, + /// Hook told of the written SSTs. + hook: Option, /// Index options for the region. - pub(crate) index_options: IndexOptions, - /// Semaphore to control flush concurrency. - pub(crate) flush_semaphore: Arc, + index_options: IndexOptions, + /// Semaphore to control concurrent SST writes. + write_semaphore: Arc, /// Partition expression of the region. /// /// This is used to generate the file meta. - pub(crate) partition_expr: Option, - /// Waits until the WAL is durable through the entry id the flush records. - pub(crate) durability_barrier: DurabilityBarrier, + partition_expr: Option, +} + +/// Kind of the writes of a [MemtableSstWriter]. +#[derive(Clone, Copy)] +enum MemtableWriteKind { + /// Writes of a flush, for the reason its log names. + Flush(FlushReason), + /// Writes of the replay of pending WAL tails. + TailReplay, +} + +impl MemtableWriteKind { + /// Returns the [WriteType] of the writes' metrics. + fn write_type(self) -> WriteType { + match self { + MemtableWriteKind::Flush(_) => WriteType::Flush, + MemtableWriteKind::TailReplay => WriteType::TailReplay, + } + } } struct FlushTaskWaiters { @@ -385,8 +412,8 @@ impl RegionFlushTask { let timer = FLUSH_ELAPSED.with_label_values(&["total"]).start_timer(); let uncommitted = UncommittedSsts::new( self.region_id, - self.access_layer.clone(), - Some(self.cache_manager.clone()), + self.sst_writer.access_layer.clone(), + Some(self.sst_writer.cache_manager.clone()), ); self.listener.on_flush_begin(self.region_id).await; let flush_result = if state.is_cancelled() { @@ -444,81 +471,6 @@ impl RegionFlushTask { self.send_worker_request(worker_request).await; } - /// Writes the immutable memtables of `version` to level 0 SSTs, which `uncommitted` - /// tracks until a manifest edit references them, and returns their file metas. - pub(crate) async fn write_ssts( - &self, - version: &VersionRef, - state: &CancellableTaskState, - uncommitted: &UncommittedSsts, - ) -> Result> { - let timer = FLUSH_ELAPSED - .with_label_values(&["flush_memtables"]) - .start_timer(); - - let mut write_opts = WriteOptions { - write_buffer_size: self.engine_config.sst_write_buffer_size, - float_field_encoding: version.options.float_field_encoding, - ..Default::default() - }; - if let Some(row_group_size) = self.row_group_size { - write_opts.row_group_size = row_group_size; - } - - let DoFlushMemtablesResult { - file_metas, - flushed_bytes, - series_count, - encoded_part_count, - flush_metrics, - sst_infos, - } = self - .do_flush_memtables(version, write_opts, state, uncommitted) - .await?; - - if !file_metas.is_empty() { - FLUSH_BYTES_TOTAL.inc_by(flushed_bytes); - } - - let mut file_ids = Vec::with_capacity(file_metas.len()); - let mut total_rows = 0; - let mut total_bytes = 0; - for meta in &file_metas { - file_ids.push(meta.file_id); - total_rows += meta.num_rows; - total_bytes += meta.file_size; - } - info!( - "Successfully flush memtables, region: {}, reason: {}, files: {:?}, series count: {}, total_rows: {}, total_bytes: {}, cost: {:?}, encoded_part_count: {}, metrics: {:?}", - self.region_id, - self.reason.as_str(), - file_ids, - series_count, - total_rows, - total_bytes, - timer.stop_and_record(), - encoded_part_count, - flush_metrics, - ); - flush_metrics.observe(); - - let hook = self.manifest_ctx.hook(); - if let Some(hook) = &hook { - let files: Vec> = sst_infos - .iter() - .zip(file_metas.iter()) - .map(|(sst_info, file_meta)| SstFileInfo { - sst_info_ref: sst_info, - file_meta, - }) - .collect(); - hook.on_sst_files_written(self.region_id, &version.metadata, &files) - .await; - } - - Ok(file_metas) - } - /// Flushes memtables to level 0 SSTs and updates the manifest. /// Returns the [RegionEdit] to apply. async fn flush_memtables( @@ -530,6 +482,7 @@ impl RegionFlushTask { // We must use the immutable memtables list and entry ids from the `version_data` // for consistency as others might already modify the version in the `version_control`. let file_metas = self + .sst_writer .write_ssts(&version_data.version, state, uncommitted) .await?; @@ -537,11 +490,11 @@ impl RegionFlushTask { // that acknowledges appends before their entries are durable can have // handed out `last_entry_id` for an entry that is still in its backlog. // A DDL that cancels the flush must not wait behind that upload. - let durable = self.durability_barrier.wait(version_data.last_entry_id); - tokio::pin!(durable); - match CancellableFuture::new(durable.as_mut(), state.cancel_handle()).await { - Ok(result) => result?, - Err(_) => return FlushCancelledSnafu.fail(), + let cancellation = state.cancel_token(); + tokio::select! { + biased; + _ = cancellation.cancelled() => return FlushCancelledSnafu.fail(), + result = self.durability_barrier.wait(version_data.last_entry_id) => result?, } let edit = RegionEdit { @@ -601,6 +554,193 @@ impl RegionFlushTask { Ok(edit) } + /// Notify flush job status. + pub(crate) async fn send_worker_request(&self, request: WorkerRequest) { + if let Err(e) = self + .request_sender + .send(WorkerRequestWithTime::new(request)) + .await + { + let request = e.0.request; + error!( + "Failed to notify flush job status for region {}, request: {:?}", + self.region_id, request + ); + if let WorkerRequest::Background { notify, .. } = request { + let err = RegionClosedSnafu { + region_id: self.region_id, + } + .build(); + match notify { + BackgroundNotify::FlushFinished(mut finished) => { + finished.on_failure(err); + } + BackgroundNotify::FlushFailed(failed) => { + let err = Arc::new(err); + for sender in failed.senders { + sender.send(Err(err.clone()).context(FlushRegionSnafu { + region_id: self.region_id, + })); + } + } + _ => {} + } + } + } + } + + /// Merge two flush tasks. + fn merge(&mut self, mut other: RegionFlushTask) { + assert_eq!(self.region_id, other.region_id); + // Now we only merge senders. They share the same flush reason. + self.senders.append(&mut other.senders); + } +} + +impl MemtableSstWriter { + /// Creates a writer of the `region`'s immutable memtables for a flush with `reason`. + pub(crate) fn new_flush( + region: &MitoRegion, + reason: FlushReason, + row_group_size: Option, + engine_config: Arc, + cache_manager: CacheManagerRef, + write_semaphore: Arc, + ) -> Self { + Self::new( + MemtableWriteKind::Flush(reason), + region, + row_group_size, + engine_config, + cache_manager, + write_semaphore, + ) + } + + /// Creates a writer of the `region`'s immutable memtables for a tail replay. Only + /// [TailReplayLimits::new_sst_writer](crate::tail_replay::TailReplayLimits::new_sst_writer) + /// calls it, with the replays' write semaphore. + pub(crate) fn new_tail_replay( + region: &MitoRegion, + engine_config: Arc, + cache_manager: CacheManagerRef, + write_semaphore: Arc, + ) -> Self { + Self::new( + MemtableWriteKind::TailReplay, + region, + None, + engine_config, + cache_manager, + write_semaphore, + ) + } + + fn new( + kind: MemtableWriteKind, + region: &MitoRegion, + row_group_size: Option, + engine_config: Arc, + cache_manager: CacheManagerRef, + write_semaphore: Arc, + ) -> Self { + Self { + region_id: region.region_id, + kind, + access_layer: region.access_layer.clone(), + engine_config, + // The request-provided size (e.g. manual flush) takes precedence over the + // region option. + row_group_size: row_group_size.or(region.version().options.max_row_group_row_count), + cache_manager, + hook: region.manifest_ctx.hook(), + index_options: region.version().options.index_options.clone(), + write_semaphore, + partition_expr: region.metadata().partition_expr.clone(), + } + } + + /// Returns the cache manager the written SSTs go through. + pub(crate) fn cache_manager(&self) -> &CacheManagerRef { + &self.cache_manager + } + + /// Writes the immutable memtables of `version` to level 0 SSTs, which `uncommitted` + /// tracks until a manifest edit references them, and returns their file metas. Its log + /// names the flush reason, or the write type when the write is not a flush. + pub(crate) async fn write_ssts( + &self, + version: &VersionRef, + state: &CancellableTaskState, + uncommitted: &UncommittedSsts, + ) -> Result> { + let timer = self.write_elapsed().start_timer(); + + let mut write_opts = WriteOptions { + write_buffer_size: self.engine_config.sst_write_buffer_size, + float_field_encoding: version.options.float_field_encoding, + ..Default::default() + }; + if let Some(row_group_size) = self.row_group_size { + write_opts.row_group_size = row_group_size; + } + + let DoFlushMemtablesResult { + file_metas, + flushed_bytes, + series_count, + encoded_part_count, + flush_metrics, + sst_infos, + } = self + .do_flush_memtables(version, write_opts, state, uncommitted) + .await?; + + if !file_metas.is_empty() { + self.bytes_total().inc_by(flushed_bytes); + } + + let mut file_ids = Vec::with_capacity(file_metas.len()); + let mut total_rows = 0; + let mut total_bytes = 0; + for meta in &file_metas { + file_ids.push(meta.file_id); + total_rows += meta.num_rows; + total_bytes += meta.file_size; + } + info!( + "Successfully flush memtables, region: {}, reason: {}, files: {:?}, series count: {}, total_rows: {}, total_bytes: {}, cost: {:?}, encoded_part_count: {}, metrics: {:?}", + self.region_id, + match self.kind { + MemtableWriteKind::Flush(reason) => reason.as_str(), + MemtableWriteKind::TailReplay => WriteType::TailReplay.into(), + }, + file_ids, + series_count, + total_rows, + total_bytes, + timer.stop_and_record(), + encoded_part_count, + flush_metrics, + ); + flush_metrics.observe(); + + if let Some(hook) = &self.hook { + let files: Vec> = sst_infos + .iter() + .zip(file_metas.iter()) + .map(|(sst_info, file_meta)| SstFileInfo { + sst_info_ref: sst_info, + file_meta, + }) + .collect(); + hook.on_sst_files_written(self.region_id, &version.metadata, &files) + .await; + } + + Ok(file_metas) + } + async fn do_flush_memtables( &self, version: &VersionRef, @@ -613,9 +753,8 @@ impl RegionFlushTask { let mut flushed_bytes = 0; let mut series_count = 0; let mut encoded_part_count = 0; - let mut flush_metrics = Metrics::new(WriteType::Flush); + let mut flush_metrics = Metrics::new(self.kind.write_type()); let partition_expr = parse_partition_expr(self.partition_expr.as_deref())?; - let hook = self.manifest_ctx.hook(); let mut all_sst_infos = Vec::new(); for mem in memtables { if mem.is_empty() { @@ -691,7 +830,7 @@ impl RegionFlushTask { version.options.preserve_row_sequence, )?); } - if hook.is_some() { + if self.hook.is_some() { all_sst_infos.extend(ssts_written); } } @@ -740,22 +879,24 @@ impl RegionFlushTask { &version.options, field_column_start, )?; + let file_total = self.file_total(); let mut tasks = Vec::with_capacity(flat_sources.encoded.len() + flat_sources.sources.len()); let num_encoded = flat_sources.encoded.len(); for (source, max_sequence) in flat_sources.sources { let write_request = self.new_write_request(version, max_sequence, source); let access_layer = self.access_layer.clone(); let write_opts = write_opts.clone(); - let semaphore = self.flush_semaphore.clone(); + let semaphore = self.write_semaphore.clone(); let uncommitted = uncommitted.clone(); + let write_type = self.kind.write_type(); let task = common_runtime::spawn_global(async move { let _permit = semaphore.acquire().await.unwrap(); - let mut metrics = Metrics::new(WriteType::Flush); + let mut metrics = Metrics::new(write_type); let ssts = access_layer .write_sst(write_request, &write_opts, &mut metrics) .await?; uncommitted.track(&ssts); - FLUSH_FILE_TOTAL.inc_by(ssts.len() as u64); + file_total.inc_by(ssts.len() as u64); Ok((max_sequence, ssts, metrics)) }); tasks.push(task); @@ -764,10 +905,11 @@ impl RegionFlushTask { for (mut encoded, max_sequence) in flat_sources.encoded { let access_layer = self.access_layer.clone(); let cache_manager = self.cache_manager.clone(); - let region_id = version.metadata.region_id; + let region_id = self.region_id; let write_buffer_size = write_opts.write_buffer_size; - let semaphore = self.flush_semaphore.clone(); + let semaphore = self.write_semaphore.clone(); let uncommitted = uncommitted.clone(); + let write_type = self.kind.write_type(); let index_build_params = build_index.then(|| EncodedSstIndexBuildParams { metadata: version.metadata.clone(), index_options: self.index_options.clone(), @@ -780,7 +922,8 @@ impl RegionFlushTask { uncommitted.track_before_upload(encoded.sst_info.file_id, index_build_params.is_some()); let task = common_runtime::spawn_global(async move { let _permit = semaphore.acquire().await.unwrap(); - let metrics = access_layer + let mut metrics = Metrics::new(write_type); + access_layer .put_sst( &encoded.data, region_id, @@ -788,10 +931,11 @@ impl RegionFlushTask { &cache_manager, write_buffer_size, index_build_params, + &mut metrics, ) .await?; uncommitted.track(std::slice::from_ref(&encoded.sst_info)); - FLUSH_FILE_TOTAL.inc(); + file_total.inc(); Ok((max_sequence, smallvec![encoded.sst_info], metrics)) }); tasks.push(task); @@ -803,12 +947,17 @@ impl RegionFlushTask { .collect::>(); let join_all = futures::future::join_all(tasks); tokio::pin!(join_all); - let results = match CancellableFuture::new(join_all.as_mut(), state.cancel_handle()).await { - Ok(results) => results + let cancellation = state.cancel_token(); + let results = match tokio::select! { + biased; + _ = cancellation.cancelled() => None, + results = join_all.as_mut() => Some(results), + } { + Some(results) => results .into_iter() .map(|result| result.context(JoinSnafu)) .collect::>>()?, - Err(_) => { + None => { for handle in abort_handles { handle.abort(); } @@ -894,46 +1043,30 @@ impl RegionFlushTask { } } - /// Notify flush job status. - pub(crate) async fn send_worker_request(&self, request: WorkerRequest) { - if let Err(e) = self - .request_sender - .send(WorkerRequestWithTime::new(request)) - .await - { - let request = e.0.request; - error!( - "Failed to notify flush job status for region {}, request: {:?}", - self.region_id, request - ); - if let WorkerRequest::Background { notify, .. } = request { - let err = RegionClosedSnafu { - region_id: self.region_id, - } - .build(); - match notify { - BackgroundNotify::FlushFinished(mut finished) => { - finished.on_failure(err); - } - BackgroundNotify::FlushFailed(failed) => { - let err = Arc::new(err); - for sender in failed.senders { - sender.send(Err(err.clone()).context(FlushRegionSnafu { - region_id: self.region_id, - })); - } - } - _ => {} - } + /// Returns the histogram that times [Self::write_ssts] for this writer's kind. + fn write_elapsed(&self) -> Histogram { + match self.kind { + MemtableWriteKind::TailReplay => { + TAIL_REPLAY_ELAPSED.with_label_values(&["write_chunk"]) } + MemtableWriteKind::Flush(_) => FLUSH_ELAPSED.with_label_values(&["flush_memtables"]), } } - /// Merge two flush tasks. - fn merge(&mut self, mut other: RegionFlushTask) { - assert_eq!(self.region_id, other.region_id); - // Now we only merge senders. They share the same flush reason. - self.senders.append(&mut other.senders); + /// Returns the counter of SST bytes this writer writes. + fn bytes_total(&self) -> &'static IntCounter { + match self.kind { + MemtableWriteKind::TailReplay => &TAIL_REPLAY_BYTES_TOTAL, + MemtableWriteKind::Flush(_) => &FLUSH_BYTES_TOTAL, + } + } + + /// Returns the counter of SST files this writer writes. + fn file_total(&self) -> &'static IntCounter { + match self.kind { + MemtableWriteKind::TailReplay => &TAIL_REPLAY_FILE_TOTAL, + MemtableWriteKind::Flush(_) => &FLUSH_FILE_TOTAL, + } } } @@ -1729,15 +1862,20 @@ mod tests { reason, senders: Vec::new(), request_sender, - access_layer: env.access_layer.clone(), listener: WorkerListener::default(), - engine_config: Arc::new(MitoConfig::default()), - row_group_size: None, - cache_manager: Arc::new(CacheManager::default()), manifest_ctx, - index_options: IndexOptions::default(), - flush_semaphore: Arc::new(Semaphore::new(2)), - partition_expr: None, + sst_writer: MemtableSstWriter { + region_id, + kind: MemtableWriteKind::Flush(reason), + access_layer: env.access_layer.clone(), + engine_config: Arc::new(MitoConfig::default()), + row_group_size: None, + cache_manager: Arc::new(CacheManager::default()), + hook: None, + index_options: IndexOptions::default(), + write_semaphore: Arc::new(Semaphore::new(2)), + partition_expr: None, + }, durability_barrier: DurabilityBarrier::noop(), } } @@ -1872,24 +2010,16 @@ mod tests { let version_control = Arc::new(builder.build()); let (output_tx, output_rx) = oneshot::channel(); - let mut task = RegionFlushTask { - region_id: builder.region_id(), - reason: FlushReason::Manual, - senders: Vec::new(), - request_sender: tx, - access_layer: env.access_layer.clone(), - listener: WorkerListener::default(), - engine_config: Arc::new(MitoConfig::default()), - row_group_size: None, - cache_manager: Arc::new(CacheManager::default()), - manifest_ctx: env - .mock_manifest_context(version_control.current().version.metadata.clone()) - .await, - index_options: IndexOptions::default(), - flush_semaphore: Arc::new(Semaphore::new(2)), - partition_expr: None, - durability_barrier: DurabilityBarrier::noop(), - }; + let manifest_ctx = env + .mock_manifest_context(version_control.current().version.metadata.clone()) + .await; + let mut task = new_test_flush_task( + &env, + builder.region_id(), + FlushReason::Manual, + tx, + manifest_ctx, + ); task.push_sender(OptionOutputTx::from(output_tx)); scheduler .schedule_flush(builder.region_id(), &version_control, task) @@ -2251,21 +2381,14 @@ mod tests { .await; // Creates 3 tasks. let mut tasks: Vec<_> = (0..3) - .map(|_| RegionFlushTask { - region_id: builder.region_id(), - reason: FlushReason::Manual, - senders: Vec::new(), - request_sender: tx.clone(), - access_layer: env.access_layer.clone(), - listener: WorkerListener::default(), - engine_config: Arc::new(MitoConfig::default()), - row_group_size: None, - cache_manager: Arc::new(CacheManager::default()), - manifest_ctx: manifest_ctx.clone(), - index_options: IndexOptions::default(), - flush_semaphore: Arc::new(Semaphore::new(2)), - partition_expr: None, - durability_barrier: DurabilityBarrier::noop(), + .map(|_| { + new_test_flush_task( + &env, + builder.region_id(), + FlushReason::Manual, + tx.clone(), + manifest_ctx.clone(), + ) }) .collect(); // Schedule first task. @@ -2558,21 +2681,14 @@ mod tests { .await; // Creates 2 tasks. let mut tasks: Vec<_> = (0..2) - .map(|_| RegionFlushTask { - region_id: builder.region_id(), - reason: FlushReason::Manual, - senders: Vec::new(), - request_sender: tx.clone(), - access_layer: env.access_layer.clone(), - listener: WorkerListener::default(), - engine_config: Arc::new(MitoConfig::default()), - row_group_size: None, - cache_manager: Arc::new(CacheManager::default()), - manifest_ctx: manifest_ctx.clone(), - index_options: IndexOptions::default(), - flush_semaphore: Arc::new(Semaphore::new(2)), - partition_expr: None, - durability_barrier: DurabilityBarrier::noop(), + .map(|_| { + new_test_flush_task( + &env, + builder.region_id(), + FlushReason::Manual, + tx.clone(), + manifest_ctx.clone(), + ) }) .collect(); // Schedule first task. diff --git a/src/mito2/src/lease.rs b/src/mito2/src/lease.rs index a501ba4b61a..b6b7caaada9 100644 --- a/src/mito2/src/lease.rs +++ b/src/mito2/src/lease.rs @@ -12,10 +12,14 @@ // See the License for the specific language governing permissions and // limitations under the License. -use std::sync::LazyLock; +use std::collections::HashMap; use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::sync::{LazyLock, Mutex}; use std::time::Instant; +use store_api::logstore::ObjectStoreWalIoPermit; +use store_api::storage::RegionId; + /// The instant lease deadlines count from, so that a deadline fits in an [AtomicU64]. static LEASE_EPOCH: LazyLock = LazyLock::new(Instant::now); @@ -89,3 +93,102 @@ impl NodeLease { .fetch_max(self.deadline.get(), Ordering::Relaxed); } } + +/// A region lease the metasrv granted for a heartbeat sent at `sent_at`. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) struct GrantedLease { + pub(crate) candidate_lease_id: Option, + /// When the heartbeat request for which this lease was granted was sent. + pub(crate) sent_at: Instant, +} + +/// The lease of the latest heartbeat each region received, whether or not the region applied it. +/// It is kept apart from the region instance, so a reopen during catchup keeps it. +#[derive(Debug, Default)] +pub(crate) struct GrantedLeases(Mutex>); + +impl GrantedLeases { + /// Records the lease if `region_is_open` holds. The check runs under the same lock as + /// [Self::remove], which a worker calls after it removes the region, so a lease recorded + /// concurrently with the removal does not outlive it. + pub(crate) fn record( + &self, + region_id: RegionId, + sent_at: Instant, + candidate_lease_id: Option, + region_is_open: impl FnOnce() -> bool, + ) { + let lease = GrantedLease { + candidate_lease_id, + sent_at, + }; + let mut leases = self.0.lock().unwrap(); + if !region_is_open() { + return; + } + leases + .entry(region_id) + .and_modify(|latest| { + if sent_at > latest.sent_at { + *latest = lease; + } + }) + .or_insert(lease); + } + + pub(crate) fn remove(&self, region_id: RegionId) { + self.0.lock().unwrap().remove(®ion_id); + } + + #[cfg(any(test, feature = "test"))] + pub(crate) fn get(&self, region_id: RegionId) -> Option { + self.0.lock().unwrap().get(®ion_id).copied() + } +} + +impl ObjectStoreWalIoPermit for NodeLease { + fn allows_object_store_io(&self) -> bool { + !self.is_enabled() || self.now() < self.deadline.get() + } +} + +#[cfg(test)] +mod tests { + use std::time::Duration; + + use super::*; + + #[test] + fn test_object_store_permission_follows_node_lease() { + let lease = NodeLease::default(); + assert!(lease.allows_object_store_io()); + lease.enable(); + assert!(!lease.allows_object_store_io()); + let deadline = Instant::now() + Duration::from_secs(10); + lease.renew(deadline); + lease.freeze_clock(deadline - Duration::from_secs(1)); + assert!(lease.allows_object_store_io()); + lease.freeze_clock(deadline); + assert!(!lease.allows_object_store_io()); + lease.renew(deadline + Duration::from_secs(1)); + assert!(lease.allows_object_store_io()); + lease.renew(deadline - Duration::from_secs(1)); + assert!(lease.allows_object_store_io()); + } + + #[test] + fn test_record_checks_region_under_removal_lock() { + let leases = GrantedLeases::default(); + let region_id = RegionId::new(1, 1); + leases.record(region_id, Instant::now(), Some(1), || { + // A concurrent `remove` waits until the record is done. + assert!(leases.0.try_lock().is_err()); + true + }); + assert_eq!(leases.get(region_id).unwrap().candidate_lease_id, Some(1)); + + leases.remove(region_id); + leases.record(region_id, Instant::now(), Some(2), || false); + assert_eq!(leases.get(region_id), None); + } +} diff --git a/src/mito2/src/manifest/checkpointer.rs b/src/mito2/src/manifest/checkpointer.rs index 3d33942a2f9..8f5a33c8c7c 100644 --- a/src/mito2/src/manifest/checkpointer.rs +++ b/src/mito2/src/manifest/checkpointer.rs @@ -22,6 +22,7 @@ use store_api::storage::RegionId; use store_api::{MIN_VERSION, ManifestVersion}; #[cfg(test)] use tokio::sync::Notify; +use tokio::sync::watch; use crate::error::Result; use crate::manifest::action::{RegionCheckpoint, RegionManifest}; @@ -34,11 +35,19 @@ use crate::metrics::MANIFEST_OP_ELAPSED; pub(crate) struct Checkpointer { manifest_options: RegionManifestOptions, inner: Arc, - checkpoint_task: Option>, + checkpoint_task: Option, #[cfg(test)] pending_checkpoint_wait_started: Arc, } +/// A spawned checkpoint task and the signal that it has ended. +#[derive(Debug)] +struct CheckpointTask { + handle: JoinHandle<()>, + /// Closes when the task ends, so that it can be awaited without borrowing the checkpointer. + done: watch::Receiver<()>, +} + #[derive(Debug)] struct Inner { region_id: RegionId, @@ -142,7 +151,7 @@ impl Checkpointer { if self .checkpoint_task .as_ref() - .is_some_and(|handle| !handle.is_finished()) + .is_some_and(|task| !task.handle.is_finished()) { return; } @@ -187,9 +196,36 @@ impl Checkpointer { fn do_checkpoint(&mut self, checkpoint: RegionCheckpoint) { let inner = self.inner.clone(); - self.checkpoint_task = Some(common_runtime::spawn_global(async move { + let (done_sender, done) = watch::channel(()); + let handle = common_runtime::spawn_global(async move { + // The sender is dropped however the task ends, which closes the channel. + let _done_sender = done_sender; inner.do_checkpoint(checkpoint).await; - })); + }); + self.checkpoint_task = Some(CheckpointTask { handle, done }); + } + + /// Returns a future that resolves once the checkpoint task running now has ended. + /// + /// Unlike [Self::wait_for_pending_checkpoint], which borrows the checkpointer mutably and reaps + /// the task handle, this does neither, so the caller can await the future without holding the + /// manifest lock. + pub(crate) fn pending_checkpoint_completion(&self) -> impl Future + Send + use<> { + let done = self.checkpoint_task.as_ref().map(|task| task.done.clone()); + let region_id = self.inner.region_id(); + #[cfg(test)] + let wait_started = self.pending_checkpoint_wait_started.clone(); + async move { + // The channel is closed once the task has ended. + let Some(mut done) = done.filter(|receiver| receiver.has_changed().is_ok()) else { + return; + }; + #[cfg(test)] + wait_started.notify_one(); + info!("Waiting for the pending checkpoint of region {}", region_id); + // Nothing is ever sent, so this returns once the task drops the sender. + let _ = done.changed().await; + } } /// Waits for the current checkpoint task without removing its handle first. @@ -197,14 +233,14 @@ impl Checkpointer { /// Keeping the handle in `self` while awaiting is important. If the caller is /// cancelled, another lifecycle transition can still wait for the same task. pub(crate) async fn wait_for_pending_checkpoint(&mut self) { - let Some(handle) = self.checkpoint_task.as_mut() else { + let Some(task) = self.checkpoint_task.as_mut() else { return; }; #[cfg(test)] self.pending_checkpoint_wait_started.notify_one(); - let result = (&mut *handle).await; + let result = (&mut task.handle).await; // There is no cancellation point between observing completion and // clearing the handle. self.checkpoint_task = None; @@ -218,7 +254,16 @@ impl Checkpointer { pub(crate) fn is_doing_checkpoint(&self) -> bool { self.checkpoint_task .as_ref() - .is_some_and(|handle| !handle.is_finished()) + .is_some_and(|task| !task.handle.is_finished()) + } + + #[cfg(test)] + pub(crate) fn abort_checkpoint_task(&self) { + self.checkpoint_task + .as_ref() + .expect("checkpoint task must exist") + .handle + .abort(); } #[cfg(test)] diff --git a/src/mito2/src/manifest/manager.rs b/src/mito2/src/manifest/manager.rs index 6f5e36683f6..35817d50078 100644 --- a/src/mito2/src/manifest/manager.rs +++ b/src/mito2/src/manifest/manager.rs @@ -19,16 +19,15 @@ use std::time::Instant; use common_datasource::compression::CompressionType; use common_telemetry::{debug, info, warn}; -use futures::TryStreamExt; use object_store::ObjectStore; -use snafu::{OptionExt, ResultExt, ensure}; +use snafu::ensure; use store_api::metadata::RegionMetadataRef; use store_api::{MAX_VERSION, MIN_VERSION, ManifestVersion}; use crate::cache::manifest_cache::ManifestCache; use crate::config::MitoConfig; use crate::error::{ - self, EndStagingPendingSnafu, InstallManifestToSnafu, NoCheckpointSnafu, NoManifestsSnafu, + EndStagingPendingSnafu, InstallManifestToSnafu, NoCheckpointSnafu, NoManifestsSnafu, RegionStoppedSnafu, Result, }; use crate::manifest::action::{ @@ -36,10 +35,7 @@ use crate::manifest::action::{ RegionMetaAction, RegionMetaActionList, RemovedFile, }; use crate::manifest::checkpointer::Checkpointer; -use crate::manifest::storage::{ - ManifestObjectStore, file_version, is_checkpoint_file, is_delta_file, list_start_after, - manifest_compress_type, manifest_dir, -}; +use crate::manifest::storage::{ManifestObjectStore, manifest_compress_type, manifest_dir}; use crate::metrics::MANIFEST_OP_ELAPSED; use crate::region::ManifestStats; use crate::sst::file_metadata::FileMetadataInternerRef; @@ -442,7 +438,12 @@ impl RegionManifestManager { Ok(Some(manager)) } - /// Stops the manager. + /// Stops the manager. A stopped manager takes no update and starts no checkpoint, but a + /// checkpoint already running keeps writing the manifest directory until it ends. + /// + /// A caller that hands the storage to another instance waits for that checkpoint with + /// `pending_checkpoint_completion` after the stop, as engine stop and reload do. Close and + /// drop, which run in the region worker loop, deliberately do not. pub async fn stop(&mut self) { self.stopped = true; } @@ -849,6 +850,13 @@ impl RegionManifestManager { self.checkpointer.wait_for_pending_checkpoint().await; } + /// Returns a future that resolves once the in-flight checkpoint has finished, including its + /// cleanup. Unlike [Self::wait_for_pending_checkpoint], which borrows the manager mutably and + /// reaps the task handle, this does neither. + pub(crate) fn pending_checkpoint_completion(&self) -> impl Future + Send + use<> { + self.checkpointer.pending_checkpoint_completion() + } + /// Clear deleted files from manifest's `removed_files` field without update version. Notice if datanode exit before checkpoint then new manifest by open region may still contain these deleted files, which is acceptable for gc process. pub fn clear_deleted_files(&mut self, deleted_files: Vec) { let mut manifest = (*self.manifest()).clone(); @@ -879,37 +887,11 @@ impl RegionManifestManager { /// /// It is typically used in read-only regions to catch up with manifest. /// It doesn't lock the manifest directory in the object store so the result - /// may be inaccurate if there are concurrent writes. + /// may be inaccurate if there are concurrent writes. A caller holds the region's manifest + /// `RwLock` read guard across the listing (e.g. `ManifestContext::has_update`), which + /// `ManifestContext::installed_version_if_updated` does not hold while it lists. pub async fn has_update(&self) -> Result { - let last_version = self.last_version(); - - // Skip older files at the object-store layer. Files for `v == last_version` - // may still appear (`{path}{v:020}` sorts before `{path}{v:020}.json`) but - // they are filtered out below by the `version > last_version` check. - let start_after = list_start_after(self.store.manifest_dir(), last_version); - let streamer = self - .store - .manifest_lister(Some(&start_after)) - .await? - .context(error::EmptyManifestDirSnafu { - manifest_dir: self.store.manifest_dir(), - })?; - - let need_update = streamer - .try_any(|entry| async move { - let file_name = entry.name(); - if is_delta_file(file_name) || is_checkpoint_file(file_name) { - let version = file_version(file_name); - if version > last_version { - return true; - } - } - false - }) - .await - .context(error::OpenDalSnafu)?; - - Ok(need_update) + self.store.has_version_after(self.last_version()).await } /// Increases last version and returns the increased version. diff --git a/src/mito2/src/manifest/storage.rs b/src/mito2/src/manifest/storage.rs index 70693d64368..1b641ccbc32 100644 --- a/src/mito2/src/manifest/storage.rs +++ b/src/mito2/src/manifest/storage.rs @@ -32,14 +32,14 @@ use lazy_static::lazy_static; use object_store::util::join_dir; use object_store::{Lister, ObjectStore, util}; use regex::Regex; -use snafu::{ResultExt, ensure}; +use snafu::{OptionExt, ResultExt, ensure}; use store_api::storage::RegionId; use store_api::{MIN_VERSION, ManifestVersion}; use crate::cache::manifest_cache::ManifestCache; use crate::error::{ - ChecksumMismatchSnafu, ManifestVersionConflictSnafu, OpenDalSnafu, Result, - UnsupportedOperationSnafu, + ChecksumMismatchSnafu, EmptyManifestDirSnafu, ManifestVersionConflictSnafu, OpenDalSnafu, + Result, UnsupportedOperationSnafu, }; use crate::manifest::storage::checkpoint::CheckpointStorage; use crate::manifest::storage::delta::DeltaStorage; @@ -262,6 +262,35 @@ impl ManifestObjectStore { &self.path } + /// Returns whether the directory holds a delta or checkpoint of a version after + /// `last_version`. It reads the directory without locking it. + pub(crate) async fn has_version_after(&self, last_version: ManifestVersion) -> Result { + // Skip older files at the object-store layer. Files for `v == last_version` + // may still appear (`{path}{v:020}` sorts before `{path}{v:020}.json`) but + // they are filtered out below by the `version > last_version` check. + let start_after = list_start_after(self.manifest_dir(), last_version); + let streamer = + self.manifest_lister(Some(&start_after)) + .await? + .context(EmptyManifestDirSnafu { + manifest_dir: self.manifest_dir(), + })?; + + streamer + .try_any(|entry| async move { + let file_name = entry.name(); + if is_delta_file(file_name) || is_checkpoint_file(file_name) { + let version = file_version(file_name); + if version > last_version { + return true; + } + } + false + }) + .await + .context(OpenDalSnafu) + } + /// Returns an iterator of manifests. /// /// `start_after` is forwarded to the lister to skip entries whose name is diff --git a/src/mito2/src/manifest/tests/checkpoint.rs b/src/mito2/src/manifest/tests/checkpoint.rs index 86f9329ffbe..0a8a7bdab59 100644 --- a/src/mito2/src/manifest/tests/checkpoint.rs +++ b/src/mito2/src/manifest/tests/checkpoint.rs @@ -14,7 +14,7 @@ use std::assert_matches; use std::sync::Arc; -use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use std::time::Duration; use common_datasource::compression::CompressionType; @@ -25,6 +25,7 @@ use object_store::layers::mock::{ }; use store_api::storage::{FileId, RegionId}; use strum::IntoEnumIterator; +use tokio::sync::Notify; use crate::error::Error::{ChecksumMismatch, ManifestDeltaNotFound}; use crate::manifest::action::{ @@ -828,6 +829,132 @@ async fn completed_checkpoint_is_reaped_before_scheduling_the_next_one() { assert_eq!(2, manager.checkpointer().last_checkpoint_version()); } +#[rstest::rstest] +#[case::cleanup_finished(false)] +#[case::task_aborted(true)] +#[tokio::test] +async fn pending_checkpoint_completion_waits_until_the_task_ends(#[case] abort: bool) { + let (blocker, mock_layer) = CheckpointTaskBlocker::block_cleanup(); + let env = TestEnv::new().await.with_mock_layer(mock_layer); + let metadata = Arc::new(basic_region_metadata()); + let mut manager = env + .create_manifest_manager(CompressionType::Uncompressed, 1, Some(metadata)) + .await + .unwrap() + .unwrap(); + + manager.update(nop_action(), false).await.unwrap(); + tokio::time::timeout(Duration::from_secs(5), blocker.wait_until_blocked()) + .await + .expect("checkpoint cleanup did not start"); + + // Two waiters stay on their own tasks until the checkpoint ends; a third is cancelled. + let waiters = [ + manager.pending_checkpoint_completion(), + manager.pending_checkpoint_completion(), + ] + .map(tokio::spawn); + let mut cancelled = Box::pin(manager.pending_checkpoint_completion()); + assert!( + tokio::time::timeout(Duration::from_millis(100), &mut cancelled) + .await + .is_err(), + "the cancelled wait ended before the checkpoint cleanup" + ); + drop(cancelled); + assert!( + waiters.iter().all(|waiter| !waiter.is_finished()), + "a spawned wait ended before the checkpoint cleanup" + ); + // The cleanup stays blocked in the abort case, so only the abort can end the task. + if abort { + manager.checkpointer().abort_checkpoint_task(); + } else { + blocker.release(); + } + for waiter in waiters { + tokio::time::timeout(Duration::from_secs(5), waiter) + .await + .expect("the wait did not end with the checkpoint task") + .unwrap(); + } + let wait_started = manager.checkpointer().pending_checkpoint_wait_started(); + // Consumes the permit the waiters above left. + let _ = tokio::time::timeout(Duration::ZERO, wait_started.notified()).await; + tokio::time::timeout(Duration::ZERO, manager.pending_checkpoint_completion()) + .await + .expect("a wait after the checkpoint task ended did not return at once"); + assert!( + tokio::time::timeout(Duration::ZERO, wait_started.notified()) + .await + .is_err(), + "a wait after the checkpoint task ended started waiting" + ); +} + +/// Panics on the first delete, which a checkpoint issues in its cleanup, once released. +struct PanickingDeleter { + entered: Arc, + release: Arc, + panicked: Arc, +} + +impl oio::Delete for PanickingDeleter { + async fn delete(&mut self, _path: &str, _args: OpDelete) -> MockResult<()> { + self.entered.notify_one(); + self.release.notified().await; + self.panicked.store(true, Ordering::Relaxed); + panic!("mock manifest delete panic"); + } + + async fn close(&mut self) -> MockResult<()> { + Ok(()) + } +} + +#[tokio::test] +async fn pending_checkpoint_completion_ends_when_the_task_panics() { + let entered = Arc::new(Notify::new()); + let release = Arc::new(Notify::new()); + let panicked = Arc::new(AtomicBool::new(false)); + let (factory_entered, factory_release, factory_panicked) = + (entered.clone(), release.clone(), panicked.clone()); + let mock_layer = MockLayerBuilder::default() + .deleter_factory(Arc::new(move |_inner| { + Box::new(PanickingDeleter { + entered: factory_entered.clone(), + release: factory_release.clone(), + panicked: factory_panicked.clone(), + }) + })) + .build() + .unwrap(); + let env = TestEnv::new().await.with_mock_layer(mock_layer); + let metadata = Arc::new(basic_region_metadata()); + let mut manager = env + .create_manifest_manager(CompressionType::Uncompressed, 1, Some(metadata)) + .await + .unwrap() + .unwrap(); + + manager.update(nop_action(), false).await.unwrap(); + tokio::time::timeout(Duration::from_secs(5), entered.notified()) + .await + .expect("checkpoint cleanup did not start"); + let mut done = Box::pin(manager.pending_checkpoint_completion()); + assert!( + tokio::time::timeout(Duration::from_millis(100), &mut done) + .await + .is_err(), + "the wait ended before the checkpoint task panicked" + ); + release.notify_one(); + tokio::time::timeout(Duration::from_secs(5), done) + .await + .expect("the wait did not end after the checkpoint task panicked"); + assert!(panicked.load(Ordering::Relaxed)); +} + /// Retention runs inside the checkpoint task, so waiting for task completion also /// makes logical size accounting observable to the assertions below. async fn wait_for_manifest_checkpoint(manager: &RegionManifestManager) { diff --git a/src/mito2/src/metrics.rs b/src/mito2/src/metrics.rs index 2d706af3cae..83d72c5bd50 100644 --- a/src/mito2/src/metrics.rs +++ b/src/mito2/src/metrics.rs @@ -722,6 +722,35 @@ lazy_static! { /// Counter of flush files. pub static ref FLUSH_FILE_TOTAL: IntCounter = register_int_counter!("greptime_mito_flush_file_total", "mito flushed file count").unwrap(); + + /// Elapsed time of the SST writes of tail replays, by stage. + pub static ref TAIL_REPLAY_ELAPSED: HistogramVec = register_histogram_vec!( + "greptime_mito_tail_replay_elapsed", + "mito tail replay elapsed", + &[TYPE_LABEL], + // 1 ~ 3125 + exponential_buckets(1.0, 5.0, 6).unwrap(), + ) + .unwrap(); + /// Bytes of SSTs from completed chunk writes of tail replays, including chunks of rounds + /// that fail later. + pub static ref TAIL_REPLAY_BYTES_TOTAL: IntCounter = register_int_counter!( + "greptime_mito_tail_replay_bytes_total", + "mito tail replay bytes total" + ) + .unwrap(); + /// Count of SSTs written by tail replays, including SSTs of failed rounds that were deleted. + pub static ref TAIL_REPLAY_FILE_TOTAL: IntCounter = register_int_counter!( + "greptime_mito_tail_replay_file_total", + "mito tail replay file count" + ) + .unwrap(); + /// Count of failed tail replay rounds. + pub static ref TAIL_REPLAY_FAILURE_TOTAL: IntCounter = register_int_counter!( + "greptime_mito_tail_replay_failure_total", + "mito tail replay failure total" + ) + .unwrap(); } #[cfg(feature = "hdfs-object-store")] diff --git a/src/mito2/src/region.rs b/src/mito2/src/region.rs index 0fc8acb8e24..20796a67599 100644 --- a/src/mito2/src/region.rs +++ b/src/mito2/src/region.rs @@ -126,6 +126,20 @@ pub enum RegionRoleState { } impl RegionRoleState { + /// Returns whether a region in this state can replay pending tails: a leader that is + /// Writable, Altering or Editing. A region with pending tails cannot enter staging; a + /// downgrading one is leaving. + pub(crate) fn can_replay_tails(self) -> bool { + matches!( + self, + RegionRoleState::Leader( + RegionLeaderState::Writable + | RegionLeaderState::Altering + | RegionLeaderState::Editing + ) + ) + } + /// Converts the region role state to leader state if it is a leader state. pub fn into_leader_state(self) -> Option { match self { @@ -446,17 +460,10 @@ impl MitoRegion { self.manifest_ctx.state.load() == RegionRoleState::Leader(RegionLeaderState::Truncating) } - /// Returns whether the region can replay pending tails: a leader that is Writable, Altering or - /// Editing. A region with pending tails cannot enter staging; a downgrading one is leaving. + /// Returns whether the region can replay pending tails (see + /// [RegionRoleState::can_replay_tails]). pub(crate) fn can_replay_tails(&self) -> bool { - matches!( - self.manifest_ctx.state.load(), - RegionRoleState::Leader( - RegionLeaderState::Writable - | RegionLeaderState::Altering - | RegionLeaderState::Editing - ) - ) + self.manifest_ctx.state.load().can_replay_tails() } pub fn region_id(&self) -> RegionId { @@ -486,9 +493,10 @@ impl MitoRegion { self.manifest_ctx.state.load() } - /// Sets the region role state. - pub(crate) fn set_role(&self, next_role: RegionRole) { - self.manifest_ctx.set_role(next_role, self.region_id); + /// Sets the region role state. Returns the state this call replaced, None if it left the + /// state unchanged. + pub(crate) fn set_role(&self, next_role: RegionRole) -> Option { + self.manifest_ctx.set_role(next_role, self.region_id) } pub(crate) fn region_role(&self) -> RegionRole { @@ -591,7 +599,8 @@ impl MitoRegion { } } - /// Sets the region role state gracefully. This acquires the manifest write lock. + /// Sets the region role state gracefully. This acquires the manifest write lock, and releases + /// it while a change to follower or downgrading leader waits for the pending checkpoint. /// /// Ending staging awaits `drain_stalled_writes` (see [Self::end_staging]); other changes /// drop it. @@ -688,8 +697,10 @@ impl MitoRegion { wait_for_checkpoint = true; } RegionRoleState::Follower => { - // Already in desired state - no-op + // Already in desired state. The change that made it a follower may + // still wait for the checkpoint. info!("Region {} already in follower mode", self.region_id); + wait_for_checkpoint = true; } } None @@ -722,6 +733,7 @@ impl MitoRegion { "Cannot start downgrade for region {} from state {:?}", self.region_id, current_state ); + wait_for_checkpoint = true; } RegionRoleState::Leader(_) => { // The region may become writable again when the @@ -740,11 +752,15 @@ impl MitoRegion { } }; - // The state is changed before waiting, so no new writable-leader work - // can race with the barrier. Keep the manager lock while joining to - // serialize the barrier with checkpoint scheduling. + // The checkpoint task is taken under the lock after the state change, so every commit + // that could start a checkpoint has registered it: a follower takes no commit, and a + // commit of a downgrading leader starts no checkpoint. The wait holds no lock, so the + // worker and other users of the manifest are not blocked while the checkpoint finishes. if wait_for_checkpoint { - manager.wait_for_pending_checkpoint().await; + let checkpoint_done = manager.pending_checkpoint_completion(); + drop(manager); + checkpoint_done.await; + manager = self.manifest_ctx.manifest_manager.write().await; } // Hack(zhongzc): If we have just become leader (writable), persist any backfilled metadata. @@ -1528,6 +1544,60 @@ impl ManifestContext { self.manifest_manager.read().await.has_update().await } + /// Waits for the in-flight checkpoint of a stopped manager. A stopped manager starts no + /// checkpoint, so this instance no longer writes the manifest directory afterwards. + /// + /// Callers must not hold the manifest lock: this takes its read lock, and the lock is not + /// reentrant. Under the lock, use [RegionManifestManager::wait_for_pending_checkpoint] + /// instead. The wait itself holds no lock. + pub(crate) async fn wait_for_checkpoint_after_stop(&self) { + let done = { + let manager = self.manifest_manager.read().await; + debug_assert!(manager.is_stopped()); + manager.pending_checkpoint_completion() + }; + done.await; + } + + /// Returns the installed manifest version if the storage holds a newer one. The version is + /// read under the manifest read lock, which is not held across the listing, so a caller + /// rechecks it under the write lock before acting on it. It is the installed version, not + /// `last_version`, which a failed commit leaves ahead of it. + pub(crate) async fn installed_version_if_updated(&self) -> Result> { + let (store, installed) = { + let manager = self.manifest_manager.read().await; + (manager.store(), manager.manifest().manifest_version) + }; + // Lists without the read lock: held across the listing, it would let a queued writer + // block every later reader. + Ok(store + .has_version_after(installed) + .await? + .then_some(installed)) + } + + /// Fences the region for a reload, see [Self::fence_for_reload], if it is still a Writable + /// leader at `expected_version`. Returns whether it fenced the region. + pub(crate) async fn fence_for_reload_if_unchanged( + &self, + manager: &mut RegionManifestManager, + region_id: RegionId, + expected_version: ManifestVersion, + ) -> bool { + let state = self.state.load(); + let version = manager.manifest().manifest_version; + if state != RegionRoleState::Leader(RegionLeaderState::Writable) + || version != expected_version + { + info!( + "Region {region_id} is {state:?} at manifest version {version}, not a writable leader at version {expected_version}, not fencing it" + ); + return false; + } + self.fence_for_reload(manager, region_id).await; + true + } + /// Returns the current region role state. pub(crate) fn current_state(&self) -> RegionRoleState { self.state.load() @@ -2078,7 +2148,14 @@ impl ManifestContext { /// /// A region that is ending staging keeps its state: the end of staging reads the Leader /// deadline and the downgrade start when it leaves that state. - pub(crate) fn set_role(&self, next_role: RegionRole, region_id: RegionId) { + /// + /// Returns the state this call replaced, None if it left the state unchanged. It comes from + /// the atomic operation that replaced it. + pub(crate) fn set_role( + &self, + next_role: RegionRole, + region_id: RegionId, + ) -> Option { match next_role { RegionRole::Follower => { if self @@ -2090,7 +2167,7 @@ impl ManifestContext { region_id, RegionRoleState::Leader(RegionLeaderState::Staging) ); - return; + return Some(RegionRoleState::Leader(RegionLeaderState::Staging)); } match self.state.fetch_update(|state| { if !matches!( @@ -2103,10 +2180,13 @@ impl ManifestContext { None } }) { - Ok(state) => info!( - "Convert region {} to follower, previous role state: {:?}", - region_id, state - ), + Ok(state) => { + info!( + "Convert region {} to follower, previous role state: {:?}", + region_id, state + ); + Some(state) + } Err(state) => { if state != RegionRoleState::Follower { warn!( @@ -2114,6 +2194,7 @@ impl ManifestContext { region_id, state ) } + None } } } @@ -2130,7 +2211,7 @@ impl ManifestContext { region_id, RegionRoleState::Leader(RegionLeaderState::Staging) ); - return; + return Some(RegionRoleState::Leader(RegionLeaderState::Staging)); } match self.state.fetch_update(|state| { if matches!( @@ -2143,10 +2224,13 @@ impl ManifestContext { None } }) { - Ok(state) => info!( - "Convert region {} to leader, previous role state: {:?}", - region_id, state - ), + Ok(state) => { + info!( + "Convert region {} to leader, previous role state: {:?}", + region_id, state + ); + Some(state) + } Err(state) => { // These states already have the leader role; keep their ongoing operation. if !matches!( @@ -2166,6 +2250,7 @@ impl ManifestContext { region_id, state ) } + None } } } @@ -2174,6 +2259,7 @@ impl ManifestContext { "Ignore direct conversion of region {} to staging leader; staging requires the dedicated workflow", region_id ); + None } RegionRole::DowngradingLeader => { if self @@ -2188,16 +2274,19 @@ impl ManifestContext { region_id, RegionRoleState::Leader(RegionLeaderState::Staging) ); - return; + return Some(RegionRoleState::Leader(RegionLeaderState::Staging)); } match self.state.compare_exchange( RegionRoleState::Leader(RegionLeaderState::Writable), RegionRoleState::Leader(RegionLeaderState::Downgrading), ) { - Ok(state) => info!( - "Convert region {} to downgrading region, previous role state: {:?}", - region_id, state - ), + Ok(state) => { + info!( + "Convert region {} to downgrading region, previous role state: {:?}", + region_id, state + ); + Some(state) + } Err(state) => { if state != RegionRoleState::Leader(RegionLeaderState::Downgrading) { warn!( @@ -2205,6 +2294,7 @@ impl ManifestContext { region_id, state ) } + None } } } @@ -3371,49 +3461,115 @@ mod tests { .await; let region_id = RegionId::new(1024, 0); + // Each call returns the state it replaced, None if it left the state unchanged. // Leader -> Follower - manifest_ctx.set_role(RegionRole::Follower, region_id); + assert_eq!( + manifest_ctx.set_role(RegionRole::Follower, region_id), + Some(RegionRoleState::Leader(RegionLeaderState::Writable)) + ); assert_eq!(manifest_ctx.state.load(), RegionRoleState::Follower); + // Follower -> Follower + assert_eq!(manifest_ctx.set_role(RegionRole::Follower, region_id), None); + // Follower -> Leader - manifest_ctx.set_role(RegionRole::Leader, region_id); + assert_eq!( + manifest_ctx.set_role(RegionRole::Leader, region_id), + Some(RegionRoleState::Follower) + ); assert_eq!( manifest_ctx.state.load(), RegionRoleState::Leader(RegionLeaderState::Writable) ); // Direct Leader -> StagingLeader should be ignored. - manifest_ctx.set_role(RegionRole::StagingLeader, region_id); + assert_eq!( + manifest_ctx.set_role(RegionRole::StagingLeader, region_id), + None + ); assert_eq!( manifest_ctx.state.load(), RegionRoleState::Leader(RegionLeaderState::Writable) ); // Leader -> Downgrading Leader - manifest_ctx.set_role(RegionRole::DowngradingLeader, region_id); + assert_eq!( + manifest_ctx.set_role(RegionRole::DowngradingLeader, region_id), + Some(RegionRoleState::Leader(RegionLeaderState::Writable)) + ); assert_eq!( manifest_ctx.state.load(), RegionRoleState::Leader(RegionLeaderState::Downgrading) ); // Downgrading Leader -> Follower - manifest_ctx.set_role(RegionRole::Follower, region_id); + assert_eq!( + manifest_ctx.set_role(RegionRole::Follower, region_id), + Some(RegionRoleState::Leader(RegionLeaderState::Downgrading)) + ); assert_eq!(manifest_ctx.state.load(), RegionRoleState::Follower); // Can't downgrade from follower (Follower -> Downgrading Leader) - manifest_ctx.set_role(RegionRole::DowngradingLeader, region_id); + assert_eq!( + manifest_ctx.set_role(RegionRole::DowngradingLeader, region_id), + None + ); assert_eq!(manifest_ctx.state.load(), RegionRoleState::Follower); // Set region role too Downgrading Leader - manifest_ctx.set_role(RegionRole::Leader, region_id); - manifest_ctx.set_role(RegionRole::DowngradingLeader, region_id); + assert_eq!( + manifest_ctx.set_role(RegionRole::Leader, region_id), + Some(RegionRoleState::Follower) + ); + assert_eq!( + manifest_ctx.set_role(RegionRole::DowngradingLeader, region_id), + Some(RegionRoleState::Leader(RegionLeaderState::Writable)) + ); assert_eq!( manifest_ctx.state.load(), RegionRoleState::Leader(RegionLeaderState::Downgrading) ); + assert_eq!( + manifest_ctx.set_role(RegionRole::DowngradingLeader, region_id), + None + ); + // Downgrading Leader -> Leader - manifest_ctx.set_role(RegionRole::Leader, region_id); + assert_eq!( + manifest_ctx.set_role(RegionRole::Leader, region_id), + Some(RegionRoleState::Leader(RegionLeaderState::Downgrading)) + ); + assert_eq!( + manifest_ctx.state.load(), + RegionRoleState::Leader(RegionLeaderState::Writable) + ); + + assert_eq!(manifest_ctx.set_role(RegionRole::Leader, region_id), None); + + // Altering Leader -> Follower + let altering = RegionRoleState::Leader(RegionLeaderState::Altering); + manifest_ctx.state.store(altering); + assert_eq!( + manifest_ctx.set_role(RegionRole::Follower, region_id), + Some(altering) + ); + assert_eq!(manifest_ctx.state.load(), RegionRoleState::Follower); + + // Staging Leader -> Follower + let staging = RegionRoleState::Leader(RegionLeaderState::Staging); + manifest_ctx.state.store(staging); + assert_eq!( + manifest_ctx.set_role(RegionRole::Follower, region_id), + Some(staging) + ); + assert_eq!(manifest_ctx.state.load(), RegionRoleState::Follower); + + manifest_ctx.state.store(staging); + assert_eq!( + manifest_ctx.set_role(RegionRole::Leader, region_id), + Some(staging) + ); assert_eq!( manifest_ctx.state.load(), RegionRoleState::Leader(RegionLeaderState::Writable) diff --git a/src/mito2/src/region/opener.rs b/src/mito2/src/region/opener.rs index 5cf63b7c85a..8071dfe1123 100644 --- a/src/mito2/src/region/opener.rs +++ b/src/mito2/src/region/opener.rs @@ -78,8 +78,11 @@ use crate::sst::FormatType; use crate::sst::file::{FileHandle, RegionFileId, RegionIndexId}; use crate::sst::file_purger::{FilePurgerRef, create_file_purger}; use crate::sst::file_ref::FileReferenceManagerRef; +use crate::sst::index::IndexBuildType; +use crate::sst::index::handler::PlanContext; use crate::sst::index::intermediate::IntermediateManager; use crate::sst::index::puffin_manager::PuffinManagerFactory; +use crate::sst::index::registry::IndexRegistryRef; use crate::sst::location::{self, region_dir_from_table_dir}; use crate::sst::parquet::metadata::{MetadataLoader, extract_primary_key_range}; use crate::sst::parquet::reader::MetadataCacheMetrics; @@ -149,6 +152,7 @@ pub type PartitionExprFetcherRef = Arc; /// Builder to create a new [MitoRegion] or open an existing one. pub(crate) struct RegionOpener { + index_registry: Option, region_id: RegionId, metadata_builder: Option, memtable_builder_provider: MemtableBuilderProvider, @@ -192,6 +196,7 @@ impl RegionOpener { partition_expr_fetcher: PartitionExprFetcherRef, ) -> RegionOpener { RegionOpener { + index_registry: None, region_id, metadata_builder: None, memtable_builder_provider, @@ -217,6 +222,12 @@ impl RegionOpener { } } + /// Sets the registry used to validate new-region index options. + pub(crate) fn with_index_registry(mut self, registry: IndexRegistryRef) -> Self { + self.index_registry = Some(registry); + self + } + /// Sets the store for companion range indexes. pub(crate) fn series_index_store(mut self, store: Option) -> Self { self.series_index_store = store; @@ -384,6 +395,24 @@ impl RegionOpener { }; ensure_json2_uses_flat_format(&metadata, &options)?; options.validate_column_compression(&metadata)?; + // Validate explicit new-region configuration before creating its manifest. + // Opening an existing manifest above does not require its optional providers. + if let Some(registry) = &self.index_registry { + registry + .validate(&PlanContext { + metadata: &metadata, + index_options: &options.index_options, + // Validate initial options without building indexes; extensions skip flush work. + build_type: IndexBuildType::Flush, + existing_indexes: &[], + }) + .map_err(|err| { + InvalidRegionOptionsSnafu { + reason: err.to_string(), + } + .build() + })?; + } // The region's WAL history starts in this log store, so reopening // the region on it passes the history check without any entry. It is // recorded before the manifest exists: a log store that gave up its diff --git a/src/mito2/src/request.rs b/src/mito2/src/request.rs index d15b2f232a0..be3e76f53c9 100644 --- a/src/mito2/src/request.rs +++ b/src/mito2/src/request.rs @@ -1159,6 +1159,13 @@ pub(crate) enum BackgroundNotify { }, /// The region became writable and may have pending tails to replay. RegionBecameWritable, + /// A role change left the region unable to replay its tails (see + /// [MitoRegion::can_replay_tails](crate::region::MitoRegion::can_replay_tails)); a running + /// replay is cancelled. + RegionCannotReplay { + /// The instance the role change applied to. + region: MitoRegionRef, + }, /// A tail replay published its result in the manifest. TailReplayCommitted { /// The instance the replay ran for. @@ -1204,6 +1211,7 @@ impl BackgroundNotify { | Self::RegionFenced | Self::RegionReloaded { .. } | Self::RegionBecameWritable + | Self::RegionCannotReplay { .. } | Self::TailReplayCommitted { .. } | Self::TailReplayEnded => false, } diff --git a/src/mito2/src/schedule.rs b/src/mito2/src/schedule.rs index e0b91e1ad59..9b09a83927d 100644 --- a/src/mito2/src/schedule.rs +++ b/src/mito2/src/schedule.rs @@ -15,7 +15,7 @@ use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Mutex}; -use common_base::cancellation::CancellationHandle; +use tokio_util::sync::CancellationToken; pub mod remote_job_scheduler; pub mod scheduler; @@ -23,7 +23,7 @@ pub mod scheduler; /// Shared state for cooperatively cancelling a task until it starts committing. #[derive(Debug, Clone)] pub(crate) struct CancellableTaskState { - cancel_handle: Arc, + cancel_token: CancellationToken, commit_started: Arc>, started: Arc, } @@ -31,7 +31,7 @@ pub(crate) struct CancellableTaskState { impl CancellableTaskState { pub(crate) fn new() -> Self { Self { - cancel_handle: Arc::new(CancellationHandle::default()), + cancel_token: CancellationToken::new(), commit_started: Arc::new(Mutex::new(false)), started: Arc::new(AtomicBool::new(false)), } @@ -47,12 +47,12 @@ impl CancellableTaskState { self.started.load(Ordering::Relaxed) } - pub(crate) fn cancel_handle(&self) -> Arc { - self.cancel_handle.clone() + pub(crate) fn cancel_token(&self) -> CancellationToken { + self.cancel_token.clone() } pub(crate) fn is_cancelled(&self) -> bool { - self.cancel_handle.is_cancelled() + self.cancel_token.is_cancelled() } /// Returns whether the task has crossed the non-cancellable publication boundary. @@ -65,7 +65,7 @@ impl CancellableTaskState { /// Returns false if cancellation was requested first. pub(crate) fn mark_commit_started(&self) -> bool { let mut commit_started = self.commit_started.lock().unwrap(); - if self.cancel_handle.is_cancelled() { + if self.cancel_token.is_cancelled() { return false; } *commit_started = true; @@ -78,11 +78,11 @@ impl CancellableTaskState { if *commit_started { return RequestCancelResult::TooLateToCancel; } - if self.cancel_handle.is_cancelled() { + if self.cancel_token.is_cancelled() { return RequestCancelResult::AlreadyCancelling; } - self.cancel_handle.cancel(); + self.cancel_token.cancel(); RequestCancelResult::CancelIssued } } diff --git a/src/mito2/src/series_index/task.rs b/src/mito2/src/series_index/task.rs index eeb8ef50de6..9df371dd2e3 100644 --- a/src/mito2/src/series_index/task.rs +++ b/src/mito2/src/series_index/task.rs @@ -594,7 +594,9 @@ mod tests { LifecycleChange::Remove => { regions.remove_region(region.region_id).unwrap(); } - LifecycleChange::Demote => region.set_role(RegionRole::Follower), + LifecycleChange::Demote => { + region.set_role(RegionRole::Follower); + } LifecycleChange::Stop => state.stop(), } release.notify_one(); diff --git a/src/mito2/src/sst.rs b/src/mito2/src/sst.rs index a99d539d17c..cc579a11843 100644 --- a/src/mito2/src/sst.rs +++ b/src/mito2/src/sst.rs @@ -50,6 +50,7 @@ pub mod location; pub mod parquet; pub(crate) mod primary_key; pub mod range_index; +pub(crate) mod upload; pub(crate) mod version; /// Default write buffer size, it should be greater than the default minimum upload part of S3 (5mb). diff --git a/src/mito2/src/sst/file.rs b/src/mito2/src/sst/file.rs index f886fe9f9d8..fc7f09bed1f 100644 --- a/src/mito2/src/sst/file.rs +++ b/src/mito2/src/sst/file.rs @@ -45,6 +45,7 @@ use crate::sst::file_ref::{FileReferenceManager, FileReferenceManagerRef}; use crate::sst::index::fulltext_index::FULLTEXT_BLOOM_VERSION; use crate::sst::location; use crate::sst::parquet::SstInfo; +use crate::sst::parquet::writer::SstWriteGuard; use crate::sst::primary_key::PrimaryKeyRangeMapper; /// Custom serde functions for Bytes fields serialized as base64 strings. @@ -1042,7 +1043,7 @@ pub async fn delete_files( Ok(()) } -/// Tracks finalized SSTs until their manifest edit is committed. +/// Tracks SSTs from creation until their manifest edit is committed. /// /// Flush and local compaction jobs use this to remove files that were written successfully but /// abandoned by cancellation or a later failure. @@ -1054,6 +1055,15 @@ pub(crate) struct UncommittedSsts { cache_manager: Option, } +#[async_trait::async_trait] +impl SstWriteGuard for UncommittedSsts { + async fn before_create(&self, file_id: RegionFileId) -> crate::error::Result<()> { + // An index can be created before its final metadata is available. + self.track_before_upload(file_id.file_id(), true); + Ok(()) + } +} + impl UncommittedSsts { pub(crate) fn new( region_id: RegionId, diff --git a/src/mito2/src/sst/index.rs b/src/mito2/src/sst/index.rs index 93c7241ff45..cc4ffcbb8ad 100644 --- a/src/mito2/src/sst/index.rs +++ b/src/mito2/src/sst/index.rs @@ -23,7 +23,7 @@ mod indexer; pub mod intermediate; pub(crate) mod inverted_index; pub mod kind; -mod primary_key; +pub mod primary_key; pub mod puffin_manager; pub mod registry; #[cfg(test)] @@ -63,8 +63,8 @@ use crate::cache::{CacheManagerRef, CacheStrategy}; #[cfg(test)] use crate::config::{BloomFilterConfig, InvertedIndexConfig}; use crate::error::{ - BuildIndexAsyncSnafu, Error, ExternalSnafu, InvalidConfigSnafu, JoinSnafu, RegionClosedSnafu, - RegionDroppedSnafu, RegionTruncatedSnafu, Result, + BuildIndexAsyncSnafu, Error, ExternalSnafu, InvalidConfigSnafu, JoinSnafu, + OperateAbortedIndexSnafu, RegionClosedSnafu, RegionDroppedSnafu, RegionTruncatedSnafu, Result, }; use crate::metrics::{ INDEX_ARTIFACT_CLEANUP_FAILURE_TOTAL, INDEX_CREATE_DISCARDED_TOTAL, INDEX_CREATE_MEMORY_USAGE, @@ -292,6 +292,11 @@ impl Indexer { self.creators.is_empty() } + /// Whether this output has an active extension creator. + pub(crate) fn has_extension_creators(&self) -> bool { + self.creators.iter().any(|active| !active.is_builtin()) + } + #[cfg(test)] fn has_kind(&self, kind: kind::IndexKind) -> bool { self.creators @@ -512,6 +517,20 @@ pub(crate) struct IndexerBuilderImpl { pub(crate) index_options: IndexOptions, } +impl IndexerBuilderImpl { + fn plan(&self) -> Arc { + if let Some(inputs) = &self.index_build_inputs { + return inputs.plan.clone(); + } + Arc::new(self.registry.plan(&handler::PlanContext { + metadata: &self.metadata, + index_options: &self.index_options, + build_type: self.build_type.clone(), + existing_indexes: &[], + })) + } +} + #[async_trait::async_trait] impl IndexerBuilder for IndexerBuilderImpl { /// Sanity check for arguments and create a new [Indexer] if arguments are valid. @@ -530,17 +549,7 @@ impl IndexerBuilder for IndexerBuilderImpl { ..Default::default() }; - let plan = if let Some(inputs) = &self.index_build_inputs { - inputs.plan.clone() - } else { - let context = handler::PlanContext { - metadata: &self.metadata, - index_options: &self.index_options, - build_type: self.build_type.clone(), - existing_indexes: &[], - }; - Arc::new(self.registry.plan(&context)) - }; + let plan = self.plan(); indexer.failure = plan.check_success().err(); let mut context = handler::BuildContext { metadata: &self.metadata, @@ -796,7 +805,8 @@ pub struct IndexBuildTask { pub file_purger: FilePurgerRef, /// When write cache is enabled, the indexer builder should be built from the write cache. /// Otherwise, it should be built from the access layer. - pub indexer_builder: Arc, + /// Rebuild owns plan assembly; external implementations enter through the registry. + pub(crate) indexer_builder: Arc, /// Request sender to notify the region worker. pub(crate) request_sender: Sender, /// Senders of callers waiting for this build. Coalesced tasks and @@ -957,16 +967,20 @@ impl IndexBuildTask { // Taken before `prepare_source` replaces the source, and used for the // index files and listener events of this build. let region_file_id = self.region_file_id(); - if let ControlFlow::Break(report) = - self.prepare_source(region_file_id, &version_control).await + if let ControlFlow::Break(report) = self + .prepare_source(region_file_id, &version_control) + .await? { return Ok(report); } - let new_index_version = self - .source - .file_meta - .index_version() - .map_or(0, |version| version + 1); + // Metadata-only removal leaves no current index, but its version still reserves + // every older path until GC finishes. Never reuse those paths on a later build. + let file_meta = &self.source.file_meta; + let new_index_version = if file_meta.index_version > 0 || file_meta.exists_index() { + file_meta.index_version + 1 + } else { + 0 + }; let (mut indexer, index_output) = match self.create_index(region_file_id, new_index_version).await? { ControlFlow::Continue(created) => created, @@ -992,13 +1006,13 @@ impl IndexBuildTask { &mut self, region_file_id: RegionFileId, version_control: &VersionControlRef, - ) -> ControlFlow { + ) -> Result> { // Check SST file existence before building index to avoid failure of parquet reader. if !self.check_sst_file_exists(version_control).await { - return ControlFlow::Break( + return Ok(ControlFlow::Break( self.abort_and_notify(region_file_id, "SST file not found during index build") .await, - ); + )); } // A task may have waited behind another build of the same SST. Build on @@ -1011,41 +1025,96 @@ impl IndexBuildTask { .get(&self.source.file_meta.file_id) .cloned(); let Some(current_file_meta) = current_file_meta else { - return ControlFlow::Break( + return Ok(ControlFlow::Break( self.abort_and_notify( region_file_id, "SST file not found in manifest during index build", ) .await, - ); + )); }; + if matches!( + self.reason, + IndexBuildType::Manual | IndexBuildType::SchemaChange + ) { + self.indexer_builder + .registry + .validate_schema_kinds(&self.target_region_metadata) + .with_context(|_| ExternalSnafu { + context: "validating index handlers for rebuild".to_string(), + })?; + } + let context = handler::PlanContext { + metadata: &self.target_region_metadata, + index_options: &self.index_options, + build_type: self.reason.clone(), + existing_indexes: ¤t_file_meta.indexes, + }; + let plan = Arc::new(self.indexer_builder.registry.plan(&context)); + plan.check_success().context(BuildIndexAsyncSnafu { + region_id: self.region_id, + })?; + // Manual requests skip current indexes; schema changes must run their maintenance plans. if self.reason == IndexBuildType::Manual && current_file_meta.is_index_consistent_with_region( &self.target_region_metadata.column_metadatas, &self.index_options, ) + && plan.is_current(¤t_file_meta, &context) { - return ControlFlow::Break( + return Ok(ControlFlow::Break( self.abort_and_notify(region_file_id, "Index is already up to date") .await, - ); + )); } + let current_file = self.file.with_updated_index(current_file_meta.clone()); + let builder = Arc::make_mut(&mut self.indexer_builder); + let output_rows = (current_file_meta.num_rows != 0).then_some(current_file_meta.num_rows); + if let Some(inputs) = &mut builder.index_build_inputs { + inputs.plan = plan; + inputs.inputs = vec![current_file.clone()].into(); + inputs.output_rows = output_rows; + } else { + builder.index_build_inputs = Some(build::IndexBuildInputs { + plan, + inputs: vec![current_file.clone()].into(), + input_puffin_manager: self.access_layer.build_puffin_manager(), + can_merge_inputs: self + .target_region_metadata + .partition_expr + .as_deref() + .is_none_or(str::is_empty) + && current_file_meta.region_id == self.region_id, + output_rows, + memory_limit: None, + }); + } + self.file = current_file; self.source.file_meta = current_file_meta.as_ref().clone(); - ControlFlow::Continue(()) + Ok(ControlFlow::Continue(())) } - /// Reads the SST and creates the index files. + /// Builds a replacement index file, scanning data only when a creator needs rows. async fn create_index( &self, region_file_id: RegionFileId, new_index_version: u64, ) -> Result> { - let mut parquet_reader = self + let reader_builder = self .access_layer - .read_sst(self.file.clone()) // use the latest file handle instead of creating a new one - .expected_metadata(Some(self.target_region_metadata.clone())) - .build() - .await?; + .read_sst(self.file.clone()) + .expected_metadata(Some(self.target_region_metadata.clone())); + let plan = self.indexer_builder.plan(); + // Inverted segments must align with the actual SST row groups. Other + // creators can decide input reuse without opening the Parquet file. + let needs_row_group_size = plan + .entries() + .any(|entry| entry.kind.index_type() == IndexType::InvertedIndex); + let mut parquet_reader = if needs_row_group_size { + reader_builder.build().await? + } else { + None + }; let row_group_size = parquet_reader.as_ref().and_then(|reader| { reader @@ -1055,39 +1124,139 @@ impl IndexBuildTask { .map(|row_group| row_group.num_rows() as usize) .filter(|size| *size > 0) }); - let mut indexer = self .indexer_builder .build(region_file_id, new_index_version, row_group_size) .await; - // The build type or index options may leave nothing to build. Return before reading - // any row; an empty indexer finishes with no output, which publishes nothing. + self.check_rebuild_indexer_or_abort(&mut indexer).await?; if indexer.is_empty() { + if self.can_remove_all_indexes() { + return Ok(ControlFlow::Continue((indexer, IndexOutput::default()))); + } return Ok(ControlFlow::Break(self.aborted("No index to build"))); } - if let Some(mut parquet_reader) = parquet_reader.take() { - // TODO(SNC123): optimize index batch - loop { - match parquet_reader.next_record_batch().await { + if indexer.requires_row_scan() && !needs_row_group_size { + parquet_reader = match reader_builder.build().await { + Ok(reader) => reader, + Err(err) => { + indexer.abort().await; + return Err(err); + } + }; + } + if indexer.requires_row_scan() + && let Some(mut reader) = parquet_reader.take() + { + while indexer.requires_row_scan() { + match reader.next_record_batch().await { Ok(Some(batch)) => { indexer.update_flat(&batch).await; + self.check_rebuild_indexer_or_abort(&mut indexer).await?; } Ok(None) => break, - Err(e) => { + Err(err) => { indexer.abort().await; - return Err(e); + return Err(err); } } } } - let index_output = indexer.finish().await; - - if index_output.file_size == 0 { - // The indexer logs and drops index creation failures. + let output = indexer.finish().await; + self.check_rebuild_indexer_or_abort(&mut indexer).await?; + if let Err(err) = self.check_rebuild_output(&output) { + indexer.abort().await; + return Err(err).context(BuildIndexAsyncSnafu { + region_id: self.region_id, + }); + } + if output.file_size == 0 { return Ok(ControlFlow::Break(self.aborted("No index was created"))); } - Ok(ControlFlow::Continue((indexer, index_output))) + Ok(ControlFlow::Continue((indexer, output))) + } + + /// Aborts a failed replacement before propagating the rebuild error. + async fn check_rebuild_indexer_or_abort(&self, indexer: &mut Indexer) -> Result<()> { + if let Err(err) = self.check_rebuild_indexer(indexer) { + indexer.abort().await; + return Err(err).context(BuildIndexAsyncSnafu { + region_id: self.region_id, + }); + } + Ok(()) + } + + /// A budget skip may omit a new kind, but must not erase an existing one. + fn check_rebuild_indexer(&self, indexer: &Indexer) -> Result<(), Arc> { + indexer.check_success()?; + let source = &self.source.file_meta; + if indexer.discarded().iter().any(|kind| { + let index_type = kind.index_type(); + source.available_indexes.contains(&index_type) + || source + .indexes + .iter() + .any(|column| column.created_indexes.contains(&index_type)) + }) { + warn!( + "Preserving previous index generation after budget discard, region_id: {}, file_id: {}, discarded: {:?}", + self.region_id, + source.file_id, + indexer.discarded() + ); + return Err(Arc::new(OperateAbortedIndexSnafu.build())); + } + Ok(()) + } + + /// A skipped creator or partial completion must not erase a requested existing extension. + fn check_rebuild_output(&self, output: &IndexOutput) -> Result<(), Arc> { + let source = &self.source.file_meta; + for entry in self.indexer_builder.plan().entries() { + if entry.kind.is_builtin() { + continue; + } + let index_type = entry.kind.index_type(); + let existing_column = source.indexes.iter().any(|column| { + column.column_id == entry.column_id && column.created_indexes.contains(&index_type) + }); + // Legacy file-level descriptors do not identify individual indexed columns. + let legacy_kind = source.available_indexes.contains(&index_type) + && !source + .indexes + .iter() + .any(|column| column.created_indexes.contains(&index_type)); + if (existing_column || legacy_kind) + && !output.entries.iter().any(|completed| { + completed.kind == entry.kind + && (legacy_kind || completed.column_id == Some(entry.column_id)) + }) + { + warn!( + "Preserving previous index generation after incomplete rebuild, region_id: {}, file_id: {}, column_id: {}, kind: {}", + self.region_id, + source.file_id, + entry.column_id, + entry.kind.as_str() + ); + return Err(Arc::new(OperateAbortedIndexSnafu.build())); + } + } + Ok(()) + } + + /// Disabled options may remove old indexes after handler validation. + /// A failed plan is not an empty removal plan and must retain the old file. + fn can_remove_all_indexes(&self) -> bool { + self.source.file_meta.exists_index() + && self + .indexer_builder + .index_build_inputs + .as_ref() + .is_some_and(|inputs| { + inputs.plan.check_success().is_ok() && inputs.plan.entries().next().is_none() + }) } /// Uploads the index files and commits them to the manifest. @@ -1171,7 +1340,7 @@ impl IndexBuildTask { // cannot storm. self.notify_worker(BackgroundNotify::IndexBuildRetry(BuildIndexRequest { region_id: self.region_id, - build_type: IndexBuildType::SchemaChange, + build_type: self.reason.clone(), file_metas: vec![self.source.file_meta.clone()], result_senders: self.result_senders.clone(), })) @@ -1185,6 +1354,9 @@ impl IndexBuildTask { index_file_id: FileId, index_version: u64, ) -> Result<()> { + if output.file_size == 0 { + return Ok(()); + } if let Some(write_cache) = &self.write_cache { let file_id = self.source.file_meta.file_id; let region_id = self.source.file_meta.region_id; @@ -1448,6 +1620,25 @@ impl IndexBuildScheduler { &mut self, version_control: &VersionControlRef, task: IndexBuildTask, + ) { + self.schedule_build_inner(version_control, task, false) + .await; + } + + /// A retry is queued before its previous task releases the active slot. + pub(crate) async fn schedule_retry( + &mut self, + version_control: &VersionControlRef, + task: IndexBuildTask, + ) { + self.schedule_build_inner(version_control, task, true).await; + } + + async fn schedule_build_inner( + &mut self, + version_control: &VersionControlRef, + task: IndexBuildTask, + is_retry: bool, ) { let status = self .region_status @@ -1461,7 +1652,8 @@ impl IndexBuildScheduler { ); // A manual build must not report success while an active build that may // not create the requested indexes is still running, so it waits as well. - let can_wait_for_active = status.retiring + let can_wait_for_active = is_retry + || status.retiring || matches!( task.reason, IndexBuildType::SchemaChange | IndexBuildType::Manual @@ -1633,7 +1825,7 @@ impl IndexBuildScheduler { #[cfg(test)] mod tests { - use std::sync::Arc; + use std::sync::{Arc, Mutex}; use api::v1::SemanticType; use common_base::readable_size::ReadableSize; @@ -1663,7 +1855,7 @@ mod tests { use crate::region::version::{VersionBuilder, VersionControl}; use crate::schedule::scheduler::{LocalScheduler, Scheduler}; use crate::sst::file::{FileMeta, RegionFileId}; - use crate::sst::file_purger::NoopFilePurger; + use crate::sst::file_purger::{FilePurger, NoopFilePurger}; use crate::sst::location; use crate::sst::parquet::WriteOptions; use crate::test_util::memtable_util::EmptyMemtableBuilder; @@ -2080,6 +2272,13 @@ mod tests { } impl handler::IndexKindHandler for TestProvider { + fn validate( + &self, + _context: &handler::PlanContext<'_>, + ) -> std::result::Result<(), common_error::ext::BoxedError> { + Ok(()) + } + fn kinds(&self) -> &[kind::IndexKind] { match self.kind { Some(kind::ExtensionIndexKind::Kll) => { @@ -2118,6 +2317,9 @@ mod tests { }], } } + fn is_current(&self, _: &crate::sst::file::FileMeta, _: &handler::PlanContext<'_>) -> bool { + false + } fn memory_limit(&self) -> Option { self.hard_limit @@ -2183,6 +2385,10 @@ mod tests { Reused, Budget, Create, + SkipCreate, + EmptyFinish, + CompletePair, + PartialFinish, Update, UpdateFlat, Finish, @@ -2206,6 +2412,13 @@ mod tests { } impl handler::IndexKindHandler for FailingProvider { + fn validate( + &self, + _context: &handler::PlanContext<'_>, + ) -> std::result::Result<(), common_error::ext::BoxedError> { + Ok(()) + } + fn kinds(&self) -> &[kind::IndexKind] { &[kind::IndexKind::Extension(kind::ExtensionIndexKind::Hll)] } @@ -2235,12 +2448,32 @@ mod tests { handler::IndexKindHandler::kinds(self) } fn entries(&self) -> &[handler::PlanEntry] { + if matches!( + self.0, + ProviderFailure::CompletePair | ProviderFailure::PartialFinish + ) { + return &[ + handler::PlanEntry { + column_id: 0, + kind: kind::IndexKind::Extension(kind::ExtensionIndexKind::Hll), + format_version: 2, + }, + handler::PlanEntry { + column_id: 1, + kind: kind::IndexKind::Extension(kind::ExtensionIndexKind::Hll), + format_version: 2, + }, + ]; + } &[handler::PlanEntry { column_id: 0, kind: kind::IndexKind::Extension(kind::ExtensionIndexKind::Hll), format_version: 2, }] } + fn is_current(&self, _: &crate::sst::file::FileMeta, _: &handler::PlanContext<'_>) -> bool { + false + } fn memory_limit(&self) -> Option { (self.0 == ProviderFailure::Budget).then_some(16) @@ -2256,6 +2489,9 @@ mod tests { if self.0 == ProviderFailure::Create { return Err(provider_test_error()); } + if self.0 == ProviderFailure::SkipCreate { + return Ok(None); + } Ok(Some(Box::new(FailingCreator(self.0)))) } } @@ -2300,6 +2536,9 @@ mod tests { ) -> std::result::Result, common_error::ext::BoxedError> { use puffin::puffin_manager::PuffinWriter; + if self.0 == ProviderFailure::EmptyFinish { + return Ok(Vec::new()); + } writer .put_blob( "test-sketch", @@ -2313,11 +2552,18 @@ mod tests { // Fail after writing to exercise partially written artifact handling. return Err(provider_test_error()); } - Ok(vec![CompletedEntry { + let mut entries = vec![CompletedEntry { column_id: Some(0), kind: kind::IndexKind::Extension(kind::ExtensionIndexKind::Hll), format_version: 2, - }]) + }]; + if self.0 == ProviderFailure::CompletePair { + entries.push(CompletedEntry { + column_id: Some(1), + ..entries[0].clone() + }); + } + Ok(entries) } async fn abort(&mut self) -> std::result::Result<(), common_error::ext::BoxedError> { @@ -2475,6 +2721,41 @@ mod tests { } } + #[tokio::test] + async fn test_extension_finish_failure_discards_completed_builtin_output() { + for failure in [ProviderFailure::None, ProviderFailure::Finish] { + let env = SchedulerEnv::new().await; + let mut builder = mock_indexer_builder(Arc::new(sst_region_metadata()), &env).await; + let builder = Arc::make_mut(&mut builder); + builder.build_type = IndexBuildType::Compact; + Arc::make_mut(&mut builder.registry) + .register(Arc::new(FailingProvider(failure))) + .unwrap(); + let mut indexer = builder.build(random_region_file_id(), 0, Some(1024)).await; + // Registry order puts real built-in creators before the failing extension. + assert!(indexer.creators.first().unwrap().is_builtin()); + assert!(!indexer.creators.last().unwrap().is_builtin()); + indexer + .update_flat(&new_record_batch_by_range(&["a", "b"], 0, 10)) + .await; + assert!(indexer.check_success().is_ok()); + let output = indexer.finish().await; + if failure == ProviderFailure::None { + assert!(output.entries.iter().any(|entry| entry.kind.is_builtin())); + assert!(output.entries.iter().any(|entry| !entry.kind.is_builtin())); + assert!(output.file_size > 0); + assert!(indexer.check_success().is_ok()); + } else { + // A shared writer cannot publish the preceding successful index alone. + assert!(output.entries.is_empty()); + assert!(output.build_indexes().unwrap().is_empty()); + assert_eq!(output.file_size, 0); + assert!(indexer.check_success().is_err()); + } + assert!(indexer.creators.is_empty()); + } + } + #[tokio::test] async fn test_provider_compaction_only_and_per_output() { let (dir, factory) = PuffinManagerFactory::new_for_test_async("provider_scope").await; @@ -2524,6 +2805,9 @@ mod tests { ); assert!(!first.is_empty()); assert!(!second.is_empty()); + // Deferring the built-in indexes must retain the sketch creator. + first.abort_builtin_creators().await; + assert!(!first.creators.is_empty()); assert_eq!(first.creators[0].creator.memory_usage(), 17); first.abort().await; assert!(first.creators.is_empty()); @@ -3154,6 +3438,11 @@ mod tests { file_size: sst_info.file_size, max_row_group_uncompressed_size: sst_info.max_row_group_uncompressed_size, available_indexes: smallvec![IndexType::InvertedIndex], + indexes: vec![ColumnIndexMetadata { + column_id: 2, + created_indexes: smallvec::smallvec![IndexType::InvertedIndex], + ..Default::default() + }], // Old manifests may publish an index without recording its size. index_file_size: 0, index_version: 0, @@ -3210,6 +3499,18 @@ mod tests { assert!(updated_meta.index_file_size > 0); assert_eq!(updated_meta.file_id, file_meta.file_id); assert_eq!(updated_meta.index_version, 1); + // This built-in-only rebuild must not advertise extension indexes. + assert!( + updated_meta + .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 + ))) + ); let field_0_index = updated_meta .indexes .iter() @@ -3343,8 +3644,489 @@ mod tests { schedule_index_build_task_with_mode(IndexBuildMode::Sync).await; } + #[derive(Debug, Default)] + struct RecordingRebuildPurger(Mutex>); + + impl FilePurger for RecordingRebuildPurger { + fn purge_file(&self, meta: FileMeta) { + self.0.lock().unwrap().push(meta); + } + } + + #[rstest::rstest] + #[case(false)] + #[case(true)] + #[tokio::test] + async fn test_rebuild_metadata_refresh_retains_sst_lifetime(#[case] unknown_rows: bool) { + let env = SchedulerEnv::new().await; + let metadata = Arc::new(sst_region_metadata()); + let manifest_ctx = env.mock_manifest_context(metadata.clone()).await; + let purger = Arc::new(RecordingRebuildPurger::default()); + let info = mock_sst_file(metadata.clone(), &env, IndexBuildMode::Async).await; + let meta = FileMeta { + region_id: metadata.region_id, + file_id: info.file_id, + file_size: info.file_size, + num_rows: if unknown_rows { + 0 + } else { + info.num_rows as u64 + }, + num_row_groups: info.num_row_groups, + ..Default::default() + }; + let mut refreshed = meta.clone(); + refreshed.index_version = 1; + seed_manifest_file(&manifest_ctx, &refreshed).await; + let version = mock_version_control( + metadata.clone(), + Arc::new(NoopFilePurger), + HashMap::from([(meta.file_id, refreshed.clone())]), + ) + .await; + let original = FileHandle::new(meta.clone(), purger.clone()); + let builder = mock_indexer_builder(metadata.clone(), &env).await; + let (tx, _rx) = mpsc::channel(4); + let mut task = IndexBuildTask { + region_id: metadata.region_id, + file: original.clone(), + target_region_metadata: metadata.clone(), + source: IndexBuildSource::new(meta.clone(), metadata.schema_version), + reason: IndexBuildType::SchemaChange, + access_layer: env.access_layer.clone(), + listener: WorkerListener::default(), + manifest_ctx, + write_cache: None, + cache_manager: None, + file_purger: purger.clone(), + indexer_builder: builder, + request_sender: tx, + index_options: IndexOptions::default(), + result_senders: Vec::new(), + }; + assert!(matches!( + task.prepare_source(meta.file_id(), &version).await.unwrap(), + ControlFlow::Continue(()) + )); + assert_eq!(task.file.meta_ref().index_version, 1); + assert_eq!( + task.indexer_builder + .index_build_inputs + .as_ref() + .unwrap() + .output_rows, + (!unknown_rows).then_some(info.num_rows as u64), + ); + let reader = task + .indexer_builder + .index_build_inputs + .as_ref() + .unwrap() + .inputs[0] + .clone(); + // Removal after preparation must wait for the task and its plugin readers. + original.mark_deleted(); + drop(original); + assert!(purger.0.lock().unwrap().is_empty()); + drop(task); + assert!(purger.0.lock().unwrap().is_empty()); + drop(reader); + assert_eq!(*purger.0.lock().unwrap(), vec![refreshed]); + } + + #[tokio::test] + async fn test_rebuild_scans_only_when_a_creator_requires_rows() { + for with_builtin in [false, true] { + let env = SchedulerEnv::new().await; + let mut metadata = sst_region_metadata(); + if !with_builtin { + for column in &mut metadata.column_metadatas { + column.column_schema.set_inverted_index(false); + column.column_schema.unset_skipping_options().unwrap(); + } + } + let metadata = Arc::new(metadata); + let manifest_ctx = env.mock_manifest_context(metadata.clone()).await; + let file_purger = Arc::new(NoopFilePurger {}); + let info = mock_sst_file(metadata.clone(), &env, IndexBuildMode::Async).await; + let file_meta = FileMeta { + region_id: metadata.region_id, + file_id: info.file_id, + file_size: info.file_size, + max_row_group_uncompressed_size: info.max_row_group_uncompressed_size, + num_rows: info.num_rows as u64, + num_row_groups: info.num_row_groups, + ..Default::default() + }; + seed_manifest_file(&manifest_ctx, &file_meta).await; + let version = mock_version_control( + metadata.clone(), + file_purger.clone(), + HashMap::from([(file_meta.file_id, file_meta.clone())]), + ) + .await; + let mut builder = mock_indexer_builder(metadata.clone(), &env).await; + let mutable = Arc::make_mut(&mut builder); + mutable.build_type = IndexBuildType::Manual; + Arc::make_mut(&mut mutable.registry) + .register(Arc::new(FailingProvider(ProviderFailure::Reused))) + .unwrap(); + let (tx, _rx) = mpsc::channel(4); + let mut task = IndexBuildTask { + region_id: metadata.region_id, + file: FileHandle::new(file_meta.clone(), file_purger.clone()), + target_region_metadata: metadata.clone(), + source: IndexBuildSource::new(file_meta.clone(), metadata.schema_version), + reason: IndexBuildType::Manual, + access_layer: env.access_layer.clone(), + listener: WorkerListener::default(), + manifest_ctx: manifest_ctx.clone(), + write_cache: None, + cache_manager: None, + file_purger, + indexer_builder: builder, + request_sender: tx, + index_options: IndexOptions::default(), + result_senders: Vec::new(), + }; + if !with_builtin { + // A reuse-only build must not open even the Parquet footer. + // Keep the file identity published, but make footer reads fail. + let path = task + .file + .file_path(env.access_layer.table_dir(), env.access_layer.path_type()); + env.access_layer + .object_store() + .write(&path, Bytes::from_static(b"not a parquet file")) + .await + .unwrap(); + } + // The reused creator rejects row updates, even when built-in creators need a scan. + task.index_build(version).await.unwrap(); + let published = manifest_ctx.manifest().await.files[&file_meta.file_id].clone(); + assert!(published.available_indexes.contains(&IndexType::HllIndex)); + assert!(published.index_file_size > 0); + let reader = env + .access_layer + .build_puffin_manager() + .reader(&RegionIndexId::new( + RegionFileId::new(metadata.region_id, file_meta.file_id), + published.index_version, + )) + .await + .unwrap(); + reader.blob("test-sketch").await.unwrap(); + if with_builtin { + assert!( + published + .available_indexes + .contains(&IndexType::InvertedIndex) + ); + let blob = reader.blob(inverted_index::INDEX_BLOB_TYPE).await.unwrap(); + let index_metadata = + index::inverted_index::format::reader::InvertedIndexBlobReader::new( + blob.reader().await.unwrap(), + ) + .metadata(None) + .await + .unwrap(); + assert_eq!(index_metadata.total_row_count, file_meta.num_rows); + } else { + assert_eq!( + published.available_indexes.as_slice(), + &[IndexType::HllIndex] + ); + } + } + } + + #[tokio::test] + async fn test_rebuild_failure_preserves_published_indexes() { + for (failure, old_hll, legacy, with_builtin) in [ + (Some(ProviderFailure::Plan), true, false, true), + (Some(ProviderFailure::Create), true, false, true), + (Some(ProviderFailure::UpdateFlat), true, false, true), + (Some(ProviderFailure::Finish), true, false, true), + (Some(ProviderFailure::Budget), true, false, true), + (Some(ProviderFailure::Budget), false, false, true), + (Some(ProviderFailure::SkipCreate), true, false, true), + (Some(ProviderFailure::SkipCreate), true, false, false), + (Some(ProviderFailure::SkipCreate), true, true, true), + (Some(ProviderFailure::SkipCreate), false, false, true), + (Some(ProviderFailure::EmptyFinish), true, false, true), + (Some(ProviderFailure::PartialFinish), true, false, true), + (Some(ProviderFailure::None), true, false, true), + (None, true, false, true), + (None, false, false, true), + ] { + let env = SchedulerEnv::new().await; + let mut metadata = sst_region_metadata(); + if !with_builtin { + for column in &mut metadata.column_metadatas { + column.column_schema.set_inverted_index(false); + column.column_schema.unset_skipping_options().unwrap(); + } + } + let metadata = Arc::new(metadata); + let region_id = metadata.region_id; + let manifest_ctx = env.mock_manifest_context(metadata.clone()).await; + let file_purger = Arc::new(NoopFilePurger {}); + let info = mock_sst_file(metadata.clone(), &env, IndexBuildMode::Async).await; + let initial = FileMeta { + region_id, + file_id: info.file_id, + file_size: info.file_size, + max_row_group_uncompressed_size: info.max_row_group_uncompressed_size, + num_rows: info.num_rows as u64, + num_row_groups: info.num_row_groups, + ..Default::default() + }; + seed_manifest_file(&manifest_ctx, &initial).await; + let version = mock_version_control( + metadata.clone(), + file_purger.clone(), + HashMap::from([(initial.file_id, initial.clone())]), + ) + .await; + let mut builder = mock_indexer_builder(metadata.clone(), &env).await; + Arc::make_mut(&mut builder).build_type = IndexBuildType::Manual; + if old_hll { + Arc::make_mut(&mut Arc::make_mut(&mut builder).registry) + .register(Arc::new(FailingProvider( + if matches!( + failure, + Some(ProviderFailure::PartialFinish | ProviderFailure::None) + ) { + ProviderFailure::CompletePair + } else { + ProviderFailure::None + }, + ))) + .unwrap(); + } + let (tx, _rx) = mpsc::channel(4); + let mut task = IndexBuildTask { + region_id, + file: FileHandle::new(initial.clone(), file_purger.clone()), + target_region_metadata: metadata.clone(), + source: IndexBuildSource::new(initial.clone(), metadata.schema_version), + reason: IndexBuildType::Manual, + access_layer: env.access_layer.clone(), + listener: WorkerListener::default(), + manifest_ctx: manifest_ctx.clone(), + write_cache: None, + cache_manager: None, + file_purger: file_purger.clone(), + indexer_builder: builder, + request_sender: tx, + index_options: IndexOptions::default(), + result_senders: Vec::new(), + }; + // First publish real built-in blobs and the test provider's HLL blob. + task.index_build(version).await.unwrap(); + let mut old = manifest_ctx.manifest().await.files[&initial.file_id].clone(); + if legacy { + let mut legacy_meta = old.as_ref().clone(); + for column in &mut legacy_meta.indexes { + column + .created_indexes + .retain(|kind| *kind != IndexType::HllIndex); + } + old = legacy_meta.into(); + seed_manifest_file(&manifest_ctx, old.as_ref()).await; + } + assert_eq!( + old.available_indexes.contains(&IndexType::HllIndex), + old_hll + ); + assert_eq!( + old.available_indexes + .iter() + .any(|kind| *kind != IndexType::HllIndex), + with_builtin, + ); + let old_path = location::index_file_path( + env.access_layer.table_dir(), + RegionIndexId::new(RegionFileId::new(region_id, old.file_id), old.index_version), + env.access_layer.path_type(), + ); + let old_bytes = env + .access_layer + .object_store() + .read(&old_path) + .await + .unwrap() + .to_bytes(); + assert!(!old_bytes.is_empty()); + let version = mock_version_control( + metadata.clone(), + file_purger.clone(), + HashMap::from([(old.file_id, old.as_ref().clone())]), + ) + .await; + let mut builder = mock_indexer_builder(metadata.clone(), &env).await; + Arc::make_mut(&mut builder).build_type = IndexBuildType::Manual; + if let Some(failure) = failure { + Arc::make_mut(&mut Arc::make_mut(&mut builder).registry) + .register(Arc::new(FailingProvider(failure))) + .unwrap(); + } + if failure.is_none() && !old_hll { + // Newly configured sketches must also fail before replacing the + // built-in indexes when their provider is unavailable. + Arc::make_mut(&mut task.target_region_metadata).column_metadatas[0] + .column_schema + .mut_metadata() + .insert( + datatypes::schema::HLL_KEY.into(), + r#"{"precision":10}"#.into(), + ); + } + if failure == Some(ProviderFailure::None) { + // Keep only the first column configured; the second old HLL is obsolete. + Arc::make_mut(&mut task.target_region_metadata).column_metadatas[0] + .column_schema + .mut_metadata() + .insert( + datatypes::schema::HLL_KEY.into(), + r#"{"precision":10}"#.into(), + ); + Arc::make_mut(&mut builder).metadata = task.target_region_metadata.clone(); + } + task.file = FileHandle::new(old.clone(), file_purger); + task.source = IndexBuildSource::new(old.as_ref().clone(), metadata.schema_version); + task.indexer_builder = builder; + let result = task.index_build(version).await; + let published = manifest_ctx.manifest().await.files[&old.file_id].clone(); + if !with_builtin { + // No creator means no publication; the requested plan is not a removal plan. + assert!(matches!( + result.unwrap(), + IndexBuildReport::Done(IndexBuildOutcome::Aborted(_)) + )); + assert_eq!(old, published); + } else if failure == Some(ProviderFailure::None) { + result.unwrap(); + assert_eq!(published.index_version, old.index_version + 1); + let hll_columns = published + .indexes + .iter() + .filter(|column| column.created_indexes.contains(&IndexType::HllIndex)) + .map(|column| column.column_id) + .collect::>(); + assert_eq!(hll_columns, vec![0]); + } else if (old_hll && failure.is_some()) || (failure.is_none() && !old_hll) { + assert!(result.is_err(), "maintenance must fail for {failure:?}"); + assert_eq!( + old, published, + "failed {failure:?} must not change manifest" + ); + } else { + result.unwrap(); + assert_eq!(published.index_version, old.index_version + 1); + assert!(!published.available_indexes.contains(&IndexType::HllIndex)); + assert!( + published + .indexes + .iter() + .all(|column| !column.created_indexes.contains(&IndexType::HllIndex)) + ); + let expected: Vec<_> = old + .available_indexes + .iter() + .copied() + .filter(|kind| *kind != IndexType::HllIndex) + .collect(); + assert_eq!(published.available_indexes.as_slice(), expected.as_slice()); + assert!(published.index_file_size > 0); + } + // NoopFilePurger keeps the historical generation available for byte comparison. + assert_eq!( + old_bytes, + env.access_layer + .object_store() + .read(&old_path) + .await + .unwrap() + .to_bytes() + ); + } + } + #[tokio::test] async fn test_index_build_task_no_index() { + for remove_sketches in [false, true] { + check_empty_index_build(remove_sketches, true).await; + if remove_sketches { + check_empty_index_build(true, false).await; + } + } + } + + #[derive(Debug)] + struct RemoveTestIndex; + + impl handler::IndexKindHandler for RemoveTestIndex { + fn validate( + &self, + _context: &handler::PlanContext<'_>, + ) -> std::result::Result<(), common_error::ext::BoxedError> { + Ok(()) + } + + fn kinds(&self) -> &[kind::IndexKind] { + &[kind::IndexKind::Extension(kind::ExtensionIndexKind::Hll)] + } + + fn plan( + &self, + context: &handler::PlanContext<'_>, + ) -> std::result::Result< + Option>, + common_error::ext::BoxedError, + > { + Ok(context + .existing_indexes + .iter() + .any(|column| { + column + .created_indexes + .contains(&crate::sst::file::IndexType::HllIndex) + }) + .then(|| Arc::new(Self) as Arc)) + } + } + + #[async_trait::async_trait] + impl handler::PlannedIndex for RemoveTestIndex { + fn kinds(&self) -> &[kind::IndexKind] { + handler::IndexKindHandler::kinds(self) + } + + fn entries(&self) -> &[handler::PlanEntry] { + &[] + } + + async fn build( + &self, + _: &handler::BuildContext<'_>, + ) -> std::result::Result< + Option>, + common_error::ext::BoxedError, + > { + Ok(None) + } + + fn is_current(&self, file: &FileMeta, _: &handler::PlanContext<'_>) -> bool { + !file.indexes.iter().any(|column| { + column + .created_indexes + .contains(&crate::sst::file::IndexType::HllIndex) + }) + } + } + + async fn check_empty_index_build(remove_sketches: bool, registered: bool) { let env = SchedulerEnv::new().await; let mut scheduler = env.mock_index_build_scheduler(4); let mut metadata = sst_region_metadata(); @@ -3358,7 +4140,7 @@ mod tests { let manifest_ctx = env.mock_manifest_context(metadata.clone()).await; let file_purger = Arc::new(NoopFilePurger {}); let sst_info = mock_sst_file(metadata.clone(), &env, IndexBuildMode::Async).await; - let file_meta = FileMeta { + let mut file_meta = FileMeta { region_id, file_id: sst_info.file_id, file_size: sst_info.file_size, @@ -3368,13 +4150,47 @@ mod tests { num_row_groups: sst_info.num_row_groups, ..Default::default() }; + if remove_sketches { + file_meta + .indexes + .push(crate::sst::file::ColumnIndexMetadata { + column_id: metadata.column_metadatas[0].column_id, + created_indexes: smallvec::smallvec![crate::sst::file::IndexType::HllIndex], + fulltext_bloom_version: 0, + }); + file_meta.index_file_size = 123; + } seed_manifest_file(&manifest_ctx, &file_meta).await; let files = HashMap::from([(file_meta.file_id, file_meta.clone())]); let version_control = mock_version_control(metadata.clone(), file_purger.clone(), files).await; - let indexer_builder = mock_indexer_builder(metadata.clone(), &env).await; - + let mut indexer_builder = mock_indexer_builder(metadata.clone(), &env).await; let file = FileHandle::new(file_meta.clone(), file_purger.clone()); + if remove_sketches { + // A registered owner can remove its index after options are disabled. + let builder = Arc::make_mut(&mut indexer_builder); + if registered { + Arc::make_mut(&mut builder.registry) + .register(Arc::new(RemoveTestIndex)) + .unwrap(); + } + let plan = builder.registry.plan(&handler::PlanContext { + metadata: &metadata, + index_options: &builder.index_options, + build_type: IndexBuildType::SchemaChange, + existing_indexes: &file_meta.indexes, + }); + assert_eq!(!plan.is_empty(), registered); + assert!(plan.entries().next().is_none()); + builder.index_build_inputs = Some(build::IndexBuildInputs { + output_rows: None, + plan: Arc::new(plan), + inputs: vec![file.clone()].into(), + input_puffin_manager: builder.puffin_manager.clone(), + can_merge_inputs: false, + memory_limit: None, + }); + } // Create mock task. let (tx, mut rx) = mpsc::channel(4); @@ -3387,10 +4203,14 @@ mod tests { file_meta.clone(), version_control.current().version.metadata.schema_version, ), - reason: IndexBuildType::Flush, + reason: if registered { + IndexBuildType::SchemaChange + } else { + IndexBuildType::Manual + }, access_layer: env.access_layer.clone(), listener: WorkerListener::default(), - manifest_ctx, + manifest_ctx: manifest_ctx.clone(), write_cache: None, cache_manager: None, file_purger, @@ -3400,7 +4220,74 @@ mod tests { result_senders: vec![result_tx], }; - scheduler.schedule_build(&version_control, task).await; + if remove_sketches { + assert!(task.can_remove_all_indexes()); + for column_level in [false, true] { + let mut mixed = task.clone(); + if column_level { + mixed.source.file_meta.indexes[0] + .created_indexes + .push(IndexType::InvertedIndex); + } else { + mixed + .source + .file_meta + .available_indexes + .push(IndexType::InvertedIndex); + } + assert!(mixed.can_remove_all_indexes()); + } + } + + scheduler + .schedule_build(&version_control, task.clone()) + .await; + + if remove_sketches { + let finished = recv_index_build_finished(&mut rx).await; + assert!(finished.file_meta.indexes.is_empty()); + assert!(finished.file_meta.available_indexes.is_empty()); + assert_eq!(finished.file_meta.index_file_size, 0); + assert_eq!(finished.file_meta.index_version, 1); + assert!( + manifest_ctx.manifest().await.files[&file_meta.file_id] + .indexes + .is_empty() + ); + // Reconstruct the file from persisted metadata as reopening does, then enable + // an ordinary index. Its new Puffin must not reuse the historical version 0. + let persisted = serde_json::to_vec(&finished.file_meta).unwrap(); + let reopened: FileMeta = serde_json::from_slice(&persisted).unwrap(); + assert!(!reopened.exists_index()); + let target_metadata = Arc::new(sst_region_metadata()); + let reopened_version = mock_version_control( + target_metadata.clone(), + task.file_purger.clone(), + HashMap::from([(reopened.file_id, reopened.clone())]), + ) + .await; + let (tx, mut rx) = mpsc::channel(4); + let mut rebuild = task; + rebuild.file = FileHandle::new(reopened.clone(), rebuild.file_purger.clone()); + rebuild.source.file_meta = reopened; + rebuild.target_region_metadata = target_metadata.clone(); + rebuild.indexer_builder = mock_indexer_builder(target_metadata, &env).await; + rebuild.request_sender = tx; + let mut reopened_scheduler = env.mock_index_build_scheduler(4); + reopened_scheduler + .schedule_build(&reopened_version, rebuild) + .await; + let rebuilt = recv_index_build_finished(&mut rx).await; + assert!(rebuilt.file_meta.exists_index()); + assert_eq!(rebuilt.file_meta.index_version, 2); + let path = location::index_file_path( + env.access_layer.table_dir(), + RegionIndexId::new(RegionFileId::new(region_id, file_meta.file_id), 2), + env.access_layer.path_type(), + ); + assert!(env.access_layer.object_store().exists(&path).await.unwrap()); + return; + } // No index needs to be built, so the SST is not read. assert!(matches!( diff --git a/src/mito2/src/sst/index/build.rs b/src/mito2/src/sst/index/build.rs index 863aa84b7a4..180b1e26272 100644 --- a/src/mito2/src/sst/index/build.rs +++ b/src/mito2/src/sst/index/build.rs @@ -21,13 +21,13 @@ use crate::sst::index::puffin_manager::SstPuffinManager; use crate::sst::index::registry::IndexBuildPlan; /// An immutable plan with operation-scoped input files and output constraints. -/// Currently compaction and explicit rebuild supply these inputs; flush does not -/// inject extension handlers and builds only the existing built-in indexes. +/// Compaction and SST index rebuilds supply these inputs, including asynchronous +/// post-flush indexing. Synchronous memtable flushes have no persisted input files. #[derive(Clone)] pub struct IndexBuildInputs { /// Typed plans shared by output files of this operation. pub plan: Arc, - /// Pinned physical input files; flushes have no inputs. + /// Pinned physical input files. Post-flush indexing reads the newly written SST. pub inputs: Arc<[FileHandle]>, /// Reads persisted inputs even when output uses a local write cache. /// Input availability is determined by `inputs.is_empty()`, not this manager. diff --git a/src/mito2/src/sst/index/handler.rs b/src/mito2/src/sst/index/handler.rs index dba75c143ce..de9fba783a9 100644 --- a/src/mito2/src/sst/index/handler.rs +++ b/src/mito2/src/sst/index/handler.rs @@ -28,7 +28,7 @@ use store_api::storage::ColumnId; use crate::read::Batch; use crate::region::options::IndexOptions; -use crate::sst::file::{ColumnIndexMetadata, FileHandle, RegionIndexId}; +use crate::sst::file::{ColumnIndexMetadata, FileHandle, FileMeta, RegionIndexId}; use crate::sst::index::intermediate::IntermediateManager; use crate::sst::index::kind::IndexKind; use crate::sst::index::puffin_manager::{SstPuffinManager, SstPuffinWriter}; @@ -104,6 +104,11 @@ pub trait IndexKindHandler: Send + Sync + Debug { /// entirely built-in or entirely extension kinds. fn kinds(&self) -> &[IndexKind]; + /// Validates options at region creation independently of whether this lifecycle + /// event builds indexes. Implementations must not skip validation based on + /// `context.build_type`. + fn validate(&self, context: &PlanContext<'_>) -> Result<(), BoxedError>; + /// Prepares typed parameters. `None` means no work; an empty entry list may /// still request removal of obsolete descriptors during maintenance. fn plan(&self, context: &PlanContext<'_>) -> Result>, BoxedError>; @@ -124,6 +129,10 @@ pub trait PlannedIndex: Send + Sync + Debug { context: &BuildContext<'_>, ) -> Result>, BoxedError>; + /// Whether persisted entries satisfy this plan. + /// The context uses the same file's indexes as the planning input. + fn is_current(&self, file: &FileMeta, context: &PlanContext<'_>) -> bool; + /// Whether building this plan can reuse persisted input summaries. /// Row-only plans do not require checking input object existence. fn needs_input_reuse(&self) -> bool { diff --git a/src/mito2/src/sst/index/handler/builtin.rs b/src/mito2/src/sst/index/handler/builtin.rs index c814cb4b43b..9c561a5dcb1 100644 --- a/src/mito2/src/sst/index/handler/builtin.rs +++ b/src/mito2/src/sst/index/handler/builtin.rs @@ -24,6 +24,7 @@ use common_error::ext::BoxedError; use index::target::IndexTarget; use crate::config::{BloomFilterConfig, FulltextIndexConfig, InvertedIndexConfig}; +use crate::sst::file::FileMeta; use crate::sst::index::handler::builtin::bloom::BloomPlan; use crate::sst::index::handler::builtin::fulltext::FulltextPlan; use crate::sst::index::handler::builtin::inverted::InvertedPlan; @@ -47,6 +48,12 @@ impl IndexKindHandler for BuiltinIndexHandler { } } + fn validate(&self, _context: &PlanContext<'_>) -> Result<(), BoxedError> { + // Built-in options retain their existing schema/build-time validation. + // Planning here would make region creation reject inputs it previously accepted. + Ok(()) + } + fn plan(&self, context: &PlanContext<'_>) -> Result>, BoxedError> { match self { Self::Inverted(config) => InvertedPlan::plan(config, context) @@ -83,6 +90,11 @@ fn normalize_entries(entries: &mut Vec) { }); } +fn builtin_is_current(file: &FileMeta, context: &PlanContext<'_>) -> bool { + // Preserve the established schema/version policy, including its JSON rebuild scope. + file.is_index_consistent_with_region(&context.metadata.column_metadatas, context.index_options) +} + #[cfg(test)] mod tests { use super::*; @@ -90,6 +102,45 @@ mod tests { use crate::sst::index::IndexBuildType; use crate::test_util::sst_util; + #[test] + fn test_builtin_validation_preserves_build_time_option_errors() { + for (handler, key) in [ + ( + BuiltinIndexHandler::Fulltext(FulltextIndexConfig::default()), + datatypes::schema::FULLTEXT_KEY, + ), + ( + BuiltinIndexHandler::Bloom(BloomFilterConfig::default()), + datatypes::schema::SKIPPING_INDEX_KEY, + ), + ] { + let mut metadata = sst_util::sst_region_metadata(); + let column = metadata + .column_metadatas + .iter_mut() + .find(|column| column.semantic_type == api::v1::SemanticType::Field) + .unwrap(); + column.column_schema = + column + .column_schema + .clone() + .with_metadata(std::collections::HashMap::from([( + key.to_string(), + "invalid json".to_string(), + )])); + let metadata = Arc::new(metadata); + let options = IndexOptions::default(); + let context = PlanContext { + metadata: &metadata, + index_options: &options, + build_type: IndexBuildType::Flush, + existing_indexes: &[], + }; + assert!(handler.validate(&context).is_ok()); + assert!(handler.plan(&context).is_err()); + } + } + #[test] fn test_builtin_planning_reports_invalid_options() { for (handler, key) in [ diff --git a/src/mito2/src/sst/index/handler/builtin/bloom.rs b/src/mito2/src/sst/index/handler/builtin/bloom.rs index aff50955bb8..18f9867337b 100644 --- a/src/mito2/src/sst/index/handler/builtin/bloom.rs +++ b/src/mito2/src/sst/index/handler/builtin/bloom.rs @@ -24,8 +24,11 @@ use index::target::IndexTarget; use crate::config::BloomFilterConfig; use crate::read::Batch; +use crate::sst::file::FileMeta; use crate::sst::index::bloom_filter::creator::BloomFilterIndexer; -use crate::sst::index::handler::builtin::{column_target_id, normalize_entries, target_column_id}; +use crate::sst::index::handler::builtin::{ + builtin_is_current, column_target_id, normalize_entries, target_column_id, +}; use crate::sst::index::handler::{ BuildContext, IndexCreator, PlanContext, PlanEntry, PlannedIndex, }; @@ -105,6 +108,10 @@ impl PlannedIndex for BloomPlan { .map(|creator| creator.map(|c| Box::new(c) as Box)) .map_err(BoxedError::new) } + + fn is_current(&self, file: &FileMeta, context: &PlanContext<'_>) -> bool { + builtin_is_current(file, context) + } } #[async_trait] diff --git a/src/mito2/src/sst/index/handler/builtin/fulltext.rs b/src/mito2/src/sst/index/handler/builtin/fulltext.rs index 4a287ef4017..5b82a73e662 100644 --- a/src/mito2/src/sst/index/handler/builtin/fulltext.rs +++ b/src/mito2/src/sst/index/handler/builtin/fulltext.rs @@ -24,9 +24,12 @@ use index::target::IndexTarget; use crate::config::FulltextIndexConfig; use crate::read::Batch; +use crate::sst::file::FileMeta; use crate::sst::index::fulltext_index; use crate::sst::index::fulltext_index::creator::{FulltextIndexer, FulltextTarget}; -use crate::sst::index::handler::builtin::{column_target_id, normalize_entries, target_column_id}; +use crate::sst::index::handler::builtin::{ + builtin_is_current, column_target_id, normalize_entries, target_column_id, +}; use crate::sst::index::handler::{ BuildContext, IndexCreator, PlanContext, PlanEntry, PlannedIndex, }; @@ -118,6 +121,10 @@ impl PlannedIndex for FulltextPlan { .map(|creator| creator.map(|c| Box::new(c) as Box)) .map_err(BoxedError::new) } + + fn is_current(&self, file: &FileMeta, context: &PlanContext<'_>) -> bool { + builtin_is_current(file, context) + } } #[async_trait] diff --git a/src/mito2/src/sst/index/handler/builtin/inverted.rs b/src/mito2/src/sst/index/handler/builtin/inverted.rs index 353afd5cff9..44010b629ba 100644 --- a/src/mito2/src/sst/index/handler/builtin/inverted.rs +++ b/src/mito2/src/sst/index/handler/builtin/inverted.rs @@ -27,7 +27,10 @@ use index::target::IndexTarget; use crate::config::InvertedIndexConfig; use crate::read::Batch; -use crate::sst::index::handler::builtin::{column_target_id, normalize_entries, target_column_id}; +use crate::sst::file::FileMeta; +use crate::sst::index::handler::builtin::{ + builtin_is_current, column_target_id, normalize_entries, target_column_id, +}; use crate::sst::index::handler::{ BuildContext, IndexCreator, PlanContext, PlanEntry, PlannedIndex, }; @@ -131,6 +134,10 @@ impl PlannedIndex for InvertedPlan { self.targets.clone(), )))) } + + fn is_current(&self, file: &FileMeta, context: &PlanContext<'_>) -> bool { + builtin_is_current(file, context) + } } fn json_inverted_targets(context: &PlanContext<'_>) -> Vec { diff --git a/src/mito2/src/sst/index/indexer/abort.rs b/src/mito2/src/sst/index/indexer/abort.rs index 0bc659666b1..8bb26b4445c 100644 --- a/src/mito2/src/sst/index/indexer/abort.rs +++ b/src/mito2/src/sst/index/indexer/abort.rs @@ -19,6 +19,20 @@ use crate::sst::file::{RegionFileId, RegionIndexId}; use crate::sst::index::Indexer; impl Indexer { + /// Aborts builtin creators while retaining synchronous extension creators. + pub(crate) async fn abort_builtin_creators(&mut self) { + self.dense_pk_decoder = None; + let mut position = 0; + while position < self.creators.len() { + if self.creators[position].is_builtin() { + self.abort_creator(position).await; + } else { + position += 1; + } + } + self.flush_mem_metrics(); + } + pub(crate) async fn abort_creator(&mut self, position: usize) { let mut active = self.creators.remove(position); if let Err(err) = active.creator.abort().await { diff --git a/src/mito2/src/sst/index/primary_key.rs b/src/mito2/src/sst/index/primary_key.rs index 4724ae44e6f..45ad95d7d78 100644 --- a/src/mito2/src/sst/index/primary_key.rs +++ b/src/mito2/src/sst/index/primary_key.rs @@ -21,13 +21,14 @@ use crate::sst::parquet::flat_format::primary_key_column_index; use crate::sst::parquet::format::PrimaryKeyArray; /// Iterates consecutive dictionary-key runs, preserving their row order without decoding. -pub(crate) struct PrimaryKeyRuns<'a> { +pub struct PrimaryKeyRuns<'a> { keys: &'a [u32], values: &'a BinaryArray, } impl<'a> PrimaryKeyRuns<'a> { - pub(crate) fn try_new(batch: &'a RecordBatch) -> Result { + /// Borrows the encoded primary keys of a flat batch without decoding values. + pub fn try_new(batch: &'a RecordBatch) -> Result { let pk = batch .column(primary_key_column_index(batch.num_columns())) .as_any() diff --git a/src/mito2/src/sst/index/registry.rs b/src/mito2/src/sst/index/registry.rs index 7b9da2e51dd..fb9bcb07311 100644 --- a/src/mito2/src/sst/index/registry.rs +++ b/src/mito2/src/sst/index/registry.rs @@ -19,11 +19,11 @@ use std::sync::Arc; use common_error::ext::BoxedError; use common_telemetry::warn; -use snafu::IntoError; +use snafu::{IntoError, ResultExt}; use store_api::metadata::RegionMetadataRef; use store_api::storage::RegionId; -use crate::config::{BloomFilterConfig, FulltextIndexConfig, InvertedIndexConfig}; +use crate::config::{BloomFilterConfig, FulltextIndexConfig, InvertedIndexConfig, MitoConfig}; use crate::error::{Error, ExternalSnafu, InvalidConfigSnafu}; use crate::metrics::{INDEX_CREATE_DISCARDED_TOTAL, INDEX_DISCARD_ADMISSION_REJECTED}; use crate::sst::file::{FileMeta, IndexType}; @@ -59,6 +59,22 @@ impl IndexRegistry { } } + /// Assembles the configured built-ins and the injected provider. + pub(crate) fn from_config( + config: &MitoConfig, + provider: Option, + ) -> crate::error::Result { + Self::new( + config.inverted_index.clone(), + config.fulltext_index.clone(), + config.bloom_filter_index.clone(), + ) + .with_provider(provider) + .with_context(|_| ExternalSnafu { + context: "registering index handlers".to_string(), + }) + } + /// Adds the embedding application's handlers after the built-in configuration. pub fn with_provider( mut self, @@ -72,6 +88,16 @@ impl IndexRegistry { Ok(self) } + /// Validates required providers and their options before creating a new region. + /// Built-in handlers preserve their existing schema/build-time validation. + pub fn validate(&self, context: &PlanContext<'_>) -> Result<(), BoxedError> { + self.validate_schema_kinds(context.metadata)?; + for handler in &self.handlers { + handler.validate(context)?; + } + Ok(()) + } + /// Installs a handler, rejecting empty or overlapping kind ownership. pub fn register(&mut self, handler: Arc) -> Result<(), BoxedError> { self.validate_registration(handler.kinds())?; @@ -89,6 +115,57 @@ impl IndexRegistry { files: impl IntoIterator, ) -> Result<(), BoxedError> { self.validate_schema_kinds(metadata)?; + self.validate_file_kinds(files) + } + + /// Reports unavailable sketches without blocking compaction after a downgrade. + /// Logs each missing kind at most once for this input group. + pub(crate) fn warn_missing_compaction_handlers<'a>( + &self, + metadata: &RegionMetadataRef, + files: impl IntoIterator, + ) { + let missing = ExtensionIndexKind::ALL + .map(|kind| !self.has_handler(IndexKind::Extension(kind).index_type())); + if !missing.iter().any(|missing| *missing) { + return; + } + let mut requested = ExtensionIndexKind::ALL.map(|kind| { + metadata.column_metadatas.iter().any(|column| { + column + .column_schema + .metadata() + .contains_key(kind.required_metadata_key()) + }) + }); + for file in files { + for (position, kind) in ExtensionIndexKind::ALL.iter().enumerate() { + if missing[position] && !requested[position] { + let index_type = IndexKind::Extension(*kind).index_type(); + requested[position] = file.available_indexes.contains(&index_type) + || file + .indexes + .iter() + .any(|column| column.created_indexes.contains(&index_type)); + } + } + } + for (position, kind) in ExtensionIndexKind::ALL.iter().enumerate() { + if missing[position] && requested[position] { + warn!( + "Compacting without unavailable sketch provider, region_id: {}, kind: {}; output will omit this sketch", + metadata.region_id, + kind.as_str() + ); + } + } + } + + /// Rejects unavailable implementations for indexes being replaced. + fn validate_file_kinds<'a>( + &self, + files: impl IntoIterator, + ) -> Result<(), BoxedError> { for file in files { for kind in file.available_indexes.iter().chain( file.indexes @@ -223,7 +300,10 @@ impl IndexRegistry { }); } - fn validate_schema_kinds(&self, metadata: &RegionMetadataRef) -> Result<(), BoxedError> { + pub(crate) fn validate_schema_kinds( + &self, + metadata: &RegionMetadataRef, + ) -> Result<(), BoxedError> { for column in &metadata.column_metadatas { let schema = &column.column_schema; for kind in ExtensionIndexKind::ALL { @@ -270,6 +350,11 @@ impl IndexBuildPlan { &self.planned } + /// Whether no handler requested work, including metadata-only maintenance. + pub fn is_empty(&self) -> bool { + self.planned.is_empty() + } + /// All requested column formats. pub fn entries(&self) -> impl Iterator { self.planned.iter().flat_map(|plan| plan.entries()) @@ -301,6 +386,51 @@ impl IndexBuildPlan { self.planned .retain(|plan| plan.kinds().iter().all(|kind| kind.is_builtin())); } + + /// Whether every handler considers the published file current. + pub fn is_current(&self, file: &FileMeta, context: &PlanContext<'_>) -> bool { + let has_removed_extensions = matches!( + context.build_type, + IndexBuildType::Manual | IndexBuildType::SchemaChange + ) && ExtensionIndexKind::ALL.iter().any(|kind| { + let index_type = IndexKind::Extension(*kind).index_type(); + let configured = |column_id| { + context + .metadata + .column_by_id(column_id) + .is_some_and(|column| { + column + .column_schema + .metadata() + .contains_key(kind.required_metadata_key()) + }) + }; + let mut has_column_descriptor = false; + for column in &file.indexes { + if column.created_indexes.contains(&index_type) { + has_column_descriptor = true; + if !configured(column.column_id) { + return true; + } + } + } + // Legacy file-level descriptors cannot identify individual columns. + !has_column_descriptor + && file.available_indexes.contains(&index_type) + && !context.metadata.column_metadatas.iter().any(|column| { + column + .column_schema + .metadata() + .contains_key(kind.required_metadata_key()) + }) + }); + self.failure.is_none() + && !has_removed_extensions + && self + .planned + .iter() + .all(|plan| plan.is_current(file, context)) + } } #[cfg(test)] @@ -315,6 +445,11 @@ mod tests { fn kinds(&self) -> &[IndexKind] { &self.0 } + + fn validate(&self, _: &PlanContext<'_>) -> Result<(), BoxedError> { + Ok(()) + } + fn plan(&self, _: &PlanContext<'_>) -> Result>, BoxedError> { Ok(None) } @@ -340,6 +475,10 @@ mod tests { ) -> Result>, BoxedError> { unreachable!("admission must not construct creators") } + + fn is_current(&self, _: &FileMeta, _: &PlanContext<'_>) -> bool { + false + } } #[test] @@ -427,6 +566,10 @@ mod tests { &self.owned } + fn validate(&self, _: &PlanContext<'_>) -> Result<(), BoxedError> { + Ok(()) + } + fn plan(&self, _: &PlanContext<'_>) -> Result>, BoxedError> { Ok(Some(self.plan.clone())) } diff --git a/src/mito2/src/sst/parquet/index_writer.rs b/src/mito2/src/sst/parquet/index_writer.rs index 6d6414b9cd2..24da3f1a9b4 100644 --- a/src/mito2/src/sst/parquet/index_writer.rs +++ b/src/mito2/src/sst/parquet/index_writer.rs @@ -12,15 +12,11 @@ // See the License for the specific language governing permissions and // limitations under the License. -use bytes::Bytes; use datatypes::arrow::datatypes::SchemaRef; use datatypes::arrow::record_batch::RecordBatch; -use futures::future::BoxFuture; -use object_store::{ObjectStore, Writer}; +use object_store::ObjectStore; use parquet::arrow::AsyncArrowWriter; -use parquet::arrow::async_writer::AsyncFileWriter; use parquet::basic::{Compression, Encoding, ZstdLevel}; -use parquet::errors::ParquetError; use parquet::file::metadata::KeyValue; use parquet::file::properties::WriterProperties; use snafu::{OptionExt, ResultExt}; @@ -29,55 +25,9 @@ use crate::access_layer::TempFileCleaner; use crate::error::{OpenDalSnafu, Result, UnexpectedSnafu, WriteParquetSnafu}; use crate::sst::{DEFAULT_WRITE_BUFFER_SIZE, DEFAULT_WRITE_CONCURRENCY}; -type ArrowWriter = AsyncArrowWriter; +use crate::sst::parquet::writer::ObjectStoreWriter; -/// Bridges an OpenDAL [`Writer`] with Parquet's [`AsyncFileWriter`] and tracks -/// the number of bytes successfully submitted to the object store. -struct AsyncWriter { - inner: Writer, - output_bytes: u64, -} - -impl AsyncWriter { - fn new(inner: Writer) -> Self { - Self { - inner, - output_bytes: 0, - } - } - - fn output_bytes(&self) -> u64 { - self.output_bytes - } - - fn into_inner(self) -> Writer { - self.inner - } -} - -impl AsyncFileWriter for AsyncWriter { - fn write(&mut self, bytes: Bytes) -> BoxFuture<'_, parquet::errors::Result<()>> { - Box::pin(async move { - let len = bytes.len() as u64; - self.inner - .write(bytes) - .await - .map_err(|error| ParquetError::External(Box::new(error)))?; - self.output_bytes += len; - Ok(()) - }) - } - - fn complete(&mut self) -> BoxFuture<'_, parquet::errors::Result<()>> { - Box::pin(async move { - self.inner - .close() - .await - .map(|_| ()) - .map_err(|error| ParquetError::External(Box::new(error))) - }) - } -} +type ArrowWriter = AsyncArrowWriter; /// Shared Parquet output and cleanup lifecycle for index writers. pub(crate) struct ParquetIndexWriter { @@ -112,9 +62,12 @@ impl ParquetIndexWriter { .set_statistics_truncate_length(None) .set_key_value_metadata(key_value_metadata) .build(); - let writer = - AsyncArrowWriter::try_new(AsyncWriter::new(output), schema.clone(), Some(properties)) - .context(WriteParquetSnafu)?; + let writer = AsyncArrowWriter::try_new( + ObjectStoreWriter::new(output, DEFAULT_WRITE_BUFFER_SIZE.as_bytes() as usize, None), + schema.clone(), + Some(properties), + ) + .context(WriteParquetSnafu)?; Ok(Self { name, diff --git a/src/mito2/src/sst/parquet/parallel_writer.rs b/src/mito2/src/sst/parquet/parallel_writer.rs index d257574cb79..d0caf95285c 100644 --- a/src/mito2/src/sst/parquet/parallel_writer.rs +++ b/src/mito2/src/sst/parquet/parallel_writer.rs @@ -19,6 +19,7 @@ use std::sync::Arc; use std::time::{Duration, Instant}; use bytes::Bytes; +use common_base::cancellation::Cancelled; use common_runtime::JoinHandle; use datatypes::arrow::datatypes::SchemaRef; use datatypes::arrow::record_batch::RecordBatch; @@ -31,6 +32,7 @@ use parquet::errors::{ParquetError, Result}; use parquet::file::metadata::ParquetMetaData; use parquet::file::properties::WriterProperties; use parquet::file::writer::SerializedFileWriter; +use tokio_util::sync::CancellationToken; /// Runtime whose blocking pool encodes the columns of a writer. #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] @@ -90,6 +92,7 @@ pub struct ParallelArrowWriter { /// Tasks encoding the previous row group. encoding: Vec>>, num_row_groups: usize, + cancellation: Option, } impl ParallelArrowWriter { @@ -137,13 +140,20 @@ impl ParallelArrowWriter { buffered_rows: 0, encoding: Vec::new(), num_row_groups: 0, + cancellation: None, }) } + pub(crate) fn with_cancellation(mut self, cancellation: Option) -> Self { + self.cancellation = cancellation; + self + } + /// Buffers `batch`, starting to encode each row group once it is full. pub async fn write(&mut self, batch: &RecordBatch) -> Result<()> { let mut offset = 0; while offset < batch.num_rows() { + check_cancelled(self.cancellation.as_ref())?; let len = (self.max_row_group_rows - self.buffered_rows).min(batch.num_rows() - offset); self.buffered.push(batch.slice(offset, len)); self.buffered_rows += len; @@ -165,6 +175,11 @@ impl ParallelArrowWriter { /// Writes the remaining rows and the footer, then completes the async writer. pub async fn close(mut self) -> Result { + self.finish().await + } + + /// Finalizes the file while retaining the upload for abort if it fails. + pub(crate) async fn finish(&mut self) -> Result { self.flush().await?; let metadata = self.file_writer.finish()?; self.write_buffered_bytes().await?; @@ -173,9 +188,10 @@ impl ParallelArrowWriter { } /// Discards buffered input and waits for encoders without writing a failed SST. - pub(crate) async fn abort(mut self) { + pub(crate) async fn abort(mut self) -> W { self.buffered.clear(); abort_encoding_tasks(&mut self.encoding).await; + self.async_writer } /// Installs controlled tasks to test SST write-error cleanup independently of codec timing. @@ -191,6 +207,7 @@ impl ParallelArrowWriter { /// Starts encoding the buffered rows once the previous row group is written. async fn encode_buffered(&mut self) -> Result<()> { self.finish_encoding().await?; + check_cancelled(self.cancellation.as_ref())?; let batches: Arc<[RecordBatch]> = mem::take(&mut self.buffered).into(); self.buffered_rows = 0; @@ -209,8 +226,9 @@ impl ParallelArrowWriter { .map(|fields| { let batches = batches.clone(); let schema = self.arrow_schema.clone(); + let cancellation = self.cancellation.clone(); self.runtime - .spawn(move || encode_fields(&schema, &batches, fields)) + .spawn(move || encode_fields(&schema, &batches, fields, cancellation.as_ref())) }) .collect(); Ok(()) @@ -301,17 +319,26 @@ fn assign_fields( .collect() } +fn check_cancelled(cancellation: Option<&CancellationToken>) -> Result<()> { + if cancellation.is_some_and(CancellationToken::is_cancelled) { + return Err(ParquetError::External(Box::new(Cancelled))); + } + Ok(()) +} + /// Encodes `fields` of all `batches` and closes their column writers. fn encode_fields( schema: &SchemaRef, batches: &[RecordBatch], fields: Vec, + cancellation: Option<&CancellationToken>, ) -> Result { let mut chunks = Vec::new(); let mut costs = Vec::with_capacity(fields.len()); for (field, mut writers) in fields { let start = Instant::now(); for batch in batches { + check_cancelled(cancellation)?; let leaves = compute_leaves(schema.field(field), batch.column(field))?; if leaves.len() != writers.len() { return Err(ParquetError::General(format!( @@ -322,10 +349,12 @@ fn encode_fields( ))); } for (leaf, (_, writer)) in leaves.iter().zip(writers.iter_mut()) { + check_cancelled(cancellation)?; writer.write(leaf)?; } } for (leaf, writer) in writers { + check_cancelled(cancellation)?; chunks.push((leaf, writer.close()?)); } costs.push((field, start.elapsed())); @@ -534,8 +563,12 @@ mod tests { let running = runtime.spawn_blocking(move || { started_tx.send(()).unwrap(); release_rx.blocking_recv().unwrap(); - let _encoded = - encode_fields(&schema(), &running_batches, vec![(0, vec![(0, column)])])?; + let _encoded = encode_fields( + &schema(), + &running_batches, + vec![(0, vec![(0, column)])], + None, + )?; Err(ParquetError::General("later encoding failure".to_string())) }); // With one blocking thread, this also proves the first task has ended. diff --git a/src/mito2/src/sst/parquet/writer.rs b/src/mito2/src/sst/parquet/writer.rs index 3b4c02b3080..29827704ee2 100644 --- a/src/mito2/src/sst/parquet/writer.rs +++ b/src/mito2/src/sst/parquet/writer.rs @@ -15,15 +15,15 @@ //! Parquet writer. use std::collections::HashMap; +use std::error::Error as StdError; use std::future::Future; use std::mem; -use std::pin::Pin; use std::sync::Arc; use std::sync::atomic::{AtomicUsize, Ordering}; -use std::task::{Context, Poll}; use std::time::Instant; use bytes::Bytes; +use common_base::cancellation::Cancelled; use common_telemetry::debug; use common_time::Timestamp; use datatypes::arrow::array::{ @@ -34,28 +34,29 @@ use datatypes::arrow::compute::{max, min}; use datatypes::arrow::datatypes::{DataType, SchemaRef, TimeUnit}; use datatypes::arrow::record_batch::RecordBatch; use datatypes::extension::json::is_json2_extension_type; -use object_store::{FuturesAsyncWriter, ObjectStore}; +use futures::future::BoxFuture; +use object_store::{ObjectStore, Writer}; use parquet::arrow::AsyncArrowWriter; use parquet::arrow::async_writer::AsyncFileWriter; use parquet::basic::{Compression, Encoding, ZstdLevel}; +use parquet::errors::ParquetError; use parquet::file::metadata::{FileMetaData, KeyValue, ParquetMetaData}; use parquet::file::properties::WriterProperties; use smallvec::smallvec; -use snafu::{OptionExt, ResultExt, ensure}; +use snafu::{IntoError, OptionExt, ResultExt, ensure}; use store_api::metadata::RegionMetadataRef; use store_api::storage::{FileId, SequenceNumber}; -use tokio::io::AsyncWrite; -use tokio_util::compat::{Compat, FuturesAsyncWriteCompatExt}; +use tokio_util::sync::CancellationToken; use crate::access_layer::{FilePathProvider, Metrics, SstInfoArray, TempFileCleaner}; use crate::config::{IndexBuildMode, IndexConfig}; use crate::error::{ - InvalidMetadataSnafu, InvalidRecordBatchSnafu, OpenDalSnafu, Result, UnexpectedSnafu, + Error, InvalidMetadataSnafu, InvalidRecordBatchSnafu, OpenDalSnafu, Result, UnexpectedSnafu, WriteParquetSnafu, }; use crate::read::FlatSource; use crate::sst::file::RegionFileId; -use crate::sst::index::{IndexOutput, Indexer, IndexerBuilder}; +use crate::sst::index::{Indexer, IndexerBuilder}; use crate::sst::parquet::flat_format::{ FlatWriteFormat, primary_key_column_index, time_index_column_index, }; @@ -65,6 +66,7 @@ use crate::sst::parquet::{ COLUMN_INDEX_TRUNCATE_LENGTH, PARQUET_METADATA_KEY, SstInfo, WriteOptions, apply_column_compression, apply_float_field_encoding, apply_internal_column_encoding, }; +use crate::sst::upload::{self, UploadError}; use crate::sst::{ DEFAULT_WRITE_CONCURRENCY, FlatSchemaOptions, SeriesEstimator, maybe_wrap_schema, }; @@ -179,16 +181,17 @@ impl SstArrowWriter { } } - async fn close(self) -> parquet::errors::Result { + async fn finish(&mut self) -> parquet::errors::Result { match self { - SstArrowWriter::Serial(writer) => writer.close().await, - SstArrowWriter::Parallel(writer) => writer.close().await, + SstArrowWriter::Serial(writer) => writer.finish().await, + SstArrowWriter::Parallel(writer) => writer.finish().await, } } - async fn abort(self) { - if let SstArrowWriter::Parallel(writer) = self { - writer.abort().await; + async fn abort(self) -> W { + match self { + SstArrowWriter::Serial(writer) => writer.into_inner(), + SstArrowWriter::Parallel(writer) => writer.abort().await, } } } @@ -248,28 +251,105 @@ pub struct ParquetWriter<'a, F: WriterFactory, I: IndexerBuilder, P: FilePathPro /// Write metrics metrics: &'a mut Metrics, write_guard: Option>, + cancellation: Option, memory: WriteMemory, } -/// Registers durable ownership before either an SST or its index is published to storage. +/// Registers output ownership before either an SST or its index is created in storage. #[async_trait::async_trait] pub trait SstWriteGuard: Send + Sync { async fn before_create(&self, file_id: RegionFileId) -> Result<()>; } -/// Protection and resource limits travel together for table-compaction output. +/// Optional ownership, cancellation, and resource limits for an SST write. +#[derive(Default)] pub(crate) struct SstWriteContext { - pub(crate) guard: Arc, - pub(crate) limits: SstWriteLimits, + /// Registers output ownership before creating files, including cached files. + pub(crate) guard: Option>, + /// Resource bounds enforced by the direct writer, with one upload at a time. + /// The write cache does not enforce these limits, so bounded writes bypass it. + pub(crate) limits: Option, + /// Signals cancellation; the writer still drains encoders and aborts unfinished output. + pub(crate) cancellation: Option, } pub trait WriterFactory { - type Writer: AsyncWrite + Send + Unpin; + type Writer: AsyncFileWriter; + + /// Opens output with the same cancellation signal as its encoders. fn create( &mut self, file_path: &str, write_buffer_size: usize, + cancellation: Option<&CancellationToken>, ) -> impl Future>; + + /// Aborts unfinished output after all encoders have stopped using it. + fn abort(writer: Self::Writer) -> impl Future>; +} + +/// Bridges an OpenDAL [`Writer`] with Parquet's [`AsyncFileWriter`] and tracks +/// the number of bytes successfully submitted to the object store. +pub struct ObjectStoreWriter { + inner: Writer, + output_bytes: u64, + write_buffer_size: usize, + cancellation: Option, +} + +impl ObjectStoreWriter { + pub(crate) fn new( + inner: Writer, + write_buffer_size: usize, + cancellation: Option, + ) -> Self { + Self { + inner, + output_bytes: 0, + write_buffer_size, + cancellation, + } + } + + pub(crate) fn output_bytes(&self) -> u64 { + self.output_bytes + } + + pub(crate) fn into_inner(self) -> Writer { + self.inner + } +} + +impl AsyncFileWriter for ObjectStoreWriter { + fn write(&mut self, bytes: Bytes) -> BoxFuture<'_, parquet::errors::Result<()>> { + Box::pin(async move { + let written = upload::write( + &mut self.inner, + bytes.into(), + self.write_buffer_size, + self.cancellation.as_ref(), + ) + .await + .map_err(|error| match error { + UploadError::Cancelled => ParquetError::External(Box::new(Cancelled)), + UploadError::Read { source } | UploadError::Write { source } => { + ParquetError::External(Box::new(source)) + } + })?; + self.output_bytes += written; + Ok(()) + }) + } + + fn complete(&mut self) -> BoxFuture<'_, parquet::errors::Result<()>> { + Box::pin(async move { + self.inner + .close() + .await + .map(|_| ()) + .map_err(|error| ParquetError::External(Box::new(error))) + }) + } } pub struct ObjectStoreWriterFactory { @@ -278,17 +358,26 @@ pub struct ObjectStoreWriterFactory { } impl WriterFactory for ObjectStoreWriterFactory { - type Writer = Compat; + type Writer = ObjectStoreWriter; - async fn create(&mut self, file_path: &str, write_buffer_size: usize) -> Result { + async fn create( + &mut self, + file_path: &str, + write_buffer_size: usize, + cancellation: Option<&CancellationToken>, + ) -> Result { self.object_store .writer_with(file_path) .chunk(write_buffer_size) .concurrent(self.concurrency) .await - .map(|v| v.into_futures_async_write().compat_write()) + .map(|writer| ObjectStoreWriter::new(writer, write_buffer_size, cancellation.cloned())) .context(OpenDalSnafu) } + + async fn abort(writer: Self::Writer) -> Result<()> { + writer.into_inner().abort().await.context(OpenDalSnafu) + } } impl<'a, I, P> ParquetWriter<'a, ObjectStoreWriterFactory, I, P> @@ -361,9 +450,26 @@ where file_cleaner: None, metrics, write_guard: None, + cancellation: None, } } + pub(crate) fn with_cancellation(mut self, cancellation: Option) -> Self { + self.cancellation = cancellation; + self + } + + fn check_cancelled(&self) -> Result<()> { + ensure!( + !self + .cancellation + .as_ref() + .is_some_and(|handle| handle.is_cancelled()), + crate::error::SstWriteCancelledSnafu + ); + Ok(()) + } + pub(crate) fn with_write_guard(mut self, guard: Option>) -> Self { self.write_guard = guard; self @@ -409,8 +515,9 @@ where ssts: &mut SstInfoArray, stats: &mut SourceStats, ) -> Result<()> { + self.check_cancelled()?; // maybe_init_writer will re-create a new file. - if let Some(mut current_writer) = mem::take(&mut self.writer) { + if self.writer.is_some() { let mut stats = mem::take(stats); // At least one row has been written. assert!(stats.num_rows > 0); @@ -424,21 +531,29 @@ where // Finish indexer and writer. // safety: writer and index can only be both present or not. - let mut index_output = IndexOutput::default(); - match self.index_config.build_mode { - IndexBuildMode::Sync => { - index_output = self.current_indexer.as_mut().unwrap().finish().await; - } - IndexBuildMode::Async => { - debug!( - "Index for file {} will be built asynchronously later", - self.current_file - ); - } - } - current_writer.flush().await.context(WriteParquetSnafu)?; - - let parquet_metadata = current_writer.close().await.context(WriteParquetSnafu)?; + let index_output = self.current_indexer.as_mut().unwrap().finish().await; + self.check_cancelled()?; + self.writer + .as_mut() + .context(UnexpectedSnafu { + reason: "Missing SST writer during finalization", + })? + .flush() + .await + .map_err(map_write_error)?; + self.check_cancelled()?; + // Keep the upload owned until finalization succeeds, so an error + // still reaches the common abort path. + let parquet_metadata = self + .writer + .as_mut() + .context(UnexpectedSnafu { + reason: "Missing SST writer during finalization", + })? + .finish() + .await + .map_err(map_write_error)?; + self.writer.take(); let file_size = self.bytes_written.load(Ordering::Relaxed) as u64; if self.memory.limits.is_some() { self.memory.completed = self.memory.completed.saturating_add( @@ -517,6 +632,7 @@ where ); let res = self.write_all_flat_inner(source, &converter, opts).await; if res.is_err() { + self.abort_current_indexer().await; self.abort_current_file().await; } res @@ -542,6 +658,7 @@ where }; let res = self.write_all_flat_inner(source, &converter, opts).await; if res.is_err() { + self.abort_current_indexer().await; self.abort_current_file().await; } res @@ -558,7 +675,17 @@ where loop { let start = Instant::now(); - let batch = match source.next_batch().await { + self.check_cancelled()?; + let next = if let Some(cancellation) = &self.cancellation { + tokio::select! { + biased; + _ = cancellation.cancelled() => return crate::error::SstWriteCancelledSnafu.fail(), + next = source.next_batch() => next, + } + } else { + source.next_batch().await + }; + let batch = match next { Ok(Some(batch)) => batch, Ok(None) => break, Err(e) => { @@ -622,26 +749,28 @@ where stats: &mut SourceStats, ) -> Result<()> { let result = async { + self.check_cancelled()?; let arrow_batch = converter.convert_batch(batch)?; + self.check_cancelled()?; let start = Instant::now(); self.maybe_init_writer(arrow_batch.schema_ref(), opts) .await? .write(&arrow_batch) .await - .context(WriteParquetSnafu)?; + .map_err(map_write_error)?; self.metrics.write_batch += start.elapsed(); + self.check_cancelled()?; stats.update_flat(batch)?; - if matches!(self.index_config.build_mode, IndexBuildMode::Sync) { - let start = Instant::now(); - // safety: self.current_indexer must be set when first batch has been written. - self.current_indexer - .as_mut() - .unwrap() - .update_flat(batch) - .await; - self.metrics.update_index += start.elapsed(); - } + let start = Instant::now(); + // The indexer exists once the first batch has been written. Outputs + // with extensions build all indexes together, including in async mode. + self.current_indexer + .as_mut() + .unwrap() + .update_flat(batch) + .await; + self.metrics.update_index += start.elapsed(); Ok(()) } .await; @@ -664,7 +793,10 @@ where /// Joins encoders before dropping the writer and deleting its failed output. async fn abort_current_file(&mut self) { if let Some(writer) = self.writer.take() { - writer.abort().await; + let output = writer.abort().await; + if let Err(error) = F::abort(output.inner).await { + common_telemetry::warn!(error; "Failed to abort SST writer, file: {}", self.current_file); + } } if let Some(cleaner) = &self.file_cleaner { cleaner.clean_by_file_id(self.current_file).await; @@ -672,7 +804,7 @@ where } async fn abort_current_indexer(&mut self) { - if let Some(indexer) = &mut self.current_indexer { + if let Some(mut indexer) = self.current_indexer.take() { indexer.abort().await; } } @@ -682,6 +814,7 @@ where schema: &SchemaRef, opts: &WriteOptions, ) -> Result<&mut SstArrowWriter>> { + self.check_cancelled()?; if let Some(ref mut w) = self.writer { Ok(w) } else { @@ -719,7 +852,11 @@ where } let writer = SizeAwareWriter::new( self.writer_factory - .create(&sst_file_path, opts.write_buffer_size.as_bytes() as usize) + .create( + &sst_file_path, + opts.write_buffer_size.as_bytes() as usize, + self.cancellation.as_ref(), + ) .await?, self.bytes_written.clone(), ); @@ -736,17 +873,18 @@ where opts.encode_parallelism, opts.encode_runtime, ) - .context(WriteParquetSnafu)?, + .map_err(map_write_error)? + .with_cancellation(self.cancellation.clone()), ) } else { SstArrowWriter::Serial( AsyncArrowWriter::try_new(writer, schema, Some(writer_props)) - .context(WriteParquetSnafu)?, + .map_err(map_write_error)?, ) }; self.writer = Some(arrow_writer); - let indexer = self + let mut indexer = self .indexer_builder .build( RegionFileId::new(self.metadata.region_id, self.current_file), @@ -754,6 +892,14 @@ where Some(opts.row_group_size), ) .await; + if matches!(self.index_config.build_mode, IndexBuildMode::Async) + && !indexer.has_extension_creators() + { + indexer.abort_builtin_creators().await; + } + // Extensions share one Puffin with built-in indexes. When an extension + // is active, finish all creators here instead of replacing its output + // with a built-in-only Puffin in the background. self.current_indexer = Some(indexer); // safety: self.writer is assigned above @@ -762,6 +908,19 @@ where } } +/// Keeps cancellation inside the SST write error contract, including nested encoder errors. +fn map_write_error(error: ParquetError) -> Error { + let cancelled = std::iter::successors(Some(&error as &(dyn StdError + 'static)), |source| { + (*source).source() + }) + .any(|source| source.is::()); + if cancelled { + crate::error::SstWriteCancelledSnafu.build() + } else { + WriteParquetSnafu.into_error(error) + } +} + #[derive(Default)] struct SourceStats { /// Number of rows fetched. @@ -875,47 +1034,34 @@ impl SizeAwareWriter { } } -impl AsyncWrite for SizeAwareWriter -where - W: AsyncWrite + Unpin, -{ - fn poll_write( - mut self: Pin<&mut Self>, - cx: &mut Context<'_>, - buf: &[u8], - ) -> Poll> { - let this = self.as_mut().get_mut(); - - match Pin::new(&mut this.inner).poll_write(cx, buf) { - Poll::Ready(Ok(bytes_written)) => { - this.size.fetch_add(bytes_written, Ordering::Relaxed); - Poll::Ready(Ok(bytes_written)) - } - other => other, - } +impl AsyncFileWriter for SizeAwareWriter { + fn write(&mut self, bytes: Bytes) -> BoxFuture<'_, parquet::errors::Result<()>> { + Box::pin(async move { + let len = bytes.len(); + self.inner.write(bytes).await?; + self.size.fetch_add(len, Ordering::Relaxed); + Ok(()) + }) } - fn poll_flush( - mut self: Pin<&mut Self>, - cx: &mut Context<'_>, - ) -> Poll> { - Pin::new(&mut self.inner).poll_flush(cx) - } - - fn poll_shutdown( - mut self: Pin<&mut Self>, - cx: &mut Context<'_>, - ) -> Poll> { - Pin::new(&mut self.inner).poll_shutdown(cx) + fn complete(&mut self) -> BoxFuture<'_, parquet::errors::Result<()>> { + self.inner.complete() } } #[cfg(test)] mod tests { + use std::sync::Mutex; use std::sync::atomic::AtomicBool; use std::time::Duration; + use common_base::readable_size::ReadableSize; use common_runtime::runtime::{BuilderBuild, RuntimeTrait}; + use object_store::layers::mock::{ + Metadata, MockLayerBuilder, ObservedWriter, WriterObservations, oio, + }; + use object_store::services::Memory; + use object_store::{Buffer, Error as ObjectStoreError, ErrorKind, Result as ObjectStoreResult}; use parquet::arrow::ArrowWriter; use parquet::errors::ParquetError; use store_api::region_request::PathType; @@ -925,20 +1071,445 @@ mod tests { use super::*; use crate::access_layer::{RegionFilePathFactory, WriteType}; use crate::compaction::memory_manager::new_compaction_memory_manager; - use crate::error::Error; use crate::sst::FormatType; use crate::sst::parquet::tests::NoopIndexBuilder; use crate::test_util::TestEnv; use crate::test_util::sst_util::{new_record_batch_by_range, sst_region_metadata}; + struct GatedObjectStoreWriter { + inner: oio::Writer, + started: Option>, + release: Option>, + completed: Arc, + write_error: Option, + } + + impl oio::Write for GatedObjectStoreWriter { + async fn write(&mut self, bytes: Buffer) -> ObjectStoreResult<()> { + if let Some(started) = self.started.take() { + started.send(()).unwrap(); + self.release.take().unwrap().await.unwrap(); + } + if let Some(error) = self.write_error.take() { + return Err(error); + } + self.inner.write(bytes).await?; + self.completed.fetch_add(1, Ordering::Relaxed); + Ok(()) + } + + async fn close(&mut self) -> ObjectStoreResult { + self.inner.close().await + } + + async fn abort(&mut self) -> ObjectStoreResult<()> { + self.inner.abort().await + } + } + + #[rstest::rstest] + #[tokio::test] + async fn test_object_store_writer_cancellation_between_chunks( + #[values(false, true)] observe_cancellation: bool, + ) { + let cancellation = CancellationToken::new(); + let observations = Arc::new(Mutex::new(WriterObservations::default())); + let completed = Arc::new(AtomicUsize::new(0)); + let (started_tx, started_rx) = oneshot::channel(); + let (release_tx, release_rx) = oneshot::channel(); + let gate = Mutex::new(Some((started_tx, release_rx))); + let observed = observations.clone(); + let completed_writes = completed.clone(); + let layer = MockLayerBuilder::default() + .writer_factory(Arc::new(move |_, _, inner| { + let (started, release) = gate.lock().unwrap().take().unwrap(); + Box::new(ObservedWriter::new( + Box::new(GatedObjectStoreWriter { + inner, + started: Some(started), + release: Some(release), + completed: completed_writes.clone(), + write_error: None, + }), + observed.clone(), + )) + })) + .build() + .unwrap(); + let store = ObjectStore::new(Memory::default()).unwrap().layer(layer); + let inner = store + .writer_with("output.parquet") + .chunk(4) + .concurrent(1) + .await + .unwrap(); + let mut writer = + ObjectStoreWriter::new(inner, 4, observe_cancellation.then(|| cancellation.clone())); + let data = Bytes::from(vec![42; 32]); + let mut write = Box::pin(writer.write(data.clone())); + assert!(futures::poll!(write.as_mut()).is_pending()); + timeout(Duration::from_secs(5), started_rx) + .await + .unwrap() + .unwrap(); + cancellation.cancel(); + // A started storage write retains its owner until it completes. + assert!(futures::poll!(write.as_mut()).is_pending()); + assert_eq!(0, completed.load(Ordering::Relaxed)); + release_tx.send(()).unwrap(); + let result = timeout(Duration::from_secs(5), write).await.unwrap(); + { + let observed = observations.lock().unwrap(); + assert_eq!(0, observed.abort_calls); + assert_eq!(0, observed.close_calls); + } + if observe_cancellation { + assert!( + matches!(result, Err(ParquetError::External(ref source)) if source.is::()) + ); + assert_eq!(1, completed.load(Ordering::Relaxed)); + assert_eq!(vec![4], observations.lock().unwrap().write_sizes); + // The caller owns abort; the adapter only reports cancellation. + writer.into_inner().abort().await.unwrap(); + assert_eq!(1, observations.lock().unwrap().abort_calls); + assert!(!store.exists("output.parquet").await.unwrap()); + } else { + result.unwrap(); + writer.complete().await.unwrap(); + assert_eq!(data, store.read("output.parquet").await.unwrap().to_bytes()); + let observed = observations.lock().unwrap(); + assert_eq!(1, observed.close_calls); + assert_eq!(0, observed.abort_calls); + assert_eq!(vec![4; 8], observed.write_sizes); + } + } + + #[rstest::rstest] + #[tokio::test] + async fn test_parquet_write_error_aborts_upload( + #[values(1, 2)] parallelism: usize, + #[values(false, true)] cancel_during_write: bool, + ) { + let cancellation = CancellationToken::new(); + let observations = Arc::new(Mutex::new(WriterObservations::default())); + let completed = Arc::new(AtomicUsize::new(0)); + let (started_tx, started_rx) = oneshot::channel(); + let (release_tx, release_rx) = oneshot::channel(); + let gate = Mutex::new(Some((started_tx, release_rx))); + let observed = observations.clone(); + let completed_writes = completed.clone(); + let layer = MockLayerBuilder::default() + .writer_factory(Arc::new(move |_, _, inner| { + let (started, release) = gate.lock().unwrap().take().unwrap(); + Box::new(ObservedWriter::new( + Box::new(GatedObjectStoreWriter { + inner, + started: Some(started), + release: Some(release), + completed: completed_writes.clone(), + write_error: (!cancel_during_write).then(|| { + ObjectStoreError::new( + ErrorKind::PermissionDenied, + "injected upload failure", + ) + }), + }), + observed.clone(), + )) + })) + .build() + .unwrap(); + let store = ObjectStore::new(Memory::default()).unwrap().layer(layer); + let metadata = Arc::new(sst_region_metadata()); + let mut metrics = Metrics::new(WriteType::Compaction); + let mut writer = ParquetWriter::new_with_object_store( + store, + metadata, + IndexConfig::default(), + NoopIndexBuilder, + RegionFilePathFactory::new(String::new(), PathType::Bare), + &mut metrics, + ) + .await + .with_write_concurrency(1) + .with_cancellation(Some(cancellation.clone())); + let batch = new_record_batch_by_range(&["a", "b"], 0, 8); + let opts = WriteOptions { + // A partial group reaches the upload through finish_current_file. + row_group_size: batch.num_rows() + 1, + write_buffer_size: ReadableSize(1), + encode_parallelism: parallelism, + ..Default::default() + }; + let source_finished = Arc::new(AtomicBool::new(false)); + let finished = source_finished.clone(); + let source = FlatSource::new_stream( + batch.schema(), + Box::pin(async_stream::try_stream! { + yield batch; + finished.store(true, Ordering::Relaxed); + }), + ); + let mut write = Box::pin(writer.write_all_flat(source, None, &opts)); + tokio::select! { + started = started_rx => started.unwrap(), + result = &mut write => panic!("writer returned before the upload gate: {result:?}"), + _ = tokio::time::sleep(Duration::from_secs(5)) => panic!("writer did not reach the upload gate"), + } + assert!(source_finished.load(Ordering::Relaxed)); + if cancel_during_write { + cancellation.cancel(); + } + assert!(futures::poll!(write.as_mut()).is_pending()); + assert_eq!(0, observations.lock().unwrap().abort_calls); + release_tx.send(()).unwrap(); + let error = timeout(Duration::from_secs(5), write) + .await + .unwrap() + .unwrap_err(); + if cancel_during_write { + assert!( + matches!(error, Error::SstWriteCancelled { .. }), + "{error:?}" + ); + } else { + assert!(matches!(error, Error::WriteParquet { .. }), "{error:?}"); + let source = + std::iter::successors(Some(&error as &(dyn StdError + 'static)), |error| { + (*error).source() + }) + .find_map(|error| error.downcast_ref::()) + .unwrap(); + assert_eq!(ErrorKind::PermissionDenied, source.kind()); + assert!(source.to_string().contains("injected upload failure")); + } + assert_eq!( + usize::from(cancel_during_write), + completed.load(Ordering::Relaxed) + ); + let observed = observations.lock().unwrap(); + assert_eq!(vec![1], observed.write_sizes); + assert_eq!(1, observed.abort_calls); + assert_eq!(0, observed.close_calls); + assert!(writer.writer.is_none()); + assert!(writer.current_indexer.is_none()); + } + #[rstest::rstest] #[case::flat(FormatType::Flat)] #[case::primary_key(FormatType::PrimaryKey)] #[tokio::test] - async fn test_source_error_waits_for_encoding_cleanup(#[case] format: FormatType) { + async fn test_encoding_error_classification( + #[case] format: FormatType, + #[values(false, true)] finish_file: bool, + #[values(false, true)] cancelled: bool, + ) { let mut env = TestEnv::new().await; let metadata = Arc::new(sst_region_metadata()); let mut metrics = Metrics::new(WriteType::Compaction); + let mut writer = ParquetWriter::new_with_object_store( + env.init_object_store_manager(), + metadata.clone(), + IndexConfig::default(), + NoopIndexBuilder, + RegionFilePathFactory::new(String::new(), PathType::Bare), + &mut metrics, + ) + .await; + let batch = new_record_batch_by_range(&["a", "b"], 0, 4); + let converter = match format { + FormatType::Flat => FlatBatchConverter::Flat(FlatWriteFormat::new( + metadata.clone(), + &FlatSchemaOptions::default(), + )), + FormatType::PrimaryKey => FlatBatchConverter::PrimaryKey { + format: PrimaryKeyWriteFormat::new(metadata.clone()), + num_fields: metadata.field_columns().count(), + }, + }; + let schema = converter.convert_batch(&batch).unwrap().schema(); + let opts = WriteOptions { + // A full row group joins the previous task in append_flat_batch; + // a partial group joins it in finish_current_file instead. + row_group_size: batch.num_rows() + usize::from(finish_file), + encode_parallelism: 2, + ..Default::default() + }; + let SstArrowWriter::Parallel(parallel) = + writer.maybe_init_writer(&schema, &opts).await.unwrap() + else { + panic!("expected parallel encoding"); + }; + let task = common_runtime::spawn_blocking_compact(move || { + let source: Box = if cancelled { + Box::new(Cancelled) + } else { + Box::new(std::io::Error::other("encoding failed")) + }; + Err(ParquetError::External(source)) + }); + // No SST-level cancellation handle: only the encoder's error can report cancellation. + parallel.set_encoding_tasks_for_test(vec![task]); + let source = + FlatSource::new_stream(batch.schema(), Box::pin(futures::stream::iter([Ok(batch)]))); + let error = match format { + FormatType::Flat => writer.write_all_flat(source, None, &opts).await, + FormatType::PrimaryKey => { + writer + .write_all_flat_as_primary_key(source, None, &opts) + .await + } + } + .unwrap_err(); + if cancelled { + assert!(matches!(error, Error::SstWriteCancelled { .. })); + } else { + assert!( + matches!(error, Error::WriteParquet { error: ParquetError::External(ref source), .. } + if source.downcast_ref::().is_some_and(|error| error.to_string() == "encoding failed")) + ); + } + assert!(writer.writer.is_none()); + assert!(writer.current_indexer.is_none()); + assert_eq!(0, writer.bytes_written.load(Ordering::Relaxed)); + } + + #[rstest::rstest] + #[case::flat(FormatType::Flat)] + #[case::primary_key(FormatType::PrimaryKey)] + #[tokio::test] + async fn test_cancel_pending_source( + #[case] format: FormatType, + #[values(1, 2)] parallelism: usize, + ) { + let mut env = TestEnv::new().await; + let metadata = Arc::new(sst_region_metadata()); + let cancellation = CancellationToken::new(); + let mut metrics = Metrics::new(WriteType::Compaction); + let mut writer = ParquetWriter::new_with_object_store( + env.init_object_store_manager(), + metadata, + IndexConfig::default(), + NoopIndexBuilder, + RegionFilePathFactory::new(String::new(), PathType::Bare), + &mut metrics, + ) + .await + .with_cancellation(Some(cancellation.clone())); + let batch = new_record_batch_by_range(&["a", "b"], 0, 4); + let schema = batch.schema(); + let source = FlatSource::new_stream( + schema, + Box::pin(async_stream::try_stream! { + yield batch; + futures::future::pending::<()>().await; + }), + ); + let opts = WriteOptions { + row_group_size: 8, + encode_parallelism: parallelism, + ..Default::default() + }; + let mut write = Box::pin(async { + match format { + FormatType::Flat => writer.write_all_flat(source, None, &opts).await, + FormatType::PrimaryKey => { + writer + .write_all_flat_as_primary_key(source, None, &opts) + .await + } + } + }); + assert!(futures::poll!(write.as_mut()).is_pending()); + cancellation.cancel(); + let error = timeout(Duration::from_secs(5), write) + .await + .unwrap() + .unwrap_err(); + assert!(matches!(error, Error::SstWriteCancelled { .. })); + assert!(writer.writer.is_none()); + } + + /// Controlled comparison: identical batches and cancellation point, changing + /// only whether the writer observes cancellation. + #[rstest::rstest] + #[case::flat(FormatType::Flat)] + #[case::primary_key(FormatType::PrimaryKey)] + #[tokio::test] + async fn test_batch_cancellation_ablation( + #[case] format: FormatType, + #[values(1, 2)] parallelism: usize, + ) { + for enabled in [false, true] { + let mut env = TestEnv::new().await; + let cancellation = CancellationToken::new(); + let mut metrics = Metrics::new(WriteType::Compaction); + let mut writer = ParquetWriter::new_with_object_store( + env.init_object_store_manager(), + Arc::new(sst_region_metadata()), + IndexConfig::default(), + NoopIndexBuilder, + RegionFilePathFactory::new(String::new(), PathType::Bare), + &mut metrics, + ) + .await + .with_cancellation(enabled.then(|| cancellation.clone())); + let batch = new_record_batch_by_range(&["a", "b"], 0, 4); + let consumed = Arc::new(AtomicUsize::new(0)); + let observed = consumed.clone(); + let source = FlatSource::new_stream( + batch.schema(), + Box::pin(async_stream::try_stream! { + for i in 0..32 { + if i == 1 { cancellation.cancel(); } + observed.fetch_add(1, Ordering::Relaxed); + yield new_record_batch_by_range(&["a", "b"], i * 8, i * 8 + 8); + } + }), + ); + let opts = WriteOptions { + row_group_size: 8, + encode_parallelism: parallelism, + ..Default::default() + }; + let result = match format { + FormatType::Flat => writer.write_all_flat(source, None, &opts).await, + FormatType::PrimaryKey => { + writer + .write_all_flat_as_primary_key(source, None, &opts) + .await + } + }; + if enabled { + assert!(result.is_err()); + assert_eq!(2, consumed.load(Ordering::Relaxed)); + assert!(writer.writer.is_none()); + } else { + assert_eq!( + 256, + result + .unwrap() + .iter() + .map(|info| info.num_rows) + .sum::() + ); + assert_eq!(32, consumed.load(Ordering::Relaxed)); + } + } + } + + #[rstest::rstest] + #[case::flat(FormatType::Flat)] + #[case::primary_key(FormatType::PrimaryKey)] + #[tokio::test] + async fn test_source_error_waits_for_encoding_cleanup( + #[case] format: FormatType, + #[values(false, true)] cancel_source: bool, + ) { + let mut env = TestEnv::new().await; + let metadata = Arc::new(sst_region_metadata()); + let cancellation = CancellationToken::new(); + let mut metrics = Metrics::new(WriteType::Compaction); let mut writer = ParquetWriter::new_with_object_store( env.init_object_store_manager(), metadata.clone(), @@ -947,7 +1518,8 @@ mod tests { RegionFilePathFactory::new("".to_string(), PathType::Bare), &mut metrics, ) - .await; + .await + .with_cancellation(Some(cancellation.clone())); let opts = WriteOptions { row_group_size: 8, encode_parallelism: 2, @@ -1010,13 +1582,11 @@ mod tests { parallel.set_encoding_tasks_for_test(vec![running, queued]); let source = FlatSource::new_stream( batch.schema(), - Box::pin(futures::stream::iter(vec![ - Ok(batch), - InvalidRecordBatchSnafu { - reason: "source read failed", - } - .fail(), - ])), + Box::pin(async_stream::try_stream! { + yield batch; + if cancel_source { futures::future::pending::<()>().await; } + Err(InvalidRecordBatchSnafu { reason: "source read failed" }.build())?; + }), ); let memory = new_compaction_memory_manager(1024 * 1024); let budget = memory.try_acquire(memory.limit_bytes()).unwrap(); @@ -1034,6 +1604,10 @@ mod tests { // The next row group is buffered, then the source fails. No codec timing // or I/O wait can make the old indexer-only cleanup pass this assertion. assert!(futures::poll!(write.as_mut()).is_pending()); + if cancel_source { + cancellation.cancel(); + assert!(futures::poll!(write.as_mut()).is_pending()); + } assert!(memory.try_acquire(memory.limit_bytes()).is_none()); assert!(retained_field.upgrade().is_some()); release_tx.send(()).unwrap(); @@ -1041,9 +1615,13 @@ mod tests { .await .unwrap() .unwrap_err(); - assert!( - matches!(error, Error::InvalidRecordBatch { reason, .. } if reason == "source read failed") - ); + if cancel_source { + assert!(matches!(error, Error::SstWriteCancelled { .. })); + } else { + assert!( + matches!(error, Error::InvalidRecordBatch { reason, .. } if reason == "source read failed") + ); + } assert!(!queued_started.load(Ordering::SeqCst)); assert!(retained_field.upgrade().is_none()); assert!(memory.try_acquire(memory.limit_bytes()).is_some()); diff --git a/src/mito2/src/sst/upload.rs b/src/mito2/src/sst/upload.rs new file mode 100644 index 00000000000..a5dfeaf2384 --- /dev/null +++ b/src/mito2/src/sst/upload.rs @@ -0,0 +1,243 @@ +// Copyright 2023 Greptime Team +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! Cooperative byte transfer for SST uploads. Callers own close, abort, and file cleanup. + +use futures::{Stream, StreamExt}; +use object_store::{Buffer, Error as ObjectStoreError, Result as ObjectStoreResult, Writer}; +use snafu::Snafu; +use tokio_util::sync::CancellationToken; + +/// Preserves read/write attribution until the caller adds its file context. +#[derive(Debug, Snafu)] +pub(crate) enum UploadError { + #[snafu(display("Upload cancelled"))] + Cancelled, + #[snafu(display("Failed to read upload source: {source}"))] + Read { source: ObjectStoreError }, + #[snafu(display("Failed to write upload: {source}"))] + Write { source: ObjectStoreError }, +} + +/// Copies chunks without dropping an in-flight write when cancellation arrives. +pub(crate) async fn copy( + reader: &mut (impl Stream> + Unpin), + writer: &mut Writer, + write_buffer_size: usize, + cancellation: Option<&CancellationToken>, +) -> Result { + let mut written = 0; + loop { + let next = if let Some(cancellation) = cancellation { + tokio::select! { + biased; + _ = cancellation.cancelled() => return Err(UploadError::Cancelled), + next = reader.next() => next, + } + } else { + reader.next().await + }; + let Some(bytes) = next else { + return Ok(written); + }; + let bytes = bytes.map_err(|source| UploadError::Read { source })?; + written += write(writer, bytes, write_buffer_size, cancellation).await?; + } +} + +/// Writes bounded, zero-copy slices, awaiting each started write to completion. +pub(crate) async fn write( + writer: &mut Writer, + mut bytes: Buffer, + write_buffer_size: usize, + cancellation: Option<&CancellationToken>, +) -> Result { + let len = bytes.len() as u64; + // Keep each slice nonempty even when the configured size is zero. + let write_buffer_size = write_buffer_size.max(1); + while !bytes.is_empty() { + if cancellation.is_some_and(CancellationToken::is_cancelled) { + return Err(UploadError::Cancelled); + } + let chunk = bytes.split_to(bytes.len().min(write_buffer_size)); + writer + .write(chunk) + .await + .map_err(|source| UploadError::Write { source })?; + } + if cancellation.is_some_and(CancellationToken::is_cancelled) { + return Err(UploadError::Cancelled); + } + Ok(len) +} + +#[cfg(test)] +mod tests { + use std::sync::{Arc, Mutex}; + use std::time::Duration; + + use bytes::Bytes; + use futures::stream; + use object_store::ObjectStore; + use object_store::layers::mock::{ + Metadata, MockLayerBuilder, ObservedWriter, WriterObservations, oio, + }; + use object_store::services::Memory; + use tokio::sync::Notify; + use tokio::time::timeout; + + use super::*; + + #[tokio::test] + async fn test_copy_cancels_pending_read() { + let store = ObjectStore::new(Memory::default()).unwrap(); + let mut writer = store.writer("pending").await.unwrap(); + let mut reader = stream::pending(); + let cancellation = CancellationToken::new(); + let mut copy = Box::pin(super::copy( + &mut reader, + &mut writer, + 4, + Some(&cancellation), + )); + assert!(futures::poll!(copy.as_mut()).is_pending()); + cancellation.cancel(); + let error = timeout(Duration::from_secs(5), copy) + .await + .unwrap() + .unwrap_err(); + assert!(matches!(error, UploadError::Cancelled)); + writer.abort().await.unwrap(); + assert!(!store.exists("pending").await.unwrap()); + } + + struct GatedWriter { + inner: oio::Writer, + started: Arc, + release: Arc, + } + + impl oio::Write for GatedWriter { + async fn write(&mut self, bytes: Buffer) -> ObjectStoreResult<()> { + self.started.notify_one(); + self.release.notified().await; + self.inner.write(bytes).await + } + + async fn close(&mut self) -> ObjectStoreResult { + self.inner.close().await + } + + async fn abort(&mut self) -> ObjectStoreResult<()> { + self.inner.abort().await + } + } + + #[tokio::test] + async fn test_copy_cancellation_waits_for_started_write() { + let started = Arc::new(Notify::new()); + let release = Arc::new(Notify::new()); + let observations = Arc::new(Mutex::new(WriterObservations::default())); + let observer = observations.clone(); + let started_write = started.clone(); + let release_write = release.clone(); + let layer = MockLayerBuilder::default() + .writer_factory(Arc::new(move |_, _, inner| { + Box::new(ObservedWriter::new( + Box::new(GatedWriter { + inner, + started: started_write.clone(), + release: release_write.clone(), + }), + observer.clone(), + )) + })) + .build() + .unwrap(); + let store = ObjectStore::new(Memory::default()).unwrap().layer(layer); + // Leave the OpenDAL writer unbuffered so the observer sees helper boundaries. + let mut writer = store.writer("gated").await.unwrap(); + let mut reader = stream::iter([Ok(Buffer::from(Bytes::from_static(b"abcdefghijkl")))]); + let cancellation = CancellationToken::new(); + let mut copy = Box::pin(super::copy( + &mut reader, + &mut writer, + 4, + Some(&cancellation), + )); + assert!(futures::poll!(copy.as_mut()).is_pending()); + timeout(Duration::from_secs(5), started.notified()) + .await + .unwrap(); + + cancellation.cancel(); + assert!(futures::poll!(copy.as_mut()).is_pending()); + release.notify_one(); + let error = timeout(Duration::from_secs(5), copy) + .await + .unwrap() + .unwrap_err(); + assert!(matches!(error, UploadError::Cancelled)); + { + let observations = observations.lock().unwrap(); + assert_eq!(vec![4], observations.write_sizes); + assert_eq!(0, observations.close_calls); + assert_eq!(0, observations.abort_calls); + } + writer.abort().await.unwrap(); + assert_eq!(1, observations.lock().unwrap().abort_calls); + assert!(!store.exists("gated").await.unwrap()); + } + + #[rstest::rstest] + #[tokio::test] + async fn test_copy_preserves_contents(#[values(false, true)] cancellable: bool) { + let observations = Arc::new(Mutex::new(WriterObservations::default())); + let observer = observations.clone(); + let layer = MockLayerBuilder::default() + .writer_factory(Arc::new(move |_, _, inner| { + Box::new(ObservedWriter::new(inner, observer.clone())) + })) + .build() + .unwrap(); + let store = ObjectStore::new(Memory::default()).unwrap().layer(layer); + let mut writer = store.writer("complete").await.unwrap(); + let mut reader = stream::iter([ + Ok(Buffer::from(Bytes::from_static(b"abcde"))), + Ok(Buffer::from(Bytes::from_static(b"fghijkl"))), + ]); + let cancellation = CancellationToken::new(); + let copied = super::copy( + &mut reader, + &mut writer, + 4, + cancellable.then_some(&cancellation), + ) + .await + .unwrap(); + assert_eq!(12, copied); + { + let observations = observations.lock().unwrap(); + assert_eq!(vec![4, 1, 4, 3], observations.write_sizes); + assert_eq!(0, observations.close_calls); + assert_eq!(0, observations.abort_calls); + } + writer.close().await.unwrap(); + assert_eq!(1, observations.lock().unwrap().close_calls); + assert_eq!( + Bytes::from_static(b"abcdefghijkl"), + store.read("complete").await.unwrap().to_bytes() + ); + } +} diff --git a/src/mito2/src/tail_replay.rs b/src/mito2/src/tail_replay.rs index d9c7d33d70e..5a8e712cd79 100644 --- a/src/mito2/src/tail_replay.rs +++ b/src/mito2/src/tail_replay.rs @@ -16,23 +16,27 @@ use std::num::NonZeroU64; use std::sync::Arc; +use std::sync::atomic::{AtomicUsize, Ordering}; use std::time::Duration; -use common_base::cancellation::CancellableFuture; use common_telemetry::{error, info, warn}; use futures::TryStreamExt; use snafu::ensure; use store_api::logstore::{LogStore, WalReadUpperBound}; use store_api::storage::RegionId; +use tokio::sync::Semaphore; use tokio::sync::mpsc::Sender; -use crate::error::{Error, FlushCancelledSnafu, Result, TailEntryMissingSnafu}; -use crate::flush::RegionFlushTask; +use crate::cache::CacheManagerRef; +use crate::config::MitoConfig; +use crate::error::{Error, FlushCancelledSnafu, Result, TailEntryMissingSnafu, UnexpectedSnafu}; +use crate::flush::MemtableSstWriter; use crate::manifest::action::{ PendingTail, RegionEdit, RegionMetaAction, RegionMetaActionList, UptoKind, WalRecoveryEdit, cap_wal_release, }; use crate::memtable::time_partition::TimePartitions; +use crate::metrics::TAIL_REPLAY_FAILURE_TOTAL; use crate::region::opener::replay_entry; use crate::region::version::{VersionBuilder, VersionControl, VersionControlRef}; use crate::region::{MitoRegion, MitoRegionRef, TailPublication}; @@ -40,9 +44,15 @@ use crate::request::{BackgroundNotify, WorkerRequest, WorkerRequestWithTime}; use crate::schedule::CancellableTaskState; use crate::sst::file::{FileMeta, UncommittedSsts}; use crate::wal::{EntryId, Wal, WalEntryStream}; +use crate::worker::WorkerListener; -/// Memtable usage at which replayed rows are written to SSTs. +/// Memtable usage at which replayed rows are written to SSTs at the latest. const CHUNK_MEMTABLE_USAGE: usize = 64 * 1024 * 1024; +/// Replays that read and write at once on a node. +const MAX_CONCURRENT_TAIL_REPLAYS: usize = 16; +/// The replay chunks of a node may use `1 / TAIL_REPLAY_MEMORY_FACTOR` of the global write +/// buffer size. +const TAIL_REPLAY_MEMORY_FACTOR: usize = 8; /// Delay before the first retry of a failed round or an unfinished commit. const MIN_BACKOFF: Duration = Duration::from_secs(1); /// Longest delay between retries. @@ -61,19 +71,28 @@ pub(crate) fn should_replay_tails(region: &MitoRegion) -> bool { /// Each round reads the tails in order and writes each into its own SSTs: an SST can give all its /// rows its largest sequence, so in an SST shared with a later tail, an earlier tail's rows would /// take the later tail's sequence and outrank rows that a leader between the two tails flushed. A -/// tail's 64 MiB chunks only bound memory: writes accepted during the replay already take sequences -/// above every tail's. The edit adds the SSTs, clears the tails and advances the flushed entry id -/// and sequence. Another node's listed tail is only a bound, so until the region receives a Leader -/// lease after a catchup made it writable, the edit keeps its unread part, which a second edit -/// clears once a lease arrives. A failed round is retried after a back-off while -/// [should_replay_tails] holds. The task always reports its end to the worker. +/// tail's chunks only bound memory: writes accepted during the replay already take sequences +/// above every tail's. A chunk is written once it reaches 64 MiB, or once it grows above its floor +/// and the node's replay memory pool cannot cover the growth. The edit adds the SSTs, clears +/// the tails and advances the flushed entry id and sequence. Another node's listed tail is only a +/// bound, so until the region receives a Leader lease after a catchup made it writable, the edit +/// keeps its unread part, which a second edit clears once a lease arrives. A failed round is +/// retried after a back-off while [should_replay_tails] holds, unless the storage holds a newer +/// manifest and the region is still a Writable leader at its installed version: then the task +/// fences the region for a reload and ends. The task always reports its end to the worker. pub(crate) struct TailReplayTask { pub(crate) region: MitoRegionRef, /// Id of this node, whose tails are read from `wal`. pub(crate) node_id: Option, pub(crate) wal: Wal, - /// Writes the chunks. It is never scheduled as a flush. - pub(crate) flush_task: RegionFlushTask, + /// Writes the chunks, built by [TailReplayLimits::new_sst_writer]. + pub(crate) sst_writer: MemtableSstWriter, + /// Test listener told of failed rounds, lease and fence checks and commits. + pub(crate) listener: WorkerListener, + /// Sends the task's results and its end to the worker. + pub(crate) request_sender: Sender, + /// Limits of the node's tail replays. + pub(crate) limits: TailReplayLimits, pub(crate) state: CancellableTaskState, } @@ -81,7 +100,7 @@ impl TailReplayTask { pub(crate) async fn run(self) { let region_id = self.region.region_id; let _ended = TailReplayEndGuard { - sender: self.flush_task.request_sender.clone(), + sender: self.request_sender.clone(), region_id, }; let mut backoff = MIN_BACKOFF; @@ -91,9 +110,19 @@ impl TailReplayTask { Err(_) if self.state.is_cancelled() => break, Err(e) => { error!(e; "Failed to replay the pending WAL tails of region {region_id}"); - self.flush_task - .listener - .on_tail_replay_failed(region_id, &e); + TAIL_REPLAY_FAILURE_TOTAL.inc(); + self.listener.on_tail_replay_failed(region_id, &e); + // The tails may be gone from a newer manifest, e.g. after another writer + // committed them and their source released its WAL. The worker reloads the + // fenced region once this task ends. + match self.fence_if_manifest_updated().await { + Ok(true) => break, + Ok(false) => {} + Err(_) if self.state.is_cancelled() => break, + Err(e) => { + warn!(e; "Failed to check region {region_id} for a newer manifest"); + } + } } } if !self.sleep(backoff).await { @@ -106,8 +135,49 @@ impl TailReplayTask { ); } + /// Fences the region for a reload if the storage holds a newer manifest and the region is + /// still a Writable leader at its installed version. Returns whether it fenced the region. + /// Cancellation ends it until it holds the manifest write lock. + async fn fence_if_manifest_updated(&self) -> Result { + let manifest_ctx = &self.region.manifest_ctx; + let Some(installed) = self + .unless_cancelled(manifest_ctx.installed_version_if_updated()) + .await? + else { + return Ok(false); + }; + let region_id = self.region.region_id; + info!( + "Region {region_id} found a manifest newer than its version {installed} after a failed replay round" + ); + self.listener.on_tail_fence_begin(region_id); + let mut manager = self + .unless_cancelled(async { Ok(manifest_ctx.manifest_manager.write().await) }) + .await?; + Ok(manifest_ctx + .fence_for_reload_if_unchanged(&mut manager, region_id, installed) + .await) + } + /// Replays the current tails and publishes the result. An error asks for another round. async fn replay_round(&self) -> Result<()> { + let region_id = self.region.region_id; + let replay_semaphore = &self.limits.replay_semaphore; + let permit = match replay_semaphore.try_acquire() { + Ok(permit) => permit, + Err(_) => { + info!("Region {region_id} waits for a tail replay permit"); + self.unless_cancelled(async { + replay_semaphore.acquire().await.map_err(|error| { + UnexpectedSnafu { + reason: format!("failed to acquire a tail replay permit: {error}"), + } + .build() + }) + }) + .await? + } + }; // Keeps no version past this point: it would hold the region's memtables, and their // write buffer memory, after a flush released them. let (tails, flushed_entry_id) = { @@ -115,11 +185,13 @@ impl TailReplayTask { (version.pending_tails.clone(), version.flushed_entry_id) }; let uncommitted = UncommittedSsts::new( - self.region.region_id, + region_id, self.region.access_layer.clone(), - Some(self.flush_task.cache_manager.clone()), + Some(self.sst_writer.cache_manager().clone()), ); - let (files, last_entry_ids) = match self.replay_tails(&tails, &uncommitted).await { + let replayed = self.replay_tails(&tails, &uncommitted).await; + drop(permit); + let (files, last_entry_ids) = match replayed { Ok(replayed) => replayed, Err(e) => { uncommitted.cleanup().await; @@ -210,6 +282,7 @@ impl TailReplayTask { for tail in tails { let mut entries = self.unless_cancelled(self.read_tail_entries(tail)).await?; let mut chunk = self.new_chunk_version(); + let mut reservation = self.limits.memory.chunk_reservation(); let mut last_entry_id = None; while let Some((entry_id, entry)) = self.unless_cancelled(entries.try_next()).await? { if entry_id > tail.upto { @@ -217,9 +290,11 @@ impl TailReplayTask { } replay_entry(provider, region_id, &chunk, entry, entry_id).await?; last_entry_id = Some(entry_id); - if chunk.current().version.memtables.mutable_usage() >= CHUNK_MEMTABLE_USAGE { + let usage = chunk.current().version.memtables.mutable_usage(); + if usage >= CHUNK_MEMTABLE_USAGE || !reservation.grow_to(usage) { files.extend(self.write_chunk_ssts(&chunk, uncommitted).await?); chunk = self.new_chunk_version(); + reservation.clear(); } if entry_id == tail.upto { break; @@ -263,7 +338,7 @@ impl TailReplayTask { let region_id = self.region.region_id; info!("Region {region_id} waits for a Leader lease to clear its unread listed tails"); while self.region.can_replay_tails() { - self.flush_task.listener.on_tail_lease_check(region_id); + self.listener.on_tail_lease_check(region_id); if self.region.manifest_ctx.leader_lease_received() { return true; } @@ -303,7 +378,7 @@ impl TailReplayTask { if version.memtables.immutables().is_empty() { return Ok(Vec::new()); } - self.flush_task + self.sst_writer .write_ssts(&version, &self.state, uncommitted) .await } @@ -323,10 +398,7 @@ impl TailReplayTask { // Whether an attempt may have persisted the edit, which only the same content confirms. let mut uncertain = false; loop { - self.flush_task - .listener - .on_tail_commit_begin(region_id) - .await; + self.listener.on_tail_commit_begin(region_id).await; if self.state.is_cancelled() { info!("Region {region_id} cancelled its tail replay before publishing"); uncommitted.cleanup().await; @@ -351,7 +423,7 @@ impl TailReplayTask { edit, tails, }; - notify_worker(&self.flush_task.request_sender, region_id, notify).await; + notify_worker(&self.request_sender, region_id, notify).await; return Ok(true); } Ok(TailPublication::Busy) => {} @@ -416,16 +488,22 @@ impl TailReplayTask { /// Awaits `future` unless the task is cancelled first. async fn unless_cancelled(&self, future: impl Future>) -> Result { - CancellableFuture::new(future, self.state.cancel_handle()) - .await - .unwrap_or_else(|_| FlushCancelledSnafu.fail()) + let cancellation = self.state.cancel_token(); + tokio::select! { + biased; + _ = cancellation.cancelled() => FlushCancelledSnafu.fail(), + result = future => result, + } } /// Sleeps for `delay`. Returns false if the task is cancelled first. async fn sleep(&self, delay: Duration) -> bool { - CancellableFuture::new(tokio::time::sleep(delay), self.state.cancel_handle()) - .await - .is_ok() + self.unless_cancelled(async { + tokio::time::sleep(delay).await; + Ok(()) + }) + .await + .is_ok() } } @@ -460,3 +538,171 @@ impl Drop for TailReplayEndGuard { }); } } + +/// Bounds the tail replays of a node. They take none of the flush permits, while their chunk +/// memtables still count in the global write buffer. +#[derive(Clone)] +pub(crate) struct TailReplayLimits { + /// Replays that read and write at once. + replay_semaphore: Arc, + /// SST writes of the replays, as many as the flushes may run, so a node may write up to + /// `2 * max_background_flushes` level 0 SSTs at once. Writer buffers are not part of the + /// replay memory budget. + write_semaphore: Arc, + /// Memtable memory of the replay chunks. + memory: Arc, +} + +impl TailReplayLimits { + /// Creates the limits of a node from `config`: `MAX_CONCURRENT_TAIL_REPLAYS` replays, + /// `max_background_flushes` SST writes and + /// `global_write_buffer_size / TAIL_REPLAY_MEMORY_FACTOR` bytes of chunk memory. + pub(crate) fn new(config: &MitoConfig) -> Self { + Self { + replay_semaphore: Arc::new(Semaphore::new(MAX_CONCURRENT_TAIL_REPLAYS)), + write_semaphore: Arc::new(Semaphore::new(config.max_background_flushes)), + memory: Arc::new(TailReplayMemory::new( + config.global_write_buffer_size.as_bytes() as usize / TAIL_REPLAY_MEMORY_FACTOR, + )), + } + } + + /// Creates a writer of the `region`'s replay chunks, which takes these limits' write + /// permits. + pub(crate) fn new_sst_writer( + &self, + region: &MitoRegion, + engine_config: Arc, + cache_manager: CacheManagerRef, + ) -> MemtableSstWriter { + MemtableSstWriter::new_tail_replay( + region, + engine_config, + cache_manager, + self.write_semaphore.clone(), + ) + } +} + +/// Memtable memory of the replay chunks on a node, out of a `budget`. The chunks share a pool of +/// half the budget above their floors, and each of the [MAX_CONCURRENT_TAIL_REPLAYS] replays may +/// always use a floor of an equal share of the other half. +struct TailReplayMemory { + /// Bytes each replay's chunk may always use without a reservation. + floor: usize, + /// Bytes the chunks share above their floors. + pool: usize, + /// Bytes of the pool the chunks hold. + reserved: AtomicUsize, +} + +impl TailReplayMemory { + /// Splits `budget` into the floors and the pool. + fn new(budget: usize) -> Self { + Self { + floor: budget / (2 * MAX_CONCURRENT_TAIL_REPLAYS), + pool: budget / 2, + reserved: AtomicUsize::new(0), + } + } + + /// Returns an empty reservation for one chunk. + fn chunk_reservation(&self) -> ChunkReservation<'_> { + ChunkReservation { + memory: self, + bytes: 0, + } + } + + /// Reserves `bytes` of the pool. Returns false if the pool has not enough left. + fn try_reserve(&self, bytes: usize) -> bool { + self.reserved + .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |reserved| { + (reserved + bytes <= self.pool).then_some(reserved + bytes) + }) + .is_ok() + } + + /// Returns `bytes` to the pool. + fn release(&self, bytes: usize) { + self.reserved.fetch_sub(bytes, Ordering::Relaxed); + } +} + +/// The pool memory a chunk uses above its floor. It is released on drop. +struct ChunkReservation<'a> { + /// Memory the reservation is taken from. + memory: &'a TailReplayMemory, + /// Bytes of the pool the chunk holds. + bytes: usize, +} + +impl ChunkReservation<'_> { + /// Grows the reservation to cover a chunk using `usage` bytes. Returns false if the pool + /// has not enough left, in which case the reservation is unchanged. + fn grow_to(&mut self, usage: usize) -> bool { + let needed = usage.saturating_sub(self.memory.floor); + if needed <= self.bytes { + return true; + } + if !self.memory.try_reserve(needed - self.bytes) { + return false; + } + self.bytes = needed; + true + } + + /// Releases the reservation for a new chunk. + fn clear(&mut self) { + self.memory.release(self.bytes); + self.bytes = 0; + } +} + +impl Drop for ChunkReservation<'_> { + fn drop(&mut self) { + self.clear(); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_chunk_reservation_keeps_floor_when_pool_is_exhausted() { + // Floor 1 KiB, pool 16 KiB. + let memory = TailReplayMemory::new(32 * 1024); + let mut first = memory.chunk_reservation(); + let mut second = memory.chunk_reservation(); + assert!(first.grow_to(17 * 1024)); + assert!(!first.grow_to(17 * 1024 + 1)); + // The pool is used up, but another chunk still grows to its floor. + assert!(second.grow_to(1024)); + assert!(!second.grow_to(1025)); + + first.clear(); + assert!(second.grow_to(17 * 1024)); + drop(second); + assert_eq!(0, memory.reserved.load(Ordering::Relaxed)); + } + + #[test] + fn test_chunk_reservation_grows_by_increments_and_reuses_after_clear() { + // Floor 1 KiB, pool 16 KiB. + let memory = TailReplayMemory::new(32 * 1024); + let reserved = || memory.reserved.load(Ordering::Relaxed); + let mut chunk = memory.chunk_reservation(); + assert!(chunk.grow_to(5 * 1024)); + assert_eq!(4 * 1024, reserved()); + assert!(chunk.grow_to(9 * 1024)); + assert_eq!(8 * 1024, reserved()); + + chunk.clear(); + assert_eq!(0, reserved()); + assert!(chunk.grow_to(3 * 1024)); + assert_eq!(2 * 1024, reserved()); + drop(chunk); + assert_eq!(0, reserved()); + } +} diff --git a/src/mito2/src/test_util.rs b/src/mito2/src/test_util.rs index 7af095b4ca6..04d56fb6499 100644 --- a/src/mito2/src/test_util.rs +++ b/src/mito2/src/test_util.rs @@ -42,7 +42,7 @@ use common_meta::kv_backend::KvBackendRef; use common_meta::kv_backend::memory::MemoryKvBackend; use common_telemetry::{debug, warn}; use common_test_util::temp_dir::{TempDir, create_temp_dir}; -use common_wal::config::object_store::{ObjectStoreWalConfig, STANDALONE_GENERATION}; +use common_wal::config::object_store::{FIXED_DIRECTORY_GENERATION, ObjectStoreWalConfig}; use common_wal::options::{KafkaWalOptions, WAL_OPTIONS_KEY, WalOptions}; use datatypes::arrow::array::{TimestampMillisecondArray, UInt8Array, UInt64Array}; use datatypes::extension::json::{Json2ExtensionType, JsonExtensionType}; @@ -683,10 +683,14 @@ impl TestEnv { wal_config: &ObjectStoreWalConfig, ) -> (MitoEngine, Arc) { let wal_object_store = ObjectStore::new(Memory::default()).unwrap(); - let log_store = - ObjectStoreLogStore::try_new(wal_object_store, wal_config, 0, STANDALONE_GENERATION) - .await - .unwrap(); + let log_store = ObjectStoreLogStore::try_new( + wal_object_store, + wal_config, + 0, + FIXED_DIRECTORY_GENERATION, + ) + .await + .unwrap(); let engine = self .create_engine_with_log_store(config, log_store.clone()) .await; diff --git a/src/mito2/src/worker.rs b/src/mito2/src/worker.rs index fc2f04aa87e..820596c62e7 100644 --- a/src/mito2/src/worker.rs +++ b/src/mito2/src/worker.rs @@ -71,14 +71,14 @@ use crate::config::MitoConfig; use crate::error::{self, CreateDirSnafu, JoinSnafu, Result, WorkerStoppedSnafu}; use crate::flush::{FlushScheduler, WriteBufferManagerImpl, WriteBufferManagerRef}; use crate::gc::{GcLimiter, GcLimiterRef}; -use crate::lease::NodeLease; +use crate::lease::{GrantedLeases, NodeLease}; use crate::memtable::MemtableBuilderProvider; use crate::memtable::bulk::CompactDispatcher; use crate::metrics::{REGION_COUNT, REQUEST_WAIT_TIME, WRITE_STALLING}; use crate::region::opener::PartitionExprFetcherRef; use crate::region::{ - CatchupRegions, CatchupRegionsRef, MitoRegion, MitoRegionRef, OpeningRegions, - OpeningRegionsRef, RegionMap, RegionMapRef, + CatchupRegions, CatchupRegionsRef, MitoRegionRef, OpeningRegions, OpeningRegionsRef, RegionMap, + RegionMapRef, }; use crate::request::{ BackgroundNotify, BulkInsertRequest, DdlRequest, OptionOutputTx, SenderBulkRequest, @@ -92,8 +92,11 @@ use crate::series_index::{ use crate::sst::file::RegionFileId; use crate::sst::file_ref::FileReferenceManagerRef; use crate::sst::index::IndexBuildScheduler; +use crate::sst::index::handler::IndexKindProviderRef; use crate::sst::index::intermediate::IntermediateManager; use crate::sst::index::puffin_manager::PuffinManagerFactory; +use crate::sst::index::registry::{IndexRegistry, IndexRegistryRef}; +use crate::tail_replay::TailReplayLimits; #[cfg(feature = "hdfs-object-store")] use crate::temp_file_sweeper; use crate::time_provider::{StdTimeProvider, TimeProviderRef}; @@ -166,6 +169,7 @@ pub(crate) struct WorkerGroup { /// Gc limiter to limit concurrent gc jobs. gc_limiter: GcLimiterRef, node_lease: Arc, + granted_leases: Arc, /// Object store manager. object_store_manager: ObjectStoreManagerRef, /// Puffin manager factory. @@ -217,6 +221,7 @@ impl WorkerGroup { let memtable_compact_dispatcher = Arc::new(CompactDispatcher::new(config.max_background_compactions)); let flush_semaphore = Arc::new(Semaphore::new(config.max_background_flushes)); + let tail_replay_limits = TailReplayLimits::new(&config); // We use another scheduler to avoid purge jobs blocking other jobs. let purge_scheduler = Arc::new(LocalScheduler::new(config.max_background_purges)); let upload_store_wrapper = plugins.get::(); @@ -264,6 +269,7 @@ impl WorkerGroup { let sweep_limiter = (config.gc.max_concurrent_gc_job > 0) .then(|| Arc::new(Semaphore::new(config.gc.max_concurrent_gc_job))); let node_lease = Arc::new(NodeLease::default()); + let granted_leases = Arc::new(GrantedLeases::default()); let staging_regions = StagingRegionsRef::default(); let wal = Wal::new(log_store); @@ -295,9 +301,11 @@ impl WorkerGroup { file_ref_manager: file_ref_manager.clone(), partition_expr_fetcher: partition_expr_fetcher.clone(), flush_semaphore: flush_semaphore.clone(), + tail_replay_limits: tail_replay_limits.clone(), #[cfg(feature = "hdfs-object-store")] sweep_limiter: sweep_limiter.clone(), node_lease: node_lease.clone(), + granted_leases: granted_leases.clone(), staging_regions: staging_regions.clone(), } .start() @@ -314,6 +322,7 @@ impl WorkerGroup { file_ref_manager, gc_limiter, node_lease, + granted_leases, object_store_manager, puffin_manager_factory, intermediate_manager, @@ -422,11 +431,25 @@ impl WorkerGroup { &self.node_lease } + /// Returns the latest lease each region of this group received. + pub(crate) fn granted_leases(&self) -> &GrantedLeases { + &self.granted_leases + } + /// Asks the worker of `region` to replay its pending tails, if it has any, without waiting. - pub(crate) fn notify_writable(&self, region: &MitoRegion) { + pub(crate) fn notify_writable(&self, region: &MitoRegionRef) { handle_tail_replay::notify_writable(&self.worker(region.region_id).sender, region); } + pub(crate) fn node_lease_permit(&self) -> Arc { + self.node_lease.clone() + } + + /// Asks the worker of `region` to cancel its tail replay, if one runs, without waiting. + pub(crate) fn notify_cannot_replay(&self, region: &MitoRegionRef) { + handle_tail_replay::notify_cannot_replay(&self.worker(region.region_id).sender, region); + } + /// Get worker for specific `region_id`. pub(crate) fn worker(&self, region_id: RegionId) -> &RegionWorker { let index = region_id_to_index(region_id, self.workers.len()); @@ -494,6 +517,7 @@ impl WorkerGroup { config.max_background_compactions, )); let flush_semaphore = Arc::new(Semaphore::new(config.max_background_flushes)); + let tail_replay_limits = TailReplayLimits::new(&config); let purge_scheduler = Arc::new(LocalScheduler::new(config.max_background_flushes)); let puffin_manager_factory = PuffinManagerFactory::new( &config.index.aux_path, @@ -543,6 +567,7 @@ impl WorkerGroup { let sweep_limiter = (config.gc.max_concurrent_gc_job > 0) .then(|| Arc::new(Semaphore::new(config.gc.max_concurrent_gc_job))); let node_lease = Arc::new(NodeLease::default()); + let granted_leases = Arc::new(GrantedLeases::default()); let staging_regions = StagingRegionsRef::default(); let wal = Wal::new(log_store); let workers = (0..config.num_workers) @@ -573,9 +598,11 @@ impl WorkerGroup { file_ref_manager: file_ref_manager.clone(), partition_expr_fetcher: partition_expr_fetcher.clone(), flush_semaphore: flush_semaphore.clone(), + tail_replay_limits: tail_replay_limits.clone(), #[cfg(feature = "hdfs-object-store")] sweep_limiter: sweep_limiter.clone(), node_lease: node_lease.clone(), + granted_leases: granted_leases.clone(), staging_regions: staging_regions.clone(), } .start() @@ -592,6 +619,7 @@ impl WorkerGroup { file_ref_manager, gc_limiter, node_lease, + granted_leases, object_store_manager, puffin_manager_factory, intermediate_manager, @@ -660,6 +688,14 @@ pub(crate) fn worker_init_check_delay() -> Duration { Duration::from_secs(init_check_delay) } +/// Constructs the shared registry for region creation and index maintenance. +fn index_registry( + config: &MitoConfig, + provider: Option, +) -> Result { + IndexRegistry::from_config(config, provider).map(Arc::new) +} + /// Worker start config. struct WorkerStarter { id: WorkerId, @@ -689,11 +725,14 @@ struct WorkerStarter { file_ref_manager: FileReferenceManagerRef, partition_expr_fetcher: PartitionExprFetcherRef, flush_semaphore: Arc, + /// Limits of the node's tail replays. + tail_replay_limits: TailReplayLimits, #[cfg(feature = "hdfs-object-store")] /// Limiter for the temporary file sweeps, or `None` if the datanode allows /// no concurrent GC job. sweep_limiter: Option>, node_lease: Arc, + granted_leases: Arc, staging_regions: StagingRegionsRef, } @@ -797,10 +836,12 @@ impl WorkerStarter { file_ref_manager: self.file_ref_manager.clone(), partition_expr_fetcher: self.partition_expr_fetcher, flush_semaphore: self.flush_semaphore, + tail_replay_limits: self.tail_replay_limits, plugins: self.plugins, #[cfg(feature = "hdfs-object-store")] sweep_limiter: self.sweep_limiter, node_lease: self.node_lease, + granted_leases: self.granted_leases, staging_regions: self.staging_regions, tail_replays: HashMap::new(), }; @@ -1255,6 +1296,8 @@ struct RegionWorkerLoop { partition_expr_fetcher: PartitionExprFetcherRef, /// Semaphore to control flush concurrency. flush_semaphore: Arc, + /// Limits of the node's tail replays. + tail_replay_limits: TailReplayLimits, /// Plugins for flush hooks. plugins: Plugins, #[cfg(feature = "hdfs-object-store")] @@ -1262,6 +1305,7 @@ struct RegionWorkerLoop { /// no concurrent GC job. sweep_limiter: Option>, node_lease: Arc, + granted_leases: Arc, /// Staging regions of this node that have received writes. staging_regions: StagingRegionsRef, /// Running tail replays, which stay here until they report their end. @@ -1725,7 +1769,7 @@ impl RegionWorkerLoop { self.handle_index_build_stopped(region_id, req).await } BackgroundNotify::IndexBuildRetry(req) => { - self.handle_rebuild_index(req, OptionOutputTx::new(None)) + self.handle_rebuild_index_inner(req, OptionOutputTx::new(None), true) .await } BackgroundNotify::CompactionFinished(req) => { @@ -1754,6 +1798,9 @@ impl RegionWorkerLoop { self.handle_region_reloaded(region_id, old, result).await } BackgroundNotify::RegionBecameWritable => self.maybe_replay_tails(region_id), + BackgroundNotify::RegionCannotReplay { region } => { + self.handle_region_cannot_replay(region_id, region) + } BackgroundNotify::TailReplayCommitted { region, edit, @@ -1769,7 +1816,8 @@ impl RegionWorkerLoop { if should_dispatch_pending { self.dispatch_pending_region_requests(region_id).await; } - // A commit that found a newer manifest fenced the region before its job reported here. + // A commit or a tail replay that found a newer manifest fenced the region before its job + // reported here. if !is_reload_result { self.maybe_reload_region(region_id); } @@ -1847,12 +1895,24 @@ impl RegionWorkerLoop { } // Closes remaining regions. let regions = self.regions.list_regions(); - for region in regions { + for region in ®ions { region.deactivate_region_manifest_size_metric(); region.stop().await; } + // Another engine may open these regions from the same storage after the stop. Regions + // closed earlier are not waited for; a datanode or standalone shutdown closes every region + // first, so there this only covers regions whose close failed. + join_all( + regions + .iter() + .map(|region| region.manifest_ctx.wait_for_checkpoint_after_stop()), + ) + .await; self.regions.clear(); + for region in regions { + self.granted_leases.remove(region.region_id); + } } /// Notifies the whole group that a flush job is finished so other @@ -1920,6 +1980,14 @@ impl WorkerListener { } } + /// A tail replay that found a newer manifest is about to wait to fence the region. + pub(crate) fn on_tail_fence_begin(&self, _region_id: RegionId) { + #[cfg(any(test, feature = "test"))] + if let Some(listener) = &self.listener { + listener.on_tail_fence_begin(_region_id); + } + } + /// A round of tail replay failed. pub(crate) fn on_tail_replay_failed(&self, _region_id: RegionId, _error: &crate::error::Error) { #[cfg(any(test, feature = "test"))] @@ -2131,6 +2199,13 @@ impl WorkerListener { } } + pub(crate) async fn on_index_build_stopped(&self, _region_file_id: RegionFileId) { + #[cfg(any(test, feature = "test"))] + if let Some(listener) = &self.listener { + listener.on_index_build_stopped(_region_file_id).await; + } + } + pub(crate) async fn on_index_build_before_manifest_commit( &self, _region_file_id: RegionFileId, diff --git a/src/mito2/src/worker/handle_close.rs b/src/mito2/src/worker/handle_close.rs index 69029b44f1a..03da3578a58 100644 --- a/src/mito2/src/worker/handle_close.rs +++ b/src/mito2/src/worker/handle_close.rs @@ -126,6 +126,7 @@ impl RegionWorkerLoop { let Some(region) = self.regions.remove_region(region_id) else { return; }; + self.granted_leases.remove(region_id); region.deactivate_region_manifest_size_metric(); self.cancel_tail_replay(region_id); region.stop().await; diff --git a/src/mito2/src/worker/handle_compaction.rs b/src/mito2/src/worker/handle_compaction.rs index b22ed7f27ff..6bc8d13a5da 100644 --- a/src/mito2/src/worker/handle_compaction.rs +++ b/src/mito2/src/worker/handle_compaction.rs @@ -27,9 +27,24 @@ use crate::request::{ BuildIndexRequest, CompactionFailed, CompactionFinished, CompactionUnitNotification, OnFailure, OptionOutputTx, }; +use crate::sst::file::FileMeta; use crate::sst::index::IndexBuildType; +use crate::sst::index::kind::{ExtensionIndexKind, IndexKind}; use crate::worker::RegionWorkerLoop; +/// Completed extensions prove the writer built this output's indexes together. +/// A background replacement would otherwise erase those extension blobs. +fn needs_background_indexes(file: &FileMeta) -> bool { + !ExtensionIndexKind::ALL.iter().any(|kind| { + let index_type = IndexKind::Extension(*kind).index_type(); + file.available_indexes.contains(&index_type) + || file + .indexes + .iter() + .any(|column| column.created_indexes.contains(&index_type)) + }) +} + fn made_progress(files_to_add: usize, files_to_remove: usize) -> bool { files_to_add > 0 || files_to_remove > files_to_add } @@ -71,14 +86,19 @@ impl RegionWorkerLoop { plan_id, Ok(progress), ); + let files_to_index = edit + .files_to_add + .into_iter() + .filter(needs_background_indexes) + .collect::>(); if self.config.index.build_mode == IndexBuildMode::Async - && !edit.files_to_add.is_empty() + && !files_to_index.is_empty() { self.handle_rebuild_index( BuildIndexRequest { region_id, build_type: IndexBuildType::Compact, - file_metas: edit.files_to_add, + file_metas: files_to_index, result_senders: Vec::new(), }, OptionOutputTx::new(None), @@ -231,7 +251,10 @@ impl RegionWorkerLoop { region.file_purger.clone(), ); - let index_build_file_metas = std::mem::take(&mut request.edit.files_to_add); + let index_build_file_metas = std::mem::take(&mut request.edit.files_to_add) + .into_iter() + .filter(needs_background_indexes) + .collect::>(); // compaction finished. request.on_success(); diff --git a/src/mito2/src/worker/handle_create.rs b/src/mito2/src/worker/handle_create.rs index 5c7da5779f3..3dd9c8e5aca 100644 --- a/src/mito2/src/worker/handle_create.rs +++ b/src/mito2/src/worker/handle_create.rs @@ -22,9 +22,10 @@ use store_api::storage::RegionId; use crate::error::Result; use crate::region::opener::{RegionOpener, check_recovered_region}; +use crate::sst::index::handler::IndexKindProviderRef; #[cfg(feature = "hdfs-object-store")] use crate::temp_file_sweeper; -use crate::worker::RegionWorkerLoop; +use crate::worker::{RegionWorkerLoop, index_registry}; impl RegionWorkerLoop { pub(crate) async fn handle_create_request( @@ -57,6 +58,7 @@ impl RegionWorkerLoop { // Create a MitoRegion from the RegionMetadata. let requirements = request.requirements; + let registry = index_registry(&self.config, self.plugins.get::())?; let opener = RegionOpener::new( region_id, &request.table_dir, @@ -76,7 +78,8 @@ impl RegionWorkerLoop { .cache(Some(self.cache_manager.clone())) .series_index_store(self.series_index_store.clone()) .series_index_purger(self.series_index_purger.clone()) - .hook(self.plugins.get()); + .hook(self.plugins.get()) + .with_index_registry(registry); opener.ensure_region_requirements(requirements)?; diff --git a/src/mito2/src/worker/handle_drop.rs b/src/mito2/src/worker/handle_drop.rs index 8c55733da9e..709618428b3 100644 --- a/src/mito2/src/worker/handle_drop.rs +++ b/src/mito2/src/worker/handle_drop.rs @@ -114,6 +114,7 @@ where region.stop().await; // Removes this region from region map to prevent other requests from accessing this region self.regions.remove_region(region_id); + self.granted_leases.remove(region_id); region.deactivate_region_manifest_size_metric(); self.cancel_tail_replay(region_id); self.dropping_regions.insert_region(region.clone()); diff --git a/src/mito2/src/worker/handle_flush.rs b/src/mito2/src/worker/handle_flush.rs index 5473799b2d2..e51845c71ce 100644 --- a/src/mito2/src/worker/handle_flush.rs +++ b/src/mito2/src/worker/handle_flush.rs @@ -27,7 +27,7 @@ use store_api::storage::RegionId; use crate::config::{IndexBuildMode, MitoConfig}; use crate::error::{FlushRegionSnafu, RegionBusySnafu, RegionNotFoundSnafu, Result}; -use crate::flush::{FlushReason, RegionFlushTask}; +use crate::flush::{FlushReason, MemtableSstWriter, RegionFlushTask}; use crate::manifest::action::cap_wal_release; use crate::region::version::VersionRef; use crate::region::{MitoRegion, MitoRegionRef}; @@ -281,17 +281,16 @@ impl RegionWorkerLoop { reason, senders: Vec::new(), request_sender: self.sender.clone(), - access_layer: region.access_layer.clone(), listener: self.listener.clone(), - engine_config, - // The request-provided size (e.g. manual flush) takes precedence over the - // region option. - row_group_size: row_group_size.or(region.version().options.max_row_group_row_count), - cache_manager: self.cache_manager.clone(), manifest_ctx: region.manifest_ctx.clone(), - index_options: region.version().options.index_options.clone(), - flush_semaphore: self.flush_semaphore.clone(), - partition_expr: region.metadata().partition_expr.clone(), + sst_writer: MemtableSstWriter::new_flush( + region, + reason, + row_group_size, + engine_config, + self.cache_manager.clone(), + self.flush_semaphore.clone(), + ), durability_barrier: self .wal .durability_barrier(region.region_id, ®ion.provider), diff --git a/src/mito2/src/worker/handle_rebuild_index.rs b/src/mito2/src/worker/handle_rebuild_index.rs index 502b5dfc91d..e897a113be5 100644 --- a/src/mito2/src/worker/handle_rebuild_index.rs +++ b/src/mito2/src/worker/handle_rebuild_index.rs @@ -19,6 +19,7 @@ use std::sync::Arc; use api::v1::region::build_index_request; use common_telemetry::{debug, warn}; +use snafu::{IntoError, ResultExt}; use store_api::metadata::RegionMetadataRef; use store_api::region_request::RegionBuildIndexRequest; use store_api::storage::{FileId, RegionId}; @@ -26,7 +27,8 @@ use tokio::sync::mpsc; use crate::cache::CacheStrategy; use crate::error::{ - IndexBuildIncompleteSnafu, InvalidRequestSnafu, RegionStateSnafu, Result, WorkerStoppedSnafu, + BuildIndexAsyncSnafu, ExternalSnafu, IndexBuildIncompleteSnafu, InvalidRequestSnafu, + RegionStateSnafu, Result, WorkerStoppedSnafu, }; use crate::manifest::action::RegionEdit; use crate::metrics::INDEX_PUBLICATION_STALE_TOTAL; @@ -34,11 +36,13 @@ use crate::region::options::IndexOptions; use crate::region::{IndexBuildSource, MitoRegionRef, RegionLeaderState, RegionRoleState}; use crate::request::{BuildIndexRequest, IndexBuildFinished, IndexBuildStopped, OptionOutputTx}; use crate::sst::file::{self, FileHandle, FileMeta, RegionFileId, RegionIndexId}; +use crate::sst::index::handler::{IndexKindProviderRef, PlanContext}; +use crate::sst::index::registry::{IndexRegistry, IndexRegistryRef}; use crate::sst::index::{ IndexBuildOutcome, IndexBuildTask, IndexBuildType, IndexerBuilderImpl, ResultMpscSender, cleanup_stale_index_caches, }; -use crate::worker::RegionWorkerLoop; +use crate::worker::{RegionWorkerLoop, index_registry}; /// Parts of a region version that index build tasks need. /// @@ -54,11 +58,12 @@ impl RegionWorkerLoop { &self, region: &MitoRegionRef, snapshot: &IndexBuildSnapshot, - file: FileHandle, - file_meta: FileMeta, + registry: IndexRegistryRef, + source: (FileHandle, FileMeta), build_type: IndexBuildType, result_senders: Vec, ) -> IndexBuildTask { + let (file, file_meta) = source; let access_layer = region.access_layer.clone(); let puffin_manager = if let Some(write_cache) = self.cache_manager.write_cache() { @@ -74,14 +79,10 @@ impl RegionWorkerLoop { }; let indexer_builder_ref = Arc::new(IndexerBuilderImpl { + index_build_inputs: None, build_type: build_type.clone(), metadata: snapshot.metadata.clone(), - index_build_inputs: None, - registry: Arc::new(crate::sst::index::registry::IndexRegistry::new( - self.config.inverted_index.clone(), - self.config.fulltext_index.clone(), - self.config.bloom_filter_index.clone(), - )), + registry: registry.clone(), index_options: snapshot.index_options.clone(), intermediate_manager, puffin_manager, @@ -107,6 +108,25 @@ impl RegionWorkerLoop { } } + /// Validates providers and the current plan before selecting or scheduling files. + fn prepare_rebuild_registry( + &self, + snapshot: &IndexBuildSnapshot, + build_type: IndexBuildType, + ) -> Result { + // Post-flush/compaction tasks build the built-in indexes of a new SST. + // Compaction extension construction belongs to the compaction writer. + let provider = match build_type { + IndexBuildType::Flush | IndexBuildType::Compact => None, + IndexBuildType::Manual | IndexBuildType::SchemaChange => { + self.plugins.get::() + } + }; + let registry = index_registry(&self.config, provider)?; + validate_rebuild_plan(®istry, snapshot, build_type)?; + Ok(registry) + } + /// Handles manual build index requests. pub(crate) async fn handle_build_index_request( &mut self, @@ -165,9 +185,19 @@ impl RegionWorkerLoop { } pub(crate) async fn handle_rebuild_index( + &mut self, + request: BuildIndexRequest, + sender: OptionOutputTx, + ) { + self.handle_rebuild_index_inner(request, sender, false) + .await; + } + + pub(crate) async fn handle_rebuild_index_inner( &mut self, request: BuildIndexRequest, mut sender: OptionOutputTx, + is_retry: bool, ) { let region_id = request.region_id; let Some(region) = self.regions.writable_region_or(region_id, &mut sender) else { @@ -223,19 +253,10 @@ impl RegionWorkerLoop { file_meta.cloned() }; - let build_tasks = if request.file_metas.is_empty() { - // If no specific files are provided, find files whose index is inconsistent with the region metadata. - // Check the version rather than the manifest: a publication committed - // to the manifest but not yet applied is still invisible to queries. - // Its build still holds the file, so the manual task waits for it. + // Collect eligible inputs before currency selection. + let candidates = if request.file_metas.is_empty() { all_files .values() - .filter(|file| { - !file.meta_ref().is_index_consistent_with_region( - &snapshot.metadata.column_metadatas, - &snapshot.index_options, - ) - }) .filter_map(|file| { let file_meta = current_file_meta(file.meta_ref().file_id)?; Some((file.clone(), file_meta)) @@ -253,6 +274,44 @@ impl RegionWorkerLoop { .collect::>() }; + let registry = match self.prepare_rebuild_registry(&snapshot, request.build_type.clone()) { + Ok(registry) => registry, + Err(err) => { + warn!(err; + "Failed to prepare index build, region_id: {}, build_type: {:?}, candidate_files: {}", + region_id, request.build_type, candidates.len() + ); + let err = Arc::new(err); + for result_sender in &request.result_senders { + let _ = result_sender + .send(Err( + BuildIndexAsyncSnafu { region_id }.into_error(err.clone()) + )) + .await; + } + sender.send(Err(BuildIndexAsyncSnafu { region_id }.into_error(err))); + return; + } + }; + let build_tasks = if request.file_metas.is_empty() { + // Check the version rather than the manifest: a publication committed + // to the manifest but not yet applied is still invisible to queries. + // Its build still holds the file, so the manual task waits for it. + candidates + .into_iter() + .filter(|(file, _)| { + index_needs_rebuild( + ®istry, + &snapshot, + file.meta_ref(), + request.build_type.clone(), + ) + }) + .collect::>() + } else { + candidates + }; + if build_tasks.is_empty() { debug!( "No files need to build index for region {}, request: {:?}", @@ -292,14 +351,20 @@ impl RegionWorkerLoop { let task = self.new_index_build_task( ®ion, &snapshot, - file_handle, - file_meta.as_ref().clone(), + registry.clone(), + (file_handle, file_meta.as_ref().clone()), request.build_type.clone(), result_senders, ); - self.index_build_scheduler - .schedule_build(®ion.version_control, task) - .await; + if is_retry { + self.index_build_scheduler + .schedule_retry(®ion.version_control, task) + .await; + } else { + self.index_build_scheduler + .schedule_build(®ion.version_control, task) + .await; + } } drop(tx); @@ -336,10 +401,11 @@ impl RegionWorkerLoop { let incomplete = present .into_iter() .filter(|file_id| { - !manifest.files[file_id].is_index_consistent_with_region( + let file = &manifest.files[file_id]; + !file.is_index_consistent_with_region( &snapshot.metadata.column_metadatas, &snapshot.index_options, - ) + ) || index_needs_rebuild(®istry, &snapshot, file, build_type.clone()) }) .collect::>(); let result = if incomplete.is_empty() { @@ -449,5 +515,349 @@ impl RegionWorkerLoop { ) { self.index_build_scheduler .on_task_stopped(region_id, request.file_id); + self.listener + .on_index_build_stopped(RegionFileId::new(region_id, request.file_id)) + .await; + } +} + +/// Rejects invalid current options before selecting files or scheduling any task. +fn validate_rebuild_plan( + registry: &IndexRegistry, + snapshot: &IndexBuildSnapshot, + build_type: IndexBuildType, +) -> Result<()> { + // New SSTs need built-in indexes even when optional providers are unavailable. + // Explicit maintenance follows current options, allowing removed sketch options + // to discard their historical descriptors without requiring a provider. + if matches!( + build_type, + IndexBuildType::Manual | IndexBuildType::SchemaChange + ) { + registry + .validate_schema_kinds(&snapshot.metadata) + .with_context(|_| ExternalSnafu { + context: "validating index handlers for rebuild".to_string(), + })?; + } + let plan = registry.plan(&PlanContext { + metadata: &snapshot.metadata, + index_options: &snapshot.index_options, + build_type, + existing_indexes: &[], + }); + plan.check_success().context(BuildIndexAsyncSnafu { + region_id: snapshot.metadata.region_id, + }) +} + +fn index_needs_rebuild( + registry: &IndexRegistry, + snapshot: &IndexBuildSnapshot, + file: &FileMeta, + build_type: IndexBuildType, +) -> bool { + let context = PlanContext { + metadata: &snapshot.metadata, + index_options: &snapshot.index_options, + build_type, + existing_indexes: &file.indexes, + }; + let plan = registry.plan(&context); + !plan.is_current(file, &context) +} + +#[cfg(test)] +mod tests { + use common_error::ext::ErrorExt; + use common_error::status_code::StatusCode; + use store_api::metadata::RegionMetadataBuilder; + + use super::*; + use crate::sst::file::ColumnIndexMetadata; + use crate::sst::index::handler::{ + BuildContext, IndexCreator, IndexKindHandler, PlanEntry, PlannedIndex, + }; + use crate::sst::index::kind::{ExtensionIndexKind, IndexKind}; + use crate::test_util::CreateRequestBuilder; + + #[derive(Debug)] + struct MaintenanceHandler; + + impl IndexKindHandler for MaintenanceHandler { + fn kinds(&self) -> &[IndexKind] { + &[IndexKind::Extension(ExtensionIndexKind::Hll)] + } + + fn validate( + &self, + _context: &PlanContext<'_>, + ) -> std::result::Result<(), common_error::ext::BoxedError> { + Ok(()) + } + + fn plan( + &self, + context: &PlanContext<'_>, + ) -> std::result::Result>, common_error::ext::BoxedError> + { + let existing = context.existing_indexes.iter().any(|column| { + column + .created_indexes + .contains(&crate::sst::file::IndexType::HllIndex) + }); + Ok((existing + && matches!( + context.build_type, + IndexBuildType::Manual | IndexBuildType::SchemaChange + )) + .then(|| Arc::new(Self) as Arc)) + } + } + + #[async_trait::async_trait] + impl PlannedIndex for MaintenanceHandler { + fn kinds(&self) -> &[IndexKind] { + IndexKindHandler::kinds(self) + } + + fn entries(&self) -> &[PlanEntry] { + &[] + } + + async fn build( + &self, + _context: &BuildContext<'_>, + ) -> std::result::Result>, common_error::ext::BoxedError> + { + Ok(None) + } + + fn is_current(&self, _file: &FileMeta, _context: &PlanContext<'_>) -> bool { + false + } + } + + fn snapshot_without_builtin_indexes() -> IndexBuildSnapshot { + let request = CreateRequestBuilder::new().build(); + let mut metadata = RegionMetadataBuilder::new(RegionId::new(1, 1)); + metadata.primary_key(request.primary_key); + for mut column in request.column_metadatas { + column.column_schema.set_inverted_index(false); + column.column_schema.unset_skipping_options().unwrap(); + metadata.push_column_metadata(column); + } + IndexBuildSnapshot { + metadata: Arc::new(metadata.build().unwrap()), + index_options: IndexOptions::default(), + } + } + + #[test] + fn test_rebuild_selection_uses_registered_currency_and_empty_maintenance_plans() { + let snapshot = snapshot_without_builtin_indexes(); + let builtin = + IndexRegistry::new(Default::default(), Default::default(), Default::default()); + let mut registered = builtin.clone(); + registered.register(Arc::new(MaintenanceHandler)).unwrap(); + let empty = FileMeta::default(); + let mut existing = empty.clone(); + existing.indexes.push(ColumnIndexMetadata { + column_id: 0, + created_indexes: smallvec::smallvec![crate::sst::file::IndexType::HllIndex], + ..Default::default() + }); + // Missing owners are rejected before selection; currency only compares + // the plans of registered handlers with the persisted indexes. + assert!( + builtin + .validate_required_kinds(&snapshot.metadata, [&existing]) + .is_err() + ); + for reason in [IndexBuildType::Manual, IndexBuildType::SchemaChange] { + assert!(!index_needs_rebuild( + ®istered, + &snapshot, + &empty, + reason.clone() + )); + assert!( + index_needs_rebuild(®istered, &snapshot, &existing, reason), + "an explicit empty maintenance plan still requests publication" + ); + } + for reason in [IndexBuildType::Flush, IndexBuildType::Compact] { + assert!(!index_needs_rebuild( + ®istered, + &snapshot, + &existing, + reason + )); + } + } + + #[derive(Debug)] + struct FailingPlanHandler; + + impl IndexKindHandler for FailingPlanHandler { + fn kinds(&self) -> &[IndexKind] { + &[IndexKind::Extension(ExtensionIndexKind::Hll)] + } + + fn validate( + &self, + _context: &PlanContext<'_>, + ) -> std::result::Result<(), common_error::ext::BoxedError> { + Ok(()) + } + + fn plan( + &self, + _context: &PlanContext<'_>, + ) -> std::result::Result>, common_error::ext::BoxedError> + { + Err(common_error::ext::BoxedError::new( + common_error::ext::PlainError::new( + "injected plan failure".into(), + common_error::status_code::StatusCode::Internal, + ), + )) + } + } + + #[test] + fn test_failed_plan_requires_rebuild_even_without_planned_entries() { + let snapshot = snapshot_without_builtin_indexes(); + let mut registry = + IndexRegistry::new(Default::default(), Default::default(), Default::default()); + registry.register(Arc::new(FailingPlanHandler)).unwrap(); + let file = FileMeta { + indexes: vec![ColumnIndexMetadata { + column_id: 0, + created_indexes: smallvec::smallvec![crate::sst::file::IndexType::HllIndex], + ..Default::default() + }], + ..Default::default() + }; + assert!( + registry + .validate_required_kinds(&snapshot.metadata, [&file]) + .is_ok() + ); + for reason in [IndexBuildType::Manual, IndexBuildType::SchemaChange] { + let plan = registry.plan(&PlanContext { + metadata: &snapshot.metadata, + index_options: &snapshot.index_options, + build_type: reason.clone(), + existing_indexes: &file.indexes, + }); + assert!(plan.entries().next().is_none()); + assert!(plan.check_success().is_err()); + assert!(index_needs_rebuild(®istry, &snapshot, &file, reason)); + } + } + + #[derive(Debug)] + struct DuplicateKindProvider; + + impl crate::sst::index::handler::IndexKindProvider for DuplicateKindProvider { + fn handlers(&self) -> Vec> { + vec![Arc::new(MaintenanceHandler), Arc::new(MaintenanceHandler)] + } + } + + #[test] + fn test_rebuild_registry_registration_failure_is_not_provider_absence() { + let config = crate::config::MitoConfig::default(); + assert!(index_registry(&config, None).is_ok()); + let error = index_registry(&config, Some(Arc::new(DuplicateKindProvider))).unwrap_err(); + assert_eq!(error.status_code(), StatusCode::InvalidArguments); + assert!(error.to_string().contains("registering index handlers")); + } + + #[test] + fn test_rebuild_preflight_rejects_plan_failure_before_file_selection() { + let snapshot = snapshot_without_builtin_indexes(); + let mut registry = + IndexRegistry::new(Default::default(), Default::default(), Default::default()); + assert!(validate_rebuild_plan(®istry, &snapshot, IndexBuildType::Manual).is_ok()); + registry.register(Arc::new(FailingPlanHandler)).unwrap(); + assert!(validate_rebuild_plan(®istry, &snapshot, IndexBuildType::Manual).is_err()); + } + + #[test] + fn test_required_handlers_cover_schema_and_both_persisted_locations() { + use crate::sst::file::IndexType; + let registry = + IndexRegistry::new(Default::default(), Default::default(), Default::default()); + for kind in [IndexType::HllIndex, IndexType::KllIndex, IndexType::MgIndex] { + let mut snapshot = snapshot_without_builtin_indexes(); + let schema = + &mut Arc::make_mut(&mut snapshot.metadata).column_metadatas[0].column_schema; + let (key, value) = match kind { + IndexType::HllIndex => (datatypes::schema::HLL_KEY, r#"{"precision":10}"#), + IndexType::KllIndex => (datatypes::schema::KLL_KEY, r#"{"capacity":64}"#), + IndexType::MgIndex => (datatypes::schema::MG_KEY, r#"{"max-counters":64}"#), + _ => unreachable!(), + }; + schema.mut_metadata().insert(key.into(), value.into()); + assert!( + registry + .validate_required_kinds(&snapshot.metadata, []) + .is_err() + ); + assert!(validate_rebuild_plan(®istry, &snapshot, IndexBuildType::Manual).is_err()); + assert!( + registry + .plan(&PlanContext { + metadata: &snapshot.metadata, + index_options: &snapshot.index_options, + build_type: IndexBuildType::Flush, + existing_indexes: &[], + }) + .check_success() + .is_ok() + ); + let snapshot = snapshot_without_builtin_indexes(); + for column_level in [false, true] { + let mut file = FileMeta::default(); + if column_level { + file.indexes.push(ColumnIndexMetadata { + column_id: 0, + created_indexes: smallvec::smallvec![kind], + ..Default::default() + }); + } else { + file.available_indexes.push(kind); + } + // Historical descriptors alone do not require the provider. + assert!( + validate_rebuild_plan(®istry, &snapshot, IndexBuildType::Manual).is_ok() + ); + assert!(index_needs_rebuild( + ®istry, + &snapshot, + &file, + IndexBuildType::Manual + )); + // Compaction's strict input validation remains available to its writer. + assert!( + registry + .validate_required_kinds(&snapshot.metadata, [&file]) + .is_err() + ); + } + } + let snapshot = snapshot_without_builtin_indexes(); + let legacy = FileMeta { + available_indexes: smallvec::smallvec![IndexType::VectorIndex], + ..Default::default() + }; + assert!(validate_rebuild_plan(®istry, &snapshot, IndexBuildType::Manual).is_ok()); + assert!( + registry + .validate_required_kinds(&snapshot.metadata, [&legacy]) + .is_ok() + ); } } diff --git a/src/mito2/src/worker/handle_reload.rs b/src/mito2/src/worker/handle_reload.rs index 948e79fa0a8..b489c84aef9 100644 --- a/src/mito2/src/worker/handle_reload.rs +++ b/src/mito2/src/worker/handle_reload.rs @@ -12,7 +12,8 @@ // See the License for the specific language governing permissions and // limitations under the License. -//! Reloading a region that a manifest version conflict fenced. +//! Reloading a region fenced by a manifest version conflict, or by a failed tail replay round +//! that found a newer manifest. use std::sync::Arc; @@ -28,7 +29,8 @@ use crate::worker::RegionWorkerLoop; impl RegionWorkerLoop { /// Starts reloading the region from its manifest and this node's WAL if a manifest version - /// conflict fenced it and no catchup or reload of it runs. + /// conflict or a failed tail replay round that found a newer manifest fenced it, and no + /// catchup or reload of it runs. pub(crate) fn maybe_reload_region(&mut self, region_id: RegionId) { let Some(region) = self.regions.get_region(region_id) else { return; @@ -66,6 +68,9 @@ impl RegionWorkerLoop { let sender = self.sender.clone(); common_runtime::spawn_global(async move { let result = async { + // The fenced instance is stopped, but its last checkpoint may still be writing + // the manifest that the reload reads. + region.manifest_ctx.wait_for_checkpoint_after_stop().await; // The replay reads only what the log store has made durable. durability_barrier.wait(last_entry_id).await?; opener.open(&config, &wal).await diff --git a/src/mito2/src/worker/handle_tail_replay.rs b/src/mito2/src/worker/handle_tail_replay.rs index b859eef8fb3..46d6b2f6911 100644 --- a/src/mito2/src/worker/handle_tail_replay.rs +++ b/src/mito2/src/worker/handle_tail_replay.rs @@ -22,9 +22,8 @@ use store_api::storage::RegionId; use tokio::sync::mpsc::Sender; use crate::config::IndexBuildMode; -use crate::flush::FlushReason; use crate::manifest::action::{PendingTail, RegionEdit}; -use crate::region::{MitoRegion, MitoRegionRef}; +use crate::region::MitoRegionRef; use crate::request::{BackgroundNotify, BuildIndexRequest, OptionOutputTx, WorkerRequestWithTime}; use crate::schedule::CancellableTaskState; use crate::sst::index::IndexBuildType; @@ -43,15 +42,17 @@ impl RegionWorkerLoop { info!("Replaying the pending WAL tails of region {region_id}"); let state = CancellableTaskState::new(); let task = TailReplayTask { - flush_task: self.new_flush_task( + sst_writer: self.tail_replay_limits.new_sst_writer( ®ion, - FlushReason::TailReplay, - None, self.config.clone(), + self.cache_manager.clone(), ), region, node_id: self.file_ref_manager.node_id(), wal: self.wal.clone(), + listener: self.listener.clone(), + request_sender: self.sender.clone(), + limits: self.tail_replay_limits.clone(), state: state.clone(), }; self.tail_replays.insert(region_id, state); @@ -109,6 +110,15 @@ impl RegionWorkerLoop { self.schedule_compaction(®ion).await; } + /// Cancels the tail replay of the region unless `region`, the instance a role change made + /// unable to replay, was replaced since. + pub(crate) fn handle_region_cannot_replay(&self, region_id: RegionId, region: MitoRegionRef) { + let registered = self.regions.get_region(region_id); + if registered.is_some_and(|registered| Arc::ptr_eq(®istered, ®ion)) { + self.cancel_tail_replay(region_id); + } + } + /// Forgets the ended tail replay of the region and starts another if it still has tails. pub(crate) fn handle_tail_replay_ended(&mut self, region_id: RegionId) { self.tail_replays.remove(®ion_id); @@ -119,7 +129,7 @@ impl RegionWorkerLoop { /// Asks the worker to replay the pending tails of a region that became writable, if it has /// any, without waiting. -pub(crate) fn notify_writable(sender: &Sender, region: &MitoRegion) { +pub(crate) fn notify_writable(sender: &Sender, region: &MitoRegionRef) { if !region.version().has_pending_tails() { return; } @@ -129,3 +139,20 @@ pub(crate) fn notify_writable(sender: &Sender, region: &M notify_worker(&sender, region_id, BackgroundNotify::RegionBecameWritable).await; }); } + +/// Asks the worker to cancel the tail replay of a region that a role change outside the worker +/// made unable to replay, if it has pending tails, without waiting. A replay the cancel reaches +/// after the region became writable again ends and the worker starts another. +pub(crate) fn notify_cannot_replay(sender: &Sender, region: &MitoRegionRef) { + if !region.version().has_pending_tails() { + return; + } + let sender = sender.clone(); + let region_id = region.region_id; + let notify = BackgroundNotify::RegionCannotReplay { + region: region.clone(), + }; + common_runtime::spawn_global(async move { + notify_worker(&sender, region_id, notify).await; + }); +} diff --git a/src/object-store/src/layers/mock.rs b/src/object-store/src/layers/mock.rs index 4807a401c95..3f8f8904a66 100644 --- a/src/object-store/src/layers/mock.rs +++ b/src/object-store/src/layers/mock.rs @@ -13,6 +13,8 @@ // limitations under the License. use std::fmt::Debug; +use std::future::Future; +use std::pin::Pin; use std::sync::{Arc, Mutex}; use derive_builder::Builder; @@ -26,6 +28,9 @@ pub type MockWriterFactory = Arc oio::Writ pub type MockReaderFactory = Arc oio::Reader + Send + Sync>; pub type MockListerFactory = Arc oio::Lister + Send + Sync>; pub type MockDeleterFactory = Arc oio::Deleter + Send + Sync>; +pub type StatInterceptor = + Arc Pin + Send>> + Send + Sync>; + pub type CopyInterceptor = Arc Option> + Send + Sync>; #[derive(Builder)] @@ -40,6 +45,8 @@ pub struct MockLayer { deleter_factory: Option, #[builder(setter(strip_option), default)] copy_interceptor: Option, + #[builder(setter(strip_option), default)] + stat_interceptor: Option, } impl Clone for MockLayer { @@ -50,6 +57,7 @@ impl Clone for MockLayer { lister_factory: self.lister_factory.clone(), deleter_factory: self.deleter_factory.clone(), copy_interceptor: self.copy_interceptor.clone(), + stat_interceptor: self.stat_interceptor.clone(), } } } @@ -69,6 +77,7 @@ impl Layer for MockLayer { lister_factory: self.lister_factory.clone(), deleter_factory: self.deleter_factory.clone(), copy_interceptor: self.copy_interceptor.clone(), + stat_interceptor: self.stat_interceptor.clone(), }) } } @@ -80,6 +89,7 @@ struct MockService { lister_factory: Option, deleter_factory: Option, copy_interceptor: Option, + stat_interceptor: Option, } impl Debug for MockService { @@ -121,6 +131,9 @@ impl Service for MockService { path: &str, args: opendal::raw::OpStat, ) -> Result { + if let Some(interceptor) = &self.stat_interceptor { + interceptor(path).await; + } self.inner.stat(ctx, path, args).await } diff --git a/src/operator/src/batcher.rs b/src/operator/src/batcher.rs index bc9ef86b34e..5d05f6f6d8b 100644 --- a/src/operator/src/batcher.rs +++ b/src/operator/src/batcher.rs @@ -19,16 +19,26 @@ use async_trait::async_trait; use common_query::Output; use session::context::QueryContextRef; use table::metadata::TableInfoRef; -use tokio::sync::OwnedSemaphorePermit; use crate::error::Result; +/// Keeps a request's admission slot and conversion memory alive across its submissions. +pub type PendingRowsPermit = Arc; + /// Accepts prepared table writes without coupling the inserter to a batcher implementation. /// Schema creation, alteration and default evaluation remain the caller's responsibility. #[async_trait] pub trait PendingRowsBatcher: Send + Sync { - /// Acquires one slot per original request, shared by all of its table submissions. - async fn acquire(&self) -> Result>; + /// Returns the conversion memory limit, or zero when byte admission is disabled. + fn memory_limit_bytes(&self) -> u64 { + 0 + } + + /// Admits an original request before conversion, retaining its slot and estimated + /// Arrow memory across all table submissions. Memory acquisition must not wait + /// because the caller can already hold transport and decoded-row reservations. + /// `held_bytes` counts those reservations, which cannot be released during conversion. + async fn acquire(&self, estimated_bytes: usize, held_bytes: u64) -> Result; /// Submits rows according to the acknowledgement policy, retaining the slot until /// writing completes even when the response acknowledges queue admission only. @@ -39,6 +49,6 @@ pub trait PendingRowsBatcher: Send + Sync { table_info: TableInfoRef, batch: RecordBatch, ctx: QueryContextRef, - permit: Arc, + permit: PendingRowsPermit, ) -> Result; } diff --git a/src/operator/src/insert.rs b/src/operator/src/insert.rs index c0792ee56e3..de4d1f9b9ce 100644 --- a/src/operator/src/insert.rs +++ b/src/operator/src/insert.rs @@ -16,7 +16,7 @@ mod otlp; pub use otlp::MetricInsertPreflight; -use std::collections::BTreeMap; +use std::collections::{BTreeMap, BTreeSet}; use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::{Arc, LazyLock}; use std::time::{Duration, Instant}; @@ -55,7 +55,7 @@ use common_meta::rpc::ddl::TriggerReason; use common_query::Output; use common_query::native_histogram::{is_native_histogram_value_type, native_histogram_value_type}; 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_telemetry::tracing_context::TracingContext; use common_telemetry::{debug, error, warn}; @@ -105,7 +105,7 @@ use crate::region_req_factory::RegionRequestFactory; use crate::req_convert::common::preprocess_row_insert_requests; use crate::req_convert::insert::{ ColumnToRow, ImpureDefaultFiller, RowToRegion, StatementToRegion, TableToRegion, - fill_reqs_with_impure_default, rows_to_record_batch, + fill_reqs_with_impure_default, rows_to_record_batch, value_matches_type, }; use crate::statement::StatementExecutor; use crate::write_dispatcher::{WriteDispatcher, WriteDispatcherRef}; @@ -120,6 +120,11 @@ pub struct Inserter { /// When `false`, missing tables are never auto-created regardless of the /// per-request `auto_create_table` hint. When `true`, the hint still applies. auto_create_table: bool, + /// Time index unit for physical metric tables created by auto table creation. + /// New logical tables created under such a physical table inherit its unit, + /// so all metric-engine ingestion paths write timestamps in this unit. + /// Defaults to milliseconds for compatibility. + auto_create_physical_table_timestamp_unit: TimeUnit, pending_rows_batcher: Option>, /// Rows handed to detached flow mirror tasks that have not finished yet. /// Bounds how much row data in-flight mirror writes may keep alive, see @@ -342,11 +347,18 @@ impl Inserter { node_manager, table_flownode_set_cache, auto_create_table, + auto_create_physical_table_timestamp_unit: TimeUnit::Millisecond, pending_rows_batcher: None, mirror_pending_rows: Arc::new(AtomicU64::new(0)), } } + /// Sets the time index unit for auto-created physical metric tables. + pub fn with_auto_create_physical_table_timestamp_unit(mut self, unit: TimeUnit) -> Self { + self.auto_create_physical_table_timestamp_unit = unit; + self + } + /// Installs the shared dispatcher used by direct writes and batch flushes. pub fn with_write_dispatcher(mut self, dispatcher: WriteDispatcherRef) -> Self { self.write_dispatcher = dispatcher; @@ -411,9 +423,10 @@ impl Inserter { reason: "invalid exemplar destination" } ); - self.bind_exemplar_table_ids(&mut requests, &ctx, sources) - .await?; + validate_column_count_match(&requests)?; preprocess_row_insert_requests(&mut requests.inserts)?; + self.bind_exemplar_table_ids(&mut requests, &ctx, sources, statement_executor) + .await?; self.handle_row_inserts_with_create_type( requests, ctx, @@ -430,9 +443,10 @@ impl Inserter { requests: &mut RowInsertRequests, ctx: &QueryContextRef, sources: &[TableInfoRef], + statement_executor: &StatementExecutor, ) -> Result<()> { - validate_column_count_match(requests)?; let mut tables = HashMap::new(); + let mut required_tags = BTreeMap::>::new(); for info in sources.iter().filter(|info| { info.catalog_name == ctx.current_catalog() && info.schema_name == ctx.current_schema() }) { @@ -452,6 +466,7 @@ impl Inserter { let Some(rows) = request.rows.as_mut() else { continue; }; + validate_exemplar_rows(rows)?; ensure!( !rows .schema @@ -497,6 +512,16 @@ impl Inserter { ), } ); + let tags = required_tags.entry(name.clone()).or_default(); + for (column, value) in rows.schema.iter().zip(&row.values) { + if column.semantic_type == SemanticType::Tag as i32 + && column.column_name != EXEMPLAR_METRIC_COLUMN + && column.column_name != DATA_SCHEMA_TSID_COLUMN_NAME + && value.value_data.is_some() + { + tags.insert(column.column_name.clone()); + } + } row.values.push(ValueData::U32Value(info.table_id()).into()); } rows.schema.push(api::v1::helper::tag_column_schema( @@ -504,6 +529,83 @@ impl Inserter { ColumnDataType::Uint32, )); } + + let mut alters = Vec::new(); + let mut refresh = Vec::new(); + for (name, tags) in required_tags { + let info = &tables[&name]; + let tags = tags + .into_iter() + .map(|name| api::v1::helper::tag_column_schema(&name, ColumnDataType::String)) + .collect::>(); + if let Some(add_columns) = exemplar_source_add_columns(info, &tags)? { + ensure!( + self.auto_create_disabled_reason(ctx)?.is_none(), + InvalidInsertRequestSnafu { + reason: format!( + "exemplar source {name} requires new tags, but automatic DDL is disabled" + ), + } + ); + alters.push(( + info.table_id(), + AlterTableExpr { + catalog_name: info.catalog_name.clone(), + schema_name: info.schema_name.clone(), + table_name: name, + kind: Some(Kind::AddColumns(add_columns)), + }, + )); + refresh.push((info, tags)); + } + } + if !alters.is_empty() { + if let Some(table) = self + .get_table( + ctx.current_catalog(), + &ctx.current_schema(), + METRICS_EXEMPLARS_TABLE, + ) + .await? + { + // Reject an incompatible destination before changing any source schema. + validate_exemplar_table(&table.table_info())?; + } + statement_executor + .alter_logical_tables_with_ids(alters, ctx.clone(), TriggerReason::AutoAlter) + .await?; + for (pinned, tags) in refresh { + let table = self + .get_table(&pinned.catalog_name, &pinned.schema_name, &pinned.name) + .await? + .with_context(|| InvalidInsertRequestSnafu { + reason: format!( + "exemplar source {} disappeared during reconciliation", + pinned.name + ), + })?; + let info = table.table_info(); + ensure!( + info.table_id() == pinned.table_id(), + InvalidInsertRequestSnafu { + reason: format!( + "exemplar source {} changed during reconciliation", + pinned.name + ), + } + ); + // Concurrent ADD IF NOT EXISTS can succeed on names alone; verify their definitions. + ensure!( + exemplar_source_add_columns(&info, &tags)?.is_none(), + InvalidInsertRequestSnafu { + reason: format!( + "exemplar source {} is still missing inherited tags", + pinned.name + ), + } + ); + } + } Ok(()) } @@ -654,7 +756,7 @@ impl Inserter { .values() .map(|info| (info.name.as_str(), info)) .collect::>(); - let mut prepared = Vec::with_capacity(requests.inserts.len()); + let mut estimated_bytes = Some(0usize); for request in &mut requests.inserts { let table_info = by_name @@ -666,8 +768,34 @@ impl Inserter { continue; }; ImpureDefaultFiller::new((*table_info).clone())?.fill_rows(rows); - let batch = rows_to_record_batch(rows, table_info)?; - prepared.push(((*table_info).clone(), batch)); + if batcher.memory_limit_bytes() != 0 { + estimated_bytes = estimated_bytes.and_then(|bytes| { + bytes.checked_add(crate::req_convert::insert::estimated_record_batch_bytes( + rows, table_info, + )?) + }); + } + } + // Reserve once for the whole request before constructing any Arrow arrays. + // PB rows and the converted batches coexist, so this is additional memory. + let permit = if requests.inserts.is_empty() { + None + } else { + Some( + batcher + .acquire( + estimated_bytes.unwrap_or(usize::MAX), + ctx.held_memory_bytes(), + ) + .await?, + ) + }; + let mut prepared = Vec::with_capacity(requests.inserts.len()); + for request in &requests.inserts { + let table_info = by_name[request.table_name.as_str()]; + if let Some(rows) = &request.rows { + prepared.push((table_info.clone(), rows_to_record_batch(rows, table_info)?)); + } } // Preserve the existing meter input and original request boundary. These // envelopes are only for accounting; routing happens after batching. @@ -698,11 +826,8 @@ impl Inserter { .await .context(WriteRejectedSnafu)?; prepared.retain(|(_, batch)| batch.num_rows() != 0); - let results = if prepared.is_empty() { - Vec::new() - } else { + let results = if let Some(permit) = permit { // One original request shares admission across all table submissions. - let permit = batcher.acquire().await?; let submissions = prepared.into_iter().map(|(info, batch)| { // Route to the same target database used for admission above. let mut target_ctx = ctx.fork(); @@ -712,6 +837,8 @@ impl Inserter { }); // Observe every table completion even when another table fails. future::join_all(submissions).await + } else { + Vec::new() }; let mut affected_rows = 0; let mut meta = OutputMeta::new_with_cost(write_cost as _); @@ -1753,7 +1880,9 @@ impl Inserter { let default_schema = vec![ ColumnSchema { column_name: greptime_timestamp().to_string(), - datatype: ColumnDataType::TimestampMillisecond as _, + datatype: api::helper::timestamp_datatype( + self.auto_create_physical_table_timestamp_unit, + ) as _, semantic_type: SemanticType::Timestamp as _, datatype_extension: None, options: None, @@ -2195,6 +2324,95 @@ fn validate_column_count_match(requests: &RowInsertRequests) -> Result<()> { Ok(()) } +fn validate_exemplar_rows(rows: &Rows) -> Result<()> { + let mut names = HashSet::new(); + for (index, column) in rows.schema.iter().enumerate() { + let data_type: datatypes::prelude::ConcreteDataType = + api::helper::ColumnDataTypeWrapper::try_new( + column.datatype, + column.datatype_extension.clone(), + ) + .context(crate::error::ColumnDataTypeSnafu)? + .into(); + let valid = match column.column_name.as_str() { + DATA_SCHEMA_TSID_COLUMN_NAME => { + data_type == datatypes::prelude::ConcreteDataType::uint64_datatype() + && column.semantic_type == SemanticType::Tag as i32 + } + EXEMPLAR_METRIC_COLUMN => { + data_type.is_string() && column.semantic_type == SemanticType::Tag as i32 + } + name if name == greptime_timestamp() => { + data_type.is_timestamp() && column.semantic_type == SemanticType::Timestamp as i32 + } + name if name == greptime_value() => { + data_type == datatypes::prelude::ConcreteDataType::float64_datatype() + && column.semantic_type == SemanticType::Field as i32 + } + name if name == greptime_exemplar_labels() => { + data_type.is_json2() && column.semantic_type == SemanticType::Field as i32 + } + _ => data_type.is_string() && column.semantic_type == SemanticType::Tag as i32, + }; + ensure!( + valid && names.insert(column.column_name.as_str()), + InvalidInsertRequestSnafu { + reason: format!( + "invalid or duplicate exemplar column {}", + column.column_name + ), + } + ); + ensure!( + rows.rows.iter().all(|row| value_matches_type( + &row.values[index], + column.datatype, + column.datatype_extension.as_ref(), + )), + InvalidInsertRequestSnafu { + reason: format!("invalid value for exemplar column {}", column.column_name), + } + ); + } + ensure!( + [ + DATA_SCHEMA_TSID_COLUMN_NAME, + EXEMPLAR_METRIC_COLUMN, + greptime_timestamp(), + greptime_value(), + greptime_exemplar_labels(), + ] + .iter() + .all(|name| names.contains(name)), + InvalidInsertRequestSnafu { + reason: "missing required exemplar columns", + } + ); + Ok(()) +} + +fn exemplar_source_add_columns( + info: &TableInfo, + tags: &[ColumnSchema], +) -> Result> { + for tag in tags { + if let Some(index) = info.meta.schema.column_index_by_name(&tag.column_name) { + let column = &info.meta.schema.column_schemas()[index]; + // Existing source defaults may already be part of the normalized series identity. + ensure!( + info.meta.primary_key_indices.contains(&index) && column.data_type.is_string(), + InvalidInsertRequestSnafu { + reason: format!( + "exemplar source {} column {} must be a string tag", + info.name, tag.column_name + ), + } + ); + } + } + expr_helper::extract_add_columns_expr(&info.meta.schema, ColumnExpr::from_column_schemas(tags)) +} + /// Validates the fixed exemplar contract before writing or scanning a shared table. pub fn validate_exemplar_table(table: &TableInfo) -> Result<()> { let meta = &table.meta; @@ -2271,11 +2489,11 @@ pub fn validate_exemplar_table(table: &TableInfo) -> Result<()> { reason: "exemplar value must be a DOUBLE field" } ); - let (labels_index, labels) = lookup(EXEMPLAR_LABELS_COLUMN)?; + let (labels_index, labels) = lookup(greptime_exemplar_labels())?; ensure!( labels.data_type.is_json2() && !meta.primary_key_indices.contains(&labels_index), InvalidInsertRequestSnafu { - reason: "exemplar_labels must be a JSON2 field" + reason: format!("{} must be a JSON2 field", greptime_exemplar_labels()) } ); if let Some(extension) = labels @@ -2304,7 +2522,7 @@ pub fn validate_exemplar_table(table: &TableInfo) -> Result<()> { greptime_timestamp(), greptime_value(), EXEMPLAR_METRIC_COLUMN, - EXEMPLAR_LABELS_COLUMN, + greptime_exemplar_labels(), DATA_SCHEMA_TABLE_ID_COLUMN_NAME, DATA_SCHEMA_TSID_COLUMN_NAME, ] @@ -3612,9 +3830,11 @@ mod tests { } meter.attempts.lock().unwrap().clear(); - // Rejection must also precede admission to the table batcher's queue. + // Rejection must precede queue submission, but conversion memory is reserved first. if enabled { - let batcher: Arc = Arc::new(UnexpectedBatcher); + let batcher: Arc = Arc::new(UnexpectedBatcher { + allow_acquire: true, + }); let rows = Rows { schema: vec![ api::v1::helper::tag_column_schema("a", ColumnDataType::Int32), @@ -4099,12 +4319,19 @@ mod tests { ); } - struct UnexpectedBatcher; + #[derive(Default)] + struct UnexpectedBatcher { + allow_acquire: bool, + } #[async_trait::async_trait] impl PendingRowsBatcher for UnexpectedBatcher { - async fn acquire(&self) -> Result> { - panic!("empty writes must not acquire batch admission") + async fn acquire(&self, _: usize, _: u64) -> Result { + assert!( + self.allow_acquire, + "empty writes must not acquire batch admission" + ); + Ok(Arc::new(())) } async fn submit( @@ -4112,9 +4339,9 @@ mod tests { _table_info: TableInfoRef, _batch: arrow::record_batch::RecordBatch, _ctx: QueryContextRef, - _permit: Arc, + _permit: crate::batcher::PendingRowsPermit, ) -> Result { - panic!("empty writes must not submit a batch") + panic!("writes must not submit a batch") } } @@ -4271,7 +4498,7 @@ mod tests { #[tokio::test] async fn test_instant_table_bypasses_batcher() { - let batcher: Arc = Arc::new(UnexpectedBatcher); + let batcher: Arc = Arc::new(UnexpectedBatcher::default()); let inserter = batcher_test_inserter() .await .with_pending_rows_batcher(Some(batcher)); @@ -4291,7 +4518,7 @@ mod tests { let inserter = batcher_test_inserter().await; let table = make_table_ref_with_schema("ts", "value", ConcreteDataType::float64_datatype()) .table_info(); - let batcher: Arc = Arc::new(UnexpectedBatcher); + let batcher: Arc = Arc::new(UnexpectedBatcher::default()); let ctx = QueryContext::arc(); let output = inserter .submit_table_rows( diff --git a/src/operator/src/insert/otlp.rs b/src/operator/src/insert/otlp.rs index 9405480d3a2..aa6bf665eb6 100644 --- a/src/operator/src/insert/otlp.rs +++ b/src/operator/src/insert/otlp.rs @@ -118,12 +118,9 @@ impl Inserter { tables.insert(backing.clone(), table); } physical_columns.entry(backing.as_str()).or_insert_with(|| { - PhysicalColumns::new( - tables[backing] - .as_ref() - .map(table_columns) - .unwrap_or_else(default_physical_columns), - ) + PhysicalColumns::new(tables[backing].as_ref().map(table_columns).unwrap_or_else( + || default_physical_columns(self.auto_create_physical_table_timestamp_unit), + )) }); } // Match ordinary insertion: impure defaults are evaluated once per table @@ -176,7 +173,9 @@ impl Inserter { let unit = target .and_then(table_time_index_unit) .or_else(|| physical.and_then(table_time_index_unit)) - .unwrap_or(TimeUnit::Millisecond); + // The physical table will be auto-created in the configured + // unit, so validate its rows in that unit as well. + .unwrap_or(self.auto_create_physical_table_timestamp_unit); if let Some(rows) = &mut request.rows { convert_rows_time_unit(rows, unit)?; } @@ -378,13 +377,13 @@ fn table_columns(table: &TableRef) -> Vec<(DataColumn, SemanticType)> { .collect() } -fn default_physical_columns() -> Vec<(DataColumn, SemanticType)> { +fn default_physical_columns(unit: TimeUnit) -> Vec<(DataColumn, SemanticType)> { use datatypes::prelude::ConcreteDataType; vec![ ( DataColumn::new( greptime_timestamp(), - ConcreteDataType::timestamp_millisecond_datatype(), + ConcreteDataType::timestamp_datatype(unit), false, ) .with_time_index(true), @@ -698,7 +697,7 @@ mod tests { #[test] fn test_preflight_omissions_defaults_and_explicit_nulls() { - let mut columns = default_physical_columns(); + let mut columns = default_physical_columns(TimeUnit::Millisecond); columns.push(( DataColumn::new("host", ConcreteDataType::string_datatype(), false) .with_default_constraint(Some(ColumnDefaultConstraint::Value(DataValue::String( @@ -739,7 +738,7 @@ mod tests { #[test] fn test_preflight_existing_columns_and_physical_definitions() { - let columns = default_physical_columns(); + let columns = default_physical_columns(TimeUnit::Millisecond); let mut rows = Rows { schema: vec![ColumnSchema { column_name: greptime_timestamp().into(), @@ -805,7 +804,7 @@ mod tests { (defaulted, None), (impure, Some("impure default for physical field `impure`")), ] { - let mut columns = default_physical_columns(); + let mut columns = default_physical_columns(TimeUnit::Millisecond); columns.extend((0..1024).map(|index| { ( DataColumn::new( diff --git a/src/operator/src/req_convert/insert.rs b/src/operator/src/req_convert/insert.rs index 50000e8dc93..5e1757f2c03 100644 --- a/src/operator/src/req_convert/insert.rs +++ b/src/operator/src/req_convert/insert.rs @@ -25,7 +25,7 @@ pub use column_to_row::ColumnToRow; pub(crate) use fill_impure_default::ImpureDefaultFiller; pub use fill_impure_default::fill_reqs_with_impure_default; pub use row_to_batch::rows_to_record_batch; -pub(crate) use row_to_batch::value_matches_type; +pub(crate) use row_to_batch::{estimated_record_batch_bytes, value_matches_type}; pub use row_to_region::RowToRegion; use snafu::{OptionExt, ResultExt}; pub use stmt_to_region::StatementToRegion; diff --git a/src/operator/src/req_convert/insert/row_to_batch.rs b/src/operator/src/req_convert/insert/row_to_batch.rs index 440c66c93a0..0e92e74e859 100644 --- a/src/operator/src/req_convert/insert/row_to_batch.rs +++ b/src/operator/src/req_convert/insert/row_to_batch.rs @@ -12,6 +12,8 @@ // See the License for the specific language governing permissions and // limitations under the License. +mod memory; + use std::collections::HashMap; use api::helper::{ @@ -29,6 +31,8 @@ use table::metadata::TableInfo; use crate::error::{self, Result}; +pub(crate) use memory::estimated_record_batch_bytes; + /// Converts prepared rows in target-schema order without Prom-specific renaming. /// /// Missing columns evaluate their defaults once per conversion. Explicit nulls @@ -198,10 +202,14 @@ mod tests { use std::sync::Arc; use std::thread::yield_now; + use api::helper::to_grpc_value; use api::v1::value::ValueData; use api::v1::{ColumnDataType, ColumnSchema as ProtoColumnSchema, Row, Value}; use arrow::array::{Array, Int32Array, StringArray}; + use datatypes::extension::json::{Json2ExtensionType, JsonMetadata}; + use datatypes::json::{JsonSettings, JsonTypeHint}; use datatypes::schema::{ColumnDefaultConstraint, ColumnSchema, Schema}; + use datatypes::types::json_type::JsonNativeType; use datatypes::value::Value as DtValue; use table::metadata::{TableInfoBuilder, TableMetaBuilder}; @@ -260,6 +268,230 @@ mod tests { (rows, schema) } + fn json_column(metadata: JsonMetadata) -> ColumnSchema { + let mut column = ColumnSchema::new( + "json", + ConcreteDataType::json2(JsonNativeType::object()), + true, + ); + column.with_extension_type(&Json2ExtensionType::new(Arc::new(metadata))); + column + } + + fn json_rows(column: &ColumnSchema, values: impl IntoIterator) -> Rows { + let (kind, extension) = ColumnDataTypeWrapper::try_from(column.data_type.clone()) + .unwrap() + .to_parts(); + let mut input = source(&column.name, kind); + input.datatype_extension = extension; + Rows { + schema: vec![input], + rows: values + .into_iter() + .map(|value| Row { + values: vec![to_grpc_value(value)], + }) + .collect(), + } + } + + #[test] + fn test_conversion_estimate_covers_destination_padding_and_defaults() { + let (mut rows, schema) = fixture(); + rows.rows[0].values[0] = ValueData::StringValue("x".repeat(10_000)).into(); + rows.rows.resize(1000, rows.rows[0].clone()); + let mut columns = schema.column_schemas().to_vec(); + columns.extend((0..2048).map(|i| { + ColumnSchema::new( + format!("tag_{i}"), + ConcreteDataType::string_datatype(), + true, + ) + })); + columns.push( + ColumnSchema::new("default", ConcreteDataType::string_datatype(), true) + .with_default_constraint(Some(ColumnDefaultConstraint::Value(DtValue::String( + "default".repeat(1000).into(), + )))) + .unwrap(), + ); + let table = table_info(Schema::new(columns)); + let estimate = estimated_record_batch_bytes(&rows, &table).unwrap(); + let batch = rows_to_record_batch(&rows, &table).unwrap(); + assert!(estimate >= batch.get_array_memory_size()); + assert!(estimate > 4 * 1024 * 1024); + } + + #[test] + fn test_conversion_estimate_covers_nested_values_and_defaults() { + use datatypes::value::ListValue; + + let value = DtValue::List(ListValue::new( + vec![ + DtValue::String("a".into()), + DtValue::String("b".repeat(30_000).into()), + ], + Arc::new(ConcreteDataType::string_datatype()), + )); + let datatype = value.data_type(); + let table = table_info(Schema::new(vec![ + ColumnSchema::new("input", datatype.clone(), true), + ColumnSchema::new("default", datatype.clone(), true) + .with_default_constraint(Some(ColumnDefaultConstraint::Value(value.clone()))) + .unwrap(), + ])); + let (kind, extension) = ColumnDataTypeWrapper::try_from(datatype) + .unwrap() + .to_parts(); + let mut input = source("input", kind); + input.datatype_extension = extension; + let rows = Rows { + schema: vec![input], + rows: vec![ + Row { + values: vec![to_grpc_value(value)] + }; + 10 + ], + }; + let estimate = estimated_record_batch_bytes(&rows, &table).unwrap(); + let batch = rows_to_record_batch(&rows, &table).unwrap(); + assert!(estimate >= batch.get_array_memory_size()); + } + + #[test] + fn test_conversion_estimate_covers_json2_expansion() { + for (legacy, max_paths) in [ + (false, None), + (false, Some(0)), + (false, Some(1)), + (true, None), + ] { + let settings = JsonSettings::try_new( + (0..200) + .map(|i| JsonTypeHint { + path: vec![format!("hint_{i}")], + data_type: ConcreteDataType::string_datatype(), + inverted_index: false, + skipping_index: None, + fulltext_index: None, + }) + .collect(), + max_paths, + ) + .unwrap(); + let column = json_column(if legacy { + JsonMetadata::new_v1(settings.clone()) + } else { + JsonMetadata::new(settings.clone()) + }); + let rows = json_rows( + &column, + (0..200).map(|i| { + settings + .encode(serde_json::json!({ + format!("field_{i}"): "x".repeat(i * 100), + "nested": [{"name": "y".repeat(i)}, {"other": i}], + })) + .unwrap() + }), + ); + let table = table_info(Schema::new(vec![column])); + let estimate = estimated_record_batch_bytes(&rows, &table).unwrap(); + let batch = rows_to_record_batch(&rows, &table).unwrap(); + assert!( + estimate >= batch.get_array_memory_size(), + "legacy={legacy}, max_paths={max_paths:?}" + ); + } + } + + #[test] + fn test_conversion_estimate_respects_json2_expansion_limit() { + for (legacy, max_paths) in [ + (false, Some(0)), + (false, Some(100)), + (false, None), + (true, Some(0)), + ] { + let settings = JsonSettings::try_new(vec![], max_paths).unwrap(); + let column = json_column(if legacy { + JsonMetadata::new_v1(settings.clone()) + } else { + JsonMetadata::new(settings.clone()) + }); + let rows = json_rows( + &column, + (0..1000).map(|i| { + settings + .encode(serde_json::json!({format!("field_{i}"): "a"})) + .unwrap() + }), + ); + let table = table_info(Schema::new(vec![column])); + let estimate = estimated_record_batch_bytes(&rows, &table).unwrap(); + let batch = rows_to_record_batch(&rows, &table).unwrap(); + assert!( + estimate >= batch.get_array_memory_size(), + "legacy={legacy}, max_paths={max_paths:?}" + ); + if !legacy { + // Small batches must fit this quota even when every row has a different key. + assert!(estimate < 64 * 1024 * 1024, "max_paths={max_paths:?}"); + } + } + } + + #[test] + fn test_conversion_estimate_covers_nested_json2_paths_and_defaults() { + // One selected array path can contain many fields, with padding for every element. + let items = (0..256) + .map(|i| serde_json::json!({format!("field_{i}"): "a"})) + .collect::>(); + for use_default in [false, true] { + let settings = + JsonSettings::try_new(vec![], Some(if use_default { 0 } else { 1 })).unwrap(); + let value = settings + .encode(serde_json::json!({"outer": {"inner": {"items": items}}})) + .unwrap(); + let mut column = json_column(JsonMetadata::new(settings)); + let rows = if use_default { + column = column + .with_default_constraint(Some(ColumnDefaultConstraint::Value(value))) + .unwrap(); + Rows { + schema: vec![], + rows: vec![Row { values: vec![] }; 2], + } + } else { + json_rows(&column, [value.clone(), value]) + }; + let table = table_info(Schema::new(vec![column])); + let estimate = estimated_record_batch_bytes(&rows, &table).unwrap(); + let batch = rows_to_record_batch(&rows, &table).unwrap(); + assert!( + estimate >= batch.get_array_memory_size(), + "use_default={use_default}" + ); + } + } + + #[test] + fn test_conversion_estimate_covers_small_json2_view_buffers() { + let settings = JsonSettings::default(); + let column = json_column(JsonMetadata::new_v1(settings.clone())); + let rows = json_rows( + &column, + [settings + .encode(serde_json::json!({"value": "x".repeat(13)})) + .unwrap()], + ); + let table = table_info(Schema::new(vec![column])); + let estimate = estimated_record_batch_bytes(&rows, &table).unwrap(); + let batch = rows_to_record_batch(&rows, &table).unwrap(); + assert!(estimate >= batch.get_array_memory_size()); + } + #[test] fn test_reorder_multifield_and_defaults() { let (rows, schema) = fixture(); @@ -349,11 +581,7 @@ mod tests { #[test] fn test_json2_expanded_schema() { - use api::helper::to_grpc_value; - use datatypes::extension::json::{Json2ExtensionType, JsonMetadata}; - use datatypes::json::JsonSettings; use datatypes::schema::SchemaBuilder; - use datatypes::types::json_type::JsonNativeType; let settings = JsonSettings::default(); let mut column_schema = ColumnSchema::new( diff --git a/src/operator/src/req_convert/insert/row_to_batch/memory.rs b/src/operator/src/req_convert/insert/row_to_batch/memory.rs new file mode 100644 index 00000000000..7fdff3feba7 --- /dev/null +++ b/src/operator/src/req_convert/insert/row_to_batch/memory.rs @@ -0,0 +1,345 @@ +// Copyright 2023 Greptime Team +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use std::collections::{HashMap, HashSet}; + +use api::v1::value::ValueData; +use api::v1::{JsonValue, Rows, json_value}; +use arrow::datatypes::DataType; +use arrow_schema::extension::ExtensionType; +use datatypes::extension::json::Json2ExtensionType; +use datatypes::json::JSON2_DEFAULT_MAX_AUTO_EXPANDED_PATHS; +use datatypes::json::value::JsonVariant; +use datatypes::schema::ColumnDefaultConstraint; +use datatypes::value::Value; +use datatypes::vectors::json; +use table::metadata::TableInfo; + +const ARRAY_OVERHEAD: usize = 512; +const VIEW_BLOCK_BYTES: usize = 8192; +const VALUE_SCRATCH_BYTES: usize = 256; + +/// Estimates additional memory for conversion, including destination columns absent +/// from the request. Overflow fails closed. Source rows remain separately reserved. +/// +/// This budgets buffers, capacity growth and JSON2 conversion scratch, not allocator +/// RSS. shortcut: account for flush concatenation, partitioning and IPC separately +/// when extending admission to the entire flush pipeline. +pub(crate) fn estimated_record_batch_bytes(rows: &Rows, table: &TableInfo) -> Option { + let source = rows + .schema + .iter() + .enumerate() + .map(|(i, column)| (column.column_name.as_str(), i)) + .collect::>(); + let mut total = 0usize; + for (column, field) in table + .meta + .schema + .column_schemas() + .iter() + .zip(table.meta.schema.arrow_schema().fields()) + { + let mut values = ValueSize::default(); + let source_index = source.get(column.name.as_str()); + if let Some(&index) = source_index { + for row in &rows.rows { + values.proto(row.values.get(index)?.value_data.as_ref())?; + } + } else if let Some(ColumnDefaultConstraint::Value(value)) = column.default_constraint() { + values.default_value(value)?; + values.payload = values.payload.checked_mul(rows.rows.len())?; + values.items = values.items.checked_mul(rows.rows.len())?; + values.scratch = values.scratch.checked_mul(rows.rows.len())?; + } + + let count = rows.rows.len().checked_add(values.items)?; + let extension = column.extension_type::().ok()?; + // Only supplied v2 JSON2 values use the settings-aware builder; defaults use the datatype. + let settings = extension + .as_ref() + .filter(|extension| { + source_index.is_some() + && column.data_type.is_json2() + && extension.metadata().is_version_2() + }) + .map(|extension| extension.metadata().json_settings()); + let (mut bytes, paths) = if let Some(settings) = settings { + let limit = settings + .max_auto_expanded_paths() + .unwrap_or(JSON2_DEFAULT_MAX_AUTO_EXPANDED_PATHS); + ( + array_bytes(&json::json2_physical_data_type(settings), count)?, + values.expanded_paths(usize::try_from(limit).ok()?)?, + ) + } else { + (array_bytes(field.data_type(), count)?, values.paths.len()) + }; + // Each selected path can need buffers for every row or nested element. + let path_bytes = count + .checked_add(1)? + .checked_mul(48)? + .checked_add(3 * ARRAY_OVERHEAD + VIEW_BLOCK_BYTES)?; + bytes = bytes.checked_add(paths.checked_mul(path_bytes)?)?; + // Builders can double capacity; payload and JSON scratch can coexist with + // the final arrays. Fixed per-array slack covers alignment and empty buffers. + total = total + .checked_add(bytes.checked_mul(2)?)? + .checked_add(field.size().checked_mul(2)?)? + .checked_add(values.payload.checked_mul(4)?)? + .checked_add(values.scratch)?; + } + Some(total) +} + +fn array_bytes(data_type: &DataType, count: usize) -> Option { + let width = match data_type { + DataType::Null => 0, + DataType::Boolean => 1, + DataType::Utf8 | DataType::Binary | DataType::List(_) => 4, + DataType::LargeUtf8 | DataType::LargeBinary | DataType::LargeList(_) => 8, + DataType::Utf8View | DataType::BinaryView => 16, + DataType::Struct(_) | DataType::FixedSizeList(_, _) | DataType::Dictionary(_, _) => 0, + DataType::FixedSizeBinary(width) => usize::try_from(*width).ok()?, + other => other.primitive_width()?, + }; + // A byte per validity bit is deliberately conservative, including null padding. + let mut bytes = count + .checked_add(1)? + .checked_mul(width.checked_add(1)?)? + .checked_add(ARRAY_OVERHEAD)?; + if matches!(data_type, DataType::Utf8View | DataType::BinaryView) { + // Arrow starts out-of-line view data with an 8 KiB block. + bytes = bytes.checked_add(VIEW_BLOCK_BYTES)?; + } + match data_type { + DataType::Struct(fields) => { + for field in fields { + bytes = bytes.checked_add(array_bytes(field.data_type(), count)?)?; + } + } + DataType::List(field) | DataType::LargeList(field) => { + bytes = bytes.checked_add(array_bytes(field.data_type(), count)?)?; + } + DataType::FixedSizeList(field, len) => { + bytes = bytes.checked_add(array_bytes( + field.data_type(), + count.checked_mul(usize::try_from(*len).ok()?)?, + )?)?; + } + DataType::Dictionary(key, value) => { + bytes = bytes + .checked_add(array_bytes(key, count)?)? + .checked_add(array_bytes(value, count)?)?; + } + _ => {} + } + Some(bytes) +} + +#[derive(Default)] +struct ValueSize<'a> { + payload: usize, + items: usize, + scratch: usize, + paths: HashSet>>, + path: Vec>, +} + +#[derive(Clone, PartialEq, Eq, Hash)] +enum PathComponent<'a> { + Key(&'a str), + Field(usize), + Element, +} + +impl<'a> ValueSize<'a> { + fn expanded_paths(&self, limit: usize) -> Option { + if limit == 0 { + return Some(0); + } + if self.paths.len() <= limit { + return Some(self.paths.len()); + } + + // Arrays count as one selectable leaf, but all their element fields can expand. + let mut path_sizes = HashMap::new(); + for path in &self.paths { + let element = path + .iter() + .position(|part| matches!(part, PathComponent::Element)); + let leaf = &path[..element.unwrap_or(path.len())]; + let size = path_sizes.entry(leaf).or_insert(leaf.len()); + if element.is_some() { + *size = size.checked_add(1)?; + } + } + // The largest candidates bound any frequency-based selection, including parent structs. + let mut sizes = path_sizes.into_values().collect::>(); + sizes.sort_unstable_by(|a, b| b.cmp(a)); + let count = sizes + .into_iter() + .take(limit) + .try_fold(0usize, usize::checked_add)?; + Some(count.min(self.paths.len())) + } + + fn payload(&mut self, bytes: usize) -> Option<()> { + self.payload = self.payload.checked_add(bytes)?; + Some(()) + } + + fn children(&mut self, len: usize, array: bool) -> Option<()> { + if array { + self.items = self.items.checked_add(len)?; + } + self.scratch = self + .scratch + .checked_add(len.checked_mul(VALUE_SCRATCH_BYTES)?)?; + Some(()) + } + + fn variant(&mut self, bytes: usize) -> Option<()> { + self.payload(bytes)?; + // Opaque JSONB is decoded into a tree when written to a Variant remainder. + self.scratch = self.scratch.checked_add(bytes.checked_mul(64)?)?; + Some(()) + } + + fn proto(&mut self, value: Option<&'a ValueData>) -> Option<()> { + match value { + Some(ValueData::StringValue(value)) => self.payload(value.len())?, + Some(ValueData::BinaryValue(value)) => self.payload(value.len())?, + Some(ValueData::ListValue(value)) => { + self.children(value.items.len(), true)?; + self.path.push(PathComponent::Element); + for value in &value.items { + self.proto(value.value_data.as_ref())?; + } + self.path.pop(); + } + Some(ValueData::StructValue(value)) => { + self.children(value.items.len(), false)?; + for (index, value) in value.items.iter().enumerate() { + self.path.push(PathComponent::Field(index)); + self.proto(value.value_data.as_ref())?; + self.path.pop(); + } + } + Some(ValueData::JsonValue(value)) => self.json(value)?, + _ => {} + } + Some(()) + } + + fn json(&mut self, value: &'a JsonValue) -> Option<()> { + if !self.paths.contains(&self.path) { + self.paths.insert(self.path.clone()); + } + self.scratch = self.scratch.checked_add(VALUE_SCRATCH_BYTES)?; + match value.value.as_ref() { + Some(json_value::Value::Str(value)) => self.payload(value.len())?, + Some(json_value::Value::Variant(value)) => self.variant(value.len())?, + Some(json_value::Value::Array(value)) => { + self.items = self.items.checked_add(value.items.len())?; + self.path.push(PathComponent::Element); + for value in &value.items { + self.json(value)?; + } + self.path.pop(); + } + Some(json_value::Value::Object(value)) => { + for entry in &value.entries { + self.payload(entry.key.len())?; + self.path.push(PathComponent::Key(&entry.key)); + if let Some(value) = &entry.value { + self.json(value)?; + } + self.path.pop(); + } + } + _ => {} + } + Some(()) + } + + fn default_value(&mut self, value: &'a Value) -> Option<()> { + match value { + Value::String(value) => self.payload(value.len())?, + Value::Binary(value) => self.payload(value.len())?, + Value::List(value) => { + self.children(value.items().len(), true)?; + self.path.push(PathComponent::Element); + for value in value.items() { + self.default_value(value)?; + } + self.path.pop(); + } + Value::Struct(value) => { + self.children(value.items().len(), false)?; + for (index, value) in value.items().iter().enumerate() { + self.path.push(PathComponent::Field(index)); + self.default_value(value)?; + self.path.pop(); + } + } + Value::Json(value) => self.default_json(value.variant())?, + _ => {} + } + Some(()) + } + + fn default_json(&mut self, value: &'a JsonVariant) -> Option<()> { + if !self.paths.contains(&self.path) { + self.paths.insert(self.path.clone()); + } + self.scratch = self.scratch.checked_add(VALUE_SCRATCH_BYTES)?; + match value { + JsonVariant::String(value) => self.payload(value.len())?, + JsonVariant::Variant(value) => self.variant(value.len())?, + JsonVariant::Array(values) => { + self.items = self.items.checked_add(values.len())?; + self.path.push(PathComponent::Element); + for value in values { + self.default_json(value)?; + } + self.path.pop(); + } + JsonVariant::Object(values) => { + for (key, value) in values { + self.payload(key.len())?; + self.path.push(PathComponent::Key(key)); + self.default_json(value)?; + self.path.pop(); + } + } + _ => {} + } + Some(()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_estimate_overflow_fails_closed() { + assert!(array_bytes(&DataType::Utf8, usize::MAX).is_none()); + let mut values = ValueSize::default(); + assert!(values.payload(usize::MAX).is_some()); + assert!(values.payload(1).is_none()); + assert!(values.children(usize::MAX, true).is_none()); + } +} diff --git a/src/operator/src/statement/ddl.rs b/src/operator/src/statement/ddl.rs index 40a83613a56..42498325ee9 100644 --- a/src/operator/src/statement/ddl.rs +++ b/src/operator/src/statement/ddl.rs @@ -55,8 +55,8 @@ use common_meta::rpc::ddl::trigger::CreateTriggerTask; #[cfg(feature = "enterprise")] use common_meta::rpc::ddl::trigger::DropTriggerTask; use common_meta::rpc::ddl::{ - CreateFlowTask, CreatorGrantIntent, DdlTask, DropFlowTask, DropViewTask, SubmitDdlTaskRequest, - SubmitDdlTaskResponse, TriggerReason, + ALTER_LOGICAL_TABLE_IDS_EXTENSION_KEY, CreateFlowTask, CreatorGrantIntent, DdlTask, + DropFlowTask, DropViewTask, SubmitDdlTaskRequest, SubmitDdlTaskResponse, TriggerReason, }; use common_query::Output; use common_recordbatch::{RecordBatch, RecordBatches}; @@ -1558,16 +1558,7 @@ impl StatementExecutor { query_context: QueryContextRef, trigger_reason: TriggerReason, ) -> Result { - let _timer = crate::metrics::DIST_ALTER_TABLES.start_timer(); - ensure!( - !alter_table_exprs.is_empty(), - EmptyDdlExprSnafu { - name: "alter logical tables" - } - ); - - // group by physical table id - let mut groups: HashMap> = HashMap::new(); + let mut tables = Vec::with_capacity(alter_table_exprs.len()); for expr in alter_table_exprs { // Get table_id from catalog_manager let catalog = if expr.catalog_name.is_empty() { @@ -1590,20 +1581,49 @@ impl StatementExecutor { table_name: format_full_table_name(catalog, &schema, table_name), })?; let table_id = table.table_info().ident.table_id; + tables.push((table_id, expr)); + } + self.alter_logical_tables_with_ids(tables, query_context, trigger_reason) + .await + } + + /// Alters the captured table generations, rejecting concurrent drop/recreate under DDL locks. + pub(crate) async fn alter_logical_tables_with_ids( + &self, + tables: Vec<(TableId, AlterTableExpr)>, + query_context: QueryContextRef, + trigger_reason: TriggerReason, + ) -> Result { + let _timer = crate::metrics::DIST_ALTER_TABLES.start_timer(); + ensure!( + !tables.is_empty(), + EmptyDdlExprSnafu { + name: "alter logical tables" + } + ); + let mut groups: HashMap> = HashMap::new(); + for (table_id, expr) in tables { let physical_table_id = self .table_metadata_manager .table_route_manager() .get_physical_table_id(table_id) .await .context(TableMetadataManagerSnafu)?; - groups.entry(physical_table_id).or_default().push(expr); + groups + .entry(physical_table_id) + .or_default() + .push((table_id, expr)); } // Submit procedure for each physical table let mut handles = Vec::with_capacity(groups.len()); - for (_physical_table_id, exprs) in groups { - let fut = - self.alter_logical_tables_procedure(exprs, query_context.clone(), trigger_reason); + for (physical_table_id, exprs) in groups { + let fut = self.alter_logical_tables_procedure( + physical_table_id, + exprs, + query_context.clone(), + trigger_reason, + ); handles.push(fut); } let _results = futures::future::try_join_all(handles).await?; @@ -2330,17 +2350,54 @@ impl StatementExecutor { async fn alter_logical_tables_procedure( &self, - tables_data: Vec, + physical_table_id: TableId, + tables_data: Vec<(TableId, AlterTableExpr)>, query_context: QueryContextRef, trigger_reason: TriggerReason, ) -> Result { - let executor_context = to_executor_context(query_context, trigger_reason); - let request = SubmitDdlTaskRequest::new(DdlTask::new_alter_logical_tables(tables_data)); + let mut invalidate_keys = vec![CacheIdent::TableId(physical_table_id)]; + if let Some(physical) = self + .table_metadata_manager + .table_info_manager() + .get(physical_table_id) + .await + .context(TableMetadataManagerSnafu)? + { + invalidate_keys.push(CacheIdent::TableName(physical.table_name())); + } + for (id, expr) in &tables_data { + invalidate_keys.push(CacheIdent::TableId(*id)); + invalidate_keys.push(CacheIdent::TableName(TableName::new( + &expr.catalog_name, + &expr.schema_name, + &expr.table_name, + ))); + } + let mut executor_context = to_executor_context(query_context, trigger_reason); + let (table_ids, exprs): (Vec<_>, Vec<_>) = tables_data.into_iter().unzip(); + if let Some(context) = &mut executor_context.query_context { + context.extensions.insert( + ALTER_LOGICAL_TABLE_IDS_EXTENSION_KEY.to_string(), + table_ids + .iter() + .map(ToString::to_string) + .collect::>() + .join(","), + ); + } + let request = SubmitDdlTaskRequest::new(DdlTask::new_alter_logical_tables(exprs)); - self.procedure_executor + let response = self + .procedure_executor .submit_ddl_task(executor_context, request) .await - .context(error::ExecuteDdlSnafu) + .context(error::ExecuteDdlSnafu)?; + // Metasrv notifications are asynchronous; callers need the updated local schema now. + self.cache_invalidator + .invalidate(&Context::default(), &invalidate_keys) + .await + .context(error::InvalidateTableCacheSnafu)?; + Ok(response) } async fn drop_table_procedure( diff --git a/src/plugins/src/frontend.rs b/src/plugins/src/frontend.rs index b8e56cf4668..608a9215216 100644 --- a/src/plugins/src/frontend.rs +++ b/src/plugins/src/frontend.rs @@ -18,6 +18,7 @@ use auth::{DefaultPermissionChecker, PermissionCheckerRef, UserProviderRef}; use common_base::Plugins; use common_base::secrets::ExposeSecret; use common_meta::cache::CacheRegistryBuilder; +use common_meta::cache_invalidator::KvCacheInvalidatorRef; use frontend::error::{IllegalAuthConfigSnafu, Result}; use frontend::frontend::FrontendOptions; use frontend::heartbeat::FrontendHeartbeatExtensions; @@ -87,7 +88,10 @@ pub async fn start_frontend_plugins(_instance: &Instance) -> Result<()> { } /// Allows frontend plugins to add cache invalidators to the layered registry. -pub fn configure_cache_registry(_plugins: &Plugins) -> Option { +pub fn configure_cache_registry( + _plugins: &Plugins, + _kv_cache: KvCacheInvalidatorRef, +) -> Option { None } diff --git a/src/query/src/optimizer/test_util.rs b/src/query/src/optimizer/test_util.rs index 09f72bb08b7..befaa62daad 100644 --- a/src/query/src/optimizer/test_util.rs +++ b/src/query/src/optimizer/test_util.rs @@ -109,6 +109,7 @@ impl RegionEngine for MetaRegionEngine { _role: RegionRole, _sent_at: std::time::Instant, _deadline: std::time::Instant, + _candidate_lease_id: Option, ) -> Result { unimplemented!() } diff --git a/src/relational-engine/src/engine.rs b/src/relational-engine/src/engine.rs index 3d84c10971d..9af0b520c92 100644 --- a/src/relational-engine/src/engine.rs +++ b/src/relational-engine/src/engine.rs @@ -116,6 +116,7 @@ impl RegionEngine for RelationalEngine { role: RegionRole, _sent_at: Instant, _deadline: Instant, + _candidate_lease_id: Option, ) -> Result { self.set_region_role(region_id, role).map(|_| true) } diff --git a/src/servers/AGENTS.md b/src/servers/AGENTS.md index d276becb685..aaf4374f764 100644 --- a/src/servers/AGENTS.md +++ b/src/servers/AGENTS.md @@ -39,6 +39,9 @@ provided through handler traits, mostly implemented by `frontend`. `QueryContext` state; never accept it from headers or serialized contexts. - New protocols or externally visible routes also require frontend service and configuration wiring. +- PostgreSQL Arrow COPY (`postgres/copy_in/arrow.rs`) adapts IPC framing to the + shared Flight `PutRecordBatchRequestStream`; preserve raw buffers for bulk + routing and keep ingestion behavior in the existing frontend Flight handler. ## Testing diff --git a/src/servers/Cargo.toml b/src/servers/Cargo.toml index 684697687ec..55b6f56e00d 100644 --- a/src/servers/Cargo.toml +++ b/src/servers/Cargo.toml @@ -82,6 +82,7 @@ jsonb.workspace = true lazy_static.workspace = true log-query.workspace = true loki-proto.workspace = true +lz4_flex.workspace = true meter-core.workspace = true meter-macros.workspace = true metric-engine.workspace = true diff --git a/src/servers/src/batcher/logical_table.rs b/src/servers/src/batcher/logical_table.rs index 707afe2ea0f..b7c0817e03a 100644 --- a/src/servers/src/batcher/logical_table.rs +++ b/src/servers/src/batcher/logical_table.rs @@ -108,6 +108,10 @@ pub struct LogicalTablePendingRowsBatcher { worker_channel_capacity: usize, prom_store_with_metric_engine: bool, schema_alterer: PendingRowsSchemaAltererRef, + /// Time index unit the schema alterer uses when auto-creating a missing + /// physical metric table; keeps the batcher's logical-create alignment + /// consistent with the created physical table. + auto_create_physical_table_timestamp_unit: TimeUnit, pending_rows_batch_sync: bool, shutdown: broadcast::Sender<()>, } @@ -123,6 +127,7 @@ impl LogicalTablePendingRowsBatcher { table_flownode_set_cache: TableFlownodeSetCacheRef, prom_store_with_metric_engine: bool, schema_alterer: PendingRowsSchemaAltererRef, + auto_create_physical_table_timestamp_unit: TimeUnit, flush_interval: Duration, max_batch_rows: usize, max_concurrent_flushes: usize, @@ -163,6 +168,7 @@ impl LogicalTablePendingRowsBatcher { flow_notification_tx, prom_store_with_metric_engine, schema_alterer, + auto_create_physical_table_timestamp_unit, flush_limiter, request_limiter, worker_channel_capacity, @@ -184,8 +190,8 @@ impl LogicalTablePendingRowsBatcher { } /// Returns the physical metric table's time index unit resolved from - /// `ctx`, defaulting to millisecond when the table does not exist yet - /// (the schema alterer auto-creates it as millisecond). + /// `ctx`, falling back to the configured auto-create unit when the table + /// does not exist yet (the schema alterer auto-creates it with that unit). async fn physical_time_index_unit_or_default(&self, ctx: &QueryContextRef) -> TimeUnit { let key = batch_key_from_ctx(ctx); let Ok(Some(table)) = self @@ -193,7 +199,7 @@ impl LogicalTablePendingRowsBatcher { .table(&key.catalog, &key.schema, &key.physical_table, None) .await else { - return TimeUnit::Millisecond; + return self.auto_create_physical_table_timestamp_unit; }; table .table_info() diff --git a/src/servers/src/batcher/logical_table/tables.rs b/src/servers/src/batcher/logical_table/tables.rs index 140dd2d4f23..8aef0df0b39 100644 --- a/src/servers/src/batcher/logical_table/tables.rs +++ b/src/servers/src/batcher/logical_table/tables.rs @@ -94,8 +94,8 @@ impl LogicalTablePendingRowsBatcher { // New tables are created on the request's selected physical table; // their time index must use the physical table's unit (a missing - // physical table is auto-created as millisecond by the schema - // alterer, matching the default here). + // physical table is auto-created in the configured auto-create unit + // by the schema alterer, matching the fallback here). if !plan.tables_to_create.is_empty() { let physical_unit = self.physical_time_index_unit_or_default(ctx).await; for (_, request_schema) in &mut plan.tables_to_create { diff --git a/src/servers/src/batcher/logical_table/test_util.rs b/src/servers/src/batcher/logical_table/test_util.rs index 364cf0c8f5a..6cf95af1f1c 100644 --- a/src/servers/src/batcher/logical_table/test_util.rs +++ b/src/servers/src/batcher/logical_table/test_util.rs @@ -32,6 +32,7 @@ use common_meta::node_manager::{ }; use common_meta::test_util::MockDatanodeManager; use common_query::prelude::GREPTIME_PHYSICAL_TABLE; +use common_time::timestamp::TimeUnit; use datatypes::prelude::ConcreteDataType; use datatypes::schema::{ColumnSchema as DtColumnSchema, Schema as DtSchema}; use operator::test_util::{create_partition_rule_manager, prepare_mocked_backend}; @@ -110,6 +111,7 @@ pub(crate) async fn submission_batcher( mock_table_flownode_cache(1, vec![]).await, true, Arc::new(UnexpectedSchemaAlterer), + TimeUnit::Millisecond, Duration::from_secs(1), 2, 1, diff --git a/src/servers/src/batcher/table.rs b/src/servers/src/batcher/table.rs index 7840fd355c4..db5ab6b77aa 100644 --- a/src/servers/src/batcher/table.rs +++ b/src/servers/src/batcher/table.rs @@ -31,20 +31,22 @@ use common_batcher::flush_policy::timing::TimingFlushPolicy; use common_batcher::request_limiter::RequestLimiter; use common_batcher::worker_registry::WorkerRegistry; use common_error::ext::BoxedError; +use common_memory_manager::OnExhaustedPolicy; use common_query::{Output, WriteCompletion, WriteProgress}; -use operator::batcher::PendingRowsBatcher; +use operator::batcher::{PendingRowsBatcher, PendingRowsPermit}; use operator::error::{ExternalSnafu, Result, UnexpectedSnafu}; use operator::insert::Inserter; use session::context::QueryContextRef; -use snafu::ResultExt; +use snafu::{IntoError, ResultExt}; use table::metadata::TableInfoRef; -use tokio::sync::{OwnedSemaphorePermit, Semaphore, broadcast, oneshot}; +use tokio::sync::{Semaphore, broadcast, oneshot}; use crate::batcher::pending_rows_batch_sync_enabled; use crate::batcher::table::flow_notifier::FlowNotifier; use crate::batcher::table::metrics::PENDING_WORKERS; use crate::batcher::table::pending_batch::PendingBatch; use crate::batcher::table::pending_worker::{PendingWorker, WorkerCommand, start_worker}; +use crate::request_memory_limiter::ServerMemoryLimiter; #[derive(Clone, Debug, Hash, PartialEq, Eq)] struct BatchKey { @@ -72,6 +74,7 @@ pub struct TablePendingRowsBatcher { flush_policy: TimingFlushPolicy, flush_limiter: FlushLimiter, request_limiter: RequestLimiter, + memory_limiter: ServerMemoryLimiter, worker_channel_capacity: usize, pending_rows_batch_sync: bool, worker_idle_timeout: Duration, @@ -82,6 +85,7 @@ pub struct TablePendingRowsBatcher { impl TablePendingRowsBatcher { /// Creates a shared timing batcher, rejecting disabled or unsupported limits. + #[allow(clippy::too_many_arguments)] pub fn try_new( flush_interval: Duration, max_batch_rows: usize, @@ -89,6 +93,7 @@ impl TablePendingRowsBatcher { worker_channel_capacity: usize, max_inflight_requests: usize, flow_notification_queue_capacity: NonZeroUsize, + memory_limiter: ServerMemoryLimiter, inserter: Arc, ) -> Option> { if worker_channel_capacity == 0 @@ -113,6 +118,7 @@ impl TablePendingRowsBatcher { flush_policy, flush_limiter, request_limiter, + memory_limiter, worker_channel_capacity, pending_rows_batch_sync: pending_rows_batch_sync_enabled(), worker_idle_timeout: flush_interval.checked_mul(3).unwrap_or(flush_interval), @@ -154,15 +160,43 @@ impl Drop for TablePendingRowsBatcher { #[async_trait] impl PendingRowsBatcher for TablePendingRowsBatcher { + fn memory_limit_bytes(&self) -> u64 { + self.memory_limiter.limit_bytes() + } + /// Acquires once per original request, before submitting any of its tables. /// Retain a clone in every submission until its flush has completed. - async fn acquire(&self) -> Result> { - self.request_limiter.acquire().await.map_err(|_| { + async fn acquire(&self, estimated_bytes: usize, held_bytes: u64) -> Result { + let permit = self.request_limiter.acquire().await.map_err(|_| { UnexpectedSnafu { violated: "batcher admission closed".to_string(), } .build() - }) + })?; + if self.memory_limit_bytes() == 0 { + return Ok(permit); + } + let bytes = u64::try_from(estimated_bytes).unwrap_or(u64::MAX); + let reserve = || { + self.memory_limiter.check_request_fits(bytes, held_bytes)?; + self.memory_limiter.try_acquire(bytes).ok_or_else(|| { + let source = common_memory_manager::Error::MemoryLimitExceeded { + requested_bytes: bytes, + limit_bytes: self.memory_limit_bytes(), + }; + // Remote Write senders must retry contention under the wait policy. + match self.memory_limiter.policy() { + OnExhaustedPolicy::Wait { .. } => { + crate::error::OtherSnafu.into_error(BoxedError::new(source)) + } + OnExhaustedPolicy::Fail => { + crate::error::MemoryLimitExceededSnafu.into_error(source) + } + } + }) + }; + let memory = reserve().map_err(BoxedError::new).context(ExternalSnafu)?; + Ok(Arc::new((permit, memory))) } /// Acknowledges according to the global batching policy. Cancellation does @@ -172,7 +206,7 @@ impl PendingRowsBatcher for TablePendingRowsBatcher { table_info: TableInfoRef, batch: RecordBatch, ctx: QueryContextRef, - permit: Arc, + permit: PendingRowsPermit, ) -> Result { let total_rows = batch.num_rows(); let confirmed = ctx.confirmed_writes(); @@ -262,6 +296,7 @@ mod tests { use common_batcher::worker_registry::WorkerRegistry; use common_catalog::consts::default_engine; use common_grpc::flight::FlightDecoder; + use common_memory_manager::OnExhaustedPolicy; use common_meta::error::Result as MetaResult; use common_meta::peer::Peer; use common_meta::test_util::{MockDatanodeHandler, MockDatanodeManager}; @@ -292,6 +327,7 @@ mod tests { use crate::batcher::table::pending_worker::{WorkerCommand, start_worker}; use crate::batcher::table::{PendingWorkers, TablePendingRowsBatcher, batch_key_from_ctx}; use crate::batcher::test_util::mock_table_flownode_cache; + use crate::request_memory_limiter::ServerMemoryLimiter; #[derive(Clone)] struct BulkHandler { @@ -337,6 +373,8 @@ mod tests { #[tokio::test] async fn test_acknowledgement_preserves_admission() { + use common_error::ext::ErrorExt; + use common_error::status_code::StatusCode; use operator::error::UnexpectedSnafu; use crate::batcher::pending_rows_batch_sync_enabled; @@ -344,7 +382,8 @@ mod tests { use crate::batcher::table::pending_batch::notify_batches; for sync in [false, true] { - for fail in [false, true] { + for outcome in ["success", "failure", "cancel"] { + let fail = outcome == "failure"; let backend = prepare_mocked_backend().await; let nodes = Arc::new(MockDatanodeManager::new(BulkHandler { requests: Arc::new(Mutex::new(Vec::new())), @@ -359,6 +398,12 @@ mod tests { mock_table_flownode_cache(1, vec![]).await, true, )); + let policy = if sync { + OnExhaustedPolicy::default() + } else { + OnExhaustedPolicy::Fail + }; + let memory = ServerMemoryLimiter::new(4096, policy); let mut batcher = TablePendingRowsBatcher::try_new( Duration::from_secs(3600), 1, @@ -366,6 +411,7 @@ mod tests { 1, 1, NonZeroUsize::new(1).unwrap(), + memory.clone(), inserter, ) .unwrap(); @@ -374,6 +420,31 @@ mod tests { pending_rows_batch_sync_enabled() ); Arc::get_mut(&mut batcher).unwrap().pending_rows_batch_sync = sync; + assert!(batcher.acquire(4097, 0).await.is_err()); + let held = memory.try_acquire(3072).unwrap(); + let Err(error) = batcher.acquire(2048, held.granted_bytes()).await else { + panic!("body and conversion together exceed the entire quota"); + }; + assert_eq!(error.status_code(), StatusCode::RateLimited); + let additional = batcher.acquire(1024, held.granted_bytes()).await.unwrap(); + assert_eq!(memory.used_bytes(), 4096); + drop(additional); + // The same occupied quota belongs to another request and can be released. + let acquire = batcher.acquire(2048, 0); + tokio::pin!(acquire); + let std::task::Poll::Ready(Err(error)) = futures::poll!(acquire.as_mut()) else { + panic!("conversion memory must not wait while a request holds other permits"); + }; + assert_eq!( + error.status_code(), + if sync { + StatusCode::RuntimeResourcesExhausted + } else { + StatusCode::RateLimited + } + ); + drop(held); + assert_eq!(memory.used_bytes(), 0); let table = Arc::new(new_test_table_info(1, "ack", [0].into_iter())); let progress = Arc::new(session::write_progress::WriteProgress::default()); let mut ctx = QueryContext::with("greptime", "public"); @@ -388,7 +459,7 @@ mod tests { Arc::new(Int32Array::from(vec![1])) as ArrayRef, )]) .unwrap(); - let permit = batcher.acquire().await.unwrap(); + let permit = batcher.acquire(2048, 0).await.unwrap(); let submitter = batcher.clone(); let submitted = tokio::spawn(async move { submitter.submit(table, batch, ctx, permit).await }); @@ -415,8 +486,16 @@ mod tests { } assert_eq!(progress.accepted(), !sync); assert_eq!(progress.written(), 0); + if outcome == "cancel" { + if let Some(submitted) = submitted.take() { + submitted.abort(); + assert!(submitted.await.unwrap_err().is_cancelled()); + } + drop(completion.take()); + } + assert_eq!(memory.used_bytes(), 2048); // Early acknowledgement must not release capacity before completion. - let acquire = batcher.acquire(); + let acquire = batcher.acquire(0, 0); tokio::pin!(acquire); assert!(futures::poll!(acquire.as_mut()).is_pending()); let result = if fail { @@ -430,6 +509,7 @@ mod tests { Ok(()) }; notify_batches(vec![pending], result); + assert_eq!(memory.used_bytes(), 0); if let Some(submitted) = submitted { let result = timeout(Duration::from_secs(5), submitted) .await @@ -538,6 +618,7 @@ mod tests { 4, if shared_request { 1 } else { 4 }, NonZeroUsize::new(16).unwrap(), + ServerMemoryLimiter::default(), inserter, ) .unwrap(); @@ -555,7 +636,7 @@ mod tests { opentsdb_ctx.set_skip_wal(skip_wal); let (first_result, second_result) = timeout(Duration::from_secs(5), async { if shared_request { - let permit = batcher.acquire().await.unwrap(); + let permit = batcher.acquire(0, 0).await.unwrap(); let (first, second) = tokio::join!( batcher.submit(table.clone(), first, influx_ctx, permit.clone()), batcher.submit(table.clone(), second, opentsdb_ctx, permit), @@ -740,6 +821,7 @@ mod tests { 4, 4, NonZeroUsize::new(16).unwrap(), + ServerMemoryLimiter::default(), inserter, ) .unwrap(); @@ -756,8 +838,8 @@ mod tests { ctx.set_write_progress(counter.clone()); Arc::new(ctx) }); - let first_permit = batcher.acquire().await.unwrap(); - let second_permit = batcher.acquire().await.unwrap(); + let first_permit = batcher.acquire(0, 0).await.unwrap(); + let second_permit = batcher.acquire(0, 0).await.unwrap(); let (first, second) = tokio::join!( batcher.submit(table.clone(), first, contexts[0].clone(), first_permit), batcher.submit(table, second, contexts[1].clone(), second_permit), diff --git a/src/servers/src/batcher/table/pending_batch.rs b/src/servers/src/batcher/table/pending_batch.rs index c4545f5992a..4fd235499ed 100644 --- a/src/servers/src/batcher/table/pending_batch.rs +++ b/src/servers/src/batcher/table/pending_batch.rs @@ -17,11 +17,12 @@ use std::sync::Arc; use arrow::record_batch::RecordBatch; use common_error::ext::BoxedError; use common_query::WriteProgress; +use operator::batcher::PendingRowsPermit; use operator::error::Error; use session::context::QueryContextRef; use snafu::IntoError; use table::metadata::TableInfoRef; -use tokio::sync::{OwnedSemaphorePermit, oneshot}; +use tokio::sync::oneshot; /// One complete input and its completion/admission ownership. pub(in crate::batcher::table) struct PendingBatch { @@ -29,7 +30,7 @@ pub(in crate::batcher::table) struct PendingBatch { pub batch: RecordBatch, pub ctx: QueryContextRef, pub response_tx: oneshot::Sender, - pub _permit: Arc, + pub _permit: PendingRowsPermit, pub _completion: Option, } diff --git a/src/servers/src/exemplar.rs b/src/servers/src/exemplar.rs index 986c7212181..ed7d381502c 100644 --- a/src/servers/src/exemplar.rs +++ b/src/servers/src/exemplar.rs @@ -24,7 +24,7 @@ use api::v1::{ColumnDataType, Row, RowInsertRequests, Value}; use common_catalog::consts::METRICS_EXEMPLARS_TABLE; use common_grpc::precision::Precision; 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 datatypes::json; use metric_engine::row_modifier::TsidGenerator; @@ -120,7 +120,7 @@ where greptime_timestamp(), greptime_value(), EXEMPLAR_METRIC_COLUMN, - EXEMPLAR_LABELS_COLUMN, + greptime_exemplar_labels(), DATA_SCHEMA_TABLE_ID_COLUMN_NAME, DATA_SCHEMA_TSID_COLUMN_NAME, ] @@ -225,7 +225,7 @@ pub fn into_rows(exemplars: Vec) -> Result<(RowInsertRequests, BTreeSe row_writer::write_by_schema( table, std::iter::once(( - row_writer::build_json2_column_schema(EXEMPLAR_LABELS_COLUMN)?, + row_writer::build_json2_column_schema(greptime_exemplar_labels())?, Some(row_writer::encode_json2(exemplar.labels)?), )), &mut row, @@ -276,9 +276,18 @@ mod tests { for name in [ DATA_SCHEMA_TABLE_ID_COLUMN_NAME, DATA_SCHEMA_TSID_COLUMN_NAME, + greptime_exemplar_labels(), ] { assert!(labels([(name.into(), "x".into())], false, validate_label_name).is_err()); } + assert!( + labels( + [("exemplar_labels".into(), "x".into())], + false, + validate_label_name, + ) + .is_ok() + ); assert_eq!(timestamp_from_millis(-1).unwrap(), -1_000_000); assert!(timestamp_from_millis(i64::MAX).is_err()); } diff --git a/src/servers/src/exemplar/query.rs b/src/servers/src/exemplar/query.rs index 64cf609bd9d..0087c964b21 100644 --- a/src/servers/src/exemplar/query.rs +++ b/src/servers/src/exemplar/query.rs @@ -137,6 +137,7 @@ fn resolve(selector: &VectorSelector, default_schema: &str) -> Result, pub exemplars: Vec, diff --git a/src/servers/src/grpc/flight.rs b/src/servers/src/grpc/flight.rs index a7514e889d6..d5759cc833e 100644 --- a/src/servers/src/grpc/flight.rs +++ b/src/servers/src/grpc/flight.rs @@ -346,7 +346,7 @@ impl PutRecordBatchRequest { } pub struct PutRecordBatchRequestStream { - flight_data_stream: Streaming, + flight_data_stream: TonicStream, catalog: String, schema_name: String, limiter: Option, @@ -369,13 +369,13 @@ impl PutRecordBatchRequestStream { /// Creates a new `PutRecordBatchRequestStream` in Init state. /// The stream will transition to Ready state when it receives the schema message. pub async fn new( - flight_data_stream: Streaming, + flight_data_stream: impl Stream> + Send + 'static, catalog: String, schema: String, limiter: Option, ) -> TonicResult { Ok(Self { - flight_data_stream, + flight_data_stream: Box::pin(flight_data_stream), catalog, schema_name: schema, limiter, diff --git a/src/servers/src/http.rs b/src/servers/src/http.rs index 13be8b03b2a..a8d70e8fb37 100644 --- a/src/servers/src/http.rs +++ b/src/servers/src/http.rs @@ -240,9 +240,16 @@ pub async fn set_http_write_batching( .extensions() .get::() .is_some_and(|protocols| protocols.0.contains(&protocol)); + let body_memory_bytes = req + .extensions() + .get::() + .map(memory_limit::BodyMemoryAccounting::reserved_bytes_counter); if let Some(ctx) = req.extensions_mut().get_mut::() { ctx.set_batching_enabled(enabled); ctx.set_logical_batching_enabled(logical_enabled); + if let Some(bytes) = body_memory_bytes { + ctx.set_body_memory_bytes(bytes); + } } next.run(req).await } diff --git a/src/servers/src/http/memory_limit.rs b/src/servers/src/http/memory_limit.rs index 255920974fd..16c40ba0006 100644 --- a/src/servers/src/http/memory_limit.rs +++ b/src/servers/src/http/memory_limit.rs @@ -31,8 +31,8 @@ //! buffers that outlive the body stream itself). use std::pin::Pin; -use std::sync::atomic::{AtomicBool, Ordering}; -use std::sync::{Arc, Mutex}; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::sync::{Arc, Mutex, Weak}; use std::task::{Context, Poll}; use axum::body::Body; @@ -182,6 +182,7 @@ pub async fn decoded_body_accounting_middleware( #[derive(Clone, Default)] pub(crate) struct BodyMemoryAccounting { guards: Arc>>>, + reserved_bytes: Arc, /// Set when an incremental charge hit the quota, so the rejection can be /// rewritten into a 429 after the middleware regains control. quota_exceeded: Arc, @@ -190,15 +191,17 @@ pub(crate) struct BodyMemoryAccounting { impl BodyMemoryAccounting { /// Includes permit rounding and all frames collected so far. pub(crate) fn reserved_bytes(&self) -> u64 { - self.guards - .lock() - .unwrap() - .iter() - .map(MemoryGuard::granted_bytes) - .sum() + self.reserved_bytes.load(Ordering::Acquire) + } + + /// Observes subsequent body charges without extending the guards' lifetime. + pub(crate) fn reserved_bytes_counter(&self) -> Weak { + Arc::downgrade(&self.reserved_bytes) } fn hold(&self, guard: MemoryGuard) { + self.reserved_bytes + .fetch_add(guard.granted_bytes(), Ordering::Release); self.guards.lock().unwrap().push(guard); } @@ -534,6 +537,79 @@ mod tests { Body::from(compressed) } + #[tokio::test] + async fn test_body_reservations_follow_context_without_extending_lifetime() { + use std::sync::{Arc, Mutex}; + + use axum::Extension; + use session::context::QueryContext; + use tower_http::decompression::RequestDecompressionLayer; + + use crate::batcher::BatchingProtocol; + use crate::http::set_http_write_batching; + + for limit in [0, 8 * 1024] { + for compressed in [false, true] { + let limiter = ServerMemoryLimiter::new(limit, OnExhaustedPolicy::default()); + let captured = Arc::new(Mutex::new(None)); + let output = captured.clone(); + let memory = limiter.clone(); + let app = Router::new() + .route( + "/echo", + post( + move |Extension(ctx): Extension, body: Bytes| async move { + assert_eq!(body.len(), 1536); + assert!(ctx.batching_enabled()); + assert!(ctx.held_memory_bytes() >= body.len() as u64); + assert_eq!(ctx.held_memory_bytes(), memory.used_bytes()); + *output.lock().unwrap() = Some(ctx.with_write_admission()); + StatusCode::OK + }, + ), + ) + .layer(middleware::from_fn_with_state( + limiter.clone(), + super::decoded_body_accounting_middleware, + )) + .layer(RequestDecompressionLayer::new()) + .layer(middleware::from_fn_with_state( + BatchingProtocol::Influxdb, + set_http_write_batching, + )) + .layer(Extension(QueryContext::with("greptime", "public"))) + .layer(Extension(Arc::new(vec![BatchingProtocol::Influxdb]))) + .layer(middleware::from_fn_with_state( + limiter.clone(), + memory_limit_middleware, + )); + let body = vec![b'x'; 1536]; + let body = if compressed { + zstd::stream::encode_all(body.as_slice(), 3).unwrap() + } else { + body + }; + let mut request = chunked_request("/echo", body, 512); + if compressed { + request + .headers_mut() + .insert(header::CONTENT_ENCODING, "zstd".parse().unwrap()); + } + assert_eq!(app.oneshot(request).await.unwrap().status(), StatusCode::OK); + assert_eq!(limiter.used_bytes(), 0); + assert_eq!( + captured + .lock() + .unwrap() + .as_ref() + .unwrap() + .held_memory_bytes(), + 0 + ); + } + } + } + #[tokio::test] async fn test_decompressed_body_is_charged_for_content_encoded_requests() { // The decoded size (64 KiB) exceeds the 16 KiB quota: the accounting diff --git a/src/servers/src/http/prom_store.rs b/src/servers/src/http/prom_store.rs index 94613462e70..86d8bba795f 100644 --- a/src/servers/src/http/prom_store.rs +++ b/src/servers/src/http/prom_store.rs @@ -347,7 +347,10 @@ async fn ingest_remote_write_v1_inner( }); let mut ctx = query_ctx.fork(); ctx.set_write_progress(Arc::new( - session::write_progress::WriteProgress::with_reservation(reservation), + session::write_progress::WriteProgress::with_reservation( + reservation.granted_bytes(), + reservation, + ), )); Arc::new(ctx) }; @@ -503,8 +506,11 @@ pub(crate) async fn ingest_remote_write_v2( let counter = crate::metrics::PROM_STORE_REMOTE_WRITE_EXEMPLARS .with_label_values(&[db, REMOTE_WRITE_V2_VERSION]); query_ctx.set_write_progress(Arc::new( - session::write_progress::WriteProgress::with_reservation(req.memory_guard.clone()) - .with_observer(move |rows| counter.inc_by(rows)), + session::write_progress::WriteProgress::with_reservation( + req.memory_guard.granted_bytes(), + req.memory_guard.clone(), + ) + .with_observer(move |rows| counter.inc_by(rows)), )); } let query_ctx = Arc::new(query_ctx); @@ -521,9 +527,11 @@ pub(crate) async fn ingest_remote_write_v2( }; for (ctx, _) in batches { let counter = counter.clone(); - let progress = - session::write_progress::WriteProgress::with_reservation(req.memory_guard.clone()) - .with_observer(move |rows| counter.inc_by(rows)); + let progress = session::write_progress::WriteProgress::with_reservation( + req.memory_guard.granted_bytes(), + req.memory_guard.clone(), + ) + .with_observer(move |rows| counter.inc_by(rows)); let mut fork = ctx.fork(); fork.set_write_progress(Arc::new(progress)); *ctx = Arc::new(fork); diff --git a/src/servers/src/http/prom_store/exemplar.rs b/src/servers/src/http/prom_store/exemplar.rs index d6524e9ce71..30ad9246bc2 100644 --- a/src/servers/src/http/prom_store/exemplar.rs +++ b/src/servers/src/http/prom_store/exemplar.rs @@ -17,6 +17,7 @@ use std::sync::Arc; use api::v1::RowInsertRequests; use common_error::ext::BoxedError; +use common_query::Output; use futures::future::ready; use operator::insert::PreparedMetricInserts; use session::context::QueryContextRef; @@ -37,6 +38,24 @@ pub(super) struct Outcome { pub error: Option, } +impl Outcome { + async fn record(&mut self, kind: usize, output: Result) { + match output { + Ok(output) => { + self.cost += output.meta.cost; + let progress = output.write_progress().await; + self.written[kind] += progress.affected_rows as u64; + if let Err(error) = progress.into_result().context(error::ExecuteGrpcQuerySnafu) { + self.error.get_or_insert(error); + } + } + Err(error) => { + self.error.get_or_insert(error); + } + } + } +} + enum PreparedWrite { Metric(PreparedMetricInserts), Rows(RowInsertRequests), @@ -56,7 +75,7 @@ pub(super) async fn write( Ok((writes, targets)) => { let mut sources = Vec::new(); let mut prepared = Vec::new(); - let mut source_preparation_failed = false; + let mut source_failed = false; for (kind, ctx, request) in writes { if kind != 2 && metric_engine { let (pinned, other): (Vec<_>, Vec<_>) = @@ -84,7 +103,7 @@ pub(super) async fn write( if let Ok(request) = &result { sources.extend(request.source_tables().cloned()); } else { - source_preparation_failed = true; + source_failed = true; } prepared.push((kind, ctx, result.map(PreparedWrite::Metric))); } @@ -93,7 +112,7 @@ pub(super) async fn write( } } // A failed source preparation must not fall back to a newer table with the same name. - if source_preparation_failed { + if source_failed { prepared.retain(|(kind, _, _)| *kind != 2); } let sample_batches = prepared.iter().filter_map(|(kind, ctx, request)| { @@ -113,9 +132,11 @@ pub(super) async fn write( } else { None }; - let mut outputs = Vec::with_capacity(prepared.len()); - // Serialize schema preparation across batches that resolve to the same table. - for (kind, ctx, request) in prepared { + let (related, other): (Vec<_>, Vec<_>) = + prepared.into_iter().partition(|(kind, _, request)| { + *kind == 2 || !matches!(request, Ok(PreparedWrite::Rows(_))) + }); + let submit = async |(kind, ctx, request)| { let mut deferred = false; let output = match request { Err(error) => Err(error), @@ -145,29 +166,41 @@ pub(super) async fn write( } } }; - outputs.push((kind, output, deferred)); - } + (output, deferred) + }; let mut outcome = Outcome::default(); + let ((), outputs) = tokio::join!( + async { + for write in related { + let kind = write.0; + if kind == 2 && source_failed { + continue; + } + let (output, _) = submit(write).await; + // Successful submissions can still carry source storage failures. + outcome.record(kind, output).await; + source_failed |= kind != 2 && outcome.error.is_some(); + } + }, + async { + let mut outputs = Vec::with_capacity(other.len()); + // Serialize schema preparation for batches resolving to the same table. + for write in other { + let kind = write.0; + let (output, deferred) = submit(write).await; + outputs.push((kind, output, deferred)); + } + outputs + }, + ); let mut pending_samples = Vec::new(); for (kind, output, deferred) in outputs { match output { - Ok(output) => { + Ok(output) if deferred && !output.meta.write_completions.is_empty() => { outcome.cost += output.meta.cost; - if deferred && !output.meta.write_completions.is_empty() { - pending_samples.push(output); - continue; - } - let progress = output.write_progress().await; - outcome.written[kind] += progress.affected_rows as u64; - if let Err(error) = - progress.into_result().context(error::ExecuteGrpcQuerySnafu) - { - outcome.error.get_or_insert(error); - } - } - Err(error) => { - outcome.error.get_or_insert(error); + pending_samples.push(output); } + output => outcome.record(kind, output).await, } } if outcome.error.is_none() { @@ -265,17 +298,85 @@ mod tests { use crate::exemplar::Exemplar; use crate::query_handler::{PromStoreProtocolHandler, PromStoreResponse}; + #[derive(Clone, Copy, Default)] + enum WriteResult { + #[default] + Success, + ImmediateFailure, + CompletionFailure, + } + #[derive(Default)] struct Handler { events: Mutex>, - exemplar_done: Arc, + source_result: WriteResult, + other_result: WriteResult, + source_completion: Option>, + other_submission: Option>, deny_schema: bool, fail_preparation: bool, - successful_writes: bool, check_serial: bool, writing: AtomicBool, } + impl Handler { + async fn write_metric(&self, ctx: QueryContextRef, source: bool) -> Result { + if self.check_serial && !source { + assert!(!self.writing.swap(true, Ordering::SeqCst)); + tokio::task::yield_now().await; + self.writing.store(false, Ordering::SeqCst); + } + assert!(ctx.confirmed_writes()); + assert_eq!( + ctx.write_rows_to_admit(ctx.current_catalog(), &ctx.current_schema(), 3), + 0 + ); + self.events.lock().unwrap().push("metric".into()); + let result = if source { + self.source_result + } else { + self.other_result + }; + if matches!(result, WriteResult::ImmediateFailure) { + return error::InternalSnafu { + err_msg: "immediate metric failure", + } + .fail(); + } + let gate = source.then(|| self.source_completion.clone()).flatten(); + let counter = ctx.write_progress().cloned(); + let completion = WriteCompletion::with_progress(async move { + if let Some(gate) = gate { + gate.notified().await; + } + let failed = matches!(result, WriteResult::CompletionFailure); + let affected_rows = if failed { 1 } else { 2 }; + if let Some(counter) = counter { + counter.add_written(affected_rows); + } + WriteProgress { + affected_rows, + error: failed.then(|| { + Arc::new(BoxedError::new( + error::InternalSnafu { + err_msg: "late metric failure", + } + .build(), + )) + }), + } + }); + Ok(Output::new( + OutputData::AffectedRows(2), + OutputMeta { + cost: 2, + write_completions: vec![completion], + ..Default::default() + }, + )) + } + } + #[async_trait] impl PromStoreProtocolHandler for Handler { async fn prepare_metric_write( @@ -297,8 +398,7 @@ mod tests { _: PreparedMetricInserts, ctx: QueryContextRef, ) -> Result { - self.write_prepared(RowInsertRequests::default(), ctx, true) - .await + self.write_metric(ctx, true).await } async fn pre_write(&self, request: &RowInsertRequests, ctx: QueryContextRef) -> Result<()> { @@ -338,48 +438,10 @@ mod tests { ctx: QueryContextRef, _: bool, ) -> Result { - if self.check_serial { - assert!(!self.writing.swap(true, Ordering::SeqCst)); - tokio::task::yield_now().await; - self.writing.store(false, Ordering::SeqCst); + if let Some(gate) = &self.other_submission { + gate.notified().await; } - assert!(ctx.confirmed_writes()); - assert_eq!( - ctx.write_rows_to_admit(ctx.current_catalog(), &ctx.current_schema(), 3), - 0 - ); - self.events.lock().unwrap().push("metric".into()); - if self.successful_writes { - if let Some(counter) = ctx.write_progress() { - counter.add_written(2); - } - return Ok(Output::new_with_affected_rows(2)); - } - let done = self.exemplar_done.clone(); - let counter = ctx.write_progress().cloned(); - let completion = WriteCompletion::with_progress(async move { - done.notified().await; - if let Some(counter) = counter { - counter.add_written(1); - } - WriteProgress { - affected_rows: 1, - error: Some(Arc::new(BoxedError::new( - error::InternalSnafu { - err_msg: "late metric failure", - } - .build(), - ))), - } - }); - Ok(Output::new( - OutputData::AffectedRows(2), - OutputMeta { - cost: 2, - write_completions: vec![completion], - ..Default::default() - }, - )) + self.write_metric(ctx, false).await } async fn write_exemplars_prepared( @@ -396,7 +458,6 @@ mod tests { if let Some(counter) = ctx.write_progress() { counter.add_written(1); } - self.exemplar_done.notify_one(); Ok(Output::new( OutputData::AffectedRows(1), OutputMeta::new_with_cost(1), @@ -418,6 +479,34 @@ mod tests { } } + fn metric_request(tables: &[&str], num_rows: usize) -> RowInsertRequests { + RowInsertRequests { + inserts: tables + .iter() + .map(|name| RowInsertRequest { + table_name: (*name).into(), + rows: Some(Rows { + schema: vec![], + rows: vec![Row { values: vec![] }; num_rows], + }), + }) + .collect(), + } + } + + fn exemplar_requests(schema: Option) -> ExemplarRequests { + ExemplarRequests::from([( + schema, + vec![Exemplar { + metric: "metric".into(), + series_labels: BTreeMap::new().into(), + labels: BTreeMap::new(), + timestamp: 1, + value: 1.0, + }], + )]) + } + #[tokio::test] async fn exemplar_requires_successful_metric_engine_source_preparation() { for metric_engine in [false, true] { @@ -427,38 +516,17 @@ mod tests { }); let ctx = QueryContext::arc(); let samples = if metric_engine { - vec![( - ctx.clone(), - RowInsertRequests { - inserts: vec![RowInsertRequest { - table_name: "metric".into(), - rows: Some(Rows { - schema: vec![], - rows: vec![Row { values: vec![] }], - }), - }], - }, - )] + vec![(ctx.clone(), metric_request(&["metric"], 1))] } else { vec![] }; - let exemplars = ExemplarRequests::from([( - None, - vec![Exemplar { - metric: "metric".into(), - series_labels: BTreeMap::new().into(), - labels: BTreeMap::new(), - timestamp: 1, - value: 1.0, - }], - )]); let outcome = write( handler.clone(), None, metric_engine, samples, vec![], - exemplars, + exemplar_requests(None), ctx, ) .await; @@ -488,29 +556,8 @@ mod tests { if let Some(physical) = physical { target.set_extension(PHYSICAL_TABLE_PARAM, physical); } - ( - Arc::new(target), - RowInsertRequests { - inserts: vec![RowInsertRequest { - table_name: "metric".into(), - rows: Some(Rows { - schema: vec![], - rows: vec![Row { values: vec![] }], - }), - }], - }, - ) + (Arc::new(target), metric_request(&["metric"], 1)) }; - let exemplars = ExemplarRequests::from([( - None, - vec![Exemplar { - metric: "metric".into(), - series_labels: BTreeMap::new().into(), - labels: BTreeMap::new(), - timestamp: 1, - value: 1.0, - }], - )]); let (writes, targets) = prepare( &handler, vec![ @@ -519,7 +566,7 @@ mod tests { batch(None), ], vec![batch(Some("histogram_physical"))], - exemplars, + exemplar_requests(None), ctx, ) .await @@ -547,45 +594,154 @@ mod tests { } #[tokio::test] - async fn exemplar_submits_metric_batches_sequentially() { + async fn exemplar_submits_unrelated_metric_batches_sequentially() { let handler = Arc::new(Handler { - successful_writes: true, check_serial: true, ..Default::default() }); let ctx = QueryContext::arc(); let samples = ["metric", "other", "other"] .into_iter() - .map(|name| { - ( - Arc::new(ctx.fork()), - RowInsertRequests { - inserts: vec![RowInsertRequest { - table_name: name.into(), - rows: Some(Rows { - schema: vec![], - rows: vec![Row { values: vec![] }; 2], - }), - }], - }, - ) - }) + .map(|name| (Arc::new(ctx.fork()), metric_request(&[name], 2))) .collect(); - let exemplars = ExemplarRequests::from([( + let outcome = write( + handler, None, - vec![Exemplar { - metric: "metric".into(), - series_labels: BTreeMap::new().into(), - labels: BTreeMap::new(), - timestamp: 1, - value: 1.0, - }], - )]); - let outcome = write(handler, None, true, samples, vec![], exemplars, ctx).await; + true, + samples, + vec![], + exemplar_requests(None), + ctx, + ) + .await; assert!(outcome.error.is_none()); assert_eq!(outcome.written, [6, 0, 1]); } + #[tokio::test] + async fn exemplar_waits_for_source_completion() { + for histogram in [false, true] { + for failed in [false, true] { + for block_source in [false, true] { + let gate = Arc::new(Notify::new()); + let handler = Arc::new(Handler { + source_result: if failed { + WriteResult::CompletionFailure + } else { + WriteResult::Success + }, + source_completion: block_source.then(|| gate.clone()), + other_submission: (!block_source).then(|| gate.clone()), + ..Default::default() + }); + let ctx = QueryContext::arc(); + let batch = |name: &str| (ctx.clone(), metric_request(&[name], 2)); + let (samples, histograms) = if histogram { + (vec![batch("other")], vec![batch("metric")]) + } else { + (vec![batch("metric"), batch("other")], vec![]) + }; + let response = write( + handler.clone(), + None, + true, + samples, + histograms, + exemplar_requests(None), + ctx, + ); + tokio::pin!(response); + assert!(futures::poll!(&mut response).is_pending()); + { + let events = handler.events.lock().unwrap(); + assert_eq!( + events.iter().filter(|event| *event == "metric").count(), + 1 + usize::from(block_source) + ); + assert_eq!( + events.iter().any(|event| event == "exemplar"), + !block_source && !failed + ); + } + gate.notify_one(); + let outcome = response.await; + let source_rows = if failed { 1 } else { 2 }; + let exemplars = u64::from(!failed); + assert_eq!(outcome.error.is_some(), failed); + assert_eq!( + outcome.written, + if histogram { + [2, source_rows, exemplars] + } else { + [2 + source_rows, 0, exemplars] + } + ); + assert_eq!(outcome.cost, 4 + exemplars as usize); + } + } + } + } + + #[tokio::test] + async fn exemplar_only_depends_on_its_source_writes() { + for (source_result, other_result, source_rows, other_rows, exemplars) in [ + ( + WriteResult::ImmediateFailure, + WriteResult::Success, + Some(0), + 2, + 0, + ), + ( + WriteResult::Success, + WriteResult::ImmediateFailure, + Some(2), + 0, + 1, + ), + ( + WriteResult::Success, + WriteResult::CompletionFailure, + Some(2), + 1, + 1, + ), + ( + WriteResult::Success, + WriteResult::CompletionFailure, + None, + 1, + 1, + ), + ] { + let handler = Arc::new(Handler { + source_result, + other_result, + ..Default::default() + }); + let ctx = QueryContext::arc(); + let tables = [Some("other"), source_rows.map(|_| "metric")] + .into_iter() + .flatten() + .collect::>(); + let outcome = write( + handler, + None, + true, + vec![(ctx.clone(), metric_request(&tables, 2))], + vec![], + exemplar_requests(None), + ctx, + ) + .await; + assert!(outcome.error.is_some()); + assert_eq!( + outcome.written, + [source_rows.unwrap_or(0) + other_rows, 0, exemplars] + ); + } + } + #[tokio::test] async fn exemplar_v2_batching_acknowledgement_and_partial_counts() { use api::greptime_proto::io::prometheus::write::v2; @@ -650,12 +806,17 @@ mod tests { }, ], }; + let handler = Arc::new(Handler { + source_result: if successful_writes { + WriteResult::Success + } else { + WriteResult::CompletionFailure + }, + ..Default::default() + }); let response = remote_write_v2( PromStoreState { - prom_store_handler: Arc::new(Handler { - successful_writes, - ..Default::default() - }), + prom_store_handler: handler.clone(), pipeline_handler: None, prom_store_with_metric_engine: true, prom_validation_mode: PromValidationMode::Strict, @@ -689,6 +850,15 @@ mod tests { command = receiver.recv() => command.unwrap(), }; assert_eq!(early_response.is_some(), !sync && successful_writes); + assert_eq!( + handler + .events + .lock() + .unwrap() + .iter() + .any(|event| event == "exemplar"), + successful_writes + ); assert!(limiter.used_bytes() > 0); let WorkerCommand::Submit { ctx, @@ -730,18 +900,17 @@ mod tests { for (kind, count) in [ ("samples", samples), ("histograms", "0"), - ("exemplars", "1"), + ("exemplars", if successful_writes { "1" } else { "0" }), ] { assert_eq!( response.headers()[format!("x-prometheus-remote-write-{kind}-written")], count ); } - for ((counter, before), count) in counters - .into_iter() - .zip(before) - .zip([if successful_writes { 4 } else { 2 }, 1]) - { + for ((counter, before), count) in counters.into_iter().zip(before).zip([ + if successful_writes { 4 } else { 2 }, + u64::from(successful_writes), + ]) { assert_eq!(counter.get() - before, count); } drop(ctx); @@ -754,38 +923,15 @@ mod tests { for denied in [false, true] { let handler = Arc::new(Handler { deny_schema: denied, + source_result: WriteResult::CompletionFailure, ..Default::default() }); - let mut exemplars = ExemplarRequests::new(); - for schema in if denied { - vec![None, Some("other".into())] - } else { - vec![None] - } { - exemplars.insert( - schema, - vec![Exemplar { - metric: "metric".into(), - series_labels: BTreeMap::new().into(), - labels: BTreeMap::new(), - timestamp: 1, - value: 1.0, - }], - ); + let mut exemplars = exemplar_requests(None); + if denied { + exemplars.extend(exemplar_requests(Some("other".into()))); } let ctx = QueryContext::arc(); - let samples = vec![( - ctx.clone(), - RowInsertRequests { - inserts: vec![RowInsertRequest { - table_name: "metric".into(), - rows: Some(Rows { - schema: vec![], - rows: vec![Row { values: vec![] }; 2], - }), - }], - }, - )]; + let samples = vec![(ctx.clone(), metric_request(&["metric"], 2))]; let outcome = write(handler.clone(), None, true, samples, vec![], exemplars, ctx).await; assert!(outcome.error.is_some()); let events = handler.events.lock().unwrap(); @@ -793,17 +939,11 @@ mod tests { assert_eq!(outcome.written, [0, 0, 0]); assert!(!events.iter().any(|e| e == "metric" || e == "exemplar")); } else { - assert_eq!(outcome.written, [1, 0, 1]); - assert_eq!(outcome.cost, 3); + assert_eq!(outcome.written, [1, 0, 0]); + assert_eq!(outcome.cost, 2); assert_eq!( *events, - [ - "pre:public", - "pre:public", - "source:public", - "metric", - "exemplar" - ] + ["pre:public", "pre:public", "source:public", "metric"] ); } } diff --git a/src/servers/src/http/prometheus.rs b/src/servers/src/http/prometheus.rs index 6ab9b053f5f..d49f5a2e672 100644 --- a/src/servers/src/http/prometheus.rs +++ b/src/servers/src/http/prometheus.rs @@ -30,6 +30,7 @@ use auth::{PermissionTableTarget, PermissionTableTargets, UserProviderRef}; use axum::extract::{Path, Query, State}; use axum::{Extension, Form}; use catalog::CatalogManagerRef; +use common_catalog::consts; use common_decimal::Decimal128; use common_error::ext::ErrorExt; use common_error::status_code::StatusCode; @@ -965,7 +966,7 @@ async fn get_all_column_names( let mut table_names = Vec::new(); let mut tables = manager.tables(catalog, schema, None); while let Some(table) = tables.try_next().await? { - if is_internal_physical_metric_table(&table) { + if is_internal_metric_table(&table) { continue; } table_names.push(table.table_info().name.clone()); @@ -990,7 +991,7 @@ async fn get_target_column_names( Some(query_ctx), ) .await? - && !is_internal_physical_metric_table(&table) + && !is_internal_metric_table(&table) { extend_tag_column_names(&mut labels, &table); } @@ -1458,8 +1459,9 @@ fn current_schema_metric_targets( ) } -fn is_internal_physical_metric_table(table: &TableRef) -> bool { - table.table_info().is_physical_table() +fn is_internal_metric_table(table: &TableRef) -> bool { + let info = table.table_info(); + info.is_physical_table() || info.name == consts::METRICS_EXEMPLARS_TABLE } fn promql_expr_to_metric_name(expr: &PromqlExpr) -> Option { @@ -2225,7 +2227,7 @@ async fn retrieve_table_names( .options .extra_options .contains_key(LOGICAL_TABLE_METADATA_KEY) - || is_internal_physical_metric_table(&table) + || is_internal_metric_table(&table) { // skip non-prometheus (non-metricengine) tables for __name__ query continue; @@ -2416,7 +2418,7 @@ async fn readable_metadata_tables( } } candidates.retain(|table| { - !is_internal_physical_metric_table(table) + !is_internal_metric_table(table) && (selectors.is_empty() || selectors .iter() @@ -4041,6 +4043,126 @@ mod tests { assert_eq!(fields, HashSet::from(["value".to_string()])); } + #[tokio::test] + async fn test_exemplar_table_is_hidden_from_metadata() { + use common_catalog::consts::METRICS_EXEMPLARS_TABLE; + use common_query::prelude::{EXEMPLAR_METRIC_COLUMN, greptime_exemplar_labels}; + use datatypes::types::json_type::JsonNativeType; + + let manager = MemoryCatalogManager::with_default_setup(); + for (id, name, tag, field, data_type) in [ + ( + 1024, + "cpu_usage", + "host", + "value", + ConcreteDataType::float64_datatype(), + ), + ( + 1025, + METRICS_EXEMPLARS_TABLE, + EXEMPLAR_METRIC_COLUMN, + greptime_exemplar_labels(), + ConcreteDataType::json2(JsonNativeType::Null), + ), + ] { + let mut info = test_table_info( + id, + name, + DEFAULT_SCHEMA_NAME, + DEFAULT_CATALOG_NAME, + Arc::new(Schema::new(vec![ + ColumnSchema::new(tag, ConcreteDataType::string_datatype(), true), + ColumnSchema::new(field, data_type, true), + ])), + ); + info.meta.primary_key_indices = vec![0]; + manager + .register_table_sync(RegisterTableRequest { + catalog: DEFAULT_CATALOG_NAME.to_string(), + schema: DEFAULT_SCHEMA_NAME.to_string(), + table_name: name.to_string(), + table_id: id, + table: EmptyTable::from_table_info(&info), + }) + .unwrap(); + } + let manager: CatalogManagerRef = manager; + let handler: PrometheusHandlerRef = Arc::new(TestPrometheusHandler { + catalog_manager: manager.clone(), + deny_operation: false, + denied_table: Some(METRICS_EXEMPLARS_TABLE), + metric_names: Vec::new(), + label_metric_names: Vec::new(), + label_lookups: Mutex::new(Vec::new()), + queries: Mutex::new(Vec::new()), + ordered_outputs: Mutex::new(Vec::new()), + }); + let ctx = QueryContext::with(DEFAULT_CATALOG_NAME, DEFAULT_SCHEMA_NAME); + let response = labels_query( + None, + State(handler.clone()), + Query(LabelsQuery::default()), + Extension(ctx.fork()), + Form(LabelsQuery::default()), + ) + .await; + assert_eq!(None, response.status_code, "{:?}", response.error); + assert_eq!( + response.data, + PrometheusResponse::Labels(vec![METRIC_NAME_LABEL.into(), "host".into()]) + ); + + let targets = ["cpu_usage", METRICS_EXEMPLARS_TABLE].map(|name| { + PermissionTableTarget::new(DEFAULT_CATALOG_NAME, DEFAULT_SCHEMA_NAME, name) + }); + assert_eq!( + get_target_column_names(&targets, &manager, &ctx) + .await + .unwrap(), + HashSet::from(["host".to_string()]) + ); + + let exemplar_selector = format!(r#"{{__name__=~"{METRICS_EXEMPLARS_TABLE}"}}"#); + let mixed_selector = format!(r#"{{__name__=~"cpu_usage|{METRICS_EXEMPLARS_TABLE}"}}"#); + for (label, selectors, expected) in [ + (FIELD_NAME_LABEL, vec![], vec!["value"]), + (FIELD_NAME_LABEL, vec!["cpu_usage"], vec!["value"]), + ( + FIELD_NAME_LABEL, + vec![mixed_selector.as_str()], + vec!["value"], + ), + (FIELD_NAME_LABEL, vec![METRICS_EXEMPLARS_TABLE], vec![]), + (FIELD_NAME_LABEL, vec![exemplar_selector.as_str()], vec![]), + ("__schema__", vec![METRICS_EXEMPLARS_TABLE], vec![]), + ("__schema__", vec![exemplar_selector.as_str()], vec![]), + ( + "__schema__", + vec![mixed_selector.as_str()], + vec![DEFAULT_SCHEMA_NAME], + ), + ] { + let response = label_values_query( + None, + State(handler.clone()), + Path(label.to_string()), + Extension(ctx.fork()), + Query(LabelValueQuery { + matches: Matches(selectors.iter().map(|value| value.to_string()).collect()), + ..Default::default() + }), + ) + .await; + assert_eq!(None, response.status_code, "{:?}", response.error); + assert_eq!( + response.data, + PrometheusResponse::LabelValues(expected.into_iter().map(String::from).collect()), + "label={label}, selectors={selectors:?}", + ); + } + } + #[tokio::test] async fn test_get_target_column_names_uses_selected_schema() { let manager = MemoryCatalogManager::with_default_setup(); diff --git a/src/servers/src/postgres/copy_in/arrow.rs b/src/servers/src/postgres/copy_in/arrow.rs new file mode 100644 index 00000000000..184cb3a6c0c --- /dev/null +++ b/src/servers/src/postgres/copy_in/arrow.rs @@ -0,0 +1,816 @@ +// Copyright 2023 Greptime Team +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! Standard Arrow IPC streams over COPY, using Flight's bulk ingestion core. +//! +//! Only the IPC encapsulation changes: schema and record-batch metadata/bodies +//! are forwarded intact to the Flight decoder, preserving its single-region +//! fast path, compression, schema evolution and write semantics. COPY returns +//! one final row count, not Flight's per-batch request IDs or timings. + +use std::io::BufRead; +use std::sync::Arc; + +use arrow_flight::{FlightData, FlightDescriptor}; +use arrow_ipc::MessageHeader; +use bytes::{Buf, Bytes}; +use common_grpc::flight::do_put::DoPutResponse; +use common_memory_manager::MemoryGuard; +use futures::StreamExt; +use futures::channel::mpsc; +use futures::stream::BoxStream; +use pgwire::error::PgWireResult; +use session::context::QueryContextRef; +use snafu::IntoError; +use table::requests::AUTO_CREATE_TABLE_KEY; + +use crate::grpc::flight::PutRecordBatchRequestStream; +use crate::postgres::copy_in::codec::CopyFormat; +use crate::postgres::copy_in::options::CopyOptionSet; +use crate::postgres::copy_in::{bad_copy_data, unsupported}; +use crate::postgres::utils::convert_err; +use crate::query_handler::CopyInHandlerRef; +use crate::request_memory_limiter::ServerMemoryLimiter; +use crate::request_memory_metrics::RequestMemoryMetrics; + +/// Flight's ingestion hints, scoped to one COPY rather than the connection. +#[derive(Debug, Clone, Default)] +pub(crate) struct ArrowOptions { + auto_create_table: Option, + insert_skip_wal: Option, +} + +pub(crate) fn build_arrow_codec(mut options: CopyOptionSet) -> PgWireResult { + let result = ArrowOptions { + auto_create_table: options.take_flag("auto_create_table")?, + insert_skip_wal: options.take_flag("insert_skip_wal")?, + }; + options.reject_leftovers("arrow")?; + Ok(CopyFormat::Arrow(result)) +} + +impl ArrowOptions { + pub(crate) fn query_context(&self, ctx: &QueryContextRef) -> QueryContextRef { + let mut ctx = ctx.fork(); + if let Some(value) = self.auto_create_table { + ctx.set_extension(AUTO_CREATE_TABLE_KEY, value.to_string()); + } + if let Some(value) = self.insert_skip_wal { + ctx.set_skip_wal(value); + } + Arc::new(ctx) + } +} + +/// One IPC stream and one lazy Flight ingestion stream. No background task is +/// needed: each completed batch drives the handler to its acknowledgement before +/// accepting the next batch. Dropping COPY drops the decoder and pending writes. +pub(crate) struct ArrowCopyState { + table: String, + buffer: Vec, + seen_schema: bool, + ended: bool, + input: mpsc::UnboundedSender>, + output: BoxStream<'static, crate::error::Result>, + limiter: ServerMemoryLimiter, + guards: Vec>, + charged: u64, + // Schema/dictionaries live in FlightDecoder across batches. Retain their + // reservations until COPY ends, including replaced dictionaries (conservative). + retained_guards: Vec>, + retained_bytes: u64, +} + +impl ArrowCopyState { + pub(crate) async fn new( + table: String, + handler: &CopyInHandlerRef, + ctx: QueryContextRef, + limiter: ServerMemoryLimiter, + ) -> PgWireResult { + let (input, receiver) = mpsc::unbounded(); + // COPY reserves raw frames and decompression memory before forwarding; + // avoid charging the same body again in the Flight transport adapter. + let stream = PutRecordBatchRequestStream::new( + receiver, + ctx.current_catalog().to_string(), + ctx.current_schema(), + None, + ) + .await + .map_err(|e| bad_copy_data(e.to_string()))?; + let output = handler.copy_in_arrow(stream, ctx).map_err(convert_err)?; + Ok(Self { + table, + buffer: Vec::new(), + seen_schema: false, + ended: false, + input, + output, + limiter, + guards: Vec::new(), + charged: 0, + retained_guards: Vec::new(), + retained_bytes: 0, + }) + } + + /// Reserves before buffering or decompressing, with Flight's fail-fast + /// admission policy. Waiting while retaining partial frames can deadlock + /// multiple connections growing their requests against the same budget. + fn reserve(&mut self, bytes: u64) -> PgWireResult<()> { + let additional = bytes.saturating_sub(self.charged); + if additional == 0 { + return Ok(()); + } + let granted = additional + .checked_add(1023) + .map(|bytes| bytes / 1024 * 1024) + .ok_or_else(|| bad_copy_data("Arrow memory reservation overflow"))?; + let held = self + .charged + .checked_add(self.retained_bytes) + .ok_or_else(|| bad_copy_data("Arrow memory reservation overflow"))?; + self.limiter + .check_request_fits(granted, held) + .map_err(convert_err)?; + let guard = self.limiter.try_acquire(additional).ok_or_else(|| { + convert_err(crate::error::MemoryLimitExceededSnafu.into_error( + common_memory_manager::Error::MemoryLimitExceeded { + requested_bytes: additional, + limit_bytes: self.limiter.limit_bytes(), + }, + )) + })?; + self.guards.push(guard); + self.charged += granted; + Ok(()) + } + + /// Consumes arbitrary CopyData boundaries, retaining at most one incomplete + /// frame plus the stream schema/dictionaries. The import itself has no total + /// byte limit; every completed record batch is written immediately. + pub(crate) async fn feed(&mut self, mut data: &[u8]) -> PgWireResult { + let mut rows = 0; + while !data.is_empty() { + if self.ended { + return Err(bad_copy_data("data after Arrow IPC end-of-stream marker")); + } + let target = frame_target(&self.buffer)?; + // Allow for the encoded frame and decoder-owned copies/alignment. + self.reserve((target as u64).saturating_mul(2))?; + let take = (target - self.buffer.len()).min(data.len()); + self.buffer.extend_from_slice(&data[..take]); + data = &data[take..]; + if self.buffer.len() < target { + continue; + } + let Some((prefix, metadata_len)) = frame_prefix(&self.buffer)? else { + continue; + }; + if metadata_len == 0 { + if !self.seen_schema { + return Err(bad_copy_data("Arrow IPC stream requires a schema")); + } + self.ended = true; + self.buffer.clear(); + self.guards.clear(); + self.charged = 0; + continue; + } + if self.buffer.len() < prefix + metadata_len { + continue; + } + let message = arrow_ipc::root_as_message(&self.buffer[prefix..prefix + metadata_len]) + .map_err(|e| bad_copy_data(format!("invalid Arrow IPC metadata: {e}")))?; + let body_len = usize::try_from(message.bodyLength()) + .map_err(|_| bad_copy_data("invalid Arrow IPC body length"))?; + let total = (prefix + metadata_len) + .checked_add(body_len) + .ok_or_else(|| bad_copy_data("Arrow IPC frame length overflow"))?; + if self.buffer.len() < total { + continue; + } + let kind = message.header_type(); + if !self.seen_schema && kind != MessageHeader::Schema { + return Err(bad_copy_data("first Arrow IPC message must be a schema")); + } + match kind { + MessageHeader::Schema if !self.seen_schema => {} + MessageHeader::DictionaryBatch | MessageHeader::RecordBatch => {} + _ => return Err(unsupported("expected one Arrow schema followed by batches")), + } + let expanded = decompressed_size(&message, &self.buffer[prefix + metadata_len..])?; + self.reserve((total as u64).saturating_mul(2).saturating_add(expanded))?; + let bytes = Bytes::from(std::mem::take(&mut self.buffer)); + let flight_data = FlightData { + flight_descriptor: (kind == MessageHeader::Schema) + .then(|| FlightDescriptor::new_path(vec![self.table.clone()])), + data_header: bytes.slice(prefix..prefix + metadata_len), + data_body: bytes.slice(prefix + metadata_len..), + ..Default::default() + }; + // Arrow 59.2's LZ4 decoder grows a Vec with read_to_end and checks + // the declared length only afterward. Bound the actual output first, + // after reserving both expansion and the decoder's block workspace. + validate_lz4_output(&flight_data)?; + self.input + .unbounded_send(Ok(flight_data)) + .map_err(|_| bad_copy_data("Arrow ingestion stream closed"))?; + if kind == MessageHeader::RecordBatch { + let response = self + .output + .next() + .await + .ok_or_else(|| { + bad_copy_data("Arrow ingestion stream ended before acknowledgement") + })? + .map_err(convert_err)?; + rows += response.affected_rows() as u64; + self.guards.clear(); + self.charged = 0; + } else { + self.seen_schema = true; + self.retained_guards.append(&mut self.guards); + self.retained_bytes += std::mem::take(&mut self.charged); + } + } + Ok(rows) + } + + pub(crate) async fn finish(&mut self) -> PgWireResult { + if !self.seen_schema || !self.buffer.is_empty() { + return Err(bad_copy_data("incomplete Arrow IPC stream")); + } + // IPC permits clean EOF without the optional end-of-stream marker. + self.input.close_channel(); + let mut rows = 0; + while let Some(response) = self.output.next().await { + rows += response.map_err(convert_err)?.affected_rows() as u64; + } + Ok(rows) + } +} + +/// Reads both modern continuation-prefixed and legacy IPC message lengths. +fn frame_prefix(buffer: &[u8]) -> PgWireResult> { + if buffer.len() < 4 { + return Ok(None); + } + let mut input = buffer; + let first = input.get_i32_le(); + let (prefix, length) = if first == -1 { + if input.len() < 4 { + return Ok(None); + } + (8, input.get_i32_le()) + } else { + (4, first) + }; + let length = + usize::try_from(length).map_err(|_| bad_copy_data("invalid Arrow IPC metadata length"))?; + Ok(Some((prefix, length))) +} + +/// The next framing boundary, so a large CopyData never queues many batches. +fn frame_target(buffer: &[u8]) -> PgWireResult { + if buffer.len() < 4 { + return Ok(4); + } + let Some((prefix, length)) = frame_prefix(buffer)? else { + return Ok(8); + }; + let metadata_end = prefix + length; + if buffer.len() < metadata_end || length == 0 { + return Ok(metadata_end); + } + let message = arrow_ipc::root_as_message(&buffer[prefix..metadata_end]) + .map_err(|e| bad_copy_data(format!("invalid Arrow IPC metadata: {e}")))?; + let body = usize::try_from(message.bodyLength()) + .map_err(|_| bad_copy_data("invalid Arrow IPC body length"))?; + metadata_end + .checked_add(body) + .ok_or_else(|| bad_copy_data("Arrow IPC frame length overflow")) +} + +/// Compressed IPC buffers carry their uncompressed length in an i64 prefix. +/// Includes the peak LZ4 workspace, which depends on its frame header, not the +/// IPC length prefix. Buffers are decoded sequentially, so workspaces do not sum. +fn decompressed_size(message: &arrow_ipc::Message<'_>, body: &[u8]) -> PgWireResult { + let mut total = 0u64; + let mut workspace = 0; + visit_compressed_buffers(message, body, |codec, length, compressed| { + total = total + .checked_add(length.max(0) as u64) + .ok_or_else(|| bad_copy_data("Arrow decompression size overflow"))?; + if codec == arrow_ipc::CompressionType::LZ4_FRAME && length > 0 { + workspace = workspace.max(lz4_workspace_size(compressed)?); + } + Ok(()) + })?; + total + .checked_add(workspace) + .ok_or_else(|| bad_copy_data("Arrow decompression size overflow")) +} + +/// Visits compressed record/dictionary buffers, excluding their IPC length +/// prefix. A length of -1 denotes an uncompressed buffer; zero is empty. +fn visit_compressed_buffers( + message: &arrow_ipc::Message<'_>, + body: &[u8], + mut visit: impl FnMut(arrow_ipc::CompressionType, i64, &[u8]) -> PgWireResult<()>, +) -> PgWireResult<()> { + let batch = match message.header_type() { + MessageHeader::RecordBatch => message.header_as_record_batch(), + MessageHeader::DictionaryBatch => { + message.header_as_dictionary_batch().and_then(|b| b.data()) + } + _ => None, + }; + let Some(batch) = batch else { + return Ok(()); + }; + let Some(compression) = batch.compression() else { + return Ok(()); + }; + if let Some(buffers) = batch.buffers() { + for buffer in buffers { + if buffer.length() == 0 { + continue; + } + if buffer.length() < 8 { + return Err(bad_copy_data("truncated compressed Arrow buffer")); + } + let start = usize::try_from(buffer.offset()) + .map_err(|_| bad_copy_data("invalid Arrow buffer offset"))?; + let length = usize::try_from(buffer.length()) + .map_err(|_| bad_copy_data("invalid Arrow buffer length"))?; + let buffer_end = start + .checked_add(length) + .filter(|end| *end <= body.len()) + .ok_or_else(|| bad_copy_data("truncated compressed Arrow buffer"))?; + let end = start + .checked_add(8) + .ok_or_else(|| bad_copy_data("invalid Arrow buffer offset"))?; + let mut prefix = body + .get(start..end) + .ok_or_else(|| bad_copy_data("truncated compressed Arrow buffer"))?; + let length = prefix.get_i64_le(); + if length < -1 { + return Err(bad_copy_data("invalid compressed Arrow buffer length")); + } + visit(compression.codec(), length, &body[end..buffer_end])?; + } + } + Ok(()) +} + +/// lz4_flex 0.14 allocates a source block plus a destination block; linked mode +/// uses two destination blocks and a 64 KiB history window. Admission must cover +/// these allocations even when the IPC prefix claims just one byte of output. +/// See the LZ4 frame specification's magic, FLG and BD fields and +/// lz4_flex::frame::FrameDecoder::read_frame_info. Keep this calculation in sync +/// with the pinned decoder version used by Arrow. +fn lz4_workspace_size(input: &[u8]) -> PgWireResult { + if input.starts_with(&[0x02, 0x21, 0x4c, 0x18]) { + // Legacy frames use independent 8 MiB blocks. + return Ok(2 * 8 * 1024 * 1024); + } + if !input.starts_with(&[0x04, 0x22, 0x4d, 0x18]) || input.len() < 7 { + return Err(bad_copy_data("invalid LZ4 frame header")); + } + let block = match (input[5] >> 4) & 7 { + 4 => 64 * 1024, + 5 => 256 * 1024, + 6 => 1024 * 1024, + 7 => 4 * 1024 * 1024, + _ => return Err(bad_copy_data("invalid LZ4 block size")), + }; + Ok(if input[4] & 0x20 != 0 { + 2 * block + } else { + 3 * block + 64 * 1024 + }) +} + +/// Rejects dishonest LZ4 output lengths before Arrow's unbounded read_to_end. +/// The same decoder Arrow uses is drained block-by-block without collecting +/// output. Each block fits the workspace already admitted above; as soon as a +/// block exceeds the remaining declared length, decoding stops. Thus even a +/// tiny declared length cannot trigger an unreserved whole-output allocation. +/// FIXME(#10470): Remove this extra LZ4 pass when Arrow bounds output itself. +fn validate_lz4_output(data: &FlightData) -> PgWireResult<()> { + let message = arrow_ipc::root_as_message(&data.data_header) + .map_err(|e| bad_copy_data(format!("invalid Arrow IPC metadata: {e}")))?; + visit_compressed_buffers(&message, &data.data_body, |codec, length, compressed| { + if codec != arrow_ipc::CompressionType::LZ4_FRAME || length <= 0 { + return Ok(()); + } + let mut decoder = lz4_flex::frame::FrameDecoder::new(compressed); + let mut remaining = length as u64; + loop { + let block = decoder + .fill_buf() + .map_err(|e| bad_copy_data(format!("invalid LZ4 buffer: {e}")))?; + if block.is_empty() { + if remaining != 0 { + return Err(bad_copy_data( + "LZ4 output is shorter than its declared length", + )); + } + return Ok(()); + } + let len = block.len(); + remaining = remaining + .checked_sub(len as u64) + .ok_or_else(|| bad_copy_data("LZ4 output exceeds its declared length"))?; + decoder.consume(len); + } + }) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::query_handler::CopyInHandler; + use arrow::array::{Int64Array, StringArray}; + use arrow::record_batch::RecordBatch; + use arrow_ipc::writer::{IpcWriteOptions, StreamWriter}; + use async_trait::async_trait; + use common_query::Output; + + struct Handler; + + #[async_trait] + impl CopyInHandler for Handler { + async fn copy_in_table( + &self, + _: &str, + _: &str, + _: &str, + _: QueryContextRef, + ) -> crate::error::Result> { + Ok(None) + } + + async fn copy_in_insert( + &self, + _: api::v1::RowInsertRequests, + _: QueryContextRef, + ) -> crate::error::Result { + panic!("Arrow must not use row ingestion") + } + + fn copy_in_arrow( + &self, + stream: PutRecordBatchRequestStream, + _: QueryContextRef, + ) -> crate::error::Result>> { + Ok(stream + .map(|request| { + let request = request.map_err(|e| { + crate::error::InvalidParameterSnafu { + reason: e.to_string(), + } + .build() + })?; + assert_eq!(request.table_name.table_name, "test"); + assert_eq!(request.record_batch, batch()); + Ok(DoPutResponse::new(0, request.record_batch.num_rows(), 0.0)) + }) + .boxed()) + } + } + + fn batch() -> RecordBatch { + RecordBatch::try_from_iter(vec![ + ( + "ts", + Arc::new(Int64Array::from(vec![1, 2])) as arrow::array::ArrayRef, + ), + ( + "value", + Arc::new(StringArray::from(vec!["a", "b"])) as arrow::array::ArrayRef, + ), + ]) + .unwrap() + } + + fn ipc(compression: Option, batches: usize) -> Vec { + let batch = batch(); + let options = IpcWriteOptions::default() + .try_with_compression(compression) + .unwrap(); + let mut writer = + StreamWriter::try_new_with_options(Vec::new(), &batch.schema(), options).unwrap(); + for _ in 0..batches { + writer.write(&batch).unwrap(); + } + writer.finish().unwrap(); + writer.into_inner().unwrap() + } + + async fn state(limit: u64) -> ArrowCopyState { + ArrowCopyState::new( + "test".into(), + &(Arc::new(Handler) as CopyInHandlerRef), + session::context::QueryContext::arc(), + ServerMemoryLimiter::new(limit, Default::default()), + ) + .await + .unwrap() + } + + #[tokio::test] + async fn chunked_ipc_and_compression() { + for compression in [ + None, + Some(arrow_ipc::CompressionType::LZ4_FRAME), + Some(arrow_ipc::CompressionType::ZSTD), + ] { + let bytes = ipc(compression, 3); + for chunk in [1, 2, 7, 64, bytes.len()] { + let mut state = state(16 * 1024 * 1024).await; + let mut rows = 0; + for data in bytes.chunks(chunk) { + rows += state.feed(data).await.unwrap(); + } + rows += state.finish().await.unwrap(); + assert_eq!(rows, 6, "chunk={chunk}, compression={compression:?}"); + assert_eq!(state.charged, 0); + } + } + } + + #[tokio::test] + async fn legacy_ipc_framing() { + let batch = batch(); + let options = IpcWriteOptions::try_new(8, true, arrow_ipc::MetadataVersion::V4).unwrap(); + let mut writer = + StreamWriter::try_new_with_options(Vec::new(), &batch.schema(), options).unwrap(); + writer.write(&batch).unwrap(); + writer.finish().unwrap(); + let bytes = writer.into_inner().unwrap(); + let mut copy = state(1024 * 1024).await; + let mut rows = 0; + for chunk in bytes.chunks(3) { + rows += copy.feed(chunk).await.unwrap(); + } + rows += copy.finish().await.unwrap(); + assert_eq!(rows, 2); + } + + #[tokio::test] + async fn empty_truncated_and_trailing_data() { + let mut empty = state(1024 * 1024).await; + assert!(empty.finish().await.is_err()); + let bytes = ipc(None, 0); + let mut schema_only = state(1024 * 1024).await; + assert_eq!(schema_only.feed(&bytes).await.unwrap(), 0); + assert_eq!(schema_only.finish().await.unwrap(), 0); + assert!(schema_only.feed(b"extra").await.is_err()); + let bytes = ipc(None, 1); + let mut truncated = state(1024 * 1024).await; + truncated.feed(&bytes[..bytes.len() - 10]).await.unwrap(); + assert!(truncated.finish().await.is_err()); + let mut eof = state(1024 * 1024).await; + assert_eq!(eof.feed(&bytes[..bytes.len() - 8]).await.unwrap(), 2); + assert_eq!(eof.finish().await.unwrap(), 0); + } + + #[tokio::test] + async fn malformed_lengths_and_memory_quota() { + // Even an unlimited limiter must reject arithmetic overflow. + let mut unlimited = state(0).await; + assert!(unlimited.reserve(u64::MAX).is_err()); + let mut copy = state(1024).await; + let error = copy.feed(&ipc(None, 1)).await.unwrap_err(); + assert!(!error.to_string().is_empty()); + let mut copy = state(1024).await; + assert!( + copy.feed(&[255, 255, 255, 255, 254, 255, 255, 255]) + .await + .is_err() + ); + let mut copy = state(1024).await; + assert!( + copy.feed(&[255, 255, 255, 255, 255, 255, 255, 127]) + .await + .is_ok() + ); + // Declared metadata length is admitted before reading/allocating it. + assert!(copy.feed(&[0]).await.is_err()); + } + + #[tokio::test] + async fn streaming_releases_batch_memory() { + let mut copy = state(16 * 1024).await; + let limiter = copy.limiter.clone(); + let bytes = ipc(None, 100); + assert!(bytes.len() > limiter.limit_bytes() as usize); + let mut rows = 0; + for chunk in bytes.chunks(37) { + rows += copy.feed(chunk).await.unwrap(); + } + rows += copy.finish().await.unwrap(); + assert_eq!(rows, 200); + drop(copy); + assert_eq!(limiter.used_bytes(), 0); + + let mut incomplete = state(16 * 1024).await; + let limiter = incomplete.limiter.clone(); + incomplete.feed(&bytes[..100]).await.unwrap(); + assert!(limiter.used_bytes() > 0); + drop(incomplete); + assert_eq!(limiter.used_bytes(), 0); + } + + #[tokio::test] + async fn decompression_is_admitted_before_decode() { + let batch = RecordBatch::try_from_iter(vec![( + "value", + Arc::new(StringArray::from(vec!["x".repeat(1024 * 1024)])) as arrow::array::ArrayRef, + )]) + .unwrap(); + let options = IpcWriteOptions::default() + .try_with_compression(Some(arrow_ipc::CompressionType::ZSTD)) + .unwrap(); + let mut writer = + StreamWriter::try_new_with_options(Vec::new(), &batch.schema(), options).unwrap(); + writer.write(&batch).unwrap(); + writer.finish().unwrap(); + let bytes = writer.into_inner().unwrap(); + assert!(bytes.len() < 64 * 1024); + let mut copy = state(64 * 1024).await; + let limiter = copy.limiter.clone(); + assert!(copy.feed(&bytes).await.is_err()); + drop(copy); + assert_eq!(limiter.used_bytes(), 0); + } + + /// Corrupts the largest IPC buffer's declared length, leaving the actual + /// compressed frame untouched (the reviewer's 8 MiB -> 1 byte repro). + fn understate_lz4_length(bytes: &mut [u8]) { + let mut offset = 0; + while offset < bytes.len() { + let (prefix, length) = frame_prefix(&bytes[offset..]).unwrap().unwrap(); + assert_ne!(length, 0, "expected a compressed string buffer"); + let body_start = offset + prefix + length; + let message = arrow_ipc::root_as_message(&bytes[offset + prefix..body_start]).unwrap(); + let batch = match message.header_type() { + MessageHeader::RecordBatch => message.header_as_record_batch(), + MessageHeader::DictionaryBatch => { + message.header_as_dictionary_batch().unwrap().data() + } + _ => None, + }; + if let Some(buffers) = batch.and_then(|batch| batch.buffers()) { + for buffer in buffers { + if buffer.length() < 8 { + continue; + } + let start = body_start + buffer.offset() as usize; + let declared = (&bytes[start..start + 8]).get_i64_le(); + if declared >= 8 * 1024 * 1024 { + bytes[start..start + 8].copy_from_slice(&1i64.to_le_bytes()); + return; + } + } + } + offset = body_start + message.bodyLength() as usize; + } + panic!("expected a compressed string buffer"); + } + + #[tokio::test] + async fn dishonest_lz4_length_is_bounded_before_arrow_decode() { + use arrow::array::{ArrayRef, StringDictionaryBuilder}; + use arrow::datatypes::Int32Type; + + for dictionary in [false, true] { + let value = "x".repeat(8 * 1024 * 1024); + let array: ArrayRef = if dictionary { + let mut builder = StringDictionaryBuilder::::new(); + builder.append(&value).unwrap(); + Arc::new(builder.finish()) + } else { + Arc::new(StringArray::from(vec![value])) + }; + let batch = RecordBatch::try_from_iter(vec![("value", array)]).unwrap(); + let options = IpcWriteOptions::default() + .try_with_compression(Some(arrow_ipc::CompressionType::LZ4_FRAME)) + .unwrap(); + let mut writer = + StreamWriter::try_new_with_options(Vec::new(), &batch.schema(), options).unwrap(); + writer.write(&batch).unwrap(); + writer.finish().unwrap(); + let mut bytes = writer.into_inner().unwrap(); + assert!(bytes.len() < 64 * 1024); + understate_lz4_length(&mut bytes); + + // The workspace fits, but no full-output Vec is ever built: the + // bounded preflight stops at the first block that exceeds 1 byte. + let mut copy = state(12 * 1024 * 1024).await; + let limiter = copy.limiter.clone(); + let error = copy.feed(&bytes).await.unwrap_err(); + assert!( + error + .to_string() + .contains("LZ4 output exceeds its declared length"), + "{error}" + ); + assert!(limiter.used_bytes() <= limiter.limit_bytes()); + drop(copy); + assert_eq!(limiter.used_bytes(), 0); + + // A smaller quota rejects even the block decoder's workspace before + // constructing it, despite the tiny declared expansion. + let mut copy = state(128 * 1024).await; + let limiter = copy.limiter.clone(); + let error = copy.feed(&bytes).await.unwrap_err(); + assert!(!error.to_string().contains("LZ4 output exceeds"), "{error}"); + drop(copy); + assert_eq!(limiter.used_bytes(), 0); + } + } + + #[test] + fn lz4_workspace_covers_block_modes_and_sizes() { + use lz4_flex::frame::{BlockMode, BlockSize, FrameEncoder, FrameInfo}; + use std::io::Write; + + for (block_size, size) in [ + (BlockSize::Max64KB, 64 * 1024), + (BlockSize::Max256KB, 256 * 1024), + (BlockSize::Max1MB, 1024 * 1024), + (BlockSize::Max4MB, 4 * 1024 * 1024), + ] { + for mode in [BlockMode::Independent, BlockMode::Linked] { + let info = FrameInfo::new().block_size(block_size).block_mode(mode); + let mut encoder = FrameEncoder::with_frame_info(info, Vec::new()); + encoder.write_all(b"test").unwrap(); + let compressed = encoder.finish().unwrap(); + let expected = if mode == BlockMode::Independent { + 2 * size + } else { + 3 * size + 64 * 1024 + }; + assert_eq!(lz4_workspace_size(&compressed).unwrap(), expected); + } + } + assert_eq!( + lz4_workspace_size(&[0x02, 0x21, 0x4c, 0x18]).unwrap(), + 16 * 1024 * 1024 + ); + for invalid in [ + &b""[..], + &b"garbage"[..], + &[0x04, 0x22, 0x4d, 0x18, 0x60, 0, 0][..], + ] { + assert!(lz4_workspace_size(invalid).is_err()); + } + } + + #[test] + fn options_are_scoped_to_copy() { + use crate::postgres::copy_in::copy_from_stdin_from_sql; + let stmt = copy_from_stdin_from_sql( + "COPY t FROM STDIN WITH (FORMAT arrow, auto_create_table false, insert_skip_wal true)", + ) + .unwrap() + .unwrap(); + let CopyFormat::Arrow(options) = stmt.format else { + panic!("expected arrow") + }; + let original = session::context::QueryContext::arc(); + let ctx = options.query_context(&original); + assert_eq!(ctx.extension(AUTO_CREATE_TABLE_KEY), Some("false")); + assert!(ctx.skip_wal()); + assert!(!original.skip_wal()); + assert!(original.extension(AUTO_CREATE_TABLE_KEY).is_none()); + for option in [ + "header", + "pipeline_name 'p'", + "auto_create_table 'false'", + "insert_skip_wal 1", + ] { + assert!( + copy_from_stdin_from_sql(&format!( + "COPY t FROM STDIN WITH (FORMAT arrow, {option})" + )) + .is_err() + ); + } + } +} diff --git a/src/servers/src/postgres/copy_in/codec.rs b/src/servers/src/postgres/copy_in/codec.rs index 005c0e99f8d..9c05d9c2584 100644 --- a/src/servers/src/postgres/copy_in/codec.rs +++ b/src/servers/src/postgres/copy_in/codec.rs @@ -55,6 +55,7 @@ use datatypes::prelude::ConcreteDataType; use datatypes::schema::ColumnSchema; use pgwire::error::PgWireResult; +use crate::postgres::copy_in::arrow::ArrowOptions; use crate::postgres::copy_in::csv::CsvCodec; use crate::postgres::copy_in::influxdb::InfluxdbOptions; use crate::postgres::copy_in::jsonl::JsonlCodec; @@ -71,6 +72,9 @@ pub(super) enum CopyFormat { /// targeted table's columns through arrow-json, the engine behind /// file-based `COPY ... FROM 'file.json'`. Jsonl(JsonlCodec), + /// Table-bound Arrow IPC stream, completed batch-by-batch through Flight's + /// bulk ingestion handler. Advertises binary wire format code 1. + Arrow(ArrowOptions), /// Table-less influxdb line protocol: the whole payload is one /// bounded request body, completed through the line-protocol /// pipeline the HTTP write endpoints use (one COPY statement is one @@ -95,6 +99,7 @@ impl CopyFormat { match self { CopyFormat::Csv(_) => "csv", CopyFormat::Jsonl(_) => "jsonl", + CopyFormat::Arrow(_) => "arrow", CopyFormat::Influxdb(_) => "influxdb", CopyFormat::Otlp(_) => "otlp", CopyFormat::PromWrite(_) => "promwrite", @@ -104,8 +109,8 @@ impl CopyFormat { /// A table-bound COPY format: records decode against the targeted /// table's columns into insertable rows (csv, jsonl). Implemented by -/// the codec config structs; the copy lifecycle treats every -/// table-bound format identically through it. +/// the codec config structs; the copy lifecycle treats these row-based +/// formats identically through it. Arrow IPC uses a separate bulk-ingestion path. pub(crate) trait TableBoundCodec: Send + Sync { /// Validates that a column of `data_type` can be ingested. fn check_column_type(&self, data_type: &ConcreteDataType) -> PgWireResult<()>; diff --git a/src/servers/src/postgres/copy_in/mod.rs b/src/servers/src/postgres/copy_in/mod.rs index 37e6a3961ff..9df8cda00ca 100644 --- a/src/servers/src/postgres/copy_in/mod.rs +++ b/src/servers/src/postgres/copy_in/mod.rs @@ -31,6 +31,7 @@ //! arms. Builders resolve a `FORMAT` name (and its aliases) through //! [`REGISTERED_FORMATS`]. See the `codec` module docs. +mod arrow; mod codec; mod csv; mod influxdb; @@ -102,13 +103,13 @@ pub(crate) const COPY_IN_MAX_PAYLOAD_BYTES: usize = 64 * 1024 * 1024; type FormatBuilder = fn(options::CopyOptionSet) -> PgWireResult; /// The registered COPY FROM STDIN formats: accepted `FORMAT` name to -/// builder. `csv` is the only implemented format; the others are -/// registered so they report a clear "not supported yet" instead of an -/// unknown-format error. +/// builder. Unimplemented PostgreSQL text/binary formats are registered +/// to report a clear "not supported yet" instead of an unknown-format error. const REGISTERED_FORMATS: &[(&str, FormatBuilder)] = &[ ("csv", csv::build_csv_codec), ("jsonl", jsonl::build_jsonl_codec), ("json", jsonl::build_jsonl_codec), + ("arrow", arrow::build_arrow_codec), ("influxdb", influxdb::build_influxdb_codec), ("influxdb_line", influxdb::build_influxdb_codec), ("otlp", otlp::build_otlp_codec), @@ -253,7 +254,7 @@ pub(crate) struct CopyInState { query_ctx: QueryContextRef, payload: Payload, /// Reservations against the shared request-memory limiter for the - /// bytes buffered by a Prometheus payload, acquired per CopyData + /// bytes buffered by a table-less payload, acquired per CopyData /// chunk as it arrives and held until the buffer is flushed or the /// copy ends — the receive-stage counterpart of HTTP's /// body-accounting middleware, so concurrent unfinished COPY @@ -296,6 +297,8 @@ impl BufferedReservation { } enum Payload { + /// Table-bound Arrow IPC batches, written without protobuf row conversion. + Arrow(Box), /// Table-bound rows: parsed against `grpc_schema` and flushed to /// `table_name` via `copy_in_insert`. The schema is cloned into each /// flushed batch: `Rows.schema` is an owned `Vec` in the proto @@ -432,10 +435,14 @@ impl CopyInState { self.codec_format_code } - /// Prometheus bodies are charged against the shared request-memory limiter - /// as they arrive, before decode and conversion acquire additional memory. + /// Whether the payload buffers raw CopyData bytes until `CopyDone` + /// (the table-less formats); such bytes are charged against the + /// shared request-memory limiter as they arrive. fn buffers_payload(&self) -> bool { - matches!(self.payload, Payload::PromWrite { .. }) + matches!( + self.payload, + Payload::Influxdb { .. } | Payload::Otlp { .. } | Payload::PromWrite { .. } + ) } /// The payload bytes currently buffered (charged or not). @@ -444,7 +451,7 @@ impl CopyInState { Payload::Influxdb { data, .. } | Payload::Otlp { data, .. } | Payload::PromWrite { data, .. } => data.len() as u64, - Payload::Table { .. } => 0, + Payload::Table { .. } | Payload::Arrow(_) => 0, } } @@ -483,6 +490,8 @@ impl CopyInState { fn feed(&mut self, data: &[u8]) -> PgWireResult<()> { match &mut self.payload { Payload::Table { parser, rows, .. } => rows.extend(parser.feed(data)?), + // Arrow's asynchronous feed writes each complete batch immediately. + Payload::Arrow(_) => return Err(bad_copy_data("Arrow requires asynchronous feed")), Payload::Influxdb { data: buffered, .. } | Payload::Otlp { data: buffered, .. } | Payload::PromWrite { data: buffered, .. } => { @@ -503,6 +512,8 @@ impl CopyInState { fn finish(&mut self) -> PgWireResult<()> { match &mut self.payload { Payload::Table { parser, rows, .. } => rows.extend(parser.finish()?), + // Finalized asynchronously by on_copy_done. + Payload::Arrow(_) => {} // The whole payload is one request body; nothing to finalize. Payload::Influxdb { .. } | Payload::Otlp { .. } | Payload::PromWrite { .. } => {} } @@ -512,6 +523,7 @@ impl CopyInState { fn should_flush(&self) -> bool { match &self.payload { Payload::Table { rows, .. } => rows.len() >= COPY_IN_FLUSH_ROWS, + Payload::Arrow(_) => false, // Completed once at CopyDone, not mid-stream. Payload::Influxdb { .. } | Payload::Otlp { .. } | Payload::PromWrite { .. } => false, } @@ -544,14 +556,18 @@ impl CopyInState { } /// Takes the buffered OTLP payload and its options, if any. - fn take_otlp(&mut self) -> Option<(OtlpOptions, Vec)> { + fn take_otlp(&mut self) -> Option<(OtlpOptions, Vec, BufferedReservation)> { let Payload::Otlp { options, data } = &mut self.payload else { return None; }; if data.is_empty() { return None; } - Some((options.clone(), std::mem::take(data))) + Some(( + options.clone(), + std::mem::take(data), + self.take_reservation(), + )) } /// Takes the buffered remote-write body and its options, if any. @@ -572,19 +588,20 @@ impl CopyInState { /// Takes the buffered payload as one line-protocol request body, if /// any — the same bytes an HTTP write of the same records would /// carry. - fn take_lines(&mut self) -> PgWireResult> { + fn take_lines(&mut self) -> PgWireResult> { let Payload::Influxdb { data, precision } = &mut self.payload else { return Ok(None); }; if data.is_empty() { return Ok(None); } - let lines = String::from_utf8(std::mem::take(data)) - .map_err(|e| bad_copy_data(format!("COPY FROM STDIN data is not valid UTF-8: {e}")))?; - Ok(Some(InfluxdbRequest { + let request = InfluxdbRequest { precision: *precision, - lines, - })) + lines: String::from_utf8(std::mem::take(data)).map_err(|e| { + bad_copy_data(format!("COPY FROM STDIN data is not valid UTF-8: {e}")) + })?, + }; + Ok(Some((request, self.take_reservation()))) } } @@ -685,10 +702,53 @@ impl PostgresServerHandlerInner { // Each format states its own target rule and ingestion shape // explicitly. let state = match &stmt.format { - // Table-bound formats require a target table: records are - // parsed against its columns and inserted in batches. + // Row-based table-bound formats parse records against the + // target columns and insert them in batches. CopyFormat::Csv(codec) => self.table_bound_state(&stmt, codec).await?, CopyFormat::Jsonl(codec) => self.table_bound_state(&stmt, codec).await?, + CopyFormat::Arrow(options) => { + if stmt.table.is_empty() { + return Err(unsupported("format arrow requires a target table")); + } + if !stmt.columns.is_empty() { + return Err(unsupported( + "format arrow uses IPC field names; omit the COPY column list", + )); + } + let (catalog, schema, table) = resolve_table_name(&query_ctx, &stmt.table)?; + // Validate against the original context, including COPY's + // cross-catalog policy, before changing the target scope. + if self + .copy_in_handler + .copy_in_table(&catalog, &schema, &table, query_ctx.clone()) + .await + .map_err(convert_err)? + .is_none() + { + return Err(copy_in_error( + PgErrorCode::Ec42P01, + format!("relation \"{}\" does not exist", stmt.table.join(".")), + )); + } + let query_ctx = + options.query_context(&adjust_query_context(query_ctx, &catalog, &schema)); + let arrow = arrow::ArrowCopyState::new( + table, + &self.copy_in_handler, + query_ctx.clone(), + self.memory_limiter.clone(), + ) + .await?; + CopyInState { + query_ctx, + payload: Payload::Arrow(Box::new(arrow)), + memory_guards: Vec::new(), + granted_bytes: 0, + codec_name: "arrow", + codec_format_code: 1, + rows_written: 0, + } + } // influxdb forbids a target table — each line names its own // measurement — and completes through the line-protocol // pipeline the HTTP write endpoints use; the server must be @@ -743,6 +803,8 @@ impl PostgresServerHandlerInner { }; let num_columns = match &state.payload { Payload::Table { grpc_schema, .. } => grpc_schema.len(), + // The IPC schema arrives after the COPY handshake. + Payload::Arrow(_) => 0, // No fixed column set: the format routes per record. Payload::Influxdb { .. } | Payload::Otlp { .. } | Payload::PromWrite { .. } => 0, }; @@ -804,13 +866,23 @@ impl PostgresServerHandlerInner { // timestamp alignment and inserts are identical to an HTTP // write of the same bytes. The context stays this connection's // postgres context. - if let Some((options, bytes)) = state.take_otlp() { + if let Some((options, bytes, reservation)) = state.take_otlp() { let Some(otlp_handler) = &self.otlp_handler else { return Err(unsupported("this server is not wired for the otlp format")); }; - return self - .flush_otlp(otlp_handler, options, bytes, query_ctx) - .await; + // The reservation outlives the payload: it is dropped when + // the payload's bytes are consumed below. + let rows = self + .flush_otlp( + otlp_handler, + options, + bytes, + reservation.charged_bytes(), + query_ctx, + ) + .await?; + drop(reservation); + return Ok(rows); } if let Some((options, bytes, reservation)) = state.take_prom_write() { let Some(prom_write_state) = &self.prom_write_state else { @@ -822,7 +894,7 @@ impl PostgresServerHandlerInner { .flush_prom_write(prom_write_state, options, bytes, reservation, query_ctx) .await; } - if let Some(request) = state.take_lines()? { + if let Some((request, reservation)) = state.take_lines()? { let Some(influxdb_handler) = &self.influxdb_handler else { return Err(unsupported( "this server is not wired for the influxdb line protocol format", @@ -832,6 +904,7 @@ impl PostgresServerHandlerInner { .exec(request, query_ctx) .await .map_err(convert_err)?; + drop(reservation); return match output.data { OutputData::AffectedRows(rows) => Ok(rows as u64), OutputData::RecordBatches(_) | OutputData::Stream(_) => Ok(0), @@ -865,6 +938,7 @@ impl PostgresServerHandlerInner { otlp_handler: &crate::query_handler::OpenTelemetryProtocolHandlerRef, options: OtlpOptions, bytes: Vec, + body_reserved_bytes: u64, query_ctx: QueryContextRef, ) -> PgWireResult { use opentelemetry_proto::tonic::collector::logs::v1::ExportLogsServiceRequest; @@ -900,7 +974,7 @@ impl PostgresServerHandlerInner { .metrics( request, Arc::new(ctx), - Some((self.memory_limiter.clone(), 0)), + Some((self.memory_limiter.clone(), body_reserved_bytes)), ) .await .map_err(convert_err)?; @@ -1122,12 +1196,16 @@ impl CopyHandler for PostgresServerHandlerInner { // otherwise a pooled connection would retain failed-import // buffers until its next COPY. On success it is put back. // - // Buffered Prometheus payloads charge their bytes against the + // Buffered table-less payloads charge their bytes against the // shared request-memory limiter as they arrive (the // receive-stage counterpart of HTTP's body accounting); the // reservation is held until the buffer is flushed or the state // is dropped. - if state.buffers_payload() { + if let Payload::Arrow(arrow) = &mut state.payload { + let rows = arrow.feed(©_data.data).await?; + state.rows_written += rows; + METRIC_POSTGRES_COPY_IN_ROWS.inc_by(rows); + } else if state.buffers_payload() { let chunk_bytes = u64::try_from(copy_data.data.len()) .map_err(|_| bad_copy_data("chunk too large"))?; // Charge only this chunk's uncovered delta against the @@ -1185,8 +1263,12 @@ impl CopyHandler for PostgresServerHandlerInner { "CopyDone message received outside COPY FROM STDIN", )); }; - state.finish()?; - let rows = self.flush_copy_in(&mut state).await?; + let rows = if let Payload::Arrow(arrow) = &mut state.payload { + arrow.finish().await? + } else { + state.finish()?; + self.flush_copy_in(&mut state).await? + }; state.rows_written += rows; METRIC_POSTGRES_COPY_IN_ROWS.inc_by(rows); diff --git a/src/servers/src/prom_remote_write/README.md b/src/servers/src/prom_remote_write/README.md index 9e86a8753dd..48fcfbacbf3 100644 --- a/src/servers/src/prom_remote_write/README.md +++ b/src/servers/src/prom_remote_write/README.md @@ -15,32 +15,42 @@ flowchart TD C --> D["borrow symbols and time-series bytes"] D --> E["decode leaf messages and build rows"] - E --> F["samples ContextReq"] - E --> G["histograms ContextReq"] - - F --> H["write_prometheus_rows_with_progress"] - H --> I["metric engine / pending batcher when enabled"] - - G --> J["histogram ContextOpt"] - J --> K["write_prometheus_rows_with_progress"] - K --> L["same metric-engine flag as samples, no batcher"] - L --> M["table: "] - - M --> N["field: configured native-histogram Struct"] - N --> O["struct children: counts, spans, buckets, sum, schema"] - I --> P["written headers and counters"] - L --> P + E --> F{"Retained exemplars?"} + F -->|No| G["write_prometheus_v2_rows_with_progress"] + F -->|Yes| H["exemplar::write"] + G --> I["sample / native histogram writes"] + H --> I + H --> J["exemplar writes: greptime_metrics_exemplars"] + I --> K["written headers and counters"] + J --> K ``` -The conversion step splits one v2 request into two `ContextReq`s: - The `decode` codec metric covers decompression and the borrowed request envelope. The `convert` metric covers per-series scans, leaf prost decoding, validation, and row construction. +The conversion step produces sample and histogram `ContextReq`s plus validated +`ExemplarRequests`: + - samples keep the existing sample table name and can use the metric-engine physical table path and pending rows batcher; -- native histograms keep the existing metric table name. +- native histograms keep the existing metric table name; +- exemplars are grouped by database and written through `exemplar::write`, which + prepares their source metric tables and tracks progress for each kind of write. + +Accompanying source sample and histogram writes must succeed before exemplars +are written. A source write failure skips the request's exemplars while unrelated +metric writes proceed independently. Exemplar-only inputs remain supported for +existing logical metric tables. + +Exemplar persistence requires metric-engine ingestion and logical metric-engine +source tables. Exemplars are stored in the target database's +`greptime_metrics_exemplars` table using ordinary Mito storage with sparse primary +keys and append mode. Remote Write v1 uses the same exemplar write path. + +Exemplar-owned labels are stored in a JSON2 field named +`_exemplar_labels`. The default name is +`greptime_exemplar_labels`; an empty prefix produces `exemplar_labels`. Native histogram rows follow the same metric-engine switch as samples. They do not use the pending rows batcher yet because the batcher assumes the classic @@ -56,6 +66,7 @@ Each histogram row stores one Struct field named - list children for custom values, spans, and positive/negative buckets; - original Prometheus labels as Greptime tags. -The v2 response always reports written sample, histogram, and exemplar counts in -Prometheus remote-write headers. Exemplars are currently ignored and reported as -zero. +The v2 response reports sample, histogram, and exemplar counts in Prometheus +remote-write headers. Exemplar counts reflect confirmed storage writes, including +partial writes on error. Invalid exemplar observations are dropped during +conversion and excluded from the exemplar count. diff --git a/src/servers/src/prom_remote_write/v2.rs b/src/servers/src/prom_remote_write/v2.rs index 6f82247b727..7ef8c7848fd 100644 --- a/src/servers/src/prom_remote_write/v2.rs +++ b/src/servers/src/prom_remote_write/v2.rs @@ -1782,8 +1782,10 @@ mod tests { .await .unwrap(); assert!(limiter.used_bytes() >= label.len() as u64); - let progress = - session::write_progress::WriteProgress::with_reservation(decoded.memory_guard.clone()); + let progress = session::write_progress::WriteProgress::with_reservation( + decoded.memory_guard.granted_bytes(), + decoded.memory_guard.clone(), + ); drop(decoded); assert!(limiter.used_bytes() >= label.len() as u64); drop(progress); @@ -1816,8 +1818,10 @@ mod tests { .unwrap(); assert_eq!(decoded.exemplar_count, 1); assert!(limiter.used_bytes() >= label.len() as u64); - let progress = - session::write_progress::WriteProgress::with_reservation(decoded.memory_guard.clone()); + let progress = session::write_progress::WriteProgress::with_reservation( + decoded.memory_guard.granted_bytes(), + decoded.memory_guard.clone(), + ); drop(decoded); assert!(limiter.used_bytes() >= label.len() as u64); drop(progress); diff --git a/src/servers/src/query_handler.rs b/src/servers/src/query_handler.rs index 9ddc46d4db9..a12e8c3cdae 100644 --- a/src/servers/src/query_handler.rs +++ b/src/servers/src/query_handler.rs @@ -378,6 +378,22 @@ pub trait CopyInHandler: Send + Sync { query_ctx: QueryContextRef, ) -> Result>; + /// Ingests Arrow batches through the same bulk path as Flight DoPut. + /// The COPY transport owns framing and memory admission; implementations + /// retain stream-level authorization and schema reconciliation. + fn copy_in_arrow( + &self, + _stream: crate::grpc::flight::PutRecordBatchRequestStream, + _query_ctx: QueryContextRef, + ) -> Result< + futures::stream::BoxStream<'static, Result>, + > { + crate::error::NotSupportedSnafu { + feat: "Arrow COPY ingestion", + } + .fail() + } + /// Inserts a parsed batch produced by a COPY stream. Returns the /// number of affected rows. async fn copy_in_insert( diff --git a/src/session/src/context.rs b/src/session/src/context.rs index 93890e7d535..66c0e1cb7d4 100644 --- a/src/session/src/context.rs +++ b/src/session/src/context.rs @@ -16,7 +16,8 @@ use std::collections::HashMap; use std::fmt::{Display, Formatter}; use std::net::SocketAddr; use std::str::FromStr; -use std::sync::{Arc, RwLock}; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::{Arc, RwLock, Weak}; use std::time::Duration; use api::v1::ExplainOptions; @@ -99,6 +100,9 @@ pub struct QueryContext { /// Process-local storage acknowledgements; never accepted from a wire context. #[builder(setter(skip))] write_progress: Option>, + /// Reads transport-owned reservations without retaining them in queued writes. + #[builder(setter(skip))] + body_memory_bytes: Weak, /// Preserve storage acknowledgements for protocol-level partial-write accounting. #[builder(setter(skip))] confirmed_writes: bool, @@ -304,6 +308,23 @@ impl QueryContext { self.write_progress = Some(progress); } + /// Attaches the live, process-local count of transport-owned memory permits. + pub fn set_body_memory_bytes(&mut self, bytes: Weak) { + self.body_memory_bytes = bytes; + } + + /// Returns permits held through conversion, excluding independently flushing Arrow batches. + pub fn held_memory_bytes(&self) -> u64 { + self.body_memory_bytes + .upgrade() + .map_or(0, |bytes| bytes.load(Ordering::Acquire)) + .saturating_add( + self.write_progress + .as_ref() + .map_or(0, |progress| progress.reserved_bytes()), + ) + } + /// Forks this context to retain storage acknowledgements for partial write accounting. /// /// Insertion APIs returning `Output` may return `Ok` while carrying storage errors @@ -797,6 +818,7 @@ impl QueryContextBuilder { batching_enabled: self.batching_enabled.unwrap_or_default(), admitted_write: None, write_progress: None, + body_memory_bytes: Weak::new(), confirmed_writes: false, logical_batching_enabled: self.logical_batching_enabled.unwrap_or_default(), process_id: self.process_id.unwrap_or_default(), diff --git a/src/session/src/write_progress.rs b/src/session/src/write_progress.rs index e6f7fc511d4..df473cbe72e 100644 --- a/src/session/src/write_progress.rs +++ b/src/session/src/write_progress.rs @@ -25,7 +25,7 @@ pub struct WriteProgress { written: AtomicU64, accepted: AtomicBool, // A queued write must keep its decoder's memory reservation alive. - _reservation: Option>, + reservation: Option<(u64, Arc)>, on_write: Option>, pending: AtomicUsize, completed: Notify, @@ -70,13 +70,19 @@ impl WriteProgress { } } - pub fn with_reservation(reservation: Arc) -> Self { + /// Retains a fixed-size reservation and its granted bytes for later memory admission. + pub fn with_reservation(reserved_bytes: u64, reservation: Arc) -> Self { Self { - _reservation: Some(reservation), + reservation: Some((reserved_bytes, reservation)), ..Self::default() } } + /// Returns the quota retained by this request's decoder or exemplar rows. + pub fn reserved_bytes(&self) -> u64 { + self.reservation.as_ref().map_or(0, |(bytes, _)| *bytes) + } + pub fn add_written(&self, rows: usize) { self.written.fetch_add(rows as u64, Ordering::Relaxed); self.observe(rows as u64); @@ -125,16 +131,27 @@ mod tests { fn confirmations_do_not_double_count_and_contexts_keep_local_ownership() { let observed = Arc::new(AtomicUsize::new(0)); let counter = observed.clone(); - let progress = Arc::new(WriteProgress::default().with_observer(move |rows| { - counter.fetch_add(rows as usize, Ordering::Relaxed); - })); + let progress = Arc::new( + WriteProgress::with_reservation(2048, Arc::new(())).with_observer(move |rows| { + counter.fetch_add(rows as usize, Ordering::Relaxed); + }), + ); let mut context = crate::context::QueryContext::with("greptime", "public"); + let body_bytes = Arc::new(AtomicU64::new(0)); + context.set_body_memory_bytes(Arc::downgrade(&body_bytes)); context.set_write_progress(progress.clone()); let fork = context.with_write_admission(); assert!(Arc::ptr_eq(fork.write_progress().unwrap(), &progress)); + assert_eq!(fork.held_memory_bytes(), 2048); + body_bytes.store(1024, Ordering::Release); + assert_eq!(context.held_memory_bytes(), 3072); + assert_eq!(fork.held_memory_bytes(), 3072); let wire = api::v1::QueryContext::from(context); let received = crate::context::QueryContext::try_from(wire).unwrap(); assert!(received.write_progress().is_none()); + assert_eq!(received.held_memory_bytes(), 0); + drop(body_bytes); + assert_eq!(fork.held_memory_bytes(), 2048); progress.add_written(2); progress.confirm(3); progress.confirm(3); diff --git a/src/standalone/src/options.rs b/src/standalone/src/options.rs index fe7d91371d0..3c7a9e6ce13 100644 --- a/src/standalone/src/options.rs +++ b/src/standalone/src/options.rs @@ -21,6 +21,7 @@ use common_event_recorder::EventRecorderOptions; use common_memory_manager::OnExhaustedPolicy; use common_options::memory::MemoryOptions; use common_telemetry::logging::{LoggingOptions, SlowQueryOptions, TracingOptions}; +use common_time::timestamp::TimeUnit; use common_wal::config::DatanodeWalConfig; use datanode::config::{DatanodeOptions, ProcedureConfig, RegionEngineConfig, StorageConfig}; use file_engine::config::EngineConfig as FileEngineConfig; @@ -47,11 +48,20 @@ pub struct StandaloneOptions { /// Upper bound: when `false`, missing tables are never auto-created even if a /// request sets the `auto_create_table` hint to `true`. 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()", "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, @@ -107,6 +117,7 @@ impl Default for StandaloneOptions { 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(), @@ -177,6 +188,8 @@ impl StandaloneOptions { FrontendOptions { default_timezone: cloned_opts.default_timezone, auto_create_table: cloned_opts.auto_create_table, + auto_create_physical_table_timestamp_unit: cloned_opts + .auto_create_physical_table_timestamp_unit, max_in_flight_write_bytes: cloned_opts.max_in_flight_write_bytes, write_bytes_exhausted_policy: cloned_opts.write_bytes_exhausted_policy, http: cloned_opts.http, diff --git a/src/store-api/src/logstore.rs b/src/store-api/src/logstore.rs index 3716b914ef0..00f3f1a929f 100644 --- a/src/store-api/src/logstore.rs +++ b/src/store-api/src/logstore.rs @@ -30,6 +30,15 @@ pub use crate::logstore::entry::Id as EntryId; use crate::logstore::provider::Provider; use crate::storage::RegionId; +/// Allows a log store to initiate object-store I/O. +/// +/// A metasrv-controlled datanode supplies this from its node lease. The log +/// store deliberately does not know how the permission is renewed. +pub trait ObjectStoreWalIoPermit: Send + Sync + 'static { + /// Returns whether a new object-store create or delete may start now. + fn allows_object_store_io(&self) -> bool; +} + /// `LogStore` serves as a Write-Ahead-Log for storage engine. #[async_trait::async_trait] pub trait LogStore: Send + Sync + 'static + std::fmt::Debug { diff --git a/src/store-api/src/region_engine.rs b/src/store-api/src/region_engine.rs index a2e47640d42..16f1edd3dfa 100644 --- a/src/store-api/src/region_engine.rs +++ b/src/store-api/src/region_engine.rs @@ -179,6 +179,10 @@ impl SetRegionRoleStateResponse { pub struct GrantedRegion { pub region_id: RegionId, pub region_role: RegionRole, + /// An opaque non-zero id the metadata plane attaches to some leases, `None` for a lease + /// without one. It reaches the engine through [`RegionEngine::set_region_role_with_lease`]; + /// engines may keep it with the lease and must not interpret it. + pub candidate_lease_id: Option, pub extensions: HashMap>, } @@ -187,6 +191,7 @@ impl GrantedRegion { Self { region_id, region_role, + candidate_lease_id: None, extensions: HashMap::new(), } } @@ -197,6 +202,7 @@ impl From for PbGrantedRegion { PbGrantedRegion { region_id: value.region_id.as_u64(), role: PbRegionRole::from(value.region_role).into(), + candidate_lease_id: value.candidate_lease_id.unwrap_or_default(), extensions: value.extensions, } } @@ -207,6 +213,8 @@ impl From for GrantedRegion { GrantedRegion { region_id: RegionId::from_u64(value.region_id), region_role: value.role().into(), + // 0 means the lease carries no candidate lease id. + candidate_lease_id: (value.candidate_lease_id != 0).then_some(value.candidate_lease_id), extensions: value.extensions, } } @@ -786,6 +794,49 @@ mod tests { use super::*; + #[test] + fn test_legacy_granted_region_wire() { + use prost::Message; + + let legacy_bytes: &[u8] = include_bytes!( + "../../../tests/compatibility/wire/candidate_lease_id/legacy_granted_region.pb" + ); + let granted = GrantedRegion::from(PbGrantedRegion::decode(legacy_bytes).unwrap()); + assert_eq!( + granted, + GrantedRegion { + candidate_lease_id: None, + extensions: HashMap::from([("plugin".to_string(), b"payload".to_vec())]), + ..GrantedRegion::new(RegionId::new(1024, 1), RegionRole::Follower) + } + ); + + assert_eq!(PbGrantedRegion::from(granted).encode_to_vec(), legacy_bytes); + } + + #[test] + fn test_granted_region_candidate_lease_id_wire() { + use prost::Message; + + let granted = GrantedRegion { + candidate_lease_id: Some(7), + ..GrantedRegion::new(RegionId::new(1024, 1), RegionRole::Follower) + }; + // Region id (field 1), role Follower (field 2), then candidate_lease_id as a uint64 + // varint in field 3. + let bytes: &[u8] = &[ + 0x08, 0x81, 0x80, 0x80, 0x80, 0x80, 0x80, 0x01, 0x10, 0x01, 0x18, 0x07, + ]; + assert_eq!( + PbGrantedRegion::from(granted.clone()).encode_to_vec(), + bytes + ); + assert_eq!( + GrantedRegion::from(PbGrantedRegion::decode(bytes).unwrap()), + granted + ); + } + #[test] fn region_statistic_flush_bytes_compatibility() { let legacy_bytes = br#"{ @@ -1169,12 +1220,15 @@ pub trait RegionEngine: Send + Sync { /// The region must not acknowledge a write whose WAL append completes at or after the /// deadline of its latest Leader or StagingLeader lease. Leases of other roles do not extend /// that deadline. + /// + /// `candidate_lease_id` is the lease's [GrantedRegion::candidate_lease_id]. fn set_region_role_with_lease( &self, region_id: RegionId, role: RegionRole, sent_at: Instant, deadline: Instant, + candidate_lease_id: Option, ) -> Result; /// Syncs the region manifest to the given manifest version. diff --git a/tests-integration/src/instance.rs b/tests-integration/src/instance.rs index dd9509b3958..c2ab3a678d1 100644 --- a/tests-integration/src/instance.rs +++ b/tests-integration/src/instance.rs @@ -754,7 +754,7 @@ mod tests { let instance = standalone.fe_instance(); query(instance, "CREATE DATABASE other").await; for schema in ["public", "other"] { - create_table(instance, &format!("CREATE TABLE {schema}.{METRICS_EXEMPLARS_TABLE} (__table_id INT UNSIGNED NOT NULL, __tsid BIGINT UNSIGNED NOT NULL, greptime_timestamp TIMESTAMP(9) TIME INDEX, greptime_metric STRING, greptime_value DOUBLE, exemplar_labels JSON2, PRIMARY KEY (__table_id, __tsid, greptime_metric)) WITH ('append_mode'='true', 'primary_key_encoding'='sparse')")).await; + create_table(instance, &format!("CREATE TABLE {schema}.{METRICS_EXEMPLARS_TABLE} (__table_id INT UNSIGNED NOT NULL, __tsid BIGINT UNSIGNED NOT NULL, greptime_timestamp TIMESTAMP(9) TIME INDEX, greptime_metric STRING, greptime_value DOUBLE, greptime_exemplar_labels JSON2, PRIMARY KEY (__table_id, __tsid, greptime_metric)) WITH ('append_mode'='true', 'primary_key_encoding'='sparse')")).await; } for expression in [ "rate(metric{__schema__=\"public\"}[5m]) + metric{__database__=\"secret\"}", diff --git a/tests-integration/src/otlp.rs b/tests-integration/src/otlp.rs index 47e169e54ec..8e193843627 100644 --- a/tests-integration/src/otlp.rs +++ b/tests-integration/src/otlp.rs @@ -1923,8 +1923,9 @@ WITH( } } + #[rstest::rstest] #[tokio::test(flavor = "multi_thread")] - async fn test_exemplar_otlp_memory_wait_and_lifetime() { + async fn test_exemplar_otlp_memory_wait_and_lifetime(#[values(false, true)] gate_source: bool) { use common_memory_manager::OnExhaustedPolicy; use servers::request_memory_limiter::ServerMemoryLimiter; @@ -2052,12 +2053,32 @@ WITH( timeout: Duration::from_secs(10), }, ); + let mut request = exemplar_metric_request(2); + for (index, metric) in request.resource_metrics[0].scope_metrics[0] + .metrics + .iter_mut() + .enumerate() + { + let Some(metric::Data::Gauge(gauge)) = &mut metric.data else { + unreachable!() + }; + let point = &mut gauge.data_points[0]; + point.time_unix_nano = 120_000_000_000; + point.exemplars[0].time_unix_nano = point.time_unix_nano; + if index == 1 { + point.exemplars.clear(); + } + } let table = instance .catalog_manager() .table( DEFAULT_CATALOG_NAME, "public", - METRICS_EXEMPLARS_TABLE, + if gate_source { + "exemplar_memory_0" + } else { + METRICS_EXEMPLARS_TABLE + }, None, ) .await @@ -2071,6 +2092,7 @@ WITH( .region_routes[0] .region .id; + let region_id = RegionId::new(table.table_info().table_id(), region_id.region_number()); for cancel in [false, true] { let (started_tx, started_rx) = oneshot::channel(); let (release_tx, release_rx) = oneshot::channel(); @@ -2109,6 +2131,18 @@ WITH( let released = limiter.acquire(limit).await.unwrap(); drop(released); assert_eq!(limiter.used_bytes(), 0); + if gate_source { + for sql in [ + format!( + "SELECT COUNT(*)=0 FROM {METRICS_EXEMPLARS_TABLE} WHERE CAST(greptime_timestamp AS BIGINT)=120000000000" + ), + "SELECT COUNT(*)=1 FROM exemplar_memory_1".into(), + ] { + assert_trace_v2_query(&instance, &sql, ctx.clone()) + .await + .unwrap(); + } + } } } @@ -2136,9 +2170,9 @@ WITH( let mut metrics = Vec::new(); for (i, key) in [ "greptime_metric", - "exemplar_labels", + "greptime_exemplar_labels", "greptime.metric", - "exemplar.labels", + "greptime.exemplar.labels", ] .into_iter() .enumerate() @@ -2177,9 +2211,9 @@ WITH( assert_eq!(dropped.get(), before + 9); for (table, column) in [ ("collision_0", "greptime_metric"), - ("collision_1", "exemplar_labels"), + ("collision_1", "greptime_exemplar_labels"), ("collision_2", "greptime_metric"), - ("collision_3", "exemplar_labels"), + ("collision_3", "greptime_exemplar_labels"), ("collision_default", "greptime_metric"), ] { assert_trace_v2_query( @@ -3965,6 +3999,94 @@ WITH( } } + #[tokio::test(flavor = "multi_thread")] + async fn test_otlp_initial_write_auto_create_physical_timestamp_unit() { + use common_time::timestamp::TimeUnit as ConfigTimeUnit; + + for (unit, arrow_unit, expected) in [ + (ConfigTimeUnit::Second, TimeUnit::Second, 60), + (ConfigTimeUnit::Millisecond, TimeUnit::Millisecond, 60_123), + ( + ConfigTimeUnit::Microsecond, + TimeUnit::Microsecond, + 60_123_456, + ), + ( + ConfigTimeUnit::Nanosecond, + TimeUnit::Nanosecond, + 60_123_456_789, + ), + ] { + let standalone = GreptimeDbStandaloneBuilder::new(&format!("otlp_initial_{unit:?}")) + .with_auto_create_physical_table_timestamp_unit(unit) + .build() + .await; + let instance = standalone.fe_instance(); + let mut ctx = QueryContext::with(DEFAULT_CATALOG_NAME, "public"); + ctx.set_protocol_ctx(ProtocolCtx::OtlpMetric(OtlpMetricCtx { + with_metric_engine: true, + ..Default::default() + })); + let ctx = Arc::new(ctx); + + // No pre-created tables: preflight must accept the first point so + // ingestion can create both tables with the configured time index. + let outcome = instance + .metrics( + metric_request(vec![gauge_metric( + "initial_metric", + &[(60_123_456_789, 1.0, None)], + )]), + ctx.clone(), + None, + ) + .await + .unwrap(); + assert_eq!( + (outcome.accepted_data_points, outcome.rejected_data_points), + (1, 0), + "unit={unit:?}" + ); + + for table in ["greptime_physical_table", "initial_metric"] { + let output = instance + .do_query( + &format!("SELECT greptime_timestamp FROM {table}"), + ctx.clone(), + ) + .await + .remove(0) + .unwrap(); + let OutputData::Stream(stream) = output.data else { + panic!("expected stream") + }; + let batches = RecordBatches::try_collect(stream).await.unwrap().take(); + assert_eq!( + batches.iter().map(|batch| batch.num_rows()).sum::(), + 1 + ); + let timestamp = batches[0].column(0); + assert_eq!( + timestamp.data_type(), + &DataType::Timestamp(arrow_unit, None) + ); + let actual = match arrow_unit { + TimeUnit::Second => timestamp.as_primitive::().value(0), + TimeUnit::Millisecond => timestamp + .as_primitive::() + .value(0), + TimeUnit::Microsecond => timestamp + .as_primitive::() + .value(0), + TimeUnit::Nanosecond => { + timestamp.as_primitive::().value(0) + } + }; + assert_eq!(actual, expected, "unit={unit:?}, table={table}"); + } + } + } + #[tokio::test(flavor = "multi_thread")] async fn test_otlp_preflight_shared_physical_and_fanout_conflicts() { let standalone = GreptimeDbStandaloneBuilder::new("otlp_physical_conflicts") diff --git a/tests-integration/src/prom_store.rs b/tests-integration/src/prom_store.rs index 8e78b32cdee..c248f5124f3 100644 --- a/tests-integration/src/prom_store.rs +++ b/tests-integration/src/prom_store.rs @@ -45,6 +45,315 @@ mod tests { use crate::standalone::GreptimeDbStandaloneBuilder; use crate::tests; + #[tokio::test(flavor = "multi_thread")] + async fn test_table_batch_combined_memory_limit() { + use std::time::Duration; + + use api::greptime_proto::io::prometheus::write::v2; + use frontend::service_config::BatcherOptions; + use servers::batcher::BatchingProtocol; + use servers::prom_remote_write::validation::PromValidationMode; + + let label = "x".repeat(64 * 1024); + let v1 = WriteRequest { + timeseries: vec![TimeSeries { + labels: vec![ + Label { + name: "__name__".into(), + value: "quota_probe".into(), + }, + Label { + name: "job".into(), + value: label.clone(), + }, + ], + samples: vec![Sample { + value: 1.0, + timestamp: 1, + }], + ..Default::default() + }], + ..Default::default() + }; + let v2 = v2::Request { + symbols: vec![ + "".into(), + "__name__".into(), + "quota_probe".into(), + "job".into(), + "x".repeat(32 * 1024), + ], + timeseries: vec![v2::TimeSeries { + labels_refs: vec![1, 2, 3, 4], + samples: vec![v2::Sample { + value: 1.0, + timestamp: 1, + ..Default::default() + }], + ..Default::default() + }], + }; + for limit in [320 * 1024, 768 * 1024, 0] { + let standalone = GreptimeDbStandaloneBuilder::new(&format!("combined_memory_{limit}")) + .with_write_memory_limit(limit) + .with_table_batcher(BatcherOptions { + protocols: vec![BatchingProtocol::Prom, BatchingProtocol::Influxdb], + pending_rows_flush_interval: Duration::from_millis(10), + ..Default::default() + }) + .build() + .await; + let instance = standalone.fe_instance(); + let memory = instance.server_memory_limiter(); + let build_server = |protocols| { + HttpServerBuilder::new(HttpOptions::default()) + .with_memory_limiter(memory.clone()) + .with_batching_protocols(protocols) + .with_influxdb_handler(instance.clone()) + .with_prom_handler( + instance.clone(), + None, + false, + PromValidationMode::Strict, + None, + ) + .build() + }; + let server = build_server(vec![BatchingProtocol::Prom, BatchingProtocol::Influxdb]); + let client = TestClient::new(server.build(server.make_app()).unwrap()).await; + let v2_body = prom_store::snappy_compress(&v2.encode_to_vec()).unwrap(); + // The v2 decoder itself fits; the rejection below must happen during Arrow admission. + let unbatched = build_server(vec![]); + let unbatched = TestClient::new(unbatched.build(unbatched.make_app()).unwrap()).await; + let response = unbatched + .post("/v1/prometheus/write") + .header( + "content-type", + "application/x-protobuf;proto=io.prometheus.write.v2.Request", + ) + .header("content-encoding", "snappy") + .body(v2_body.clone()) + .send() + .await; + assert!(response.status().is_success(), "{}", response.text().await); + assert_eq!(memory.used_bytes(), 0); + + for (path, content_type, encoding, body, fits_alone) in [ + // The longer label still fits in Arrow when only the compressed body is retained. + ( + "/v1/prometheus/write", + "application/x-protobuf", + "snappy", + prom_store::snappy_compress(&v1.encode_to_vec()).unwrap(), + true, + ), + ( + "/v1/influxdb/write", + "text/plain", + "identity", + format!("quota_probe,job={label} greptime_value=1 1000000").into_bytes(), + false, + ), + ( + "/v1/prometheus/write", + "application/x-protobuf;proto=io.prometheus.write.v2.Request", + "snappy", + v2_body, + false, + ), + ] { + let response = client + .post(path) + .header("content-type", content_type) + .header("content-encoding", encoding) + .body(body) + .send() + .await; + if limit == 320 * 1024 && !fits_alone { + assert_eq!(response.status(), 429, "{}", response.text().await); + } else { + assert!(response.status().is_success(), "{}", response.text().await); + } + tokio::time::timeout(Duration::from_secs(5), async { + while memory.used_bytes() != 0 { + tokio::task::yield_now().await; + } + }) + .await + .unwrap(); + } + } + } + + #[tokio::test(flavor = "multi_thread")] + async fn test_exemplar_wide_schema_conversion_memory_limit() { + use std::time::Duration; + + use api::prom_store::remote::Exemplar; + use frontend::service_config::BatcherOptions; + use otel_arrow_rust::proto::opentelemetry::collector::metrics::v1::ExportMetricsServiceRequest; + use otel_arrow_rust::proto::opentelemetry::metrics::v1 as otlp; + use servers::batcher::BatchingProtocol; + use servers::prom_remote_write::validation::PromValidationMode; + + let v1 = WriteRequest { + timeseries: vec![TimeSeries { + labels: vec![ + Label { + name: "__name__".into(), + value: "probe_metric".into(), + }, + Label { + name: "job".into(), + value: "api".into(), + }, + ], + samples: vec![Sample { + value: 1.0, + timestamp: 60_000, + }], + exemplars: vec![ + Exemplar { + labels: vec![Label { + name: "trace_id".into(), + value: "abc".into() + }], + value: 0.5, + timestamp: 60_000, + }; + 1000 + ], + ..Default::default() + }], + ..Default::default() + }; + let otlp = ExportMetricsServiceRequest { + resource_metrics: vec![otlp::ResourceMetrics { + scope_metrics: vec![otlp::ScopeMetrics { + metrics: vec![otlp::Metric { + name: "probe_metric".into(), + data: Some(otlp::metric::Data::Gauge(otlp::Gauge { + data_points: vec![otlp::NumberDataPoint { + time_unix_nano: 62_000_000_000, + value: Some(otlp::number_data_point::Value::AsDouble(1.0)), + exemplars: vec![ + otlp::Exemplar { + time_unix_nano: 62_000_000_000, + value: Some(otlp::exemplar::Value::AsDouble(0.5)), + trace_id: vec![0xab; 16], + ..Default::default() + }; + 1000 + ], + ..Default::default() + }], + })), + ..Default::default() + }], + ..Default::default() + }], + ..Default::default() + }], + }; + for (limit, remote_write) in [ + (4 * 1024 * 1024, false), + (64 * 1024 * 1024, false), + // Metric-engine Remote Write bypasses ordinary-table Arrow batching. + (4 * 1024 * 1024, true), + ] { + let standalone = + GreptimeDbStandaloneBuilder::new(&format!("exemplar_wide_{limit}_{remote_write}")) + .with_write_memory_limit(limit) + .with_table_batcher(BatcherOptions { + protocols: vec![BatchingProtocol::Prom, BatchingProtocol::Otlp], + pending_rows_flush_interval: Duration::from_millis(10), + ..Default::default() + }) + .build() + .await; + let instance = standalone.fe_instance(); + let names = (0..2048).map(|i| format!("tag_{i}")).collect::>(); + for sql in [ + "CREATE TABLE probe_physical (greptime_timestamp TIMESTAMP(3) TIME INDEX, greptime_value DOUBLE) ENGINE=metric WITH ('physical_metric_table'='')".to_string(), + "CREATE TABLE probe_metric (greptime_timestamp TIMESTAMP(3) TIME INDEX, greptime_value DOUBLE, job STRING, PRIMARY KEY(job)) ENGINE=metric WITH ('on_physical_table'='probe_physical')".to_string(), + format!("CREATE TABLE greptime_metrics_exemplars (__table_id INT UNSIGNED NOT NULL, __tsid BIGINT UNSIGNED NOT NULL, greptime_metric STRING, greptime_timestamp TIMESTAMP(9) TIME INDEX, greptime_value DOUBLE, greptime_exemplar_labels JSON2, job STRING, {}, PRIMARY KEY (__table_id, __tsid, greptime_metric, job, {})) ENGINE=mito WITH ('append_mode'='true', 'primary_key_encoding'='sparse')", + names.iter().map(|n| format!("{n} STRING")).collect::>().join(","), names.join(",")), + ] { + instance.do_query(&sql, QueryContext::arc()).await.remove(0).unwrap(); + } + let memory = instance.server_memory_limiter(); + assert_eq!(memory.limit_bytes(), limit); + let server = HttpServerBuilder::new(HttpOptions::default()) + .with_memory_limiter(memory.clone()) + .with_batching_protocols(vec![BatchingProtocol::Prom, BatchingProtocol::Otlp]) + .with_otlp_handler(instance.clone(), true) + .with_prom_handler( + instance.clone(), + None, + true, + PromValidationMode::Strict, + None, + ) + .build(); + let client = TestClient::new(server.build(server.make_app()).unwrap()).await; + let (path, encoding, body) = if remote_write { + ( + "/v1/prometheus/write", + "snappy", + prom_store::snappy_compress(&v1.encode_to_vec()).unwrap(), + ) + } else { + ("/v1/otlp/v1/metrics", "identity", otlp.encode_to_vec()) + }; + let response = client + .post(path) + .header("content-type", "application/x-protobuf") + .header("content-encoding", encoding) + .body(body) + .send() + .await; + let success = remote_write || limit > 4 * 1024 * 1024; + assert_eq!( + response.status().is_success(), + success, + "{path}, quota={limit}: {}", + response.text().await + ); + if !success { + assert_eq!(response.status(), 429); + } + tokio::time::timeout(Duration::from_secs(5), async { + while memory.used_bytes() != 0 { + tokio::task::yield_now().await; + } + }) + .await + .unwrap(); + let output = instance + .do_query( + "SELECT COUNT(*) FROM greptime_metrics_exemplars", + QueryContext::arc(), + ) + .await + .remove(0) + .unwrap(); + let OutputData::Stream(stream) = output.data else { + unreachable!() + }; + let batches = common_recordbatch::RecordBatches::try_collect(stream) + .await + .unwrap() + .take(); + assert_eq!( + batches[0] + .column(0) + .as_primitive::() + .value(0), + if success { 1000 } else { 0 } + ); + } + } + #[tokio::test(flavor = "multi_thread")] async fn test_standalone_prom_store_remote_rw_default_physical_table() { common_telemetry::init_default_ut_logging(); @@ -169,6 +478,202 @@ mod tests { .await; } + #[tokio::test(flavor = "multi_thread")] + async fn test_standalone_prom_remote_write_auto_create_microsecond_physical_table() { + common_telemetry::init_default_ut_logging(); + let standalone = GreptimeDbStandaloneBuilder::new("test_prom_rw_auto_create_us_physical") + .with_auto_create_physical_table_timestamp_unit( + common_time::timestamp::TimeUnit::Microsecond, + ) + .build() + .await; + let instance = standalone.fe_instance(); + + let db = "prometheus_auto_create_us"; + let ctx = Arc::new(QueryContext::with(DEFAULT_CATALOG_NAME, db)); + assert!( + SqlQueryHandler::do_query( + instance.as_ref(), + &format!("CREATE DATABASE IF NOT EXISTS {db}"), + ctx.clone(), + ) + .await + .first() + .unwrap() + .is_ok() + ); + + // No manual table creation: both the physical table and the logical + // table `metric1` must be auto-created by the write, with a + // microsecond time index inherited from the physical table. + let write_request = WriteRequest { + timeseries: vec![prom_store::mock_timeseries()[0].clone()], + ..Default::default() + }; + let (row_inserts, _) = to_grpc_row_insert_requests(&write_request).unwrap(); + instance + .write(row_inserts, ctx.clone(), true) + .await + .unwrap(); + + for table in ["greptime_physical_table", "metric1"] { + let mut output = instance + .do_query( + &format!("SELECT greptime_timestamp FROM {table}"), + ctx.clone(), + ) + .await; + let OutputData::Stream(stream) = output.remove(0).unwrap().data else { + unreachable!() + }; + let batches = common_recordbatch::RecordBatches::try_collect(stream) + .await + .unwrap() + .take(); + assert_eq!(batches[0].num_rows(), 2, "unexpected rows in {table}"); + let ts_column = batches[0].column(0); + assert_eq!( + ts_column.data_type(), + &DataType::Timestamp(TimeUnit::Microsecond, None), + "unexpected time index type in {table}" + ); + let timestamps = ts_column + .as_primitive::() + .values(); + assert_eq!(timestamps.to_vec(), vec![1_000_000, 2_000_000]); + } + + // Remote read narrows microsecond timestamps back to milliseconds. + let read_request = ReadRequest { + queries: vec![Query { + start_timestamp_ms: 1000, + end_timestamp_ms: 2000, + matchers: vec![LabelMatcher { + name: prom_store::METRIC_NAME_LABEL.to_string(), + value: "metric1".to_string(), + r#type: 0, + }], + ..Default::default() + }], + ..Default::default() + }; + let resp = instance.read(read_request, ctx.clone()).await.unwrap(); + let body = prom_store::snappy_decompress(&resp.body).unwrap(); + let read_response = ReadResponse::decode(&body[..]).unwrap(); + let samples = &read_response.results[0].timeseries[0].samples; + assert_eq!( + samples.clone(), + vec![ + Sample { + value: 1.0, + timestamp: 1000 + }, + Sample { + value: 2.0, + timestamp: 2000 + } + ] + ); + } + + #[tokio::test(flavor = "multi_thread")] + async fn test_standalone_prom_batcher_auto_create_microsecond_physical_table() { + use servers::batcher::logical_table::PendingRowsSchemaAlterer; + + common_telemetry::init_default_ut_logging(); + let standalone = GreptimeDbStandaloneBuilder::new("test_prom_batcher_auto_create_us") + .with_auto_create_physical_table_timestamp_unit( + common_time::timestamp::TimeUnit::Microsecond, + ) + .build() + .await; + let instance = standalone.fe_instance(); + + // Drives the batcher's schema-alterer path: a missing physical table is + // auto-created with the configured microsecond unit, and new logical + // tables aligned to it. + let db = "prometheus_batcher_auto_create_us"; + let ctx = Arc::new(QueryContext::with(DEFAULT_CATALOG_NAME, db)); + assert!( + SqlQueryHandler::do_query( + instance.as_ref(), + &format!("CREATE DATABASE IF NOT EXISTS {db}"), + ctx.clone(), + ) + .await + .first() + .unwrap() + .is_ok() + ); + // The batcher aligns request schemas to the physical table's unit + // before invoking the schema alterer, so the schema below arrives in + // the configured microsecond unit. A missing physical table must be + // auto-created with the same unit. + let request_schema = vec![ + api::v1::ColumnSchema { + column_name: "greptime_timestamp".to_string(), + datatype: ColumnDataType::TimestampMicrosecond as i32, + semantic_type: SemanticType::Timestamp as i32, + datatype_extension: None, + options: None, + }, + api::v1::ColumnSchema { + column_name: "greptime_value".to_string(), + datatype: ColumnDataType::Float64 as i32, + semantic_type: SemanticType::Field as i32, + datatype_extension: None, + options: None, + }, + api::v1::ColumnSchema { + column_name: "job".to_string(), + datatype: ColumnDataType::String as i32, + semantic_type: SemanticType::Tag as i32, + datatype_extension: None, + options: None, + }, + ]; + instance + .create_tables_if_missing_batch( + DEFAULT_CATALOG_NAME, + db, + &[("metric1", request_schema.as_slice())], + true, + ctx.clone(), + ) + .await + .unwrap(); + + for table in ["greptime_physical_table", "metric1"] { + let mut output = instance + .do_query( + &format!( + "SELECT greptime_data_type FROM information_schema.columns \ + WHERE table_schema='{db}' AND table_name='{table}' \ + AND column_name='greptime_timestamp'" + ), + ctx.clone(), + ) + .await; + let OutputData::Stream(stream) = output.remove(0).unwrap().data else { + unreachable!() + }; + let batches = common_recordbatch::RecordBatches::try_collect(stream) + .await + .unwrap() + .take(); + assert_eq!( + batches[0].num_rows(), + 1, + "missing time index column in {table}" + ); + let data_type = batches[0].column(0).as_string::().value(0); + assert_eq!( + data_type, "TimestampMicrosecond", + "unexpected time index type in {table}" + ); + } + } + /// Regression test for : /// prometheus remote write/read against a physical metric table /// pre-created with a non-millisecond time index. Millisecond samples are diff --git a/tests-integration/src/standalone.rs b/tests-integration/src/standalone.rs index 142ef72b000..159b1fb6085 100644 --- a/tests-integration/src/standalone.rs +++ b/tests-integration/src/standalone.rs @@ -22,6 +22,7 @@ use cache::{ use catalog::kvbackend::KvBackendCatalogManagerBuilder; use catalog::process_manager::ProcessManager; use common_base::Plugins; +use common_base::readable_size::ReadableSize; use common_catalog::consts::{MIN_USER_FLOW_ID, MIN_USER_TABLE_ID}; use common_config::KvBackendConfig; use common_datasource::object_store::LocalFileAccess; @@ -90,8 +91,10 @@ pub struct GreptimeDbStandaloneBuilder { slow_query_options: SlowQueryOptions, event_recorder_options: EventRecorderOptions, auto_create_table: bool, + auto_create_physical_table_timestamp_unit: Option, logical_batcher: Option, table_batcher: BatcherOptions, + max_in_flight_write_bytes: ReadableSize, mito_config: Option, pipeline_options: pipeline::PipelineOptions, } @@ -112,8 +115,10 @@ impl GreptimeDbStandaloneBuilder { }, event_recorder_options: EventRecorderOptions::default(), auto_create_table: true, + auto_create_physical_table_timestamp_unit: None, logical_batcher: None, table_batcher: BatcherOptions::default(), + max_in_flight_write_bytes: ReadableSize(0), mito_config: None, pipeline_options: pipeline::PipelineOptions::default(), } @@ -140,6 +145,13 @@ impl GreptimeDbStandaloneBuilder { self } + /// Configures the shared protocol and conversion memory quota. + #[must_use] + pub fn with_write_memory_limit(mut self, bytes: u64) -> Self { + self.max_in_flight_write_bytes = ReadableSize(bytes); + self + } + /// Configures logical-table batching for integration tests. #[must_use] pub fn with_logical_batcher(mut self, options: BatcherOptions) -> Self { @@ -153,6 +165,16 @@ impl GreptimeDbStandaloneBuilder { self } + /// Sets the time index unit for auto-created physical metric tables. + #[must_use] + pub fn with_auto_create_physical_table_timestamp_unit( + mut self, + unit: common_time::timestamp::TimeUnit, + ) -> Self { + self.auto_create_physical_table_timestamp_unit = Some(unit); + self + } + /// Sets the event recorder options for the standalone instance. #[must_use] pub fn with_event_recorder_options( @@ -410,7 +432,11 @@ impl GreptimeDbStandaloneBuilder { slow_query: self.slow_query_options.clone(), event_recorder: self.event_recorder_options.clone(), auto_create_table: self.auto_create_table, + auto_create_physical_table_timestamp_unit: self + .auto_create_physical_table_timestamp_unit + .unwrap_or(common_time::timestamp::TimeUnit::Millisecond), pipeline: self.pipeline_options.clone(), + max_in_flight_write_bytes: self.max_in_flight_write_bytes, pending_rows_batcher: PendingRowsBatcherOptions { logical_table: self.logical_batcher.clone(), table: self.table_batcher.clone(), diff --git a/tests-integration/src/test_util.rs b/tests-integration/src/test_util.rs index 5eee6ea1fed..9742fb5bb61 100644 --- a/tests-integration/src/test_util.rs +++ b/tests-integration/src/test_util.rs @@ -913,6 +913,7 @@ pub fn build_test_prom_server( frontend_ref.table_flownode_set_cache().clone(), true, frontend_ref.clone(), + common_time::timestamp::TimeUnit::Millisecond, Duration::from_millis(50), 1000, 4, diff --git a/tests-integration/src/tests/instance_test.rs b/tests-integration/src/tests/instance_test.rs index 2d8034b1510..8c54a5c485a 100644 --- a/tests-integration/src/tests/instance_test.rs +++ b/tests-integration/src/tests/instance_test.rs @@ -3935,6 +3935,15 @@ async fn execute_sql(instance: &Arc, sql: &str) -> Output { execute_sql_with(instance, sql, QueryContext::arc()).await } +async fn get_table(instance: &Arc, name: &str) -> table::TableRef { + instance + .catalog_manager() + .table(DEFAULT_CATALOG_NAME, DEFAULT_SCHEMA_NAME, name, None) + .await + .unwrap() + .unwrap() +} + async fn execute_sql_with_query_parallelism( instance: &Arc, sql: &str, @@ -4558,17 +4567,7 @@ async fn test_exemplar_preserves_physical_table_routing(#[case] batching: bool) ); } for suffix in ["a", "b"] { - let table = frontend - .catalog_manager() - .table( - DEFAULT_CATALOG_NAME, - "public", - &format!("routed_{version}_{suffix}"), - None, - ) - .await - .unwrap() - .unwrap(); + let table = get_table(frontend, &format!("routed_{version}_{suffix}")).await; assert_eq!( table.table_info().meta.options.extra_options["on_physical_table"], format!("physical_{suffix}") @@ -4582,17 +4581,7 @@ async fn test_exemplar_preserves_physical_table_routing(#[case] batching: bool) "+----------+\n| count(*) |\n+----------+\n| 1 |\n+----------+", ) .await; - let table = frontend - .catalog_manager() - .table( - DEFAULT_CATALOG_NAME, - "public", - METRICS_EXEMPLARS_TABLE, - None, - ) - .await - .unwrap() - .unwrap(); + let table = get_table(frontend, METRICS_EXEMPLARS_TABLE).await; let info = table.table_info(); let ids = info.name_to_ids().unwrap(); assert_eq!( @@ -4782,7 +4771,7 @@ async fn test_exemplar_precreated_table_options( execute_sql(frontend, "CREATE TABLE source_physical (ts TIMESTAMP TIME INDEX, val DOUBLE) ENGINE=metric WITH ('physical_metric_table'='')").await; execute_sql(frontend, "CREATE TABLE metric_source (job STRING PRIMARY KEY, ts TIMESTAMP TIME INDEX, val DOUBLE) ENGINE=metric WITH ('on_physical_table'='source_physical')").await; execute_sql(frontend, &format!( - "CREATE TABLE {METRICS_EXEMPLARS_TABLE} (__table_id INT UNSIGNED NOT NULL, __tsid BIGINT UNSIGNED NOT NULL, greptime_metric STRING, greptime_timestamp TIMESTAMP({precision}) TIME INDEX, greptime_value DOUBLE, exemplar_labels JSON2, PRIMARY KEY (__table_id, __tsid, greptime_metric)) ENGINE=mito WITH ('append_mode'='{append_mode}', 'primary_key_encoding'='{encoding}', 'compaction.type'='twcs')" + "CREATE TABLE {METRICS_EXEMPLARS_TABLE} (__table_id INT UNSIGNED NOT NULL, __tsid BIGINT UNSIGNED NOT NULL, greptime_metric STRING, greptime_timestamp TIMESTAMP({precision}) TIME INDEX, greptime_value DOUBLE, greptime_exemplar_labels JSON2, PRIMARY KEY (__table_id, __tsid, greptime_metric)) ENGINE=mito WITH ('append_mode'='{append_mode}', 'primary_key_encoding'='{encoding}', 'compaction.type'='twcs')" )).await; let (request, _) = into_rows(vec![Exemplar { metric: "metric_source".into(), @@ -4807,17 +4796,7 @@ async fn test_exemplar_precreated_table_options( "{error:?}" ); } - let table = frontend - .catalog_manager() - .table( - DEFAULT_CATALOG_NAME, - "public", - METRICS_EXEMPLARS_TABLE, - None, - ) - .await - .unwrap() - .unwrap(); + let table = get_table(frontend, METRICS_EXEMPLARS_TABLE).await; // Invalid destinations must fail before auto-ALTER adds the inherited label. assert_eq!( table.schema().column_schema_by_name("job").is_some(), @@ -4899,24 +4878,36 @@ async fn test_exemplar_source_identity_policy() { execute_sql(frontend, "CREATE TABLE source_physical (ts TIMESTAMP TIME INDEX, val DOUBLE) ENGINE=metric WITH ('physical_metric_table'='')").await; let create = "CREATE TABLE metric_source (job STRING PRIMARY KEY, ts TIMESTAMP TIME INDEX, val DOUBLE) ENGINE=metric WITH ('on_physical_table'='source_physical')"; execute_sql(frontend, create).await; - let source = frontend - .catalog_manager() - .table(DEFAULT_CATALOG_NAME, "public", "metric_source", None) - .await - .unwrap() - .unwrap() - .table_info(); + let source = get_table(frontend, "metric_source").await.table_info(); // A metric write's captured table ID must not be replaced by a later name lookup. execute_sql(frontend, "DROP TABLE metric_source").await; execute_sql(frontend, create).await; - let replacement = frontend - .catalog_manager() - .table(DEFAULT_CATALOG_NAME, "public", "metric_source", None) - .await - .unwrap() - .unwrap() - .table_info(); + let replacement = get_table(frontend, "metric_source").await.table_info(); assert_ne!(source.table_id(), replacement.table_id()); + let mut missing_tag_request = request("metric_source"); + let rows = missing_tag_request.inserts[0].rows.as_mut().unwrap(); + rows.schema.push(api::v1::helper::tag_column_schema( + "new_tag", + api::v1::ColumnDataType::String, + )); + rows.rows[0] + .values + .push(api::v1::value::ValueData::StringValue("present".into()).into()); + assert!( + frontend + .write_exemplars_with_sources( + missing_tag_request, + QueryContext::arc(), + std::slice::from_ref(&source), + ) + .await + .is_err() + ); + let after = get_table(frontend, "metric_source").await.table_info(); + assert_eq!( + replacement, after, + "reconciliation must not alter a replacement table" + ); frontend .write_exemplars_with_sources( request("metric_source"), @@ -4929,17 +4920,7 @@ async fn test_exemplar_source_identity_policy() { .write_exemplars_prepared(request("metric_source"), QueryContext::arc()) .await .unwrap(); - let table = frontend - .catalog_manager() - .table( - DEFAULT_CATALOG_NAME, - "public", - METRICS_EXEMPLARS_TABLE, - None, - ) - .await - .unwrap() - .unwrap(); + let table = get_table(frontend, METRICS_EXEMPLARS_TABLE).await; let info = table.table_info(); assert_eq!( info.meta @@ -4955,7 +4936,7 @@ async fn test_exemplar_source_identity_policy() { "job", "greptime_value", "greptime_timestamp", - "exemplar_labels", + "greptime_exemplar_labels", ] ); assert_eq!(info.meta.primary_key_indices, [0, 1, 2, 3]); @@ -5363,6 +5344,198 @@ async fn create_exemplar_source(frontend: &Arc, schema: &str, name: &s )).await; } +#[tokio::test(flavor = "multi_thread")] +async fn test_exemplar_source_tag_reconciliation() { + use std::collections::BTreeMap; + + use servers::exemplar::query::Query; + use servers::exemplar::{Exemplar, into_rows}; + use servers::prometheus_handler::PrometheusHandler; + use servers::query_handler::PromStoreProtocolHandler; + use table::requests::AUTO_CREATE_TABLE_KEY; + + use crate::standalone::GreptimeDbStandaloneBuilder; + + let instance = GreptimeDbStandaloneBuilder::new("exemplar_source_tags") + .build() + .await; + let frontend = instance.fe_instance(); + for name in ["first", "second"] { + create_exemplar_source(frontend, "public", name).await; + } + let exemplar = |metric: &str, tag: &str, value: &str| Exemplar { + metric: metric.into(), + series_labels: BTreeMap::from([(tag.into(), value.into())]).into(), + timestamp: 1, + value: 1.0, + labels: BTreeMap::from([("trace_id".into(), "trace".into())]), + }; + let exemplars = vec![ + exemplar("first", "first_only", ""), + exemplar("second", "second_only", "present"), + exemplar("first", "later", "present"), + ]; + let requests = into_rows(exemplars.clone()).unwrap().0; + let rows = requests.inserts[0].rows.as_ref().unwrap(); + let tsid_index = rows + .schema + .iter() + .position(|c| c.column_name == "__tsid") + .unwrap(); + let tsids = rows + .rows + .iter() + .map(|row| { + let Some(api::v1::value::ValueData::U64Value(tsid)) = + &row.values[tsid_index].value_data + else { + panic!("expected a source TSID") + }; + tsid.to_string() + }) + .collect::>(); + frontend + .write_exemplars_prepared(requests, QueryContext::arc()) + .await + .unwrap(); + let mut source_ids = BTreeMap::new(); + for (name, expected) in [ + ("first", vec!["first_only", "later"]), + ("second", vec!["second_only"]), + ] { + let info = get_table(frontend, name).await.table_info(); + source_ids.insert(name, info.table_id()); + let tags = info + .meta + .primary_key_indices + .iter() + .map(|&index| info.meta.schema.column_schemas()[index].name.as_str()) + .collect::>(); + assert_eq!(tags, expected); + assert!(info.meta.schema.column_schema_by_name("trace_id").is_none()); + let output = execute_sql(frontend, &format!("SELECT COUNT(*) FROM {name}")).await; + check_output_stream( + output.data, + "+----------+\n| count(*) |\n+----------+\n| 0 |\n+----------+", + ) + .await; + } + let query = || Query::parse("first + second".into(), "0", "1", "public").unwrap(); + let before = frontend + .query_exemplars(query(), QueryContext::arc()) + .await + .unwrap(); + assert_eq!(before.len(), 3); + for (exemplar, tsid) in exemplars.iter().zip(tsids) { + let mut expected = (*exemplar.series_labels).clone(); + expected.insert("__name__".into(), exemplar.metric.to_string()); + expected.insert( + "__table_id".into(), + source_ids[exemplar.metric.as_ref()].to_string(), + ); + expected.insert("__tsid".into(), tsid); + assert!(before.iter().any(|series| series.series_labels == expected)); + } + + // Disabled automatic DDL and malformed values must not add source tags. + let source = get_table(frontend, "first").await.table_info(); + let mut ctx = QueryContext::arc().fork(); + ctx.set_extension(AUTO_CREATE_TABLE_KEY, "false"); + let blocked = into_rows(vec![exemplar("first", "blocked", "present")]) + .unwrap() + .0; + assert!( + frontend + .write_exemplars_prepared(blocked.clone(), Arc::new(ctx)) + .await + .is_err() + ); + let mut malformed = blocked; + let rows = malformed.inserts[0].rows.as_mut().unwrap(); + let index = rows + .schema + .iter() + .position(|c| c.column_name == "blocked") + .unwrap(); + rows.rows[0].values[index] = api::v1::value::ValueData::F64Value(1.0).into(); + assert!( + frontend + .write_exemplars_prepared(malformed, QueryContext::arc()) + .await + .is_err() + ); + let after = get_table(frontend, "first").await.table_info(); + assert_eq!(source, after); + + execute_sql(frontend, "CREATE TABLE conflict_physical (ts TIMESTAMP TIME INDEX, occupied_field DOUBLE) ENGINE=metric WITH ('physical_metric_table'='')").await; + execute_sql(frontend, "CREATE TABLE conflicting_source (ts TIMESTAMP TIME INDEX, occupied_field DOUBLE) ENGINE=metric WITH ('on_physical_table'='conflict_physical')").await; + let request = into_rows(vec![exemplar( + "conflicting_source", + "occupied_field", + "present", + )]) + .unwrap() + .0; + let error = frontend + .write_exemplars_prepared(request, QueryContext::arc()) + .await + .unwrap_err(); + assert!( + error.output_msg().contains("must be a string tag"), + "{error}" + ); + // Missing sources retain all tags; recreated sources define the exact query's tag projection. + execute_sql(frontend, "DROP TABLE first").await; + let missing = frontend + .query_exemplars(query(), QueryContext::arc()) + .await + .unwrap(); + assert_eq!(before, missing); + create_exemplar_source(frontend, "public", "first").await; + let after = frontend + .query_exemplars(query(), QueryContext::arc()) + .await + .unwrap(); + let mut pruned = before.clone(); + for series in &mut pruned { + series.series_labels.remove("first_only"); + series.series_labels.remove("later"); + } + assert_eq!(pruned, after); + assert_eq!( + after.len(), + 3, + "stored IDs must keep pruned series distinct" + ); + let filtered = frontend + .query_exemplars( + Query::parse("first{later=\"present\"}".into(), "0", "1", "public").unwrap(), + QueryContext::arc(), + ) + .await + .unwrap(); + assert_eq!(filtered.len(), 1); + assert!(!filtered[0].series_labels.contains_key("later")); + assert_eq!( + filtered[0].series_labels["__table_id"], + source_ids["first"].to_string() + ); + for expression in [ + "{__name__=~\"first|second\"}", + "first + {__name__=~\"second\"}", + "first + second + missing", + ] { + let broad = frontend + .query_exemplars( + Query::parse(expression.into(), "0", "1", "public").unwrap(), + QueryContext::arc(), + ) + .await + .unwrap(); + assert_eq!(before, broad, "{expression}"); + } +} + #[rstest] #[case::standalone(false, false, false, false)] #[case::standalone_batched(false, true, false, false)] @@ -5446,7 +5619,7 @@ async fn exemplar_protocol_storage_lifecycle(distributed: bool, batching: bool, greptime_timestamp TIMESTAMP(6) TIME INDEX, greptime_metric STRING, greptime_value DOUBLE, - exemplar_labels JSON2(max_auto_expanded_paths = 0, trace_id STRING), + greptime_exemplar_labels JSON2(max_auto_expanded_paths = 0, trace_id STRING), PRIMARY KEY (__table_id, __tsid, greptime_metric) ) WITH ('append_mode'='true', 'primary_key_encoding'='sparse', 'sst_format'='primary_key')" ), @@ -5566,26 +5739,25 @@ async fn exemplar_protocol_storage_lifecycle(distributed: bool, batching: bool, .await .unwrap(); let status = response.status(); - assert_eq!( - response - .headers() - .get("x-prometheus-remote-write-exemplars-written") - .unwrap(), - "1" - ); - assert_eq!( - response - .headers() - .get("x-prometheus-remote-write-samples-written") - .unwrap(), - "0" - ); + let headers = response.headers().clone(); assert_eq!( status, 204, "{:?}", to_bytes(response.into_body(), usize::MAX).await.unwrap() ); + assert_eq!( + headers + .get("x-prometheus-remote-write-exemplars-written") + .unwrap(), + "1" + ); + assert_eq!( + headers + .get("x-prometheus-remote-write-samples-written") + .unwrap(), + "0" + ); let output = execute_sql( &context.frontend(), "SELECT COUNT(*) FROM retained_exemplar", @@ -5597,6 +5769,62 @@ async fn exemplar_protocol_storage_lifecycle(distributed: bool, batching: bool, ) .await; + let source = get_table(&context.frontend(), "retained_exemplar") + .await + .table_info(); + assert!(source.meta.schema.column_schema_by_name("zone").is_some()); + create_exemplar_source(&context.frontend(), "public", "v1_exemplar_only").await; + let request = WriteRequest { + timeseries: vec![TimeSeries { + labels: vec![ + Label { + name: "__name__".into(), + value: "v1_exemplar_only".into(), + }, + Label { + name: "v1_tag".into(), + value: "present".into(), + }, + ], + exemplars: vec![Exemplar { + timestamp: 1720000000124, + value: 2.0, + ..Default::default() + }], + ..Default::default() + }], + ..Default::default() + }; + let response = app + .clone() + .oneshot( + Request::post("/v1/prometheus/write") + .header("Content-Encoding", "snappy") + .header("Content-Type", "application/x-protobuf") + .body(Body::from( + snappy_compress(&request.encode_to_vec()).unwrap(), + )) + .unwrap(), + ) + .await + .unwrap(); + assert_eq!( + response.status(), + 204, + "{:?}", + to_bytes(response.into_body(), usize::MAX).await.unwrap() + ); + let source = get_table(&context.frontend(), "v1_exemplar_only") + .await + .table_info(); + assert!(source.meta.schema.column_schema_by_name("v1_tag").is_some()); + let output = execute_sql(&context.frontend(), "SELECT COUNT(*) FROM v1_exemplar_only").await; + check_output_stream( + output.data, + "+----------+\n| count(*) |\n+----------+\n| 0 |\n+----------+", + ) + .await; + use otel_arrow_rust::proto::opentelemetry::collector::metrics::v1::ExportMetricsServiceRequest; use otel_arrow_rust::proto::opentelemetry::metrics::v1 as otlp; let request = ExportMetricsServiceRequest { @@ -5685,8 +5913,12 @@ async fn exemplar_protocol_storage_lifecycle(distributed: bool, batching: bool, let value: serde_json::Value = serde_json::from_slice(&bytes).unwrap(); assert_eq!(value["status"], "success", "{phase}: {value}"); for series in value["data"].as_array().unwrap() { - assert!(series["seriesLabels"].get("__table_id").is_none()); - assert!(series["seriesLabels"].get("__tsid").is_none()); + let labels = &series["seriesLabels"]; + let source = get_table(&context.frontend(), labels["__name__"].as_str().unwrap()) + .await + .table_info(); + assert_eq!(labels["__table_id"], source.table_id().to_string()); + assert!(labels["__tsid"].as_str().unwrap().parse::().is_ok()); } assert_eq!( value["data"].as_array().unwrap().len(), @@ -5813,7 +6045,7 @@ async fn test_exemplar_query_bounds_and_malformed_rows( .build() .await; let frontend = instance.fe_instance(); - execute_sql(frontend, &format!("CREATE TABLE {METRICS_EXEMPLARS_TABLE} (__table_id INT UNSIGNED NOT NULL, __tsid BIGINT UNSIGNED NOT NULL, greptime_timestamp TIMESTAMP(9) TIME INDEX, greptime_metric STRING, job STRING, greptime_value DOUBLE, exemplar_labels JSON2, PRIMARY KEY (__table_id, __tsid, greptime_metric, job)) WITH ('append_mode'='true', 'primary_key_encoding'='sparse')")).await; + execute_sql(frontend, &format!("CREATE TABLE {METRICS_EXEMPLARS_TABLE} (__table_id INT UNSIGNED NOT NULL, __tsid BIGINT UNSIGNED NOT NULL, greptime_timestamp TIMESTAMP(9) TIME INDEX, greptime_metric STRING, job STRING, greptime_value DOUBLE, greptime_exemplar_labels JSON2, PRIMARY KEY (__table_id, __tsid, greptime_metric, job)) WITH ('append_mode'='true', 'primary_key_encoding'='sparse')")).await; execute_sql( frontend, &format!( @@ -5883,6 +6115,8 @@ async fn test_exemplar_query_bounds_and_malformed_rows( assert!(response.get("warnings").is_none(), "{response}"); } if series > 0 { + assert_eq!(response["data"][0]["seriesLabels"]["__table_id"], "42"); + assert_eq!(response["data"][0]["seriesLabels"]["__tsid"], "7"); assert_eq!( response["data"][0]["exemplars"].as_array().unwrap().len(), 2, @@ -5957,15 +6191,13 @@ async fn test_exemplar_concurrent_ddl_and_precreated_contract() { }); assert_eq!(futures::future::join_all(writes).await, vec![1; 8]); } - let info = frontend - .catalog_manager() - .table("greptime", "public", METRICS_EXEMPLARS_TABLE, None) + let info = get_table(frontend, METRICS_EXEMPLARS_TABLE) .await - .unwrap() - .unwrap() .table_info(); assert_eq!(info.meta.primary_key_indices.len(), 12); operator::insert::validate_exemplar_table(&info).unwrap(); + let source = get_table(frontend, "concurrent").await.table_info(); + assert_eq!(source.meta.primary_key_indices.len(), 9); let response = frontend .query_exemplars( Query::parse("concurrent".into(), "0", "1", "public").unwrap(), @@ -5980,7 +6212,7 @@ async fn test_exemplar_concurrent_ddl_and_precreated_contract() { // Incompatible pre-created tables must be rejected before adding inherited tags. let definition = format!( - "CREATE TABLE {METRICS_EXEMPLARS_TABLE} (__table_id INT UNSIGNED NOT NULL, __tsid BIGINT UNSIGNED NOT NULL, greptime_timestamp TIMESTAMP(6) TIME INDEX, greptime_metric STRING, greptime_value DOUBLE, exemplar_labels JSON2(max_auto_expanded_paths=0, trace_id STRING), PRIMARY KEY (__table_id, __tsid, greptime_metric)) WITH ('append_mode'='true', 'primary_key_encoding'='sparse')" + "CREATE TABLE {METRICS_EXEMPLARS_TABLE} (__table_id INT UNSIGNED NOT NULL, __tsid BIGINT UNSIGNED NOT NULL, greptime_timestamp TIMESTAMP(6) TIME INDEX, greptime_metric STRING, greptime_value DOUBLE, greptime_exemplar_labels JSON2(max_auto_expanded_paths=0, trace_id STRING), PRIMARY KEY (__table_id, __tsid, greptime_metric)) WITH ('append_mode'='true', 'primary_key_encoding'='sparse')" ); for definition in [ definition.replace("greptime_value DOUBLE", "greptime_value BIGINT"), @@ -5990,12 +6222,8 @@ async fn test_exemplar_concurrent_ddl_and_precreated_contract() { ] { execute_sql(frontend, &format!("DROP TABLE {METRICS_EXEMPLARS_TABLE}")).await; execute_sql(frontend, &definition).await; - let before = frontend - .catalog_manager() - .table("greptime", "public", METRICS_EXEMPLARS_TABLE, None) + let before = get_table(frontend, METRICS_EXEMPLARS_TABLE) .await - .unwrap() - .unwrap() .table_info(); assert!( frontend @@ -6004,14 +6232,15 @@ async fn test_exemplar_concurrent_ddl_and_precreated_contract() { .is_err(), "{definition}" ); - let after = frontend - .catalog_manager() - .table("greptime", "public", METRICS_EXEMPLARS_TABLE, None) + let after = get_table(frontend, METRICS_EXEMPLARS_TABLE) .await - .unwrap() - .unwrap() .table_info(); assert_eq!(before, after, "incompatible table must not be altered"); + let source_after = get_table(frontend, "concurrent").await.table_info(); + assert_eq!( + source, source_after, + "incompatible destination must not alter sources" + ); } let disabled = GreptimeDbStandaloneBuilder::new("exemplar_disabled_ddl") @@ -6034,6 +6263,8 @@ async fn test_exemplar_concurrent_ddl_and_precreated_contract() { .unwrap() .is_none() ); + let source = get_table(frontend, "concurrent").await.table_info(); + assert!(source.meta.primary_key_indices.is_empty()); } #[rstest] @@ -6088,7 +6319,7 @@ async fn test_exemplar_precreated_precision_and_label_defaults( __tsid BIGINT UNSIGNED NOT NULL, greptime_timestamp TIMESTAMP(6) TIME INDEX, greptime_metric STRING, site STRING {default}, - greptime_value DOUBLE, exemplar_labels JSON2, + greptime_value DOUBLE, greptime_exemplar_labels JSON2, PRIMARY KEY (__table_id, __tsid, greptime_metric, site) ) WITH ('append_mode'='true', 'primary_key_encoding'='sparse')" ), @@ -6194,14 +6425,24 @@ async fn test_exemplar_cross_schema_exact_identity() { .query_exemplars(query, QueryContext::arc()) .await .unwrap(); - assert_eq!(response.len(), 1); - assert_eq!(response[0].exemplars.len(), values.len()); + assert_eq!(response.len(), 2); + assert_ne!( + response[0].series_labels["__table_id"], + response[1].series_labels["__table_id"] + ); + assert_eq!( + response[0].series_labels["__tsid"], + response[1].series_labels["__tsid"] + ); let encoded = serde_json::to_string(&response).unwrap(); - for value in ["0", "-0", "NaN", "+Inf", "-Inf"] { - assert!( - response[0].exemplars.iter().any(|e| e.value == value), - "{encoded}" - ); + for series in &response { + assert_eq!(series.exemplars.len(), values.len()); + for value in ["0", "-0", "NaN", "+Inf", "-Inf"] { + assert!( + series.exemplars.iter().any(|e| e.value == value), + "{encoded}" + ); + } } assert!(encoded.contains("\"timestamp\":-0.001"), "{encoded}"); } diff --git a/tests-integration/src/tests/postgres_copy_in_test.rs b/tests-integration/src/tests/postgres_copy_in_test.rs index e6d57330cb5..df165d428e2 100644 --- a/tests-integration/src/tests/postgres_copy_in_test.rs +++ b/tests-integration/src/tests/postgres_copy_in_test.rs @@ -17,6 +17,7 @@ use bytes::Bytes; use common_telemetry::init_default_ut_logging; +use datatypes::arrow; use futures::SinkExt; use tokio_postgres::NoTls; @@ -41,6 +42,396 @@ async fn feed_copy_in( sink.as_mut().finish().await } +/// Standard IPC output, not Flight protobuf messages or PostgreSQL binary COPY. +fn arrow_copy_payload(compression: Option, batches: usize) -> Vec { + use arrow::array::{ArrayRef, Float64Array, StringArray, TimestampMillisecondArray}; + use arrow::ipc::writer::{IpcWriteOptions, StreamWriter}; + use arrow::record_batch::RecordBatch; + use std::sync::Arc; + + // Field order deliberately differs from the table's declaration. + let batch = RecordBatch::try_from_iter(vec![ + ( + "val", + Arc::new(Float64Array::from(vec![Some(1.5), None])) as ArrayRef, + ), + ( + "ts", + Arc::new(TimestampMillisecondArray::from(vec![1000, 2000])) as ArrayRef, + ), + ( + "host", + Arc::new(StringArray::from(vec!["a", "z"])) as ArrayRef, + ), + ]) + .unwrap(); + let options = IpcWriteOptions::default() + .try_with_compression(compression) + .unwrap(); + let mut writer = + StreamWriter::try_new_with_options(Vec::new(), &batch.schema(), options).unwrap(); + for _ in 0..batches { + writer.write(&batch).unwrap(); + } + writer.finish().unwrap(); + writer.into_inner().unwrap() +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn test_postgres_copy_in_arrow_end_to_end() { + init_default_ut_logging(); + let (_guard, server) = setup_pg_server(StorageType::File, "pg_copy_arrow").await; + let client = connect(server.bind_addr().unwrap().port()).await; + client.simple_query("CREATE TABLE arrow_copy (host STRING PRIMARY KEY, val DOUBLE, ts TIMESTAMP TIME INDEX)").await.unwrap(); + for compression in [ + None, + Some(arrow::ipc::CompressionType::LZ4_FRAME), + Some(arrow::ipc::CompressionType::ZSTD), + ] { + let payload = arrow_copy_payload(compression, 3); + let rows = feed_copy_in( + &client, + "COPY public.arrow_copy FROM STDIN WITH (FORMAT arrow)", + payload.chunks(7).map(Bytes::copy_from_slice).collect(), + ) + .await + .unwrap(); + assert_eq!(rows, 6); + let messages = client + .simple_query( + "SELECT host, val, CAST(ts AS BIGINT) AS millis FROM arrow_copy ORDER BY ts", + ) + .await + .unwrap(); + let rows: Vec<_> = messages + .iter() + .filter(|m| matches!(m, tokio_postgres::SimpleQueryMessage::Row(_))) + .collect(); + assert_eq!(rows.len(), 2); + assert_eq!(host_of(rows[0], 0), "a"); + assert_eq!(host_of(rows[0], 1), "1.5"); + assert_eq!(host_of(rows[0], 2), "1000"); + assert_eq!(host_of(rows[1], 0), "z"); + assert_eq!(host_of(rows[1], 1), ""); + } + assert_eq!( + feed_copy_in( + &client, + "COPY arrow_copy FROM STDIN WITH (FORMAT arrow)", + vec![Bytes::from(arrow_copy_payload(None, 0))] + ) + .await + .unwrap(), + 0 + ); + server.shutdown().await.unwrap(); +} + +/// A forged IPC length must be rejected before Arrow's LZ4 decoder can grow +/// an output Vec beyond that length. Exercise the actual COPY endpoint, not +/// just the reservation estimator, and verify failure leaves the session usable. +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn test_postgres_copy_in_arrow_understated_lz4_length() { + use arrow::array::{ArrayRef, Float64Array, StringArray, TimestampMillisecondArray}; + use arrow::ipc::writer::{IpcWriteOptions, StreamWriter}; + use arrow::record_batch::RecordBatch; + use bytes::Buf; + use std::sync::Arc; + + init_default_ut_logging(); + let (_guard, server) = setup_pg_server(StorageType::File, "pg_copy_arrow_lz4_bound").await; + let client = connect(server.bind_addr().unwrap().port()).await; + client + .simple_query( + "CREATE TABLE arrow_lz4 (host STRING PRIMARY KEY, val DOUBLE, ts TIMESTAMP TIME INDEX)", + ) + .await + .unwrap(); + let batch = RecordBatch::try_from_iter(vec![ + ( + "host", + Arc::new(StringArray::from(vec!["x".repeat(8 * 1024 * 1024)])) as ArrayRef, + ), + ("val", Arc::new(Float64Array::from(vec![1.5])) as ArrayRef), + ( + "ts", + Arc::new(TimestampMillisecondArray::from(vec![1000])) as ArrayRef, + ), + ]) + .unwrap(); + let options = IpcWriteOptions::default() + .try_with_compression(Some(arrow::ipc::CompressionType::LZ4_FRAME)) + .unwrap(); + let mut writer = + StreamWriter::try_new_with_options(Vec::new(), &batch.schema(), options).unwrap(); + writer.write(&batch).unwrap(); + writer.finish().unwrap(); + let mut payload = writer.into_inner().unwrap(); + assert!(payload.len() < 64 * 1024); + // StreamWriter emits modern IPC framing: continuation + metadata length. + let mut offset = 0; + let mut forged = false; + while offset < payload.len() { + let mut prefix = &payload[offset..]; + assert_eq!(prefix.get_i32_le(), -1); + let length = prefix.get_i32_le() as usize; + if length == 0 { + break; + } + let body_start = offset + 8 + length; + let message = arrow::ipc::root_as_message(&payload[offset + 8..body_start]).unwrap(); + let next = body_start + message.bodyLength() as usize; + if let Some(batch) = message.header_as_record_batch() { + for buffer in batch.buffers().unwrap() { + if buffer.length() < 8 { + continue; + } + let start = body_start + buffer.offset() as usize; + if (&payload[start..start + 8]).get_i64_le() >= 8 * 1024 * 1024 { + payload[start..start + 8].copy_from_slice(&1i64.to_le_bytes()); + forged = true; + break; + } + } + } + if forged { + break; + } + offset = next; + } + assert!(forged); + let error = feed_copy_in( + &client, + "COPY arrow_lz4 FROM STDIN WITH (FORMAT arrow)", + payload.chunks(1024).map(Bytes::copy_from_slice).collect(), + ) + .await + .unwrap_err(); + let error = error.as_db_error().unwrap(); + assert_eq!(error.code().code(), "22P04"); + assert!( + error + .message() + .contains("LZ4 output exceeds its declared length"), + "{error}" + ); + let messages = client + .simple_query("SELECT count(*) FROM arrow_lz4") + .await + .unwrap(); + let count = messages.iter().find_map(|message| match message { + tokio_postgres::SimpleQueryMessage::Row(row) => row.get(0), + _ => None, + }); + assert_eq!(count, Some("0")); + assert_eq!( + feed_copy_in( + &client, + "COPY arrow_lz4 FROM STDIN WITH (FORMAT arrow)", + vec![Bytes::from(arrow_copy_payload( + Some(arrow::ipc::CompressionType::LZ4_FRAME), + 1 + ))] + ) + .await + .unwrap(), + 2 + ); + server.shutdown().await.unwrap(); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn test_postgres_copy_in_arrow_partitioned() { + init_default_ut_logging(); + let instance = crate::tests::create_distributed_instance("pg_copy_arrow_partitioned").await; + let server = + crate::test_util::setup_pg_server_for_frontend_instance(instance.frontend(), None).await; + let client = connect(server.bind_addr().unwrap().port()).await; + client.simple_query( + "CREATE TABLE arrow_partitioned (host STRING PRIMARY KEY, val DOUBLE, ts TIMESTAMP TIME INDEX) \ + PARTITION ON COLUMNS (host) (host < 'm', host >= 'm')" + ).await.unwrap(); + assert_eq!( + feed_copy_in( + &client, + "COPY arrow_partitioned FROM STDIN WITH (FORMAT arrow)", + vec![Bytes::from(arrow_copy_payload( + Some(arrow::ipc::CompressionType::ZSTD), + 1 + ))] + ) + .await + .unwrap(), + 2 + ); + let messages = client + .simple_query("SELECT host FROM arrow_partitioned ORDER BY host") + .await + .unwrap(); + let hosts: Vec<_> = messages + .iter() + .filter_map(|m| match m { + tokio_postgres::SimpleQueryMessage::Row(row) => row.get(0), + _ => None, + }) + .collect(); + assert_eq!(hosts, vec!["a", "z"]); + server.shutdown().await.unwrap(); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn test_postgres_copy_in_arrow_skip_wal() { + use crate::test_util::{ + MockInstanceImpl, assert_wal_delta, setup_pg_server_for_frontend_instance, + }; + + init_default_ut_logging(); + for (distributed, partitioned) in [(false, false), (false, true), (true, false), (true, true)] { + let mut db = + MockInstanceImpl::new(&format!("pg_copy_arrow_wal_{partitioned}"), distributed).await; + let server = setup_pg_server_for_frontend_instance(db.frontend(), None).await; + let client = connect(server.bind_addr().unwrap().port()).await; + let partition = if partitioned { + " PARTITION ON COLUMNS (host) (host < 'm', host >= 'm')" + } else { + "" + }; + client.simple_query(&format!( + "CREATE TABLE arrow_wal (host STRING PRIMARY KEY, val DOUBLE, ts TIMESTAMP TIME INDEX){partition}" + )).await.unwrap(); + let mut before = db.flush_and_snapshot_wal().await; + assert_eq!(before.len(), if partitioned { 2 } else { 1 }); + for hint in [None, Some(true), Some(false), None] { + let option = hint + .map(|value| format!(", insert_skip_wal {value}")) + .unwrap_or_default(); + assert_eq!( + feed_copy_in( + &client, + &format!("COPY arrow_wal FROM STDIN WITH (FORMAT arrow{option})"), + vec![Bytes::from(arrow_copy_payload(None, 2))] + ) + .await + .unwrap(), + 4 + ); + let after = db.flush_and_snapshot_wal().await; + assert_wal_delta(&before, &after, hint == Some(true)); + for (id, &(flushed_sequence, _)) in &after { + assert!( + flushed_sequence > before[id].0, + "region {id:?} received no rows" + ); + } + before = after; + } + server.shutdown().await.unwrap(); + db.shutdown().await; + } +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn test_postgres_copy_in_arrow_schema_evolution() { + init_default_ut_logging(); + let (_guard, server) = setup_pg_server(StorageType::File, "pg_copy_arrow_schema").await; + let client = connect(server.bind_addr().unwrap().port()).await; + client + .simple_query( + "CREATE TABLE arrow_schema (host STRING PRIMARY KEY, ts TIMESTAMP TIME INDEX)", + ) + .await + .unwrap(); + let payload = arrow_copy_payload(None, 1); + let error = feed_copy_in( + &client, + "COPY arrow_schema FROM STDIN WITH (FORMAT arrow, auto_create_table false)", + vec![Bytes::from(payload.clone())], + ) + .await + .unwrap_err(); + assert!(error.as_db_error().is_some()); + // Request-local hints must not disable schema evolution on the next COPY. + assert_eq!(feed_copy_in(&client, + "COPY arrow_schema FROM STDIN WITH (FORMAT arrow, auto_create_table true, insert_skip_wal false)", + vec![Bytes::from(payload)]).await.unwrap(), 2); + let messages = client + .simple_query("SELECT val FROM arrow_schema ORDER BY ts") + .await + .unwrap(); + let row = messages + .iter() + .find(|m| matches!(m, tokio_postgres::SimpleQueryMessage::Row(_))) + .unwrap(); + assert_eq!(host_of(row, 0), "1.5"); + server.shutdown().await.unwrap(); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn test_postgres_copy_in_arrow_errors_and_recovery() { + init_default_ut_logging(); + let (_guard, server) = setup_pg_server(StorageType::File, "pg_copy_arrow_errors").await; + let client = connect(server.bind_addr().unwrap().port()).await; + client.simple_query("CREATE TABLE arrow_errors (host STRING PRIMARY KEY, val DOUBLE, ts TIMESTAMP TIME INDEX)").await.unwrap(); + for sql in [ + "COPY FROM STDIN WITH (FORMAT arrow)", + "COPY arrow_errors (host, ts) FROM STDIN WITH (FORMAT arrow)", + "COPY missing_table FROM STDIN WITH (FORMAT arrow)", + "COPY arrow_errors FROM STDIN WITH (FORMAT arrow, pipeline_name 'p')", + ] { + let error = client.simple_query(sql).await.unwrap_err(); + assert!(error.as_db_error().is_some(), "{sql}: {error}"); + } + let payload = arrow_copy_payload(None, 1); + for bytes in [ + Vec::new(), + b"not arrow".to_vec(), + payload[..payload.len() - 10].to_vec(), + ] { + assert!( + feed_copy_in( + &client, + "COPY arrow_errors FROM STDIN WITH (FORMAT arrow)", + vec![Bytes::from(bytes)] + ) + .await + .is_err() + ); + assert!(!client.simple_query("SELECT 1").await.unwrap().is_empty()); + } + // Earlier complete batches are not rolled back when a later frame is bad. + let mut bad_tail = payload[..payload.len() - 8].to_vec(); + bad_tail.extend_from_slice(&[255, 255, 255, 255, 1]); + assert!( + feed_copy_in( + &client, + "COPY arrow_errors FROM STDIN WITH (FORMAT arrow)", + vec![Bytes::from(bad_tail)] + ) + .await + .is_err() + ); + let messages = client + .simple_query("SELECT count(*) FROM arrow_errors") + .await + .unwrap(); + let row = messages + .iter() + .find(|m| matches!(m, tokio_postgres::SimpleQueryMessage::Row(_))) + .unwrap(); + assert_eq!(host_of(row, 0), "2"); + assert_eq!( + feed_copy_in( + &client, + "COPY arrow_errors FROM STDIN WITH (FORMAT arrow)", + vec![Bytes::from(payload)] + ) + .await + .unwrap(), + 2 + ); + server.shutdown().await.unwrap(); +} + fn host_of(message: &tokio_postgres::SimpleQueryMessage, column: usize) -> String { let tokio_postgres::SimpleQueryMessage::Row(row) = message else { panic!("expected row, got {message:?}"); @@ -2112,6 +2503,110 @@ async fn test_postgres_copy_in_prom_write_held_body_quota() { server.shutdown().await.unwrap(); } +/// Existing table-less formats enforce the same receive budget as Prometheus. +/// An oversized body is rejected before either format's decoder runs. +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn test_postgres_copy_in_buffered_receive_quota() { + let server = quota_test_server( + "pg_copy_buffered_receive_quota", + common_memory_manager::OnExhaustedPolicy::Fail, + ) + .await; + let client = connect(server.bind_addr().unwrap().port()).await; + for format in ["influxdb", "otlp"] { + let error = feed_copy_in( + &client, + &format!("COPY FROM STDIN WITH (FORMAT {format})"), + vec![Bytes::from(vec![b'x'; 65 * 1024])], + ) + .await + .unwrap_err(); + assert!( + error + .as_db_error() + .unwrap() + .message() + .to_lowercase() + .contains("memory") + ); + assert!(!client.simple_query("SELECT 1").await.unwrap().is_empty()); + } + server.shutdown().await.unwrap(); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn test_postgres_copy_in_otlp_held_body_quota() { + use std::time::Duration; + + use otel_arrow_rust::proto::opentelemetry::collector::metrics::v1::ExportMetricsServiceRequest; + use otel_arrow_rust::proto::opentelemetry::common::v1::{AnyValue, KeyValue, any_value}; + use otel_arrow_rust::proto::opentelemetry::metrics::v1::{ + Exemplar, Gauge, Metric, NumberDataPoint, ResourceMetrics, ScopeMetrics, exemplar, metric, + number_data_point, + }; + use prost::Message; + + init_default_ut_logging(); + let server = quota_test_server( + "pg_copy_in_otlp_held_body", + common_memory_manager::OnExhaustedPolicy::Wait { + timeout: Duration::from_secs(30), + }, + ) + .await; + let client = connect(server.bind_addr().unwrap().port()).await; + let request = ExportMetricsServiceRequest { + resource_metrics: vec![ResourceMetrics { + scope_metrics: vec![ScopeMetrics { + metrics: vec![Metric { + name: "copy_otlp_held_body".into(), + data: Some(metric::Data::Gauge(Gauge { + data_points: vec![NumberDataPoint { + time_unix_nano: 1_700_000_000_000_000_000, + value: Some(number_data_point::Value::AsDouble(1.0)), + attributes: vec![KeyValue { + key: "host".into(), + value: Some(AnyValue { + value: Some(any_value::Value::StringValue( + "x".repeat(13 * 1024), + )), + }), + }], + exemplars: vec![Exemplar { + time_unix_nano: 1_700_000_000_000_000_000, + value: Some(exemplar::Value::AsDouble(1.0)), + ..Default::default() + }], + ..Default::default() + }], + })), + ..Default::default() + }], + ..Default::default() + }], + ..Default::default() + }], + }; + let body = request.encode_to_vec(); + let conversion = servers::otlp::metrics::to_grpc_insert_requests( + request, + &mut session::protocol_ctx::OtlpMetricCtx { + with_metric_engine: true, + ..Default::default() + }, + ) + .unwrap(); + assert_eq!(conversion.exemplars.len(), 1); + let expansion = + servers::exemplar::estimated_row_bytes([conversion.exemplars.as_slice()]).unwrap(); + assert!(body.len() < 64 * 1024); + assert!(expansion < 64 * 1024); + assert!(body.len() + expansion > 64 * 1024); + + assert_copy_rejects_held_body(&client, "COPY FROM STDIN WITH (FORMAT otlp)", body).await; + server.shutdown().await.unwrap(); +} + async fn assert_copy_rejects_held_body(client: &tokio_postgres::Client, sql: &str, body: Vec) { let error = tokio::time::timeout( std::time::Duration::from_secs(5), diff --git a/tests-integration/tests/http.rs b/tests-integration/tests/http.rs index 950feb8a6ca..f044e91cc09 100644 --- a/tests-integration/tests/http.rs +++ b/tests-integration/tests/http.rs @@ -3418,6 +3418,7 @@ providers = []"#, r#" enable_telemetry = true auto_create_table = true +auto_create_physical_table_timestamp_unit = "Millisecond" max_in_flight_write_bytes = "0KiB" write_bytes_exhausted_policy = "wait" init_regions_in_background = false diff --git a/tests/cases/standalone/common/drop/drop_database_logical_tables.result b/tests/cases/standalone/common/drop/drop_database_logical_tables.result new file mode 100644 index 00000000000..a6920679e4d --- /dev/null +++ b/tests/cases/standalone/common/drop/drop_database_logical_tables.result @@ -0,0 +1,126 @@ +CREATE DATABASE drop_database_logical_tables; + +Affected Rows: 1 + +USE drop_database_logical_tables; + +Affected Rows: 0 + +CREATE TABLE physical (ts TIMESTAMP TIME INDEX, val DOUBLE) +ENGINE=metric WITH ("physical_metric_table" = ""); + +Affected Rows: 0 + +CREATE TABLE logical_a (ts TIMESTAMP TIME INDEX, val DOUBLE, host STRING PRIMARY KEY) +ENGINE=metric WITH ("on_physical_table" = "physical"); + +Affected Rows: 0 + +CREATE TABLE logical_b (ts TIMESTAMP TIME INDEX, val DOUBLE, host STRING PRIMARY KEY) +ENGINE=metric WITH ("on_physical_table" = "physical"); + +Affected Rows: 0 + +CREATE TABLE ordinary (ts TIMESTAMP TIME INDEX, val DOUBLE); + +Affected Rows: 0 + +CREATE VIEW logical_view AS SELECT * FROM logical_a; + +Affected Rows: 0 + +INSERT INTO logical_a (ts, val, host) VALUES (0, 1, 'a'); + +Affected Rows: 1 + +INSERT INTO logical_b (ts, val, host) VALUES (0, 2, 'b'); + +Affected Rows: 1 + +SELECT * FROM logical_view; + ++------+---------------------+-----+ +| host | ts | val | ++------+---------------------+-----+ +| a | 1970-01-01T00:00:00 | 1.0 | ++------+---------------------+-----+ + +SHOW TABLES; + ++----------------------------------------+ +| Tables_in_drop_database_logical_tables | ++----------------------------------------+ +| logical_a | +| logical_b | +| logical_view | +| ordinary | +| physical | ++----------------------------------------+ + +USE public; + +Affected Rows: 0 + +DROP DATABASE drop_database_logical_tables; + +Affected Rows: 0 + +SHOW TABLES FROM drop_database_logical_tables; + ++----------------------------------------+ +| Tables_in_drop_database_logical_tables | ++----------------------------------------+ ++----------------------------------------+ + +-- Reusing names must not retain the dropped tables or their rows. +CREATE DATABASE drop_database_logical_tables; + +Affected Rows: 1 + +USE drop_database_logical_tables; + +Affected Rows: 0 + +CREATE TABLE physical (ts TIMESTAMP TIME INDEX, val DOUBLE) +ENGINE=metric WITH ("physical_metric_table" = ""); + +Affected Rows: 0 + +CREATE TABLE logical_a (ts TIMESTAMP TIME INDEX, val DOUBLE, host STRING PRIMARY KEY) +ENGINE=metric WITH ("on_physical_table" = "physical"); + +Affected Rows: 0 + +SELECT COUNT(*) FROM logical_a; + ++----------+ +| count(*) | ++----------+ +| 0 | ++----------+ + +INSERT INTO logical_a (ts, val, host) VALUES (0, 7, 'new'); + +Affected Rows: 1 + +-- SQLNESS ARG restart=true +SELECT * FROM logical_a; + ++------+---------------------+-----+ +| host | ts | val | ++------+---------------------+-----+ +| new | 1970-01-01T00:00:00 | 7.0 | ++------+---------------------+-----+ + +USE public; + +Affected Rows: 0 + +DROP DATABASE drop_database_logical_tables; + +Affected Rows: 0 + +DROP DATABASE IF EXISTS drop_database_logical_tables; + +Affected Rows: 0 + diff --git a/tests/cases/standalone/common/drop/drop_database_logical_tables.sql b/tests/cases/standalone/common/drop/drop_database_logical_tables.sql new file mode 100644 index 00000000000..753a34a251d --- /dev/null +++ b/tests/cases/standalone/common/drop/drop_database_logical_tables.sql @@ -0,0 +1,37 @@ +CREATE DATABASE drop_database_logical_tables; +USE drop_database_logical_tables; + +CREATE TABLE physical (ts TIMESTAMP TIME INDEX, val DOUBLE) +ENGINE=metric WITH ("physical_metric_table" = ""); +CREATE TABLE logical_a (ts TIMESTAMP TIME INDEX, val DOUBLE, host STRING PRIMARY KEY) +ENGINE=metric WITH ("on_physical_table" = "physical"); +CREATE TABLE logical_b (ts TIMESTAMP TIME INDEX, val DOUBLE, host STRING PRIMARY KEY) +ENGINE=metric WITH ("on_physical_table" = "physical"); +CREATE TABLE ordinary (ts TIMESTAMP TIME INDEX, val DOUBLE); +CREATE VIEW logical_view AS SELECT * FROM logical_a; + +INSERT INTO logical_a (ts, val, host) VALUES (0, 1, 'a'); +INSERT INTO logical_b (ts, val, host) VALUES (0, 2, 'b'); +SELECT * FROM logical_view; +SHOW TABLES; + +USE public; +DROP DATABASE drop_database_logical_tables; +SHOW TABLES FROM drop_database_logical_tables; + +-- Reusing names must not retain the dropped tables or their rows. +CREATE DATABASE drop_database_logical_tables; +USE drop_database_logical_tables; +CREATE TABLE physical (ts TIMESTAMP TIME INDEX, val DOUBLE) +ENGINE=metric WITH ("physical_metric_table" = ""); +CREATE TABLE logical_a (ts TIMESTAMP TIME INDEX, val DOUBLE, host STRING PRIMARY KEY) +ENGINE=metric WITH ("on_physical_table" = "physical"); +SELECT COUNT(*) FROM logical_a; +INSERT INTO logical_a (ts, val, host) VALUES (0, 7, 'new'); + +-- SQLNESS ARG restart=true +SELECT * FROM logical_a; + +USE public; +DROP DATABASE drop_database_logical_tables; +DROP DATABASE IF EXISTS drop_database_logical_tables; diff --git a/tests/compatibility/README.md b/tests/compatibility/README.md index 0dfcba20215..47f80bafc76 100644 --- a/tests/compatibility/README.md +++ b/tests/compatibility/README.md @@ -15,6 +15,18 @@ read-preference defaulting and unrelated metadata preservation: cargo nextest run -p session -E 'test(test_legacy_query_context_wire_defaults_to_leader)' ``` +The same legacy fixture also checks that logical ALTER requests without pinned +table IDs retain their original behavior, and that new pinned IDs survive the +query-context protobuf conversion: + +```shell +cargo nextest run -p common-meta -E 'test(test_pinned_logical_table_ids_wire_compatibility)' +``` + +The ID guard requires an updated metasrv; older metasrvs ignore the new internal +extension. Update metasrv before enabling exemplar source-schema reconciliation +on frontends. No procedure-state or protobuf fields are added. + The [native histogram Remote Read fixture](wire/native_histogram_remote_read/README.md) checks the sampled encoder against independent Prometheus protobuf values, including exact integer counts, custom bounds, and NaN payloads: @@ -23,6 +35,14 @@ including exact integer counts, custom bounds, and NaN payloads: cargo nextest run -p servers -E 'test(native_histogram_remote_read_wire_fixture)' ``` +The [legacy region lease fixture](wire/candidate_lease_id/README.md) checks that a +lease without a candidate lease id decodes as such and encodes to the same bytes +as before the field existed: + +```shell +cargo nextest run -p store-api -E 'test(test_legacy_granted_region_wire)' +``` + ## Object store WAL fixtures Frozen objects of the object store WAL are checked byte for byte by the format tests of diff --git a/tests/compatibility/wire/candidate_lease_id/README.md b/tests/compatibility/wire/candidate_lease_id/README.md new file mode 100644 index 00000000000..6d8253afffc --- /dev/null +++ b/tests/compatibility/wire/candidate_lease_id/README.md @@ -0,0 +1,36 @@ +# Legacy region lease wire compatibility + +`legacy_granted_region.pb` is a generated legacy-shaped protobuf fixture, not a +capture from a released binary. It uses the `greptime.v1.meta.GrantedRegion` +schema at greptime-proto revision +`5870f5adc4d601173e742888e7db2032a690b583`, which has no `candidate_lease_id`. + +Logical contents: + +- Region `4398046511105` (table `1024`, region number `1`), role `Follower`. +- Unrelated extension `plugin = "payload"`. + +SHA-256: `9b0c4796ce8c5094a0336c1febb00e3bef62c9deb4b8a04eccc26f28ea265ec0`. + +Run the regression: + +```shell +cargo nextest run -p store-api -E 'test(test_legacy_granted_region_wire)' +``` + +The test checks that the legacy bytes decode to a lease without a candidate +lease id, and that such a lease encodes back to exactly the legacy bytes, so a +release without the field reads it unchanged. + +## Reproduce the fixture + +With `PROTO_ROOT` pointing to the `proto` directory of the revision above: + +```shell +printf '%s\n' \ + 'region_id: 4398046511105' \ + 'role: Follower' \ + 'extensions { key: "plugin" value: "payload" }' | + protoc --proto_path="$PROTO_ROOT" --encode=greptime.v1.meta.GrantedRegion \ + greptime/v1/meta/heartbeat.proto > legacy_granted_region.pb +``` diff --git a/tests/compatibility/wire/candidate_lease_id/legacy_granted_region.pb b/tests/compatibility/wire/candidate_lease_id/legacy_granted_region.pb new file mode 100644 index 00000000000..bc4d199252e --- /dev/null +++ b/tests/compatibility/wire/candidate_lease_id/legacy_granted_region.pb @@ -0,0 +1,2 @@ +�€€€€€š +pluginpayload \ No newline at end of file