-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathtiered-bench.rs
More file actions
2121 lines (1949 loc) · 71.1 KB
/
Copy pathtiered-bench.rs
File metadata and controls
2121 lines (1949 loc) · 71.1 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
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! tiered-bench - Benchmark for tiered S3-backed VFS
//!
//! Early-Facebook-style dataset:
//! - users, posts, friendships, likes (4 tables, indexed)
//! - Point lookups, JOINs, indexed filters, scans
//!
//! Four cache levels:
//! none = nothing cached (full cold start from S3)
//! interior = interior B-tree pages cached, index + data from S3
//! index = interior + index pages cached, data from S3
//! data = everything cached (warm, measures pread latency)
//!
//! ```bash
//! TIERED_TEST_BUCKET=turbolite-test \
//! AWS_ENDPOINT_URL=https://t3.storage.dev \
//! cargo run --release --features bench-s3,zstd --bin tiered-bench
//! ```
// Benchmark CLIs intentionally pass many knobs through to the VFS; suppress
// structural lints that would require invasive refactoring without improving
// correctness.
#![allow(clippy::too_many_arguments)]
use clap::Parser;
use rusqlite::{Connection, OpenFlags};
use std::sync::atomic::{AtomicU32, AtomicU64, Ordering};
use std::sync::Arc;
use std::time::Instant;
use tempfile::TempDir;
#[allow(deprecated)] // benchmarks use the legacy checkpoint-mode shim
use turbolite::tiered::{
attach_integer_constraint_hints, parse_eqp_output, push_planned_accesses,
set_local_checkpoint_only, CacheConfig, CompressionConfig, PrefetchConfig, TurboliteConfig,
TurboliteSharedState, TurboliteVfs,
};
static VFS_COUNTER: AtomicU32 = AtomicU32::new(0);
// =========================================================================
// Post-Phase-Anvil-g storage wiring
//
// The VFS no longer owns an S3Client and no longer exposes byte counters.
// Benchmarks that want counters hold an Arc<S3Storage> themselves and read
// the backend's own counters. `BenchCtx` pairs the SharedState (cache
// control) with the S3Storage (counters) and exposes the same
// `clear_cache_*`, `reset_s3_counters`, `s3_counters` method names the
// pre-Anvil-g bench code called on `TurboliteSharedState`. Baseline
// subtraction is used for "reset" because S3Storage is cumulative.
// =========================================================================
/// Build an S3 backend from env. Shared by every site that used to build a
/// TurboliteConfig with `bucket`/`prefix`/`endpoint_url`/`region`.
fn build_s3_backend(
runtime: &tokio::runtime::Handle,
prefix: &str,
) -> Arc<hadb_storage_s3::S3Storage> {
let bucket = test_bucket();
let endpoint = endpoint_url();
let storage = runtime.block_on(async {
hadb_storage_s3::S3Storage::from_env(bucket, endpoint.as_deref())
.await
.expect("build S3Storage")
});
Arc::new(storage.with_prefix(prefix.to_string()))
}
/// Wrapper that pairs shared-state cache control with an S3Storage counter
/// reader. Baseline subtraction gives the illusion of `reset_s3_counters`.
struct BenchCtx<'a> {
state: &'a TurboliteSharedState,
s3: Arc<hadb_storage_s3::S3Storage>,
fetch_count_base: AtomicU64,
bytes_fetched_base: AtomicU64,
}
impl<'a> BenchCtx<'a> {
fn new(state: &'a TurboliteSharedState, s3: Arc<hadb_storage_s3::S3Storage>) -> Self {
Self {
fetch_count_base: AtomicU64::new(s3.fetch_count()),
bytes_fetched_base: AtomicU64::new(s3.bytes_fetched()),
state,
s3,
}
}
fn clear_cache_data_only(&self) {
self.state.clear_cache_data_only();
}
fn clear_cache_interior_only(&self) {
self.state.clear_cache_interior_only();
}
fn clear_cache_all(&self) {
self.state.clear_cache_all();
}
/// Snapshot the current S3 counters as a new baseline. Subsequent
/// `s3_counters()` calls report deltas from this moment.
fn reset_s3_counters(&self) {
self.fetch_count_base
.store(self.s3.fetch_count(), Ordering::Relaxed);
self.bytes_fetched_base
.store(self.s3.bytes_fetched(), Ordering::Relaxed);
}
fn s3_counters(&self) -> (u64, u64) {
let fc = self
.s3
.fetch_count()
.saturating_sub(self.fetch_count_base.load(Ordering::Relaxed));
let fb = self
.s3
.bytes_fetched()
.saturating_sub(self.bytes_fetched_base.load(Ordering::Relaxed));
(fc, fb)
}
fn cache_info(&self) -> String {
self.state.cache_info()
}
}
// =========================================================================
// Data constants
// =========================================================================
const FIRST_NAMES: &[&str] = &[
"Mark",
"Eduardo",
"Dustin",
"Chris",
"Sean",
"Priscilla",
"Sheryl",
"Andrew",
"Adam",
"Mike",
"Sarah",
"Jessica",
"Emily",
"David",
"Alex",
"Randi",
"Naomi",
"Kevin",
"Amy",
"Dan",
"Lisa",
"Tom",
"Rachel",
"Brian",
"Caitlin",
"Nicole",
"Matt",
"Laura",
"Jake",
"Megan",
];
const LAST_NAMES: &[&str] = &[
"Zuckerberg",
"Saverin",
"Moskovitz",
"Hughes",
"Parker",
"Chan",
"Sandberg",
"McCollum",
"D'Angelo",
"Schroepfer",
"Smith",
"Johnson",
"Williams",
"Brown",
"Jones",
"Garcia",
"Miller",
"Davis",
"Rodriguez",
"Martinez",
"Anderson",
"Taylor",
"Thomas",
"Hernandez",
"Moore",
"Martin",
"Jackson",
"Thompson",
"White",
"Lopez",
];
const SCHOOLS: &[&str] = &[
"Harvard",
"Stanford",
"MIT",
"Yale",
"Princeton",
"Columbia",
"Penn",
"Brown",
"Cornell",
"Dartmouth",
"Duke",
"Georgetown",
"UCLA",
"Berkeley",
"Michigan",
"NYU",
"Boston University",
"Northeastern",
"USC",
"Emory",
];
const CITIES: &[&str] = &[
"Palo Alto, CA",
"San Francisco, CA",
"New York, NY",
"Boston, MA",
"Cambridge, MA",
"Seattle, WA",
"Austin, TX",
"Chicago, IL",
"Los Angeles, CA",
"Miami, FL",
"Denver, CO",
"Portland, OR",
"Philadelphia, PA",
"Washington, DC",
"Atlanta, GA",
];
const POST_TEMPLATES: &[&str] = &[
"Just moved into my new dorm room! {} is going to be amazing this year.",
"Can't believe we won the game last night. Go {}!",
"Anyone else studying for the {} midterm? This is brutal.",
"Looking for people to join our {} intramural team. DM me!",
"Had the best {} at that new place downtown. Highly recommend!",
"Working on a new project with {}. Can't say much yet but stay tuned...",
"Missing home but {} makes it worth it. Great people here.",
"Just finished reading {}. Changed my perspective on everything.",
"Road trip to {} this weekend! Who's in?",
"Three exams in one week. {} life is no joke.",
"Happy birthday to my roommate {}! Best {} ever.",
"Throwback to that {} concert last summer. Need to see them again.",
"Anyone want to grab {} at the dining hall? Meeting at 6pm.",
"Finally submitted my {} paper. Time to celebrate!",
"The weather in {} is unreal today. Perfect for frisbee on the quad.",
];
const FILL_WORDS: &[&str] = &[
"college",
"freshman year",
"organic chemistry",
"basketball",
"pizza",
"the team",
"campus",
"Malcolm Gladwell",
"New York",
"Harvard",
"Alex",
"friend",
"Radiohead",
"dinner",
"thesis",
"San Francisco",
];
#[derive(Parser)]
#[command(name = "tiered-bench")]
#[command(about = "Warm/cold benchmark for tiered S3-backed VFS")]
struct Cli {
/// Row counts (total posts) to benchmark (comma-separated)
#[arg(long, default_value = "10000", env = "BENCH_SIZES")]
sizes: String,
/// Number of measured iterations per query per mode (warm + cold)
#[arg(long, default_value = "10", env = "BENCH_ITERATIONS")]
iterations: usize,
/// Number of warmup iterations before measuring (cold only)
#[arg(long, default_value = "2", env = "BENCH_WARMUP")]
warmup: usize,
/// Delete S3 data after benchmarks (default: keep for reuse)
#[arg(long, env = "BENCH_CLEANUP")]
cleanup: bool,
/// Force regeneration even if S3 data exists at the prefix
#[arg(long, env = "BENCH_FORCE")]
force: bool,
/// Import a local SQLite DB file to S3 (skip VFS-based data gen).
/// Use --import auto to generate locally then import, or --import <path> for existing file.
#[arg(long, env = "BENCH_IMPORT")]
import: Option<String>,
/// Page size (bytes). Default 65536 (64KB).
#[arg(long, default_value = "65536", env = "BENCH_PAGE_SIZE")]
page_size: u32,
/// Pages per page group. Default 256 (16MB uncompressed at 64KB pages).
#[arg(long, default_value = "256", env = "BENCH_PPG")]
ppg: u32,
/// Rows per transaction commit during data generation. Default 10000.
#[arg(long, default_value = "10000", env = "BENCH_BATCH_SIZE")]
batch_size: usize,
/// Number of worker threads for parallel S3 fetches.
/// Defaults to max(num_cpus - 1, 1).
#[arg(long, env = "BENCH_PREFETCH_THREADS")]
prefetch_threads: Option<u32>,
/// Prefetch schedule for SEARCH queries (aggressive warmup).
/// Comma-separated fractions. Default "0.3,0.3,0.4".
/// SCAN queries use plan-aware bulk prefetch (bypasses schedule entirely).
#[arg(long, default_value = "0.3,0.3,0.4", env = "BENCH_PREFETCH_SEARCH")]
prefetch_search: String,
/// Prefetch schedule for index lookups / point queries (conservative).
/// Comma-separated fractions. Default "0,0,0" (three free hops before any prefetch).
#[arg(long, default_value = "0,0,0", env = "BENCH_PREFETCH_LOOKUP")]
prefetch_lookup: String,
/// Which queries to run (comma-separated). Default: all.
/// Options: post, profile, who-liked, mutual
#[arg(long, env = "BENCH_QUERIES")]
queries: Option<String>,
/// Which modes to run (comma-separated). Default: all.
/// Cache levels: none, interior, index, data
/// none = nothing cached (full cold start from S3)
/// interior = interior B-tree pages cached, index + data from S3
/// index = interior + index pages cached, data from S3
/// data = everything cached (warm)
#[arg(long, env = "BENCH_MODES")]
modes: Option<String>,
/// Skip COUNT(*) verification (avoids full table scan on tiny machines)
#[arg(long, env = "BENCH_SKIP_VERIFY")]
skip_verify: bool,
/// Phase Marne: query-plan-aware prefetch. Before each query, runs
/// EXPLAIN QUERY PLAN and pushes planned B-tree accesses to the global
/// queue. The VFS drains the queue on first read and prefetches all
/// planned groups immediately instead of waiting for the hop schedule.
#[arg(long, env = "BENCH_PLAN_AWARE")]
plan_aware: bool,
/// Naive mode: disable ALL prefetch (no sibling prefetch, no plan-aware).
/// Simulates dumb "fetch page from S3 on demand" like other S3-backed SQLite.
/// Useful as a baseline to measure turbolite's prefetch advantage.
#[arg(long, env = "BENCH_NAIVE")]
naive: bool,
/// Per-query SEARCH prefetch schedule for "post+user" (point lookup).
/// Default: "off" (point lookup, 1-2 pages per tree, prefetch is wasted).
#[arg(long, default_value = "off", env = "BENCH_POST_PREFETCH")]
post_prefetch: String,
/// Per-query LOOKUP prefetch schedule for "post+user".
/// Default: "off" (point lookup needs zero lookup prefetch).
#[arg(long, default_value = "off", env = "BENCH_POST_LOOKUP")]
post_lookup: String,
/// Per-query SEARCH prefetch schedule for "profile" (multi-tree join).
/// Default: "0.1,0.2,0.3" (moderate, hits a few pages across trees).
#[arg(long, default_value = "0.1,0.2,0.3", env = "BENCH_PROFILE_PREFETCH")]
profile_prefetch: String,
/// Per-query LOOKUP prefetch schedule for "profile".
/// Default: "0,0,0,0" (multi-join, conservative: 4 free hops before any lookup prefetch).
#[arg(long, default_value = "0,0,0,0", env = "BENCH_PROFILE_LOOKUP")]
profile_lookup: String,
/// Per-query SEARCH prefetch schedule for "who-liked" (SEARCH on likes index).
/// Default: "0.3,0.3,0.4" (aggressive, scans unknown portion of index).
#[arg(long, default_value = "0.3,0.3,0.4", env = "BENCH_WHO_LIKED_PREFETCH")]
who_liked_prefetch: String,
/// Per-query LOOKUP prefetch schedule for "who-liked".
/// Default: "0,0,0" (index SEARCH, no lookup prefetch needed).
#[arg(long, default_value = "0,0,0", env = "BENCH_WHO_LIKED_LOOKUP")]
who_liked_lookup: String,
/// Per-query SEARCH prefetch schedule for "mutual" (multiple SEARCH scans).
/// Default: "0.4,0.3,0.3" (very aggressive, many index pages).
#[arg(long, default_value = "0.4,0.3,0.3", env = "BENCH_MUTUAL_PREFETCH")]
mutual_prefetch: String,
/// Per-query LOOKUP prefetch schedule for "mutual".
/// Default: "0,0,0" (multiple SEARCH, no lookup prefetch needed).
#[arg(long, default_value = "0,0,0", env = "BENCH_MUTUAL_LOOKUP")]
mutual_lookup: String,
/// Per-query SEARCH prefetch schedule for "idx-filter" (index range scan).
/// Default: "0.2,0.3,0.5" (moderate-aggressive, range of index pages).
#[arg(long, default_value = "0.2,0.3,0.5", env = "BENCH_IDX_FILTER_PREFETCH")]
idx_filter_prefetch: String,
/// Per-query LOOKUP prefetch schedule for "idx-filter".
/// Default: "0,0,0" (covered index scan, no lookup prefetch).
#[arg(long, default_value = "0,0,0", env = "BENCH_IDX_FILTER_LOOKUP")]
idx_filter_lookup: String,
/// Per-query SEARCH prefetch schedule for "scan-filter" (full table scan).
/// Default: "off" (plan-aware bulk prefetch handles this, schedule irrelevant).
#[arg(long, default_value = "off", env = "BENCH_SCAN_FILTER_PREFETCH")]
scan_filter_prefetch: String,
/// Per-query LOOKUP prefetch schedule for "scan-filter".
/// Default: "off" (plan-aware handles this).
#[arg(long, default_value = "off", env = "BENCH_SCAN_FILTER_LOOKUP")]
scan_filter_lookup: String,
/// Matrix mode: test each query at "none" level with every schedule in --matrix-schedules.
/// Outputs a comparison table per query: schedule vs latency/GETs.
#[arg(long, env = "BENCH_MATRIX")]
matrix: bool,
/// Schedule pairs to test in matrix mode (semicolon-separated).
/// Format: "search/lookup" per entry. "off" = both disabled.
/// No slash = same schedule for both search and lookup.
/// 10 pairs covering off -> aggressive, symmetric and asymmetric.
#[arg(
long,
default_value = "off;0.33,0.33,0.34;0.3,0.3,0.4/0,0.1,0.2;0.3,0.3,0.4/0.3,0.3,0.4;0.5,0.5/0,0,0.1;0.5,0.5/0.1,0.2,0.3;0.5,0.3,0.2/0.1,0.1,0.2;1.0/0;0.2,0.3,0.5/0,0,0.2;0.4,0.3,0.3/0.1,0.2,0.3",
env = "BENCH_MATRIX_SCHEDULES"
)]
matrix_schedules: String,
}
// =========================================================================
// Helpers
// =========================================================================
fn unique_vfs_name(prefix: &str) -> String {
let n = VFS_COUNTER.fetch_add(1, Ordering::SeqCst);
format!("bench_{}_{}", prefix, n)
}
fn test_bucket() -> String {
std::env::var("TIERED_TEST_BUCKET")
.or_else(|_| std::env::var("BUCKET_NAME"))
.expect("TIERED_TEST_BUCKET or BUCKET_NAME env var required")
}
fn endpoint_url() -> Option<String> {
std::env::var("AWS_ENDPOINT_URL")
.or_else(|_| std::env::var("AWS_ENDPOINT_URL_S3"))
.ok()
}
/// Deterministic pseudo-random hash
fn phash(seed: u64) -> u64 {
let mut x = seed;
x = x
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
x ^= x >> 33;
x = x.wrapping_mul(0xff51afd7ed558ccd);
x ^= x >> 33;
x
}
fn percentile(latencies: &[f64], p: f64) -> f64 {
if latencies.is_empty() {
return 0.0;
}
let mut sorted = latencies.to_vec();
sorted.sort_by(|a, b| a.partial_cmp(b).unwrap());
let idx = ((p * sorted.len() as f64) as usize).min(sorted.len() - 1);
sorted[idx]
}
struct BenchResult {
label: String,
latencies_us: Vec<f64>,
s3_fetches: Vec<u64>,
s3_bytes: Vec<u64>,
}
impl BenchResult {
fn p50(&self) -> f64 {
percentile(&self.latencies_us, 0.5)
}
fn p90(&self) -> f64 {
percentile(&self.latencies_us, 0.9)
}
fn p99(&self) -> f64 {
percentile(&self.latencies_us, 0.99)
}
fn avg_fetches(&self) -> f64 {
if self.s3_fetches.is_empty() {
return 0.0;
}
self.s3_fetches.iter().sum::<u64>() as f64 / self.s3_fetches.len() as f64
}
fn avg_bytes_kb(&self) -> f64 {
if self.s3_bytes.is_empty() {
return 0.0;
}
(self.s3_bytes.iter().sum::<u64>() as f64 / self.s3_bytes.len() as f64) / 1024.0
}
}
fn format_number(n: usize) -> String {
let s = n.to_string();
let mut result = String::new();
for (i, ch) in s.chars().rev().enumerate() {
if i > 0 && i % 3 == 0 {
result.push(',');
}
result.push(ch);
}
result.chars().rev().collect()
}
/// Parse a per-query prefetch schedule. "off" = None (disabled), otherwise comma-separated floats.
fn parse_query_prefetch(s: &str) -> Option<Vec<f32>> {
match s.trim().to_lowercase().as_str() {
"off" | "none" | "disabled" | "" => None,
_ => Some(parse_prefetch_hops(s)),
}
}
const DEFAULT_MODE_ORDER: [&str; 4] = ["data", "index", "interior", "none"];
fn selected_mode_order(modes: Option<&str>) -> Vec<&'static str> {
let Some(modes) = modes else {
return DEFAULT_MODE_ORDER.to_vec();
};
let mut selected = Vec::new();
for mode in modes.split(',') {
let mode = match mode.trim().to_lowercase().as_str() {
"data" => "data",
"index" => "index",
"interior" => "interior",
"none" => "none",
_ => continue,
};
if !selected.contains(&mode) {
selected.push(mode);
}
}
selected
}
#[cfg(test)]
mod mode_order_tests {
use super::*;
#[test]
fn selected_mode_order_preserves_explicit_order() {
assert_eq!(
selected_mode_order(Some("none,interior,index,data")),
vec!["none", "interior", "index", "data"]
);
}
#[test]
fn selected_mode_order_keeps_default_order_when_absent() {
assert_eq!(selected_mode_order(None), DEFAULT_MODE_ORDER.to_vec());
}
#[test]
fn effective_prefetch_threads_leaves_one_core_by_default() {
assert_eq!(
effective_prefetch_threads_from(None, None),
PrefetchConfig::default_threads()
);
}
#[test]
fn effective_prefetch_threads_keeps_turbolite_env_precedence() {
assert_eq!(effective_prefetch_threads_from(Some(5), Some("7")), 7);
}
}
fn format_ms(us: f64) -> String {
if us >= 1_000_000.0 {
format!("{:.1}s", us / 1_000_000.0)
} else if us >= 1000.0 {
format!("{:.1}ms", us / 1000.0)
} else {
format!("{:.0}us", us)
}
}
fn format_kb(kb: f64) -> String {
if kb >= 1024.0 {
format!("{:.1}MB", kb / 1024.0)
} else {
format!("{:.0}KB", kb)
}
}
fn parse_prefetch_hops(s: &str) -> Vec<f32> {
s.split(',')
.filter_map(|v| v.trim().parse::<f32>().ok())
.collect()
}
fn effective_prefetch_threads_from(cli_threads: Option<u32>, turbolite_env: Option<&str>) -> u32 {
turbolite_env
.and_then(|v| v.parse().ok())
.or(cli_threads)
.unwrap_or_else(PrefetchConfig::default_threads)
}
fn effective_prefetch_threads(cli_threads: Option<u32>) -> u32 {
let turbolite_env = std::env::var("TURBOLITE_PREFETCH_THREADS").ok();
effective_prefetch_threads_from(cli_threads, turbolite_env.as_deref())
}
fn make_config(
_prefix: &str,
cache_dir: &std::path::Path,
ppg: u32,
prefetch_threads: Option<u32>,
prefetch_search: Vec<f32>,
prefetch_lookup: Vec<f32>,
) -> TurboliteConfig {
let env_prefetch = PrefetchConfig::from_env();
let prefetch_threads = effective_prefetch_threads(prefetch_threads);
TurboliteConfig {
cache_dir: cache_dir.to_path_buf(),
compression: CompressionConfig {
level: 1,
..Default::default()
},
cache: CacheConfig {
pages_per_group: ppg,
..Default::default()
},
prefetch: PrefetchConfig {
threads: prefetch_threads,
search: prefetch_search,
lookup: prefetch_lookup,
..env_prefetch
},
..Default::default()
}
}
fn make_reader_config(
_prefix: &str,
cache_dir: &std::path::Path,
ppg: u32,
prefetch_threads: Option<u32>,
prefetch_search: Vec<f32>,
prefetch_lookup: Vec<f32>,
) -> TurboliteConfig {
let env_prefetch = PrefetchConfig::from_env();
let prefetch_threads = effective_prefetch_threads(prefetch_threads);
TurboliteConfig {
cache_dir: cache_dir.to_path_buf(),
compression: CompressionConfig {
level: 1,
..Default::default()
},
read_only: true,
cache: CacheConfig {
pages_per_group: ppg,
..Default::default()
},
prefetch: PrefetchConfig {
threads: prefetch_threads,
search: prefetch_search,
lookup: prefetch_lookup,
..env_prefetch
},
..Default::default()
}
}
// =========================================================================
// Schema
// =========================================================================
const SCHEMA: &str = "
CREATE TABLE users (
id INTEGER PRIMARY KEY,
first_name TEXT NOT NULL,
last_name TEXT NOT NULL,
email TEXT NOT NULL,
school TEXT NOT NULL,
city TEXT NOT NULL,
bio TEXT NOT NULL,
joined_at INTEGER NOT NULL
);
CREATE TABLE posts (
id INTEGER PRIMARY KEY,
user_id INTEGER NOT NULL,
content TEXT NOT NULL,
created_at INTEGER NOT NULL,
like_count INTEGER NOT NULL DEFAULT 0
);
CREATE TABLE friendships (
user_a INTEGER NOT NULL,
user_b INTEGER NOT NULL,
created_at INTEGER NOT NULL,
PRIMARY KEY (user_a, user_b)
);
CREATE TABLE likes (
user_id INTEGER NOT NULL,
post_id INTEGER NOT NULL,
created_at INTEGER NOT NULL,
PRIMARY KEY (user_id, post_id)
);
CREATE INDEX idx_posts_user ON posts(user_id);
CREATE INDEX idx_posts_created ON posts(created_at);
CREATE INDEX idx_friendships_b ON friendships(user_b, user_a);
CREATE INDEX idx_likes_post ON likes(post_id);
CREATE INDEX idx_likes_user ON likes(user_id, created_at);
CREATE INDEX idx_users_school ON users(school);
";
// =========================================================================
// Data generation
// =========================================================================
fn generate_post_content(id: i64) -> String {
let h = phash(id as u64 + 9_000_000);
let template = POST_TEMPLATES[(h as usize) % POST_TEMPLATES.len()];
let fill1 = FILL_WORDS[((h >> 16) as usize) % FILL_WORDS.len()];
let fill2 = FILL_WORDS[((h >> 24) as usize) % FILL_WORDS.len()];
let mut content = template.replacen("{}", fill1, 1);
content = content.replacen("{}", fill2, 1);
let target_len = 200 + ((h >> 32) % 1800) as usize;
if content.len() < target_len {
let padding = [
" Can't wait to see what happens next.",
" This semester is flying by.",
" Anyone else feel the same way?",
" Comment below if you're interested!",
" Life is good right now.",
" Really grateful for this experience.",
" Shoutout to everyone who made this happen.",
" More updates coming soon!",
];
while content.len() < target_len {
let pidx = phash(content.len() as u64 + id as u64) as usize % padding.len();
content.push_str(padding[pidx]);
}
}
content
}
fn generate_bio(id: i64) -> String {
let h = phash(id as u64 + 7_000_000);
let interests = [
"music",
"startups",
"hiking",
"photography",
"cooking",
"travel",
"reading",
"sports",
"gaming",
"art",
];
let i1 = interests[((h >> 8) as usize) % interests.len()];
let i2 = interests[((h >> 16) as usize) % interests.len()];
let i3 = interests[((h >> 24) as usize) % interests.len()];
let year = 2004 + (h % 4);
format!(
"Class of {}. Into {}, {}, and {}. Looking to connect!",
year, i1, i2, i3
)
}
fn generate_data(conn: &Connection, n_posts: usize, batch_size: usize) {
let n_users = (n_posts / 10).max(100);
let friends_per_user = 50usize;
let n_friendships = n_users * friends_per_user / 2;
let n_likes = n_posts * 3;
eprintln!(
" Generating: {} users, {} posts, {} friendships, {} likes",
format_number(n_users),
format_number(n_posts),
format_number(n_friendships),
format_number(n_likes),
);
// Users (batch commit every batch_size rows)
{
let mut batch = 0usize;
let mut tx = conn.unchecked_transaction().unwrap();
for i in 0..n_users as i64 {
let h = phash(i as u64);
tx.execute(
"INSERT INTO users VALUES (?1,?2,?3,?4,?5,?6,?7,?8)",
rusqlite::params![
i,
FIRST_NAMES[(h as usize) % FIRST_NAMES.len()],
LAST_NAMES[((h >> 16) as usize) % LAST_NAMES.len()],
format!(
"{}.{}{}@{}.edu",
FIRST_NAMES[(h as usize) % FIRST_NAMES.len()].to_lowercase(),
LAST_NAMES[((h >> 16) as usize) % LAST_NAMES.len()].to_lowercase(),
i,
SCHOOLS[((h >> 24) as usize) % SCHOOLS.len()]
.to_lowercase()
.replace(' ', "")
),
SCHOOLS[((h >> 24) as usize) % SCHOOLS.len()],
CITIES[((h >> 32) as usize) % CITIES.len()],
generate_bio(i),
1075000000i64 + (h % 100_000_000) as i64,
],
)
.unwrap();
batch += 1;
if batch >= batch_size {
tx.commit().unwrap();
tx = conn.unchecked_transaction().unwrap();
batch = 0;
}
}
tx.commit().unwrap();
eprintln!(" users inserted: {}", format_number(n_users));
}
// Posts
{
let mut batch = 0usize;
let mut tx = conn.unchecked_transaction().unwrap();
for i in 0..n_posts as i64 {
let h = phash(i as u64 + 1_000_000);
tx.execute(
"INSERT INTO posts (id, user_id, content, created_at, like_count) VALUES (?1,?2,?3,?4,?5)",
rusqlite::params![
i,
(h % n_users as u64) as i64,
generate_post_content(i),
1075000000i64 + (h >> 16) as i64 % 94_000_000,
(phash(i as u64 + 2_000_000) % 200) as i64,
],
).unwrap();
batch += 1;
if batch >= batch_size {
tx.commit().unwrap();
tx = conn.unchecked_transaction().unwrap();
batch = 0;
if (i as usize).is_multiple_of(batch_size * 10) {
eprintln!(
" posts: {}/{}",
format_number(i as usize),
format_number(n_posts)
);
}
}
}
tx.commit().unwrap();
eprintln!(" posts inserted: {}", format_number(n_posts));
}
// Friendships
{
let mut batch = 0usize;
let mut count = 0usize;
let mut tx = conn.unchecked_transaction().unwrap();
for i in 0..n_users as u64 {
let n_friends = friends_per_user.min(n_users - 1);
for j in 0..n_friends {
let h = phash(i * 100 + j as u64 + 3_000_000);
let friend = (h % n_users as u64) as i64;
if friend != i as i64 {
let (a, b) = if (i as i64) < friend {
(i as i64, friend)
} else {
(friend, i as i64)
};
tx.execute(
"INSERT OR IGNORE INTO friendships VALUES (?1,?2,?3)",
rusqlite::params![a, b, 1075000000i64 + (h >> 16) as i64 % 94_000_000],
)
.unwrap();
count += 1;
batch += 1;
if batch >= batch_size {
tx.commit().unwrap();
tx = conn.unchecked_transaction().unwrap();
batch = 0;
}
}
if count >= n_friendships {
break;
}
}
if count >= n_friendships {
break;
}
}
tx.commit().unwrap();
eprintln!(" friendships inserted: {}", format_number(count));
}
// Likes
{
let mut batch = 0usize;
let mut tx = conn.unchecked_transaction().unwrap();
for i in 0..n_likes as u64 {
let h = phash(i + 4_000_000);
tx.execute(
"INSERT OR IGNORE INTO likes VALUES (?1,?2,?3)",
rusqlite::params![
(h % n_users as u64) as i64,
((h >> 16) % n_posts as u64) as i64,
1075000000i64 + (h >> 32) as i64 % 94_000_000,
],
)
.unwrap();
batch += 1;
if batch >= batch_size {
tx.commit().unwrap();
tx = conn.unchecked_transaction().unwrap();
batch = 0;
if (i as usize).is_multiple_of(batch_size * 10) && i > 0 {
eprintln!(
" likes: {}/{}",
format_number(i as usize),
format_number(n_likes)
);
}
}
}
tx.commit().unwrap();
eprintln!(" likes inserted: {}", format_number(n_likes));
}
}
/// Generate a plain SQLite DB file locally (no VFS, max speed).
/// Uses journal_mode=OFF and synchronous=OFF for fastest possible writes.
#[allow(deprecated)] // benchmarks intentionally use the legacy checkpoint-mode shim
fn generate_local_db(path: &std::path::Path, n_posts: usize, batch_size: usize, page_size: u32) {
let conn = Connection::open(path).expect("open local DB");
conn.execute_batch(&format!(
"PRAGMA page_size={}; PRAGMA journal_mode=OFF; PRAGMA synchronous=OFF; PRAGMA cache_size=-262144;",
page_size,
)).expect("pragma setup");
conn.execute_batch(SCHEMA).expect("create tables");
generate_data(&conn, n_posts, batch_size);
// Verify
let count: i64 = conn
.query_row("SELECT COUNT(*) FROM posts", [], |r| r.get(0))
.unwrap();
let page_count: i64 = conn
.query_row("PRAGMA page_count", [], |r| r.get(0))
.unwrap();
let ps: i64 = conn
.query_row("PRAGMA page_size", [], |r| r.get(0))
.unwrap();
eprintln!(
"[local-gen] {} posts, {} pages x {} bytes = {:.1} MB",
count,
page_count,
ps,
(page_count * ps) as f64 / (1024.0 * 1024.0),
);
}
// =========================================================================
// Benchmark queries
// =========================================================================
const Q_POST_DETAIL: &str = "\
SELECT posts.id, posts.content, posts.created_at, posts.like_count,
users.first_name, users.last_name, users.school, users.city
FROM posts
JOIN users ON users.id = posts.user_id
WHERE posts.id = ?1";
const Q_PROFILE: &str = "\
SELECT users.first_name, users.last_name, users.school, users.city, users.bio,
posts.id, posts.content, posts.created_at, posts.like_count
FROM users
JOIN posts ON posts.user_id = users.id
WHERE users.id = ?1
ORDER BY posts.created_at DESC
LIMIT 10";
const Q_WHO_LIKED: &str = "\
SELECT users.first_name, users.last_name, users.school, likes.created_at
FROM likes
JOIN users ON users.id = likes.user_id
WHERE likes.post_id = ?1
ORDER BY likes.created_at DESC
LIMIT 50";