do-memory-storage-turso 0.1.29

Turso/libSQL storage backend for the do-memory-core episodic learning system
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
//! Performance Metrics for Turso Optimizations
//!
//! Tracks the impact of Phase 1 optimizations:
//! - Cache-first reads (85% reduction in Turso queries)
//! - Request batching (55% reduction in round trips)
//! - Prepared statement caching (35% faster queries)
//! - Metadata query optimization (70% faster queries)

use parking_lot::RwLock;
use std::sync::Arc;
use std::time::{Duration, Instant};

/// Performance metrics for optimization tracking
#[derive(Debug, Clone, Default)]
pub struct OptimizationMetrics {
    /// Cache-first read strategy metrics
    pub cache_first: CacheFirstMetrics,
    /// Batch operation metrics
    pub batching: BatchingMetrics,
    /// Prepared statement metrics
    pub prepared_statements: PreparedStatementMetrics,
    /// Query optimization metrics
    pub query_optimization: QueryOptimizationMetrics,
}

/// Metrics for cache-first read strategy
#[derive(Debug, Clone, Default)]
pub struct CacheFirstMetrics {
    /// Total read requests
    pub total_reads: u64,
    /// Reads served from cache (no Turso query)
    pub cache_hits: u64,
    /// Reads requiring Turso query
    pub cache_misses: u64,
    /// Average latency for cache hits (microseconds)
    pub avg_cache_hit_latency_us: u64,
    /// Average latency for cache misses (microseconds)
    pub avg_cache_miss_latency_us: u64,
    /// Turso queries avoided by cache
    pub queries_avoided: u64,
}

impl CacheFirstMetrics {
    /// Calculate cache hit rate
    pub fn hit_rate(&self) -> f64 {
        if self.total_reads == 0 {
            0.0
        } else {
            self.cache_hits as f64 / self.total_reads as f64
        }
    }

    /// Calculate Turso query reduction percentage
    pub fn query_reduction_pct(&self) -> f64 {
        self.hit_rate() * 100.0
    }

    /// Calculate average latency improvement
    pub fn latency_improvement_pct(&self) -> f64 {
        if self.avg_cache_miss_latency_us == 0 {
            0.0
        } else {
            let improvement = self.avg_cache_miss_latency_us - self.avg_cache_hit_latency_us;
            (improvement as f64 / self.avg_cache_miss_latency_us as f64) * 100.0
        }
    }
}

/// Metrics for batch operations
#[derive(Debug, Clone, Default)]
pub struct BatchingMetrics {
    /// Total operations performed
    pub total_operations: u64,
    /// Operations performed via batching
    pub batched_operations: u64,
    /// Operations performed individually
    pub individual_operations: u64,
    /// Average batch size
    pub avg_batch_size: f64,
    /// Round trips avoided by batching
    pub round_trips_avoided: u64,
    /// Average latency per operation in batch (microseconds)
    pub avg_batch_latency_us: u64,
    /// Average latency per individual operation (microseconds)
    pub avg_individual_latency_us: u64,
}

impl BatchingMetrics {
    /// Calculate batching efficiency (percentage of operations batched)
    pub fn batching_efficiency(&self) -> f64 {
        if self.total_operations == 0 {
            0.0
        } else {
            self.batched_operations as f64 / self.total_operations as f64 * 100.0
        }
    }

    /// Calculate round trip reduction percentage
    pub fn round_trip_reduction_pct(&self) -> f64 {
        if self.total_operations == 0 {
            0.0
        } else {
            self.round_trips_avoided as f64 / self.total_operations as f64 * 100.0
        }
    }

    /// Calculate latency improvement from batching
    pub fn latency_improvement_pct(&self) -> f64 {
        if self.avg_individual_latency_us == 0 {
            0.0
        } else {
            let improvement = self.avg_individual_latency_us - self.avg_batch_latency_us;
            (improvement as f64 / self.avg_individual_latency_us as f64) * 100.0
        }
    }
}

/// Metrics for prepared statement caching
#[derive(Debug, Clone, Default)]
pub struct PreparedStatementMetrics {
    /// Total queries executed
    pub total_queries: u64,
    /// Queries using cached prepared statements
    pub cached_statements: u64,
    /// Queries requiring statement preparation
    pub uncached_statements: u64,
    /// Average preparation time (microseconds)
    pub avg_preparation_time_us: u64,
    /// Average execution time with cached statement (microseconds)
    pub avg_cached_execution_us: u64,
    /// Average execution time without cache (microseconds)
    pub avg_uncached_execution_us: u64,
}

impl PreparedStatementMetrics {
    /// Calculate cache hit rate
    pub fn cache_hit_rate(&self) -> f64 {
        if self.total_queries == 0 {
            0.0
        } else {
            self.cached_statements as f64 / self.total_queries as f64
        }
    }

    /// Calculate query speedup from caching
    pub fn query_speedup_pct(&self) -> f64 {
        if self.avg_uncached_execution_us == 0 {
            0.0
        } else {
            let improvement = self.avg_uncached_execution_us - self.avg_cached_execution_us;
            (improvement as f64 / self.avg_uncached_execution_us as f64) * 100.0
        }
    }
}

/// Metrics for query optimization
#[derive(Debug, Clone, Default)]
pub struct QueryOptimizationMetrics {
    /// Total metadata queries
    pub total_metadata_queries: u64,
    /// Queries using json_extract
    pub json_extract_queries: u64,
    /// Queries using LIKE pattern
    pub like_pattern_queries: u64,
    /// Average latency for json_extract (microseconds)
    pub avg_json_extract_latency_us: u64,
    /// Average latency for LIKE pattern (microseconds)
    pub avg_like_pattern_latency_us: u64,
}

impl QueryOptimizationMetrics {
    /// Calculate optimization adoption rate
    pub fn optimization_rate(&self) -> f64 {
        if self.total_metadata_queries == 0 {
            0.0
        } else {
            self.json_extract_queries as f64 / self.total_metadata_queries as f64 * 100.0
        }
    }

    /// Calculate query speedup from optimization
    pub fn query_speedup_pct(&self) -> f64 {
        if self.avg_like_pattern_latency_us == 0 {
            0.0
        } else {
            let improvement = self.avg_like_pattern_latency_us - self.avg_json_extract_latency_us;
            (improvement as f64 / self.avg_like_pattern_latency_us as f64) * 100.0
        }
    }
}

/// Performance metrics collector
pub struct PerformanceMetrics {
    /// Optimization metrics
    metrics: Arc<RwLock<OptimizationMetrics>>,
    /// Collection start time
    start_time: Instant,
}

impl PerformanceMetrics {
    /// Create a new performance metrics collector
    pub fn new() -> Self {
        Self {
            metrics: Arc::new(RwLock::new(OptimizationMetrics::default())),
            start_time: Instant::now(),
        }
    }

    /// Record a cache-first read operation
    pub fn record_cache_read(&self, hit: bool, latency: Duration) {
        let mut metrics = self.metrics.write();
        metrics.cache_first.total_reads += 1;

        let latency_us = latency.as_micros() as u64;

        if hit {
            metrics.cache_first.cache_hits += 1;
            metrics.cache_first.queries_avoided += 1;
            // Update moving average for cache hits
            let n = metrics.cache_first.cache_hits;
            metrics.cache_first.avg_cache_hit_latency_us =
                ((metrics.cache_first.avg_cache_hit_latency_us * (n - 1)) + latency_us) / n;
        } else {
            metrics.cache_first.cache_misses += 1;
            // Update moving average for cache misses
            let n = metrics.cache_first.cache_misses;
            metrics.cache_first.avg_cache_miss_latency_us =
                ((metrics.cache_first.avg_cache_miss_latency_us * (n - 1)) + latency_us) / n;
        }
    }

    /// Record a batch operation
    pub fn record_batch_operation(&self, batch_size: usize, latency: Duration) {
        let mut metrics = self.metrics.write();
        metrics.batching.total_operations += batch_size as u64;
        metrics.batching.batched_operations += batch_size as u64;

        // Update average batch size
        let total_batches = metrics.batching.batched_operations / batch_size as u64;
        metrics.batching.avg_batch_size =
            ((metrics.batching.avg_batch_size * (total_batches - 1) as f64) + batch_size as f64)
                / total_batches as f64;

        // Each batch operation saves (batch_size - 1) round trips
        metrics.batching.round_trips_avoided += (batch_size - 1) as u64;

        // Update average batch latency per operation
        let latency_per_op = latency.as_micros() as u64 / batch_size as u64;
        let n = metrics.batching.batched_operations;
        metrics.batching.avg_batch_latency_us = ((metrics.batching.avg_batch_latency_us
            * (n - batch_size as u64))
            + (latency_per_op * batch_size as u64))
            / n;
    }

    /// Record an individual operation (non-batched)
    pub fn record_individual_operation(&self, latency: Duration) {
        let mut metrics = self.metrics.write();
        metrics.batching.total_operations += 1;
        metrics.batching.individual_operations += 1;

        let latency_us = latency.as_micros() as u64;
        let n = metrics.batching.individual_operations;
        metrics.batching.avg_individual_latency_us =
            ((metrics.batching.avg_individual_latency_us * (n - 1)) + latency_us) / n;
    }

    /// Record a prepared statement cache operation
    pub fn record_prepared_statement(&self, cached: bool, latency: Duration) {
        let mut metrics = self.metrics.write();
        metrics.prepared_statements.total_queries += 1;

        let latency_us = latency.as_micros() as u64;

        if cached {
            metrics.prepared_statements.cached_statements += 1;
            let n = metrics.prepared_statements.cached_statements;
            metrics.prepared_statements.avg_cached_execution_us =
                ((metrics.prepared_statements.avg_cached_execution_us * (n - 1)) + latency_us) / n;
        } else {
            metrics.prepared_statements.uncached_statements += 1;
            let n = metrics.prepared_statements.uncached_statements;
            metrics.prepared_statements.avg_uncached_execution_us =
                ((metrics.prepared_statements.avg_uncached_execution_us * (n - 1)) + latency_us)
                    / n;
        }
    }

    /// Record a metadata query optimization
    pub fn record_metadata_query(&self, uses_json_extract: bool, latency: Duration) {
        let mut metrics = self.metrics.write();
        metrics.query_optimization.total_metadata_queries += 1;

        let latency_us = latency.as_micros() as u64;

        if uses_json_extract {
            metrics.query_optimization.json_extract_queries += 1;
            let n = metrics.query_optimization.json_extract_queries;
            metrics.query_optimization.avg_json_extract_latency_us =
                ((metrics.query_optimization.avg_json_extract_latency_us * (n - 1)) + latency_us)
                    / n;
        } else {
            metrics.query_optimization.like_pattern_queries += 1;
            let n = metrics.query_optimization.like_pattern_queries;
            metrics.query_optimization.avg_like_pattern_latency_us =
                ((metrics.query_optimization.avg_like_pattern_latency_us * (n - 1)) + latency_us)
                    / n;
        }
    }

    /// Get current metrics snapshot
    pub fn snapshot(&self) -> OptimizationMetrics {
        self.metrics.read().clone()
    }

    /// Get uptime since metrics collection started
    pub fn uptime(&self) -> Duration {
        self.start_time.elapsed()
    }

    /// Generate a performance report
    pub fn report(&self) -> String {
        let metrics = self.snapshot();
        let uptime = self.uptime();

        format!(
            r#"
╔══════════════════════════════════════════════════════════════════╗
║         Turso Performance Optimization Report (Phase 1)          ║
╠══════════════════════════════════════════════════════════════════╣
║ Uptime: {:.2} hours                                              
╠══════════════════════════════════════════════════════════════════╣
║ 1. Cache-First Read Strategy                                     ║
╠══════════════════════════════════════════════════════════════════╣
║   Total Reads:           {:>10}                                  ║
║   Cache Hits:            {:>10} ({:>5.1}%)                       ║
║   Cache Misses:          {:>10} ({:>5.1}%)                       ║
║   Turso Queries Avoided: {:>10}                                  ║
║   Avg Hit Latency:       {:>8} µs                                ║
║   Avg Miss Latency:      {:>8} µs                                ║
║   Latency Improvement:   {:>5.1}%                                ║
╠══════════════════════════════════════════════════════════════════╣
║ 2. Request Batching                                              ║
╠══════════════════════════════════════════════════════════════════╣
║   Total Operations:      {:>10}                                  ║
║   Batched Operations:    {:>10} ({:>5.1}%)                       ║
║   Individual Operations: {:>10} ({:>5.1}%)                       ║
║   Avg Batch Size:        {:>10.1}                                ║
║   Round Trips Avoided:   {:>10} ({:>5.1}% reduction)             ║
║   Avg Batch Latency:     {:>8} µs/op                             ║
║   Avg Individual Latency:{:>8} µs/op                             ║
║   Latency Improvement:   {:>5.1}%                                ║
╠══════════════════════════════════════════════════════════════════╣
║ 3. Prepared Statement Caching                                    ║
╠══════════════════════════════════════════════════════════════════╣
║   Total Queries:         {:>10}                                  ║
║   Cached Statements:     {:>10} ({:>5.1}%)                       ║
║   Uncached Statements:   {:>10} ({:>5.1}%)                       ║
║   Avg Cached Latency:    {:>8} µs                                ║
║   Avg Uncached Latency:  {:>8} µs                                ║
║   Query Speedup:         {:>5.1}%                                ║
╠══════════════════════════════════════════════════════════════════╣
║ 4. Metadata Query Optimization (json_extract)                    ║
╠══════════════════════════════════════════════════════════════════╣
║   Total Metadata Queries:{:>10}                                  ║
║   json_extract Queries:  {:>10} ({:>5.1}%)                       ║
║   LIKE Pattern Queries:  {:>10} ({:>5.1}%)                       ║
║   Avg json_extract:      {:>8} µs                                ║
║   Avg LIKE Pattern:      {:>8} µs                                ║
║   Query Speedup:         {:>5.1}%                                ║
╚══════════════════════════════════════════════════════════════════╝
"#,
            uptime.as_secs_f64() / 3600.0,
            // Cache-first metrics
            metrics.cache_first.total_reads,
            metrics.cache_first.cache_hits,
            metrics.cache_first.hit_rate(),
            metrics.cache_first.cache_misses,
            100.0 - metrics.cache_first.hit_rate(),
            metrics.cache_first.queries_avoided,
            metrics.cache_first.avg_cache_hit_latency_us,
            metrics.cache_first.avg_cache_miss_latency_us,
            metrics.cache_first.latency_improvement_pct(),
            // Batching metrics
            metrics.batching.total_operations,
            metrics.batching.batched_operations,
            metrics.batching.batching_efficiency(),
            metrics.batching.individual_operations,
            100.0 - metrics.batching.batching_efficiency(),
            metrics.batching.avg_batch_size,
            metrics.batching.round_trips_avoided,
            metrics.batching.round_trip_reduction_pct(),
            metrics.batching.avg_batch_latency_us,
            metrics.batching.avg_individual_latency_us,
            metrics.batching.latency_improvement_pct(),
            // Prepared statement metrics
            metrics.prepared_statements.total_queries,
            metrics.prepared_statements.cached_statements,
            metrics.prepared_statements.cache_hit_rate() * 100.0,
            metrics.prepared_statements.uncached_statements,
            100.0 - metrics.prepared_statements.cache_hit_rate() * 100.0,
            metrics.prepared_statements.avg_cached_execution_us,
            metrics.prepared_statements.avg_uncached_execution_us,
            metrics.prepared_statements.query_speedup_pct(),
            // Query optimization metrics
            metrics.query_optimization.total_metadata_queries,
            metrics.query_optimization.json_extract_queries,
            metrics.query_optimization.optimization_rate(),
            metrics.query_optimization.like_pattern_queries,
            100.0 - metrics.query_optimization.optimization_rate(),
            metrics.query_optimization.avg_json_extract_latency_us,
            metrics.query_optimization.avg_like_pattern_latency_us,
            metrics.query_optimization.query_speedup_pct(),
        )
    }

    /// Reset all metrics
    pub fn reset(&self) {
        let mut metrics = self.metrics.write();
        *metrics = OptimizationMetrics::default();
    }
}

impl Default for PerformanceMetrics {
    fn default() -> Self {
        Self::new()
    }
}