do-memory-storage-turso
Purpose: Primary durable storage using Turso/libSQL
Overview
do-memory-storage-turso implements the durable storage layer for AI agent episodic memory using Turso and libSQL. It provides production-ready distributed SQL storage with connection pooling, circuit breaking, and resilient error handling.
Features
- Distributed Storage: Deploy to Turso's edge network for global low-latency access
- Local Development: Use local libSQL files for offline development
- Production Ready: Connection pooling, circuit breakers, and resilient error handling
- Secure: Parameterized queries, TLS enforcement, credential validation
- Analytics: Complex SQL queries for pattern analysis and insights
- Conflict Resolution: Turso as source of truth with automatic reconciliation
- Vector Indexing: Native DiskANN vector index for semantic search
Key Modules
| Module | Purpose |
|---|---|
schema |
Database schema initialization and migrations |
storage |
Core storage operations and CRUD functionality |
pool |
Semaphore-based connection pooling |
resilient |
Circuit breaker and retry logic |
Installation
Add this to your Cargo.toml:
[]
= "0.1"
Quick Start
With Turso (Production)
use TursoStorage;
async
With Local libSQL (Development)
use TursoStorage;
async
Configuration
Environment Variables
# Production (Turso)
# Development (Local libSQL)
Getting Turso Credentials
- Sign up at turso.tech
- Install Turso CLI:
brew install tursodatabase/tap/turso(macOS) - Create a database:
turso db create my-memory-db - Get the URL:
turso db show my-memory-db --url - Create a token:
turso db tokens create my-memory-db
Database Schema
The storage layer maintains five main tables:
Tables
- episodes: Stores complete episode data with JSON fields for steps, context, and artifacts
- steps: Individual execution steps with timestamps, tool usage, and results
- patterns: Extracted patterns with metadata for retrieval
- embeddings: Vector embeddings for semantic search (if enabled)
- spatiotemporal_index: Spatiotemporal metadata for location/time-aware queries
Indexes
- Native DiskANN Vector Index: Built-in vector similarity search for embeddings
- Secondary Indexes: Optimized queries for episode retrieval, pattern matching, and temporal queries
- Spatial Indexes: Geospatial queries for spatiotemporal features
Schema is automatically initialized on first connection.
Performance
Connection pooling and query optimization ensure excellent performance:
- Concurrent operations: 100+ ops/second
- Connection pool: Configurable size (default: 10)
- Circuit breaker: Automatic failure detection with exponential backoff
- Query caching: Prepared statements for frequently used queries
- Vector similarity: Sub-millisecond search with DiskANN index
Resilience Features
Connection Pooling
- Semaphore-based pool management for efficient resource usage
- Default pool size: 10 connections
- Configurable limits: Adjust based on workload
- Automatic cleanup: Close idle connections
Circuit Breaker
- Automatic failure detection with configurable thresholds
- Exponential backoff for retry attempts
- Half-open state: Probes for recovery before full restoration
- Timeout handling: Prevents cascade failures
Retry Logic
- Configurable retry strategies for transient failures
- Max retry attempts: Prevent infinite loops
- Jitter: Adds randomness to avoid thundering herd
Health Checks
- Endpoint verification: Test database connectivity
- Pool statistics: Monitor connection health
- Metrics tracking: Query performance and error rates
Security
SQL Injection Prevention
- Parameterized queries: All SQL queries use parameter binding
- No string concatenation: Never build SQL queries with user input
- Input validation: Sanitize all data before storage
TLS Enforcement
- Encrypted connections: TLS required for Turso connections
- Certificate validation: Automatic certificate verification
- No plaintext fallback: Rejects unencrypted connections
Credential Validation
- Environment variable validation: Check credentials on startup
- Token expiration handling: Detect and handle expired tokens
- Secure storage: Never log or expose credentials
Input Sanitization
- JSON serialization validation: Validate before storage
- Size limits: Prevent oversized data insertion
- Type checking: Ensure data integrity
Performance Characteristics
| Operation | Latency (P95) | Throughput |
|---|---|---|
| Episode Insert | < 10ms | 100+ ops/s |
| Episode Query | < 5ms | 200+ ops/s |
| Pattern Insert | < 5ms | 200+ ops/s |
| Vector Search | < 50ms | 50+ ops/s |
| Spatiotemporal Query | < 20ms | 100+ ops/s |
Usage with do-memory-core
use SelfLearningMemory;
use TursoStorage;
use RedbStorage;
async
Advanced Configuration
Connection Pool Configuration
use ;
let pool_config = PoolConfig ;
let storage = with_config.await?;
Circuit Breaker Configuration
use ;
let breaker_config = CircuitBreakerConfig ;
let retry_policy = RetryPolicy ;
Monitoring
Pool Statistics
let stats = storage.get_pool_stats?;
println!;
println!;
println!;
Circuit Breaker Status
let status = storage.get_circuit_breaker_status?;
println!;
println!;
println!;
Testing
Run integration tests with a local libSQL database:
For production testing against Turso, set environment variables first:
Dependencies
Core Dependencies
- libsql: Turso/libSQL client library
- tokio: Async runtime
- async-trait: Async trait support
- anyhow: Error handling
- serde: Serialization framework
- serde_json: JSON serialization for stored data
- uuid: Unique identifiers
- chrono: Date/time handling
Documentation
Full API documentation: docs.rs/do-memory-storage-turso
Additional Documentation
- LOCAL_DATABASE_SETUP.md - Local database configuration
- database_schema.md - Detailed schema documentation
License
Licensed under the MIT License. See LICENSE for details.
Project
Part of the rust-self-learning-memory project.
Best Practices
Production Deployment
- Use Turso for distributed, globally accessible storage
- Enable TLS encryption (default)
- Configure connection pool based on expected load
- Monitor circuit breaker status and adjust thresholds
- Set up alerts for high failure rates
Development
- Use local libSQL for offline development
- Lower connection pool size to conserve resources
- Disable circuit breaker for easier debugging
- Use separate database for testing
Security
- Never commit database credentials
- Rotate auth tokens regularly
- Use environment variables for secrets
- Enable query logging for audit trails
- Validate all user inputs
Migration Guide
See database_schema.md for schema changes and migration instructions between versions.