sqlite-graphrag 1.0.67

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
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
//! Shared module for spawning Claude Code (`claude -p`) subprocesses.
//!
//! Eliminates duplication between `enrich.rs` and `ingest_claude.rs` (G02).
//! Detects `terminal_reason: "max_turns"` in the JSON output (G03).

use crate::errors::AppError;
use std::path::Path;
use std::process::{Command, Stdio};

/// Minimum Claude Code version required for structured JSON output.
const MIN_CLAUDE_VERSION: &str = "2.1.0";

/// Environment variables whitelisted for the subprocess.
const ENV_WHITELIST: &[&str] = &[
    "PATH",
    "HOME",
    "USER",
    "SHELL",
    "TERM",
    "LANG",
    "XDG_CONFIG_HOME",
    "XDG_DATA_HOME",
    "XDG_RUNTIME_DIR",
    "ANTHROPIC_API_KEY",
    "CLAUDE_CONFIG_DIR",
    "TMPDIR",
    "TMP",
    "TEMP",
    "DYLD_FALLBACK_LIBRARY_PATH",
];

/// Windows-only environment variables.
#[cfg(windows)]
const ENV_WHITELIST_WINDOWS: &[&str] = &[
    "LOCALAPPDATA",
    "APPDATA",
    "USERPROFILE",
    "SystemRoot",
    "COMSPEC",
    "PATHEXT",
    "HOMEPATH",
    "HOMEDRIVE",
];

/// Default virtual memory limit for LLM subprocesses (4 GiB).
const DEFAULT_SUBPROCESS_MEMORY_LIMIT_MB: u64 = 4096;

/// Spawns a command with a virtual memory limit via `setrlimit(RLIMIT_AS)`.
///
/// On Linux, applies the limit in a `pre_exec` hook before the child process
/// starts.  On non-Linux platforms, falls back to an unlimited spawn.
/// The limit is read from `SQLITE_GRAPHRAG_SUBPROCESS_MEMORY_LIMIT_MB`
/// (default: 4096 MiB).
#[cfg(target_os = "linux")]
pub fn spawn_with_memory_limit(cmd: &mut Command) -> std::io::Result<std::process::Child> {
    use std::os::unix::process::CommandExt;
    let max_mb: u64 = std::env::var("SQLITE_GRAPHRAG_SUBPROCESS_MEMORY_LIMIT_MB")
        .ok()
        .and_then(|v| v.parse().ok())
        .unwrap_or(DEFAULT_SUBPROCESS_MEMORY_LIMIT_MB);
    let max_bytes = max_mb * 1024 * 1024;
    // SAFETY: pre_exec closure runs between fork() and exec() in the
    // single-threaded child process — no other threads exist.
    // libc::setsid and libc::setrlimit are async-signal-safe per POSIX.1-2008 §2.4.3.
    // RLIMIT_AS limits virtual address space, not physical RSS.
    // setsid failure with EPERM is tolerated (process already a session leader).
    // On setrlimit failure, Err(last_os_error()) prevents exec.
    unsafe {
        cmd.pre_exec(move || {
            let sid = libc::setsid();
            if sid == -1 {
                let err = std::io::Error::last_os_error();
                if err.raw_os_error() != Some(libc::EPERM) {
                    return Err(err);
                }
            }
            let limit = libc::rlimit {
                rlim_cur: max_bytes,
                rlim_max: max_bytes,
            };
            if libc::setrlimit(libc::RLIMIT_AS, &limit) != 0 {
                return Err(std::io::Error::last_os_error());
            }
            Ok(())
        });
    }
    tracing::debug!(
        target: "process",
        program = ?cmd.get_program(),
        args = ?cmd.get_args().collect::<Vec<_>>(),
        "spawning external process"
    );
    cmd.spawn()
}

/// Spawns a command without memory limits (non-Linux fallback).
/// On Unix (macOS, FreeBSD), applies setsid for process group isolation.
#[cfg(not(target_os = "linux"))]
pub fn spawn_with_memory_limit(cmd: &mut Command) -> std::io::Result<std::process::Child> {
    #[cfg(unix)]
    {
        use std::os::unix::process::CommandExt;
        // SAFETY: setsid() is async-signal-safe per POSIX.1-2008 §2.4.3.
        // Creates independent session for cascade termination.
        unsafe {
            cmd.pre_exec(|| {
                let sid = libc::setsid();
                if sid == -1 {
                    let err = std::io::Error::last_os_error();
                    if err.raw_os_error() != Some(libc::EPERM) {
                        return Err(err);
                    }
                }
                Ok(())
            });
        }
    }
    tracing::debug!(
        target: "process",
        program = ?cmd.get_program(),
        args = ?cmd.get_args().collect::<Vec<_>>(),
        "spawning external process"
    );
    cmd.spawn()
}

/// Parsed output element from `claude -p --output-format json`.
#[derive(Debug, serde::Deserialize)]
pub struct ClaudeOutputElement {
    pub r#type: Option<String>,
    pub subtype: Option<String>,
    #[serde(default)]
    pub is_error: bool,
    pub structured_output: Option<serde_json::Value>,
    pub result: Option<String>,
    pub total_cost_usd: Option<f64>,
    pub error: Option<String>,
    pub terminal_reason: Option<String>,
    #[serde(rename = "apiKeySource")]
    pub api_key_source: Option<String>,
}

/// Result of a successful Claude invocation.
#[derive(Debug)]
pub struct ClaudeResult {
    pub value: serde_json::Value,
    pub cost_usd: f64,
    pub is_oauth: bool,
}

/// Validates that the Claude binary meets the minimum version requirement.
pub fn validate_claude_version(binary: &Path) -> Result<String, AppError> {
    let resolved = which::which(binary).map_err(|_| {
        AppError::Validation(format!(
            "executable '{}' not found in PATH; ensure it is installed and accessible",
            binary.display()
        ))
    })?;
    let output = Command::new(&resolved)
        .arg("--version")
        .stdin(Stdio::null())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .output()
        .map_err(AppError::Io)?;

    if !output.status.success() {
        return Err(AppError::Validation(
            "failed to run 'claude --version'".to_string(),
        ));
    }

    let version_str = String::from_utf8(output.stdout)
        .map_err(|_| AppError::Validation("claude --version output is not UTF-8".to_string()))?;
    let version = version_str.trim().to_string();
    let numeric = version.split([' ', '(']).next().unwrap_or("").trim();

    fn parse_semver(s: &str) -> Option<(u64, u64, u64)> {
        let parts: Vec<&str> = s.splitn(3, '.').collect();
        if parts.len() < 2 {
            return None;
        }
        let major = parts[0].parse::<u64>().ok()?;
        let minor = parts[1].parse::<u64>().ok()?;
        let patch = parts
            .get(2)
            .and_then(|p| p.parse::<u64>().ok())
            .unwrap_or(0);
        Some((major, minor, patch))
    }

    if let (Some(actual), Some(min)) = (parse_semver(numeric), parse_semver(MIN_CLAUDE_VERSION)) {
        if actual < min {
            return Err(AppError::Validation(format!(
                "Claude Code version {numeric} is below minimum required {MIN_CLAUDE_VERSION}"
            )));
        }
    }

    Ok(version)
}

/// Builds a `Command` for `claude -p` with least-privilege environment.
pub fn build_claude_command(
    binary: &Path,
    prompt: &str,
    json_schema: &str,
    model: Option<&str>,
    max_turns: u32,
) -> Command {
    let mut cmd = Command::new(binary);

    cmd.env_clear();
    for var in ENV_WHITELIST {
        if let Ok(val) = std::env::var(var) {
            cmd.env(var, val);
        }
    }

    #[cfg(windows)]
    for var in ENV_WHITELIST_WINDOWS {
        if let Ok(val) = std::env::var(var) {
            cmd.env(var, val);
        }
    }

    cmd.arg("-p")
        .arg(prompt)
        .arg("--output-format")
        .arg("json")
        .arg("--json-schema")
        .arg(json_schema)
        .arg("--max-turns")
        .arg(max_turns.to_string())
        .arg("--no-session-persistence");

    if std::env::var("ANTHROPIC_API_KEY").is_ok() {
        cmd.arg("--bare");
    } else {
        cmd.arg("--dangerously-skip-permissions")
            .arg("--settings")
            .arg(r#"{"hooks":{}}"#);
    }

    if let Some(m) = model {
        cmd.arg("--model").arg(m);
    }

    cmd.stdin(Stdio::null())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped());

    cmd
}

/// Parses `claude -p --output-format json` output array.
///
/// G03: detects `terminal_reason: "max_turns"` and returns a specific error
/// instead of a generic failure message.
pub fn parse_claude_output(stdout: &str) -> Result<ClaudeResult, AppError> {
    let elements: Vec<ClaudeOutputElement> = serde_json::from_str(stdout).map_err(|e| {
        AppError::Validation(format!("failed to parse claude output as JSON array: {e}"))
    })?;

    let is_oauth = elements
        .iter()
        .find(|e| e.r#type.as_deref() == Some("system") && e.subtype.as_deref() == Some("init"))
        .and_then(|e| e.api_key_source.as_deref())
        .map(|s| s == "none")
        .unwrap_or(false);

    let result_elem = elements
        .iter()
        .find(|e| e.r#type.as_deref() == Some("result"))
        .ok_or_else(|| {
            AppError::Validation("claude output missing 'result' element".to_string())
        })?;

    // G03: detect max_turns exhaustion before checking is_error
    if result_elem.terminal_reason.as_deref() == Some("max_turns") {
        tracing::warn!(
            target: "claude_runner",
            "claude -p hit max_turns limit — hooks may have consumed turns"
        );
        return Err(AppError::Validation(
            "claude -p hit max_turns: hooks may be consuming turns; increase --max-turns or disable hooks".to_string(),
        ));
    }

    if result_elem.is_error {
        let err_msg = result_elem
            .error
            .as_deref()
            .or(result_elem.result.as_deref())
            .unwrap_or("unknown error");
        if err_msg.contains("rate_limit") || err_msg.contains("overloaded") {
            return Err(AppError::RateLimited {
                detail: err_msg.to_string(),
            });
        }
        if err_msg.contains("Not logged in") || err_msg.contains("authentication") {
            tracing::warn!(
                target: "claude_runner",
                "Claude Code authentication failed. Re-authenticate interactively with: claude"
            );
        }
        return Err(AppError::Validation(format!(
            "claude extraction failed: {err_msg}"
        )));
    }

    let value = if let Some(v) = result_elem.structured_output.clone() {
        v
    } else if let Some(text) = &result_elem.result {
        serde_json::from_str(text).map_err(|e| {
            AppError::Validation(format!("failed to parse claude result field as JSON: {e}"))
        })?
    } else {
        return Err(AppError::Validation(
            "claude result missing structured_output and result field".into(),
        ));
    };

    let cost = result_elem.total_cost_usd.unwrap_or(0.0);
    Ok(ClaudeResult {
        value,
        cost_usd: cost,
        is_oauth,
    })
}

/// Calls `claude -p` with prompt and schema, waits with timeout, and parses output.
///
/// G03: parses stdout even on non-zero exit to detect `terminal_reason: "max_turns"`.
pub fn run_claude(
    binary: &Path,
    prompt: &str,
    json_schema: &str,
    input_text: &str,
    model: Option<&str>,
    timeout_secs: u64,
    max_turns: u32,
) -> Result<ClaudeResult, AppError> {
    use wait_timeout::ChildExt;

    let full_prompt = format!("{prompt}\n\n{input_text}");
    let mut cmd = build_claude_command(binary, &full_prompt, json_schema, model, max_turns);

    let mut child = spawn_with_memory_limit(&mut cmd).map_err(|e| {
        AppError::Io(std::io::Error::new(
            e.kind(),
            format!("failed to spawn claude: {e}"),
        ))
    })?;

    let start = std::time::Instant::now();
    let timeout = std::time::Duration::from_secs(timeout_secs);
    let status = child.wait_timeout(timeout).map_err(AppError::Io)?;

    match status {
        Some(exit_status) => {
            tracing::debug!(
                target: "process",
                exit_code = ?exit_status.code(),
                elapsed_ms = start.elapsed().as_millis() as u64,
                "external process completed"
            );

            let mut stdout_buf = Vec::new();
            let mut stderr_buf = Vec::new();
            if let Some(mut out) = child.stdout.take() {
                std::io::Read::read_to_end(&mut out, &mut stdout_buf).map_err(AppError::Io)?;
            }
            if let Some(mut err) = child.stderr.take() {
                std::io::Read::read_to_end(&mut err, &mut stderr_buf).map_err(AppError::Io)?;
            }

            let stdout_str = String::from_utf8(stdout_buf)
                .map_err(|_| AppError::Validation("claude -p stdout is not valid UTF-8".into()))?;

            // G03: parse stdout even on failure to detect terminal_reason
            if !exit_status.success() {
                if let Ok(result) = parse_claude_output(&stdout_str) {
                    return Ok(result);
                }
                let stderr_str = String::from_utf8_lossy(&stderr_buf);
                if stderr_str.contains("auth") || stderr_str.contains("login") {
                    tracing::warn!(
                        target: "claude_runner",
                        "Claude Code authentication may have failed. Re-authenticate with: claude"
                    );
                }
                return Err(AppError::Validation(format!(
                    "claude -p exited with code {:?}: {}",
                    exit_status.code(),
                    stderr_str.trim()
                )));
            }

            parse_claude_output(&stdout_str)
        }
        None => {
            tracing::warn!(target: "claude_runner", timeout_secs, "claude -p timed out, terminating");
            terminate_gracefully(&mut child, 3);
            Err(AppError::Validation(format!(
                "claude -p timed out after {timeout_secs} seconds"
            )))
        }
    }
}

/// Terminates a child process gracefully: SIGTERM first, SIGKILL after grace period.
#[cfg(unix)]
pub fn terminate_gracefully(child: &mut std::process::Child, grace_secs: u64) {
    use wait_timeout::ChildExt;
    unsafe {
        libc::kill(child.id() as i32, libc::SIGTERM);
    }
    match child.wait_timeout(std::time::Duration::from_secs(grace_secs)) {
        Ok(Some(_)) => {}
        _ => {
            tracing::warn!(target: "process", pid = child.id(), "child ignored SIGTERM, sending SIGKILL");
            let _ = child.kill();
            let _ = child.wait();
        }
    }
}

/// Non-Unix fallback: kill immediately (Windows TerminateProcess).
#[cfg(not(unix))]
pub fn terminate_gracefully(child: &mut std::process::Child, _grace_secs: u64) {
    let _ = child.kill();
    let _ = child.wait();
}

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

    #[test]
    fn parse_output_detects_max_turns() {
        let stdout = r#"[{"type":"system","subtype":"init","apiKeySource":"none"},{"type":"result","is_error":false,"terminal_reason":"max_turns","structured_output":{"name":"t"}}]"#;
        let err = parse_claude_output(stdout).unwrap_err();
        assert!(
            format!("{err}").contains("max_turns"),
            "must detect max_turns in output"
        );
    }

    #[test]
    fn parse_output_extracts_structured_value() {
        let stdout = r#"[{"type":"system","subtype":"init","apiKeySource":"none"},{"type":"result","is_error":false,"structured_output":{"key":"val"},"total_cost_usd":0.01}]"#;
        let result = parse_claude_output(stdout).unwrap();
        assert_eq!(result.value["key"], "val");
        assert!((result.cost_usd - 0.01).abs() < f64::EPSILON);
        assert!(result.is_oauth);
    }

    #[test]
    fn parse_output_detects_rate_limit() {
        let stdout = r#"[{"type":"result","is_error":true,"error":"rate_limit exceeded"}]"#;
        let err = parse_claude_output(stdout).unwrap_err();
        assert!(
            matches!(err, AppError::RateLimited { .. }),
            "expected AppError::RateLimited, got: {err}"
        );
    }
}