codex-memory 3.0.15

A simple memory storage service with MCP interface for Claude Desktop
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
use crate::common::TestDatabaseManager;
use anyhow::Result;
use codex_memory::Storage;
use serial_test::serial;
use std::sync::Arc;

/// Test content size limits and edge cases
#[tokio::test]
#[serial]
async fn test_empty_content() -> Result<()> {
    let mut manager = TestDatabaseManager::new()?;
    let pool = manager.setup_test_database().await?;
    let storage = Arc::new(Storage::new(pool));

    // Test completely empty string
    let result = storage
        .store(
            "",
            "Test context".to_string(),
            "Test summary".to_string(),
            None,
        )
        .await;
    assert!(result.is_ok(), "Empty content should be allowed");

    let id = result?;
    let retrieved = storage
        .get(id)
        .await?
        .expect("Should retrieve empty content");
    assert_eq!(retrieved.content, "");

    manager.cleanup().await?;
    Ok(())
}

#[tokio::test]
#[serial]
async fn test_whitespace_only_content() -> Result<()> {
    let mut manager = TestDatabaseManager::new()?;
    let pool = manager.setup_test_database().await?;
    let storage = Arc::new(Storage::new(pool));

    let whitespace_variations = [
        " ",        // Single space
        "   ",      // Multiple spaces
        "\t",       // Tab
        "\n",       // Newline
        "\r\n",     // Windows newline
        " \t\n\r ", // Mixed whitespace
    ];

    for (i, content) in whitespace_variations.iter().enumerate() {
        let id = storage
            .store(
                content,
                format!("Whitespace test #{}", i),
                "Test summary".to_string(),
                None,
            )
            .await?;

        let retrieved = storage
            .get(id)
            .await?
            .expect("Should retrieve whitespace content");
        assert_eq!(
            retrieved.content, *content,
            "Whitespace should be preserved exactly"
        );
    }

    manager.cleanup().await?;
    Ok(())
}

#[tokio::test]
#[serial]
async fn test_unicode_and_emoji_content() -> Result<()> {
    let mut manager = TestDatabaseManager::new()?;
    let pool = manager.setup_test_database().await?;
    let storage = Arc::new(Storage::new(pool));

    let unicode_tests = [
        "Hello 世界",       // Mixed English/Chinese
        "🎉 🚀 💾 🔥 ⭐",   // Emojis
        "Ñoño ñoño ÑOÑO",   // Spanish characters
        "Здравствуй мир",   // Cyrillic
        "مرحبا بالعالم",    // Arabic (RTL)
        "🏳️‍🌈 🏳️‍⚧️ 👨‍👩‍👧‍👦",         // Complex emoji sequences
        "Test\u{0000}null", // Null byte (might be problematic)
        "Test\u{FEFF}BOM",  // Byte order mark
    ];

    for (i, content) in unicode_tests.iter().enumerate() {
        let result = storage
            .store(
                content,
                format!("Unicode test #{}", i),
                "Test summary".to_string(),
                None,
            )
            .await;

        match result {
            Ok(id) => {
                let retrieved = storage
                    .get(id)
                    .await?
                    .expect("Should retrieve unicode content");
                assert_eq!(
                    retrieved.content, *content,
                    "Unicode content should be preserved exactly"
                );
            }
            Err(e) => {
                // Some content (like null bytes) might legitimately fail
                println!(
                    "Content '{}' failed as expected: {}",
                    content.escape_debug(),
                    e
                );
            }
        }
    }

    manager.cleanup().await?;
    Ok(())
}

#[tokio::test]
#[serial]
async fn test_large_content_1mb() -> Result<()> {
    let mut manager = TestDatabaseManager::new()?;
    let pool = manager.setup_test_database().await?;
    let storage = Arc::new(Storage::new(pool));

    // Generate 1MB of content
    let chunk = "This is a test string that will be repeated many times to create large content. ";
    let target_size = 1024 * 1024; // 1MB
    let repeats = target_size / chunk.len() + 1;
    let large_content = chunk.repeat(repeats);
    let large_content = &large_content[..target_size]; // Trim to exact size

    println!("Testing {}KB content", large_content.len() / 1024);

    let start = std::time::Instant::now();
    let result = storage
        .store(
            large_content,
            "1MB content test".to_string(),
            "Large content performance test".to_string(),
            Some(vec!["large".to_string(), "performance".to_string()]),
        )
        .await;
    let storage_time = start.elapsed();

    println!("Storage took: {:?}", storage_time);

    match result {
        Ok(id) => {
            let start = std::time::Instant::now();
            let retrieved = storage
                .get(id)
                .await?
                .expect("Should retrieve large content");
            let retrieval_time = start.elapsed();

            println!("Retrieval took: {:?}", retrieval_time);

            assert_eq!(retrieved.content.len(), large_content.len());
            assert_eq!(retrieved.content, large_content);

            // Performance expectations (adjust based on your requirements)
            assert!(
                storage_time < std::time::Duration::from_secs(10),
                "Storage should complete within 10 seconds"
            );
            assert!(
                retrieval_time < std::time::Duration::from_secs(5),
                "Retrieval should complete within 5 seconds"
            );
        }
        Err(e) => {
            println!("Large content failed (may be expected): {}", e);
            // Depending on database configuration, this might fail
            // Document the actual limits in your system
        }
    }

    manager.cleanup().await?;
    Ok(())
}

#[tokio::test]
#[serial]
async fn test_extremely_large_content_10mb() -> Result<()> {
    let mut manager = TestDatabaseManager::new()?;
    let pool = manager.setup_test_database().await?;
    let storage = Arc::new(Storage::new(pool));

    // Generate 10MB of content
    let chunk = "Large content test data - this will be repeated to create a very large payload for testing database limits and performance characteristics. ";
    let target_size = 10 * 1024 * 1024; // 10MB
    let repeats = target_size / chunk.len() + 1;
    let huge_content = chunk.repeat(repeats);
    let huge_content = &huge_content[..target_size]; // Trim to exact size

    println!("Testing {}MB content", huge_content.len() / (1024 * 1024));

    let start = std::time::Instant::now();
    let result = storage
        .store(
            huge_content,
            "10MB content stress test".to_string(),
            "Extremely large content for database limit testing".to_string(),
            Some(vec!["stress".to_string(), "limit".to_string()]),
        )
        .await;
    let storage_time = start.elapsed();

    println!("Storage attempt took: {:?}", storage_time);

    match result {
        Ok(id) => {
            println!("Successfully stored 10MB content");

            let start = std::time::Instant::now();
            let retrieved = storage
                .get(id)
                .await?
                .expect("Should retrieve huge content");
            let retrieval_time = start.elapsed();

            println!("Retrieval took: {:?}", retrieval_time);

            assert_eq!(retrieved.content.len(), huge_content.len());
            // Don't compare entire content for performance reasons, just sample
            assert_eq!(&retrieved.content[..1000], &huge_content[..1000]);
            assert_eq!(
                &retrieved.content[retrieved.content.len() - 1000..],
                &huge_content[huge_content.len() - 1000..]
            );
        }
        Err(e) => {
            println!(
                "10MB content failed (may be expected due to database limits): {}",
                e
            );
            // This might fail due to:
            // - PostgreSQL max_allowed_packet limits
            // - Memory constraints
            // - Connection timeouts
            // This is useful information about system limits
        }
    }

    manager.cleanup().await?;
    Ok(())
}

#[tokio::test]
#[serial]
async fn test_binary_data_handling() -> Result<()> {
    let mut manager = TestDatabaseManager::new()?;
    let pool = manager.setup_test_database().await?;
    let storage = Arc::new(Storage::new(pool));

    // Create binary-like data (should still be UTF-8 for TEXT field)
    let binary_patterns = [
        // Base64-encoded binary data
        "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==",
        // Hex-encoded data
        "89504e470d0a1a0a0000000d494844520000000100000001080200000090773645000000",
        // Mixed binary-like content
        "\x00\x01\x02\x03invalid", // This will likely fail as it's not valid UTF-8
        // JSON with binary data
        r#"{"data": "binary_data_here", "encoding": "base64"}"#,
    ];

    for (i, content) in binary_patterns.iter().enumerate() {
        let result = storage
            .store(
                content,
                format!("Binary test #{}", i),
                "Test summary".to_string(),
                None,
            )
            .await;

        match result {
            Ok(id) => {
                let retrieved = storage
                    .get(id)
                    .await?
                    .expect("Should retrieve binary content");
                assert_eq!(
                    retrieved.content, *content,
                    "Binary content should be preserved"
                );
                println!("Binary pattern #{} stored successfully", i);
            }
            Err(e) => {
                println!(
                    "Binary pattern #{} failed (may be expected for invalid UTF-8): {}",
                    i, e
                );
            }
        }
    }

    manager.cleanup().await?;
    Ok(())
}

#[tokio::test]
#[serial]
async fn test_content_with_sql_like_patterns() -> Result<()> {
    let mut manager = TestDatabaseManager::new()?;
    let pool = manager.setup_test_database().await?;
    let storage = Arc::new(Storage::new(pool));

    // Content that might cause issues if not properly escaped
    let sql_patterns = [
        "'; DROP TABLE memories; --",
        "SELECT * FROM memories WHERE id = '1'",
        "INSERT INTO memories VALUES ('evil', 'content')",
        "' OR '1'='1",
        "'; DELETE FROM memories; --",
        "UNION SELECT password FROM users",
        r#"{"key": "'; DROP TABLE memories; --"}"#,
        "Content with single ' quotes",
        r#"Content with "double quotes""#,
        "Content with `backticks`",
        "Content with $1 parameter-like $$ strings",
    ];

    for (i, content) in sql_patterns.iter().enumerate() {
        let id = storage
            .store(
                content,
                format!("SQL injection test #{}", i),
                "Testing content that might cause SQL issues".to_string(),
                Some(vec!["sql".to_string(), "security".to_string()]),
            )
            .await?;

        let retrieved = storage
            .get(id)
            .await?
            .expect("Should retrieve SQL-like content");
        assert_eq!(
            retrieved.content, *content,
            "SQL-like content should be stored safely"
        );
    }

    // Verify that our table still exists and wasn't dropped
    let stats = storage.stats().await?;
    assert_eq!(stats.total_memories, sql_patterns.len() as i64);

    manager.cleanup().await?;
    Ok(())
}

#[tokio::test]
#[serial]
async fn test_extremely_long_single_line() -> Result<()> {
    let mut manager = TestDatabaseManager::new()?;
    let pool = manager.setup_test_database().await?;
    let storage = Arc::new(Storage::new(pool));

    // Create a very long single line (no newlines)
    let word = "supercalifragilisticexpialidocious";
    let long_line = word.repeat(10000); // ~340KB single line

    println!("Testing single line of {} characters", long_line.len());

    let result = storage
        .store(
            &long_line,
            "Extremely long single line test".to_string(),
            "Testing single line content limits".to_string(),
            Some(vec!["long".to_string(), "line".to_string()]),
        )
        .await;

    match result {
        Ok(id) => {
            let retrieved = storage.get(id).await?.expect("Should retrieve long line");
            assert_eq!(retrieved.content.len(), long_line.len());
            assert_eq!(retrieved.content, long_line);
            println!("Long single line stored and retrieved successfully");
        }
        Err(e) => {
            println!("Long single line failed: {}", e);
        }
    }

    manager.cleanup().await?;
    Ok(())
}

#[tokio::test]
#[serial]
async fn test_content_hash_collision_simulation() -> Result<()> {
    let mut manager = TestDatabaseManager::new()?;
    let pool = manager.setup_test_database().await?;
    let storage = Arc::new(Storage::new(pool));

    // Store identical content to test deduplication
    let content = "This content will be stored multiple times to test hash collision handling";

    let id1 = storage
        .store(
            content,
            "First instance".to_string(),
            "First summary".to_string(),
            None,
        )
        .await?;

    let id2 = storage
        .store(
            content,
            "Second instance".to_string(),
            "Second summary".to_string(),
            None,
        )
        .await?;

    // Should return the same ID (deduplication)
    assert_eq!(id1, id2, "Identical content should deduplicate to same ID");

    // Verify the context and summary were updated
    let retrieved = storage
        .get(id1)
        .await?
        .expect("Should retrieve deduplicated content");
    assert_eq!(retrieved.content, content);
    assert_eq!(retrieved.context, "Second instance".to_string());
    assert_eq!(retrieved.summary, "Second summary".to_string());

    manager.cleanup().await?;
    Ok(())
}