mirror of
https://github.com/GreptimeTeam/greptimedb.git
synced 2026-11-28 05:34:02 +00:00
fix(recordbatch,datanode,client,flow): state a watermark's own slice and its creators
An incremental read proves a region's watermark, but the proof travels without the two facts that make it usable: which partition expression the region was opened under, and which regions' files the region could see at that moment. Both are known when the scan opens the version that yields the watermark, and both are lost afterwards: the entry carried `partition_expr: None` unconditionally, the client projected the entries onto `region -> sequence`, and the flow sample kept only that projection. Carry the expression identity and the visible foreign creators alongside the watermark from the same version snapshot. `None` means unknown, never "none": a caller that has to decide whether a round may advance cannot read an absent answer as a negative one. Keep the region-wide entry and its slices apart, and keep "read without a proved watermark" apart from "never read".
This commit is contained in:
+286
-3
@@ -12,7 +12,8 @@
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::collections::btree_map::Entry;
|
||||
use std::collections::{BTreeMap, HashMap};
|
||||
use std::pin::Pin;
|
||||
use std::str::FromStr;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
@@ -45,7 +46,7 @@ use common_grpc::flight::{
|
||||
FLOW_EXTENSIONS_METADATA_KEY, FlightDecoder, FlightMessage, SNAPSHOT_SEQS_METADATA_KEY,
|
||||
};
|
||||
use common_query::Output;
|
||||
use common_recordbatch::adapter::RecordBatchMetrics;
|
||||
use common_recordbatch::adapter::{RecordBatchMetrics, RegionWatermarkEntry};
|
||||
use common_recordbatch::error::ExternalSnafu;
|
||||
use common_recordbatch::{OrderOption, RecordBatch, RecordBatchStream, RecordBatchStreamWrapper};
|
||||
use common_telemetry::tracing::Span;
|
||||
@@ -179,6 +180,48 @@ impl OutputMetrics {
|
||||
self.inner.metrics.read().unwrap().clone()
|
||||
}
|
||||
|
||||
/// Returns the `(region, partition expression, watermark)` statements of the terminal
|
||||
/// metrics, one per slice, ordered by region id and then by expression.
|
||||
///
|
||||
/// This is the form a caller that owns per-slice cursors consumes: `partition_expr` is the
|
||||
/// identity a cursor entry is keyed by (`None` = the region's complete value domain), and
|
||||
/// `watermark` is the sequence the read proved for that slice, or `None` when the slice
|
||||
/// participated without a proof. A slice is never projected onto its region here, and an
|
||||
/// unproved slice stays in place rather than disappearing.
|
||||
///
|
||||
/// Statements about the **same** slice are merged with the rule the query's own merge uses
|
||||
/// (`query::metrics`): equal proofs converge, and a differing proof is a conflict that
|
||||
/// degrades the slice to unproved. Nothing takes the `min`/`max` of two proofs.
|
||||
///
|
||||
/// Each entry also carries `visible_foreign_file_creators`: the creators of the files the
|
||||
/// region had visible when the read opened it (`Some(vec![])` = it held none of another
|
||||
/// region's files, `None` = the read stated none). Two statements of the same slice that name
|
||||
/// different file sets are merged to `None` as well: they saw different file lists, so neither
|
||||
/// set is the one the slice was read under.
|
||||
///
|
||||
/// Note that `partition_expr: None` is a positive statement - the region has no partition
|
||||
/// expression, so its value domain is the whole domain - and not "unknown": see the upgrade
|
||||
/// note on the datanode's region watermark reporting for what mixing builds means.
|
||||
pub fn region_watermark_entries(&self) -> Option<Vec<RegionWatermarkEntry>> {
|
||||
let mut slices = BTreeMap::<(u64, Option<String>), RegionWatermarkEntry>::new();
|
||||
for entry in self.get()?.region_watermarks {
|
||||
match slices.entry((entry.region_id, entry.partition_expr.clone())) {
|
||||
Entry::Occupied(mut occupied) => {
|
||||
let merged = occupied.get_mut();
|
||||
merged.watermark = merge_watermark_proof(merged.watermark, entry.watermark);
|
||||
merged.visible_foreign_file_creators = merge_visible_file_creators(
|
||||
merged.visible_foreign_file_creators.take(),
|
||||
entry.visible_foreign_file_creators,
|
||||
);
|
||||
}
|
||||
Entry::Vacant(vacant) => {
|
||||
vacant.insert(entry);
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(slices.into_values().collect())
|
||||
}
|
||||
|
||||
/// Returns proved per-region watermarks.
|
||||
///
|
||||
/// The terminal metrics state one entry per `(region, partition expression)`. A
|
||||
@@ -187,9 +230,12 @@ impl OutputMetrics {
|
||||
/// (that entry represents a participating domain whose terminal sequence bound was not
|
||||
/// provable) and otherwise reports the *minimum* over its entries. With the region-wide
|
||||
/// entries a pre-expression producer writes, that minimum is exactly its one value.
|
||||
///
|
||||
/// This is a convenience projection of [`Self::region_watermark_entries`]: a consumer that
|
||||
/// owns per-slice cursors reads the triples instead of losing the expression dimension here.
|
||||
pub fn region_watermark_map(&self) -> Option<std::collections::HashMap<u64, u64>> {
|
||||
let mut regions: std::collections::HashMap<u64, Option<u64>> = Default::default();
|
||||
for entry in self.get()?.region_watermarks {
|
||||
for entry in self.region_watermark_entries()? {
|
||||
let slot = regions.entry(entry.region_id).or_insert(entry.watermark);
|
||||
*slot = match (*slot, entry.watermark) {
|
||||
(Some(current), Some(seq)) => Some(current.min(seq)),
|
||||
@@ -248,6 +294,13 @@ impl OutputWithMetrics {
|
||||
self.metrics.region_watermark_map()
|
||||
}
|
||||
|
||||
/// Returns the terminal metrics' `(region, partition expression, watermark)` statements.
|
||||
///
|
||||
/// See [`OutputMetrics::region_watermark_entries`].
|
||||
pub fn region_watermark_entries(&self) -> Option<Vec<RegionWatermarkEntry>> {
|
||||
self.metrics.region_watermark_entries()
|
||||
}
|
||||
|
||||
/// Returns all regions participating in terminal metric collection.
|
||||
pub fn participating_regions(&self) -> Option<std::collections::BTreeSet<u64>> {
|
||||
self.metrics.participating_regions()
|
||||
@@ -259,6 +312,40 @@ impl OutputWithMetrics {
|
||||
}
|
||||
}
|
||||
|
||||
/// Merges two proofs of the **same** `(region, partition expression)` slice.
|
||||
///
|
||||
/// Equal proofs converge. Anything else - one side unproved, or two different sequences - is a
|
||||
/// slice whose bound is not provable, so the result is `None`. In particular this is not
|
||||
/// `min`/`max`: taking either would advance a cursor to a sequence one of the statements never
|
||||
/// proved.
|
||||
fn merge_watermark_proof(current: Option<u64>, incoming: Option<u64>) -> Option<u64> {
|
||||
match (current, incoming) {
|
||||
(Some(current), Some(incoming)) if current == incoming => Some(current),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Merges two statements about the files the same `(region, partition expression)` slice had
|
||||
/// visible when it was opened.
|
||||
///
|
||||
/// A statement that names no set adds no information and leaves a named set in place. Two
|
||||
/// statements that name different sets describe file lists that were not the same, so the merged
|
||||
/// answer is unknown rather than either of them: taking one would hide the regions whose rows the
|
||||
/// other set's files hold.
|
||||
fn merge_visible_file_creators(
|
||||
current: Option<Vec<u64>>,
|
||||
incoming: Option<Vec<u64>>,
|
||||
) -> Option<Vec<u64>> {
|
||||
let Some(incoming) = incoming else {
|
||||
return current;
|
||||
};
|
||||
match current {
|
||||
None => Some(incoming),
|
||||
Some(current) if current == incoming => Some(current),
|
||||
Some(_) => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_terminal_metrics(metrics_json: &str) -> Result<RecordBatchMetrics> {
|
||||
serde_json::from_str(metrics_json).map_err(|e| {
|
||||
IllegalFlightMessagesSnafu {
|
||||
@@ -1150,6 +1237,7 @@ mod tests {
|
||||
region_id: 7,
|
||||
partition_expr: None,
|
||||
watermark: Some(seq),
|
||||
visible_foreign_file_creators: None,
|
||||
}],
|
||||
..Default::default()
|
||||
})
|
||||
@@ -1382,6 +1470,7 @@ mod tests {
|
||||
region_id: 7,
|
||||
partition_expr: None,
|
||||
watermark: Some(42),
|
||||
visible_foreign_file_creators: None,
|
||||
}],
|
||||
..Default::default()
|
||||
},
|
||||
@@ -1723,28 +1812,33 @@ mod tests {
|
||||
region_id: 1,
|
||||
partition_expr: Some("k0 < 10".to_string()),
|
||||
watermark: Some(9),
|
||||
visible_foreign_file_creators: None,
|
||||
},
|
||||
RegionWatermarkEntry {
|
||||
region_id: 1,
|
||||
partition_expr: Some("k0 >= 10".to_string()),
|
||||
watermark: Some(4),
|
||||
visible_foreign_file_creators: None,
|
||||
},
|
||||
// One unproved expression omits the whole region.
|
||||
RegionWatermarkEntry {
|
||||
region_id: 2,
|
||||
partition_expr: Some("k0 < 10".to_string()),
|
||||
watermark: Some(7),
|
||||
visible_foreign_file_creators: None,
|
||||
},
|
||||
RegionWatermarkEntry {
|
||||
region_id: 2,
|
||||
partition_expr: Some("k0 >= 10".to_string()),
|
||||
watermark: None,
|
||||
visible_foreign_file_creators: None,
|
||||
},
|
||||
// A region-wide entry keeps its single value.
|
||||
RegionWatermarkEntry {
|
||||
region_id: 3,
|
||||
partition_expr: None,
|
||||
watermark: Some(5),
|
||||
visible_foreign_file_creators: None,
|
||||
},
|
||||
],
|
||||
..Default::default()
|
||||
@@ -1763,6 +1857,195 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_region_watermark_entries_keep_every_slice_of_a_region() {
|
||||
let metrics = OutputMetrics::default();
|
||||
metrics.update(Some(RecordBatchMetrics {
|
||||
region_watermarks: vec![
|
||||
RegionWatermarkEntry {
|
||||
region_id: 1,
|
||||
partition_expr: Some("k0 >= 10".to_string()),
|
||||
watermark: Some(4),
|
||||
visible_foreign_file_creators: Some(Vec::new()),
|
||||
},
|
||||
RegionWatermarkEntry {
|
||||
region_id: 1,
|
||||
partition_expr: Some("k0 < 10".to_string()),
|
||||
watermark: Some(9),
|
||||
visible_foreign_file_creators: Some(Vec::new()),
|
||||
},
|
||||
// A region without a partition expression states its whole domain, and the
|
||||
// creator of the one foreign file it holds.
|
||||
RegionWatermarkEntry {
|
||||
region_id: 3,
|
||||
partition_expr: None,
|
||||
watermark: Some(5),
|
||||
visible_foreign_file_creators: Some(vec![7]),
|
||||
},
|
||||
// Read, but not proved for this slice.
|
||||
RegionWatermarkEntry {
|
||||
region_id: 2,
|
||||
partition_expr: Some("k0 < 10".to_string()),
|
||||
watermark: None,
|
||||
visible_foreign_file_creators: Some(Vec::new()),
|
||||
},
|
||||
],
|
||||
..Default::default()
|
||||
}));
|
||||
|
||||
assert_eq!(
|
||||
metrics.region_watermark_entries(),
|
||||
Some(vec![
|
||||
RegionWatermarkEntry {
|
||||
region_id: 1,
|
||||
partition_expr: Some("k0 < 10".to_string()),
|
||||
watermark: Some(9),
|
||||
visible_foreign_file_creators: Some(Vec::new()),
|
||||
},
|
||||
RegionWatermarkEntry {
|
||||
region_id: 1,
|
||||
partition_expr: Some("k0 >= 10".to_string()),
|
||||
watermark: Some(4),
|
||||
visible_foreign_file_creators: Some(Vec::new()),
|
||||
},
|
||||
RegionWatermarkEntry {
|
||||
region_id: 2,
|
||||
partition_expr: Some("k0 < 10".to_string()),
|
||||
watermark: None,
|
||||
visible_foreign_file_creators: Some(Vec::new()),
|
||||
},
|
||||
RegionWatermarkEntry {
|
||||
region_id: 3,
|
||||
partition_expr: None,
|
||||
watermark: Some(5),
|
||||
visible_foreign_file_creators: Some(vec![7]),
|
||||
},
|
||||
]),
|
||||
"the statements reach the caller with the expression and file-creator dimensions intact"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_region_watermark_entries_degrade_differing_file_creator_sets_to_unknown() {
|
||||
let metrics = OutputMetrics::default();
|
||||
metrics.update(Some(RecordBatchMetrics {
|
||||
region_watermarks: vec![
|
||||
// One slice, two statements that saw different file lists: unknown, not either.
|
||||
RegionWatermarkEntry {
|
||||
region_id: 1,
|
||||
partition_expr: None,
|
||||
watermark: Some(9),
|
||||
visible_foreign_file_creators: Some(vec![7]),
|
||||
},
|
||||
RegionWatermarkEntry {
|
||||
region_id: 1,
|
||||
partition_expr: None,
|
||||
watermark: Some(9),
|
||||
visible_foreign_file_creators: Some(vec![8]),
|
||||
},
|
||||
// A statement that names no set adds nothing to one that names it.
|
||||
RegionWatermarkEntry {
|
||||
region_id: 2,
|
||||
partition_expr: None,
|
||||
watermark: Some(4),
|
||||
visible_foreign_file_creators: Some(vec![7]),
|
||||
},
|
||||
RegionWatermarkEntry {
|
||||
region_id: 2,
|
||||
partition_expr: None,
|
||||
watermark: Some(4),
|
||||
visible_foreign_file_creators: None,
|
||||
},
|
||||
],
|
||||
..Default::default()
|
||||
}));
|
||||
|
||||
assert_eq!(
|
||||
metrics.region_watermark_entries(),
|
||||
Some(vec![
|
||||
RegionWatermarkEntry {
|
||||
region_id: 1,
|
||||
partition_expr: None,
|
||||
watermark: Some(9),
|
||||
visible_foreign_file_creators: None,
|
||||
},
|
||||
RegionWatermarkEntry {
|
||||
region_id: 2,
|
||||
partition_expr: None,
|
||||
watermark: Some(4),
|
||||
visible_foreign_file_creators: Some(vec![7]),
|
||||
},
|
||||
])
|
||||
);
|
||||
assert_eq!(
|
||||
metrics.region_watermark_map(),
|
||||
Some(std::collections::HashMap::from([
|
||||
(1_u64, 9_u64),
|
||||
(2_u64, 4_u64)
|
||||
])),
|
||||
"the file creator set does not decide the region projection"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_region_watermark_entries_degrade_conflicting_proofs_to_unproved() {
|
||||
let metrics = OutputMetrics::default();
|
||||
metrics.update(Some(RecordBatchMetrics {
|
||||
region_watermarks: vec![
|
||||
// The same slice proved twice with different sequences: not min/max, unproved.
|
||||
RegionWatermarkEntry {
|
||||
region_id: 1,
|
||||
partition_expr: Some("k0 < 10".to_string()),
|
||||
watermark: Some(9),
|
||||
visible_foreign_file_creators: None,
|
||||
},
|
||||
RegionWatermarkEntry {
|
||||
region_id: 1,
|
||||
partition_expr: Some("k0 < 10".to_string()),
|
||||
watermark: Some(4),
|
||||
visible_foreign_file_creators: None,
|
||||
},
|
||||
// The same slice proved twice with the same sequence: still proved.
|
||||
RegionWatermarkEntry {
|
||||
region_id: 2,
|
||||
partition_expr: None,
|
||||
watermark: Some(7),
|
||||
visible_foreign_file_creators: None,
|
||||
},
|
||||
RegionWatermarkEntry {
|
||||
region_id: 2,
|
||||
partition_expr: None,
|
||||
watermark: Some(7),
|
||||
visible_foreign_file_creators: None,
|
||||
},
|
||||
],
|
||||
..Default::default()
|
||||
}));
|
||||
|
||||
assert_eq!(
|
||||
metrics.region_watermark_entries(),
|
||||
Some(vec![
|
||||
RegionWatermarkEntry {
|
||||
region_id: 1,
|
||||
partition_expr: Some("k0 < 10".to_string()),
|
||||
watermark: None,
|
||||
visible_foreign_file_creators: None,
|
||||
},
|
||||
RegionWatermarkEntry {
|
||||
region_id: 2,
|
||||
partition_expr: None,
|
||||
watermark: Some(7),
|
||||
visible_foreign_file_creators: None,
|
||||
},
|
||||
])
|
||||
);
|
||||
assert_eq!(
|
||||
metrics.region_watermark_map(),
|
||||
Some(std::collections::HashMap::from([(2_u64, 7_u64)])),
|
||||
"a conflicting slice keeps its region out of the region projection"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_output_metrics_distinguishes_empty_region_watermarks_from_absence() {
|
||||
let metrics = OutputMetrics::default();
|
||||
|
||||
@@ -865,6 +865,22 @@ pub struct RegionWatermarkEntry {
|
||||
pub partition_expr: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub watermark: Option<u64>,
|
||||
/// One sentence: **the creators of the files the region had visible when this read opened
|
||||
/// it**, i.e. the regions whose rows its own file list may hold, read from the same version
|
||||
/// snapshot as `partition_expr` and `watermark` and independent of what the read pruned.
|
||||
///
|
||||
/// The region itself is never listed: a file it wrote is its own rows, and a consumer that
|
||||
/// enumerates candidates adds the region on its own. Sorted, deduplicated.
|
||||
///
|
||||
/// - `Some(creators)` — possibly empty — states the set: `Some(vec![])` says every visible
|
||||
/// file was created by the region itself, which is a positive "nothing foreign" answer.
|
||||
/// - `None` (also: the field's absence in a payload an earlier build wrote) states **nothing**
|
||||
/// about the file list, and must be read as "unknown", not as "empty".
|
||||
///
|
||||
/// This is not [`RecordBatchMetrics::foreign_file_row_creators`]: that answers which creators
|
||||
/// the read *delivered rows* of, this answers which creators were *visible* before it started.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub visible_foreign_file_creators: Option<Vec<u64>>,
|
||||
}
|
||||
|
||||
/// Determines if a metric name represents a time measurement that should be formatted.
|
||||
@@ -2090,11 +2106,13 @@ mod test {
|
||||
region_id: 1,
|
||||
partition_expr: None,
|
||||
watermark: Some(100),
|
||||
visible_foreign_file_creators: None,
|
||||
},
|
||||
RegionWatermarkEntry {
|
||||
region_id: 2,
|
||||
partition_expr: None,
|
||||
watermark: None,
|
||||
visible_foreign_file_creators: None,
|
||||
},
|
||||
],
|
||||
..Default::default()
|
||||
@@ -2228,6 +2246,7 @@ mod test {
|
||||
region_id: 1,
|
||||
partition_expr: Some(r#"{"lhs":...}"#.to_string()),
|
||||
watermark: Some(100),
|
||||
visible_foreign_file_creators: None,
|
||||
}],
|
||||
..Default::default()
|
||||
};
|
||||
@@ -2255,6 +2274,56 @@ mod test {
|
||||
region_id: 3,
|
||||
partition_expr: None,
|
||||
watermark: None,
|
||||
visible_foreign_file_creators: None,
|
||||
}]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_region_watermark_entry_states_visible_file_creators_on_the_wire() {
|
||||
let metrics = RecordBatchMetrics {
|
||||
region_watermarks: vec![
|
||||
RegionWatermarkEntry {
|
||||
region_id: 1,
|
||||
partition_expr: None,
|
||||
watermark: Some(10),
|
||||
visible_foreign_file_creators: Some(vec![7, 9]),
|
||||
},
|
||||
// "Nothing foreign visible" is a positive answer and travels as an empty list.
|
||||
RegionWatermarkEntry {
|
||||
region_id: 2,
|
||||
partition_expr: None,
|
||||
watermark: Some(20),
|
||||
visible_foreign_file_creators: Some(Vec::new()),
|
||||
},
|
||||
],
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let value = serde_json::to_value(&metrics).unwrap();
|
||||
assert_eq!(
|
||||
value.get("region_watermarks").unwrap(),
|
||||
&json!([
|
||||
{ "region_id": 1, "watermark": 10, "visible_foreign_file_creators": [7, 9] },
|
||||
{ "region_id": 2, "watermark": 20, "visible_foreign_file_creators": [] }
|
||||
])
|
||||
);
|
||||
|
||||
let decoded: RecordBatchMetrics = serde_json::from_value(value).unwrap();
|
||||
assert_eq!(decoded.region_watermarks, metrics.region_watermarks);
|
||||
|
||||
// A statement written before the field existed states nothing about the region's files,
|
||||
// which reads back as unknown - never as "holds no foreign file".
|
||||
let mut legacy = serde_json::to_value(RecordBatchMetrics::default()).unwrap();
|
||||
legacy["region_watermarks"] = json!([{ "region_id": 3, "watermark": 5 }]);
|
||||
let decoded: RecordBatchMetrics = serde_json::from_value(legacy).unwrap();
|
||||
assert_eq!(
|
||||
decoded.region_watermarks,
|
||||
vec![RegionWatermarkEntry {
|
||||
region_id: 3,
|
||||
partition_expr: None,
|
||||
watermark: Some(5),
|
||||
visible_foreign_file_creators: None,
|
||||
}]
|
||||
);
|
||||
}
|
||||
|
||||
@@ -41,7 +41,7 @@ use common_error::status_code::StatusCode;
|
||||
use common_meta::datanode::TopicStatsReporter;
|
||||
use common_query::OutputData;
|
||||
use common_query::request::QueryRequest;
|
||||
use common_recordbatch::adapter::RecordBatchMetrics;
|
||||
use common_recordbatch::adapter::{RecordBatchMetrics, RegionWatermarkEntry};
|
||||
use common_recordbatch::{OrderOption, RecordBatch, RecordBatchStream, SendableRecordBatchStream};
|
||||
use common_runtime::{JoinHandle, Runtime};
|
||||
use common_telemetry::tracing::{self, info_span};
|
||||
@@ -74,6 +74,7 @@ use servers::grpc::flight::{
|
||||
use servers::grpc::region_server::RegionServerHandler;
|
||||
use session::context::{
|
||||
FLIGHT_METRICS_HEARTBEAT_INTERVAL, QueryContext, QueryContextBuilder, QueryContextRef,
|
||||
ScanPartitionExpr, ScanVisibleFileCreators,
|
||||
};
|
||||
use snafu::{IntoError, OptionExt, ResultExt, ensure};
|
||||
use store_api::metric_engine_consts::{
|
||||
@@ -1010,56 +1011,135 @@ fn wrap_flow_region_watermark_stream(
|
||||
region_id: RegionId,
|
||||
query_ctx: &QueryContextRef,
|
||||
) -> SendableRecordBatchStream {
|
||||
if should_collect_region_watermark_from_extensions(&query_ctx.extensions())
|
||||
&& let Some(seq) = query_ctx.get_snapshot(region_id.as_u64())
|
||||
{
|
||||
Box::pin(RegionWatermarkStream::new(stream, region_id, seq)) as SendableRecordBatchStream
|
||||
} else {
|
||||
stream
|
||||
if !should_collect_region_watermark_from_extensions(&query_ctx.extensions()) {
|
||||
return stream;
|
||||
}
|
||||
let Some(seq) = query_ctx.get_snapshot(region_id.as_u64()) else {
|
||||
return stream;
|
||||
};
|
||||
|
||||
// The expression is the one this region's scan stated, and the scan stated it from the very
|
||||
// version it read `seq` from (see [`RegionWatermarkStatement`]). A region whose scans stated
|
||||
// no identity - or two different ones - participates without a proof: `partition_expr: None`
|
||||
// says the region's value domain *is* the whole domain, so it cannot stand in for an
|
||||
// identity this process does not know.
|
||||
let (partition_expr, watermark) = match query_ctx.scan_partition_expr(region_id.as_u64()) {
|
||||
Some(ScanPartitionExpr::WholeDomain) => (None, Some(seq)),
|
||||
Some(ScanPartitionExpr::Slice(expr)) => (Some(expr), Some(seq)),
|
||||
Some(ScanPartitionExpr::Conflicting) | None => (None, None),
|
||||
};
|
||||
// The file list the scan started from is a separate statement and stays reportable even
|
||||
// when the domain above is ambiguous: it says which other regions' rows sat in this region
|
||||
// when it was opened, not what this read proved.
|
||||
let visible_foreign_file_creators =
|
||||
match query_ctx.scan_visible_file_creators(region_id.as_u64()) {
|
||||
Some(ScanVisibleFileCreators::Stated(creators)) => Some(creators),
|
||||
Some(ScanVisibleFileCreators::Conflicting) | None => None,
|
||||
};
|
||||
let statement = RegionWatermarkStatement {
|
||||
region_id: region_id.as_u64(),
|
||||
partition_expr,
|
||||
watermark,
|
||||
visible_foreign_file_creators,
|
||||
};
|
||||
Box::pin(RegionWatermarkStream::new(stream, statement)) as SendableRecordBatchStream
|
||||
}
|
||||
|
||||
/// The `(region, partition expression, watermark)` statement one region read makes about where an
|
||||
/// incremental read of it may resume.
|
||||
///
|
||||
/// # Why the expression belongs to the same snapshot as the sequence
|
||||
///
|
||||
/// A watermark is a statement about **one value domain**. `watermark` is the upper bound the scan
|
||||
/// was opened at, and `partition_expr` is the region's partition expression of the very same
|
||||
/// version the engine read that bound from: the engine states both together
|
||||
/// ([`store_api::region_engine::ScanSnapshotIdentity`]) and the query binds them together
|
||||
/// (`query::dummy_catalog::DummyTableProvider`), so a concurrent repartition - which publishes a
|
||||
/// new version - cannot pair this expression with another version's bound.
|
||||
///
|
||||
/// `partition_expr: None` therefore means exactly one thing: **this region's value domain is the
|
||||
/// whole domain**, because it has no partition expression. It is never the fallback for a region
|
||||
/// whose expression this process does not know; such a read reports `watermark: None` instead, so
|
||||
/// it participates without proving a bound.
|
||||
///
|
||||
/// # Upgrade order: this report is not mixed-version compatible
|
||||
///
|
||||
/// [`RegionWatermarkEntry::partition_expr`] is optional, so a payload that omits it decodes as
|
||||
/// `None`. That is also what a build predating this report writes for a **partitioned** region,
|
||||
/// because it knew no expression to write. The merge
|
||||
/// (`query::metrics::merge_region_watermark_entries`) keys statements by
|
||||
/// `(region_id, partition_expr)` and folds a region's slices conservatively, so running both
|
||||
/// builds against one flow makes the same region's proofs disagree: an upgraded node states
|
||||
/// `Slice(expr)` where an old node states the whole domain, and neither statement subsumes the
|
||||
/// other, so the region is reported unproved rather than advancing to either. Nothing silently
|
||||
/// takes a min/max and no cursor moves to a bound that was never proved - the cost is stalled flow
|
||||
/// checkpoints for the affected regions.
|
||||
///
|
||||
/// So there is an explicit upgrade order, and no pretending the two can run together: upgrade
|
||||
/// **every** datanode that serves a flow's source regions before that flow resumes, and do not
|
||||
/// roll a datanode back below this build while any flow holds slices of its partitioned regions.
|
||||
/// Regions without a partition expression are unaffected (both builds state `None`), so a cluster
|
||||
/// whose flow sources are all unpartitioned may be upgraded in any order.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
struct RegionWatermarkStatement {
|
||||
region_id: u64,
|
||||
/// The slice the statement is about, or `None` when the region's value domain **is** the whole
|
||||
/// domain.
|
||||
partition_expr: Option<String>,
|
||||
/// The proved upper bound, or `None` when the region participated without one.
|
||||
watermark: Option<u64>,
|
||||
/// One sentence: the creators of the files the region had visible when it was opened, i.e. the
|
||||
/// other regions whose rows its file list may hold; `None` when the read could not state them.
|
||||
/// Read from the same version as `partition_expr`/`watermark`, in memory, before any pruning.
|
||||
visible_foreign_file_creators: Option<Vec<u64>>,
|
||||
}
|
||||
|
||||
impl RegionWatermarkStatement {
|
||||
fn into_entry(self) -> RegionWatermarkEntry {
|
||||
RegionWatermarkEntry {
|
||||
region_id: self.region_id,
|
||||
partition_expr: self.partition_expr,
|
||||
watermark: self.watermark,
|
||||
visible_foreign_file_creators: self.visible_foreign_file_creators,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Wraps a region read stream so terminal metrics can carry the scan-open watermark.
|
||||
struct RegionWatermarkStream {
|
||||
stream: SendableRecordBatchStream,
|
||||
region_id: u64,
|
||||
snapshot_seq: u64,
|
||||
statement: RegionWatermarkStatement,
|
||||
finished: bool,
|
||||
}
|
||||
|
||||
impl RegionWatermarkStream {
|
||||
fn new(stream: SendableRecordBatchStream, region_id: RegionId, snapshot_seq: u64) -> Self {
|
||||
fn new(stream: SendableRecordBatchStream, statement: RegionWatermarkStatement) -> Self {
|
||||
Self {
|
||||
stream,
|
||||
region_id: region_id.as_u64(),
|
||||
snapshot_seq,
|
||||
statement,
|
||||
finished: false,
|
||||
}
|
||||
}
|
||||
|
||||
fn merged_metrics(&self, mut metrics: RecordBatchMetrics) -> RecordBatchMetrics {
|
||||
// Opening the region at `snapshot_seq` bounds the region's **complete** value
|
||||
// domain, so this statement is region-wide (`partition_expr: None`) and is a
|
||||
// duplicate only of another region-wide statement of the same region. An entry
|
||||
// about one partition expression says something narrower: dropping this one for
|
||||
// it would forget that the whole region was opened, and dropping that one for
|
||||
// this one would claim a slice nobody read. Both are kept, and the merge that
|
||||
// This read opened the region at the snapshot bound above, so its statement is about the
|
||||
// slice the same version stated: the whole domain when the region has no partition
|
||||
// expression, one expression otherwise. It is a duplicate of exactly another statement
|
||||
// about the same slice of the same region. A statement about another slice says something
|
||||
// narrower or incommensurable - dropping it would forget what was read, and dropping this
|
||||
// one for it would claim a slice nobody read - so both are kept and the merge that
|
||||
// follows keys them apart.
|
||||
let duplicate = metrics
|
||||
.region_watermarks
|
||||
.iter()
|
||||
.any(|entry| entry.region_id == self.region_id && entry.partition_expr.is_none());
|
||||
let duplicate = metrics.region_watermarks.iter().any(|entry| {
|
||||
entry.region_id == self.statement.region_id
|
||||
&& entry.partition_expr == self.statement.partition_expr
|
||||
});
|
||||
if duplicate {
|
||||
return metrics;
|
||||
}
|
||||
|
||||
metrics
|
||||
.region_watermarks
|
||||
.push(common_recordbatch::adapter::RegionWatermarkEntry {
|
||||
region_id: self.region_id,
|
||||
partition_expr: None,
|
||||
watermark: Some(self.snapshot_seq),
|
||||
});
|
||||
.push(self.statement.clone().into_entry());
|
||||
metrics
|
||||
}
|
||||
}
|
||||
@@ -2551,6 +2631,46 @@ mod tests {
|
||||
.as_stream()
|
||||
}
|
||||
|
||||
/// The statement of a read of a region that has no partition expression: its value domain
|
||||
/// **is** the whole domain.
|
||||
fn whole_domain_statement(
|
||||
region_id: RegionId,
|
||||
watermark: Option<u64>,
|
||||
) -> RegionWatermarkStatement {
|
||||
RegionWatermarkStatement {
|
||||
region_id: region_id.as_u64(),
|
||||
partition_expr: None,
|
||||
watermark,
|
||||
visible_foreign_file_creators: Some(Vec::new()),
|
||||
}
|
||||
}
|
||||
|
||||
/// The same statement, holding one file another region created.
|
||||
fn whole_domain_statement_with_foreign_file(
|
||||
region_id: RegionId,
|
||||
watermark: Option<u64>,
|
||||
creator: u64,
|
||||
) -> RegionWatermarkStatement {
|
||||
RegionWatermarkStatement {
|
||||
visible_foreign_file_creators: Some(vec![creator]),
|
||||
..whole_domain_statement(region_id, watermark)
|
||||
}
|
||||
}
|
||||
|
||||
/// The statement of a read of one partition expression of a region.
|
||||
fn slice_statement(
|
||||
region_id: RegionId,
|
||||
partition_expr: &str,
|
||||
watermark: Option<u64>,
|
||||
) -> RegionWatermarkStatement {
|
||||
RegionWatermarkStatement {
|
||||
region_id: region_id.as_u64(),
|
||||
partition_expr: Some(partition_expr.to_string()),
|
||||
watermark,
|
||||
visible_foreign_file_creators: Some(Vec::new()),
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_region_watermark_stream_only_sets_terminal_metrics() {
|
||||
let schema = Arc::new(Schema::new(vec![ColumnSchema::new(
|
||||
@@ -2565,7 +2685,9 @@ mod tests {
|
||||
.as_stream();
|
||||
|
||||
let region_id = RegionId::new(42, 7);
|
||||
let wrapped = RegionWatermarkStream::new(stream, region_id, 99);
|
||||
// A region without a partition expression states `None` and its watermark.
|
||||
let wrapped =
|
||||
RegionWatermarkStream::new(stream, whole_domain_statement(region_id, Some(99)));
|
||||
let mut pinned = Box::pin(wrapped);
|
||||
|
||||
assert!(pinned.as_ref().get_ref().metrics().is_none());
|
||||
@@ -2578,10 +2700,99 @@ mod tests {
|
||||
region_id: region_id.as_u64(),
|
||||
partition_expr: None,
|
||||
watermark: Some(99),
|
||||
visible_foreign_file_creators: Some(Vec::new()),
|
||||
}],
|
||||
"a region holding no foreign file states the empty set, not an unknown one"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_region_watermark_stream_reports_the_partition_expr_and_the_watermark() {
|
||||
let schema = Arc::new(Schema::new(vec![ColumnSchema::new(
|
||||
"v",
|
||||
ConcreteDataType::int32_datatype(),
|
||||
false,
|
||||
)]));
|
||||
let values: VectorRef = Arc::new(Int32Vector::from_slice([1]));
|
||||
let batch = RecordBatch::new(schema.clone(), vec![values]).unwrap();
|
||||
let stream = RecordBatches::try_new(schema, vec![batch])
|
||||
.unwrap()
|
||||
.as_stream();
|
||||
|
||||
let region_id = RegionId::new(42, 7);
|
||||
// A region with a partition expression states that expression and its watermark.
|
||||
let wrapped = RegionWatermarkStream::new(
|
||||
stream,
|
||||
slice_statement(region_id, r#"{"slice":"k0 < 10"}"#, Some(99)),
|
||||
);
|
||||
|
||||
let merged = wrapped.merged_metrics(RecordBatchMetrics::default());
|
||||
assert_eq!(
|
||||
merged.region_watermarks,
|
||||
vec![RegionWatermarkEntry {
|
||||
region_id: region_id.as_u64(),
|
||||
partition_expr: Some(r#"{"slice":"k0 < 10"}"#.to_string()),
|
||||
watermark: Some(99),
|
||||
visible_foreign_file_creators: Some(Vec::new()),
|
||||
}]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_region_watermark_stream_keeps_two_slices_of_the_same_region() {
|
||||
let schema = Arc::new(Schema::new(vec![ColumnSchema::new(
|
||||
"v",
|
||||
ConcreteDataType::int32_datatype(),
|
||||
false,
|
||||
)]));
|
||||
let values: VectorRef = Arc::new(Int32Vector::from_slice([1]));
|
||||
let batch = RecordBatch::new(schema.clone(), vec![values]).unwrap();
|
||||
let stream = RecordBatches::try_new(schema, vec![batch])
|
||||
.unwrap()
|
||||
.as_stream();
|
||||
|
||||
let region_id = RegionId::new(42, 7);
|
||||
let wrapped = RegionWatermarkStream::new(
|
||||
stream,
|
||||
slice_statement(region_id, r#"{"slice":"k0 < 10"}"#, Some(99)),
|
||||
);
|
||||
// The stream already stated another slice of the same region: both triples are kept, and
|
||||
// neither slice is dropped for the other.
|
||||
let other_slice_metrics = RecordBatchMetrics {
|
||||
region_watermarks: vec![RegionWatermarkEntry {
|
||||
region_id: region_id.as_u64(),
|
||||
partition_expr: Some(r#"{"slice":"k0 >= 10"}"#.to_string()),
|
||||
watermark: Some(5),
|
||||
visible_foreign_file_creators: Some(vec![7]),
|
||||
}],
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let merged = wrapped.merged_metrics(other_slice_metrics);
|
||||
assert_eq!(
|
||||
merged.region_watermarks,
|
||||
vec![
|
||||
RegionWatermarkEntry {
|
||||
region_id: region_id.as_u64(),
|
||||
partition_expr: Some(r#"{"slice":"k0 >= 10"}"#.to_string()),
|
||||
watermark: Some(5),
|
||||
visible_foreign_file_creators: Some(vec![7]),
|
||||
},
|
||||
RegionWatermarkEntry {
|
||||
region_id: region_id.as_u64(),
|
||||
partition_expr: Some(r#"{"slice":"k0 < 10"}"#.to_string()),
|
||||
watermark: Some(99),
|
||||
visible_foreign_file_creators: Some(Vec::new()),
|
||||
},
|
||||
],
|
||||
"two slices of one region are two statements, not one"
|
||||
);
|
||||
|
||||
// The same slice stated twice is the duplicate to skip.
|
||||
let merged_again = wrapped.merged_metrics(merged);
|
||||
assert_eq!(2, merged_again.region_watermarks.len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_region_watermark_stream_preserves_unproved_watermark() {
|
||||
let schema = Arc::new(Schema::new(vec![ColumnSchema::new(
|
||||
@@ -2596,12 +2807,13 @@ mod tests {
|
||||
.as_stream();
|
||||
|
||||
let region_id = RegionId::new(42, 7);
|
||||
let wrapped = RegionWatermarkStream::new(stream, region_id, 99);
|
||||
let wrapped = RegionWatermarkStream::new(stream, whole_domain_statement(region_id, None));
|
||||
let metrics = RecordBatchMetrics {
|
||||
region_watermarks: vec![RegionWatermarkEntry {
|
||||
region_id: region_id.as_u64(),
|
||||
partition_expr: None,
|
||||
watermark: None,
|
||||
visible_foreign_file_creators: Some(vec![7]),
|
||||
}],
|
||||
..Default::default()
|
||||
};
|
||||
@@ -2613,7 +2825,9 @@ mod tests {
|
||||
region_id: region_id.as_u64(),
|
||||
partition_expr: None,
|
||||
watermark: None,
|
||||
}]
|
||||
visible_foreign_file_creators: Some(vec![7]),
|
||||
}],
|
||||
"an unproved watermark keeps the file creators the stream stated"
|
||||
);
|
||||
}
|
||||
|
||||
@@ -2631,12 +2845,14 @@ mod tests {
|
||||
.as_stream();
|
||||
|
||||
let region_id = RegionId::new(42, 7);
|
||||
let wrapped = RegionWatermarkStream::new(stream, region_id, 99);
|
||||
let wrapped =
|
||||
RegionWatermarkStream::new(stream, whole_domain_statement(region_id, Some(99)));
|
||||
let slice_metrics = RecordBatchMetrics {
|
||||
region_watermarks: vec![RegionWatermarkEntry {
|
||||
region_id: region_id.as_u64(),
|
||||
partition_expr: Some(r#"{"slice":"k0 < 10"}"#.to_string()),
|
||||
watermark: Some(5),
|
||||
visible_foreign_file_creators: None,
|
||||
}],
|
||||
..Default::default()
|
||||
};
|
||||
@@ -2649,11 +2865,13 @@ mod tests {
|
||||
region_id: region_id.as_u64(),
|
||||
partition_expr: Some(r#"{"slice":"k0 < 10"}"#.to_string()),
|
||||
watermark: Some(5),
|
||||
visible_foreign_file_creators: None,
|
||||
},
|
||||
RegionWatermarkEntry {
|
||||
region_id: region_id.as_u64(),
|
||||
partition_expr: None,
|
||||
watermark: Some(99),
|
||||
visible_foreign_file_creators: Some(Vec::new()),
|
||||
},
|
||||
],
|
||||
"the region-wide statement must not be dropped for a narrower one"
|
||||
@@ -2664,35 +2882,175 @@ mod tests {
|
||||
assert_eq!(2, merged_again.region_watermarks.len());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_wrap_flow_region_watermark_stream_adds_terminal_metrics() {
|
||||
let region_id = RegionId::new(42, 7);
|
||||
let query_ctx = Arc::new(
|
||||
fn watermark_collecting_query_ctx() -> QueryContextRef {
|
||||
Arc::new(
|
||||
QueryContextBuilder::default()
|
||||
.extensions(HashMap::from([(
|
||||
FLOW_RETURN_REGION_SEQ.to_string(),
|
||||
"true".to_string(),
|
||||
)]))
|
||||
.build(),
|
||||
);
|
||||
)
|
||||
}
|
||||
|
||||
async fn drain_watermark_stream(
|
||||
mut pinned: SendableRecordBatchStream,
|
||||
) -> Vec<RegionWatermarkEntry> {
|
||||
while pinned.next().await.is_some() {}
|
||||
pinned
|
||||
.as_ref()
|
||||
.get_ref()
|
||||
.metrics()
|
||||
.expect("the wrapped stream must carry terminal metrics")
|
||||
.region_watermarks
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_wrap_flow_region_watermark_stream_adds_terminal_metrics() {
|
||||
let region_id = RegionId::new(42, 7);
|
||||
let query_ctx = watermark_collecting_query_ctx();
|
||||
query_ctx.set_snapshot(region_id.as_u64(), 99);
|
||||
// The region has no partition expression, so its value domain is the whole domain, and
|
||||
// every file it holds was created by itself.
|
||||
query_ctx.bind_scan_partition_expr(region_id.as_u64(), None);
|
||||
query_ctx.bind_scan_visible_file_creators(region_id.as_u64(), Vec::new());
|
||||
|
||||
let wrapped =
|
||||
wrap_flow_region_watermark_stream(single_value_stream(), region_id, &query_ctx);
|
||||
let mut pinned = Box::pin(wrapped);
|
||||
while pinned.next().await.is_some() {}
|
||||
|
||||
let metrics = pinned.as_ref().get_ref().metrics().unwrap();
|
||||
assert_eq!(
|
||||
metrics.region_watermarks,
|
||||
drain_watermark_stream(wrapped).await,
|
||||
vec![RegionWatermarkEntry {
|
||||
region_id: region_id.as_u64(),
|
||||
partition_expr: None,
|
||||
watermark: Some(99),
|
||||
visible_foreign_file_creators: Some(Vec::new()),
|
||||
}],
|
||||
"nothing foreign visible is stated as an empty set, not as unknown"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_wrap_flow_region_watermark_stream_reports_visible_file_creators() {
|
||||
let region_id = RegionId::new(42, 7);
|
||||
let query_ctx = watermark_collecting_query_ctx();
|
||||
query_ctx.set_snapshot(region_id.as_u64(), 99);
|
||||
query_ctx.bind_scan_partition_expr(region_id.as_u64(), None);
|
||||
// The region holds a file another region created, so its rows may come from there.
|
||||
query_ctx.bind_scan_visible_file_creators(region_id.as_u64(), vec![7]);
|
||||
|
||||
let wrapped =
|
||||
wrap_flow_region_watermark_stream(single_value_stream(), region_id, &query_ctx);
|
||||
assert_eq!(
|
||||
drain_watermark_stream(wrapped).await,
|
||||
vec![RegionWatermarkEntry {
|
||||
region_id: region_id.as_u64(),
|
||||
partition_expr: None,
|
||||
watermark: Some(99),
|
||||
visible_foreign_file_creators: Some(vec![7]),
|
||||
}],
|
||||
"the creator of a visible foreign file is reported with the watermark"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_wrap_flow_region_watermark_stream_reports_file_creators_without_a_proof() {
|
||||
let region_id = RegionId::new(42, 7);
|
||||
let query_ctx = watermark_collecting_query_ctx();
|
||||
query_ctx.set_snapshot(region_id.as_u64(), 99);
|
||||
// The domain is ambiguous, so no bound is proved - but which files the region held is a
|
||||
// separate statement and is still reported.
|
||||
query_ctx.bind_scan_partition_expr(region_id.as_u64(), None);
|
||||
query_ctx.bind_scan_partition_expr(
|
||||
region_id.as_u64(),
|
||||
Some(r#"{"slice":"k0 < 10"}"#.to_string()),
|
||||
);
|
||||
query_ctx.bind_scan_visible_file_creators(region_id.as_u64(), vec![7, 9]);
|
||||
|
||||
let wrapped =
|
||||
wrap_flow_region_watermark_stream(single_value_stream(), region_id, &query_ctx);
|
||||
assert_eq!(
|
||||
drain_watermark_stream(wrapped).await,
|
||||
vec![RegionWatermarkEntry {
|
||||
region_id: region_id.as_u64(),
|
||||
partition_expr: None,
|
||||
watermark: None,
|
||||
visible_foreign_file_creators: Some(vec![7, 9]),
|
||||
}],
|
||||
"participation without a proof still states the file creators"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_wrap_flow_region_watermark_stream_reports_the_bound_partition_expr() {
|
||||
let region_id = RegionId::new(42, 7);
|
||||
let query_ctx = watermark_collecting_query_ctx();
|
||||
query_ctx.set_snapshot(region_id.as_u64(), 99);
|
||||
query_ctx.bind_scan_partition_expr(
|
||||
region_id.as_u64(),
|
||||
Some(r#"{"slice":"k0 < 10"}"#.to_string()),
|
||||
);
|
||||
|
||||
let wrapped =
|
||||
wrap_flow_region_watermark_stream(single_value_stream(), region_id, &query_ctx);
|
||||
assert_eq!(
|
||||
drain_watermark_stream(wrapped).await,
|
||||
vec![RegionWatermarkEntry {
|
||||
region_id: region_id.as_u64(),
|
||||
partition_expr: Some(r#"{"slice":"k0 < 10"}"#.to_string()),
|
||||
watermark: Some(99),
|
||||
visible_foreign_file_creators: None,
|
||||
}],
|
||||
"a scan that stated no file list reports the creators as unknown"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_wrap_flow_region_watermark_stream_refuses_an_unknown_identity() {
|
||||
let region_id = RegionId::new(42, 7);
|
||||
let query_ctx = watermark_collecting_query_ctx();
|
||||
query_ctx.set_snapshot(region_id.as_u64(), 99);
|
||||
|
||||
// No scan stated which part of the region it read, so the read may not claim the
|
||||
// sequence for the whole domain: it participates without proving a bound.
|
||||
let wrapped =
|
||||
wrap_flow_region_watermark_stream(single_value_stream(), region_id, &query_ctx);
|
||||
assert_eq!(
|
||||
drain_watermark_stream(wrapped).await,
|
||||
vec![RegionWatermarkEntry {
|
||||
region_id: region_id.as_u64(),
|
||||
partition_expr: None,
|
||||
watermark: None,
|
||||
visible_foreign_file_creators: None,
|
||||
}]
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_wrap_flow_region_watermark_stream_refuses_conflicting_identities() {
|
||||
let region_id = RegionId::new(42, 7);
|
||||
let query_ctx = watermark_collecting_query_ctx();
|
||||
query_ctx.set_snapshot(region_id.as_u64(), 99);
|
||||
// Two scans of one region stated two different value domains.
|
||||
query_ctx.bind_scan_partition_expr(region_id.as_u64(), None);
|
||||
query_ctx.bind_scan_partition_expr(
|
||||
region_id.as_u64(),
|
||||
Some(r#"{"slice":"k0 < 10"}"#.to_string()),
|
||||
);
|
||||
|
||||
let wrapped =
|
||||
wrap_flow_region_watermark_stream(single_value_stream(), region_id, &query_ctx);
|
||||
assert_eq!(
|
||||
drain_watermark_stream(wrapped).await,
|
||||
vec![RegionWatermarkEntry {
|
||||
region_id: region_id.as_u64(),
|
||||
partition_expr: None,
|
||||
watermark: None,
|
||||
visible_foreign_file_creators: None,
|
||||
}],
|
||||
"an ambiguous domain must state no proof rather than assume one"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_wrap_flow_region_watermark_stream_skips_without_extension() {
|
||||
let region_id = RegionId::new(42, 7);
|
||||
|
||||
@@ -971,6 +971,7 @@ mod tests {
|
||||
region_id: 42,
|
||||
partition_expr: None,
|
||||
watermark: Some(99),
|
||||
visible_foreign_file_creators: None,
|
||||
}],
|
||||
..Default::default()
|
||||
},
|
||||
|
||||
@@ -12,6 +12,7 @@
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
use std::collections::btree_map::Entry;
|
||||
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
|
||||
use std::sync::{Arc, RwLock};
|
||||
use std::time::{Duration, SystemTime, UNIX_EPOCH};
|
||||
@@ -24,6 +25,7 @@ use common_error::ext::BoxedError;
|
||||
use common_meta::key::schema_name::SchemaNameKey;
|
||||
use common_query::OutputData;
|
||||
use common_query::logical_plan::breakup_insert_plan;
|
||||
use common_recordbatch::adapter::RegionWatermarkEntry;
|
||||
use common_telemetry::tracing::warn;
|
||||
use common_telemetry::{debug, info};
|
||||
use common_time::{TimeToLive, Timestamp};
|
||||
@@ -206,6 +208,11 @@ fn encode_insert_plan_request(
|
||||
///
|
||||
/// A region absent from the proved map is never reported as `0`: a missing report is not a
|
||||
/// sequence.
|
||||
///
|
||||
/// The sample keeps the `(region, partition expression, watermark)` statements it read
|
||||
/// ([`Self::slices`]) beside the projections built from them, because a caller that owns a
|
||||
/// per-slice cursor advances one slice at a time: projecting the round onto its regions first
|
||||
/// loses which part of a region's value domain the proved sequence belongs to.
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
||||
pub struct RegionWatermarkSample {
|
||||
/// Regions this round covered, i.e. regions the sample plan named and whose
|
||||
@@ -215,18 +222,99 @@ pub struct RegionWatermarkSample {
|
||||
/// (for example, a region the source route pruned), which this round did not read
|
||||
/// at all.
|
||||
read_regions: BTreeSet<u64>,
|
||||
/// Watermarks proved for a subset of `read_regions`.
|
||||
/// Watermarks proved for a subset of `read_regions`, projected over the region's slices.
|
||||
watermarks: BTreeMap<u64, u64>,
|
||||
/// Every `(region, partition expression)` slice this round stated, ordered by region id and
|
||||
/// then by expression, with the sequence it proved for that slice, the files the region had
|
||||
/// visible when it was opened and the creator set of those files. `None` for the expression is
|
||||
/// the region's complete value domain, never "unknown"; `watermark: None` is a slice that was
|
||||
/// read without a provable bound.
|
||||
slices: Vec<RegionWatermarkEntry>,
|
||||
}
|
||||
|
||||
impl RegionWatermarkSample {
|
||||
fn new(read_regions: BTreeSet<u64>, watermarks: BTreeMap<u64, u64>) -> Self {
|
||||
fn new(
|
||||
read_regions: BTreeSet<u64>,
|
||||
entries: impl IntoIterator<Item = RegionWatermarkEntry>,
|
||||
) -> Self {
|
||||
let mut by_slice = BTreeMap::<(u64, Option<String>), RegionWatermarkEntry>::new();
|
||||
for entry in entries {
|
||||
match by_slice.entry((entry.region_id, entry.partition_expr.clone())) {
|
||||
Entry::Occupied(mut occupied) => {
|
||||
let merged = occupied.get_mut();
|
||||
// The same slice stated twice: equal proofs converge, a differing proof is a
|
||||
// conflict that leaves the slice unproved. Never the min/max of two proofs.
|
||||
merged.watermark = match (merged.watermark, entry.watermark) {
|
||||
(Some(current), Some(incoming)) if current == incoming => Some(current),
|
||||
_ => None,
|
||||
};
|
||||
// Two statements that named different file sets saw different file lists, so
|
||||
// neither set is the one the slice was read under.
|
||||
merged.visible_foreign_file_creators = match (
|
||||
&merged.visible_foreign_file_creators,
|
||||
entry.visible_foreign_file_creators,
|
||||
) {
|
||||
(Some(current), Some(incoming)) if *current == incoming => Some(incoming),
|
||||
(Some(_), Some(_)) => None,
|
||||
(Some(current), None) => Some(current.clone()),
|
||||
(None, incoming) => incoming,
|
||||
};
|
||||
}
|
||||
Entry::Vacant(vacant) => {
|
||||
vacant.insert(entry);
|
||||
}
|
||||
}
|
||||
}
|
||||
let slices = by_slice.into_values().collect::<Vec<_>>();
|
||||
|
||||
// The region projection: a region may only advance to the least advanced of its slices,
|
||||
// and it is omitted entirely when one of them is unproved.
|
||||
let mut regions = BTreeMap::<u64, Option<u64>>::new();
|
||||
for entry in &slices {
|
||||
let slot = regions.entry(entry.region_id).or_insert(entry.watermark);
|
||||
*slot = match (*slot, entry.watermark) {
|
||||
(Some(current), Some(seq)) => Some(current.min(seq)),
|
||||
_ => None,
|
||||
};
|
||||
}
|
||||
|
||||
Self {
|
||||
read_regions,
|
||||
watermarks,
|
||||
watermarks: regions
|
||||
.into_iter()
|
||||
.filter_map(|(region_id, watermark)| watermark.map(|seq| (region_id, seq)))
|
||||
.collect(),
|
||||
slices,
|
||||
}
|
||||
}
|
||||
|
||||
/// The `(region, partition expression, watermark)` statements of this round, ordered by
|
||||
/// region id and then by expression.
|
||||
///
|
||||
/// A caller that owns per-slice cursors builds one cursor entry per statement: the expression
|
||||
/// keys the slice (as the identity a cursor entry is keyed by, `None` = the region's complete
|
||||
/// value domain) and the watermark is the sequence that slice proved, or `None` when the
|
||||
/// slice was read without a provable bound. A slice is never projected onto its region here,
|
||||
/// and an unproved slice stays in place instead of disappearing.
|
||||
///
|
||||
/// Each statement also carries
|
||||
/// [`RegionWatermarkEntry::visible_foreign_file_creators`]: the creators of the files the
|
||||
/// region had visible when this round opened it, i.e. the other regions whose rows its files
|
||||
/// may hold - including rows this round's pinned time index pruned away and therefore never
|
||||
/// delivered. A caller that enumerates the regions a source's rows can come from needs this
|
||||
/// beside the participating set: it is the half of that domain a row-level read cannot
|
||||
/// report. `Some(vec![])` states "no file of another region was visible", `None` states the
|
||||
/// round could not say.
|
||||
///
|
||||
/// A statement about the whole domain and a statement about one expression of the same
|
||||
/// region are different slices: they are reported separately rather than merged, because
|
||||
/// neither subsumes the other. A build that predates expression-keyed statements reports
|
||||
/// every region as the whole domain, so mixing builds makes a region's statements disagree -
|
||||
/// see the upgrade note on the datanode's region watermark reporting.
|
||||
pub fn slices(&self) -> &[RegionWatermarkEntry] {
|
||||
&self.slices
|
||||
}
|
||||
|
||||
/// Proved watermarks, always a subset of `read_regions`.
|
||||
pub fn watermarks(&self) -> &BTreeMap<u64, u64> {
|
||||
&self.watermarks
|
||||
@@ -974,17 +1062,16 @@ impl BatchingTask {
|
||||
self.config.flow_id
|
||||
),
|
||||
})?;
|
||||
let watermarks = result
|
||||
.region_watermark_map()
|
||||
.context(UnexpectedSnafu {
|
||||
reason: format!(
|
||||
"Flow {} region watermark query returned no per-region watermarks",
|
||||
self.config.flow_id
|
||||
),
|
||||
})?
|
||||
.into_iter()
|
||||
.collect::<BTreeMap<u64, u64>>();
|
||||
Ok(RegionWatermarkSample::new(read_regions, watermarks))
|
||||
// The triples travel as stated: the sample keeps the expression dimension instead of
|
||||
// only the region projection, so a caller that owns per-slice cursors can advance one
|
||||
// slice at a time.
|
||||
let entries = result.region_watermark_entries().context(UnexpectedSnafu {
|
||||
reason: format!(
|
||||
"Flow {} region watermark query returned no per-region watermarks",
|
||||
self.config.flow_id
|
||||
),
|
||||
})?;
|
||||
Ok(RegionWatermarkSample::new(read_regions, entries))
|
||||
}
|
||||
|
||||
/// Reads the proved region watermarks of this flow's sources.
|
||||
|
||||
@@ -1452,6 +1452,9 @@ fn recovery_stream_output(
|
||||
region_id,
|
||||
partition_expr: None,
|
||||
watermark,
|
||||
// The fixture states a region-wide watermark and says nothing about
|
||||
// which files were visible, which is "unknown" rather than "none".
|
||||
visible_foreign_file_creators: None,
|
||||
})
|
||||
.collect(),
|
||||
..Default::default()
|
||||
@@ -1828,6 +1831,160 @@ fn test_scheduled_loop_arithmetic_near_i64_boundary() {
|
||||
assert!(sleep_delta_secs(100, 200).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_region_watermark_sample_keeps_the_partition_expr_of_every_slice() {
|
||||
// One region, two expressions, plus a region holding a foreign file: the statements reach the
|
||||
// caller with the expression dimension and the visible file creators intact instead of being
|
||||
// projected onto their regions.
|
||||
let sample = RegionWatermarkSample::new(
|
||||
BTreeSet::from([1_u64, 3]),
|
||||
vec![
|
||||
RegionWatermarkEntry {
|
||||
region_id: 1,
|
||||
partition_expr: Some(r#"{"slice":"k0 < 10"}"#.to_string()),
|
||||
watermark: Some(9),
|
||||
visible_foreign_file_creators: Some(Vec::new()),
|
||||
},
|
||||
RegionWatermarkEntry {
|
||||
region_id: 1,
|
||||
partition_expr: Some(r#"{"slice":"k0 >= 10"}"#.to_string()),
|
||||
watermark: Some(4),
|
||||
visible_foreign_file_creators: Some(Vec::new()),
|
||||
},
|
||||
// This region holds a file another region created, so its rows may come from there
|
||||
// even though this round pruned every file away.
|
||||
RegionWatermarkEntry {
|
||||
region_id: 3,
|
||||
partition_expr: None,
|
||||
watermark: Some(5),
|
||||
visible_foreign_file_creators: Some(vec![7]),
|
||||
},
|
||||
],
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
sample.slices(),
|
||||
&[
|
||||
RegionWatermarkEntry {
|
||||
region_id: 1,
|
||||
partition_expr: Some(r#"{"slice":"k0 < 10"}"#.to_string()),
|
||||
watermark: Some(9),
|
||||
visible_foreign_file_creators: Some(Vec::new()),
|
||||
},
|
||||
RegionWatermarkEntry {
|
||||
region_id: 1,
|
||||
partition_expr: Some(r#"{"slice":"k0 >= 10"}"#.to_string()),
|
||||
watermark: Some(4),
|
||||
visible_foreign_file_creators: Some(Vec::new()),
|
||||
},
|
||||
RegionWatermarkEntry {
|
||||
region_id: 3,
|
||||
partition_expr: None,
|
||||
watermark: Some(5),
|
||||
visible_foreign_file_creators: Some(vec![7]),
|
||||
},
|
||||
]
|
||||
);
|
||||
assert_eq!(
|
||||
sample.watermarks(),
|
||||
&BTreeMap::from([(1_u64, 4_u64), (3_u64, 5_u64)]),
|
||||
"the region projection may only advance to the least advanced slice"
|
||||
);
|
||||
assert_eq!(
|
||||
sample.read_regions(),
|
||||
&BTreeSet::from([1_u64, 3]),
|
||||
"the participating set is unchanged"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_region_watermark_sample_keeps_an_unproved_slice_beside_its_region() {
|
||||
// A region read without a provable bound for one of its slices: the slice stays in the
|
||||
// statements as unproved, and the region leaves the proved projection instead of advancing.
|
||||
let sample = RegionWatermarkSample::new(
|
||||
BTreeSet::from([1_u64, 2]),
|
||||
vec![
|
||||
RegionWatermarkEntry {
|
||||
region_id: 1,
|
||||
partition_expr: None,
|
||||
watermark: None,
|
||||
visible_foreign_file_creators: Some(vec![9]),
|
||||
},
|
||||
RegionWatermarkEntry {
|
||||
region_id: 2,
|
||||
partition_expr: Some(r#"{"slice":"k0 < 10"}"#.to_string()),
|
||||
watermark: Some(7),
|
||||
visible_foreign_file_creators: Some(Vec::new()),
|
||||
},
|
||||
// The same slice stated twice with two different proofs: a conflict, never min/max.
|
||||
RegionWatermarkEntry {
|
||||
region_id: 2,
|
||||
partition_expr: Some(r#"{"slice":"k0 < 10"}"#.to_string()),
|
||||
watermark: Some(6),
|
||||
visible_foreign_file_creators: Some(Vec::new()),
|
||||
},
|
||||
],
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
sample.slices(),
|
||||
&[
|
||||
// Participation without a proof still states which files the region held.
|
||||
RegionWatermarkEntry {
|
||||
region_id: 1,
|
||||
partition_expr: None,
|
||||
watermark: None,
|
||||
visible_foreign_file_creators: Some(vec![9]),
|
||||
},
|
||||
RegionWatermarkEntry {
|
||||
region_id: 2,
|
||||
partition_expr: Some(r#"{"slice":"k0 < 10"}"#.to_string()),
|
||||
watermark: None,
|
||||
visible_foreign_file_creators: Some(Vec::new()),
|
||||
},
|
||||
]
|
||||
);
|
||||
assert_eq!(
|
||||
sample.watermarks(),
|
||||
&BTreeMap::new(),
|
||||
"no region proves a bound, and none is defaulted to 0"
|
||||
);
|
||||
assert_eq!(sample.read_regions(), &BTreeSet::from([1_u64, 2]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_region_watermark_sample_degrades_differing_file_creator_sets_to_unknown() {
|
||||
// Two statements of one slice that saw different file lists: neither set is the one the slice
|
||||
// was read under, so the sample states none instead of picking one.
|
||||
let sample = RegionWatermarkSample::new(
|
||||
BTreeSet::from([1_u64]),
|
||||
vec![
|
||||
RegionWatermarkEntry {
|
||||
region_id: 1,
|
||||
partition_expr: None,
|
||||
watermark: Some(5),
|
||||
visible_foreign_file_creators: Some(vec![7]),
|
||||
},
|
||||
RegionWatermarkEntry {
|
||||
region_id: 1,
|
||||
partition_expr: None,
|
||||
watermark: Some(5),
|
||||
visible_foreign_file_creators: Some(vec![8]),
|
||||
},
|
||||
],
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
sample.slices(),
|
||||
&[RegionWatermarkEntry {
|
||||
region_id: 1,
|
||||
partition_expr: None,
|
||||
watermark: Some(5),
|
||||
visible_foreign_file_creators: None,
|
||||
}]
|
||||
);
|
||||
}
|
||||
|
||||
fn output_with_region_watermarks(
|
||||
watermarks: impl IntoIterator<Item = (u64, Option<u64>)>,
|
||||
) -> OutputWithMetrics {
|
||||
@@ -1839,6 +1996,7 @@ fn output_with_region_watermarks(
|
||||
region_id,
|
||||
partition_expr: None,
|
||||
watermark,
|
||||
visible_foreign_file_creators: None,
|
||||
})
|
||||
.collect(),
|
||||
..Default::default()
|
||||
|
||||
@@ -1250,6 +1250,165 @@ async fn test_full_snapshot_upper_bound_returns_outdated_after_late_flush() {
|
||||
assert!(err_msg.contains(&format!("given_seq: {snapshot_upper_bound}")));
|
||||
}
|
||||
|
||||
/// A scan states the creators of the files another region left in its file list: a read that
|
||||
/// prunes every file away still says which regions' rows the region may hold, and says the empty
|
||||
/// set when every visible file is its own.
|
||||
#[tokio::test]
|
||||
async fn test_snapshot_identity_states_visible_foreign_file_creators() {
|
||||
let mut env = TestEnv::with_prefix("test_snapshot_identity_file_creators").await;
|
||||
let engine = env.create_engine(MitoConfig::default()).await;
|
||||
|
||||
let region_id = RegionId::new(1, 1);
|
||||
let foreign_creator = RegionId::new(1, 2);
|
||||
let request = CreateRequestBuilder::new().build();
|
||||
let column_schemas = test_util::rows_schema(&request);
|
||||
engine
|
||||
.handle_request(region_id, RegionRequest::Create(request))
|
||||
.await
|
||||
.unwrap();
|
||||
test_util::put_rows(
|
||||
&engine,
|
||||
region_id,
|
||||
Rows {
|
||||
schema: column_schemas,
|
||||
rows: test_util::build_rows(0, 3),
|
||||
},
|
||||
)
|
||||
.await;
|
||||
test_util::flush_region(&engine, region_id, None).await;
|
||||
|
||||
// Every visible file was created by the region itself: a positive "nothing foreign" answer.
|
||||
let own = engine
|
||||
.handle_query(region_id, ScanRequest::default())
|
||||
.await
|
||||
.unwrap()
|
||||
.snapshot_identity()
|
||||
.expect("a mito scan states its snapshot identity");
|
||||
assert_eq!(Some(Vec::new()), own.visible_foreign_file_creators);
|
||||
|
||||
// Publish a file another region created into this region's file list, which is what a
|
||||
// repartition leaves behind.
|
||||
engine
|
||||
.edit_region(
|
||||
region_id,
|
||||
RegionEdit {
|
||||
files_to_add: vec![FileMeta {
|
||||
region_id: foreign_creator,
|
||||
file_id: FileId::random(),
|
||||
time_range: (
|
||||
Timestamp::new_millisecond(0),
|
||||
Timestamp::new_millisecond(1000),
|
||||
),
|
||||
level: 0,
|
||||
file_size: 0,
|
||||
max_row_group_uncompressed_size: 0,
|
||||
available_indexes: Default::default(),
|
||||
indexes: vec![],
|
||||
index_file_size: 0,
|
||||
index_version: 0,
|
||||
num_rows: 0,
|
||||
num_row_groups: 0,
|
||||
sequence: None,
|
||||
partition_expr: None,
|
||||
num_series: 0,
|
||||
preserve_row_sequence: true,
|
||||
..Default::default()
|
||||
}],
|
||||
files_to_remove: vec![],
|
||||
timestamp_ms: None,
|
||||
compaction_time_window: None,
|
||||
flushed_entry_id: None,
|
||||
flushed_sequence: None,
|
||||
committed_sequence: None,
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
// A read whose time range prunes everything still states the creator: the file list is read
|
||||
// from the version in memory, before any pruning.
|
||||
let pruned = engine
|
||||
.handle_query(
|
||||
region_id,
|
||||
ScanRequest {
|
||||
filters: vec![col("ts").gt(lit(Timestamp::new_millisecond(i64::MAX / 2).value()))],
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.await
|
||||
.unwrap()
|
||||
.snapshot_identity()
|
||||
.expect("a mito scan states its snapshot identity");
|
||||
assert_eq!(
|
||||
Some(vec![foreign_creator.as_u64()]),
|
||||
pruned.visible_foreign_file_creators
|
||||
);
|
||||
}
|
||||
|
||||
/// A scan states the partition expression of the **one** version whose `committed_sequence` it
|
||||
/// bound as its upper bound, in the canonical form a flow cursor entry is keyed by - and states
|
||||
/// the region's whole domain as `None` when that version has no expression.
|
||||
#[tokio::test]
|
||||
async fn test_snapshot_identity_states_the_partition_expr_of_the_bound_version() {
|
||||
let mut env = TestEnv::with_prefix("test_snapshot_identity_partition_expr").await;
|
||||
let engine = env.create_engine(MitoConfig::default()).await;
|
||||
|
||||
// Value-first shape: the identity a cursor entry keys must be canonicalized before it is
|
||||
// stated, or the same slice would be keyed two ways.
|
||||
let expr_json =
|
||||
r#"{"Expr":{"lhs":{"Value":{"String":"k5"}},"op":"Gt","rhs":{"Column":"tag_0"}}}"#;
|
||||
let partitioned = RegionId::new(1, 1);
|
||||
let unpartitioned = RegionId::new(1, 2);
|
||||
for (region_id, request) in [
|
||||
(
|
||||
partitioned,
|
||||
CreateRequestBuilder::new()
|
||||
.partition_expr_json(Some(expr_json.to_string()))
|
||||
.build(),
|
||||
),
|
||||
(unpartitioned, CreateRequestBuilder::new().build()),
|
||||
] {
|
||||
engine
|
||||
.handle_request(region_id, RegionRequest::Create(request))
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
let expected_snapshot = engine.get_committed_sequence(partitioned).await.unwrap();
|
||||
let scanner = engine
|
||||
.handle_query(
|
||||
partitioned,
|
||||
ScanRequest {
|
||||
snapshot_on_scan: true,
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let identity = scanner
|
||||
.snapshot_identity()
|
||||
.expect("a mito scan states its snapshot identity");
|
||||
let expected_identity = partition::expr::PartitionExpr::from_json_str(expr_json)
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
.as_json_str()
|
||||
.unwrap();
|
||||
assert_eq!(Some(expected_snapshot), identity.bound_sequence);
|
||||
assert_eq!(Some(expected_identity), identity.partition_expr);
|
||||
|
||||
// One version, both fields: the sequence the trait reports is the identity's bound.
|
||||
assert_eq!(scanner.snapshot_sequence(), identity.bound_sequence);
|
||||
|
||||
let whole_domain = engine
|
||||
.handle_query(unpartitioned, ScanRequest::default())
|
||||
.await
|
||||
.unwrap()
|
||||
.snapshot_identity()
|
||||
.expect("a mito scan states its snapshot identity");
|
||||
assert_eq!(None, whole_domain.partition_expr);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_snapshot_bound_query_binds_memtable_upper_bound_at_scan_open() {
|
||||
let mut env =
|
||||
|
||||
@@ -47,7 +47,7 @@ use partition::overlap::associate_from_to;
|
||||
use smallvec::SmallVec;
|
||||
use snafu::{OptionExt, ResultExt, ensure};
|
||||
use store_api::metadata::{ColumnMetadata, RegionMetadata, RegionMetadataRef};
|
||||
use store_api::region_engine::{PartitionRange, RegionScannerRef};
|
||||
use store_api::region_engine::{PartitionRange, RegionScannerRef, ScanSnapshotIdentity};
|
||||
use store_api::storage::{
|
||||
ColumnId, CursorShard, RegionId, ScanRequest, SequenceNumber, SequenceRange,
|
||||
TimeSeriesDistribution, TimeSeriesRowSelector,
|
||||
@@ -522,9 +522,62 @@ impl ScanRegion {
|
||||
self.request.distribution == Some(TimeSeriesDistribution::PerSeries)
|
||||
}
|
||||
|
||||
/// The region's partition-expression identity at this scan's version snapshot.
|
||||
///
|
||||
/// [`Self::version`] is the `Version` whose `committed_sequence` the engine bound as this
|
||||
/// scan's `memtable_max_sequence` (see `EngineHandle::scan_region`), so the identity read
|
||||
/// here and that watermark describe one snapshot: a repartition that gives the region
|
||||
/// another expression publishes a new `Version`, which this scan never consults again.
|
||||
///
|
||||
/// The expression is reported in the canonical `PartitionExpr::as_json_str()` form an
|
||||
/// observed slice and a cursor entry carry, so `(region, expression)` from this scan keys
|
||||
/// the same slice as they do. `None` - no expression, or the explicit empty designation -
|
||||
/// states the region's complete value domain.
|
||||
fn snapshot_partition_expr(&self) -> Result<Option<String>> {
|
||||
let Some(expr) =
|
||||
crate::region::parse_partition_expr(self.version.metadata.partition_expr.as_deref())?
|
||||
else {
|
||||
return Ok(None);
|
||||
};
|
||||
let identity = expr
|
||||
.canonicalize()
|
||||
.as_json_str()
|
||||
.context(crate::error::SerializePartitionExprSnafu)?;
|
||||
Ok(Some(identity))
|
||||
}
|
||||
|
||||
/// The creators of the files this scan's version snapshot has visible, excluding the region
|
||||
/// itself, sorted and deduplicated.
|
||||
///
|
||||
/// This reads the version's file list in memory - no manifest read, no file open - so it is
|
||||
/// what the region held **when the scan opened**, before any predicate prunes a file away. A
|
||||
/// consumer that enumerates the regions a flow's rows can come from needs exactly this: the
|
||||
/// regions whose rows are sitting in this region's files, which a pruned read never delivers
|
||||
/// and therefore never reports.
|
||||
///
|
||||
/// The region's own files are its own rows, so its own id is not listed.
|
||||
fn visible_foreign_file_creators(&self) -> Vec<u64> {
|
||||
let region_id = self.region_id();
|
||||
let mut creators = self
|
||||
.version
|
||||
.ssts
|
||||
.levels()
|
||||
.iter()
|
||||
.flat_map(|level| level.files.values())
|
||||
.map(|file| file.meta_ref().region_id.as_u64())
|
||||
.filter(|creator| *creator != region_id)
|
||||
.collect::<Vec<_>>();
|
||||
creators.sort_unstable();
|
||||
creators.dedup();
|
||||
creators
|
||||
}
|
||||
|
||||
/// Creates a scan input.
|
||||
#[tracing::instrument(skip_all, fields(region_id = %self.region_id()))]
|
||||
async fn scan_input(mut self) -> Result<ScanInput> {
|
||||
// Pinned together with `snapshot_sequence` below, all from `self.version`.
|
||||
let snapshot_partition_expr = self.snapshot_partition_expr()?;
|
||||
let visible_foreign_file_creators = self.visible_foreign_file_creators();
|
||||
let metadata = &self.version.metadata;
|
||||
let sst_min_sequence = self.request.sst_min_sequence.and_then(NonZeroU64::new);
|
||||
let time_range = self.build_time_range_predicate();
|
||||
@@ -680,6 +733,8 @@ impl ScanRegion {
|
||||
.then_some(self.request.memtable_max_sequence)
|
||||
.flatten(),
|
||||
)
|
||||
.with_snapshot_partition_expr(snapshot_partition_expr)
|
||||
.with_visible_foreign_file_creators(visible_foreign_file_creators)
|
||||
.with_sequence_range(sequence_range)
|
||||
.with_read_across_invalid_boundary(self.request.read_across_invalid_boundary)
|
||||
.with_read_row_sequence(self.request.read_row_sequence)
|
||||
@@ -1074,6 +1129,19 @@ pub struct ScanInput {
|
||||
explain_flat_format: bool,
|
||||
/// Snapshot upper bound bound at scan open and propagated back to the caller.
|
||||
pub(crate) snapshot_sequence: Option<SequenceNumber>,
|
||||
/// The region's partition expression stated by the same version snapshot as
|
||||
/// [`Self::snapshot_sequence`] (`None` = the region's complete value domain), read once at
|
||||
/// scan open and propagated back to the caller.
|
||||
///
|
||||
/// Set for every query scan, not only for one that bound a sequence: a caller that reads at
|
||||
/// a bound it supplied itself still reports the expression the read happened under. Both
|
||||
/// fields come from [`ScanRegion::version`], the version whose `committed_sequence` the
|
||||
/// engine bound as `memtable_max_sequence` (`EngineHandle::scan_region`).
|
||||
pub(crate) snapshot_partition_expr: Option<String>,
|
||||
/// The creators of the files the same version snapshot had visible, excluding this region
|
||||
/// (`Some(vec![])` = the region held no file of another region), read once at scan open and
|
||||
/// propagated back to the caller.
|
||||
pub(crate) visible_foreign_file_creators: Option<Vec<u64>>,
|
||||
/// Set only when the region preserves per-row sequences
|
||||
/// (`preserve_row_sequence` on an append-only table) and the scan
|
||||
/// carries an explicit exact range. When set, SST readers apply the same
|
||||
@@ -1167,6 +1235,8 @@ impl ScanInput {
|
||||
distribution: None,
|
||||
explain_flat_format: false,
|
||||
snapshot_sequence: None,
|
||||
snapshot_partition_expr: None,
|
||||
visible_foreign_file_creators: None,
|
||||
sequence_range: None,
|
||||
read_across_invalid_boundary: false,
|
||||
read_row_sequence: false,
|
||||
@@ -1536,6 +1606,24 @@ impl ScanInputBuilder {
|
||||
self
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub(crate) fn with_visible_foreign_file_creators(
|
||||
mut self,
|
||||
visible_foreign_file_creators: Vec<u64>,
|
||||
) -> Self {
|
||||
self.input.visible_foreign_file_creators = Some(visible_foreign_file_creators);
|
||||
self
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub(crate) fn with_snapshot_partition_expr(
|
||||
mut self,
|
||||
snapshot_partition_expr: Option<String>,
|
||||
) -> Self {
|
||||
self.input.snapshot_partition_expr = snapshot_partition_expr;
|
||||
self
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub(crate) fn with_sequence_range(mut self, sequence_range: Option<SequenceRange>) -> Self {
|
||||
self.input.sequence_range = sequence_range;
|
||||
@@ -2016,6 +2104,17 @@ impl ScanInput {
|
||||
self.mapper.metadata()
|
||||
}
|
||||
|
||||
/// The snapshot this scan pinned: the bound it set itself (if any) and the
|
||||
/// partition-expression identity of the same version, in the canonical
|
||||
/// `PartitionExpr::as_json_str()` form a cursor entry carries.
|
||||
pub(crate) fn snapshot_identity(&self) -> ScanSnapshotIdentity {
|
||||
ScanSnapshotIdentity {
|
||||
bound_sequence: self.snapshot_sequence,
|
||||
partition_expr: self.snapshot_partition_expr.clone(),
|
||||
visible_foreign_file_creators: self.visible_foreign_file_creators.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn substituted_row_ranges(&self) -> Option<&SubstitutedRowsAccumulator> {
|
||||
self.substituted_row_ranges.as_deref()
|
||||
}
|
||||
|
||||
@@ -30,7 +30,8 @@ use futures::{StreamExt, TryStreamExt};
|
||||
use snafu::ensure;
|
||||
use store_api::metadata::RegionMetadataRef;
|
||||
use store_api::region_engine::{
|
||||
PartitionRange, PrepareRequest, QueryScanContext, RegionScanner, ScannerProperties,
|
||||
PartitionRange, PrepareRequest, QueryScanContext, RegionScanner, ScanSnapshotIdentity,
|
||||
ScannerProperties,
|
||||
};
|
||||
use store_api::storage::TimeSeriesRowSelector;
|
||||
use tokio::sync::Semaphore;
|
||||
@@ -675,8 +676,8 @@ impl RegionScanner for SeqScan {
|
||||
self.properties.set_query_load_region_id(region_id);
|
||||
}
|
||||
|
||||
fn snapshot_sequence(&self) -> Option<u64> {
|
||||
self.stream_ctx.input.snapshot_sequence
|
||||
fn snapshot_identity(&self) -> Option<ScanSnapshotIdentity> {
|
||||
Some(self.stream_ctx.input.snapshot_identity())
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -51,7 +51,7 @@ use store_api::metadata::RegionMetadataRef;
|
||||
use store_api::metric_engine_consts::is_metric_engine_internal_column;
|
||||
use store_api::region_engine::{
|
||||
PartitionRange, PrepareRequest, QueryScanContext, RawLabelSource, RegionScanner,
|
||||
ScannerProperties, SendableRawSeriesStream,
|
||||
ScanSnapshotIdentity, ScannerProperties, SendableRawSeriesStream,
|
||||
};
|
||||
use store_api::storage::consts::{ReservedColumnId, is_internal_column};
|
||||
use table::predicate::Predicate;
|
||||
@@ -1193,8 +1193,8 @@ impl RegionScanner for SeriesScan {
|
||||
self.properties.set_query_load_region_id(region_id);
|
||||
}
|
||||
|
||||
fn snapshot_sequence(&self) -> Option<u64> {
|
||||
self.stream_ctx.input.snapshot_sequence
|
||||
fn snapshot_identity(&self) -> Option<ScanSnapshotIdentity> {
|
||||
Some(self.stream_ctx.input.snapshot_identity())
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -30,7 +30,7 @@ use futures::{Stream, StreamExt};
|
||||
use snafu::ensure;
|
||||
use store_api::metadata::RegionMetadataRef;
|
||||
use store_api::region_engine::{
|
||||
PrepareRequest, QueryScanContext, RegionScanner, ScannerProperties,
|
||||
PrepareRequest, QueryScanContext, RegionScanner, ScanSnapshotIdentity, ScannerProperties,
|
||||
};
|
||||
|
||||
use crate::error::{PartitionOutOfRangeSnafu, Result};
|
||||
@@ -394,8 +394,8 @@ impl RegionScanner for UnorderedScan {
|
||||
self.properties.set_query_load_region_id(region_id);
|
||||
}
|
||||
|
||||
fn snapshot_sequence(&self) -> Option<u64> {
|
||||
self.stream_ctx.input.snapshot_sequence
|
||||
fn snapshot_identity(&self) -> Option<ScanSnapshotIdentity> {
|
||||
Some(self.stream_ctx.input.snapshot_identity())
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -196,6 +196,20 @@ impl TableProvider for DummyTableProvider {
|
||||
.map_err(|e| DataFusionError::External(Box::new(e)))?;
|
||||
}
|
||||
|
||||
// Bind what the region's scan stated about the snapshot it reads under: the partition
|
||||
// expression it covers and the creators of the files it had visible. The engine states all
|
||||
// of it from one version snapshot, so the expression a region read reports, the watermark
|
||||
// it reports and the file list it started from describe the same instant: a scan that
|
||||
// inherited a caller-fenced bound still states what it actually read under.
|
||||
if let Some(query_ctx) = &self.query_ctx
|
||||
&& let Some(identity) = scanner.snapshot_identity()
|
||||
{
|
||||
query_ctx.bind_scan_partition_expr(self.region_id.as_u64(), identity.partition_expr);
|
||||
if let Some(creators) = identity.visible_foreign_file_creators {
|
||||
query_ctx.bind_scan_visible_file_creators(self.region_id.as_u64(), creators);
|
||||
}
|
||||
}
|
||||
|
||||
let query_memory_tracker = self.engine.query_memory_tracker();
|
||||
let mut scan_exec = RegionScanExec::new(scanner, request, query_memory_tracker)?;
|
||||
if let Some(query_ctx) = &self.query_ctx {
|
||||
|
||||
+83
-26
@@ -318,7 +318,7 @@ pub fn terminal_recordbatch_metrics_from_plan_if_requested(
|
||||
/// Collects the proved terminal watermarks of `plan`, one entry per
|
||||
/// `(region, partition expression)` the plan's scans stated.
|
||||
fn collect_region_watermarks(plan: Arc<dyn ExecutionPlan>) -> Vec<RegionWatermarkEntry> {
|
||||
let mut merged = BTreeMap::<WatermarkKey, MergeState>::new();
|
||||
let mut merged = BTreeMap::<WatermarkKey, MergedWatermarkSlice>::new();
|
||||
let mut stack = vec![plan];
|
||||
|
||||
while let Some(plan) = stack.pop() {
|
||||
@@ -507,6 +507,38 @@ fn merge_foreign_file_row_creators(
|
||||
}
|
||||
}
|
||||
|
||||
/// One `(region, partition expression)` slice's merged state.
|
||||
///
|
||||
/// Two independent statements live here, because a scan states both from one version snapshot:
|
||||
/// the proof of the slice's sequence bound, and the creators of the files the region had visible
|
||||
/// when it was opened ([`RegionWatermarkEntry::visible_foreign_file_creators`]).
|
||||
#[derive(Default)]
|
||||
struct MergedWatermarkSlice {
|
||||
/// Proof state of the slice's bound; `None` until a report states one.
|
||||
proof: Option<MergeState>,
|
||||
/// The creators of the files visible at open, or `None` when no report stated them or two
|
||||
/// reports stated different sets (then the merged answer is unknown, never one of them).
|
||||
visible_foreign_file_creators: Option<Vec<u64>>,
|
||||
}
|
||||
|
||||
impl MergedWatermarkSlice {
|
||||
/// Merges one statement about the creators visible at open.
|
||||
///
|
||||
/// A report that states nothing adds no information, so it leaves a stated set in place. Two
|
||||
/// reports that state different sets describe file lists that were not the same, so the
|
||||
/// merged answer is unknown rather than either set.
|
||||
fn merge_visible_foreign_file_creators(&mut self, incoming: Option<Vec<u64>>) {
|
||||
let Some(incoming) = incoming else {
|
||||
return;
|
||||
};
|
||||
match &self.visible_foreign_file_creators {
|
||||
None => self.visible_foreign_file_creators = Some(incoming),
|
||||
Some(current) if *current == incoming => {}
|
||||
Some(_) => self.visible_foreign_file_creators = None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Merge a batch of watermark entries into the global merged state.
|
||||
///
|
||||
/// Entries are merged per `(region, partition expression)` ([`WatermarkKey`]): an
|
||||
@@ -530,7 +562,7 @@ fn merge_foreign_file_row_creators(
|
||||
/// checkpoint past rows that a competing MergeScan sub-stage has not yet
|
||||
/// scanned, causing Flow to skip data.
|
||||
fn merge_region_watermark_entries(
|
||||
merged: &mut BTreeMap<WatermarkKey, MergeState>,
|
||||
merged: &mut BTreeMap<WatermarkKey, MergedWatermarkSlice>,
|
||||
entries: impl IntoIterator<Item = RegionWatermarkEntry>,
|
||||
) {
|
||||
for entry in entries {
|
||||
@@ -538,10 +570,18 @@ fn merge_region_watermark_entries(
|
||||
region_id,
|
||||
partition_expr,
|
||||
watermark,
|
||||
visible_foreign_file_creators,
|
||||
} = entry;
|
||||
merged
|
||||
.entry((region_id, partition_expr))
|
||||
.and_modify(|existing| match watermark {
|
||||
let slice = merged.entry((region_id, partition_expr)).or_default();
|
||||
slice.merge_visible_foreign_file_creators(visible_foreign_file_creators);
|
||||
match &mut slice.proof {
|
||||
None => {
|
||||
slice.proof = Some(match watermark {
|
||||
Some(seq) => MergeState::Proved(seq),
|
||||
None => MergeState::Unproved,
|
||||
});
|
||||
}
|
||||
Some(existing) => match watermark {
|
||||
None => match existing {
|
||||
MergeState::Proved(_) => {
|
||||
*existing = MergeState::Unproved;
|
||||
@@ -563,16 +603,13 @@ fn merge_region_watermark_entries(
|
||||
}
|
||||
}
|
||||
},
|
||||
})
|
||||
.or_insert(match watermark {
|
||||
Some(seq) => MergeState::Proved(seq),
|
||||
None => MergeState::Unproved,
|
||||
});
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn merge_merge_scan_region_watermarks(
|
||||
merged: &mut BTreeMap<WatermarkKey, MergeState>,
|
||||
merged: &mut BTreeMap<WatermarkKey, MergedWatermarkSlice>,
|
||||
regions: impl IntoIterator<Item = u64>,
|
||||
sub_stage_metrics: impl IntoIterator<Item = RecordBatchMetrics>,
|
||||
) {
|
||||
@@ -603,30 +640,35 @@ fn merge_merge_scan_region_watermarks(
|
||||
region_id,
|
||||
partition_expr: None,
|
||||
watermark: None,
|
||||
// No branch said anything about the region's file list.
|
||||
visible_foreign_file_creators: None,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
fn finalize_region_watermarks(
|
||||
merged: BTreeMap<WatermarkKey, MergeState>,
|
||||
merged: BTreeMap<WatermarkKey, MergedWatermarkSlice>,
|
||||
) -> Vec<RegionWatermarkEntry> {
|
||||
merged
|
||||
.into_iter()
|
||||
.map(|((region_id, partition_expr), state)| RegionWatermarkEntry {
|
||||
region_id,
|
||||
watermark: match state {
|
||||
MergeState::Unproved => None,
|
||||
MergeState::Proved(seq) => Some(seq),
|
||||
MergeState::Conflict { watermarks } => {
|
||||
warn!(
|
||||
"Conflicting proved watermarks for region {} expression {:?}: {:?}; degrading to unproved",
|
||||
region_id, partition_expr, watermarks
|
||||
);
|
||||
None
|
||||
}
|
||||
.map(
|
||||
|((region_id, partition_expr), slice)| RegionWatermarkEntry {
|
||||
region_id,
|
||||
watermark: match slice.proof.unwrap_or(MergeState::Unproved) {
|
||||
MergeState::Unproved => None,
|
||||
MergeState::Proved(seq) => Some(seq),
|
||||
MergeState::Conflict { watermarks } => {
|
||||
warn!(
|
||||
"Conflicting proved watermarks for region {} expression {:?}: {:?}; degrading to unproved",
|
||||
region_id, partition_expr, watermarks
|
||||
);
|
||||
None
|
||||
}
|
||||
},
|
||||
partition_expr,
|
||||
visible_foreign_file_creators: slice.visible_foreign_file_creators,
|
||||
},
|
||||
partition_expr,
|
||||
})
|
||||
)
|
||||
.collect()
|
||||
}
|
||||
|
||||
@@ -698,6 +740,7 @@ mod tests {
|
||||
region_id: *region_id,
|
||||
partition_expr: None,
|
||||
watermark: *watermark,
|
||||
visible_foreign_file_creators: None,
|
||||
})
|
||||
.collect(),
|
||||
..Default::default()
|
||||
@@ -715,6 +758,7 @@ mod tests {
|
||||
region_id: *region_id,
|
||||
partition_expr: partition_expr.map(|expr| expr.to_string()),
|
||||
watermark: *watermark,
|
||||
visible_foreign_file_creators: None,
|
||||
},
|
||||
)
|
||||
.collect(),
|
||||
@@ -780,6 +824,7 @@ mod tests {
|
||||
region_id: RegionId::new(43, 0).as_u64(),
|
||||
partition_expr: None,
|
||||
watermark: None,
|
||||
visible_foreign_file_creators: None,
|
||||
}]
|
||||
);
|
||||
}
|
||||
@@ -997,11 +1042,13 @@ mod tests {
|
||||
region_id: 1,
|
||||
partition_expr: None,
|
||||
watermark: None,
|
||||
visible_foreign_file_creators: None,
|
||||
},
|
||||
RegionWatermarkEntry {
|
||||
region_id: 2,
|
||||
partition_expr: None,
|
||||
watermark: None,
|
||||
visible_foreign_file_creators: None,
|
||||
},
|
||||
]
|
||||
);
|
||||
@@ -1026,6 +1073,7 @@ mod tests {
|
||||
region_id: 42,
|
||||
partition_expr: None,
|
||||
watermark: Some(7),
|
||||
visible_foreign_file_creators: None,
|
||||
}]
|
||||
);
|
||||
}
|
||||
@@ -1055,16 +1103,19 @@ mod tests {
|
||||
region_id: 42,
|
||||
partition_expr: None,
|
||||
watermark: Some(9),
|
||||
visible_foreign_file_creators: None,
|
||||
},
|
||||
RegionWatermarkEntry {
|
||||
region_id: 42,
|
||||
partition_expr: Some("k0 < 10".to_string()),
|
||||
watermark: Some(5),
|
||||
visible_foreign_file_creators: None,
|
||||
},
|
||||
RegionWatermarkEntry {
|
||||
region_id: 42,
|
||||
partition_expr: Some("k0 >= 10".to_string()),
|
||||
watermark: Some(7),
|
||||
visible_foreign_file_creators: None,
|
||||
},
|
||||
]
|
||||
);
|
||||
@@ -1091,6 +1142,7 @@ mod tests {
|
||||
region_id: 42,
|
||||
partition_expr: Some("k0 < 10".to_string()),
|
||||
watermark: None,
|
||||
visible_foreign_file_creators: None,
|
||||
}]
|
||||
);
|
||||
}
|
||||
@@ -1114,6 +1166,7 @@ mod tests {
|
||||
region_id: 7,
|
||||
partition_expr: None,
|
||||
watermark: None,
|
||||
visible_foreign_file_creators: None,
|
||||
}]
|
||||
);
|
||||
}
|
||||
@@ -1137,6 +1190,7 @@ mod tests {
|
||||
region_id: 9,
|
||||
partition_expr: None,
|
||||
watermark: None,
|
||||
visible_foreign_file_creators: None,
|
||||
}]
|
||||
);
|
||||
}
|
||||
@@ -1160,6 +1214,7 @@ mod tests {
|
||||
region_id: 9,
|
||||
partition_expr: None,
|
||||
watermark: None,
|
||||
visible_foreign_file_creators: None,
|
||||
}]
|
||||
);
|
||||
}
|
||||
@@ -1181,6 +1236,7 @@ mod tests {
|
||||
region_id: 9,
|
||||
partition_expr: None,
|
||||
watermark: None,
|
||||
visible_foreign_file_creators: None,
|
||||
}]
|
||||
);
|
||||
}
|
||||
@@ -1202,6 +1258,7 @@ mod tests {
|
||||
region_id: 9,
|
||||
partition_expr: None,
|
||||
watermark: None,
|
||||
visible_foreign_file_creators: None,
|
||||
}]
|
||||
);
|
||||
}
|
||||
|
||||
@@ -89,6 +89,42 @@ pub fn generate_remote_query_id_value() -> QueryId {
|
||||
QueryId::new()
|
||||
}
|
||||
|
||||
/// The partition-expression identity the scans of one query stated for one region, i.e. which
|
||||
/// part of the region's value domain the snapshot they read under covers.
|
||||
///
|
||||
/// A region states its identity through its scan (`RegionScanner::snapshot_identity` in the
|
||||
/// engine's terms); the engine states the identity and the pinned snapshot sequence together, so
|
||||
/// a watermark reported for the region can be paired with the expression it was measured under.
|
||||
/// `store-api` owns that statement; this crate only records what the scans of one query said.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum ScanPartitionExpr {
|
||||
/// The region's complete value domain: it has no partition expression, so the whole domain
|
||||
/// is the only slice it has. Never means "not known".
|
||||
WholeDomain,
|
||||
/// One partition expression of the region, in the canonical `PartitionExpr::as_json_str()`
|
||||
/// form a cursor entry and an observed slice also carry.
|
||||
Slice(String),
|
||||
/// The query's scans stated two different identities for the region, so the query states
|
||||
/// none: either expression would describe a read the region did not all happen under.
|
||||
Conflicting,
|
||||
}
|
||||
|
||||
/// The creators of the files one query's scans saw visible when they opened one region.
|
||||
///
|
||||
/// It travels beside [`ScanPartitionExpr`] because both are statements about the same version
|
||||
/// snapshot: the expression says which part of the region's value domain the read covered, this
|
||||
/// says which other regions' rows were sitting in the region's files before the read pruned
|
||||
/// anything away.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum ScanVisibleFileCreators {
|
||||
/// The stated set, sorted and deduplicated, never containing the region itself. It may be
|
||||
/// empty, which states "no file of another region was visible" - a positive answer.
|
||||
Stated(Vec<u64>),
|
||||
/// The query's scans saw two different sets, so the query states none: either set would
|
||||
/// leave out files another scan held.
|
||||
Conflicting,
|
||||
}
|
||||
|
||||
#[derive(Debug, Builder, Clone)]
|
||||
#[builder(pattern = "owned")]
|
||||
#[builder(build_fn(skip))]
|
||||
@@ -97,6 +133,17 @@ pub struct QueryContext {
|
||||
/// mapping of RegionId to SequenceNumber, for snapshot read, meaning that the read should only
|
||||
/// container data that was committed before(and include) the given sequence number
|
||||
snapshot_seqs: Arc<RwLock<HashMap<u64, u64>>>,
|
||||
/// Mappings of the RegionId to the partition-expression identity its scans read the
|
||||
/// snapshot above under. Process-local: it describes what this process's scans stated, so
|
||||
/// it is never transported and never accepted from a wire context. A region is absent until
|
||||
/// a scan states its identity.
|
||||
#[builder(default)]
|
||||
scan_partition_exprs: Arc<RwLock<HashMap<u64, ScanPartitionExpr>>>,
|
||||
/// Mappings of the RegionId to the creators of the files its scans saw visible when they
|
||||
/// opened it. Process-local, like [`Self::scan_partition_exprs`]. A region is absent until a
|
||||
/// scan states a set.
|
||||
#[builder(default)]
|
||||
scan_visible_file_creators: Arc<RwLock<HashMap<u64, ScanVisibleFileCreators>>>,
|
||||
/// Mappings of the RegionId to the minimal sequence of SST file to scan.
|
||||
sst_min_sequences: Arc<RwLock<HashMap<u64, u64>>>,
|
||||
// we use Arc<RwLock>> for modifiable fields
|
||||
@@ -802,6 +849,71 @@ impl QueryContext {
|
||||
.insert(region_id, sequence);
|
||||
}
|
||||
|
||||
/// Records the partition-expression identity a scan of `region_id` read the query's pinned
|
||||
/// snapshot under: `None` states the region's complete value domain.
|
||||
///
|
||||
/// A region's first statement stands. A later scan that states another identity for the same
|
||||
/// region marks it [`ScanPartitionExpr::Conflicting`]: the query then states no identity for
|
||||
/// it, because each expression would describe a read the region did not all happen under.
|
||||
pub fn bind_scan_partition_expr(&self, region_id: u64, partition_expr: Option<String>) {
|
||||
let stated = match partition_expr {
|
||||
Some(expr) => ScanPartitionExpr::Slice(expr),
|
||||
None => ScanPartitionExpr::WholeDomain,
|
||||
};
|
||||
let mut exprs = self.scan_partition_exprs.write().unwrap();
|
||||
match exprs.get(®ion_id) {
|
||||
Some(existing) if *existing == stated => {}
|
||||
Some(_) => {
|
||||
exprs.insert(region_id, ScanPartitionExpr::Conflicting);
|
||||
}
|
||||
None => {
|
||||
exprs.insert(region_id, stated);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Records the creators of the files a scan of `region_id` saw visible when it opened the
|
||||
/// region. `creators` is sorted and deduplicated and must not contain the region itself.
|
||||
///
|
||||
/// A region's first statement stands. A later scan that saw another set marks it
|
||||
/// [`ScanVisibleFileCreators::Conflicting`]: the query then states none, because a set that
|
||||
/// omits files another scan held would hide the regions those files' rows come from.
|
||||
pub fn bind_scan_visible_file_creators(&self, region_id: u64, creators: Vec<u64>) {
|
||||
let stated = ScanVisibleFileCreators::Stated(creators);
|
||||
let mut sets = self.scan_visible_file_creators.write().unwrap();
|
||||
match sets.get(®ion_id) {
|
||||
Some(existing) if *existing == stated => {}
|
||||
Some(_) => {
|
||||
sets.insert(region_id, ScanVisibleFileCreators::Conflicting);
|
||||
}
|
||||
None => {
|
||||
sets.insert(region_id, stated);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The creators of the files the query's scans of `region_id` saw visible when they opened
|
||||
/// it, or `None` when no scan stated a set. A caller must report "unknown" for such a region
|
||||
/// rather than assume it holds no file of another region.
|
||||
pub fn scan_visible_file_creators(&self, region_id: u64) -> Option<ScanVisibleFileCreators> {
|
||||
self.scan_visible_file_creators
|
||||
.read()
|
||||
.unwrap()
|
||||
.get(®ion_id)
|
||||
.cloned()
|
||||
}
|
||||
|
||||
/// The partition-expression identity the query's scans of `region_id` stated, or `None` when
|
||||
/// no scan stated one. A caller must not report an identity for such a region rather than
|
||||
/// assume the region's whole domain.
|
||||
pub fn scan_partition_expr(&self, region_id: u64) -> Option<ScanPartitionExpr> {
|
||||
self.scan_partition_exprs
|
||||
.read()
|
||||
.unwrap()
|
||||
.get(®ion_id)
|
||||
.cloned()
|
||||
}
|
||||
|
||||
/// Returns `true` if the session can cast strings to numbers in MySQL style.
|
||||
pub fn auto_string_to_numeric(&self) -> bool {
|
||||
matches!(self.channel, Channel::Mysql)
|
||||
@@ -846,6 +958,8 @@ impl QueryContextBuilder {
|
||||
.current_catalog
|
||||
.unwrap_or_else(|| DEFAULT_CATALOG_NAME.to_string()),
|
||||
snapshot_seqs: self.snapshot_seqs.unwrap_or_default(),
|
||||
scan_partition_exprs: self.scan_partition_exprs.unwrap_or_default(),
|
||||
scan_visible_file_creators: self.scan_visible_file_creators.unwrap_or_default(),
|
||||
sst_min_sequences: self.sst_min_sequences.unwrap_or_default(),
|
||||
mutable_session_data: self.mutable_session_data.unwrap_or_default(),
|
||||
mutable_query_context_data: self.mutable_query_context_data.unwrap_or_default(),
|
||||
|
||||
@@ -774,9 +774,52 @@ pub trait RegionScanner: Debug + DisplayAs + Send {
|
||||
/// Sets the region id that should receive query-load metrics.
|
||||
fn set_query_load_region_id(&mut self, region_id: RegionId);
|
||||
|
||||
fn snapshot_sequence(&self) -> Option<SequenceNumber> {
|
||||
/// The snapshot this scan reads under, or `None` when the engine states none.
|
||||
///
|
||||
/// An engine that states one reads both fields from **one** version of the region, so a
|
||||
/// caller that reports the scan's watermark together with the region's partition
|
||||
/// expression cannot pair an expression with a watermark measured under another one.
|
||||
/// `None` states nothing: a caller that must report a `(region, expression, watermark)`
|
||||
/// triple reports none for such a scanner instead of assuming a value.
|
||||
fn snapshot_identity(&self) -> Option<ScanSnapshotIdentity> {
|
||||
None
|
||||
}
|
||||
|
||||
/// The sequence upper bound [`Self::snapshot_identity`] states, when it bound one at scan
|
||||
/// open. A scan that inherited its bound from the caller (a fenced read) states none.
|
||||
fn snapshot_sequence(&self) -> Option<SequenceNumber> {
|
||||
self.snapshot_identity()
|
||||
.and_then(|identity| identity.bound_sequence)
|
||||
}
|
||||
}
|
||||
|
||||
/// The identity of the snapshot one region scan reads under.
|
||||
///
|
||||
/// Both fields describe the same version of the region: the sequence upper bound the scan
|
||||
/// bound when it opened keeps its data inside that version, and `partition_expr` is the
|
||||
/// region's partition expression that same version states. Taking them from one snapshot is
|
||||
/// what makes a reported `(expression, watermark)` pair trustworthy: a concurrent repartition
|
||||
/// that gives the region another expression cannot pair the old expression with the new
|
||||
/// watermark, because neither is read again after the scan pinned the version.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ScanSnapshotIdentity {
|
||||
/// The sequence upper bound the scan **bound** when it opened, or `None` when it did not
|
||||
/// bind one (a caller-fenced read, whose bound the caller supplies).
|
||||
pub bound_sequence: Option<SequenceNumber>,
|
||||
/// The region's partition expression at that snapshot, in the canonical
|
||||
/// `PartitionExpr::as_json_str()` form a cursor and an observed slice also use.
|
||||
///
|
||||
/// `None` states the region's **complete value domain** - the region has no partition
|
||||
/// expression, so the whole domain is the only slice it has. It never means "not known".
|
||||
pub partition_expr: Option<String>,
|
||||
/// The creators of the files the region had visible at that snapshot, i.e. the regions whose
|
||||
/// rows its file list may hold. Read from the version's file list in memory, so what the scan
|
||||
/// prunes afterwards cannot hide a file from it.
|
||||
///
|
||||
/// The region itself is never listed. `Some(vec![])` states the region held no file of
|
||||
/// another region, which is a positive "nothing foreign" answer; `None` states that this
|
||||
/// engine does not know.
|
||||
pub visible_foreign_file_creators: Option<Vec<u64>>,
|
||||
}
|
||||
|
||||
pub type RegionScannerRef = Box<dyn RegionScanner>;
|
||||
@@ -1681,8 +1724,19 @@ impl RegionScanner for SinglePartitionScanner {
|
||||
self.properties.set_query_load_region_id(region_id);
|
||||
}
|
||||
|
||||
fn snapshot_sequence(&self) -> Option<SequenceNumber> {
|
||||
self.snapshot_sequence
|
||||
fn snapshot_identity(&self) -> Option<ScanSnapshotIdentity> {
|
||||
Some(ScanSnapshotIdentity {
|
||||
bound_sequence: self.snapshot_sequence,
|
||||
// `store-api` cannot depend on `partition`, so this states the expression the
|
||||
// metadata carries instead of canonicalizing it. An engine that partitions a region
|
||||
// and reads it under a pinned snapshot overrides this with the identity its own scans
|
||||
// state (see the mito engine), so this value only has to be right for an engine whose
|
||||
// regions keep the expression they were created with.
|
||||
partition_expr: self.metadata.partition_expr.clone(),
|
||||
// This scanner does not hold a region file list, so it states nothing about the
|
||||
// files instead of claiming the region holds none.
|
||||
visible_foreign_file_creators: None,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1055,6 +1055,7 @@ mod test {
|
||||
region_id: expected_watermark.0,
|
||||
partition_expr: None,
|
||||
watermark: Some(expected_watermark.1),
|
||||
visible_foreign_file_creators: None,
|
||||
}]
|
||||
);
|
||||
|
||||
|
||||
Reference in New Issue
Block a user