cognee-lib 0.1.3

Cognee — an AI-memory pipeline that turns raw data into queryable knowledge graphs (umbrella crate).
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
#![allow(
    clippy::unwrap_used,
    clippy::expect_used,
    reason = "test code — panics are acceptable failures"
)]
//! Integration tests for `recall()` scope widening (LIB-07).
//!
//! Validates Python parity (`cognee/api/v1/recall/recall.py:317-531`,
//! `cognee/memory/entries.py:81-115`) for:
//!   * `auto` resolution per `(session_id, datasets, query_type)`,
//!   * scope-driven source fan-out across `graph` / `session` / `trace` /
//!     `graph_context`,
//!   * graceful degradation when `session_id` is `None`,
//!   * Rust-only ergonomics: empty `Vec<RecallScope>` collapses to `[Auto]`.

use std::sync::Arc;

use async_trait::async_trait;
use cognee_lib::api::recall::{RecallScope, RecallSource, ScopeInput, normalize_scope, recall};
use cognee_search::orchestration::SearchTypeRegistry;
use cognee_search::retrievers::SearchRetriever;
use cognee_search::types::{SearchContext, SearchError, SearchOutput, SearchParams};
use cognee_search::{SearchOrchestrator, SearchType};
use cognee_session::{FsSessionStore, SessionContext, SessionManager, SessionStore};
use tempfile::TempDir;

const USER_ID: &str = "user-1";
const SESSION_ID: &str = "sess-1";

/// Minimal retriever that returns a fixed text completion for any registered
/// search type. Used to keep the graph-source path runnable without real
/// backends.
struct StubRetriever(SearchType);

#[async_trait]
impl SearchRetriever for StubRetriever {
    fn search_type(&self) -> SearchType {
        self.0
    }

    async fn get_context(
        &self,
        _query: &str,
        _params: &SearchParams,
    ) -> Result<SearchContext, SearchError> {
        Ok(vec![])
    }

    async fn get_completion(
        &self,
        _query: &str,
        _context: Option<SearchContext>,
        _session: &SessionContext,
        _params: &SearchParams,
    ) -> Result<SearchOutput, SearchError> {
        Ok(SearchOutput::Text("graph-stub".to_string()))
    }
}

fn build_orchestrator() -> SearchOrchestrator {
    let mut registry = SearchTypeRegistry::new();
    // Register every search type that recall() may route to so that any
    // auto-routed test still finds a retriever.
    for st in [
        SearchType::GraphCompletion,
        SearchType::GraphSummaryCompletion,
        SearchType::Temporal,
        SearchType::RagCompletion,
        SearchType::Chunks,
        SearchType::Summaries,
    ] {
        registry.register(Arc::new(StubRetriever(st)));
    }
    SearchOrchestrator::new(registry)
}

struct Harness {
    _sess_dir: TempDir,
    orchestrator: SearchOrchestrator,
    store: Arc<dyn SessionStore>,
    manager: SessionManager,
}

async fn build_harness() -> Harness {
    let sess_dir = TempDir::new().expect("tempdir");
    let store: Arc<dyn SessionStore> = Arc::new(FsSessionStore::new(sess_dir.path()));
    let manager = SessionManager::new(Arc::clone(&store));
    Harness {
        _sess_dir: sess_dir,
        orchestrator: build_orchestrator(),
        store,
        manager,
    }
}

async fn seed_qa(store: &dyn SessionStore, q: &str, a: &str) {
    store
        .create_qa_entry(SESSION_ID, Some(USER_ID), q, a, None)
        .await
        .expect("create qa");
}

async fn seed_trace(manager: &SessionManager, origin: &str, query: &str, ctx: &str) {
    manager
        .add_agent_trace_step(
            USER_ID,
            Some(SESSION_ID),
            origin,
            "success",
            query,
            ctx,
            serde_json::json!({}),
            None,
            "",
            false,
        )
        .await
        .expect("add trace step");
}

// ---------------------------------------------------------------------------
// auto resolution
// ---------------------------------------------------------------------------

#[tokio::test]
async fn test_scope_auto_with_session_id_uses_session_path() {
    let h = build_harness().await;
    seed_qa(&*h.store, "what is rust", "a systems language").await;

    let result = recall(
        "rust language",
        None,
        None,
        10,
        false,
        Some(SESSION_ID),
        Some(USER_ID),
        &h.orchestrator,
        Some(&*h.store),
        Some(&h.manager),
        None, // scope = None => "auto"
        None, // options
    )
    .await
    .expect("recall ok");

    assert!(
        result
            .items
            .iter()
            .any(|i| i.source == RecallSource::Session),
        "expected at least one session item; got {:?}",
        result.items.iter().map(|i| i.source).collect::<Vec<_>>()
    );
    // auto_fallthrough short-circuits the graph runner once session has hits.
    assert!(
        result.items.iter().all(|i| i.source != RecallSource::Graph),
        "graph runner should be short-circuited when session matched"
    );
}

#[tokio::test]
async fn test_scope_auto_without_session_id_uses_graph_path() {
    let h = build_harness().await;

    let result = recall(
        "anything",
        None,
        None,
        10,
        false,
        None, // no session_id
        Some(USER_ID),
        &h.orchestrator,
        Some(&*h.store),
        Some(&h.manager),
        None, // scope = None => "auto" => [Graph]
        None, // options
    )
    .await
    .expect("recall ok");

    assert!(!result.items.is_empty(), "graph stub should yield a result");
    assert!(
        result.items.iter().all(|i| i.source == RecallSource::Graph),
        "all items should be graph-tagged when session_id is None"
    );
}

// ---------------------------------------------------------------------------
// explicit scope per source
// ---------------------------------------------------------------------------

#[tokio::test]
async fn test_scope_session_returns_qa_pairs() {
    let h = build_harness().await;
    seed_qa(
        &*h.store,
        "rust ownership rules",
        "borrow checker enforces them",
    )
    .await;
    seed_qa(&*h.store, "what is python", "an interpreted language").await;

    let result = recall(
        "rust ownership",
        None,
        None,
        10,
        false,
        Some(SESSION_ID),
        Some(USER_ID),
        &h.orchestrator,
        Some(&*h.store),
        Some(&h.manager),
        Some(vec![RecallScope::Session]),
        None,
    )
    .await
    .expect("recall ok");

    assert!(!result.items.is_empty(), "expected session matches");
    assert!(
        result
            .items
            .iter()
            .all(|i| i.source == RecallSource::Session)
    );
    assert!(
        result.search_response.is_none(),
        "session-only scope must not invoke graph"
    );
}

#[tokio::test]
async fn test_scope_trace_returns_trace_entries() {
    let h = build_harness().await;
    seed_trace(
        &h.manager,
        "search.recall",
        "find rust facts",
        "ownership and borrowing",
    )
    .await;
    seed_trace(
        &h.manager,
        "ingest.add",
        "store a doc",
        "doc about python coroutines",
    )
    .await;

    let result = recall(
        "rust ownership",
        None,
        None,
        10,
        false,
        Some(SESSION_ID),
        Some(USER_ID),
        &h.orchestrator,
        Some(&*h.store),
        Some(&h.manager),
        Some(vec![RecallScope::Trace]),
        None,
    )
    .await
    .expect("recall ok");

    assert!(
        !result.items.is_empty(),
        "expected trace match for 'rust ownership'"
    );
    assert!(
        result.items.iter().all(|i| i.source == RecallSource::Trace),
        "trace-only scope should yield only trace items"
    );
}

#[tokio::test]
async fn test_scope_graph_context_returns_subgraph() {
    let h = build_harness().await;
    let snapshot = "graph-knowledge: rust borrow checker; entity:Rust; rel:has_feature.";
    h.manager
        .set_graph_context(Some(SESSION_ID), Some(USER_ID), snapshot)
        .await
        .expect("set graph context");

    let result = recall(
        "doesn't matter -- not query-matched",
        None,
        None,
        10,
        false,
        Some(SESSION_ID),
        Some(USER_ID),
        &h.orchestrator,
        Some(&*h.store),
        Some(&h.manager),
        Some(vec![RecallScope::GraphContext]),
        None,
    )
    .await
    .expect("recall ok");

    assert_eq!(result.items.len(), 1);
    assert_eq!(result.items[0].source, RecallSource::GraphContext);
    assert_eq!(
        result.items[0].content,
        serde_json::Value::String(snapshot.to_string())
    );
}

#[tokio::test]
async fn test_scope_all_merges_four_sources() {
    let h = build_harness().await;
    seed_qa(&*h.store, "session q rust", "session a rust").await;
    seed_trace(
        &h.manager,
        "trace.fn",
        "trace q about rust",
        "trace ctx rust",
    )
    .await;
    h.manager
        .set_graph_context(Some(SESSION_ID), Some(USER_ID), "graph-context rust note")
        .await
        .expect("set graph context");

    let result = recall(
        "rust",
        None,
        None,
        10,
        false,
        Some(SESSION_ID),
        Some(USER_ID),
        &h.orchestrator,
        Some(&*h.store),
        Some(&h.manager),
        Some(vec![
            RecallScope::Graph,
            RecallScope::Session,
            RecallScope::Trace,
            RecallScope::GraphContext,
        ]),
        None,
    )
    .await
    .expect("recall ok");

    let sources: std::collections::HashSet<RecallSource> =
        result.items.iter().map(|i| i.source).collect();
    assert!(sources.contains(&RecallSource::Graph));
    assert!(sources.contains(&RecallSource::Session));
    assert!(sources.contains(&RecallSource::Trace));
    assert!(sources.contains(&RecallSource::GraphContext));

    // Order: caller asked Graph first, so the first item should be Graph.
    assert_eq!(
        result.items.first().map(|i| i.source),
        Some(RecallSource::Graph)
    );
}

#[tokio::test]
async fn test_scope_session_without_session_id_returns_empty() {
    let h = build_harness().await;
    seed_qa(&*h.store, "q1", "a1").await;

    let result = recall(
        "q1",
        None,
        None,
        10,
        false,
        None, // no session_id
        Some(USER_ID),
        &h.orchestrator,
        Some(&*h.store),
        Some(&h.manager),
        Some(vec![RecallScope::Session]),
        None,
    )
    .await
    .expect("recall ok");

    assert!(
        result.items.is_empty(),
        "session runner must short-circuit empty when session_id is None"
    );
}

#[tokio::test]
async fn test_scope_unknown_value_returns_error() {
    let err = normalize_scope(Some(ScopeInput::from("bogus_scope"))).expect_err("should error");
    let msg = err.to_string();
    assert!(
        msg.contains("Unknown recall scope(s)"),
        "expected Python-parity error message; got: {msg}"
    );
    assert!(
        msg.contains("bogus_scope"),
        "expected unknown value to appear in error; got: {msg}"
    );
    assert!(
        msg.contains(r#"["all", "auto", "graph", "graph_context", "session", "trace"]"#),
        "expected canonical sorted valid-values list; got: {msg}"
    );
}