Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 7 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -244,14 +244,19 @@ Collector views (docs/design/collector-sketch-ingest.md): with
`asap_sketches --print-capabilities`) and `--emit-collector-views cv.json`,
the control plane also writes the part of the plan the collector runs: the views it builds instead of the data plane, the plan id, which metrics the
data plane still reads raw (the collector stops forwarding the others), and
the collector's declared window close delay, and
prints why each other node is not on the collector. `--plan plan.json` reads a plan written
before instead of planning `--workload`. The data
plane started with `--collector-views cv.json` does not build those views:
their states arrive from the collector on `/v1/metrics`, in metrics named
`<metric>.asap_view.<node id>`, and each window is committed when the
request carrying its states ends; later states of a committed window merge
into it within retention (`asap_collector_states_*` on `/metrics`). It
refuses a file of another plan.
into it within retention (`asap_collector_states_*` on `/metrics`). Each
state is a record of its series' lineage in its window (a full, then
deltas, numbered per collector instance): a repeated record is ignored, and
a delta whose base is missing marks the window incomplete, so queries
reading it are forwarded. A stopped collector's windows close after its
declared delay plus 2 s. It refuses a file of another plan.

`--cost-inputs costs.json` replaces the Planner's default `CostInputs`
(Stage 3's cost model, resource speed and measured operation costs); an
Expand Down
90 changes: 75 additions & 15 deletions crates/adapters/ingest/otlp/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -62,14 +62,18 @@
//! view states, not samples (docs/design/collector-sketch-ingest.md, §4):
//! each data point is one series' state in the window `(start_time_unix_nano,
//! time_unix_nano]`, its ASAPv1 bytes in the `sketch.envelope` attribute and
//! its sample count in `count`. Resource, scope and the other point
//! attributes give the series' labels as for a sample, `__name__` being the
//! metric's name before `.asap_view.`. They are decoded into
//! [`Decoded::view_states`]; the state bytes are not read. A request whose
//! view identity is missing in part or does not parse, whose view metric is
//! not named `<source metric>.asap_view.<node_id>`, or that has a
//! `sketch.envelope` point outside such a metric, is refused
//! ([`OtlpError::ViewIdentity`]).
//! its sample count in `count`, and its place in its lineage in
//! `asap.sequence`, `asap.state_kind` and `asap.base_sequence` (§8; the
//! sending collector's `asap.producer_epoch` is metric metadata). Resource,
//! scope and the other point attributes give the series' labels as for a
//! sample, `__name__` being the metric's name before `.asap_view.`. They are
//! decoded into [`Decoded::view_states`]; the state bytes are not read. A
//! request whose view identity or producer epoch is missing in part or does
//! not parse, whose view metric is not named
//! `<source metric>.asap_view.<node_id>`, with a state point whose lineage
//! attributes are missing or disagree (a full is sequence 0, a delta's base
//! is its sequence less one), or that has a `sketch.envelope` point outside
//! such a metric, is refused ([`OtlpError::ViewIdentity`]).
//!
//! # Decoding
//!
Expand All @@ -85,9 +89,12 @@ use std::collections::btree_map::Entry;
use std::collections::{BTreeMap, HashMap};
use std::io::Read;

use common::view_identity::{ENVELOPE_ATTRIBUTE, NAME_INFIX, NODE_ID, PLAN_ID, VIEW_STATE_KEY};
use common::view_identity::{
BASE_SEQUENCE, ENVELOPE_ATTRIBUTE, NAME_INFIX, NODE_ID, PLAN_ID, PRODUCER_EPOCH, SEQUENCE,
STATE_KIND, VIEW_STATE_KEY,
};
use common::{
CollectorSeriesStates, CollectorViewStates, LabelSet, ViewStateBatch, ViewStateKey,
CollectorSeriesStates, CollectorViewStates, LabelSet, StateKind, ViewStateBatch, ViewStateKey,
ViewStateRecord,
};
use prometheus_remote_write::series_cache::SeriesCache;
Expand Down Expand Up @@ -677,13 +684,14 @@ impl<B: SampleBuilder> Walk<'_, B> {
/// for a metric whose metadata names no view (none of the identity
/// keys).
fn view_of(&mut self, name: &str, metadata: &[&[u8]]) -> Result<Option<usize>, OtlpError> {
let (mut plan_id, mut node_id, mut key) = (None, None, None);
let (mut plan_id, mut node_id, mut key, mut epoch) = (None, None, None, None);
for entry in metadata {
let (entry_key, value) = key_value(entry)?;
match entry_key {
PLAN_ID => plan_id = Some(value.text().into_owned()),
NODE_ID => node_id = Some(value.text().into_owned()),
VIEW_STATE_KEY => key = Some(value.text().into_owned()),
PRODUCER_EPOCH => epoch = Some(value.text().into_owned()),
_ => {}
}
}
Expand All @@ -704,6 +712,10 @@ impl<B: SampleBuilder> Walk<'_, B> {
.map_err(|e| refused(format!("{NODE_ID}: {e}")))?;
let key: ViewStateKey = serde_json::from_str(&key.ok_or_else(|| missing(VIEW_STATE_KEY))?)
.map_err(|e| refused(format!("{VIEW_STATE_KEY}: {e}")))?;
let producer_epoch: u64 = epoch
.ok_or_else(|| missing(PRODUCER_EPOCH))?
.parse()
.map_err(|e| refused(format!("{PRODUCER_EPOCH}: {e}")))?;
if !name
.strip_suffix(&node_id.to_string())
.is_some_and(|source| source.ends_with(NAME_INFIX) && source.len() > NAME_INFIX.len())
Expand All @@ -713,16 +725,19 @@ impl<B: SampleBuilder> Walk<'_, B> {
)));
}
let views = &mut self.decoded.view_states.views;
if let Some(index) = views
.iter()
.position(|view| view.node_id == node_id && view.plan_id == plan_id && view.key == key)
{
if let Some(index) = views.iter().position(|view| {
view.node_id == node_id
&& view.producer_epoch == producer_epoch
&& view.plan_id == plan_id
&& view.key == key
}) {
return Ok(Some(index));
}
views.push(CollectorViewStates {
plan_id,
node_id,
key,
producer_epoch,
series: Vec::new(),
});
Ok(Some(views.len() - 1))
Expand All @@ -743,6 +758,7 @@ impl<B: SampleBuilder> Walk<'_, B> {
let (attributes_field, flags_field) = kind.attributes_and_flags_fields();
let (mut start_nanos, mut time_nanos, mut count, mut flags) = (0u64, 0u64, 0u64, 0u64);
let mut envelope = None;
let (mut sequence, mut state_kind, mut base) = (None, None, None);
let mut pairs = Vec::new();
let mut reader = Reader::new(point);
while let Some((field, value)) = reader.field()? {
Expand All @@ -758,6 +774,9 @@ impl<B: SampleBuilder> Walk<'_, B> {
reason: format!("{ENVELOPE_ATTRIBUTE} is not bytes"),
})
}
(SEQUENCE, value) => sequence = Some(value.text().into_owned()),
(STATE_KIND, value) => state_kind = Some(value.text().into_owned()),
(BASE_SEQUENCE, value) => base = Some(value.text().into_owned()),
pair => pairs.push(pair),
}
}
Expand All @@ -779,6 +798,11 @@ impl<B: SampleBuilder> Walk<'_, B> {
reason: format!("a point has no {ENVELOPE_ATTRIBUTE} bytes"),
});
};
let (sequence, kind) =
lineage(sequence, state_kind, base).map_err(|reason| OtlpError::ViewIdentity {
metric: name.to_string(),
reason,
})?;
if self.decoded.samples.len() >= self.max_points {
return Err(OtlpError::TooManyPoints(self.point_limit));
}
Expand All @@ -803,11 +827,47 @@ impl<B: SampleBuilder> Walk<'_, B> {
window_end_ms: (time_nanos / 1_000_000) as i64,
asapv1: envelope.to_vec(),
sample_count: count,
sequence,
kind,
});
Ok(())
}
}

/// A state point's place in its lineage from its `asap.sequence`,
/// `asap.state_kind` and `asap.base_sequence` texts: a full is sequence 0
/// with no base, a delta's base is its sequence less one. Why not, else.
fn lineage(
sequence: Option<String>,
kind: Option<String>,
base: Option<String>,
) -> Result<(u64, StateKind), String> {
let number = |key: &str, text: Option<String>| -> Result<u64, String> {
text.ok_or_else(|| format!("a state point has no {key}"))?
.parse()
.map_err(|e| format!("{key}: {e}"))
};
let sequence = number(SEQUENCE, sequence)?;
match (kind.as_deref(), sequence, base) {
(Some("full"), 0, None) => Ok((0, StateKind::Full)),
(Some("delta"), 1.., base) => {
let base_sequence = number(BASE_SEQUENCE, base)?;
if base_sequence.checked_add(1) != Some(sequence) {
return Err(format!(
"a delta's {BASE_SEQUENCE} {base_sequence} is not {SEQUENCE} {sequence} less one"
));
}
Ok((sequence, StateKind::Delta { base_sequence }))
}
(Some("full"), ..) => Err(format!(
"a full state has {SEQUENCE} {sequence} or a {BASE_SEQUENCE}; it is sequence 0 alone"
)),
(Some("delta"), ..) => Err(format!("a delta has {SEQUENCE} 0")),
(Some(other), ..) => Err(format!("{STATE_KIND} {other:?} is not full or delta")),
(None, ..) => Err(format!("a state point has no {STATE_KIND}")),
}
}

/// The error of a `sketch.envelope` point under a metric naming no view.
#[cold]
fn not_a_view(name: &str) -> OtlpError {
Expand Down
72 changes: 69 additions & 3 deletions crates/adapters/ingest/otlp/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -892,23 +892,28 @@ fn consecutive_points_share_their_series() {
const VIEW_KEY: &str = r#"{"definition_id":"5597d603bdf9f1a148d7c7e5344c1a97","window":{"tumbling":{"width_ms":5000}},"logical_properties":{"parameters":{"DDSketch":{"alpha":0.05}}}}"#;
const WINDOW_END_MS: u64 = 1_700_000_005_000;

/// The metadata naming view `node` of plan `p1` with key `key`.
/// The metadata naming view `node` of plan `p1` with key `key`, sent by
/// collector instance (producer epoch) 7.
fn view_metadata(node: i64, key: &str) -> Vec<KeyValue> {
vec![
text("asap.plan_id", "p1"),
attribute("asap.node_id", any_value::Value::IntValue(node)),
text("asap.view_state_key", key),
text("asap.producer_epoch", "7"),
]
}

/// A state point of the window ending at `WINDOW_END_MS`, as the collector
/// exports one: the series' attributes, then `sketch.envelope`.
/// exports one: the series' attributes, `sketch.envelope`, and its place
/// in its lineage (a full, sequence 0).
fn state_point(attributes: Vec<KeyValue>, envelope: &[u8], count: u64) -> SummaryDataPoint {
let mut attributes = attributes;
attributes.push(attribute(
"sketch.envelope",
any_value::Value::BytesValue(envelope.to_vec()),
));
attributes.push(attribute("asap.sequence", any_value::Value::IntValue(0)));
attributes.push(text("asap.state_kind", "full"));
SummaryDataPoint {
attributes,
start_time_unix_nano: (WINDOW_END_MS - 5_000) * 1_000_000,
Expand Down Expand Up @@ -986,13 +991,16 @@ fn a_view_metrics_points_are_states_labeled_as_raw_samples() {
plan_id: "p1".into(),
node_id: 1,
key,
producer_epoch: 7,
series: vec![CollectorSeriesStates {
labels: raw_labels.into_iter().collect(),
records: vec![ViewStateRecord {
window_start_ms: WINDOW_END_MS as i64 - 5_000,
window_end_ms: WINDOW_END_MS as i64,
asapv1: vec![1, 2, 3],
sample_count: 50,
sequence: 0,
kind: StateKind::Full,
}],
}],
}],
Expand Down Expand Up @@ -1065,7 +1073,9 @@ fn a_bad_view_identity_refuses_the_request() {
.contains("asap.view_state_key")
);
let mut no_envelope = point();
no_envelope[0].attributes.pop();
no_envelope[0]
.attributes
.retain(|attribute| attribute.key != "sketch.envelope");
assert!(refused(view_metric(
"data",
1,
Expand All @@ -1082,4 +1092,60 @@ fn a_bad_view_identity_refuses_the_request() {
}),
);
assert!(refused(unnamed).contains("names no view"));
let mut no_epoch = view_metadata(1, VIEW_KEY);
no_epoch.pop();
assert!(refused(view_metric("data", 1, no_epoch, point())).contains("asap.producer_epoch"));
}

/// A state point's lineage attributes: a delta carries its sequence and
/// base, and none of the three is a label. Missing ones, a full that is
/// not sequence 0, a delta whose base is not its sequence less one, and an
/// unknown kind refuse the request.
#[test]
fn lineage_attributes_are_decoded_and_checked() {
let delta = |sequence: i64, base: Option<i64>, kind: &str| {
let mut point = state_point(vec![text("region", "a")], &[1], 1);
point.attributes.truncate(2);
point.attributes.push(attribute(
"asap.sequence",
any_value::Value::IntValue(sequence),
));
point.attributes.push(text("asap.state_kind", kind));
if let Some(base) = base {
point.attributes.push(attribute(
"asap.base_sequence",
any_value::Value::IntValue(base),
));
}
view_metric("data", 1, view_metadata(1, VIEW_KEY), vec![point])
};
let views = decoded(&encode(&request(vec![delta(3, Some(2), "delta")])))
.unwrap()
.view_states
.views;
let series = &views[0].series[0];
assert_eq!(views[0].producer_epoch, 7);
assert_eq!(
(series.records[0].sequence, series.records[0].kind),
(3, StateKind::Delta { base_sequence: 2 })
);
assert!(series.labels.keys().all(|name| !name.starts_with("asap")));
let refused = |metric: Metric| match decoded(&encode(&request(vec![metric]))) {
Err(OtlpError::ViewIdentity { reason, .. }) => reason,
other => panic!("not refused: {other:?}"),
};
assert!(refused(delta(3, Some(1), "delta")).contains("less one"));
assert!(refused(delta(3, None, "delta")).contains("asap.base_sequence"));
assert!(refused(delta(0, None, "delta")).contains("sequence 0"));
assert!(refused(delta(2, None, "full")).contains("sequence 0 alone"));
assert!(refused(delta(0, None, "partial")).contains("not full or delta"));
let mut no_sequence = state_point(vec![text("region", "a")], &[1], 1);
no_sequence.attributes.truncate(2);
assert!(refused(view_metric(
"data",
1,
view_metadata(1, VIEW_KEY),
vec![no_sequence]
))
.contains("asap.sequence"));
}
5 changes: 5 additions & 0 deletions crates/common/src/collector_views_file.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,11 @@ pub struct CollectorViewsFile {
/// reads its raw samples (a `Scan` of it feeds a node off the
/// collector, or runs at query time).
pub backend_reads_raw: BTreeMap<String, bool>,
/// The collector's declared `window_close_delay_ms` (its capabilities),
/// copied: the longest time after a window's end before it emits the
/// window. The data plane closes a stopped collector's windows on its
/// clock after it plus a skew allowance.
pub window_close_delay_ms: u64,
/// The collector views: the sub-DAG's outputs whose states the backend
/// ingests.
pub outputs: Vec<PhysicalASAPNodeId>,
Expand Down
4 changes: 2 additions & 2 deletions crates/common/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,8 @@ pub use query_result::{
ResultSample, Sample, Table, TableValue,
};
pub use view_states::{
view_identity, CollectorSeriesStates, CollectorViewStates, ViewStateBatch, ViewStateKey,
ViewStateRecord,
view_identity, CollectorSeriesStates, CollectorViewStates, StateKind, ViewStateBatch,
ViewStateKey, ViewStateRecord,
};

/// The largest time, in milliseconds either side of the epoch, the data
Expand Down
31 changes: 29 additions & 2 deletions crates/common/src/view_states.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,9 @@ pub struct CollectorViewStates {
/// The view's `MaterializedView::view_state_key()`, as the collector
/// read it from its copy of the plan.
pub key: ViewStateKey,
/// The collector instance that sent the states (`asap.producer_epoch`):
/// a restarted collector has a new epoch, and new lineages (§8).
pub producer_epoch: u64,
pub series: Vec<CollectorSeriesStates>,
}

Expand All @@ -44,15 +47,31 @@ pub struct CollectorSeriesStates {
pub records: Vec<ViewStateRecord>,
}

/// One state of one window `(window_start_ms, window_end_ms]` (Record tier).
/// One state of one window `(window_start_ms, window_end_ms]` (Record tier):
/// a record of its `(view, series, window)` lineage (§8).
#[derive(Debug, Clone, PartialEq)]
pub struct ViewStateRecord {
pub window_start_ms: i64,
pub window_end_ms: i64,
/// The full state, as `asap_sketchlib`'s ASAPv1 bytes.
/// `asap_sketchlib`'s ASAPv1 bytes: for a full, the lineage's state so
/// far; for a delta, the state of the samples since its base.
pub asapv1: Vec<u8>,
/// Samples folded into the state, as the collector counted them.
pub sample_count: u64,
/// Its place in its lineage (`asap.sequence`): 0 for a full.
pub sequence: u64,
/// `asap.state_kind`, with `asap.base_sequence` for a delta.
pub kind: StateKind,
}

/// Whether a record starts its lineage or applies onto its base.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum StateKind {
/// Sequence 0: the lineage's state so far.
Full,
/// The state of the samples since record `base_sequence`, which is
/// `sequence - 1`.
Delta { base_sequence: u64 },
}

/// The view identity's metric metadata keys and the reserved part of a
Expand All @@ -65,4 +84,12 @@ pub mod view_identity {
pub const NAME_INFIX: &str = ".asap_view.";
/// The data point attribute holding a state's ASAPv1 bytes.
pub const ENVELOPE_ATTRIBUTE: &str = "sketch.envelope";
/// Metric metadata: the sending collector instance, decimal text.
pub const PRODUCER_EPOCH: &str = "asap.producer_epoch";
/// Data point attributes: the record's place in its lineage.
pub const SEQUENCE: &str = "asap.sequence";
/// `"full"` or `"delta"`.
pub const STATE_KIND: &str = "asap.state_kind";
/// A delta's base: the sequence it applies onto.
pub const BASE_SEQUENCE: &str = "asap.base_sequence";
}
Loading