sqlite-graphrag 1.0.66

Local GraphRAG memory for LLMs in a single SQLite file
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
//! Handler for the `link` CLI subcommand.

use crate::constants::DEFAULT_RELATION_WEIGHT;
use crate::entity_type::EntityType;
use crate::errors::AppError;
use crate::i18n::{errors_msg, validation};
use crate::output::{self, OutputFormat};
use crate::paths::AppPaths;
use crate::storage::connection::open_rw;
use crate::storage::entities;
use crate::storage::entities::NewEntity;
use rusqlite::params;
use serde::Serialize;

#[derive(clap::Args)]
#[command(after_long_help = "EXAMPLES:\n  \
    # Link two existing graph entities (extracted by GLiNER NER during `remember`)\n  \
    sqlite-graphrag link --from oauth-flow --to refresh-tokens --relation related\n\n  \
    # Auto-create entities that don't exist yet\n  \
    sqlite-graphrag link --from concept-a --to concept-b --relation depends-on --create-missing\n\n  \
    # Specify entity type for auto-created entities\n  \
    sqlite-graphrag link --from alice --to acme-corp --relation related --create-missing --entity-type person\n\n  \
    # Use a custom (non-canonical) relation type\n  \
    sqlite-graphrag link --from module-a --to module-b --relation implements --create-missing\n\n  \
    # If the entity does not exist and --create-missing is not set, the command fails with exit 4.\n  \
    # To list current entity names:\n  \
    sqlite-graphrag graph entities | jaq '.entities[].name'\n\n  \
NOTE:\n  \
    --from and --to expect ENTITY names (graph nodes), not memory names.\n  \
    Memory names are managed via remember/read/edit/forget; entities are auto-extracted\n  \
    by GLiNER NER from memory bodies or auto-created via --create-missing.")]
pub struct LinkArgs {
    /// Source ENTITY name (graph node, not memory). Entities are extracted by GLiNER NER during
    /// `remember` or auto-created via `--create-missing`. Use `graph entities` to list
    /// available entity names. Also accepts the alias `--name`.
    #[arg(long, alias = "name")]
    pub from: String,
    /// Target ENTITY name (graph node, not memory). See `--from` for sourcing entity names.
    #[arg(long)]
    pub to: String,
    /// Relation type between entities. Canonical values: applies-to, uses,
    /// depends-on, causes, fixes, contradicts, supports, follows, related,
    /// mentions, replaces, tracked-in. Any kebab-case or snake_case string
    /// is also accepted as a custom relation.
    #[arg(long, value_parser = crate::parsers::parse_relation, value_name = "RELATION")]
    pub relation: String,
    #[arg(long)]
    pub weight: Option<f64>,
    #[arg(long)]
    pub namespace: Option<String>,
    #[arg(long, value_enum, default_value = "json")]
    pub format: OutputFormat,
    #[arg(long, hide = true, help = "No-op; JSON is always emitted on stdout")]
    pub json: bool,
    #[arg(long, env = "SQLITE_GRAPHRAG_DB_PATH")]
    pub db: Option<String>,
    /// Auto-create entities when they do not exist. Created entities default to
    /// type `concept` unless `--entity-type` specifies a different type.
    #[arg(long, default_value_t = false)]
    pub create_missing: bool,
    /// Entity type assigned to auto-created entities (only effective with `--create-missing`).
    #[arg(long, value_enum, default_value = "concept")]
    pub entity_type: EntityType,
    /// Reject non-canonical relation types with exit 1.
    ///
    /// When set, any relation not in the canonical list causes an immediate error.
    /// Canonical values: applies-to, uses, depends-on, causes, fixes, contradicts,
    /// supports, follows, related, mentions, replaces, tracked-in.
    #[arg(
        long,
        default_value_t = false,
        help = "Reject non-canonical relation types with exit 1"
    )]
    pub strict_relations: bool,
    /// Emit a warning (but do not reject) when creating an edge would push either endpoint
    /// entity above this degree. Default 50. Set 0 to disable the check.
    #[arg(long, default_value_t = 50, value_name = "N")]
    pub max_entity_degree: u32,
}

#[derive(Serialize)]
struct LinkResponse {
    action: String,
    from: String,
    to: String,
    relation: String,
    weight: f64,
    namespace: String,
    /// Total execution time in milliseconds from handler start to serialisation.
    elapsed_ms: u64,
    /// Entity names that were auto-created by `--create-missing`.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    created_entities: Vec<String>,
    /// Non-fatal warnings (e.g. non-canonical relation type).
    #[serde(skip_serializing_if = "Vec::is_empty")]
    warnings: Vec<String>,
}

pub fn run(args: LinkArgs) -> Result<(), AppError> {
    let inicio = std::time::Instant::now();
    let namespace = crate::namespace::resolve_namespace(args.namespace.as_deref())?;
    let paths = AppPaths::resolve(args.db.as_deref())?;

    let norm_from = crate::parsers::normalize_entity_name(&args.from);
    let norm_to = crate::parsers::normalize_entity_name(&args.to);

    if norm_from == norm_to {
        return Err(AppError::Validation(validation::self_referential_link()));
    }

    let weight = args.weight.unwrap_or(DEFAULT_RELATION_WEIGHT);
    if !(0.0..=1.0).contains(&weight) {
        return Err(AppError::Validation(validation::invalid_link_weight(
            weight,
        )));
    }
    if weight >= 0.95 {
        tracing::warn!(
            weight = weight,
            "weight >= 0.95 compresses the scoring range; consider using a value below 0.95"
        );
    }
    if weight <= 0.05 {
        tracing::warn!(
            weight = weight,
            "weight <= 0.05 may be too weak to influence traversal; consider using a value above 0.05"
        );
    }

    crate::storage::connection::ensure_db_ready(&paths)?;

    let mut warnings: Vec<String> = Vec::new();
    let is_canonical = crate::parsers::is_canonical_relation(&args.relation);
    if !is_canonical {
        if args.strict_relations {
            return Err(AppError::Validation(format!(
                "non-canonical relation '{}': use --strict-relations=false or choose from: {}",
                args.relation,
                crate::parsers::CANONICAL_RELATIONS.join(", ")
            )));
        }
        warnings.push(format!("non-canonical relation '{}'", args.relation));
        tracing::warn!(
            relation = %args.relation,
            "non-canonical relation accepted; consider using a well-known value"
        );
    }
    let relation_str = &args.relation;

    let mut conn = open_rw(&paths.db)?;
    let tx = conn.transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)?;

    let mut created_entities: Vec<String> = Vec::with_capacity(2);

    if args.entity_type.as_str() == "memory" {
        tracing::warn!(
            entity_type = "memory",
            "entity_type 'memory' may conflict with memory table semantics; consider using 'concept' or another type"
        );
    }

    let source_id = match entities::find_entity_id(&tx, &namespace, &norm_from)? {
        Some(id) => id,
        None if args.create_missing => {
            let new_entity = NewEntity {
                name: norm_from.clone(),
                entity_type: args.entity_type,
                description: None,
            };
            created_entities.push(norm_from.clone());
            entities::upsert_entity(&tx, &namespace, &new_entity)?
        }
        None => {
            return Err(AppError::NotFound(errors_msg::entity_not_found(
                &norm_from, &namespace,
            )));
        }
    };

    let target_id = match entities::find_entity_id(&tx, &namespace, &norm_to)? {
        Some(id) => id,
        None if args.create_missing => {
            let new_entity = NewEntity {
                name: norm_to.clone(),
                entity_type: args.entity_type,
                description: None,
            };
            created_entities.push(norm_to.clone());
            entities::upsert_entity(&tx, &namespace, &new_entity)?
        }
        None => {
            return Err(AppError::NotFound(errors_msg::entity_not_found(
                &norm_to, &namespace,
            )));
        }
    };

    let (rel_id, was_created) = entities::create_or_fetch_relationship(
        &tx,
        &namespace,
        source_id,
        target_id,
        relation_str,
        weight,
        None,
    )?;

    let actual_weight: f64 = tx.query_row(
        "SELECT weight FROM relationships WHERE id = ?1",
        params![rel_id],
        |r| r.get(0),
    )?;

    if was_created {
        entities::recalculate_degree(&tx, source_id)?;
        entities::recalculate_degree(&tx, target_id)?;

        if args.max_entity_degree > 0 {
            let cap = args.max_entity_degree as i64;
            for (entity_id, entity_name) in [(source_id, &norm_from), (target_id, &norm_to)] {
                let degree: i64 = tx.query_row(
                    "SELECT degree FROM entities WHERE id = ?1",
                    params![entity_id],
                    |r| r.get(0),
                )?;
                if degree > cap {
                    output::emit_progress(&format!(
                        "WARNING: entity '{entity_name}' degree {degree} exceeds cap {cap}"
                    ));
                }
            }
        }
    }
    tx.commit()?;

    conn.execute_batch("PRAGMA wal_checkpoint(TRUNCATE);")?;

    let action = if was_created {
        "created".to_string()
    } else {
        "already_exists".to_string()
    };

    let response = LinkResponse {
        action: action.clone(),
        from: norm_from.clone(),
        to: norm_to.clone(),
        relation: relation_str.to_string(),
        weight: actual_weight,
        namespace: namespace.clone(),
        elapsed_ms: inicio.elapsed().as_millis() as u64,
        created_entities,
        warnings,
    };

    match args.format {
        OutputFormat::Json => output::emit_json(&response)?,
        OutputFormat::Text | OutputFormat::Markdown => {
            output::emit_text(&format!(
                "{}: {} --[{}]--> {} [{}]",
                action, response.from, response.relation, response.to, response.namespace
            ));
        }
    }

    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn link_response_without_redundant_aliases() {
        // P1-O: source/target fields were removed from the JSON response.
        let resp = LinkResponse {
            action: "created".to_string(),
            from: "entity-a".to_string(),
            to: "entity-b".to_string(),
            relation: "uses".to_string(),
            weight: 1.0,
            namespace: "default".to_string(),
            elapsed_ms: 0,
            created_entities: vec![],
            warnings: vec![],
        };
        let json = serde_json::to_value(&resp).expect("serialization must work");
        assert_eq!(json["from"], "entity-a");
        assert_eq!(json["to"], "entity-b");
        assert!(
            json.get("source").is_none(),
            "field 'source' was removed in P1-O"
        );
        assert!(
            json.get("target").is_none(),
            "field 'target' was removed in P1-O"
        );
    }

    #[test]
    fn link_response_serializes_all_fields() {
        let resp = LinkResponse {
            action: "already_exists".to_string(),
            from: "origin".to_string(),
            to: "destination".to_string(),
            relation: "mentions".to_string(),
            weight: 0.8,
            namespace: "test".to_string(),
            elapsed_ms: 5,
            created_entities: vec![],
            warnings: vec![],
        };
        let json = serde_json::to_value(&resp).expect("serialization must work");
        assert!(json.get("action").is_some());
        assert!(json.get("from").is_some());
        assert!(json.get("to").is_some());
        assert!(json.get("relation").is_some());
        assert!(json.get("weight").is_some());
        assert!(json.get("namespace").is_some());
        assert!(json.get("elapsed_ms").is_some());
    }

    #[test]
    fn link_response_omits_created_entities_when_empty() {
        let resp = LinkResponse {
            action: "created".to_string(),
            from: "a".to_string(),
            to: "b".to_string(),
            relation: "uses".to_string(),
            weight: 1.0,
            namespace: "global".to_string(),
            elapsed_ms: 0,
            created_entities: vec![],
            warnings: vec![],
        };
        let json = serde_json::to_value(&resp).expect("serialization");
        assert!(
            json.get("created_entities").is_none(),
            "empty vec must be omitted"
        );
    }

    #[test]
    fn link_response_includes_created_entities_when_present() {
        let resp = LinkResponse {
            action: "created".to_string(),
            from: "new-a".to_string(),
            to: "new-b".to_string(),
            relation: "depends-on".to_string(),
            weight: 0.5,
            namespace: "test".to_string(),
            elapsed_ms: 1,
            created_entities: vec!["new-a".to_string(), "new-b".to_string()],
            warnings: vec![],
        };
        let json = serde_json::to_value(&resp).expect("serialization");
        let created = json["created_entities"].as_array().expect("must be array");
        assert_eq!(created.len(), 2);
        assert_eq!(created[0], "new-a");
        assert_eq!(created[1], "new-b");
    }

    #[test]
    fn link_response_includes_warnings_when_non_canonical() {
        let resp = LinkResponse {
            action: "created".to_string(),
            from: "a".to_string(),
            to: "b".to_string(),
            relation: "implements".to_string(),
            weight: 0.5,
            namespace: "global".to_string(),
            elapsed_ms: 0,
            created_entities: vec![],
            warnings: vec!["non-canonical relation 'implements'".to_string()],
        };
        let json = serde_json::to_value(&resp).expect("serialization");
        let w = json["warnings"]
            .as_array()
            .expect("warnings must be present");
        assert_eq!(w.len(), 1);
        assert!(w[0].as_str().unwrap().contains("implements"));
    }

    #[test]
    fn link_response_omits_warnings_when_empty() {
        let resp = LinkResponse {
            action: "created".to_string(),
            from: "a".to_string(),
            to: "b".to_string(),
            relation: "uses".to_string(),
            weight: 0.5,
            namespace: "global".to_string(),
            elapsed_ms: 0,
            created_entities: vec![],
            warnings: vec![],
        };
        let json = serde_json::to_value(&resp).expect("serialization");
        assert!(
            json.get("warnings").is_none(),
            "empty warnings must be omitted"
        );
    }
}