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: 6 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -253,9 +253,12 @@ their states arrive from the collector on `/v1/metrics`, in metrics named
request carrying its states ends; later states of a committed window merge
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
deltas, numbered per collector instance, in a binary lineage frame in
front of the state's bytes): a repeated record is ignored, a delta that
comes before its base is held until the base comes, and a base still
missing after the collector's declared close delay plus 2 s marks the window
incomplete, so queries reading it are forwarded (also after a restart:
the mark is kept in the view files). 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`
Expand Down
67 changes: 15 additions & 52 deletions crates/adapters/ingest/otlp/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -62,18 +62,20 @@
//! 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`, 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,
//! behind its lineage frame (its sequence, and full or delta: §8,
//! [`common::unframe_lineage`]; the sending collector's
//! `asap.producer_epoch` is metric metadata), 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 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`]).
//! frame is missing (a bare ASAPv1 state), of another version, or
//! disagrees with itself (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 @@ -90,12 +92,11 @@ use std::collections::{BTreeMap, HashMap};
use std::io::Read;

use common::view_identity::{
BASE_SEQUENCE, ENVELOPE_ATTRIBUTE, NAME_INFIX, NODE_ID, PLAN_ID, PRODUCER_EPOCH, SEQUENCE,
STATE_KIND, VIEW_STATE_KEY,
ENVELOPE_ATTRIBUTE, NAME_INFIX, NODE_ID, PLAN_ID, PRODUCER_EPOCH, VIEW_STATE_KEY,
};
use common::{
CollectorSeriesStates, CollectorViewStates, LabelSet, StateKind, ViewStateBatch, ViewStateKey,
ViewStateRecord,
unframe_lineage, CollectorSeriesStates, CollectorViewStates, LabelSet, ViewStateBatch,
ViewStateKey, ViewStateRecord,
};
use prometheus_remote_write::series_cache::SeriesCache;
use prometheus_remote_write::wire::{Reader, Value};
Expand Down Expand Up @@ -758,7 +759,6 @@ 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 @@ -774,9 +774,6 @@ 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 @@ -798,10 +795,10 @@ 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 {
let (sequence, kind, asapv1) =
unframe_lineage(envelope).map_err(|reason| OtlpError::ViewIdentity {
metric: name.to_string(),
reason,
reason: format!("{ENVELOPE_ATTRIBUTE}: {reason}"),
})?;
if self.decoded.samples.len() >= self.max_points {
return Err(OtlpError::TooManyPoints(self.point_limit));
Expand All @@ -825,7 +822,7 @@ impl<B: SampleBuilder> Walk<'_, B> {
series[index].records.push(ViewStateRecord {
window_start_ms: (start_nanos / 1_000_000) as i64,
window_end_ms: (time_nanos / 1_000_000) as i64,
asapv1: envelope.to_vec(),
asapv1: asapv1.to_vec(),
sample_count: count,
sequence,
kind,
Expand All @@ -834,40 +831,6 @@ impl<B: SampleBuilder> Walk<'_, B> {
}
}

/// 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
73 changes: 30 additions & 43 deletions crates/adapters/ingest/otlp/src/tests.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use super::*;
use common::StateKind;
use proto::collector::metrics::v1::{ExportMetricsServiceRequest, ExportMetricsServiceResponse};
use proto::common::v1::{any_value, AnyValue, InstrumentationScope, KeyValue};
use proto::metrics::v1::{
Expand Down Expand Up @@ -904,16 +905,19 @@ fn view_metadata(node: i64, key: &str) -> Vec<KeyValue> {
}

/// A state point of the window ending at `WINDOW_END_MS`, as the collector
/// 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 {
/// exports one: the series' attributes and `sketch.envelope`, the state
/// `asapv1` behind a full's lineage frame (sequence 0).
fn state_point(attributes: Vec<KeyValue>, asapv1: &[u8], count: u64) -> SummaryDataPoint {
framed_point(attributes, &common::frame_lineage(0, asapv1), count)
}

/// [`state_point`] with `envelope` as the `sketch.envelope` bytes as is.
fn framed_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 @@ -1097,55 +1101,38 @@ fn a_bad_view_identity_refuses_the_request() {
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.
/// A state point's lineage frame: a delta carries its sequence and base,
/// the state's bytes are those behind the frame, and the frame is no label.
/// A bare ASAPv1 state (a collector from before the frame), another frame
/// version and a frame that disagrees with itself 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),
));
}
fn lineage_frames_are_decoded_and_checked() {
let with_envelope = |envelope: Vec<u8>| {
let point = framed_point(vec![text("region", "a")], &envelope, 1);
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 asapv1 = b"ASAPv1\x01state".to_vec();
let views = decoded(&encode(&request(vec![with_envelope(
common::frame_lineage(3, &asapv1),
)])))
.unwrap()
.view_states
.views;
let series = &views[0].series[0];
assert_eq!(views[0].producer_epoch, 7);
let record = &series.records[0];
assert_eq!(
(series.records[0].sequence, series.records[0].kind),
(record.sequence, record.kind),
(3, StateKind::Delta { base_sequence: 2 })
);
assert_eq!(record.asapv1, asapv1);
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"));
assert!(refused(with_envelope(asapv1.clone())).contains("without a lineage frame"));
assert!(refused(with_envelope(vec![0xA2, 0, 0])).contains("version 2"));
assert!(refused(with_envelope(vec![0xA1, 0x01, 0x03, 0x01])).contains("base 1"));
assert!(refused(with_envelope(vec![0xA1, 0x00, 0x02])).contains("a full has sequence 2"));
}
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, StateKind, ViewStateBatch,
ViewStateKey, ViewStateRecord,
frame_lineage, unframe_lineage, view_identity, CollectorSeriesStates, CollectorViewStates,
StateKind, ViewStateBatch, ViewStateKey, ViewStateRecord, LINEAGE_FRAME_V1,
};

/// The largest time, in milliseconds either side of the epoch, the data
Expand Down
Loading