Skip to main content

sqlite_graphrag/commands/
ingest.rs

1//! Handler for the `ingest` CLI subcommand.
2//!
3//! Bulk-ingests every file under a directory that matches a glob pattern.
4//! Each matched file is persisted as a separate memory using the same
5//! validation, chunking, embedding and persistence pipeline as `remember`,
6//! but executed in-process so the ONNX model is loaded only once per
7//! invocation. This is the v1.0.32 Onda 4B (finding A2) refactor that
8//! replaced a fork-spawn-per-file pipeline (every file paid the ~17s ONNX
9//! cold-start cost) with an in-process loop reusing the warm embedder
10//! (daemon when available, in-process `Embedder::new` otherwise).
11//!
12//! Memory names are derived from file basenames (kebab-case, lowercase,
13//! ASCII alphanumerics + hyphens). Output is line-delimited JSON: one
14//! object per processed file (success or error), followed by a final
15//! summary object. Designed for streaming consumption by agents.
16//!
17//! ## Incremental pipeline (v1.0.43)
18//!
19//! Phase A runs on a rayon thread pool (size = `--ingest-parallelism`):
20//! read + chunk + embed + NER per file. Results are sent immediately via a
21//! bounded `mpsc::sync_channel` to Phase B so persistence starts as soon
22//! as the first file completes — no waiting for all files to finish Phase A.
23//!
24//! Phase B runs on the main thread: receives staged files from the channel,
25//! writes to SQLite per-file (WAL absorbs individual commits), and emits
26//! NDJSON progress events to stderr as each file is persisted. `Connection`
27//! is not `Sync` so it never crosses thread boundaries.
28//!
29//! This fixes B1: with the old 2-phase design, a 50-file corpus with 27s/file
30//! NER would spend ~22min in Phase A alone, exceeding the user's 900s timeout
31//! before Phase B (and any DB writes) could begin. With this pipeline, the
32//! first file is committed within seconds of starting.
33
34use crate::chunking;
35use crate::cli::MemoryType;
36use crate::entity_type::EntityType;
37use crate::errors::AppError;
38use crate::i18n::errors_msg;
39use crate::output::{self, JsonOutputFormat};
40use crate::paths::AppPaths;
41use crate::storage::chunks as storage_chunks;
42use crate::storage::connection::{ensure_db_ready, open_rw};
43use crate::storage::entities::{NewEntity, NewRelationship};
44use crate::storage::memories::NewMemory;
45use crate::storage::{entities, memories, urls as storage_urls, versions};
46use rayon::prelude::*;
47use rusqlite::Connection;
48use serde::Serialize;
49use std::collections::BTreeSet;
50use std::path::{Path, PathBuf};
51use std::sync::mpsc;
52use unicode_normalization::UnicodeNormalization;
53
54use crate::constants::DERIVED_NAME_MAX_LEN;
55
56/// Hard cap on the numeric suffix appended for collision resolution. If 1000
57/// candidates collide we surface an error rather than loop forever.
58const MAX_NAME_COLLISION_SUFFIX: usize = 1000;
59
60#[derive(clap::Args)]
61#[command(after_long_help = "EXAMPLES:\n  \
62    # Ingest every Markdown file under ./docs as `document` memories\n  \
63    sqlite-graphrag ingest ./docs --type document\n\n  \
64    # Ingest .txt files recursively under ./notes\n  \
65    sqlite-graphrag ingest ./notes --type note --pattern '*.txt' --recursive\n\n  \
66    # Enable GLiNER NER extraction (disabled by default, slower)\n  \
67    sqlite-graphrag ingest ./big-corpus --type reference --enable-ner\n\n  \
68NOTES:\n  \
69    Each file becomes a separate memory. Names derive from file basenames\n  \
70    (kebab-case, lowercase, ASCII). Output is NDJSON: one JSON object per file,\n  \
71    followed by a final summary line with counts. Per-file errors are reported\n  \
72    inline and processing continues unless --fail-fast is set.")]
73pub struct IngestArgs {
74    /// Directory containing files to ingest.
75    #[arg(
76        value_name = "DIR",
77        help = "Directory to ingest recursively (each matching file becomes a memory)"
78    )]
79    pub dir: PathBuf,
80
81    /// Memory type stored in `memories.type` for every ingested file. Defaults to `document`.
82    #[arg(long, value_enum, default_value_t = MemoryType::Document)]
83    pub r#type: MemoryType,
84
85    /// Glob pattern matched against file basenames (default: `*.md`). Supports
86    /// `*.<ext>`, `<prefix>*`, and exact filename match.
87    #[arg(long, default_value = "*.md")]
88    pub pattern: String,
89
90    /// Recurse into subdirectories.
91    #[arg(long, default_value_t = false)]
92    pub recursive: bool,
93
94    #[arg(
95        long,
96        env = "SQLITE_GRAPHRAG_ENABLE_NER",
97        value_parser = crate::parsers::parse_bool_flexible,
98        action = clap::ArgAction::Set,
99        num_args = 0..=1,
100        default_missing_value = "true",
101        default_value = "false",
102        help = "Enable automatic GLiNER NER entity/relationship extraction (disabled by default)"
103    )]
104    pub enable_ner: bool,
105    #[arg(
106        long,
107        env = "SQLITE_GRAPHRAG_GLINER_VARIANT",
108        default_value = "fp32",
109        help = "GLiNER model variant: fp32 (best quality, 1.1GB), fp16 (580MB), int8 (349MB, fastest)"
110    )]
111    pub gliner_variant: String,
112
113    /// Deprecated: NER is now disabled by default. Kept for backwards compatibility.
114    #[arg(long, default_value_t = false, hide = true)]
115    pub skip_extraction: bool,
116
117    /// Stop on first per-file error instead of continuing with the next file.
118    #[arg(long, default_value_t = false)]
119    pub fail_fast: bool,
120
121    /// Maximum number of files to ingest (safety cap to prevent runaway ingestion).
122    #[arg(long, default_value_t = 10_000)]
123    pub max_files: usize,
124
125    /// Namespace for the ingested memories.
126    #[arg(long)]
127    pub namespace: Option<String>,
128
129    /// Database path. Falls back to `SQLITE_GRAPHRAG_DB_PATH`, then `./graphrag.sqlite`.
130    #[arg(long, env = "SQLITE_GRAPHRAG_DB_PATH")]
131    pub db: Option<String>,
132
133    #[arg(long, value_enum, default_value_t = JsonOutputFormat::Json)]
134    pub format: JsonOutputFormat,
135
136    #[arg(long, hide = true, help = "No-op; JSON is always emitted on stdout")]
137    pub json: bool,
138
139    /// Number of files to extract+embed in parallel; default = max(1, cpus/2).min(4).
140    #[arg(
141        long,
142        help = "Number of files to extract+embed in parallel; default = max(1, cpus/2).min(4)"
143    )]
144    pub ingest_parallelism: Option<usize>,
145
146    /// Force single-threaded ingest to reduce RSS pressure.
147    ///
148    /// Equivalent to `--ingest-parallelism 1`, takes precedence over any
149    /// explicit value. Recommended for environments with <4 GB available
150    /// RAM or container/cgroup constraints. Trade-off: 3-4x longer wall
151    /// time. Also honored via `SQLITE_GRAPHRAG_LOW_MEMORY=1` env var
152    /// (CLI flag has higher precedence than the env var).
153    #[arg(
154        long,
155        default_value_t = false,
156        help = "Forces single-threaded ingest (--ingest-parallelism 1) to reduce RSS pressure. \
157                Recommended for environments with <4 GB available RAM or container/cgroup \
158                constraints. Trade-off: 3-4x longer wall time. Also honored via \
159                SQLITE_GRAPHRAG_LOW_MEMORY=1 env var."
160    )]
161    pub low_memory: bool,
162}
163
164/// Returns true when the `SQLITE_GRAPHRAG_LOW_MEMORY` env var is set to a
165/// truthy value (`1`, `true`, `yes`, `on`, case-insensitive). Empty or unset
166/// values evaluate to false. Unrecognized non-empty values emit a
167/// `tracing::warn!` and evaluate to false.
168fn env_low_memory_enabled() -> bool {
169    match std::env::var("SQLITE_GRAPHRAG_LOW_MEMORY") {
170        Ok(v) if v.is_empty() => false,
171        Ok(v) => match v.to_lowercase().as_str() {
172            "1" | "true" | "yes" | "on" => true,
173            "0" | "false" | "no" | "off" => false,
174            other => {
175                tracing::warn!(
176                    target: "ingest",
177                    value = %other,
178                    "SQLITE_GRAPHRAG_LOW_MEMORY value not recognized; treating as disabled"
179                );
180                false
181            }
182        },
183        Err(_) => false,
184    }
185}
186
187/// Resolves the effective ingest parallelism honoring `--low-memory` and the
188/// `SQLITE_GRAPHRAG_LOW_MEMORY` env var.
189///
190/// Precedence:
191/// 1. `--low-memory` CLI flag forces parallelism = 1.
192/// 2. `SQLITE_GRAPHRAG_LOW_MEMORY=1` env var forces parallelism = 1.
193/// 3. Explicit `--ingest-parallelism N` (when low-memory is off).
194/// 4. Default heuristic `(cpus/2).clamp(1, 4)`.
195///
196/// When low-memory wins and the user also passed `--ingest-parallelism N>1`,
197/// emits a `tracing::warn!` advertising the override.
198fn resolve_parallelism(low_memory_flag: bool, ingest_parallelism: Option<usize>) -> usize {
199    let env_flag = env_low_memory_enabled();
200    let low_memory = low_memory_flag || env_flag;
201
202    if low_memory {
203        if let Some(n) = ingest_parallelism {
204            if n > 1 {
205                tracing::warn!(
206                    target: "ingest",
207                    requested = n,
208                    "--ingest-parallelism overridden by --low-memory; using 1"
209                );
210            }
211        }
212        if low_memory_flag {
213            tracing::info!(
214                target: "ingest",
215                source = "flag",
216                "low-memory mode enabled: forcing --ingest-parallelism 1"
217            );
218        } else {
219            tracing::info!(
220                target: "ingest",
221                source = "env",
222                "low-memory mode enabled via SQLITE_GRAPHRAG_LOW_MEMORY: forcing --ingest-parallelism 1"
223            );
224        }
225        return 1;
226    }
227
228    ingest_parallelism
229        .unwrap_or_else(|| {
230            std::thread::available_parallelism()
231                .map(|v| v.get() / 2)
232                .unwrap_or(1)
233                .clamp(1, 4)
234        })
235        .max(1)
236}
237
238#[derive(Serialize)]
239struct IngestFileEvent<'a> {
240    file: &'a str,
241    name: &'a str,
242    status: &'a str,
243    /// True when the derived name was truncated to fit `DERIVED_NAME_MAX_LEN`. False otherwise.
244    truncated: bool,
245    /// Original derived name before truncation; only present when `truncated=true`.
246    #[serde(skip_serializing_if = "Option::is_none")]
247    original_name: Option<String>,
248    #[serde(skip_serializing_if = "Option::is_none")]
249    error: Option<String>,
250    #[serde(skip_serializing_if = "Option::is_none")]
251    memory_id: Option<i64>,
252    #[serde(skip_serializing_if = "Option::is_none")]
253    action: Option<String>,
254}
255
256#[derive(Serialize)]
257struct IngestSummary {
258    summary: bool,
259    dir: String,
260    pattern: String,
261    recursive: bool,
262    files_total: usize,
263    files_succeeded: usize,
264    files_failed: usize,
265    files_skipped: usize,
266    elapsed_ms: u64,
267}
268
269/// Outcome of a successful per-file ingest, used to build the NDJSON event.
270struct FileSuccess {
271    memory_id: i64,
272    action: String,
273}
274
275/// NDJSON progress event emitted to stderr after each file completes Phase A.
276/// Schema version 1; consumers should check `schema_version` before parsing.
277#[derive(Serialize)]
278struct StageProgressEvent<'a> {
279    schema_version: u8,
280    event: &'a str,
281    path: &'a str,
282    ms: u64,
283    entities: usize,
284    relationships: usize,
285}
286
287/// All artefacts pre-computed by Phase A (CPU-bound, runs on rayon thread pool).
288/// Phase B persists these to SQLite on the main thread in submission order.
289struct StagedFile {
290    body: String,
291    body_hash: String,
292    snippet: String,
293    name: String,
294    description: String,
295    embedding: Vec<f32>,
296    chunk_embeddings: Option<Vec<Vec<f32>>>,
297    chunks_info: Vec<crate::chunking::Chunk>,
298    entities: Vec<NewEntity>,
299    relationships: Vec<NewRelationship>,
300    entity_embeddings: Vec<Vec<f32>>,
301    urls: Vec<crate::extraction::ExtractedUrl>,
302}
303
304/// Phase A worker: reads, chunks, embeds and extracts NER for one file.
305/// Never touches the database — safe to run on any rayon thread.
306fn stage_file(
307    _idx: usize,
308    path: &Path,
309    name: &str,
310    paths: &AppPaths,
311    enable_ner: bool,
312    gliner_variant: crate::extraction::GlinerVariant,
313) -> Result<StagedFile, AppError> {
314    use crate::constants::*;
315
316    if name.len() > MAX_MEMORY_NAME_LEN {
317        return Err(AppError::LimitExceeded(
318            crate::i18n::validation::name_length(MAX_MEMORY_NAME_LEN),
319        ));
320    }
321    if name.starts_with("__") {
322        return Err(AppError::Validation(
323            crate::i18n::validation::reserved_name(),
324        ));
325    }
326    {
327        let slug_re = regex::Regex::new(NAME_SLUG_REGEX)
328            .map_err(|e| AppError::Internal(anyhow::anyhow!("regex: {e}")))?;
329        if !slug_re.is_match(name) {
330            return Err(AppError::Validation(crate::i18n::validation::name_kebab(
331                name,
332            )));
333        }
334    }
335
336    let raw_body = std::fs::read_to_string(path).map_err(AppError::Io)?;
337    if raw_body.len() > MAX_MEMORY_BODY_LEN {
338        return Err(AppError::LimitExceeded(
339            crate::i18n::validation::body_exceeds(MAX_MEMORY_BODY_LEN),
340        ));
341    }
342    if raw_body.trim().is_empty() {
343        return Err(AppError::Validation(crate::i18n::validation::empty_body()));
344    }
345
346    let description = format!("ingested from {}", path.display());
347    if description.len() > MAX_MEMORY_DESCRIPTION_LEN {
348        return Err(AppError::Validation(
349            crate::i18n::validation::description_exceeds(MAX_MEMORY_DESCRIPTION_LEN),
350        ));
351    }
352
353    let mut extracted_entities: Vec<NewEntity> = Vec::new();
354    let mut extracted_relationships: Vec<NewRelationship> = Vec::new();
355    let mut extracted_urls: Vec<crate::extraction::ExtractedUrl> = Vec::new();
356    if enable_ner {
357        match crate::extraction::extract_graph_auto(&raw_body, paths, gliner_variant) {
358            Ok(extracted) => {
359                extracted_urls = extracted.urls;
360                extracted_entities = extracted.entities;
361                extracted_relationships = extracted.relationships;
362
363                if extracted_entities.len() > max_entities_per_memory() {
364                    extracted_entities.truncate(max_entities_per_memory());
365                }
366                if extracted_relationships.len() > MAX_RELATIONSHIPS_PER_MEMORY {
367                    extracted_relationships.truncate(MAX_RELATIONSHIPS_PER_MEMORY);
368                }
369            }
370            Err(e) => {
371                tracing::warn!(
372                    file = %path.display(),
373                    "auto-extraction failed (graceful degradation): {e:#}"
374                );
375            }
376        }
377    }
378
379    for rel in &mut extracted_relationships {
380        rel.relation = rel.relation.replace('-', "_");
381        if !is_valid_relation(&rel.relation) {
382            return Err(AppError::Validation(format!(
383                "invalid relation '{}' for relationship '{}' -> '{}'",
384                rel.relation, rel.source, rel.target
385            )));
386        }
387        if !(0.0..=1.0).contains(&rel.strength) {
388            return Err(AppError::Validation(format!(
389                "invalid strength {} for relationship '{}' -> '{}'; expected value in [0.0, 1.0]",
390                rel.strength, rel.source, rel.target
391            )));
392        }
393    }
394
395    let body_hash = blake3::hash(raw_body.as_bytes()).to_hex().to_string();
396    let snippet: String = raw_body.chars().take(200).collect();
397
398    let tokenizer = crate::tokenizer::get_tokenizer(&paths.models)?;
399    let chunks_info = chunking::split_into_chunks_hierarchical(&raw_body, tokenizer);
400    if chunks_info.len() > REMEMBER_MAX_SAFE_MULTI_CHUNKS {
401        return Err(AppError::LimitExceeded(format!(
402            "document produces {} chunks; current safe operational limit is {} chunks; split the document before using remember",
403            chunks_info.len(),
404            REMEMBER_MAX_SAFE_MULTI_CHUNKS
405        )));
406    }
407
408    let mut chunk_embeddings_opt: Option<Vec<Vec<f32>>> = None;
409    let embedding = if chunks_info.len() == 1 {
410        crate::daemon::embed_passage_or_local(&paths.models, &raw_body)?
411    } else {
412        let chunk_texts: Vec<&str> = chunks_info
413            .iter()
414            .map(|c| chunking::chunk_text(&raw_body, c))
415            .collect();
416        let mut chunk_embeddings = Vec::with_capacity(chunk_texts.len());
417        for chunk_text in &chunk_texts {
418            chunk_embeddings.push(crate::daemon::embed_passage_or_local(
419                &paths.models,
420                chunk_text,
421            )?);
422        }
423        let aggregated = chunking::aggregate_embeddings(&chunk_embeddings);
424        chunk_embeddings_opt = Some(chunk_embeddings);
425        aggregated
426    };
427
428    let entity_embeddings = extracted_entities
429        .iter()
430        .map(|entity| {
431            let entity_text = match &entity.description {
432                Some(desc) => format!("{} {}", entity.name, desc),
433                None => entity.name.clone(),
434            };
435            crate::daemon::embed_passage_or_local(&paths.models, &entity_text)
436        })
437        .collect::<Result<Vec<_>, _>>()?;
438
439    Ok(StagedFile {
440        body: raw_body,
441        body_hash,
442        snippet,
443        name: name.to_string(),
444        description,
445        embedding,
446        chunk_embeddings: chunk_embeddings_opt,
447        chunks_info,
448        entities: extracted_entities,
449        relationships: extracted_relationships,
450        entity_embeddings,
451        urls: extracted_urls,
452    })
453}
454
455/// Phase B: persists one `StagedFile` to the database on the main thread.
456fn persist_staged(
457    conn: &mut Connection,
458    namespace: &str,
459    memory_type: &str,
460    staged: StagedFile,
461) -> Result<FileSuccess, AppError> {
462    {
463        let active_count: u32 = conn.query_row(
464            "SELECT COUNT(DISTINCT namespace) FROM memories WHERE deleted_at IS NULL",
465            [],
466            |r| r.get::<_, i64>(0).map(|v| v as u32),
467        )?;
468        let ns_exists: bool = conn.query_row(
469            "SELECT EXISTS(SELECT 1 FROM memories WHERE namespace = ?1 AND deleted_at IS NULL)",
470            rusqlite::params![namespace],
471            |r| r.get::<_, i64>(0).map(|v| v > 0),
472        )?;
473        if !ns_exists && active_count >= crate::constants::MAX_NAMESPACES_ACTIVE {
474            return Err(AppError::NamespaceError(format!(
475                "active namespace limit of {} exceeded while creating '{namespace}'",
476                crate::constants::MAX_NAMESPACES_ACTIVE
477            )));
478        }
479    }
480
481    let existing_memory = memories::find_by_name(conn, namespace, &staged.name)?;
482    if existing_memory.is_some() {
483        return Err(AppError::Duplicate(errors_msg::duplicate_memory(
484            &staged.name,
485            namespace,
486        )));
487    }
488    let duplicate_hash_id = memories::find_by_hash(conn, namespace, &staged.body_hash)?;
489
490    let new_memory = NewMemory {
491        namespace: namespace.to_string(),
492        name: staged.name.clone(),
493        memory_type: memory_type.to_string(),
494        description: staged.description.clone(),
495        body: staged.body,
496        body_hash: staged.body_hash,
497        session_id: None,
498        source: "agent".to_string(),
499        metadata: serde_json::json!({}),
500    };
501
502    if let Some(hash_id) = duplicate_hash_id {
503        tracing::debug!(
504            target: "ingest",
505            duplicate_memory_id = hash_id,
506            "identical body already exists; persisting a new memory anyway"
507        );
508    }
509
510    let tx = conn.transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)?;
511
512    let memory_id = memories::insert(&tx, &new_memory)?;
513    versions::insert_version(
514        &tx,
515        memory_id,
516        1,
517        &staged.name,
518        memory_type,
519        &staged.description,
520        &new_memory.body,
521        &serde_json::to_string(&new_memory.metadata)?,
522        None,
523        "create",
524    )?;
525    memories::upsert_vec(
526        &tx,
527        memory_id,
528        namespace,
529        memory_type,
530        &staged.embedding,
531        &staged.name,
532        &staged.snippet,
533    )?;
534
535    if staged.chunks_info.len() > 1 {
536        storage_chunks::insert_chunk_slices(&tx, memory_id, &new_memory.body, &staged.chunks_info)?;
537        let chunk_embeddings = staged.chunk_embeddings.ok_or_else(|| {
538            AppError::Internal(anyhow::anyhow!(
539                "missing chunk embeddings cache on multi-chunk ingest path"
540            ))
541        })?;
542        for (i, emb) in chunk_embeddings.iter().enumerate() {
543            storage_chunks::upsert_chunk_vec(&tx, i as i64, memory_id, i as i32, emb)?;
544        }
545    }
546
547    if !staged.entities.is_empty() || !staged.relationships.is_empty() {
548        for (idx, entity) in staged.entities.iter().enumerate() {
549            let entity_id = entities::upsert_entity(&tx, namespace, entity)?;
550            let entity_embedding = &staged.entity_embeddings[idx];
551            entities::upsert_entity_vec(
552                &tx,
553                entity_id,
554                namespace,
555                entity.entity_type,
556                entity_embedding,
557                &entity.name,
558            )?;
559            entities::link_memory_entity(&tx, memory_id, entity_id)?;
560            entities::increment_degree(&tx, entity_id)?;
561        }
562        let entity_types: std::collections::HashMap<&str, EntityType> = staged
563            .entities
564            .iter()
565            .map(|entity| (entity.name.as_str(), entity.entity_type))
566            .collect();
567        for rel in &staged.relationships {
568            let source_entity = NewEntity {
569                name: rel.source.clone(),
570                entity_type: entity_types
571                    .get(rel.source.as_str())
572                    .copied()
573                    .unwrap_or(EntityType::Concept),
574                description: None,
575            };
576            let target_entity = NewEntity {
577                name: rel.target.clone(),
578                entity_type: entity_types
579                    .get(rel.target.as_str())
580                    .copied()
581                    .unwrap_or(EntityType::Concept),
582                description: None,
583            };
584            let source_id = entities::upsert_entity(&tx, namespace, &source_entity)?;
585            let target_id = entities::upsert_entity(&tx, namespace, &target_entity)?;
586            let rel_id = entities::upsert_relationship(&tx, namespace, source_id, target_id, rel)?;
587            entities::link_memory_relationship(&tx, memory_id, rel_id)?;
588        }
589    }
590
591    tx.commit()?;
592
593    if !staged.urls.is_empty() {
594        let url_entries: Vec<storage_urls::MemoryUrl> = staged
595            .urls
596            .into_iter()
597            .map(|u| storage_urls::MemoryUrl {
598                url: u.url,
599                offset: Some(u.offset as i64),
600            })
601            .collect();
602        let _ = storage_urls::insert_urls(conn, memory_id, &url_entries);
603    }
604
605    Ok(FileSuccess {
606        memory_id,
607        action: "created".to_string(),
608    })
609}
610
611pub fn run(args: IngestArgs) -> Result<(), AppError> {
612    let started = std::time::Instant::now();
613
614    if !args.dir.exists() {
615        return Err(AppError::NotFound(format!(
616            "directory not found: {}",
617            args.dir.display()
618        )));
619    }
620    if !args.dir.is_dir() {
621        return Err(AppError::Validation(format!(
622            "path is not a directory: {}",
623            args.dir.display()
624        )));
625    }
626
627    let mut files: Vec<PathBuf> = Vec::new();
628    collect_files(&args.dir, &args.pattern, args.recursive, &mut files)?;
629    files.sort();
630
631    if files.len() > args.max_files {
632        return Err(AppError::Validation(format!(
633            "found {} files matching pattern, exceeds --max-files cap of {} (raise the cap or narrow the pattern)",
634            files.len(),
635            args.max_files
636        )));
637    }
638
639    let namespace = crate::namespace::resolve_namespace(args.namespace.as_deref())?;
640    let memory_type_str = args.r#type.as_str().to_string();
641
642    let paths = AppPaths::resolve(args.db.as_deref())?;
643    let mut conn_or_err = match init_storage(&paths) {
644        Ok(c) => Ok(c),
645        Err(e) => Err(format!("{e}")),
646    };
647
648    let mut succeeded: usize = 0;
649    let mut failed: usize = 0;
650    let mut skipped: usize = 0;
651    let total = files.len();
652
653    // Pre-resolve all names before parallelisation so Phase A workers see a
654    // consistent, immutable name assignment (v1.0.31 A10 contract preserved).
655    let mut taken_names: BTreeSet<String> = BTreeSet::new();
656
657    // SlotMeta: per-slot output metadata retained on the main thread for NDJSON.
658    // ProcessItem: the data moved into the producer thread for Phase A computation.
659    // We split these so `slots_meta` (non-Send BTreeSet-dependent) stays on main
660    // thread while `process_items` (Send: only PathBuf + String) crosses the thread
661    // boundary into the rayon producer.
662    enum SlotMeta {
663        Skip {
664            file_str: String,
665            derived_base: String,
666            name_truncated: bool,
667            original_name: Option<String>,
668            reason: String,
669        },
670        Process {
671            file_str: String,
672            derived_name: String,
673            name_truncated: bool,
674            original_name: Option<String>,
675        },
676    }
677
678    struct ProcessItem {
679        idx: usize,
680        path: PathBuf,
681        file_str: String,
682        derived_name: String,
683    }
684
685    let mut slots_meta: Vec<SlotMeta> = Vec::with_capacity(files.len());
686    let mut process_items: Vec<ProcessItem> = Vec::new();
687    let mut truncations: Vec<(String, String)> = Vec::new();
688
689    for path in &files {
690        let file_str = path.to_string_lossy().into_owned();
691        let (derived_base, name_truncated, original_name) = derive_kebab_name(path);
692
693        if name_truncated {
694            if let Some(ref orig) = original_name {
695                truncations.push((orig.clone(), derived_base.clone()));
696            }
697        }
698
699        if derived_base.is_empty() {
700            slots_meta.push(SlotMeta::Skip {
701                file_str,
702                derived_base: String::new(),
703                name_truncated: false,
704                original_name: None,
705                reason: "could not derive a non-empty kebab-case name from filename".to_string(),
706            });
707            continue;
708        }
709
710        match unique_name(&derived_base, &taken_names) {
711            Ok(derived_name) => {
712                taken_names.insert(derived_name.clone());
713                let idx = slots_meta.len();
714                process_items.push(ProcessItem {
715                    idx,
716                    path: path.clone(),
717                    file_str: file_str.clone(),
718                    derived_name: derived_name.clone(),
719                });
720                slots_meta.push(SlotMeta::Process {
721                    file_str,
722                    derived_name,
723                    name_truncated,
724                    original_name,
725                });
726            }
727            Err(e) => {
728                slots_meta.push(SlotMeta::Skip {
729                    file_str,
730                    derived_base,
731                    name_truncated,
732                    original_name,
733                    reason: e.to_string(),
734                });
735            }
736        }
737    }
738
739    if !truncations.is_empty() {
740        tracing::info!(
741            target: "ingest",
742            count = truncations.len(),
743            max_len = DERIVED_NAME_MAX_LEN,
744            "derived names truncated; pass -vv (debug) for per-file detail"
745        );
746    }
747
748    // Determine rayon thread pool size, honoring --low-memory and the
749    // SQLITE_GRAPHRAG_LOW_MEMORY env var (both force parallelism = 1).
750    let parallelism = resolve_parallelism(args.low_memory, args.ingest_parallelism);
751
752    let pool = rayon::ThreadPoolBuilder::new()
753        .num_threads(parallelism)
754        .build()
755        .map_err(|e| AppError::Internal(anyhow::anyhow!("rayon pool: {e}")))?;
756
757    if args.enable_ner && args.skip_extraction {
758        tracing::warn!(
759            "--enable-ner and --skip-extraction are contradictory; --enable-ner takes precedence"
760        );
761    }
762    let enable_ner = args.enable_ner;
763    let gliner_variant: crate::extraction::GlinerVariant =
764        args.gliner_variant.parse().unwrap_or_else(|e| {
765            tracing::warn!("invalid --gliner-variant: {e}; using fp32");
766            crate::extraction::GlinerVariant::Fp32
767        });
768
769    let total_to_process = process_items.len();
770    tracing::info!(
771        target = "ingest",
772        phase = "pipeline_start",
773        files = total_to_process,
774        ingest_parallelism = parallelism,
775        "incremental pipeline starting: Phase A (rayon) → channel → Phase B (main thread)",
776    );
777
778    // Bounded channel: producer never gets more than parallelism*2 items ahead of
779    // the consumer, preventing memory blowup when Phase A is faster than Phase B.
780    // Each message carries the slot index so Phase B can look up SlotMeta in order.
781    let channel_bound = (parallelism * 2).max(1);
782    let (tx, rx) = mpsc::sync_channel::<(usize, Result<StagedFile, AppError>)>(channel_bound);
783
784    // Phase A: launched in a dedicated OS thread so the main thread can consume
785    // the channel concurrently. pool.install() blocks the calling thread until
786    // all rayon workers finish — if called on the main thread it would
787    // reintroduce the 2-phase blocking behaviour we are eliminating.
788    let paths_owned = paths.clone();
789    let producer_handle = std::thread::spawn(move || {
790        pool.install(|| {
791            process_items.into_par_iter().for_each(|item| {
792                let t0 = std::time::Instant::now();
793                let result = stage_file(
794                    item.idx,
795                    &item.path,
796                    &item.derived_name,
797                    &paths_owned,
798                    enable_ner,
799                    gliner_variant,
800                );
801                let elapsed_ms = t0.elapsed().as_millis() as u64;
802
803                // Emit NDJSON progress event to stderr so the user sees work
804                // happening during long NER runs (e.g. 50 files × 27s each).
805                let (n_entities, n_relationships) = match &result {
806                    Ok(sf) => (sf.entities.len(), sf.relationships.len()),
807                    Err(_) => (0, 0),
808                };
809                let progress = StageProgressEvent {
810                    schema_version: 1,
811                    event: "file_extracted",
812                    path: &item.file_str,
813                    ms: elapsed_ms,
814                    entities: n_entities,
815                    relationships: n_relationships,
816                };
817                if let Ok(line) = serde_json::to_string(&progress) {
818                    eprintln!("{line}");
819                }
820
821                // Blocking send applies backpressure: if Phase B is slower,
822                // Phase A workers wait here instead of accumulating staged files
823                // in memory. If the receiver is dropped (fail_fast abort), ignore.
824                let _ = tx.send((item.idx, result));
825            });
826            // Explicit drop of tx signals Phase B (rx iteration) to stop.
827            drop(tx);
828        });
829    });
830
831    // Phase B: main thread persists files as results arrive from the channel.
832    // Results arrive in completion order (par_iter is unordered). We persist
833    // each file immediately on arrival — this is the key fix for B1: with the
834    // old 2-phase design the first DB write happened only after ALL files had
835    // finished Phase A. Now the first commit happens as soon as the first file
836    // completes Phase A, regardless of how many files remain.
837    //
838    // NDJSON output order follows completion order (not file-system sort order).
839    // Skip slots are emitted at the end, after all Process results are consumed.
840    // This trade-off is intentional: deterministic NDJSON ordering is a lesser
841    // requirement than ensuring data is persisted before the user's timeout fires.
842    let fail_fast = args.fail_fast;
843
844    // Emit pending Skip events first so agents see them early.
845    for meta in &slots_meta {
846        if let SlotMeta::Skip {
847            file_str,
848            derived_base,
849            name_truncated,
850            original_name,
851            reason,
852        } = meta
853        {
854            output::emit_json_compact(&IngestFileEvent {
855                file: file_str,
856                name: derived_base,
857                status: "skipped",
858                truncated: *name_truncated,
859                original_name: original_name.clone(),
860                error: Some(reason.clone()),
861                memory_id: None,
862                action: None,
863            })?;
864            skipped += 1;
865        }
866    }
867
868    // Build a quick index from slot index → SlotMeta reference for O(1) lookups
869    // as channel messages arrive in completion order.
870    let meta_index: std::collections::HashMap<usize, &SlotMeta> = slots_meta
871        .iter()
872        .enumerate()
873        .filter(|(_, m)| matches!(m, SlotMeta::Process { .. }))
874        .collect();
875
876    tracing::info!(
877        target = "ingest",
878        phase = "persist_start",
879        files = total_to_process,
880        "phase B starting: persisting files incrementally as Phase A completes each one",
881    );
882
883    // Drain channel and persist each file immediately — no accumulation into a
884    // HashMap. The bounded channel ensures Phase A cannot run too far ahead of
885    // Phase B without applying backpressure.
886    for (idx, stage_result) in rx {
887        let meta = meta_index.get(&idx).ok_or_else(|| {
888            AppError::Internal(anyhow::anyhow!(
889                "channel idx {idx} has no corresponding Process slot"
890            ))
891        })?;
892        let (file_str, derived_name, name_truncated, original_name) = match meta {
893            SlotMeta::Process {
894                file_str,
895                derived_name,
896                name_truncated,
897                original_name,
898            } => (file_str, derived_name, name_truncated, original_name),
899            SlotMeta::Skip { .. } => unreachable!("channel only carries Process results"),
900        };
901
902        // If storage init failed, every file fails with the same error.
903        let conn = match conn_or_err.as_mut() {
904            Ok(c) => c,
905            Err(err_msg) => {
906                let err_clone = err_msg.clone();
907                output::emit_json_compact(&IngestFileEvent {
908                    file: file_str,
909                    name: derived_name,
910                    status: "failed",
911                    truncated: *name_truncated,
912                    original_name: original_name.clone(),
913                    error: Some(err_clone.clone()),
914                    memory_id: None,
915                    action: None,
916                })?;
917                failed += 1;
918                if fail_fast {
919                    output::emit_json_compact(&IngestSummary {
920                        summary: true,
921                        dir: args.dir.display().to_string(),
922                        pattern: args.pattern.clone(),
923                        recursive: args.recursive,
924                        files_total: total,
925                        files_succeeded: succeeded,
926                        files_failed: failed,
927                        files_skipped: skipped,
928                        elapsed_ms: started.elapsed().as_millis() as u64,
929                    })?;
930                    return Err(AppError::Validation(format!(
931                        "ingest aborted on first failure: {err_clone}"
932                    )));
933                }
934                continue;
935            }
936        };
937
938        let outcome =
939            stage_result.and_then(|sf| persist_staged(conn, &namespace, &memory_type_str, sf));
940
941        match outcome {
942            Ok(FileSuccess { memory_id, action }) => {
943                output::emit_json_compact(&IngestFileEvent {
944                    file: file_str,
945                    name: derived_name,
946                    status: "indexed",
947                    truncated: *name_truncated,
948                    original_name: original_name.clone(),
949                    error: None,
950                    memory_id: Some(memory_id),
951                    action: Some(action),
952                })?;
953                succeeded += 1;
954            }
955            Err(e) => {
956                let err_msg = format!("{e}");
957                output::emit_json_compact(&IngestFileEvent {
958                    file: file_str,
959                    name: derived_name,
960                    status: "failed",
961                    truncated: *name_truncated,
962                    original_name: original_name.clone(),
963                    error: Some(err_msg.clone()),
964                    memory_id: None,
965                    action: None,
966                })?;
967                failed += 1;
968                if fail_fast {
969                    output::emit_json_compact(&IngestSummary {
970                        summary: true,
971                        dir: args.dir.display().to_string(),
972                        pattern: args.pattern.clone(),
973                        recursive: args.recursive,
974                        files_total: total,
975                        files_succeeded: succeeded,
976                        files_failed: failed,
977                        files_skipped: skipped,
978                        elapsed_ms: started.elapsed().as_millis() as u64,
979                    })?;
980                    return Err(AppError::Validation(format!(
981                        "ingest aborted on first failure: {err_msg}"
982                    )));
983                }
984            }
985        }
986    }
987
988    // Wait for the producer thread to finish cleanly.
989    producer_handle
990        .join()
991        .map_err(|_| AppError::Internal(anyhow::anyhow!("ingest producer thread panicked")))?;
992
993    output::emit_json_compact(&IngestSummary {
994        summary: true,
995        dir: args.dir.display().to_string(),
996        pattern: args.pattern.clone(),
997        recursive: args.recursive,
998        files_total: total,
999        files_succeeded: succeeded,
1000        files_failed: failed,
1001        files_skipped: skipped,
1002        elapsed_ms: started.elapsed().as_millis() as u64,
1003    })?;
1004
1005    Ok(())
1006}
1007
1008/// Auto-initialises the database (matches the contract of every other CRUD
1009/// handler) and returns a fresh read/write connection ready for the ingest
1010/// loop. Errors here are recoverable per-file: the caller surfaces them as
1011/// failure events so `--fail-fast` and the continue-on-error path keep
1012/// working when, for example, the user points `--db` at an unwritable path.
1013fn init_storage(paths: &AppPaths) -> Result<Connection, AppError> {
1014    ensure_db_ready(paths)?;
1015    let conn = open_rw(&paths.db)?;
1016    Ok(conn)
1017}
1018
1019fn is_valid_relation(relation: &str) -> bool {
1020    matches!(
1021        relation,
1022        "applies_to"
1023            | "uses"
1024            | "depends_on"
1025            | "causes"
1026            | "fixes"
1027            | "contradicts"
1028            | "supports"
1029            | "follows"
1030            | "related"
1031            | "mentions"
1032            | "replaces"
1033            | "tracked_in"
1034    )
1035}
1036
1037fn collect_files(
1038    dir: &Path,
1039    pattern: &str,
1040    recursive: bool,
1041    out: &mut Vec<PathBuf>,
1042) -> Result<(), AppError> {
1043    let entries = std::fs::read_dir(dir).map_err(AppError::Io)?;
1044    for entry in entries {
1045        let entry = entry.map_err(AppError::Io)?;
1046        let path = entry.path();
1047        let file_type = entry.file_type().map_err(AppError::Io)?;
1048        if file_type.is_file() {
1049            let name = entry.file_name();
1050            let name_str = name.to_string_lossy();
1051            if matches_pattern(&name_str, pattern) {
1052                out.push(path);
1053            }
1054        } else if file_type.is_dir() && recursive {
1055            collect_files(&path, pattern, recursive, out)?;
1056        }
1057    }
1058    Ok(())
1059}
1060
1061fn matches_pattern(name: &str, pattern: &str) -> bool {
1062    if let Some(suffix) = pattern.strip_prefix('*') {
1063        name.ends_with(suffix)
1064    } else if let Some(prefix) = pattern.strip_suffix('*') {
1065        name.starts_with(prefix)
1066    } else {
1067        name == pattern
1068    }
1069}
1070
1071/// Returns `(final_name, truncated, original_name)`.
1072/// `truncated` is true when the derived name exceeded `DERIVED_NAME_MAX_LEN`.
1073/// `original_name` holds the pre-truncation name only when `truncated=true`.
1074///
1075/// Non-ASCII characters are first decomposed via NFD and then stripped of
1076/// combining marks so accented letters fold to their base ASCII letter
1077/// (e.g. `açaí` → `acai`, `naïve` → `naive`). Characters with no ASCII
1078/// fallback (emoji, CJK ideographs, symbols) are dropped silently. This
1079/// preserves meaningful word content rather than collapsing the basename
1080/// to a few stray ASCII letters as the previous filter did.
1081fn derive_kebab_name(path: &Path) -> (String, bool, Option<String>) {
1082    let stem = path.file_stem().and_then(|s| s.to_str()).unwrap_or("");
1083    let lowered: String = stem
1084        .nfd()
1085        .filter(|c| !unicode_normalization::char::is_combining_mark(*c))
1086        .map(|c| {
1087            if c == '_' || c.is_whitespace() {
1088                '-'
1089            } else {
1090                c
1091            }
1092        })
1093        .map(|c| c.to_ascii_lowercase())
1094        .filter(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || *c == '-')
1095        .collect();
1096    let collapsed = collapse_dashes(&lowered);
1097    let trimmed = collapsed.trim_matches('-').to_string();
1098    if trimmed.len() > DERIVED_NAME_MAX_LEN {
1099        let truncated = trimmed[..DERIVED_NAME_MAX_LEN]
1100            .trim_matches('-')
1101            .to_string();
1102        tracing::debug!(
1103            target: "ingest",
1104            original = %trimmed,
1105            truncated_to = %truncated,
1106            max_len = DERIVED_NAME_MAX_LEN,
1107            "derived memory name truncated to fit length cap; collisions will be resolved with numeric suffixes"
1108        );
1109        (truncated, true, Some(trimmed))
1110    } else {
1111        (trimmed, false, None)
1112    }
1113}
1114
1115/// v1.0.31 A10: returns the first non-colliding kebab name by appending a
1116/// numeric suffix (`-1`, `-2`, …) when needed.
1117///
1118/// `taken` is the set of names already consumed in the current ingest run.
1119/// The caller is expected to insert the returned name into `taken` so the
1120/// next call observes the consumption. Cross-run collisions are intentionally
1121/// surfaced by the per-file persistence path as duplicates so re-ingestion
1122/// of identical corpora stays idempotent.
1123///
1124/// Returns `Err(AppError::Validation)` after `MAX_NAME_COLLISION_SUFFIX`
1125/// candidates collide, signalling a pathological corpus that should be
1126/// renamed manually.
1127fn unique_name(base: &str, taken: &BTreeSet<String>) -> Result<String, AppError> {
1128    if !taken.contains(base) {
1129        return Ok(base.to_string());
1130    }
1131    for suffix in 1..=MAX_NAME_COLLISION_SUFFIX {
1132        let candidate = format!("{base}-{suffix}");
1133        if !taken.contains(&candidate) {
1134            tracing::warn!(
1135                target: "ingest",
1136                base = %base,
1137                resolved = %candidate,
1138                suffix,
1139                "memory name collision resolved with numeric suffix"
1140            );
1141            return Ok(candidate);
1142        }
1143    }
1144    Err(AppError::Validation(format!(
1145        "too many name collisions for base '{base}' (>{MAX_NAME_COLLISION_SUFFIX}); rename source files to disambiguate"
1146    )))
1147}
1148
1149fn collapse_dashes(s: &str) -> String {
1150    let mut out = String::with_capacity(s.len());
1151    let mut prev_dash = false;
1152    for c in s.chars() {
1153        if c == '-' {
1154            if !prev_dash {
1155                out.push('-');
1156            }
1157            prev_dash = true;
1158        } else {
1159            out.push(c);
1160            prev_dash = false;
1161        }
1162    }
1163    out
1164}
1165
1166#[cfg(test)]
1167mod tests {
1168    use super::*;
1169    use std::path::PathBuf;
1170
1171    #[test]
1172    fn matches_pattern_suffix() {
1173        assert!(matches_pattern("foo.md", "*.md"));
1174        assert!(!matches_pattern("foo.txt", "*.md"));
1175        assert!(matches_pattern("foo.md", "*"));
1176    }
1177
1178    #[test]
1179    fn matches_pattern_prefix() {
1180        assert!(matches_pattern("README.md", "README*"));
1181        assert!(!matches_pattern("CHANGELOG.md", "README*"));
1182    }
1183
1184    #[test]
1185    fn matches_pattern_exact() {
1186        assert!(matches_pattern("README.md", "README.md"));
1187        assert!(!matches_pattern("readme.md", "README.md"));
1188    }
1189
1190    #[test]
1191    fn derive_kebab_underscore_to_dash() {
1192        let p = PathBuf::from("/tmp/claude_code_headless.md");
1193        let (name, truncated, original) = derive_kebab_name(&p);
1194        assert_eq!(name, "claude-code-headless");
1195        assert!(!truncated);
1196        assert!(original.is_none());
1197    }
1198
1199    #[test]
1200    fn derive_kebab_uppercase_lowered() {
1201        let p = PathBuf::from("/tmp/README.md");
1202        let (name, truncated, original) = derive_kebab_name(&p);
1203        assert_eq!(name, "readme");
1204        assert!(!truncated);
1205        assert!(original.is_none());
1206    }
1207
1208    #[test]
1209    fn derive_kebab_strips_non_kebab_chars() {
1210        let p = PathBuf::from("/tmp/some@weird#name!.md");
1211        let (name, truncated, original) = derive_kebab_name(&p);
1212        assert_eq!(name, "someweirdname");
1213        assert!(!truncated);
1214        assert!(original.is_none());
1215    }
1216
1217    // Bug M-A3: NFD-based unicode normalization preserves base letters of
1218    // accented characters instead of dropping them entirely.
1219    #[test]
1220    fn derive_kebab_folds_accented_letters_to_ascii() {
1221        let p = PathBuf::from("/tmp/açaí.md");
1222        let (name, _, _) = derive_kebab_name(&p);
1223        assert_eq!(name, "acai", "got '{name}'");
1224    }
1225
1226    #[test]
1227    fn derive_kebab_handles_naive_with_diaeresis() {
1228        let p = PathBuf::from("/tmp/naïve-test.md");
1229        let (name, _, _) = derive_kebab_name(&p);
1230        assert_eq!(name, "naive-test", "got '{name}'");
1231    }
1232
1233    #[test]
1234    fn derive_kebab_drops_emoji_keeps_word() {
1235        let p = PathBuf::from("/tmp/🚀-rocket.md");
1236        let (name, _, _) = derive_kebab_name(&p);
1237        assert_eq!(name, "rocket", "got '{name}'");
1238    }
1239
1240    #[test]
1241    fn derive_kebab_mixed_unicode_emoji_keeps_letters() {
1242        let p = PathBuf::from("/tmp/açaí🦜.md");
1243        let (name, _, _) = derive_kebab_name(&p);
1244        assert_eq!(name, "acai", "got '{name}'");
1245    }
1246
1247    #[test]
1248    fn derive_kebab_pure_emoji_yields_empty() {
1249        let p = PathBuf::from("/tmp/🦜🚀🌟.md");
1250        let (name, _, _) = derive_kebab_name(&p);
1251        assert!(name.is_empty(), "got '{name}'");
1252    }
1253
1254    #[test]
1255    fn derive_kebab_collapses_consecutive_dashes() {
1256        let p = PathBuf::from("/tmp/a__b___c.md");
1257        let (name, truncated, original) = derive_kebab_name(&p);
1258        assert_eq!(name, "a-b-c");
1259        assert!(!truncated);
1260        assert!(original.is_none());
1261    }
1262
1263    #[test]
1264    fn derive_kebab_truncates_to_60_chars() {
1265        let p = PathBuf::from(format!("/tmp/{}.md", "a".repeat(80)));
1266        let (name, truncated, original) = derive_kebab_name(&p);
1267        assert!(name.len() <= 60, "got len {}", name.len());
1268        assert!(truncated);
1269        assert!(original.is_some());
1270        assert!(original.unwrap().len() > 60);
1271    }
1272
1273    #[test]
1274    fn collect_files_finds_md_files() {
1275        let tmp = tempfile::tempdir().expect("tempdir");
1276        std::fs::write(tmp.path().join("a.md"), "x").unwrap();
1277        std::fs::write(tmp.path().join("b.md"), "y").unwrap();
1278        std::fs::write(tmp.path().join("c.txt"), "z").unwrap();
1279        let mut out = Vec::new();
1280        collect_files(tmp.path(), "*.md", false, &mut out).expect("collect");
1281        assert_eq!(out.len(), 2, "should find 2 .md files, got {out:?}");
1282    }
1283
1284    #[test]
1285    fn collect_files_recursive_descends_subdirs() {
1286        let tmp = tempfile::tempdir().expect("tempdir");
1287        let sub = tmp.path().join("sub");
1288        std::fs::create_dir(&sub).unwrap();
1289        std::fs::write(tmp.path().join("a.md"), "x").unwrap();
1290        std::fs::write(sub.join("b.md"), "y").unwrap();
1291        let mut out = Vec::new();
1292        collect_files(tmp.path(), "*.md", true, &mut out).expect("collect");
1293        assert_eq!(out.len(), 2);
1294    }
1295
1296    #[test]
1297    fn collect_files_non_recursive_skips_subdirs() {
1298        let tmp = tempfile::tempdir().expect("tempdir");
1299        let sub = tmp.path().join("sub");
1300        std::fs::create_dir(&sub).unwrap();
1301        std::fs::write(tmp.path().join("a.md"), "x").unwrap();
1302        std::fs::write(sub.join("b.md"), "y").unwrap();
1303        let mut out = Vec::new();
1304        collect_files(tmp.path(), "*.md", false, &mut out).expect("collect");
1305        assert_eq!(out.len(), 1);
1306    }
1307
1308    // ── v1.0.31 A10: name truncation warns and collisions are auto-resolved ──
1309
1310    #[test]
1311    fn derive_kebab_long_basename_truncated_within_cap() {
1312        let p = PathBuf::from(format!("/tmp/{}.md", "a".repeat(120)));
1313        let (name, truncated, original) = derive_kebab_name(&p);
1314        assert!(
1315            name.len() <= DERIVED_NAME_MAX_LEN,
1316            "truncated name must respect cap; got {} chars",
1317            name.len()
1318        );
1319        assert!(!name.is_empty());
1320        assert!(truncated);
1321        assert!(original.is_some());
1322    }
1323
1324    #[test]
1325    fn unique_name_returns_base_when_free() {
1326        let taken: BTreeSet<String> = BTreeSet::new();
1327        let resolved = unique_name("note", &taken).expect("must resolve");
1328        assert_eq!(resolved, "note");
1329    }
1330
1331    #[test]
1332    fn unique_name_appends_first_free_suffix_on_collision() {
1333        let mut taken: BTreeSet<String> = BTreeSet::new();
1334        taken.insert("note".to_string());
1335        taken.insert("note-1".to_string());
1336        let resolved = unique_name("note", &taken).expect("must resolve");
1337        assert_eq!(resolved, "note-2");
1338    }
1339
1340    #[test]
1341    fn unique_name_errors_after_collision_cap() {
1342        let mut taken: BTreeSet<String> = BTreeSet::new();
1343        taken.insert("note".to_string());
1344        for i in 1..=MAX_NAME_COLLISION_SUFFIX {
1345            taken.insert(format!("note-{i}"));
1346        }
1347        let err = unique_name("note", &taken).expect_err("must surface error");
1348        assert!(matches!(err, AppError::Validation(_)));
1349    }
1350
1351    // ── v1.0.32 Onda 4B: in-process pipeline validation ──
1352
1353    #[test]
1354    fn is_valid_relation_accepts_canonical_relations() {
1355        assert!(is_valid_relation("applies_to"));
1356        assert!(is_valid_relation("depends_on"));
1357        assert!(!is_valid_relation("foo_bar"));
1358    }
1359
1360    // ── v1.0.40 H-A1: --low-memory flag and SQLITE_GRAPHRAG_LOW_MEMORY env var ──
1361
1362    use serial_test::serial;
1363
1364    /// Helper: scrubs the env var around a closure to keep tests deterministic.
1365    fn with_env_var<F: FnOnce()>(value: Option<&str>, f: F) {
1366        let key = "SQLITE_GRAPHRAG_LOW_MEMORY";
1367        let prev = std::env::var(key).ok();
1368        match value {
1369            Some(v) => std::env::set_var(key, v),
1370            None => std::env::remove_var(key),
1371        }
1372        f();
1373        match prev {
1374            Some(p) => std::env::set_var(key, p),
1375            None => std::env::remove_var(key),
1376        }
1377    }
1378
1379    #[test]
1380    #[serial]
1381    fn env_low_memory_enabled_unset_returns_false() {
1382        with_env_var(None, || assert!(!env_low_memory_enabled()));
1383    }
1384
1385    #[test]
1386    #[serial]
1387    fn env_low_memory_enabled_empty_returns_false() {
1388        with_env_var(Some(""), || assert!(!env_low_memory_enabled()));
1389    }
1390
1391    #[test]
1392    #[serial]
1393    fn env_low_memory_enabled_truthy_values_return_true() {
1394        for v in ["1", "true", "TRUE", "yes", "YES", "on", "On"] {
1395            with_env_var(Some(v), || {
1396                assert!(env_low_memory_enabled(), "value {v:?} should be truthy")
1397            });
1398        }
1399    }
1400
1401    #[test]
1402    #[serial]
1403    fn env_low_memory_enabled_falsy_values_return_false() {
1404        for v in ["0", "false", "FALSE", "no", "off"] {
1405            with_env_var(Some(v), || {
1406                assert!(!env_low_memory_enabled(), "value {v:?} should be falsy")
1407            });
1408        }
1409    }
1410
1411    #[test]
1412    #[serial]
1413    fn env_low_memory_enabled_unrecognized_value_returns_false() {
1414        with_env_var(Some("maybe"), || assert!(!env_low_memory_enabled()));
1415    }
1416
1417    #[test]
1418    #[serial]
1419    fn resolve_parallelism_flag_forces_one_overriding_explicit_value() {
1420        with_env_var(None, || {
1421            assert_eq!(resolve_parallelism(true, Some(4)), 1);
1422            assert_eq!(resolve_parallelism(true, Some(8)), 1);
1423            assert_eq!(resolve_parallelism(true, None), 1);
1424        });
1425    }
1426
1427    #[test]
1428    #[serial]
1429    fn resolve_parallelism_env_forces_one_when_flag_off() {
1430        with_env_var(Some("1"), || {
1431            assert_eq!(resolve_parallelism(false, Some(4)), 1);
1432            assert_eq!(resolve_parallelism(false, None), 1);
1433        });
1434    }
1435
1436    #[test]
1437    #[serial]
1438    fn resolve_parallelism_falsy_env_does_not_override() {
1439        with_env_var(Some("0"), || {
1440            assert_eq!(resolve_parallelism(false, Some(4)), 4);
1441        });
1442    }
1443
1444    #[test]
1445    #[serial]
1446    fn resolve_parallelism_explicit_value_when_low_memory_off() {
1447        with_env_var(None, || {
1448            assert_eq!(resolve_parallelism(false, Some(3)), 3);
1449            assert_eq!(resolve_parallelism(false, Some(1)), 1);
1450        });
1451    }
1452
1453    #[test]
1454    #[serial]
1455    fn resolve_parallelism_default_when_unset() {
1456        with_env_var(None, || {
1457            let p = resolve_parallelism(false, None);
1458            assert!((1..=4).contains(&p), "default must be in [1, 4]; got {p}");
1459        });
1460    }
1461
1462    #[test]
1463    fn ingest_args_parses_low_memory_flag_via_clap() {
1464        use clap::Parser;
1465        // Parse a synthetic Cli that contains the `ingest` subcommand. We rely
1466        // on the public `Cli` definition so the flag is wired end-to-end.
1467        let cli = crate::cli::Cli::try_parse_from([
1468            "sqlite-graphrag",
1469            "ingest",
1470            "/tmp/dummy",
1471            "--type",
1472            "document",
1473            "--low-memory",
1474        ])
1475        .expect("parse must succeed");
1476        match cli.command {
1477            crate::cli::Commands::Ingest(args) => {
1478                assert!(args.low_memory, "--low-memory must set field to true");
1479            }
1480            _ => panic!("expected Ingest subcommand"),
1481        }
1482    }
1483
1484    #[test]
1485    fn ingest_args_low_memory_defaults_false() {
1486        use clap::Parser;
1487        let cli = crate::cli::Cli::try_parse_from([
1488            "sqlite-graphrag",
1489            "ingest",
1490            "/tmp/dummy",
1491            "--type",
1492            "document",
1493        ])
1494        .expect("parse must succeed");
1495        match cli.command {
1496            crate::cli::Commands::Ingest(args) => {
1497                assert!(!args.low_memory, "default must be false");
1498            }
1499            _ => panic!("expected Ingest subcommand"),
1500        }
1501    }
1502}