tandem-memory 0.6.9

Memory storage and embedding utilities for Tandem
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
use std::fmt;

use crate::types::{
    CleanupLogEntry, ClearFileIndexResult, GlobalMemoryRecord, GlobalMemorySearchHit,
    GlobalMemoryWriteResult, KnowledgeCoverageRecord, KnowledgeItemRecord,
    KnowledgePromotionRequest, KnowledgePromotionResult, KnowledgeSpaceRecord, LayerType,
    MemoryChunk, MemoryConfig, MemoryError, MemoryLayer, MemoryNode, MemoryStats,
    MemoryTenantScope, MemoryTier, NodeType, ProjectMemoryStats, SourceObjectLifecycleRecord,
    TreeNode,
};

use super::{MemoryReadScope, MemoryWriteScope};

/// Backend-neutral result returned by the portable storage contract.
pub type MemoryStoreResult<T> = Result<T, MemoryStoreError>;

/// Stable error classes that business logic may branch on without knowing the
/// database driver used by the active backend.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MemoryStoreErrorKind {
    InvalidRequest,
    ScopeViolation,
    NotFound,
    Conflict,
    Unsupported,
    Unavailable,
    CorruptData,
    Internal,
}

/// An error crossing the [`super::MemoryStore`] boundary.
///
/// Driver error values deliberately stop at the adapter. The message is useful
/// for diagnostics, while `kind` and `retryable` are the portable contract.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MemoryStoreError {
    pub kind: MemoryStoreErrorKind,
    pub message: String,
    pub retryable: bool,
}

impl MemoryStoreError {
    pub fn new(kind: MemoryStoreErrorKind, message: impl Into<String>) -> Self {
        Self {
            kind,
            message: message.into(),
            retryable: false,
        }
    }

    pub fn retryable(mut self, retryable: bool) -> Self {
        self.retryable = retryable;
        self
    }

    pub fn invalid(message: impl Into<String>) -> Self {
        Self::new(MemoryStoreErrorKind::InvalidRequest, message)
    }

    pub fn unsupported(message: impl Into<String>) -> Self {
        Self::new(MemoryStoreErrorKind::Unsupported, message)
    }
}

impl fmt::Display for MemoryStoreError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(&self.message)
    }
}

impl std::error::Error for MemoryStoreError {}

impl From<MemoryError> for MemoryStoreError {
    fn from(error: MemoryError) -> Self {
        let (kind, retryable) = match &error {
            MemoryError::InvalidConfig(_) => (MemoryStoreErrorKind::InvalidRequest, false),
            MemoryError::TenantScopeViolation(_) => (MemoryStoreErrorKind::ScopeViolation, false),
            MemoryError::NotFound(_) => (MemoryStoreErrorKind::NotFound, false),
            MemoryError::Io(_) => (MemoryStoreErrorKind::Unavailable, true),
            MemoryError::Serialization(_) => (MemoryStoreErrorKind::CorruptData, false),
            MemoryError::Database(_) => (MemoryStoreErrorKind::Internal, false),
            MemoryError::Embedding(_)
            | MemoryError::Chunking(_)
            | MemoryError::Tokenization(_)
            | MemoryError::Lock(_) => (MemoryStoreErrorKind::Internal, false),
        };
        Self::new(kind, error.to_string()).retryable(retryable)
    }
}

/// Coordinates selecting chunks in one memory tier.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MemoryChunkSelector {
    pub tier: MemoryTier,
    pub project_id: Option<String>,
    pub session_id: Option<String>,
}

impl MemoryChunkSelector {
    pub fn session(session_id: impl Into<String>) -> Self {
        Self {
            tier: MemoryTier::Session,
            project_id: None,
            session_id: Some(session_id.into()),
        }
    }

    pub fn session_in_project(
        session_id: impl Into<String>,
        project_id: impl Into<String>,
    ) -> Self {
        Self {
            tier: MemoryTier::Session,
            project_id: Some(project_id.into()),
            session_id: Some(session_id.into()),
        }
    }

    pub fn project(project_id: impl Into<String>) -> Self {
        Self {
            tier: MemoryTier::Project,
            project_id: Some(project_id.into()),
            session_id: None,
        }
    }

    /// Select every session-tier chunk visible within the request scope.
    ///
    /// This selector is valid for vector search only. Point/list operations
    /// continue to require a concrete session id.
    pub fn all_sessions() -> Self {
        Self {
            tier: MemoryTier::Session,
            project_id: None,
            session_id: None,
        }
    }

    pub fn global() -> Self {
        Self {
            tier: MemoryTier::Global,
            project_id: None,
            session_id: None,
        }
    }
}

/// Scoped point/list reads used by memory business logic.
#[derive(Debug, Clone)]
pub enum MemoryStoreReadRequest {
    Chunks {
        scope: MemoryReadScope,
        selector: MemoryChunkSelector,
        limit: Option<i64>,
    },
    GlobalRecord {
        scope: MemoryReadScope,
        id: String,
    },
    ProjectConfig {
        scope: MemoryReadScope,
        project_id: String,
    },
    Stats {
        scope: MemoryReadScope,
    },
    ProjectStats {
        scope: MemoryReadScope,
        project_id: String,
    },
    KnowledgeSpace {
        scope: MemoryReadScope,
        id: String,
    },
    KnowledgeItem {
        scope: MemoryReadScope,
        id: String,
    },
    KnowledgeCoverage {
        scope: MemoryReadScope,
        coverage_key: String,
        space_id: String,
    },
    ImportIndexEntry {
        scope: MemoryReadScope,
        selector: MemoryChunkSelector,
        path: String,
    },
    ContextNode {
        scope: MemoryReadScope,
        uri: String,
    },
    ContextLayer {
        scope: MemoryReadScope,
        node_id: String,
        layer_type: LayerType,
    },
}

/// Typed values returned by [`MemoryStoreReadRequest`].
#[derive(Debug, Clone)]
pub enum MemoryStoreReadResult {
    Chunks(Vec<MemoryChunk>),
    GlobalRecord(Option<GlobalMemoryRecord>),
    ProjectConfig(MemoryConfig),
    Stats(MemoryStats),
    ProjectStats(ProjectMemoryStats),
    KnowledgeSpace(Option<KnowledgeSpaceRecord>),
    KnowledgeItem(Option<KnowledgeItemRecord>),
    KnowledgeCoverage(Option<KnowledgeCoverageRecord>),
    ImportIndexEntry(Option<MemoryImportIndexEntry>),
    ContextNode(Option<MemoryNode>),
    ContextLayer(Option<MemoryLayer>),
}

/// Portable replacement for the concrete import-index tuple.
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct MemoryImportIndexEntry {
    pub modified_at: i64,
    pub size: i64,
    pub hash: String,
}

/// Scoped search and filtered-list operations.
#[derive(Debug, Clone)]
pub enum MemoryStoreQueryRequest {
    SimilarChunks {
        scope: MemoryReadScope,
        selector: MemoryChunkSelector,
        query_embedding: Vec<f32>,
        limit: i64,
    },
    SearchGlobalRecords {
        scope: MemoryReadScope,
        user_id: String,
        query: String,
        limit: i64,
        project_tag: Option<String>,
    },
    ListGlobalRecords {
        scope: MemoryReadScope,
        user_id: String,
        query: Option<String>,
        project_tag: Option<String>,
        channel_tag: Option<String>,
        limit: i64,
        offset: i64,
    },
    KnowledgeSpaces {
        scope: MemoryReadScope,
        project_id: Option<String>,
    },
    KnowledgeItems {
        scope: MemoryReadScope,
        space_id: String,
        coverage_key: Option<String>,
    },
    ImportIndexPaths {
        scope: MemoryReadScope,
        selector: MemoryChunkSelector,
    },
    CleanupLog {
        scope: MemoryReadScope,
        limit: i64,
    },
    ContextNodes {
        scope: MemoryReadScope,
        parent_uri: String,
    },
    ContextTree {
        scope: MemoryReadScope,
        parent_uri: String,
        max_depth: usize,
    },
    SourceObjectLifecyclesForBinding {
        scope: MemoryReadScope,
        source_binding_id: String,
    },
}

/// Typed values returned by [`MemoryStoreQueryRequest`].
#[derive(Debug, Clone)]
pub enum MemoryStoreQueryResult {
    SimilarChunks(Vec<(MemoryChunk, f64)>),
    GlobalSearchHits(Vec<GlobalMemorySearchHit>),
    GlobalRecords(Vec<GlobalMemoryRecord>),
    KnowledgeSpaces(Vec<KnowledgeSpaceRecord>),
    KnowledgeItems(Vec<KnowledgeItemRecord>),
    Paths(Vec<String>),
    CleanupLog(Vec<CleanupLogEntry>),
    ContextNodes(Vec<MemoryNode>),
    ContextTree(Vec<TreeNode>),
    SourceObjectLifecycles(Vec<SourceObjectLifecycleRecord>),
}

/// Backend-neutral cleanup audit row to append.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MemoryCleanupLogWrite {
    pub cleanup_type: String,
    pub tier: MemoryTier,
    pub project_id: Option<String>,
    pub session_id: Option<String>,
    pub chunks_deleted: i64,
    pub bytes_reclaimed: i64,
}

/// Scoped inserts and upserts.
#[derive(Debug, Clone)]
pub enum MemoryStoreWriteRequest {
    Chunk {
        scope: MemoryWriteScope,
        chunk: MemoryChunk,
        embedding: Vec<f32>,
    },
    GlobalRecord {
        scope: MemoryWriteScope,
        record: GlobalMemoryRecord,
    },
    ProjectConfig {
        scope: MemoryWriteScope,
        project_id: String,
        config: MemoryConfig,
    },
    KnowledgeSpace {
        scope: MemoryWriteScope,
        record: KnowledgeSpaceRecord,
    },
    KnowledgeItem {
        scope: MemoryWriteScope,
        record: KnowledgeItemRecord,
    },
    KnowledgeCoverage {
        scope: MemoryWriteScope,
        record: KnowledgeCoverageRecord,
    },
    ImportIndexEntry {
        scope: MemoryWriteScope,
        selector: MemoryChunkSelector,
        path: String,
        entry: MemoryImportIndexEntry,
    },
    ProjectIndexStatus {
        scope: MemoryWriteScope,
        project_id: String,
        total_files: i64,
        processed_files: i64,
        indexed_files: i64,
        skipped_files: i64,
        errors: i64,
    },
    /// Insert a source object or refresh its active lifecycle state.
    SourceObjectLifecycle {
        scope: MemoryWriteScope,
        record: SourceObjectLifecycleRecord,
    },
    ContextNode {
        scope: MemoryWriteScope,
        uri: String,
        parent_uri: Option<String>,
        node_type: NodeType,
        metadata: Option<serde_json::Value>,
    },
    ContextLayer {
        scope: MemoryWriteScope,
        node_id: String,
        layer_type: LayerType,
        content: String,
        token_count: i64,
        source_chunk_id: Option<String>,
    },
    CleanupLog {
        scope: MemoryWriteScope,
        entry: MemoryCleanupLogWrite,
    },
}

/// Typed values returned by [`MemoryStoreWriteRequest`].
#[derive(Debug, Clone)]
pub enum MemoryStoreWriteResult {
    Stored,
    GlobalRecord(GlobalMemoryWriteResult),
    ContextNodeCreated(String),
    ContextLayerCreated(String),
}

/// Scoped updates, deletes, maintenance, and other state transitions.
#[derive(Debug, Clone)]
pub enum MemoryStoreMutationRequest {
    DeleteChunk {
        scope: MemoryReadScope,
        selector: MemoryChunkSelector,
        chunk_id: String,
    },
    ClearSession {
        scope: MemoryReadScope,
        session_id: String,
    },
    /// Atomically replace an exact set of visible session chunks with one
    /// scoped project summary. Backends must reject the whole operation if any
    /// source chunk is missing or outside `scope`.
    ReplaceSessionWithSummary {
        scope: MemoryReadScope,
        session_id: String,
        project_id: String,
        source_chunk_ids: Vec<String>,
        summary_scope: MemoryWriteScope,
        summary: Box<MemoryChunk>,
        embedding: Vec<f32>,
    },
    ClearProject {
        scope: MemoryReadScope,
        project_id: String,
    },
    ClearProjectFileIndex {
        scope: MemoryReadScope,
        project_id: String,
        vacuum: bool,
    },
    DeleteGlobalRecord {
        scope: MemoryReadScope,
        id: String,
    },
    UpdateGlobalRecordContext {
        scope: MemoryReadScope,
        id: String,
        visibility: String,
        demoted: bool,
        metadata: Option<serde_json::Value>,
        provenance: Option<serde_json::Value>,
    },
    PromoteKnowledgeItem {
        scope: MemoryReadScope,
        request: KnowledgePromotionRequest,
    },
    DeleteImportIndexEntry {
        scope: MemoryReadScope,
        selector: MemoryChunkSelector,
        path: String,
    },
    /// Delete imported file chunks and their vectors for one source path.
    DeleteChunksBySourcePath {
        scope: MemoryReadScope,
        selector: MemoryChunkSelector,
        source_path: String,
    },
    /// Replace metadata on imported file chunks for one source path.
    UpdateChunkMetadataBySourcePath {
        scope: MemoryReadScope,
        selector: MemoryChunkSelector,
        source_path: String,
        metadata: serde_json::Value,
    },
    /// Mark a source object as no longer present in its source binding.
    TombstoneSourceObjectLifecycle {
        scope: MemoryReadScope,
        source_binding_id: String,
        native_object_id: String,
        tombstoned_at_ms: u64,
    },
    SetSourceObjectLifecycleState {
        scope: MemoryReadScope,
        source_binding_id: String,
        source_object_id: String,
        state: crate::types::SourceObjectLifecycleState,
        changed_at_ms: u64,
    },
    RunHygiene {
        scope: MemoryReadScope,
        retention_days: u32,
    },
    /// Run retention across every tenant partition. This is a backend-owned
    /// scheduled-maintenance operation, not a caller-supplied tenant action.
    RunHygieneAllTenants {
        retention_days: u32,
    },
    EnforceProjectChunkCap {
        scope: MemoryReadScope,
        project_id: String,
        max_chunks: i64,
    },
    /// Reclaim unused storage across the whole backend.
    Vacuum,
}

/// Typed values returned by [`MemoryStoreMutationRequest`].
#[derive(Debug, Clone)]
#[allow(clippy::large_enum_variant)]
pub enum MemoryStoreMutationResult {
    Affected(u64),
    Changed(bool),
    SourcePathDelete(MemorySourcePathDeleteResult),
    ClearFileIndex(ClearFileIndexResult),
    Promotion(Option<KnowledgePromotionResult>),
    Completed,
}

/// Counts reported after deleting imported chunks for one source path.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct MemorySourcePathDeleteResult {
    pub chunks_deleted: i64,
    pub bytes_reclaimed: i64,
}

/// Commit semantics requested for multiple storage operations.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MemoryStoreBatchMode {
    /// All writes commit or all writes roll back.
    Atomic,
    /// Stop after the first failed item; already completed items remain applied.
    StopOnError,
    /// Attempt every item and report each outcome.
    BestEffort,
}

#[derive(Debug, Clone)]
#[allow(clippy::large_enum_variant)]
pub enum MemoryStoreBatchOperation {
    Write(MemoryStoreWriteRequest),
    Mutation(MemoryStoreMutationRequest),
}

#[derive(Debug, Clone)]
pub struct MemoryStoreBatchRequest {
    pub mode: MemoryStoreBatchMode,
    pub operations: Vec<MemoryStoreBatchOperation>,
}

#[derive(Debug, Clone)]
#[allow(clippy::large_enum_variant)]
pub enum MemoryStoreBatchValue {
    Write(MemoryStoreWriteResult),
    Mutation(MemoryStoreMutationResult),
}

#[derive(Debug, Clone)]
pub struct MemoryStoreBatchItemResult {
    pub index: usize,
    pub result: MemoryStoreResult<MemoryStoreBatchValue>,
}

#[derive(Debug, Clone)]
pub struct MemoryStoreBatchResult {
    /// True only when every requested operation completed successfully.
    pub completed: bool,
    pub items: Vec<MemoryStoreBatchItemResult>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum MemoryBackendKind {
    Sqlite,
    Postgres,
    Other(String),
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MemoryBackendHealthStatus {
    Healthy,
    Degraded,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct MemoryBackendHealthRequest {
    /// Permit the backend to repair its vector/index structures during probing.
    pub repair: bool,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MemoryBackendHealthResult {
    pub backend: MemoryBackendKind,
    pub status: MemoryBackendHealthStatus,
    pub repaired: bool,
    pub checks: Vec<MemoryBackendHealthCheck>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MemoryBackendHealthCheck {
    pub name: String,
    pub healthy: bool,
    pub detail: Option<String>,
}

/// Explicit backend-wide recovery actions.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MemoryBackendRecoveryAction {
    /// Repair backend-owned indexes without deleting memory records.
    RepairIndexes,
    /// Drop all memory data and recreate the backend schema.
    ResetAllData,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct MemoryBackendRecoveryRequest {
    pub action: MemoryBackendRecoveryAction,
    /// Must be true for [`MemoryBackendRecoveryAction::ResetAllData`].
    pub confirm_data_loss: bool,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MemoryBackendRecoveryResult {
    pub backend: MemoryBackendKind,
    pub action: MemoryBackendRecoveryAction,
    /// True when the backend changed persistent state.
    pub changed: bool,
}

/// Requirements a migration coordinator can ask a backend to satisfy.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct MemoryMigrationCapabilityRequest {
    pub require_version_introspection: bool,
    pub require_transactional_apply: bool,
    pub require_online_apply: bool,
    pub require_dry_run: bool,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MemoryMigrationApplyMode {
    OnOpen,
    Explicit,
}

/// Backend migration features, separate from any backend's DDL syntax.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MemoryMigrationCapabilityResult {
    pub backend: MemoryBackendKind,
    pub apply_mode: MemoryMigrationApplyMode,
    pub version_introspection: bool,
    pub transactional_apply: bool,
    pub online_apply: bool,
    pub dry_run: bool,
    pub requirements_satisfied: bool,
}

impl MemoryMigrationCapabilityResult {
    pub fn satisfies(&self, request: &MemoryMigrationCapabilityRequest) -> bool {
        (!request.require_version_introspection || self.version_introspection)
            && (!request.require_transactional_apply || self.transactional_apply)
            && (!request.require_online_apply || self.online_apply)
            && (!request.require_dry_run || self.dry_run)
    }
}

pub(crate) fn tenant_scope_from_global_record(record: &GlobalMemoryRecord) -> MemoryTenantScope {
    record
        .provenance
        .as_ref()
        .and_then(|value| value.get("tenant_context"))
        .and_then(|value| {
            Some(MemoryTenantScope {
                org_id: value.get("org_id")?.as_str()?.to_string(),
                workspace_id: value.get("workspace_id")?.as_str()?.to_string(),
                deployment_id: value
                    .get("deployment_id")
                    .and_then(serde_json::Value::as_str)
                    .map(ToString::to_string),
            })
        })
        .unwrap_or_default()
}