kronicler 0.1.3

Automatic performance capture and analysis for production applications in Python using a custom columnar database written in Rust.
Documentation
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
use super::bufferpool::Bufferpool;
use super::capture::Capture;
use super::column::Column;
use super::constants::{DATA_DIRECTORY, DB_WRITE_BUFFER_SIZE};
use super::index::Index;
use super::queue::KQueue;
use super::row::{create_function_name, Epoch, FieldType, Row};
use log::{debug, info, warn};
use pyo3::prelude::*;
use pyo3::types::PyList;
use std::collections::HashSet;
use std::collections::VecDeque;
use std::fs;
use std::path::Path;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::{Arc, OnceLock, RwLock};
use std::thread;

pub struct DatabaseInner {
    queue: KQueue,
    columns: Vec<Column>,
    /// Index rows by `name` field in capture
    name_index: Index,
    /// Keep track of the current row being inserted
    row_id: AtomicUsize,
    sync_consume: bool,
}

impl DatabaseInner {
    fn new(sync_consume: bool) -> Self {
        if !sync_consume {
            eprintln!(
                "Async Consume not fully supported yet in v0.1.1. Please set `sync_consume=True`."
            );
            // std::process::exit(0);
        }

        Database::create_data_dir();
        Database::check_for_data();

        let column_count = 4;

        let bp = Bufferpool::new(column_count);
        let bufferpool = Arc::new(RwLock::new(bp));

        let name_col = Column::new(
            "name".to_string(),
            0,
            bufferpool.clone(),
            FieldType::Name([0u8; 64]),
        );

        let start_col = Column::new(
            "start".to_string(),
            1,
            bufferpool.clone(),
            FieldType::Epoch(0),
        );

        let end_col = Column::new(
            "end".to_string(),
            2,
            bufferpool.clone(),
            FieldType::Epoch(0),
        );

        let delta_col = Column::new(
            "delta".to_string(),
            3,
            bufferpool.clone(),
            FieldType::Epoch(0),
        );

        let columns = vec![name_col, start_col, end_col, delta_col];

        assert_eq!(columns.len(), column_count);

        for col in &columns {
            col.save();
        }

        let name_index = Index::new();

        DatabaseInner {
            queue: KQueue::new(),
            columns,
            name_index,
            row_id: AtomicUsize::new(0),
            sync_consume,
        }
    }

    fn consume_capture(&mut self, queue: Arc<RwLock<VecDeque<Capture>>>) {
        info!("Calling consume_capture");

        let mut q = queue.write().unwrap();

        if q.len() > DB_WRITE_BUFFER_SIZE {
            info!("Starting bulk write!");

            while !q.is_empty() {
                let capture = q.pop_front();

                if let Some(c) = capture {
                    // TODO: Replace for real ID
                    // Maybe it does not need an ID?
                    // Because the columns keep track of that

                    // Get the self.row_id value (prev) and then add one to self.row_id
                    let prev = self.row_id.fetch_add(1, Ordering::SeqCst);
                    let row = c.to_row(prev);

                    info!("Writing {:?}...", &row);

                    let mut col_index = 0;
                    for field in &row.fields {
                        self.columns[col_index].insert(field);
                        debug!("{:?}", self.name_index);
                        col_index += 1;
                    }

                    self.name_index.insert(row.clone(), 0);
                }
            }

            // Save columns if there was new data
            for col in &self.columns {
                col.save();
            }
        }
    }
}

// Separate singleton instances for sync and async modes
static DATABASE_SYNC: OnceLock<Arc<RwLock<DatabaseInner>>> = OnceLock::new();
static DATABASE_ASYNC: OnceLock<Arc<RwLock<DatabaseInner>>> = OnceLock::new();

// Shared queue state using atomic bools - one for each database type
static QUEUE_HAS_DATA_SYNC: AtomicBool = AtomicBool::new(false);
static QUEUE_HAS_DATA_ASYNC: AtomicBool = AtomicBool::new(false);

#[pyclass]
pub struct Database {
    sync_consume: bool,
}

impl Database {
    fn get_instance(&self) -> Arc<RwLock<DatabaseInner>> {
        if self.sync_consume {
            DATABASE_SYNC
                .get_or_init(|| {
                    info!("Creating sync DatabaseInner with sync_consume=true");
                    Arc::new(RwLock::new(DatabaseInner::new(true)))
                })
                .clone()
        } else {
            DATABASE_ASYNC
                .get_or_init(|| {
                    info!("Creating async DatabaseInner with sync_consume=false");
                    Arc::new(RwLock::new(DatabaseInner::new(false)))
                })
                .clone()
        }
    }

    fn get_queue_state(&self) -> &'static AtomicBool {
        if self.sync_consume {
            &QUEUE_HAS_DATA_SYNC
        } else {
            &QUEUE_HAS_DATA_ASYNC
        }
    }

    fn create_data_dir() {
        fs::create_dir_all(DATA_DIRECTORY)
            .expect(&format!("Could not create directory '{}'.", DATA_DIRECTORY));

        info!("Created data directory at '{}'!", DATA_DIRECTORY);
    }

    fn check_for_data() {
        if !Database::exists() {
            eprintln!("Database does not exist at \"{}\".", &DATA_DIRECTORY);
            std::process::exit(0);
        }
    }
}

#[pymethods]
impl Database {
    #[new]
    #[pyo3(signature = (sync_consume = false))]
    pub fn new(sync_consume: bool) -> Self {
        info!("Creating Database with sync_consume={}", sync_consume);
        Database { sync_consume }
    }

    pub fn init(&mut self) {
        let db_instance = self.get_instance();
        let queue_state = self.get_queue_state();

        info!("Called init!");
        loop {
            // Use relaxed ordering since we don't need strict synchronization here
            if queue_state.load(Ordering::Relaxed) {
                info!("Running consume.");

                let queue_clone = {
                    let db = db_instance.read().unwrap();
                    Arc::clone(&db.queue.queue)
                };

                {
                    let mut db = db_instance.write().unwrap();
                    db.consume_capture(queue_clone);
                }

                // Mark queue as processed
                queue_state.store(false, Ordering::Relaxed);

                // let timeout = time::Duration::from_millis(CONSUMER_DELAY);
                // thread::sleep(timeout);
            }
        }
    }

    #[staticmethod]
    pub fn exists() -> bool {
        Path::new(&DATA_DIRECTORY).exists()
    }

    #[staticmethod]
    #[pyo3(signature = (sync_consume = false))]
    pub fn new_reader(sync_consume: bool) -> Self {
        info!(
            "Creating Database reader with sync_consume={}",
            sync_consume
        );
        Database::new(sync_consume)
    }

    /// Capture a function and write it to the queue
    pub fn capture(&mut self, name: String, args: Vec<PyObject>, start: Epoch, end: Epoch) {
        let db_instance = self.get_instance();
        let queue_state = self.get_queue_state();

        let mut db = db_instance.write().unwrap();

        // Signal that queue has new data
        queue_state.store(true, Ordering::Relaxed);

        info!("Capturing with sync_consume={}", db.sync_consume);
        db.queue.capture(name, args, start, end);

        if db.sync_consume {
            info!("Performing synchronous consume");
            let queue_clone = Arc::clone(&db.queue.queue);
            db.consume_capture(queue_clone);
            // For sync consume, we immediately mark as processed
            queue_state.store(false, Ordering::Relaxed);
        }
    }

    pub fn fetch(&mut self, index: usize) -> Option<Row> {
        info!("Starting fetch on index {}", index);

        let db_instance = self.get_instance();
        let mut db = db_instance.write().unwrap();
        let mut data = vec![];

        for col in &mut db.columns {
            let field = col.fetch(index);

            if let Some(f) = field {
                data.push(f);
            }
        }

        // TODO: Fix this to make it a better check for unwritten data
        if data.len() > 1 && data[1] == FieldType::Epoch(0) {
            return None;
        }

        Some(Row {
            id: index,
            fields: data,
        })
    }

    pub fn fetch_all(&mut self) -> Vec<Row> {
        let mut all = vec![];
        let mut index = 0;

        loop {
            let row = self.fetch(index);

            if let Some(r) = row {
                all.push(r);
            } else {
                break;
            }

            index += 1;
        }

        all
    }

    pub fn fetch_all_as_list<'py>(&mut self, py: Python<'py>) -> Vec<Bound<'py, PyList>> {
        let a = self.fetch_all().into_iter().map(|x| x.to_list(py));
        let rows_dict: Vec<Bound<'py, PyList>> = a.collect();
        rows_dict
    }

    pub fn logs<'py>(&mut self, py: Python<'py>) -> Vec<Bound<'py, PyList>> {
        self.fetch_all_as_list(py)
    }

    pub fn get_function_names(&mut self) -> HashSet<String> {
        let db_instance = self.get_instance();

        let db = db_instance.read().unwrap();

        let mut function_names = HashSet::new();
        let keys: Vec<&FieldType> = db.name_index.index.keys().into_iter().collect();

        for key in keys {
            function_names.insert(key.to_string());
        }

        function_names
    }

    /// Find the average time a function took to run
    pub fn average(&mut self, function_name: &str) -> Option<f64> {
        let name_bytes = create_function_name(function_name);

        let db_instance = self.get_instance();

        let db = db_instance.read().unwrap();
        if let Some(avg) = db.name_index.get_average(FieldType::Name(name_bytes)) {
            info!("Using amortized const average!");
            return Some(avg);
        }

        info!("Manually calculating average!");

        // Get the IDs we need to fetch
        let ids = {
            let db = db_instance.read().unwrap();
            db.name_index.get(FieldType::Name(name_bytes))
        };

        if let Some(ids) = ids {
            let mut values = vec![];

            for id in &ids {
                if let Some(row) = self.fetch(*id) {
                    let delta_index = 3;

                    let fs = row.fields;
                    if fs.len() > delta_index {
                        let f = fs[delta_index].clone();

                        match f {
                            FieldType::Epoch(e) => values.push(e),
                            _ => {}
                        }
                    }
                }
            }

            if !values.is_empty() {
                let sum: u128 = values.iter().sum();
                let avg = sum as f64 / values.len() as f64;
                return Some(avg);
            }
        } else {
            warn!("Could not get IDs");
        }

        None
    }
}

#[pyfunction]
pub fn database_init() {
    thread::spawn(|| {
        let mut db = Database::new(false);
        db.init();
    });
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn average_test() {
        let mut db = Database::new(true);

        db.capture("hello".to_string(), vec![], 100, 200);
        db.capture("hello".to_string(), vec![], 300, 450);

        let name_str = "hello";

        let avg = db.average(name_str);
        assert_eq!(avg, Some(125.0));

        db.capture("hello".to_string(), vec![], 100, 300);
        db.capture("hello".to_string(), vec![], 300, 452);

        let avg = db.average(name_str);
        assert_eq!(avg, Some(150.5));
    }

    #[test]
    fn get_function_names() {
        let mut db = Database::new(true);

        db.capture("hello".to_string(), vec![], 100, 200);
        db.capture("hello".to_string(), vec![], 300, 450);

        db.capture("hey".to_string(), vec![], 300, 450);
        db.capture("a".to_string(), vec![], 300, 450);

        let mut r = HashSet::new();
        r.insert("hello".to_string());
        r.insert("hey".to_string());
        r.insert("a".to_string());

        assert_eq!(db.get_function_names(), r);
    }

    #[test]
    fn singleton_test() {
        let mut db1 = Database::new(true);
        let mut db2 = Database::new(true);

        // Data inserted through db1 should be visible through db2
        db1.capture("test".to_string(), vec![], 100, 200);

        // This should be able to fetch the data inserted by db1
        let row = db2.fetch(0);
        assert!(row.is_some());
    }

    #[test]
    fn sync_vs_async_test() {
        let mut sync_db = Database::new(true);
        let mut async_db = Database::new(false);

        // These should use different singleton instances
        sync_db.capture("sync_test".to_string(), vec![], 100, 200);
        async_db.capture("async_test".to_string(), vec![], 100, 200);

        // sync_db should have its data immediately available
        let sync_row = sync_db.fetch(0);
        assert!(sync_row.is_some());

        // async_db might not have data immediately available (depends on buffer size)
        // but they should be separate instances
    }

    #[test]
    fn shared_queue_state_test() {
        let mut db1 = Database::new(false);
        let db2 = Database::new(false);

        // Both instances should see the same queue state
        let queue_state = db1.get_queue_state();

        // Initially false
        assert!(!queue_state.load(Ordering::Relaxed));

        // After capture through db1, both should see true
        db1.capture("test".to_string(), vec![], 100, 200);
        assert!(queue_state.load(Ordering::Relaxed));

        // Setting through one instance affects the other
        queue_state.store(false, Ordering::Relaxed);
        assert!(!db2.get_queue_state().load(Ordering::Relaxed));
    }
}