-
Notifications
You must be signed in to change notification settings - Fork 161
Expand file tree
/
Copy pathcharts.rs
More file actions
617 lines (592 loc) · 20.2 KB
/
charts.rs
File metadata and controls
617 lines (592 loc) · 20.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright the Vortex contributors
//! Per-chart payload assembly + the shared `SeriesAccumulator` glue.
//!
//! `chart_payload` dispatches on [`ChartKey`] to one of five
//! `collect_*_chart` functions, each of which runs one SQL query against
//! its fact table, threads the rows through a `SeriesAccumulator`, and
//! returns a [`ChartResponse`].
use std::collections::BTreeMap;
use std::sync::Arc;
use anyhow::Context as _;
use anyhow::Result;
use duckdb::Connection;
use duckdb::ToSql;
use duckdb::params_from_iter;
use super::dto::ChartResponse;
use super::dto::CommitPoint;
use super::dto::GroupChartsResponse;
use super::dto::NamedChartResponse;
use super::dto::SeriesTag;
use super::dto::UnitKind;
use super::groups::collect_groups;
use super::window::CommitWindow;
use crate::slug::ChartKey;
use crate::slug::GroupKey;
/// Build the JSON payload for one chart by key. This is the shared
/// implementation behind `GET /api/chart/{slug}`, the inline `<script>` JSON
/// rendered into the HTML pages, and `collect_group_charts`.
///
/// `window` caps the number of recent commits returned. `y` / `mode` are not
/// inputs here — they're rendering hints applied client-side, so the SQL is
/// unaffected and the cached payload is identical across hint values.
pub(crate) fn chart_payload(
conn: &Connection,
key: &ChartKey,
window: &CommitWindow,
) -> Result<Option<ChartResponse>> {
match key {
ChartKey::QueryMeasurement {
dataset,
dataset_variant,
scale_factor,
storage,
query_idx,
} => collect_query_chart(
conn,
dataset,
dataset_variant,
scale_factor,
storage,
*query_idx,
window,
),
ChartKey::CompressionTime {
dataset,
dataset_variant,
} => collect_compression_time_chart(conn, dataset, dataset_variant, window),
ChartKey::CompressionSize {
dataset,
dataset_variant,
} => collect_compression_size_chart(conn, dataset, dataset_variant, window),
ChartKey::RandomAccess { dataset } => collect_random_access_chart(conn, dataset, window),
ChartKey::VectorSearch {
dataset,
layout,
threshold,
} => collect_vector_search_chart(conn, dataset, layout, *threshold, window),
}
}
/// Collect every chart inside one group. Returns `None` if the group has no
/// data at all (callers should render a 404).
///
/// TODO(#7812): this re-runs the entire [`collect_groups`] discovery pass
/// per call before fetching each chart, so the landing page is
/// O(groups * charts_per_group) DB queries plus the discovery scan. Fine
/// for the current dataset; tracked for the refactor that collapses it
/// into a single query.
pub(crate) fn collect_group_charts(
conn: &Connection,
key: &GroupKey,
window: &CommitWindow,
) -> Result<Option<GroupChartsResponse>> {
let groups = collect_groups(conn)?;
let group = groups.into_iter().find(|g| g.slug == key.to_slug());
let Some(group) = group else {
return Ok(None);
};
let mut charts = Vec::with_capacity(group.charts.len());
for link in group.charts {
let chart_key = ChartKey::from_slug(&link.slug)
.with_context(|| format!("invalid chart slug in group: {}", link.slug))?;
let Some(chart) = chart_payload(conn, &chart_key, window)? else {
continue;
};
charts.push(NamedChartResponse {
name: link.name,
slug: link.slug,
chart: Arc::new(chart),
});
}
if charts.is_empty() {
return Ok(None);
}
Ok(Some(GroupChartsResponse {
name: group.name,
summary: group.summary,
description: group.description,
charts,
}))
}
/// Time series rows are gathered keyed by `(commit_sha, series_key)` and then
/// reshaped into the `commits[] / series{}` response shape.
///
/// **The accumulator is seeded with the canonical commits-in-window list
/// before any fact rows are recorded.** That list is the chart's x-axis: it
/// includes every commit in the requested [`CommitWindow`] whose timestamp
/// is at or after the earliest commit that has a row in the fact table for
/// this chart. Commits with zero rows in the fact table still appear in
/// `commits[]`; their per-series slot stays `None` and renders as a visible
/// gap in the line. Without seeding, commits absent from the fact table
/// would be silently dropped from the chart's x-axis, making partial-coverage
/// runs (a benchmark crashed; a series only runs nightly) look like
/// continuous lines when they should break.
struct SeriesAccumulator {
commits: Vec<CommitPoint>,
commit_index: BTreeMap<String, usize>,
series: BTreeMap<String, Vec<Option<f64>>>,
tags: BTreeMap<String, SeriesTag>,
}
impl SeriesAccumulator {
fn new() -> Self {
Self {
commits: Vec::new(),
commit_index: BTreeMap::new(),
series: BTreeMap::new(),
tags: BTreeMap::new(),
}
}
/// Seed the chart's commit list, oldest-first by timestamp. Must be
/// called before [`Self::record`] / [`Self::tag`] so series allocations
/// are sized correctly and missing-value slots stay `None`.
fn seed_commits(&mut self, commits: Vec<CommitPoint>) {
self.commit_index.clear();
for (i, c) in commits.iter().enumerate() {
self.commit_index.insert(c.sha.clone(), i);
}
self.commits = commits;
}
/// Index of `sha` in the seeded commits list, or `None` if the sha
/// was not part of the window. Returning `None` rather than panicking
/// keeps `collect_*_chart` resilient to an unseeded sha showing up in
/// the fact table (e.g. a transient race in concurrent ingest); we
/// just drop the row.
fn commit_idx(&self, sha: &str) -> Option<usize> {
self.commit_index.get(sha).copied()
}
fn record(&mut self, series_key: &str, commit_idx: usize, value: f64) {
let total_commits = self.commits.len();
let entry = self
.series
.entry(series_key.to_string())
.or_insert_with(|| vec![None; total_commits]);
if entry.len() < total_commits {
entry.resize(total_commits, None);
}
entry[commit_idx] = Some(value);
}
/// Record an engine/format classification for a series. Repeat calls with
/// the same `series_key` are idempotent — every row of a given series
/// shares the same engine/format by construction of the SQL.
fn tag(&mut self, series_key: &str, engine: Option<&str>, format: Option<&str>) {
if engine.is_none() && format.is_none() {
return;
}
let entry = self.tags.entry(series_key.to_string()).or_default();
if let Some(e) = engine {
entry.engine = Some(e.to_string());
}
if let Some(f) = format {
entry.format = Some(f.to_string());
}
}
fn finish(self, display_name: String, unit_kind: UnitKind) -> ChartResponse {
let total = self.commits.len();
let mut series_map = serde_json::Map::new();
for (k, mut v) in self.series {
if v.len() < total {
v.resize(total, None);
}
series_map.insert(k, serde_json::to_value(v).expect("Vec<Option<f64>>"));
}
ChartResponse {
display_name,
unit_kind,
commits: self.commits,
series: series_map,
series_meta: self.tags,
}
}
}
/// Resolve a chart's x-axis: every commit in the requested commit-window
/// whose timestamp is at or after the earliest commit that has a row in the
/// fact table for this chart. Returns the list oldest-first; an empty list
/// means the fact table has no rows at all for this chart, and the caller
/// should return `None` (404).
///
/// `earliest_subquery` is spliced into the outer query as
/// `c.timestamp >= ({earliest_subquery})`, so it must SELECT a single
/// `MIN(timestamp)` row scoped to this chart's fact-table predicates. Its
/// bound parameters appear first in `subquery_binds`; the window's `LIMIT`
/// placeholder is appended after.
///
/// The bounds matter: without the timestamp lower bound a chart's x-axis
/// would include every commit ever, including pre-history before the
/// benchmark even existed. Without the [`CommitWindow`] cap a chart with a
/// long history would always render the entire timeline regardless of the
/// caller's `?n=` request.
fn seeded_commits_in_window(
conn: &Connection,
earliest_subquery: &str,
subquery_binds: Vec<Box<dyn ToSql>>,
window: &CommitWindow,
) -> Result<Vec<CommitPoint>> {
let sql = format!(
r#"
SELECT c.commit_sha,
CAST(c.timestamp AS VARCHAR),
COALESCE(c.message, ''),
c.url
FROM commits c
WHERE c.timestamp >= ({earliest_subquery}){window_filter}
ORDER BY c.timestamp ASC
"#,
window_filter = window.sql_filter(),
);
let mut stmt = conn.prepare(&sql)?;
let mut binds = subquery_binds;
push_window_limit(&mut binds, window);
let rows = stmt.query_map(params_from_iter(binds.iter()), |row| {
Ok(CommitPoint {
sha: row.get(0)?,
timestamp: row.get(1)?,
message: row.get(2)?,
url: row.get(3)?,
})
})?;
let out: Vec<CommitPoint> = rows.collect::<Result<_, _>>()?;
Ok(out)
}
/// Append the commit-window `LIMIT` bind value to a parameter list, when the
/// window is bounded. Pairs with [`CommitWindow::sql_filter`] which emits
/// the matching `?` placeholder.
fn push_window_limit(binds: &mut Vec<Box<dyn ToSql>>, window: &CommitWindow) {
if let Some(limit) = window.limit_param() {
binds.push(Box::new(limit));
}
}
fn collect_query_chart(
conn: &Connection,
dataset: &str,
dataset_variant: &Option<String>,
scale_factor: &Option<String>,
storage: &str,
query_idx: i32,
window: &CommitWindow,
) -> Result<Option<ChartResponse>> {
// x-axis pre-pass. `IS NOT DISTINCT FROM` matches NULL == NULL so charts
// with a NULL `dataset_variant` or `scale_factor` still pin the right
// earliest-commit timestamp.
let seeded = seeded_commits_in_window(
conn,
"SELECT MIN(c2.timestamp) \
FROM query_measurements q2 \
JOIN commits c2 ON c2.commit_sha = q2.commit_sha \
WHERE q2.dataset = ? \
AND q2.dataset_variant IS NOT DISTINCT FROM ? \
AND q2.scale_factor IS NOT DISTINCT FROM ? \
AND q2.storage = ? \
AND q2.query_idx = ?",
vec![
Box::new(dataset.to_string()),
Box::new(dataset_variant.clone()),
Box::new(scale_factor.clone()),
Box::new(storage.to_string()),
Box::new(query_idx),
],
window,
)?;
if seeded.is_empty() {
return Ok(None);
}
let mut acc = SeriesAccumulator::new();
acc.seed_commits(seeded);
let sql = format!(
r#"
SELECT q.commit_sha,
q.engine, q.format, q.value_ns
FROM query_measurements q
JOIN commits c USING (commit_sha)
WHERE q.dataset = ?
AND q.dataset_variant IS NOT DISTINCT FROM ?
AND q.scale_factor IS NOT DISTINCT FROM ?
AND q.storage = ?
AND q.query_idx = ?{filter}
ORDER BY c.timestamp, q.engine, q.format
"#,
filter = window.sql_filter(),
);
let mut stmt = conn.prepare(&sql)?;
let mut binds: Vec<Box<dyn ToSql>> = vec![
Box::new(dataset.to_string()),
Box::new(dataset_variant.clone()),
Box::new(scale_factor.clone()),
Box::new(storage.to_string()),
Box::new(query_idx),
];
push_window_limit(&mut binds, window);
let rows = stmt.query_map(params_from_iter(binds.iter()), |row| {
Ok((
row.get::<_, String>(0)?,
row.get::<_, String>(1)?,
row.get::<_, String>(2)?,
row.get::<_, i64>(3)?,
))
})?;
for row in rows {
let (sha, engine, format, value_ns) = row?;
let Some(idx) = acc.commit_idx(&sha) else {
continue;
};
let series_key = format!("{engine}:{format}");
acc.record(&series_key, idx, value_ns as f64);
acc.tag(&series_key, Some(&engine), Some(&format));
}
let mut name = dataset.to_string();
if let Some(v) = dataset_variant {
name.push('/');
name.push_str(v);
}
if let Some(sf) = scale_factor {
name.push_str(" sf=");
name.push_str(sf);
}
name.push_str(&format!(" Q{query_idx} [{storage}]"));
Ok(Some(acc.finish(name, UnitKind::TimeNs)))
}
fn collect_compression_time_chart(
conn: &Connection,
dataset: &str,
dataset_variant: &Option<String>,
window: &CommitWindow,
) -> Result<Option<ChartResponse>> {
let seeded = seeded_commits_in_window(
conn,
"SELECT MIN(c2.timestamp) \
FROM compression_times t2 \
JOIN commits c2 ON c2.commit_sha = t2.commit_sha \
WHERE t2.dataset = ? \
AND t2.dataset_variant IS NOT DISTINCT FROM ?",
vec![
Box::new(dataset.to_string()),
Box::new(dataset_variant.clone()),
],
window,
)?;
if seeded.is_empty() {
return Ok(None);
}
let mut acc = SeriesAccumulator::new();
acc.seed_commits(seeded);
let sql = format!(
r#"
SELECT t.commit_sha,
t.format, t.op, t.value_ns
FROM compression_times t
JOIN commits c USING (commit_sha)
WHERE t.dataset = ?
AND t.dataset_variant IS NOT DISTINCT FROM ?{filter}
ORDER BY c.timestamp, t.format, t.op
"#,
filter = window.sql_filter(),
);
let mut stmt = conn.prepare(&sql)?;
let mut binds: Vec<Box<dyn ToSql>> = vec![
Box::new(dataset.to_string()),
Box::new(dataset_variant.clone()),
];
push_window_limit(&mut binds, window);
let rows = stmt.query_map(params_from_iter(binds.iter()), |row| {
Ok((
row.get::<_, String>(0)?,
row.get::<_, String>(1)?,
row.get::<_, String>(2)?,
row.get::<_, i64>(3)?,
))
})?;
for row in rows {
let (sha, format, op, value_ns) = row?;
let Some(idx) = acc.commit_idx(&sha) else {
continue;
};
let series_key = format!("{format}:{op}");
acc.record(&series_key, idx, value_ns as f64);
acc.tag(&series_key, None, Some(&format));
}
let mut name = dataset.to_string();
if let Some(v) = dataset_variant {
name.push('/');
name.push_str(v);
}
Ok(Some(acc.finish(name, UnitKind::TimeNs)))
}
fn collect_compression_size_chart(
conn: &Connection,
dataset: &str,
dataset_variant: &Option<String>,
window: &CommitWindow,
) -> Result<Option<ChartResponse>> {
let seeded = seeded_commits_in_window(
conn,
"SELECT MIN(c2.timestamp) \
FROM compression_sizes s2 \
JOIN commits c2 ON c2.commit_sha = s2.commit_sha \
WHERE s2.dataset = ? \
AND s2.dataset_variant IS NOT DISTINCT FROM ?",
vec![
Box::new(dataset.to_string()),
Box::new(dataset_variant.clone()),
],
window,
)?;
if seeded.is_empty() {
return Ok(None);
}
let mut acc = SeriesAccumulator::new();
acc.seed_commits(seeded);
let sql = format!(
r#"
SELECT s.commit_sha,
s.format, s.value_bytes
FROM compression_sizes s
JOIN commits c USING (commit_sha)
WHERE s.dataset = ?
AND s.dataset_variant IS NOT DISTINCT FROM ?{filter}
ORDER BY c.timestamp, s.format
"#,
filter = window.sql_filter(),
);
let mut stmt = conn.prepare(&sql)?;
let mut binds: Vec<Box<dyn ToSql>> = vec![
Box::new(dataset.to_string()),
Box::new(dataset_variant.clone()),
];
push_window_limit(&mut binds, window);
let rows = stmt.query_map(params_from_iter(binds.iter()), |row| {
Ok((
row.get::<_, String>(0)?,
row.get::<_, String>(1)?,
row.get::<_, i64>(2)?,
))
})?;
for row in rows {
let (sha, format, value_bytes) = row?;
let Some(idx) = acc.commit_idx(&sha) else {
continue;
};
acc.record(&format, idx, value_bytes as f64);
acc.tag(&format, None, Some(&format));
}
let mut name = dataset.to_string();
if let Some(v) = dataset_variant {
name.push('/');
name.push_str(v);
}
Ok(Some(acc.finish(name, UnitKind::Bytes)))
}
fn collect_random_access_chart(
conn: &Connection,
dataset: &str,
window: &CommitWindow,
) -> Result<Option<ChartResponse>> {
let seeded = seeded_commits_in_window(
conn,
"SELECT MIN(c2.timestamp) \
FROM random_access_times r2 \
JOIN commits c2 ON c2.commit_sha = r2.commit_sha \
WHERE r2.dataset = ?",
vec![Box::new(dataset.to_string())],
window,
)?;
if seeded.is_empty() {
return Ok(None);
}
let mut acc = SeriesAccumulator::new();
acc.seed_commits(seeded);
let sql = format!(
r#"
SELECT r.commit_sha,
r.format, r.value_ns
FROM random_access_times r
JOIN commits c USING (commit_sha)
WHERE r.dataset = ?{filter}
ORDER BY c.timestamp, r.format
"#,
filter = window.sql_filter(),
);
let mut stmt = conn.prepare(&sql)?;
let mut binds: Vec<Box<dyn ToSql>> = vec![Box::new(dataset.to_string())];
push_window_limit(&mut binds, window);
let rows = stmt.query_map(params_from_iter(binds.iter()), |row| {
Ok((
row.get::<_, String>(0)?,
row.get::<_, String>(1)?,
row.get::<_, i64>(2)?,
))
})?;
for row in rows {
let (sha, format, value_ns) = row?;
let Some(idx) = acc.commit_idx(&sha) else {
continue;
};
acc.record(&format, idx, value_ns as f64);
acc.tag(&format, None, Some(&format));
}
Ok(Some(acc.finish(dataset.to_string(), UnitKind::TimeNs)))
}
fn collect_vector_search_chart(
conn: &Connection,
dataset: &str,
layout: &str,
threshold: f64,
window: &CommitWindow,
) -> Result<Option<ChartResponse>> {
let seeded = seeded_commits_in_window(
conn,
"SELECT MIN(c2.timestamp) \
FROM vector_search_runs v2 \
JOIN commits c2 ON c2.commit_sha = v2.commit_sha \
WHERE v2.dataset = ? \
AND v2.layout = ? \
AND v2.threshold = ?",
vec![
Box::new(dataset.to_string()),
Box::new(layout.to_string()),
Box::new(threshold),
],
window,
)?;
if seeded.is_empty() {
return Ok(None);
}
let mut acc = SeriesAccumulator::new();
acc.seed_commits(seeded);
let sql = format!(
r#"
SELECT v.commit_sha,
v.flavor, v.value_ns
FROM vector_search_runs v
JOIN commits c USING (commit_sha)
WHERE v.dataset = ?
AND v.layout = ?
AND v.threshold = ?{filter}
ORDER BY c.timestamp, v.flavor
"#,
filter = window.sql_filter(),
);
let mut stmt = conn.prepare(&sql)?;
let mut binds: Vec<Box<dyn ToSql>> = vec![
Box::new(dataset.to_string()),
Box::new(layout.to_string()),
Box::new(threshold),
];
push_window_limit(&mut binds, window);
let rows = stmt.query_map(params_from_iter(binds.iter()), |row| {
Ok((
row.get::<_, String>(0)?,
row.get::<_, String>(1)?,
row.get::<_, i64>(2)?,
))
})?;
for row in rows {
let (sha, flavor, value_ns) = row?;
let Some(idx) = acc.commit_idx(&sha) else {
continue;
};
acc.record(&flavor, idx, value_ns as f64);
}
Ok(Some(acc.finish(
format!("{dataset} / {layout} (threshold={threshold})"),
UnitKind::TimeNs,
)))
}