diff --git a/data_plane/src/persist.rs b/data_plane/src/persist.rs index 7f46aa81..bcd7b018 100644 --- a/data_plane/src/persist.rs +++ b/data_plane/src/persist.rs @@ -129,6 +129,9 @@ pub type ViewIndex = BTreeMap, texts: HashMap, u32>, + /// The labels of each series identity its records held, looked up once + /// per segment ([`SegmentTexts::identity_labels`]). + labels_by_identity: crate::segment::LabelsByIdentity, /// The start of its first window: it rolls once a window starts /// `segment_ms` or more after it. first_start_ms: i64, @@ -420,6 +423,7 @@ impl ViewFiles { files.active = Some(ActiveSegment { segment: Segment::create(&path, &header)?, texts: HashMap::new(), + labels_by_identity: HashMap::new(), first_start_ms: start_ms, }); written.bytes += files.active.as_ref().expect("set").segment.len(); @@ -427,6 +431,7 @@ impl ViewFiles { let active = files.active.as_mut().expect("set"); let mut texts = SegmentTexts { known: &active.texts, + labels_by_identity: &mut active.labels_by_identity, base: active.segment.text_count() as u32, new: Vec::new(), new_index: HashMap::new(), @@ -573,7 +578,13 @@ impl ViewFiles { let mut by_view = ViewIndex::new(); for (retention_ms, _, path) in paths { let Some((segment, heads)) = Segment::open(&path, &expected)? else { - set_aside(&path, "a segment of another plan, group or version")?; + set_aside( + &path, + &format!( + "a segment of another plan, group or format version (this data \ + plane reads version {FORMAT_VERSION})" + ), + )?; continue; }; for head in heads { @@ -1463,6 +1474,177 @@ mod tests { let _ = std::fs::remove_dir_all(&dir); } + /// A view of `series` series with the series identity, three label + /// columns and the value. `labels_match`: each label column holds its + /// series' label (`zone` is no label, so `""`); otherwise `job` holds + /// another text. Odd series are no input series (no `__name__`, as a + /// `rate` result): their identities are never interned. + fn labeled_window(end_ms: i64, series: usize, labels_match: bool) -> Batch { + let schema = Arc::new(Schema::with_time_index( + vec![ + Field::plain("ts", DataType::Timestamp, false), + Field::plain(PROMQL_SERIES_IDENTITY, DataType::Utf8, false), + Field::plain("job", DataType::Utf8, false), + Field::plain("region", DataType::Utf8, false), + Field::plain("zone", DataType::Utf8, false), + Field::plain("v", DataType::Float64, false), + ], + 0, + vec![], + )); + let rows = (0..series) + .map(|s| { + let mut labels: BTreeMap = [ + ("job".to_string(), format!("job-{}", s % 7)), + ("region".to_string(), format!("region-{}", s % 3)), + ("series".to_string(), format!("series-{s}")), + ] + .into(); + let identity: Arc = if s % 2 == 0 { + labels.insert("__name__".into(), "data".into()); + crate::series_ids::intern(&labels).identity.clone() + } else { + labels.insert("series".into(), format!("never-interned-{s}")); + serde_json::to_string(&labels).unwrap().into() + }; + let job = if labels_match { + labels["job"].clone() + } else { + format!("other-{}", s % 7) + }; + vec![ + Value::Timestamp(end_ms), + Value::Utf8(identity), + Value::Utf8(job.into()), + Value::Utf8(labels["region"].clone().into()), + Value::Utf8("".into()), + Value::Float64(s as f64), + ] + }) + .collect(); + Batch::try_new(schema, rows).unwrap() + } + + /// A text column holding its series' label is not stored: it reads + /// back, from the active segment and once sealed, from the series + /// identity, saving its 4-byte key per row; a text column that is not + /// its series' label is stored as before. + #[test] + fn label_columns_are_read_back_from_the_series_identity() { + let dir = segment_dir("identity-labels"); + let series = 300; + let (labeled, other) = ( + labeled_window(10, series, true), + labeled_window(10, series, false), + ); + let mut files = ViewFiles::open(&dir, 7, Duration::ZERO).unwrap(); + let written = files + .append( + 0, + (0, 10), + &[ + (1, std::slice::from_ref(&labeled)), + (2, std::slice::from_ref(&other)), + ], + ) + .unwrap(); + let (l1, l2) = (location_of(&written, 1), location_of(&written, 2)); + // `job` (other) is stored in view 2 only; `region` and `zone` in + // neither. + assert_eq!(l2.len() - l1.len(), series as u32 * 4); + for (location, batch, what) in [(&l1, &labeled, "labels"), (&l2, &other, "other")] { + let active = location.read(batch.schema(), ViewRead::Mmap).unwrap().0; + assert_same_rows(batch, &active, &format!("{what}, active segment")); + } + // A later window with series new to the active segment: the label + // values built for the first read are extended by the new texts. + let later = labeled_window(20, series + 50, true); + let later_written = files + .append(0, (10, 20), &[(1, std::slice::from_ref(&later))]) + .unwrap(); + let l3 = location_of(&later_written, 1); + assert!(!l3.is_sealed()); + let read = l3.read(later.schema(), ViewRead::Mmap).unwrap().0; + assert_same_rows(&later, &read, "labels, extended values"); + let read = l1.read(labeled.schema(), ViewRead::Mmap).unwrap().0; + assert_same_rows(&labeled, &read, "labels, first window after the extension"); + files.seal(0).unwrap(); + for how in [ViewRead::Mmap, ViewRead::Pread] { + for (location, batch, what) in [(&l1, &labeled, "labels"), (&l2, &other, "other")] { + let read = location.read(batch.schema(), how).unwrap().0; + assert_same_rows(batch, &read, &format!("{what}, sealed, {how:?}")); + } + } + // After a restart: the segment indexed from its file. + drop((written, l1, l2)); + drop(files); + let view = |id: u64| -> MaterializedView { + serde_json::from_value(serde_json::json!({ + "node_id": id, + "refresh": "at_ingestion", + "coverage": {"definition_id": format!("v{id}"), "selection": []}, + "inputs": {"materialized_views": []}, + "retention_ms": 1_000_000, + })) + .unwrap() + }; + let groups = vec![vec![ + (view(1), labeled.schema().clone()), + (view(2), other.schema().clone()), + ]]; + let index = ViewFiles::open(&dir, 7, Duration::ZERO) + .unwrap() + .index(&groups) + .unwrap(); + for (id, batch, what) in [(1, &labeled, "labels"), (2, &other, "other")] { + let location = &index[&id][0].1; + let read = location.read(batch.schema(), ViewRead::Mmap).unwrap().0; + assert_same_rows(batch, &read, &format!("{what}, indexed at startup")); + } + let _ = std::fs::remove_dir_all(&dir); + } + + /// A segment of an older format version is set aside at startup, not + /// read: its label columns are stored, not rebuilt. + #[test] + fn an_older_format_version_segment_is_set_aside() { + let dir = segment_dir("version"); + let batch = labeled_window(10, 3, true); + let view: MaterializedView = serde_json::from_value(serde_json::json!({ + "node_id": 1, + "refresh": "at_ingestion", + "coverage": {"definition_id": "v", "selection": []}, + "inputs": {"materialized_views": []}, + "retention_ms": 1_000_000, + })) + .unwrap(); + let groups = vec![vec![(view, batch.schema().clone())]]; + let mut files = ViewFiles::open(&dir, 7, Duration::ZERO).unwrap(); + let written = files + .append(0, (0, 10), &[(1, std::slice::from_ref(&batch))]) + .unwrap(); + let path = location_of(&written, 1).segment_path().to_path_buf(); + drop(written); + drop(files); + // The header frame's payload ends with the version (a MessagePack + // fixint): rewrite it as the previous one. + let mut bytes = std::fs::read(&path).unwrap(); + let header_len = u32::from_le_bytes(bytes[..4].try_into().unwrap()) as usize; + assert_eq!(u32::from(bytes[8 + header_len - 1]), FORMAT_VERSION); + bytes[8 + header_len - 1] = (FORMAT_VERSION - 1) as u8; + std::fs::write(&path, bytes).unwrap(); + let index = ViewFiles::open(&dir, 7, Duration::ZERO) + .unwrap() + .index(&groups) + .unwrap(); + assert!(index.get(&1).is_none_or(Vec::is_empty)); + assert!(!path.exists()); + let mut stale = path.into_os_string(); + stale.push(".stale"); + assert!(PathBuf::from(stale).exists()); + let _ = std::fs::remove_dir_all(&dir); + } + /// V19. A segment unlinked while a location still holds it stays /// readable (the mapping keeps its pages); no read can touch past the /// end of a mapped file. diff --git a/data_plane/src/segment.rs b/data_plane/src/segment.rs index 5414dd1d..304a12a7 100644 --- a/data_plane/src/segment.rs +++ b/data_plane/src/segment.rs @@ -11,9 +11,11 @@ //! //! A fragment holds one view's rows of one window by column, so a cold read //! decodes one (view, window) without the record's other views, and a -//! fixed-width column of a sealed (mapped) segment is used in place. +//! fixed-width column of a sealed (mapped) segment is used in place. A text +//! column holding each row's series label is not stored: it is rebuilt from +//! the series identity column. -use std::collections::HashMap; +use std::collections::{BTreeMap, HashMap}; use std::fs::File; use std::os::unix::fs::FileExt; use std::path::{Path, PathBuf}; @@ -22,14 +24,14 @@ use std::sync::atomic::{AtomicBool, AtomicI64, AtomicU64, Ordering}; use std::sync::{Arc, Mutex, OnceLock, RwLock, Weak}; use asap_executor::arrow::array::{ - Array, ArrayRef, DictionaryArray, PrimitiveArray, StringArray, UInt32Array, + Array, ArrayRef, DictionaryArray, PrimitiveArray, StringArray, StringBuilder, UInt32Array, }; use asap_executor::arrow::buffer::{BooleanBuffer, Buffer, NullBuffer, ScalarBuffer}; use asap_executor::arrow::datatypes::{ ArrowPrimitiveType, DataType as ArrowType, Float64Type, Int64Type, TimeUnit, TimestampMillisecondType, UInt32Type, }; -use asap_executor::planner::ir::schema::{DataType, FieldDataType, Schema}; +use asap_executor::planner::ir::schema::{DataType, FieldDataType, Schema, PROMQL_SERIES_IDENTITY}; use asap_executor::planner::plan::physical_asap_dag::PhysicalASAPNodeId; use asap_executor::summary_kernels::HydraCms; use asap_executor::values::{ @@ -39,9 +41,10 @@ use asap_executor::Error; use serde::{Deserialize, Serialize}; use crate::persist::{decode_stored_state, encode_state, Grids, StoredValue}; +use crate::series_ids::labels_of_identity; /// The view file format version these segments are. -pub const FORMAT_VERSION: u32 = 2; +pub const FORMAT_VERSION: u32 = 3; /// Frame kinds. const HEADER_FRAME: u32 = 0; @@ -62,6 +65,10 @@ const STATES: u32 = 6; /// data section, the states (each 8-byte aligned) in the second section; /// read in place, never rebuilt. const MAPPED_STATES: u32 = 7; +/// A text column whose every row holds its series identity's label of the +/// column's name (`""` when the series has none): no data, rebuilt on read +/// from the identity column, whose index is the descriptor's flags. +const IDENTITY_LABEL: u32 = 8; /// Flag: a timestamp column whose rows all hold one value, stored once. const CONSTANT: u32 = 1; /// Bytes of one column descriptor: kind, flags, data offset and length, @@ -178,6 +185,9 @@ pub struct Segment { /// Every text dictionary built, the current one and those a window /// read before a rebuild may still hold, to count each live one once. dictionaries_built: Mutex>>, + /// What [`IDENTITY_LABEL`] columns read from the segment are built + /// from ([`Segment::label_values`]). + identity_label_values: Mutex, /// The newest window end of its records. max_end_ms: AtomicI64, } @@ -239,6 +249,7 @@ impl Segment { texts: RwLock::new(Vec::new()), dictionary: Mutex::new(None), dictionaries_built: Mutex::default(), + identity_label_values: Mutex::default(), max_end_ms: AtomicI64::new(i64::MIN), })) } @@ -314,6 +325,7 @@ impl Segment { texts: RwLock::new(texts), dictionary: Mutex::new(None), dictionaries_built: Mutex::default(), + identity_label_values: Mutex::default(), max_end_ms: AtomicI64::new(max_end_ms), }), heads, @@ -459,10 +471,11 @@ impl Segment { .map_err(|e| Error::Invalid(format!("mapping {}: {e}", self.path.display()))) } - /// Bytes of its text dictionaries still in memory: each is one array + /// Bytes of its text dictionaries still in memory (the texts, and the + /// label values of [`IDENTITY_LABEL`] columns): each is one array /// shared by the windows read from the segment while it was current, - /// so it is counted once for the segment. Several only while the - /// active segment's dictionary grew under a window still held. + /// so it is counted once for the segment. Several of one kind only + /// while the active segment's texts grew under a window still held. pub(crate) fn dictionary_bytes(&self) -> usize { let mut built = self .dictionaries_built @@ -500,6 +513,89 @@ impl Segment { } } +/// Per label name, one value per segment text: that label of the text +/// taken as a series identity (`""` without it, or for a text that is no +/// identity). The dictionary of every [`IDENTITY_LABEL`] column of that +/// name, indexed by the rows' identity keys. +#[derive(Default)] +struct IdentityLabelValues { + values_by_label: HashMap, +} + +impl Segment { + /// The values of `label` for the texts with keys below `needed` taken + /// as series identities, as one array shared by the windows read from + /// the segment ([`IdentityLabelValues`]); extended by the texts added + /// since it was built, each parsed once per label. + fn label_values(&self, label: &str, needed: usize) -> Result { + let mut identity = self + .identity_label_values + .lock() + .unwrap_or_else(|e| e.into_inner()); + let built = identity.values_by_label.get(label).cloned(); + if let Some(values) = built.as_ref().filter(|v| v.len() >= needed) { + return Ok(values.clone()); + } + let built_len = built.as_ref().map_or(0, |values| values.len()); + // The texts added since, copied out so appends do not wait for + // their parsing. + let added: Vec> = { + let texts = self.texts.read().unwrap_or_else(|e| e.into_inner()); + if texts.len() < needed { + return Err(Error::Invalid(format!( + "{}: a text key past the segment's texts", + self.path.display() + ))); + } + texts[built_len..].to_vec() + }; + let built = built + .as_ref() + .map(|values| values.as_any().downcast_ref::()) + .unwrap_or_default(); + let added: Vec = added + .iter() + .map(|text| { + parse_identity(text) + .and_then(|labels| labels.get(label).cloned()) + .unwrap_or_default() + }) + .collect(); + let mut builder = StringBuilder::with_capacity( + built_len + added.len(), + built.map_or(0, |built| built.value_data().len()) + + added.iter().map(String::len).sum::(), + ); + for value in built.into_iter().flat_map(|built| built.iter()) { + builder.append_value(value.unwrap_or_default()); + } + for value in &added { + builder.append_value(value); + } + let values: ArrayRef = Arc::new(builder.finish()); + identity + .values_by_label + .insert(label.to_string(), values.clone()); + self.dictionaries_built + .lock() + .unwrap_or_else(|e| e.into_inner()) + .push(Arc::downgrade(&values)); + Ok(values) + } +} + +/// The labels of the series whose identity text is `text`: an interned +/// series' own, else parsed (and not kept); `None` for a text that is no +/// label set's JSON. The labels the writer's `labels_of_identity` gives, +/// without its process-wide cache (a segment's texts outlive no reader). +fn parse_identity(text: &str) -> Option>> { + match crate::series_ids::by_identity(text) { + Some(series) => Some(series.labels().clone()), + None if text.starts_with('{') => serde_json::from_str(text).ok().map(Arc::new), + None => None, + } +} + /// The head of a record frame's payload. fn record_head(payload: &[u8]) -> Option { let n = payload.len(); @@ -666,8 +762,15 @@ pub(crate) struct SegmentTexts<'a> { pub base: u32, pub new: Vec>, pub new_index: HashMap, u32>, + /// The labels of each series identity the segment's records held, by + /// identity text: looked up in the interner once per segment, not once + /// per row of every window. + pub labels_by_identity: &'a mut LabelsByIdentity, } +/// Per series identity text, its labels (`None`: no label set's JSON). +pub(crate) type LabelsByIdentity = HashMap, Option>>>; + impl SegmentTexts<'_> { fn key(&mut self, text: &Arc) -> u32 { if let Some(&key) = self.known.get(text).or_else(|| self.new_index.get(text)) { @@ -679,6 +782,18 @@ impl SegmentTexts<'_> { key } + /// The labels of the series whose identity text is `identity` + /// ([`labels_of_identity`]), cached for the segment. + fn identity_labels(&mut self, identity: &Arc) -> Option>> { + if let Some(labels) = self.labels_by_identity.get(identity) { + return labels.clone(); + } + let labels = labels_of_identity(identity); + self.labels_by_identity + .insert(identity.clone(), labels.clone()); + labels + } + /// Drops the new texts after the first `mark` (a fragment left out). pub fn forget_after(&mut self, mark: usize) { for text in self.new.drain(mark..) { @@ -723,6 +838,7 @@ pub(crate) fn encode_fragment( out.extend_from_slice(&(columns as u32).to_le_bytes()); let descriptors_at = out.len(); out.resize(descriptors_at + columns * DESCRIPTOR_BYTES, 0); + let identity_labels = IdentityLabels::of(schema, rows, texts); for (column, field) in schema.fields.iter().enumerate() { let values = rows.iter().map(|row| &row[column]); let nulls: Vec = rows @@ -732,82 +848,98 @@ pub(crate) fn encode_fragment( // The second section: the validity bitmap, or a mapped state // column's states. let mut second: Option> = None; - let (kind, mut flags, data): (u32, u32, Vec) = match &field.dtype { - FieldDataType::Plain(DataType::Utf8) => { - let mut data = Vec::with_capacity(rows.len() * 4); - for value in values { - let key = match value { - Value::Utf8(text) => texts.key(text), - _ => 0, - }; - data.extend_from_slice(&key.to_le_bytes()); + // The identity column, when this column holds its series' label. + let label_of_identity_column = identity_labels + .as_ref() + .filter(|labels| { + field.dtype == FieldDataType::Plain(DataType::Utf8) + && labels.holds_label(rows, column, &field.name) + }) + .map(|labels| labels.column as u32); + let (kind, mut flags, data): (u32, u32, Vec) = if let Some(identity_column) = + label_of_identity_column + { + (IDENTITY_LABEL, identity_column, Vec::new()) + } else { + match &field.dtype { + FieldDataType::Plain(DataType::Utf8) => { + let mut data = Vec::with_capacity(rows.len() * 4); + for value in values { + let key = match value { + Value::Utf8(text) => texts.key(text), + _ => 0, + }; + data.extend_from_slice(&key.to_le_bytes()); + } + (TEXT, 0, data) } - (TEXT, 0, data) - } - FieldDataType::Plain(DataType::Float64) => { - let mut data = Vec::with_capacity(rows.len() * 8); - for value in values { - let v = match value { - Value::Float64(v) => *v, - _ => 0.0, - }; - data.extend_from_slice(&v.to_le_bytes()); + FieldDataType::Plain(DataType::Float64) => { + let mut data = Vec::with_capacity(rows.len() * 8); + for value in values { + let v = match value { + Value::Float64(v) => *v, + _ => 0.0, + }; + data.extend_from_slice(&v.to_le_bytes()); + } + (FLOAT64, 0, data) } - (FLOAT64, 0, data) - } - FieldDataType::Plain(DataType::Int64) => { - let mut data = Vec::with_capacity(rows.len() * 8); - for value in values { - let v = match value { - Value::Int64(v) => *v, - _ => 0, - }; - data.extend_from_slice(&v.to_le_bytes()); + FieldDataType::Plain(DataType::Int64) => { + let mut data = Vec::with_capacity(rows.len() * 8); + for value in values { + let v = match value { + Value::Int64(v) => *v, + _ => 0, + }; + data.extend_from_slice(&v.to_le_bytes()); + } + (INT64, 0, data) } - (INT64, 0, data) - } - FieldDataType::Plain(DataType::Timestamp) => { - let times: Vec = values - .map(|value| match value { - Value::Timestamp(t) => *t, - _ => 0, - }) - .collect(); - let constant = !times.is_empty() - && !nulls.iter().any(|&n| n) - && times.iter().all(|&t| t == times[0]); - let data: Vec = if constant { - times[0].to_le_bytes().to_vec() - } else { - times.iter().flat_map(|t| t.to_le_bytes()).collect() - }; - (TIMESTAMP, if constant { CONSTANT } else { 0 }, data) - } - FieldDataType::Plain(_) => { - let values: Vec<&Value> = values.collect(); - (GENERIC, 0, rmp_serde::to_vec(&values).ok()?) - } - family if family_has_mapped_form(family) && mapped_states(rows, column).is_some() => { - let (offsets, states) = mapped_states(rows, column).expect("checked"); - second = Some(states); - (MAPPED_STATES, 0, offsets) - } - _ => { - // States: u32 offsets[rows + 1], then each state's stored bytes. - let mut offsets = Vec::with_capacity(rows.len() + 1); - let mut bytes = Vec::new(); - offsets.push(0u32); - for value in values { - let Value::Summary { state, .. } = value else { - return None; + FieldDataType::Plain(DataType::Timestamp) => { + let times: Vec = values + .map(|value| match value { + Value::Timestamp(t) => *t, + _ => 0, + }) + .collect(); + let constant = !times.is_empty() + && !nulls.iter().any(|&n| n) + && times.iter().all(|&t| t == times[0]); + let data: Vec = if constant { + times[0].to_le_bytes().to_vec() + } else { + times.iter().flat_map(|t| t.to_le_bytes()).collect() }; - let stored = encode_state(state.as_ref(), grids)?; - bytes.extend(rmp_serde::to_vec(&stored).ok()?); - offsets.push(u32::try_from(bytes.len()).ok()?); + (TIMESTAMP, if constant { CONSTANT } else { 0 }, data) + } + FieldDataType::Plain(_) => { + let values: Vec<&Value> = values.collect(); + (GENERIC, 0, rmp_serde::to_vec(&values).ok()?) + } + family + if family_has_mapped_form(family) && mapped_states(rows, column).is_some() => + { + let (offsets, states) = mapped_states(rows, column).expect("checked"); + second = Some(states); + (MAPPED_STATES, 0, offsets) + } + _ => { + // States: u32 offsets[rows + 1], then each state's stored bytes. + let mut offsets = Vec::with_capacity(rows.len() + 1); + let mut bytes = Vec::new(); + offsets.push(0u32); + for value in values { + let Value::Summary { state, .. } = value else { + return None; + }; + let stored = encode_state(state.as_ref(), grids)?; + bytes.extend(rmp_serde::to_vec(&stored).ok()?); + offsets.push(u32::try_from(bytes.len()).ok()?); + } + let mut data: Vec = offsets.iter().flat_map(|o| o.to_le_bytes()).collect(); + data.extend(bytes); + (STATES, 0, data) } - let mut data: Vec = offsets.iter().flat_map(|o| o.to_le_bytes()).collect(); - data.extend(bytes); - (STATES, 0, data) } }; let (data_offset, data_len) = section(&mut out, &data); @@ -838,6 +970,61 @@ pub(crate) fn encode_fragment( Some(out) } +/// The labels of each row's series, from the series identity column, for +/// telling which text columns are its labels ([`IDENTITY_LABEL`]). +struct IdentityLabels { + /// The series identity column's index. + column: usize, + /// Each row's labels; `None` when a row's identity is none. + by_row: Vec>>>, +} + +impl IdentityLabels { + /// `None` when there are no rows, or `schema` has no series identity + /// text column or no other text column. + fn of(schema: &Schema, rows: &[Vec], texts: &mut SegmentTexts) -> Option { + if rows.is_empty() { + return None; + } + let is_text = |dtype: &FieldDataType| *dtype == FieldDataType::Plain(DataType::Utf8); + let column = schema + .fields + .iter() + .position(|field| field.name == PROMQL_SERIES_IDENTITY && is_text(&field.dtype))?; + if !schema + .fields + .iter() + .enumerate() + .any(|(index, field)| index != column && is_text(&field.dtype)) + { + return None; + } + let by_row = rows + .iter() + .map(|row| match &row[column] { + Value::Utf8(identity) => texts.identity_labels(identity), + _ => None, + }) + .collect(); + Some(Self { column, by_row }) + } + + /// Whether every row's `column` is its series' label `name` (`""` + /// without it), so the column need not be stored. + fn holds_label(&self, rows: &[Vec], column: usize, name: &str) -> bool { + column != self.column + && rows + .iter() + .zip(&self.by_row) + .all(|(row, labels)| match (&row[column], labels) { + (Value::Utf8(text), Some(labels)) => { + **text == *labels.get(name).map_or("", String::as_str) + } + _ => false, + }) + } +} + /// Column `column` of `rows` in the executor's mapped state layout: the /// `u32` offsets (`rows + 1`) and the states back to back, each padded to 8 /// bytes; `None` when a state has no mapped form. @@ -912,6 +1099,35 @@ fn primitive( PrimitiveArray::::try_new(values, nulls).map_err(|e| Error::Invalid(e.to_string())) } +/// One column's descriptor in a fragment: its kind and flags, and its data +/// and second sections (offset and length, inside the fragment). +struct Descriptor { + kind: u32, + flags: u32, + data: (usize, usize), + valid: (usize, usize), +} + +/// Column `column`'s descriptor in fragment `bytes`; damaged when a +/// section lies past the fragment's end. +fn descriptor(bytes: &[u8], column: usize) -> Result { + let at = 8 + column * DESCRIPTOR_BYTES; + let kind_flags = word(bytes, at)?; + let section = |at: usize| -> Result<(usize, usize), Error> { + let (offset, len) = (word(bytes, at)? as usize, word(bytes, at + 8)? as usize); + if offset.checked_add(len).is_none_or(|end| end > bytes.len()) { + return Err(damaged()); + } + Ok((offset, len)) + }; + Ok(Descriptor { + kind: (kind_flags & 0xffff_ffff) as u32, + flags: (kind_flags >> 32) as u32, + data: section(at + 8)?, + valid: section(at + 24)?, + }) +} + /// The fragment in `source` as one batch of `schema`, and the bytes of its /// mapped state columns ([`WindowLocation::read`]). fn decode_fragment( @@ -932,28 +1148,12 @@ fn decode_fragment( let mut out = Vec::with_capacity(columns); let mut mapped_state_bytes = 0; for (column, field) in schema.fields.iter().enumerate() { - let at = 8 + column * DESCRIPTOR_BYTES; - let kind_flags = word(bytes, at)?; - let (kind, flags) = ((kind_flags & 0xffff_ffff) as u32, (kind_flags >> 32) as u32); - let data = ( - word(bytes, at + 8)? as usize, - word(bytes, at + 16)? as usize, - ); - let valid = ( - word(bytes, at + 24)? as usize, - word(bytes, at + 32)? as usize, - ); - if data - .0 - .checked_add(data.1) - .is_none_or(|end| end > bytes.len()) - || valid - .0 - .checked_add(valid.1) - .is_none_or(|end| end > bytes.len()) - { - return Err(damaged()); - } + let Descriptor { + kind, + flags, + data, + valid, + } = descriptor(bytes, column)?; let nulls = if valid.1 == 0 || kind == MAPPED_STATES { None } else { @@ -974,6 +1174,25 @@ fn decode_fragment( .map_err(|e| Error::Invalid(e.to_string()))?, ) } + IDENTITY_LABEL => { + // The identity column's keys, as this column's keys into + // the label's values by text. + let identity_column = flags as usize; + if identity_column >= columns { + return Err(damaged()); + } + let identity = descriptor(bytes, identity_column)?; + if identity.kind != TEXT || identity.valid.1 != 0 || data.1 != 0 || valid.1 != 0 { + return Err(damaged()); + } + let keys = primitive::(source, identity.data, rows, None)?; + let needed = keys.values().iter().max().map_or(0, |&k| k as usize + 1); + let values = segment.label_values(&field.name, needed)?; + Arc::new( + DictionaryArray::::try_new(keys, values) + .map_err(|e| Error::Invalid(e.to_string()))?, + ) + } FLOAT64 => Arc::new(primitive::(source, data, rows, nulls)?), INT64 => Arc::new(primitive::(source, data, rows, nulls)?), TIMESTAMP if flags & CONSTANT != 0 => { diff --git a/data_plane/src/series_ids.rs b/data_plane/src/series_ids.rs index f67f56e8..a453a236 100644 --- a/data_plane/src/series_ids.rs +++ b/data_plane/src/series_ids.rs @@ -204,3 +204,13 @@ pub fn result_labels(identity: &str) -> Result>, se .or_insert(labels) .clone()) } + +/// The labels of the series whose identity text is `identity`: an +/// interned series' own (no parse), else parsed once ([`result_labels`]); +/// `None` when `identity` is not a label set's JSON. +pub fn labels_of_identity(identity: &str) -> Option>> { + match by_identity(identity) { + Some(series) => Some(series.labels().clone()), + None => result_labels(identity).ok(), + } +} diff --git a/docs/design/tiered-view-storage.md b/docs/design/tiered-view-storage.md index 1d51e29b..0111d785 100644 --- a/docs/design/tiered-view-storage.md +++ b/docs/design/tiered-view-storage.md @@ -204,7 +204,7 @@ it is deleted whole. A segment holds the existing framing (a little-endian 8-byte boundary (zero padding) so fixed-width columns can be borrowed in place: -- a header frame (MessagePack): plan hash, group, **format version 2**, +- a header frame (MessagePack): plan hash, group, **format version 3**, and the segment start; - one record frame per refreshed window. Its head is a small MessagePack map, followed by the parts it points at: @@ -221,8 +221,11 @@ laid out by column (all offsets relative to the fragment, every section 8-byte aligned): ``` -Fragment = { rows: u32, columns: [(kind, offset, len)] } +Fragment = { rows: u32, columns: [(kind, flags, offset, len)] } text column u32 keys into the segment's dictionary (+ validity bitmap) + identity label nothing: a text column whose every row holds its series + identity's label of the column's name ("" without it); + read back from the identity column (its index in flags) timestamp column i64 per row, or one i64 when every row has the same value (the window end, today stored once per row) plain column f64 / i64 / u64 / bool per row (+ validity bitmap) @@ -245,6 +248,17 @@ segment, and a segment's first use of a text writes it again. Deleting an old segment then never strands a later one's keys. At 10k series and about 96 B per identity this costs about 1–2 MB per segment. +**Label columns from the series identity.** A text column whose every row +holds its series' label of the column's name (the `job`, `region`, … +columns a per-series view carries) is not written: the fragment marks it +`identity label`, and its label values are not added to the segment's +texts. A read takes the identity column's keys as its keys, into a +per-segment array per label name holding that label of each segment text +taken as a series identity (from the interned series, else parsed from the +identity's JSON once per label name per segment). At 10k series that array is about +100–150 KB per label name per segment, counted with the segment's +dictionary; on disk it saves 4 B per row per label column. + Index: `WindowLocation { segment: Arc, offset: u64, len: u32 }` points at a view's fragment. It lives in the `ViewWindow` in memory (about 40 B per (view, window)); there is no index file. At startup the index is @@ -646,7 +660,8 @@ here changes the Planner. `pread` only for the active segment and as a fallback option. B3 still compares the two. - **Hot policy:** recency (CLOCK, idle time, byte budget). -- **Fragment encoding:** columnar, with format version 2. +- **Fragment encoding:** columnar, with format version 3; label columns + are read back from the series identity, not stored. - **No cgroup limit:** no budget, plus idle eviction. - **Old view files:** renamed `*.stale`. - **Revision (pending approval):** states are used from the mapping