1use std::collections::HashSet;
7use std::fmt;
8use std::path::{Path, PathBuf};
9use std::sync::Arc;
10pub use troupekit_context::chunk::ChunkConfig;
11pub use troupekit_context::embed::Embedder;
12use troupekit_context::ingest::{document_records, Document, Origin};
13use troupekit_context::load::walk;
14pub use troupekit_context::load::LoadSettings;
15use troupekit_context::text::stable_hash;
16use troupekit_context::ContextError;
17use troupekit_core::clock::{Clock, SystemClock};
18use troupekit_store_sqlite::SqliteVectors;
19
20const SCOPE_DEFAULT: &str = "docs";
21const CHUNK_MAX_TOKENS_DEFAULT: usize = 200;
22const CHUNK_OVERLAP_TOKENS_DEFAULT: usize = 20;
23const MAX_REMOVE_SHARE_DEFAULT: u8 = 50;
24
25#[non_exhaustive]
31#[derive(Debug, Clone, PartialEq, Eq)]
32pub struct IngestSettings {
33 scope: String,
34 chunk: ChunkConfig,
35 load: LoadSettings,
36 origin: Origin,
37 allow_remove_all: bool,
38 max_remove_share: u8,
39}
40
41impl Default for IngestSettings {
42 fn default() -> Self {
43 Self {
44 scope: SCOPE_DEFAULT.to_string(),
45 chunk: ChunkConfig {
46 max_tokens: CHUNK_MAX_TOKENS_DEFAULT,
47 overlap_tokens: CHUNK_OVERLAP_TOKENS_DEFAULT,
48 },
49 load: LoadSettings::default(),
50 origin: Origin::External,
51 allow_remove_all: false,
52 max_remove_share: MAX_REMOVE_SHARE_DEFAULT,
53 }
54 }
55}
56
57impl IngestSettings {
58 pub fn with_scope(mut self, scope: impl Into<String>) -> Self {
62 self.scope = scope.into();
63 self
64 }
65
66 pub fn with_chunk(mut self, chunk: ChunkConfig) -> Self {
70 self.chunk = chunk;
71 self
72 }
73
74 pub fn with_load(mut self, load: LoadSettings) -> Self {
78 self.load = load;
79 self
80 }
81
82 pub fn with_origin(mut self, origin: Origin) -> Self {
86 self.origin = origin;
87 self
88 }
89
90 pub fn with_allow_remove_all(mut self, allow: bool) -> Self {
94 self.allow_remove_all = allow;
95 self
96 }
97
98 pub fn with_max_remove_share(mut self, percent: u8) -> Self {
102 self.max_remove_share = percent;
103 self
104 }
105
106 pub fn allow_remove_all(&self) -> bool {
110 self.allow_remove_all
111 }
112
113 pub fn max_remove_share(&self) -> u8 {
117 self.max_remove_share
118 }
119
120 pub fn scope(&self) -> &str {
124 &self.scope
125 }
126
127 pub fn chunk(&self) -> ChunkConfig {
131 self.chunk
132 }
133
134 pub fn load(&self) -> &LoadSettings {
138 &self.load
139 }
140
141 pub fn origin(&self) -> Origin {
145 self.origin
146 }
147}
148
149#[non_exhaustive]
154#[derive(Debug, Clone, PartialEq, Eq)]
155pub struct IngestReport {
156 pub added: usize,
157 pub replaced: usize,
158 pub skipped: usize,
159 pub removed: usize,
160 pub unsupported: usize,
161 pub symlinks: usize,
162 pub failed: Vec<(String, String)>,
163 pub chunks: usize,
164}
165
166pub async fn ingest_dir(
173 vectors: &SqliteVectors,
174 embedder: &dyn Embedder,
175 dir: &Path,
176 settings: &IngestSettings,
177) -> Result<IngestReport, ContextError> {
178 if settings.scope.trim().is_empty() {
179 return Err(ContextError::Invalid("scope must not be empty".into()));
180 }
181 if settings.max_remove_share > 100 {
182 return Err(ContextError::Invalid(format!(
183 "max_remove_share is {}%, above 100%",
184 settings.max_remove_share
185 )));
186 }
187 let walked = walk(dir, &settings.load)?;
188 let present: HashSet<String> = walked.files.iter().map(|f| f.source.clone()).collect();
189 let stored = vectors.sources(&settings.scope).await?;
190 let gone: Vec<String> = stored
191 .iter()
192 .filter(|s| !present.contains(*s) && !on_disk(dir, s))
193 .cloned()
194 .collect();
195 check_removals(gone.len(), stored.len(), present.is_empty(), settings)?;
196 let mut report = IngestReport {
197 added: 0,
198 replaced: 0,
199 skipped: 0,
200 removed: 0,
201 unsupported: walked.unsupported,
202 symlinks: walked.symlinks,
203 failed: Vec::new(),
204 chunks: 0,
205 };
206 let at_ms = SystemClock.now_ms();
207 for file in walked.files {
208 let ingest_hash = ingest_hash(&file.content_hash, settings);
209 let previous = vectors.source_hash(&settings.scope, &file.source).await?;
210 if previous.as_deref() == Some(ingest_hash.as_str()) {
211 report.skipped += 1;
212 continue;
213 }
214 let doc = Document {
215 scope: settings.scope.clone(),
216 source: file.source.clone(),
217 text: file.text,
218 at_ms,
219 origin: settings.origin,
220 meta: Default::default(),
221 };
222 let outcome = match document_records(embedder, &doc, &settings.chunk).await {
223 Ok(records) => vectors
224 .replace_source(&settings.scope, &file.source, records, &ingest_hash)
225 .await
226 .map_err(ContextError::from),
227 Err(e) => Err(e),
228 };
229 match outcome {
230 Ok(written) => {
231 report.chunks += written;
232 if previous.is_some() {
233 report.replaced += 1;
234 } else {
235 report.added += 1;
236 }
237 }
238 Err(e) => {
239 let error = e.to_string();
240 vectors
241 .record_failed_source(&settings.scope, &file.source, &error)
242 .await?;
243 report.failed.push((file.source, error));
244 }
245 }
246 }
247 for source in &gone {
248 if on_disk(dir, source) {
249 continue;
250 }
251 vectors.remove_source(&settings.scope, source).await?;
252 report.removed += 1;
253 }
254 let handled = report.added + report.replaced + report.skipped + report.failed.len();
255 assert!(
256 handled <= settings.load.max_files(),
257 "more files handled than the walk allows"
258 );
259 Ok(report)
260}
261
262fn ingest_hash(content_hash: &str, settings: &IngestSettings) -> String {
267 let max = settings.chunk.max_tokens.to_string();
268 let overlap = settings.chunk.overlap_tokens.to_string();
269 let hash = format!(
270 "{:016x}",
271 stable_hash(&[content_hash, settings.origin.as_str(), &max, &overlap])
272 );
273 assert_eq!(hash.len(), 16, "ingest hash is 16 hex chars");
274 hash
275}
276
277fn check_removals(
282 planned: usize,
283 stored: usize,
284 no_files: bool,
285 settings: &IngestSettings,
286) -> Result<(), ContextError> {
287 assert!(
288 planned <= stored,
289 "more removals planned than sources stored"
290 );
291 if settings.allow_remove_all || planned == 0 {
292 return Ok(());
293 }
294 let scope = &settings.scope;
295 if no_files {
296 return Err(ContextError::Invalid(format!(
297 "walk found no supported files but scope {scope} has {stored} sources; refusing to remove them all \
298 (check the folder, or set with_allow_remove_all(true))"
299 )));
300 }
301 let share = usize::from(settings.max_remove_share);
302 if planned * 100 > stored * share {
303 return Err(ContextError::Invalid(format!(
304 "refusing to remove {planned} of {stored} sources of scope {scope}, above max_remove_share {share}% \
305 (check the folder, or raise with_max_remove_share or set with_allow_remove_all(true))"
306 )));
307 }
308 Ok(())
309}
310
311fn on_disk(dir: &Path, source: &str) -> bool {
312 let relative = Path::new(source);
313 let plain = relative
314 .components()
315 .all(|c| matches!(c, std::path::Component::Normal(_)));
316 if !plain {
317 return false;
318 }
319 match std::fs::symlink_metadata(dir.join(relative)) {
320 Ok(_) => true,
321 Err(e) => e.kind() != std::io::ErrorKind::NotFound,
322 }
323}
324
325#[derive(Clone)]
330pub struct Knowledge {
331 pub(crate) dir: PathBuf,
332 pub(crate) index: String,
333 pub(crate) store: Option<PathBuf>,
334 pub(crate) embedder: Option<Arc<dyn Embedder>>,
335 pub(crate) on_device: bool,
336 #[cfg(feature = "local")]
337 pub(crate) local: Option<crate::local::LocalChoice>,
338 pub(crate) load: LoadSettings,
339 pub(crate) chunk: ChunkConfig,
340 pub(crate) allow_failed: bool,
341}
342
343impl Knowledge {
344 pub fn dir(dir: impl AsRef<Path>) -> Self {
348 let defaults = IngestSettings::default();
349 Knowledge {
350 dir: dir.as_ref().to_path_buf(),
351 index: defaults.scope().to_string(),
352 store: None,
353 embedder: None,
354 on_device: false,
355 #[cfg(feature = "local")]
356 local: None,
357 load: defaults.load().clone(),
358 chunk: defaults.chunk(),
359 allow_failed: false,
360 }
361 }
362
363 pub fn index(mut self, index: impl Into<String>) -> Self {
367 self.index = index.into();
368 self
369 }
370
371 pub fn store(mut self, path: impl AsRef<Path>) -> Self {
375 self.store = Some(path.as_ref().to_path_buf());
376 self
377 }
378
379 pub fn embedder(mut self, embedder: Arc<dyn Embedder>) -> Self {
384 self.embedder = Some(embedder);
385 self.on_device = false;
386 self.clear_local();
387 self
388 }
389
390 pub fn on_device_embedder(mut self, embedder: Arc<dyn Embedder>) -> Self {
394 self.embedder = Some(embedder);
395 self.on_device = true;
396 self.clear_local();
397 self
398 }
399
400 #[cfg(feature = "local")]
404 pub fn local_embedder(mut self, choice: impl Into<crate::local::LocalChoice>) -> Self {
405 self.embedder = None;
406 self.local = Some(choice.into());
407 self.on_device = true;
408 self
409 }
410
411 #[cfg(feature = "local")]
412 fn clear_local(&mut self) {
413 self.local = None;
414 }
415
416 #[cfg(not(feature = "local"))]
417 fn clear_local(&mut self) {}
418
419 pub fn load(mut self, load: LoadSettings) -> Self {
423 self.load = load;
424 self
425 }
426
427 pub fn chunk(mut self, chunk: ChunkConfig) -> Self {
431 self.chunk = chunk;
432 self
433 }
434}
435
436impl Knowledge {
437 pub fn allow_failed(mut self, allow: bool) -> Self {
441 self.allow_failed = allow;
442 self
443 }
444}
445
446impl From<&str> for Knowledge {
447 fn from(dir: &str) -> Self {
448 Knowledge::dir(dir)
449 }
450}
451
452impl From<&Path> for Knowledge {
453 fn from(dir: &Path) -> Self {
454 Knowledge::dir(dir)
455 }
456}
457
458impl From<PathBuf> for Knowledge {
459 fn from(dir: PathBuf) -> Self {
460 Knowledge::dir(dir)
461 }
462}
463
464impl fmt::Debug for Knowledge {
465 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
466 f.debug_struct("Knowledge")
467 .field("dir", &self.dir)
468 .field("index", &self.index)
469 .field("store", &self.store)
470 .field("embedder", &self.embedder.is_some())
471 .field("on_device", &self.on_device)
472 .field("allow_failed", &self.allow_failed)
473 .finish_non_exhaustive()
474 }
475}