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
140 changes: 94 additions & 46 deletions data_plane/examples/packets_bench.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,9 +34,10 @@ use data_plane::remote_write::{encode, Label, Sample, TimeSeries, WriteRequest};
use data_plane::{router, DataPlane};
use tower::ServiceExt;

/// Event time of the stream's epoch: 2023-11-14, a multiple of 10 s, in
/// Event time of the stream's epoch: 2023-11-14, a whole hour (windows of
/// every width up to an hour end on it), in
/// the past (the data plane drops samples from the future).
const EPOCH_MS: i64 = 1_700_000_000_000;
const EPOCH_MS: i64 = 1_699_999_200_000;
const REQUEST_MS: i64 = 250;
const ROUND_MS: i64 = 10_000;

Expand Down Expand Up @@ -154,6 +155,8 @@ async fn main() {
no_forward: true,
..EngineOptions::default()
};
// Every row from the epoch on is fed: the first windows are complete.
options.ingestion.stream_start_ms = Some(EPOCH_MS);
if let Some(threads) = env_usize("INGEST_THREADS") {
options.ingest_threads = threads;
}
Expand Down Expand Up @@ -261,60 +264,105 @@ async fn main() {
(rows.len() * std::mem::size_of::<Packet>()) as f64 / 1048576.0,
);

// Rounds, 10 s apart, the last at the barrier.
let schedule = IntentSchedule::per_clock_from_intent_plan(&plan, intent_name)
.unwrap()
.remove(0);
let intent =
IntentLoop::new(schedule, BindMode::ParameterSlot, Duration::from_secs(600)).unwrap();
// Rounds `ROUND_STEP_MS` apart (10 s by default), the last at the
// barrier; the first clock's queries, or every clock's (`ALL_CLOCKS=1`).
let step_ms = std::env::var("ROUND_STEP_MS").map_or(ROUND_MS, |v| v.parse().unwrap());
let mut schedules = IntentSchedule::per_clock_from_intent_plan(&plan, intent_name).unwrap();
if std::env::var("ALL_CLOCKS").is_err() {
schedules.truncate(1);
}
let intents: Vec<IntentLoop> = schedules
.into_iter()
.map(|s| IntentLoop::new(s, BindMode::ParameterSlot, Duration::from_secs(600)).unwrap())
.collect();
let mut answers = std::env::var("ANSWERS_OUT")
.ok()
.map(|path| std::fs::File::create(path).unwrap());
let mut exact_failures = 0;
for round in 0..rounds {
let time_ms = EPOCH_MS + feed_ms - (rounds - 1 - round) * ROUND_MS;
let cpu_before = thread_cpu_seconds();
let record = intent.run_round(&state.engine, round as u64, time_ms).await;
let cpu_after = thread_cpu_seconds();
let cpu: f64 = cpu_after
.iter()
.map(|(name, after)| after - cpu_before.get(name).copied().unwrap_or(0.0))
.sum();
let latencies: Vec<String> = record
.queries
.iter()
.map(|q| {
format!(
"{} {:?} {} rows {}",
q.query_id,
q.status,
q.latency_ms.map_or("-".into(), |l| format!("{l:.1} ms")),
q.answer.len()
)
})
.collect();
println!(
"round {round} at +{} s: {:.1} ms, cpu {cpu:.2} s; {}",
(time_ms - EPOCH_MS) / 1000,
record.duration_ms,
latencies.join("; ")
);
if let Some(file) = answers.as_mut() {
for q in &record.queries {
let mut rows: Vec<String> = q
let time_ms = EPOCH_MS + feed_ms - (rounds - 1 - round) * step_ms;
for intent in &intents {
let cpu_before = thread_cpu_seconds();
let record = intent.run_round(&state.engine, round as u64, time_ms).await;
let cpu_after = thread_cpu_seconds();
let cpu: f64 = cpu_after
.iter()
.map(|(name, after)| after - cpu_before.get(name).copied().unwrap_or(0.0))
.sum();
let latencies: Vec<String> = record
.queries
.iter()
.map(|q| {
format!(
"{} {:?} {} rows {}{}",
q.query_id,
q.status,
q.latency_ms.map_or("-".into(), |l| format!("{l:.1} ms")),
q.answer.len(),
q.error
.as_deref()
.map_or(String::new(), |e| format!(" ERROR {e}"))
)
})
.collect();
println!(
"round {round} at +{} s: {:.1} ms, cpu {cpu:.2} s; {}",
(time_ms - EPOCH_MS) / 1000,
record.duration_ms,
latencies.join("; ")
);
// Exact check of the per-proto byte sums (`proto_<window>`).
for q in record
.queries
.iter()
.filter(|q| q.query_id.starts_with("proto_"))
{
let window_ms = match q.query_id.rsplit('_').next() {
Some("1m") => 60_000,
Some("5m") => 300_000,
Some("1h") => 3_600_000,
_ => continue,
};
let (start, end) = (time_ms - EPOCH_MS - window_ms, time_ms - EPOCH_MS);
let mut exact: std::collections::BTreeMap<String, f64> = Default::default();
for p in rows.iter().filter(|p| start < p.ts_ms && p.ts_ms <= end) {
*exact.entry(p.proto.to_string()).or_default() += p.bytes as f64;
}
let got: std::collections::BTreeMap<String, f64> = q
.answer
.iter()
.map(|r| format!("{:?} {:?}", r.labels, r.value))
.map(|r| (r.labels.get("proto").cloned().unwrap_or_default(), r.value))
.collect();
rows.sort();
let line = serde_json::json!({
"round": round, "time_ms": time_ms, "query": q.query_id,
"status": format!("{:?}", q.status), "bindings": format!("{:?}", q.bindings),
"rows": rows,
});
writeln!(file, "{line}").unwrap();
if got != exact {
exact_failures += 1;
println!(
" EXACT MISMATCH {} at +{} s: got {got:?} exact {exact:?}",
q.query_id,
end / 1000
);
} else {
println!(" exact ok {} at +{} s", q.query_id, end / 1000);
}
}
if let Some(file) = answers.as_mut() {
for q in &record.queries {
let mut rows: Vec<String> = q
.answer
.iter()
.map(|r| format!("{:?} {:?}", r.labels, r.value))
.collect();
rows.sort();
let line = serde_json::json!({
"round": round, "time_ms": time_ms, "query": q.query_id,
"status": format!("{:?}", q.status), "bindings": format!("{:?}", q.bindings),
"rows": rows,
});
writeln!(file, "{line}").unwrap();
}
}
}
}
println!("exact mismatches: {exact_failures}");
let (peak_mib, _) = rss_mib();
println!("RSS peak after rounds {peak_mib:.0} MiB");
state.engine.stop();
Expand Down
71 changes: 62 additions & 9 deletions data_plane/src/engine.rs
Original file line number Diff line number Diff line change
Expand Up @@ -721,7 +721,7 @@ impl EngineHandle {
pub async fn evaluate(&self, query: String, time_ms: i64) -> Result<Answer, Unanswered> {
let started = std::time::Instant::now();
let metrics = self.shared.metrics.query(&query);
let answer = self.run_on_worker(query, time_ms, None, None).await;
let answer = self.run_on_worker(query, time_ms, None, false, None).await;
if let Some(metrics) = metrics {
metrics.latency.observe(started.elapsed().as_secs_f64());
}
Expand All @@ -737,7 +737,55 @@ impl EngineHandle {
time_ms: i64,
slots: Vec<SlotBinding>,
) -> Result<Answer, Unanswered> {
self.run_on_worker(query, time_ms, None, Some(slots)).await
self.run_on_worker(query, time_ms, None, false, Some(slots))
.await
}

/// [`Self::evaluate`] (with `slots`: [`Self::evaluate_bound`]) over
/// `snapshot`, which every query of an intent round reads.
pub async fn evaluate_in(
&self,
query: String,
time_ms: i64,
snapshot: Arc<Snapshot>,
slots: Option<Vec<SlotBinding>>,
) -> Result<Answer, Unanswered> {
self.run_on_worker(query, time_ms, Some(snapshot), false, slots)
.await
}

/// The store an intent round at `time_ms` reads, pinned once for all
/// its queries: a query that runs late in a slow round reads the
/// samples and windows that were kept when the round started, not a
/// store already evicted past its window's start. With `max_wait`,
/// first waits (at most that long) until every sample at or before
/// `time_ms` has arrived (the watermark has passed it) and every window
/// ending by then is refreshed, so a round never answers from data its
/// producer has not delivered yet. Returns the snapshot and how long it
/// waited.
pub async fn pin_round_snapshot(
&self,
time_ms: i64,
max_wait: std::time::Duration,
) -> (Arc<Snapshot>, std::time::Duration) {
let started = std::time::Instant::now();
if !max_wait.is_zero() {
let deadline = tokio::time::Instant::now() + max_wait;
let mut arrived = false;
while tokio::time::Instant::now() < deadline {
if self.shared.published.watermark_ms() >= Some(time_ms) {
arrived = true;
break;
}
tokio::time::sleep(std::time::Duration::from_millis(20)).await;
}
// The watermark has closed every window ending by `time_ms`;
// the barrier only waits for their refreshes to commit.
if arrived {
let _ = tokio::time::timeout_at(deadline, self.advance_watermark(time_ms)).await;
}
}
(self.snapshot(), started.elapsed())
}

/// Evaluates one step of a range query over `snapshot`, which every
Expand All @@ -751,7 +799,7 @@ impl EngineHandle {
time_ms: i64,
snapshot: Arc<Snapshot>,
) -> Result<Answer, Unanswered> {
self.run_on_worker(query, time_ms, Some(snapshot), None)
self.run_on_worker(query, time_ms, Some(snapshot), true, None)
.await
}

Expand All @@ -770,7 +818,8 @@ impl EngineHandle {
&self,
query: String,
time_ms: i64,
range_step: Option<Arc<Snapshot>>,
snapshot: Option<Arc<Snapshot>>,
range_step: bool,
bound: Option<Vec<SlotBinding>>,
) -> Result<Answer, Unanswered> {
let stopped = || Unanswered::Execution("the query workers have stopped".into());
Expand All @@ -779,6 +828,7 @@ impl EngineHandle {
.send(QueryJob {
query,
time_ms,
snapshot,
range_step,
bound,
reply,
Expand Down Expand Up @@ -935,8 +985,11 @@ fn admit(queued: u64, count: u64, max_queued: u64) -> Result<u64, IngestError> {
struct QueryJob {
query: String,
time_ms: i64,
/// One step of a range query, and the snapshot every step reads.
range_step: Option<Arc<Snapshot>>,
/// The snapshot the run reads (every step of a range query, every
/// query of an intent round); `None`: the newest when the run starts.
snapshot: Option<Arc<Snapshot>>,
/// One step of a range query (for the metrics).
range_step: bool,
/// An intent query's holes bound to these values
/// ([`QueryEngine::evaluate_bound`]); `None`: as planned.
bound: Option<Vec<SlotBinding>>,
Expand Down Expand Up @@ -986,7 +1039,7 @@ fn spawn_query_workers(
// A bug in one run must not take the worker down: it
// answers that run with the error and keeps serving.
let answer = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
let snapshot = match &job.range_step {
let snapshot = match &job.snapshot {
Some(snapshot) => snapshot.clone(),
None => Arc::new(query.snapshot(&shared.published)),
};
Expand All @@ -1008,8 +1061,8 @@ fn spawn_query_workers(
});
if let Some(metrics) = shared.metrics.query(&job.query) {
match job.range_step {
None => metrics.run.record(timer),
Some(_) => metrics.range_step_run.record(timer),
false => metrics.run.record(timer),
true => metrics.range_step_run.record(timer),
};
}
let _ = job.reply.send(answer);
Expand Down
Loading