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 pub(crate) allow_remove_all: bool,
342}
343
344impl Knowledge {
345 pub fn dir(dir: impl AsRef<Path>) -> Self {
349 let defaults = IngestSettings::default();
350 Knowledge {
351 dir: dir.as_ref().to_path_buf(),
352 index: defaults.scope().to_string(),
353 store: None,
354 embedder: None,
355 on_device: false,
356 #[cfg(feature = "local")]
357 local: None,
358 load: defaults.load().clone(),
359 chunk: defaults.chunk(),
360 allow_failed: false,
361 allow_remove_all: defaults.allow_remove_all(),
362 }
363 }
364
365 pub fn index(mut self, index: impl Into<String>) -> Self {
369 self.index = index.into();
370 self
371 }
372
373 pub fn store(mut self, path: impl AsRef<Path>) -> Self {
377 self.store = Some(path.as_ref().to_path_buf());
378 self
379 }
380
381 pub fn embedder(mut self, embedder: Arc<dyn Embedder>) -> Self {
386 self.embedder = Some(embedder);
387 self.on_device = false;
388 self.clear_local();
389 self
390 }
391
392 pub fn on_device_embedder(mut self, embedder: Arc<dyn Embedder>) -> Self {
396 self.embedder = Some(embedder);
397 self.on_device = true;
398 self.clear_local();
399 self
400 }
401
402 #[cfg(feature = "local")]
406 pub fn local_embedder(mut self, choice: impl Into<crate::local::LocalChoice>) -> Self {
407 self.embedder = None;
408 self.local = Some(choice.into());
409 self.on_device = true;
410 self
411 }
412
413 #[cfg(feature = "local")]
414 fn clear_local(&mut self) {
415 self.local = None;
416 }
417
418 #[cfg(not(feature = "local"))]
419 fn clear_local(&mut self) {}
420
421 pub fn load(mut self, load: LoadSettings) -> Self {
425 self.load = load;
426 self
427 }
428
429 pub fn chunk(mut self, chunk: ChunkConfig) -> Self {
433 self.chunk = chunk;
434 self
435 }
436}
437
438impl Knowledge {
439 pub fn allow_failed(mut self, allow: bool) -> Self {
443 self.allow_failed = allow;
444 self
445 }
446
447 pub fn allow_remove_all(mut self, allow: bool) -> Self {
451 self.allow_remove_all = allow;
452 self
453 }
454}
455
456impl From<&str> for Knowledge {
457 fn from(dir: &str) -> Self {
458 Knowledge::dir(dir)
459 }
460}
461
462impl From<&Path> for Knowledge {
463 fn from(dir: &Path) -> Self {
464 Knowledge::dir(dir)
465 }
466}
467
468impl From<PathBuf> for Knowledge {
469 fn from(dir: PathBuf) -> Self {
470 Knowledge::dir(dir)
471 }
472}
473
474impl fmt::Debug for Knowledge {
475 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
476 f.debug_struct("Knowledge")
477 .field("dir", &self.dir)
478 .field("index", &self.index)
479 .field("store", &self.store)
480 .field("embedder", &self.embedder.is_some())
481 .field("on_device", &self.on_device)
482 .field("allow_failed", &self.allow_failed)
483 .field("allow_remove_all", &self.allow_remove_all)
484 .finish_non_exhaustive()
485 }
486}