-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
Copy pathlib.rs
1606 lines (1493 loc) · 56.9 KB
/
lib.rs
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
//! chroma-load is the load generator for Chroma.
//!
//! This library conceptually separates the notion of a workload from the notion of a data set.
//! Data sets map onto collections in Chroma, but there can be many data sets per collection.
//! Effectively, a data set is a way to specify what it means to get, query, or upsert.
//!
//! Workloads specify a way to manipulate a data set. They specify data-agnostic ways to get,
//! query, or upsert. The workload type is compositional and recursive, so workloads can specify
//! blends of other workloads.
//!
//! The load harness provides a way to start and stop (workload, data set) pairs. The nature of
//! the types means any workload can run against any data set (though the results may not be
//! meaningful except to be some form of load).
use std::collections::hash_map::Entry;
use std::collections::HashMap;
use std::sync::atomic::AtomicBool;
use std::sync::{Arc, Mutex};
use std::time::Instant;
use axum::extract::{MatchedPath, Request, State};
use axum::http::header::{HeaderMap, ACCEPT};
use axum::http::StatusCode;
use axum::response::IntoResponse;
use axum::routing::{get, post};
use axum::{Json, Router};
use chromadb::client::{ChromaAuthMethod, ChromaClientOptions, ChromaTokenHeader};
use chromadb::ChromaClient;
use guacamole::combinators::*;
use guacamole::{Guacamole, Zipf};
use opentelemetry::global;
use opentelemetry::metrics::Counter;
use opentelemetry::{Key, KeyValue, Value};
use tower_http::trace::TraceLayer;
use tracing::Instrument;
use uuid::Uuid;
pub mod bit_difference;
pub mod config;
pub mod data_sets;
pub mod opentelemetry_config;
pub mod rest;
pub mod words;
pub mod workloads;
const CONFIG_PATH_ENV_VAR: &str = "CONFIG_PATH";
/////////////////////////////////////////////// Error //////////////////////////////////////////////
/// Errors that can occur in the load service.
// TODO(rescrv): Implement ChromaError.
#[derive(Debug)]
pub enum Error {
/// The requested resource was not found.
NotFound(String),
/// The request was invalid.
InvalidRequest(String),
/// An internal error occurred.
InternalError(String),
/// A request to chroma failed.
FailWorkload(String),
}
impl std::fmt::Display for Error {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
match self {
Error::NotFound(msg) => write!(f, "not found: {}", msg),
Error::InvalidRequest(msg) => write!(f, "invalid request: {}", msg),
Error::InternalError(msg) => write!(f, "internal error: {}", msg),
Error::FailWorkload(msg) => write!(f, "workload failed: {}", msg),
}
}
}
impl std::error::Error for Error {}
impl axum::response::IntoResponse for Error {
fn into_response(self) -> axum::http::Response<axum::body::Body> {
let (status, body) = match self {
Error::NotFound(msg) => (StatusCode::NOT_FOUND, msg),
Error::InvalidRequest(msg) => (StatusCode::BAD_REQUEST, msg),
Error::InternalError(msg) => (StatusCode::INTERNAL_SERVER_ERROR, msg),
Error::FailWorkload(msg) => (StatusCode::INTERNAL_SERVER_ERROR, msg),
};
axum::http::Response::builder()
.status(status)
.body((body.trim().to_string() + "\n").into())
.expect("response and status are always valid")
}
}
////////////////////////////////////////////// Metrics /////////////////////////////////////////////
#[derive(Debug)]
pub struct Metrics {
/// The number of times an individual workload step was inhibited. It will not be tracked as
/// inactive or stepped.
inhibited: Counter<u64>,
/// The number of times an individual workload step was inactive. It will not be tracked as
/// inhibited or stepped.
inactive: Counter<u64>,
/// The number of times an individual workload was stepped.
step: Counter<u64>,
/// The number of times a workload issued a get against a data set.
get: Counter<u64>,
/// The number of times a workload issued a query against a data set.
query: Counter<u64>,
/// The number of times a workload issued an upsert against a data set.
upsert: Counter<u64>,
}
////////////////////////////////////////////// client //////////////////////////////////////////////
/// Instantiate a new Chroma client. This will use the CHROMA_HOST environment variable (or
/// http://localhost:8000 when unset) as the argument to [client_for_url].
pub async fn client() -> ChromaClient {
let url = std::env::var("CHROMA_HOST").unwrap_or_else(|_| "http://localhost:8000".into());
client_for_url(url).await
}
/// Create a new Chroma client for the given URL. This will use the CHROMA_TOKEN environment
/// variable if set, or no authentication if unset.
pub async fn client_for_url(url: String) -> ChromaClient {
if let Ok(auth) = std::env::var("CHROMA_TOKEN") {
ChromaClient::new(ChromaClientOptions {
url: Some(url),
auth: ChromaAuthMethod::TokenAuth {
token: auth,
header: ChromaTokenHeader::XChromaToken,
},
database: "hf-tiny-stories".to_string(),
connections: 32,
})
.await
.unwrap()
} else {
ChromaClient::new(ChromaClientOptions {
url: Some(url),
auth: ChromaAuthMethod::None,
database: "hf-tiny-stories".to_string(),
connections: 32,
})
.await
.unwrap()
}
}
////////////////////////////////////////////// DataSet /////////////////////////////////////////////
/// A data set is an abstraction over a Chroma collection. It is designed to allow callers to use
/// get/query/upsert without worrying about the semantics of a particular data set. A valid
/// [GetQuery], [QueryQuery], or [UpsertQuery] should work for any data set or return an explicit
/// error.
#[async_trait::async_trait]
pub trait DataSet: std::fmt::Debug + Send + Sync {
/// A human-readable name for the data set. This will be used for starting workloads to pair
/// them to a data set.
fn name(&self) -> String;
/// A human-readable description of the data set. This will be used in the status endpoint.
fn description(&self) -> String;
/// A JSON representation of the data set. This will be used in the status endpoint when
/// requesting JSON.
fn json(&self) -> serde_json::Value;
/// Get documents from the data set.
///
/// The semantics of this call is that it should loosely translate to a non-vector query,
/// whatever that means for the implementor of the data set.
async fn get(
&self,
client: &ChromaClient,
gq: GetQuery,
guac: &mut Guacamole,
) -> Result<(), Box<dyn std::error::Error>>;
/// Query documents from the data set.
///
/// The semantics of this call correspond to a vector query, whatever that means for the
/// implementor of the data set.
async fn query(
&self,
client: &ChromaClient,
vq: QueryQuery,
guac: &mut Guacamole,
) -> Result<(), Box<dyn std::error::Error>>;
/// Upsert documents into the data set.
///
/// The semantics of this call correspond to writing documents into the data set, whatever that
/// means for the implementor of the data set.
async fn upsert(
&self,
client: &ChromaClient,
uq: UpsertQuery,
guac: &mut Guacamole,
) -> Result<(), Box<dyn std::error::Error>>;
}
/////////////////////////////////////////// Distribution ///////////////////////////////////////////
/// Distribution size and shape.
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
pub enum Distribution {
/// Draw a constant value.
Constant(usize),
/// Draw from an exponential distribution with the given average.
Exponential(f64),
/// Draw from a uniform distribution between min and max.
Uniform(usize, usize),
/// Draw from a Zipf distribution with the given number of elements and theta (<1.0).
Zipf(u64, f64),
}
impl Distribution {
/// Given Guacamole, generate a sample from the distribution.
pub fn sample(&self, guac: &mut Guacamole) -> usize {
match self {
Distribution::Constant(n) => *n,
Distribution::Exponential(rate) => poisson(*rate)(guac).ceil() as usize,
Distribution::Uniform(min, max) => uniform(*min, *max)(guac),
Distribution::Zipf(n, alpha) => {
let z = Zipf::from_alpha(*n, *alpha);
z.next(guac) as usize
}
}
}
}
impl Eq for Distribution {}
impl PartialEq for Distribution {
fn eq(&self, other: &Self) -> bool {
match (self, other) {
(Distribution::Constant(a), Distribution::Constant(b)) => a == b,
(Distribution::Exponential(a), Distribution::Exponential(b)) => a.total_cmp(b).is_eq(),
(Distribution::Uniform(a, b), Distribution::Uniform(c, d)) => a == c && b == d,
(Distribution::Zipf(a, b), Distribution::Zipf(c, d)) => {
a == c && b.total_cmp(d).is_eq()
}
_ => false,
}
}
}
/////////////////////////////////////////////// Skew ///////////////////////////////////////////////
/// Distribution shape, without size.
#[derive(Copy, Clone, Debug, serde::Deserialize, serde::Serialize)]
pub enum Skew {
/// A uniform skew introduces no bias in the selection.
#[serde(rename = "uniform")]
Uniform,
/// A Zipf skew is skewed according to theta. Theta=0.0 is uniform, theta=1.0-\epsilon is very
/// skewed. Try 0.9 and add nines for skew.
#[serde(rename = "zipf")]
Zipf { theta: f64 },
}
impl Eq for Skew {}
impl PartialEq for Skew {
fn eq(&self, other: &Self) -> bool {
match (self, other) {
(Skew::Uniform, Skew::Uniform) => true,
(Skew::Zipf { theta: a }, Skew::Zipf { theta: b }) => a.total_cmp(b).is_eq(),
_ => false,
}
}
}
///////////////////////////////////////// TinyStoriesMixin /////////////////////////////////////////
#[derive(Clone, Debug, PartialEq, serde::Deserialize, serde::Serialize)]
pub enum TinyStoriesMixin {
#[serde(rename = "numeric")]
Numeric { ratio_selected: f64 },
}
impl TinyStoriesMixin {
pub fn to_json(&self, guac: &mut Guacamole) -> serde_json::Value {
match self {
Self::Numeric { ratio_selected } => {
let field: &'static str = match uniform(0u8, 5u8)(guac) {
0 => "i1",
1 => "i2",
2 => "i3",
3 => "f1",
4 => "f2",
5 => "f3",
_ => unreachable!(),
};
let mut center = uniform(0, 1_000_000)(guac);
let window = (1e6 * ratio_selected) as usize;
if window / 2 > center {
center = window / 2
}
let min = center - window / 2;
let max = center + window / 2;
serde_json::json!({"$and": [{field: {"$gte": min}}, {field: {"$lt": max}}]})
}
}
}
}
//////////////////////////////////////////// WhereMixin ////////////////////////////////////////////
/// A metadata query specifies a metadata filter in Chroma.
#[derive(Clone, Debug, PartialEq, serde::Deserialize, serde::Serialize)]
pub enum WhereMixin {
/// A raw metadata query simply copies the provided filter spec.
#[serde(rename = "query")]
Constant(serde_json::Value),
/// Search for a word from the provided set of words with skew.
#[serde(rename = "fts")]
FullTextSearch(Skew),
/// The tiny stories workload. The way these collections were setup, there are three fields
/// each of integer, float, and string. The integer fields are named i1, i2, and i3. The
/// float fields are named f1, f2, and f3. The string fields are named s1, s2, and s3.
///
/// This mixin selects one of these 6 numeric fields at random and picks a metadata range query
/// to perform on it that will return data according to the mixin.
#[serde(rename = "tiny-stories")]
TinyStories(TinyStoriesMixin),
/// A constant operator with different comparison.
/// A mix of metadata queries selects one of the queries at random.
#[serde(rename = "select")]
Select(Vec<(f64, WhereMixin)>),
}
impl WhereMixin {
/// Convert the metadata query into a JSON value suitable for use in a Chroma query.
pub fn to_json(&self, guac: &mut Guacamole) -> serde_json::Value {
match self {
Self::Constant(query) => query.clone(),
Self::FullTextSearch(skew) => {
const WORDS: &[&str] = words::FEW_WORDS;
let word = match skew {
Skew::Uniform => WORDS[uniform(0, WORDS.len() as u64)(guac) as usize],
Skew::Zipf { theta } => {
let z = Zipf::from_alpha(WORDS.len() as u64, *theta);
WORDS[z.next(guac) as usize]
}
};
serde_json::json!({"$contains": word.to_string()})
}
Self::TinyStories(mixin) => mixin.to_json(guac),
Self::Select(select) => {
let scale: f64 = any(guac);
let mut total = scale * select.iter().map(|(p, _)| *p).sum::<f64>();
for (p, mixin) in select {
if *p < 0.0 {
return serde_json::Value::Null;
}
if *p >= total {
return mixin.to_json(guac);
}
total -= *p;
}
serde_json::Value::Null
}
}
}
}
impl Eq for WhereMixin {}
///////////////////////////////////////////// GetQuery /////////////////////////////////////////////
/// A get query specifies a get operation in Chroma.
///
/// This roughly corresponds to a skew in popularity of a key (note that it's not a distribution
/// because the distribution requires a size and that comes when bound to the workload).
///
/// The limit specifies a distribution of request sizes. (note that it's a distribution and not a
/// skew because we specify the size as part of the query spec).
///
/// Then there are metadata and document filters, which are optional.
#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
pub struct GetQuery {
pub skew: Skew,
pub limit: Distribution,
#[serde(skip_serializing_if = "Option::is_none")]
pub metadata: Option<WhereMixin>,
#[serde(skip_serializing_if = "Option::is_none")]
pub document: Option<WhereMixin>,
}
//////////////////////////////////////////// QueryQuery ////////////////////////////////////////////
/// A query query specifies a vector query operation in Chroma.
///
/// This roughly corresponds to a skew in popularity of a vector (note that it's not a distribution
/// because the distribution requires a size and that comes when bound to the workload).
///
/// The limit specifies a distribution of request sizes. (note that it's a distribution and not a
/// skew because we specify the size as part of the query spec).
///
/// Then there are metadata and document filters, which are optional.
#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
pub struct QueryQuery {
pub skew: Skew,
pub limit: Distribution,
#[serde(skip_serializing_if = "Option::is_none")]
pub metadata: Option<WhereMixin>,
#[serde(skip_serializing_if = "Option::is_none")]
pub document: Option<WhereMixin>,
}
//////////////////////////////////////////// KeySelector ///////////////////////////////////////////
/// A means of selecting a key for upsert.
#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
#[serde(tag = "type")]
pub enum KeySelector {
/// Select a key by index. If the index is out of bounds, the behavior is defined to wrap.
#[serde(rename = "index")]
Index(usize),
/// Select a key by skew. The skew is used to select a key from the distribution of keys the
/// data set has available for upsert.
#[serde(rename = "random")]
Random(Skew),
}
//////////////////////////////////////////// UpsertQuery ///////////////////////////////////////////
/// An upsert query specifies an upsert operation in Chroma.
///
/// The batch will be selected using the provided key. The batch size is the number of documents
/// to upsert in a single operation. The associativity is the ratio is data set defined, but
/// generally means that denser operations will take place with higher values.
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct UpsertQuery {
/// Select the document ID to upsert.
pub key: KeySelector,
/// The number of documents to upsert in a single operation.
pub batch_size: usize,
/// The associativity of the upsert operation. Implementation-defined meaning.
pub associativity: f64,
}
/////////////////////////////////////////// WorkloadState //////////////////////////////////////////
/// The state of a workload.
#[derive(Clone)]
pub struct WorkloadState {
seq_no: u64,
guac: Guacamole,
}
///////////////////////////////////////////// Workload /////////////////////////////////////////////
/// A workload is a description of a set of operations to perform against a data set.
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
pub enum Workload {
/// No Operatioon; do nothing.
#[serde(rename = "nop")]
Nop,
/// Resolve the workload by name.
#[serde(rename = "by_name")]
ByName(String),
/// Get documents from the data set according to the query.
#[serde(rename = "get")]
Get(GetQuery),
/// Query documents from the data set according to the query.
#[serde(rename = "query")]
Query(QueryQuery),
/// A hybrid workload is a blend of other workloads. The blend is specified as a list of other
/// valid workload. The probabilities are normalized to 1.0 before selection.
#[serde(rename = "hybrid")]
Hybrid(Vec<(f64, Workload)>),
/// Delay the workload until after the specified time.
#[serde(rename = "delay")]
Delay {
after: chrono::DateTime<chrono::FixedOffset>,
wrap: Box<Workload>,
},
/// Load the data set. Will repeatedly load until the time expires.
#[serde(rename = "load")]
Load,
/// Randomly upsert a document.
#[serde(rename = "random")]
RandomUpsert(KeySelector),
}
impl Workload {
/// A human-readable description of the workload.
pub fn description(&self) -> String {
serde_json::to_string_pretty(self).unwrap()
}
/// Resolve named workload references to the actual workloads they reference.
pub fn resolve_by_name(&mut self, workloads: &HashMap<String, Workload>) -> Result<(), Error> {
match self {
Workload::Nop => {}
Workload::ByName(name) => {
if let Some(workload) = workloads.get(name) {
*self = workload.clone();
} else {
return Err(Error::NotFound(format!("workload not found: {name}")));
}
}
Workload::Get(_) => {}
Workload::Query(_) => {}
Workload::Hybrid(hybrid) => {
for (_, workload) in hybrid {
workload.resolve_by_name(workloads)?;
}
}
Workload::Delay { after: _, wrap } => wrap.resolve_by_name(workloads)?,
Workload::Load => {}
Workload::RandomUpsert(_) => {}
}
Ok(())
}
/// Do one operation of the workload against the data set.
pub async fn step(
&self,
client: &ChromaClient,
metrics: &Metrics,
data_set: &dyn DataSet,
state: &mut WorkloadState,
) -> Result<(), Box<dyn std::error::Error>> {
match self {
Workload::Nop => {
tracing::info!("nop");
Ok(())
}
Workload::ByName(_) => {
tracing::error!("cannot step by name; by_name should be resolved");
Err(Box::new(Error::InternalError(
"cannot step by name".to_string(),
)))
}
Workload::Get(get) => {
metrics.get.add(
1,
&[KeyValue::new(
Key::from_static_str("data_set"),
Value::from(data_set.name()),
)],
);
data_set
.get(client, get.clone(), &mut state.guac)
.instrument(tracing::info_span!("get"))
.await
}
Workload::Query(query) => {
metrics.query.add(
1,
&[KeyValue::new(
Key::from_static_str("data_set"),
Value::from(data_set.name()),
)],
);
data_set
.query(client, query.clone(), &mut state.guac)
.instrument(tracing::info_span!("query"))
.await
}
Workload::Hybrid(hybrid) => {
let scale: f64 = any(&mut state.guac);
let mut total = scale
* hybrid
.iter()
.filter_map(|(p, w)| if w.is_active() { Some(*p) } else { None })
.sum::<f64>();
for (p, workload) in hybrid {
if *p < 0.0 {
return Err(Box::new(Error::InvalidRequest(
"hybrid probabilities must be positive".to_string(),
)));
}
if workload.is_active() {
if *p >= total {
return Box::pin(workload.step(client, metrics, data_set, state)).await;
}
total -= *p;
}
}
Err(Box::new(Error::InternalError(
"miscalculation of total hybrid probabilities".to_string(),
)))
}
Workload::Delay { after: _, wrap } => {
Box::pin(wrap.step(client, metrics, data_set, state)).await
}
Workload::Load => {
metrics.upsert.add(
1,
&[KeyValue::new(
Key::from_static_str("data_set"),
Value::from(data_set.name()),
)],
);
data_set
.upsert(
client,
UpsertQuery {
key: KeySelector::Index(state.seq_no as usize),
batch_size: 100,
// Associativity is the ratio of documents in a cluster to documents
// written by the workload. It is ignored for load.
associativity: 0.0,
},
&mut state.guac,
)
.instrument(tracing::info_span!("load"))
.await
}
Workload::RandomUpsert(key) => {
metrics.upsert.add(
1,
&[KeyValue::new(
Key::from_static_str("data_set"),
Value::from(data_set.name()),
)],
);
data_set
.upsert(
client,
UpsertQuery {
key: key.clone(),
batch_size: 100,
// Associativity is the ratio of documents in a cluster to documents
// written by the workload. It is ignored for load.
associativity: 0.0,
},
&mut state.guac,
)
.instrument(tracing::info_span!("load"))
.await
}
}
}
/// True if the workload is active, which means it may interact with Chroma.
pub fn is_active(&self) -> bool {
match self {
Workload::Nop => true,
Workload::ByName(_) => true,
Workload::Get(_) => true,
Workload::Query(_) => true,
Workload::Hybrid(hybrid) => hybrid.iter().any(|(_, w)| w.is_active()),
Workload::Delay { after, wrap } => chrono::Utc::now() >= *after && wrap.is_active(),
Workload::Load => true,
Workload::RandomUpsert(_) => true,
}
}
}
impl Eq for Workload {}
impl PartialEq for Workload {
fn eq(&self, other: &Self) -> bool {
match (self, other) {
(Workload::Nop, Workload::Nop) => true,
(Workload::ByName(a), Workload::ByName(b)) => a == b,
(Workload::Get(a), Workload::Get(b)) => a == b,
(Workload::Query(a), Workload::Query(b)) => a == b,
(Workload::Hybrid(a), Workload::Hybrid(b)) => {
a.len() == b.len()
&& a.iter()
.zip(b.iter())
.all(|(a, b)| a.0.total_cmp(&b.0).is_eq() && a.1 == b.1)
}
(
Workload::Delay {
after: a,
wrap: a_wrap,
},
Workload::Delay {
after: b,
wrap: b_wrap,
},
) => a == b && a_wrap == b_wrap,
(Workload::Load, Workload::Load) => true,
(Workload::RandomUpsert(a), Workload::RandomUpsert(b)) => a == b,
_ => false,
}
}
}
//////////////////////////////////////////// Throughput ////////////////////////////////////////////
/// A throughput specification.
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
pub enum Throughput {
/// Target a constant throughput.
#[serde(rename = "constant")]
Constant(f64),
/// Operate in a sinusoidal fashion, oscillating between min and max throughput over
/// periodicity seconds.
#[serde(rename = "sinusoidal")]
Sinusoidal {
/// Trough throughput.
min: f64,
/// Peak throughput.
max: f64,
/// Periodicity in seconds.
periodicity: usize,
},
/// Sawtooth throughput, increasing linearly from min to max throughput over periodicity
#[serde(rename = "sawtooth")]
Sawtooth {
/// Starting throughput.
min: f64,
/// Ending throughput.
max: f64,
/// Periodicity in seconds.
periodicity: usize,
},
}
impl std::fmt::Display for Throughput {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
match self {
Throughput::Constant(throughput) => write!(f, "constant: {}", throughput),
Throughput::Sinusoidal {
min,
max,
periodicity,
} => {
write!(f, "sinusoidal: {} to {} over {}s", min, max, periodicity)
}
Throughput::Sawtooth {
min,
max,
periodicity,
} => {
write!(f, "sawtooth: {} to {} over {}s", min, max, periodicity)
}
}
}
}
impl Eq for Throughput {}
impl PartialEq for Throughput {
fn eq(&self, other: &Self) -> bool {
match (self, other) {
(Throughput::Constant(a), Throughput::Constant(b)) => a == b,
(
Throughput::Sinusoidal {
min: amin,
max: amax,
periodicity: aperiodicity,
},
Throughput::Sinusoidal {
min: bmin,
max: bmax,
periodicity: bperiodicity,
},
) => {
amin.total_cmp(bmin).is_eq()
&& amax.total_cmp(bmax).is_eq()
&& aperiodicity == bperiodicity
}
(
Throughput::Sawtooth {
min: amin,
max: amax,
periodicity: aperiodicity,
},
Throughput::Sawtooth {
min: bmin,
max: bmax,
periodicity: bperiodicity,
},
) => {
amin.total_cmp(bmin).is_eq()
&& amax.total_cmp(bmax).is_eq()
&& aperiodicity == bperiodicity
}
_ => false,
}
}
}
////////////////////////////////////////// RunningWorkload /////////////////////////////////////////
/// A running workload is a workload that has been bound to a data set at a given throughput. It
/// is assigned a name, uuid, and expiration time.
#[derive(Clone, Debug)]
pub struct RunningWorkload {
uuid: Uuid,
name: String,
workload: Workload,
data_set: Arc<dyn DataSet>,
expires: chrono::DateTime<chrono::FixedOffset>,
throughput: Throughput,
}
impl RunningWorkload {
/// A human-readable description of the running workload.
pub fn description(&self) -> String {
format!("{}/{}", self.uuid, self.data_set.name())
}
}
impl From<WorkloadSummary> for Option<RunningWorkload> {
fn from(s: WorkloadSummary) -> Self {
if let Some(data_set) = data_sets::from_json(&s.data_set) {
Some(RunningWorkload {
uuid: s.uuid,
name: s.name,
workload: s.workload,
data_set,
expires: s.expires,
throughput: s.throughput,
})
} else {
None
}
}
}
impl Eq for RunningWorkload {}
impl PartialEq for RunningWorkload {
fn eq(&self, other: &Self) -> bool {
self.uuid == other.uuid
&& self.name == other.name
&& self.workload == other.workload
&& self.data_set.json() == other.data_set.json()
&& self.expires == other.expires
&& self.throughput == other.throughput
}
}
////////////////////////////////////////// WorkloadSummary /////////////////////////////////////////
/// A summary of a workload.
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct WorkloadSummary {
/// The UUID of the workload.
pub uuid: Uuid,
/// The name of the workload.
pub name: String,
/// The workload itself.
pub workload: Workload,
/// The data set the workload is bound to.
pub data_set: serde_json::Value,
/// The expiration time of the workload.
pub expires: chrono::DateTime<chrono::FixedOffset>,
/// The throughput of the workload.
pub throughput: Throughput,
}
impl From<RunningWorkload> for WorkloadSummary {
fn from(r: RunningWorkload) -> Self {
WorkloadSummary {
uuid: r.uuid,
name: r.name,
workload: r.workload,
data_set: r.data_set.json(),
expires: r.expires,
throughput: r.throughput,
}
}
}
//////////////////////////////////////////// SavedState ////////////////////////////////////////////
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct SavedState {
inhibited: bool,
running: Vec<WorkloadSummary>,
}
//////////////////////////////////////////// LoadHarness ///////////////////////////////////////////
/// A load harness is a collection of running workloads.
#[derive(Debug)]
pub struct LoadHarness {
running: Vec<RunningWorkload>,
}
impl LoadHarness {
/// The status of the load harness.
pub fn status(&self) -> Vec<RunningWorkload> {
self.running.clone()
}
/// Start a workload on the load harness.
pub fn start(
&mut self,
name: String,
workload: Workload,
data_set: &Arc<dyn DataSet>,
expires: chrono::DateTime<chrono::FixedOffset>,
throughput: Throughput,
) -> Uuid {
let uuid = Uuid::new_v4();
let data_set = Arc::clone(data_set);
self.running.push(RunningWorkload {
uuid,
name,
workload,
data_set,
expires,
throughput,
});
uuid
}
/// Stop a workload on the load harness.
pub fn stop(&mut self, uuid: Uuid) -> bool {
let old_sz = self.running.len();
self.running.retain(|w| w.uuid != uuid);
let new_sz = self.running.len();
old_sz > new_sz
}
}
//////////////////////////////////////////// LoadService ///////////////////////////////////////////
/// The load service is a collection of data sets and workloads that can be started and stopped.
#[derive(Debug)]
#[allow(clippy::type_complexity)]
pub struct LoadService {
metrics: Metrics,
inhibit: Arc<AtomicBool>,
harness: Mutex<LoadHarness>,
running: Mutex<HashMap<Uuid, (Arc<AtomicBool>, tokio::task::JoinHandle<()>)>>,
data_sets: Vec<Arc<dyn DataSet>>,
workloads: HashMap<String, Workload>,
persistent_path: Option<String>,
}
impl LoadService {
/// Create a new load service from the given data sets and workloads.
pub fn new(data_sets: Vec<Arc<dyn DataSet>>, workloads: HashMap<String, Workload>) -> Self {
let meter = global::meter("chroma");
let inhibited = meter.u64_counter("inhibited").build();
let inactive = meter.u64_counter("inactive").build();
let step = meter.u64_counter("step").build();
let get = meter.u64_counter("get").build();
let query = meter.u64_counter("query").build();
let upsert = meter.u64_counter("upsert").build();
let metrics = Metrics {
inhibited,
inactive,
step,
get,
query,
upsert,
};
LoadService {
metrics,
inhibit: Arc::new(AtomicBool::new(false)),
harness: Mutex::new(LoadHarness { running: vec![] }),
running: Mutex::new(HashMap::default()),
data_sets,
workloads,
persistent_path: None,
}
}
/// Set the persistent path and load its contents.
pub fn set_persistent_path_and_load(
&mut self,
persistent_path: Option<String>,
) -> Result<(), Error> {
if let Some(persistent_path) = persistent_path {
self.persistent_path = Some(persistent_path);
self.load_persistent()?;
}
Ok(())
}
/// Inhibit the load service. This stops all activity in perpetuity until a call to uninhibit.
/// Even subsequent calls to start will not do anything until a call to uninhibit.
pub fn inhibit(&self) -> Result<(), Error> {
self.inhibit
.store(true, std::sync::atomic::Ordering::Relaxed);
self.save_persistent()?;
Ok(())
}
/// Uninhibit the load service. This allows activity to resume.
pub fn uninhibit(&self) -> Result<(), Error> {
self.inhibit
.store(false, std::sync::atomic::Ordering::Relaxed);
self.save_persistent()?;
Ok(())
}
/// Check if the load service is inhibited.
pub fn is_inhibited(&self) -> bool {
self.inhibit.load(std::sync::atomic::Ordering::Relaxed)
}
/// Get the data sets in the load service.
pub fn data_sets(&self) -> &[Arc<dyn DataSet>] {
&self.data_sets
}