chaotic_semantic_memory 0.3.2

AI memory systems with hyperdimensional vectors and chaotic reservoirs
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
use libsql::params;
use tokio::fs;
use tracing::{info, warn};

use crate::error::{MemoryError, Result};
use crate::persistence::{ConceptVersion, Persistence};

impl Persistence {
    pub async fn save_associations(&self, associations: &[(String, String, f32)]) -> Result<()> {
        if associations.is_empty() {
            return Ok(());
        }

        let _permit = self.acquire_remote_slot().await?;
        let conn = self.connect().await?;
        conn.execute("BEGIN", ())
            .await
            .map_err(|e| MemoryError::database(format!("Failed to begin transaction: {}", e)))?;

        let mut first_error: Option<MemoryError> = None;
        for (from, to, strength) in associations {
            if let Err(e) = conn
                .execute(
                    "INSERT OR REPLACE INTO csm_associations (from_id, to_id, strength)
                     VALUES (?1, ?2, ?3)",
                    params![from.clone(), to.clone(), *strength],
                )
                .await
            {
                first_error = Some(MemoryError::database(format!(
                    "Failed to batch save association: {}",
                    e
                )));
                break;
            }
        }

        if let Some(error) = first_error {
            let _ = conn.execute("ROLLBACK", ()).await;
            return Err(error);
        }

        conn.execute("COMMIT", ())
            .await
            .map_err(|e| MemoryError::database(format!("Failed to commit transaction: {}", e)))?;

        Ok(())
    }

    pub async fn clear_all(&self) -> Result<()> {
        let _permit = self.acquire_remote_slot().await?;
        let conn = self.connect().await?;
        conn.execute_batch(
            "BEGIN;
             DELETE FROM csm_associations;
             DELETE FROM csm_versions;
             DELETE FROM csm_concepts;
             COMMIT;",
        )
        .await
        .map_err(|e| MemoryError::database(format!("Failed to clear all data: {}", e)))?;
        Ok(())
    }

    pub async fn get_concept_history(&self, id: &str, limit: usize) -> Result<Vec<ConceptVersion>> {
        let _permit = self.acquire_remote_slot().await?;
        let conn = self.connect().await?;

        let mut rows = conn
            .query(
                "SELECT concept_id, version, vector, metadata, modified_at
                 FROM csm_versions
                 WHERE concept_id = ?1
                 ORDER BY version DESC
                 LIMIT ?2",
                libsql::params![id, limit as i64],
            )
            .await
            .map_err(|e| MemoryError::database(format!("Failed to load concept history: {}", e)))?;

        let mut history = Vec::new();
        while let Some(row) = rows.next().await.map_err(|e| {
            MemoryError::database(format!("Failed to fetch concept history row: {}", e))
        })? {
            let concept_id: String = row
                .get(0)
                .map_err(|e| MemoryError::database(format!("Failed to get concept_id: {}", e)))?;
            let version: i64 = row
                .get(1)
                .map_err(|e| MemoryError::database(format!("Failed to get version: {}", e)))?;
            let vector_bytes: Vec<u8> = row
                .get(2)
                .map_err(|e| MemoryError::database(format!("Failed to get vector: {}", e)))?;
            let metadata_json: String = row
                .get(3)
                .map_err(|e| MemoryError::database(format!("Failed to get metadata: {}", e)))?;
            let modified_at: i64 = row
                .get(4)
                .map_err(|e| MemoryError::database(format!("Failed to get modified_at: {}", e)))?;

            history.push(ConceptVersion {
                concept_id,
                version,
                vector: crate::hyperdim::HVec10240::from_bytes(&vector_bytes)?,
                metadata: serde_json::from_str(&metadata_json)?,
                modified_at: modified_at as u64,
            });
        }

        Ok(history)
    }

    pub async fn schema_version(&self) -> Result<i64> {
        let _permit = self.acquire_remote_slot().await?;
        let conn = self.connect().await?;
        let mut rows = conn
            .query(
                "SELECT COALESCE(MAX(version), 0) FROM csm_schema_version",
                (),
            )
            .await
            .map_err(|e| MemoryError::database(format!("Failed to get schema version: {}", e)))?;

        if let Some(row) = rows.next().await.map_err(|e| {
            MemoryError::database(format!("Failed to fetch schema version row: {}", e))
        })? {
            let version: i64 = row.get(0).map_err(|e| {
                MemoryError::database(format!("Failed to parse schema version: {}", e))
            })?;
            Ok(version)
        } else {
            Ok(0)
        }
    }

    pub async fn apply_migrations(&self, target_version: i64) -> Result<()> {
        let current = self.schema_version().await?;
        if target_version <= current {
            return Ok(());
        }

        let _permit = self.acquire_remote_slot().await?;
        let conn = self.connect().await?;
        conn.execute("BEGIN", ()).await.map_err(|e| {
            MemoryError::database(format!("Failed to begin migration transaction: {}", e))
        })?;

        for version in (current + 1)..=target_version {
            info!(version, "applying schema migration");
            if version == 2 {
                conn.execute_batch(
                    "CREATE INDEX IF NOT EXISTS idx_csm_versions_modified_at
                     ON csm_versions(modified_at);",
                )
                .await
                .map_err(|e| MemoryError::database(format!("Failed migration v2: {}", e)))?;
            }

            if version == 3 {
                // Add expires_at column for TTL support
                conn.execute_batch("ALTER TABLE csm_concepts ADD COLUMN expires_at INTEGER;")
                    .await
                    .map_err(|e| MemoryError::database(format!("Failed migration v3: {}", e)))?;
            }

            if version == 4 {
                // Add canonical_concepts table for semantic bridge
                conn.execute_batch(
                    "CREATE TABLE IF NOT EXISTS csm_canonical (
                        id TEXT PRIMARY KEY,
                        version INTEGER NOT NULL,
                        labels_json TEXT NOT NULL,
                        related_json TEXT NOT NULL
                    );",
                )
                .await
                .map_err(|e| MemoryError::database(format!("Failed migration v4: {}", e)))?;
            }

            if version == 5 {
                // Rename tables to use csm_ prefix for namespace isolation
                // Only rename if old tables exist (handles both new and existing databases)
                // Use SQLite's table existence check
                let has_old_tables: bool = conn
                    .query(
                        "SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name='concepts'",
                        (),
                    )
                    .await
                    .map_err(|e| MemoryError::database(format!("Failed to check tables: {}", e)))?
                    .next()
                    .await
                    .map_err(|e| MemoryError::database(format!("Failed to fetch: {}", e)))?
                    .map(|row| row.get::<i64>(0).unwrap_or(0) > 0)
                    .unwrap_or(false);

                if has_old_tables {
                    conn.execute_batch(
                        "ALTER TABLE concepts RENAME TO csm_concepts;
                         ALTER TABLE associations RENAME TO csm_associations;
                         ALTER TABLE concept_versions RENAME TO csm_versions;
                         DROP TABLE __schema_version;
                         ALTER TABLE canonical_concepts RENAME TO csm_canonical;",
                    )
                    .await
                    .map_err(|e| {
                        MemoryError::database(format!("Failed migration v5 rename: {}", e))
                    })?;
                }
            }

            conn.execute(
                "INSERT INTO csm_schema_version(version) VALUES (?1)",
                libsql::params![version],
            )
            .await
            .map_err(|e| {
                MemoryError::database(format!("Failed to record schema version: {}", e))
            })?;
        }

        conn.execute("COMMIT", ())
            .await
            .map_err(|e| MemoryError::database(format!("Failed to commit migrations: {}", e)))?;

        Ok(())
    }

    pub async fn backup(&self, path: &str) -> Result<()> {
        let Some(_local_path) = &self.local_path else {
            return Err(MemoryError::UnsupportedOperation(
                "backup is only supported for local SQLite databases".to_string(),
            ));
        };

        self.checkpoint().await?;
        if fs::metadata(path).await.is_ok() {
            fs::remove_file(path).await.map_err(MemoryError::Io)?;
        }

        let _permit = self.acquire_remote_slot().await?;
        let conn = self.connect().await?;
        conn.execute("VACUUM INTO ?1", params![path])
            .await
            .map_err(|e| MemoryError::database(format!("Failed to create backup: {}", e)))?;
        Ok(())
    }

    pub async fn restore(&self, path: &str) -> Result<()> {
        let Some(_local_path) = &self.local_path else {
            return Err(MemoryError::UnsupportedOperation(
                "restore is only supported for local SQLite databases".to_string(),
            ));
        };

        fs::metadata(path).await.map_err(MemoryError::Io)?;

        let _permit = self.acquire_remote_slot().await?;
        let conn = self.connect().await?;
        conn.execute("BEGIN IMMEDIATE", ()).await.map_err(|e| {
            MemoryError::database(format!("Failed to begin restore transaction: {}", e))
        })?;

        if let Err(error) = async {
            conn.execute("ATTACH DATABASE ?1 AS restore_db", params![path])
                .await
                .map_err(|e| MemoryError::database(format!("Failed to attach backup DB: {}", e)))?;

            conn.execute_batch(
                "DELETE FROM csm_associations;
                 DELETE FROM csm_versions;
                 DELETE FROM csm_concepts;
                 DELETE FROM csm_schema_version;",
            )
            .await
            .map_err(|e| MemoryError::database(format!("Failed to clear current database: {}", e)))?;

            conn.execute_batch(
                "INSERT INTO csm_concepts (id, vector, metadata, created_at, modified_at)
                 SELECT id, vector, metadata, created_at, modified_at FROM restore_db.csm_concepts;
                 INSERT INTO csm_associations (from_id, to_id, strength)
                 SELECT from_id, to_id, strength FROM restore_db.csm_associations;
                 INSERT INTO csm_versions (concept_id, version, vector, metadata, modified_at)
                 SELECT concept_id, version, vector, metadata, modified_at FROM restore_db.csm_versions;
                 INSERT INTO csm_schema_version(version)
                 SELECT version FROM restore_db.csm_schema_version;",
            )
            .await
            .map_err(|e| MemoryError::database(format!("Failed to import backup data: {}", e)))?;

            Ok::<(), MemoryError>(())
        }
        .await
        {
            let _ = conn.execute_batch("ROLLBACK;").await;
            return Err(error);
        }

        conn.execute("COMMIT", ())
            .await
            .map_err(|e| MemoryError::database(format!("Failed to commit restore: {}", e)))?;
        if let Err(error) = conn.execute_batch("DETACH DATABASE restore_db;").await {
            warn!(error = %error, "failed to detach restore_db after restore");
        }

        self.init_schema().await?;
        Ok(())
    }

    pub async fn health_check(&self) -> Result<()> {
        let _permit = self.acquire_remote_slot().await?;
        let conn = self.connect().await?;
        conn.query("SELECT 1", ()).await.map_err(|e| {
            MemoryError::database(format!("Failed persistence health check: {}", e))
        })?;
        Ok(())
    }

    /// Delete a single association between two concepts.
    pub async fn delete_association(&self, from: &str, to: &str) -> Result<()> {
        let _permit = self.acquire_remote_slot().await?;
        let conn = self.connect().await?;
        conn.execute(
            "DELETE FROM csm_associations WHERE from_id = ?1 AND to_id = ?2",
            params![from, to],
        )
        .await
        .map_err(|e| MemoryError::database(format!("Failed to delete association: {}", e)))?;
        Ok(())
    }

    /// Clear all outbound associations for a concept.
    pub async fn clear_concept_associations(&self, id: &str) -> Result<()> {
        let _permit = self.acquire_remote_slot().await?;
        let conn = self.connect().await?;
        conn.execute(
            "DELETE FROM csm_associations WHERE from_id = ?1",
            params![id],
        )
        .await
        .map_err(|e| {
            MemoryError::database(format!("Failed to clear concept associations: {}", e))
        })?;
        Ok(())
    }

    /// Internal migration method that reuses an existing connection.
    /// Used by init_schema() to avoid semaphore deadlock from nested permit acquisition.
    pub(crate) async fn apply_migrations_with_conn(
        &self,
        conn: &libsql::Connection,
        target_version: i64,
    ) -> Result<()> {
        let current = self.schema_version_with_conn(conn).await?;
        if target_version <= current {
            return Ok(());
        }

        conn.execute("BEGIN", ()).await.map_err(|e| {
            MemoryError::database(format!("Failed to begin migration transaction: {}", e))
        })?;

        for version in (current + 1)..=target_version {
            info!(version, "applying schema migration");
            if version == 2 {
                conn.execute_batch(
                    "CREATE INDEX IF NOT EXISTS idx_csm_versions_modified_at
                     ON csm_versions(modified_at);",
                )
                .await
                .map_err(|e| MemoryError::database(format!("Failed migration v2: {}", e)))?;
            }

            if version == 3 {
                // Add expires_at column for TTL support
                conn.execute_batch("ALTER TABLE csm_concepts ADD COLUMN expires_at INTEGER;")
                    .await
                    .map_err(|e| MemoryError::database(format!("Failed migration v3: {}", e)))?;
            }

            if version == 4 {
                // Add canonical_concepts table for semantic bridge
                conn.execute_batch(
                    "CREATE TABLE IF NOT EXISTS csm_canonical (
                        id TEXT PRIMARY KEY,
                        version INTEGER NOT NULL,
                        labels_json TEXT NOT NULL,
                        related_json TEXT NOT NULL
                    );",
                )
                .await
                .map_err(|e| MemoryError::database(format!("Failed migration v4: {}", e)))?;
            }

            if version == 5 {
                // Rename tables to use csm_ prefix for namespace isolation
                // Only rename if old tables exist (handles both new and existing databases)
                // Use SQLite's table existence check
                let has_old_tables: bool = conn
                    .query(
                        "SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name='concepts'",
                        (),
                    )
                    .await
                    .map_err(|e| MemoryError::database(format!("Failed to check tables: {}", e)))?
                    .next()
                    .await
                    .map_err(|e| MemoryError::database(format!("Failed to fetch: {}", e)))?
                    .map(|row| row.get::<i64>(0).unwrap_or(0) > 0)
                    .unwrap_or(false);

                if has_old_tables {
                    conn.execute_batch(
                        "ALTER TABLE concepts RENAME TO csm_concepts;
                         ALTER TABLE associations RENAME TO csm_associations;
                         ALTER TABLE concept_versions RENAME TO csm_versions;
                         DROP TABLE __schema_version;
                         ALTER TABLE canonical_concepts RENAME TO csm_canonical;",
                    )
                    .await
                    .map_err(|e| {
                        MemoryError::database(format!("Failed migration v5 rename: {}", e))
                    })?;
                }
            }

            conn.execute(
                "INSERT INTO csm_schema_version(version) VALUES (?1)",
                libsql::params![version],
            )
            .await
            .map_err(|e| {
                MemoryError::database(format!("Failed to record schema version: {}", e))
            })?;
        }

        conn.execute("COMMIT", ())
            .await
            .map_err(|e| MemoryError::database(format!("Failed to commit migrations: {}", e)))?;

        Ok(())
    }

    /// Internal schema version query that reuses an existing connection.
    async fn schema_version_with_conn(&self, conn: &libsql::Connection) -> Result<i64> {
        let mut rows = conn
            .query(
                "SELECT COALESCE(MAX(version), 0) FROM csm_schema_version",
                (),
            )
            .await
            .map_err(|e| MemoryError::database(format!("Failed to get schema version: {}", e)))?;

        if let Some(row) = rows.next().await.map_err(|e| {
            MemoryError::database(format!("Failed to fetch schema version row: {}", e))
        })? {
            let version: i64 = row.get(0).map_err(|e| {
                MemoryError::database(format!("Failed to parse schema version: {}", e))
            })?;
            Ok(version)
        } else {
            Ok(0)
        }
    }
}