Skip to main content

nvs_packer/
loader.rs

1use anyhow::{Context, Result};
2use serde::Deserialize;
3use serde_json::{Map as JsonMap, Value as JsonValue};
4use std::fs::File;
5use std::io::Read;
6use std::path::{Path, PathBuf};
7use xxhash_rust::xxh64::xxh64;
8
9#[derive(Deserialize)]
10pub struct InputDocRaw {
11    #[serde(default)]
12    pub id: Option<String>,
13    #[serde(default)]
14    pub text: Option<String>,
15    #[serde(default)]
16    pub content: Option<String>,
17    #[serde(default)]
18    pub metadata: Option<JsonValue>,
19}
20
21#[derive(Clone)]
22pub struct Doc {
23    pub id: String,
24    pub text: String,
25    pub embedding: Vec<f32>,
26    pub meta: Option<JsonMap<String, JsonValue>>,
27}
28
29pub fn extract_embedding_and_meta(
30    meta: JsonValue,
31) -> Option<(Vec<f32>, Option<JsonMap<String, JsonValue>>)> {
32    // metadata may be object with embedding field; remove it and return remaining
33    if let Some(mut m) = meta.as_object().cloned() {
34        if let Some(emb) = m.remove("embedding") {
35            if let Some(arr) = emb.as_array() {
36                let mut v = Vec::with_capacity(arr.len());
37                for x in arr {
38                    if let Some(f) = x.as_f64() {
39                        v.push(f as f32);
40                    } else if let Some(i) = x.as_i64() {
41                        v.push(i as f32);
42                    } else {
43                        return None;
44                    }
45                }
46                return Some((v, Some(m)));
47            }
48        }
49    }
50    None
51}
52
53pub fn build_doc_from_raw(r: InputDocRaw, idx_salt: Option<usize>) -> Option<Doc> {
54    let text = r.text.or(r.content).unwrap_or_default();
55    let mv = r.metadata?;
56    let (embedding, meta_other) = extract_embedding_and_meta(mv)?;
57    if embedding.is_empty() {
58        return None;
59    }
60    let id = r.id.unwrap_or_else(|| {
61        let mut h = xxh64(text.as_bytes(), 0);
62        if let Some(s) = idx_salt {
63            h ^= s as u64;
64        }
65        format!("doc-{h:016x}")
66    });
67    Some(Doc {
68        id,
69        text,
70        embedding,
71        meta: meta_other,
72    })
73}
74
75pub fn read_docs(input_dir: &Path) -> Result<(Vec<Doc>, Vec<(String, usize)>)> {
76    use walkdir::WalkDir;
77    let mut docs = Vec::new();
78    let mut receipts: Vec<(String, usize)> = Vec::new();
79    let pb = indicatif::ProgressBar::new_spinner();
80    pb.set_style(indicatif::ProgressStyle::with_template(
81        "{spinner:.green} {msg}",
82    )?);
83    pb.set_message("Scanning JSON files...");
84    let mut _total = 0usize;
85    let mut skipped = 0usize;
86    for entry in WalkDir::new(input_dir).into_iter().filter_map(|e| e.ok()) {
87        if entry.file_type().is_file()
88            && entry
89                .path()
90                .extension()
91                .map(|e| e == "json")
92                .unwrap_or(false)
93        {
94            let path = entry.path();
95            pb.set_message(format!("Reading {}", path.display()));
96            let mut s = String::new();
97            File::open(path)
98                .with_context(|| format!("open {}", path.display()))?
99                .read_to_string(&mut s)?;
100            if s.trim_start().starts_with('[') {
101                let before = docs.len();
102                let arr: Vec<serde_json::Value> = serde_json::from_str(&s)
103                    .with_context(|| format!("parse array in {}", path.display()))?;
104                for (i, v) in arr.into_iter().enumerate() {
105                    _total += 1;
106                    match serde_json::from_value::<InputDocRaw>(v) {
107                        Ok(r) => {
108                            if let Some(doc) = build_doc_from_raw(r, Some(i)) {
109                                docs.push(doc);
110                            } else {
111                                skipped += 1;
112                                eprintln!(
113                                    "{} skipping invalid/empty doc ({}:#{})",
114                                    console::style("! ").yellow(),
115                                    path.display(),
116                                    i
117                                );
118                            }
119                        }
120                        Err(e) => {
121                            skipped += 1;
122                            eprintln!(
123                                "{} skipping invalid doc ({}:#{}) — {}",
124                                console::style("! ").yellow(),
125                                path.display(),
126                                i,
127                                e
128                            );
129                        }
130                    }
131                }
132                let produced = docs.len() - before;
133                receipts.push((path.display().to_string(), produced));
134            } else {
135                _total += 1;
136                match serde_json::from_str::<InputDocRaw>(&s) {
137                    Ok(r) => {
138                        let fname = path.display().to_string();
139                        if let Some(doc) = build_doc_from_raw(r, None) {
140                            docs.push(doc);
141                            receipts.push((fname, 1));
142                        } else {
143                            skipped += 1;
144                            eprintln!(
145                                "{} skipping doc without embedding/metadata ({})",
146                                console::style("! ").yellow(),
147                                path.display()
148                            );
149                            receipts.push((fname, 0));
150                        }
151                    }
152                    Err(e) => {
153                        skipped += 1;
154                        eprintln!(
155                            "{} skipping invalid doc ({}) — {}",
156                            console::style("! ").yellow(),
157                            path.display(),
158                            e
159                        );
160                        receipts.push((path.display().to_string(), 0));
161                    }
162                }
163            }
164        }
165    }
166    pb.finish_with_message(format!("Loaded {} docs (skipped {})", docs.len(), skipped));
167    receipts.sort_by(|a, b| a.0.cmp(&b.0));
168    Ok((docs, receipts))
169}
170
171// Fast adaptive loader (moved largely as-is for behavior parity)
172pub fn read_docs_fast(
173    input_dir: &Path,
174    mmap_threshold: usize,
175) -> Result<(Vec<Doc>, Vec<(String, usize)>)> {
176    use crossbeam_channel as chan;
177    use memmap2::Mmap;
178    use serde::de::{self, Deserializer as _, SeqAccess, Visitor};
179    use std::thread;
180    use walkdir::WalkDir;
181
182    #[derive(Debug)]
183    enum Buf {
184        Mmap(Mmap),
185        Vec(Vec<u8>),
186    }
187    impl Buf {
188        fn as_slice(&self) -> &[u8] {
189            match self {
190                Buf::Mmap(m) => &m,
191                Buf::Vec(v) => v,
192            }
193        }
194    }
195    #[derive(Debug)]
196    struct Job {
197        _path: PathBuf,
198        buf: Buf,
199    }
200
201    let pb = indicatif::ProgressBar::new_spinner();
202    pb.set_style(indicatif::ProgressStyle::with_template(
203        "{spinner:.green} {msg}",
204    )?);
205    pb.set_message("Scanning JSON files (fast)...");
206
207    let (tx, rx) = chan::bounded::<Job>(64);
208    {
209        let tx = tx.clone();
210        let input_dir = input_dir.to_path_buf();
211        thread::spawn(move || {
212            for entry in WalkDir::new(&input_dir).into_iter().filter_map(|e| e.ok()) {
213                if !(entry.file_type().is_file()
214                    && entry
215                        .path()
216                        .extension()
217                        .map(|e| e == "json")
218                        .unwrap_or(false))
219                {
220                    continue;
221                }
222                let path = entry.path().to_path_buf();
223                let md = match std::fs::metadata(&path) {
224                    Ok(m) => m,
225                    Err(_) => continue,
226                };
227                let job = if md.len() as usize <= mmap_threshold {
228                    match File::open(&path).and_then(|f| {
229                        unsafe { Mmap::map(&f) }
230                            .map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, e))
231                    }) {
232                        Ok(m) => Job {
233                            _path: path,
234                            buf: Buf::Mmap(m),
235                        },
236                        Err(_) => match std::fs::read(&path) {
237                            Ok(v) => Job {
238                                _path: path,
239                                buf: Buf::Vec(v),
240                            },
241                            Err(_) => continue,
242                        },
243                    }
244                } else {
245                    match std::fs::read(&path) {
246                        Ok(v) => Job {
247                            _path: path,
248                            buf: Buf::Vec(v),
249                        },
250                        Err(_) => continue,
251                    }
252                };
253                if tx.send(job).is_err() {
254                    break;
255                }
256            }
257        });
258    }
259
260    let nthreads = thread::available_parallelism()
261        .map(|n| n.get())
262        .unwrap_or(4);
263    let mut handles = Vec::new();
264    for _ in 0..nthreads {
265        let rx = rx.clone();
266        handles.push(thread::spawn(
267            move || -> (Vec<Doc>, usize, Vec<(String, usize)>) {
268                let mut out: Vec<Doc> = Vec::with_capacity(1024);
269                let mut skipped: usize = 0;
270                let mut receipts: Vec<(String, usize)> = Vec::with_capacity(128);
271
272                while let Ok(job) = rx.recv() {
273                    let file_name = job._path.display().to_string();
274                    let bytes = job.buf.as_slice();
275                    let mut de = serde_json::Deserializer::from_slice(bytes);
276                    struct StreamVisitor<'a> {
277                        out: &'a mut Vec<Doc>,
278                        skipped: &'a mut usize,
279                    }
280                    impl<'de, 'a> Visitor<'de> for StreamVisitor<'a> {
281                        type Value = ();
282                        fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
283                            write!(f, "array or object of docs")
284                        }
285                        fn visit_seq<A>(self, mut seq: A) -> Result<(), A::Error>
286                        where
287                            A: SeqAccess<'de>,
288                        {
289                            while let Some(raw) = seq.next_element::<InputDocRaw>()? {
290                                if let Some((embedding, meta_other)) =
291                                    raw.metadata.and_then(extract_embedding_and_meta)
292                                {
293                                    let text = raw.text.or(raw.content).unwrap_or_default();
294                                    if !embedding.is_empty() {
295                                        let id = raw.id.unwrap_or_else(|| {
296                                            let h = xxh64(text.as_bytes(), 0);
297                                            format!("doc-{h:016x}")
298                                        });
299                                        self.out.push(Doc {
300                                            id,
301                                            text,
302                                            embedding,
303                                            meta: meta_other,
304                                        });
305                                    } else {
306                                        *self.skipped += 1;
307                                    }
308                                } else {
309                                    *self.skipped += 1;
310                                }
311                            }
312                            Ok(())
313                        }
314                        fn visit_map<M>(self, mut map: M) -> Result<(), M::Error>
315                        where
316                            M: de::MapAccess<'de>,
317                        {
318                            let mut id: Option<String> = None;
319                            let mut text: Option<String> = None;
320                            let mut content: Option<String> = None;
321                            let mut metadata: Option<serde_json::Value> = None;
322                            while let Some(k) = map.next_key::<String>()? {
323                                match k.as_str() {
324                                    "id" => {
325                                        id = map.next_value()?;
326                                    }
327                                    "text" => {
328                                        text = map.next_value()?;
329                                    }
330                                    "content" => {
331                                        content = map.next_value()?;
332                                    }
333                                    "metadata" => {
334                                        metadata = map.next_value()?;
335                                    }
336                                    _ => {
337                                        let _: serde_json::Value = map.next_value()?;
338                                    }
339                                }
340                            }
341                            if let Some((embedding, meta_other)) =
342                                metadata.and_then(extract_embedding_and_meta)
343                            {
344                                let the_text = text.or(content).unwrap_or_default();
345                                if !embedding.is_empty() {
346                                    let the_id = id.unwrap_or_else(|| {
347                                        let h = xxh64(the_text.as_bytes(), 0);
348                                        format!("doc-{h:016x}")
349                                    });
350                                    self.out.push(Doc {
351                                        id: the_id,
352                                        text: the_text,
353                                        embedding,
354                                        meta: meta_other,
355                                    });
356                                } else {
357                                    *self.skipped += 1;
358                                }
359                            } else {
360                                *self.skipped += 1;
361                            }
362                            Ok(())
363                        }
364                    }
365
366                    let res = de.deserialize_any(StreamVisitor {
367                        out: &mut out,
368                        skipped: &mut skipped,
369                    });
370                    if res.is_err() {
371                        // fallback: try single object
372                        match serde_json::from_slice::<InputDocRaw>(bytes) {
373                            Ok(r) => {
374                                if let Some(doc) = build_doc_from_raw(r, None) {
375                                    out.push(doc);
376                                    receipts.push((file_name, 1));
377                                } else {
378                                    receipts.push((file_name, 0));
379                                }
380                            }
381                            Err(_) => {
382                                receipts.push((file_name, 0));
383                            }
384                        }
385                    } else {
386                        let produced = out.len();
387                        receipts.push((file_name, produced));
388                    }
389                }
390                (out, skipped, receipts)
391            },
392        ));
393    }
394
395    drop(tx);
396    let mut docs = Vec::new();
397    let mut skipped_total = 0usize;
398    let mut receipts_all: Vec<(String, usize)> = Vec::new();
399    for h in handles {
400        let (mut d, s, mut r) = h.join().unwrap();
401        docs.append(&mut d);
402        skipped_total += s;
403        receipts_all.append(&mut r);
404    }
405    pb.finish_with_message(format!(
406        "Loaded {} docs (skipped {})",
407        docs.len(),
408        skipped_total
409    ));
410    receipts_all.sort_by(|a, b| a.0.cmp(&b.0));
411    Ok((docs, receipts_all))
412}
413
414#[cfg(test)]
415mod tests {
416    use super::*;
417    use std::fs;
418    use std::io::Write;
419
420    fn make_tmp(prefix: &str) -> PathBuf {
421        let mut p = std::env::temp_dir();
422        let t = std::time::SystemTime::now()
423            .duration_since(std::time::UNIX_EPOCH)
424            .unwrap()
425            .as_nanos();
426        p.push(format!("nvs_packer_test_{}_{}", prefix, t));
427        fs::create_dir_all(&p).unwrap();
428        p
429    }
430
431    #[test]
432    fn extract_embedding_and_meta_ok() {
433        let meta = serde_json::json!({
434            "embedding": [1.0, 2.5, 3.0],
435            "author": "alice",
436            "tags": ["x"]
437        });
438        let (emb, rest) = extract_embedding_and_meta(meta).expect("should parse");
439        assert_eq!(emb, vec![1.0, 2.5, 3.0]);
440        let rest = rest.unwrap();
441        assert_eq!(rest.get("author").unwrap(), &serde_json::json!("alice"));
442        assert!(rest.get("embedding").is_none());
443    }
444
445    #[test]
446    fn build_doc_from_raw_id_and_meta() {
447        let raw = InputDocRaw {
448            id: None,
449            text: Some("Hello world".into()),
450            content: None,
451            metadata: Some(serde_json::json!({ "embedding": [0.1, 0.2] , "x": 1 })),
452        };
453        let doc = build_doc_from_raw(raw, None).expect("doc");
454        // id is doc-<xxh64(text)>
455        let h = xxh64("Hello world".as_bytes(), 0);
456        assert_eq!(doc.id, format!("doc-{h:016x}"));
457        assert_eq!(doc.embedding, vec![0.1, 0.2]);
458        assert_eq!(doc.meta.unwrap().get("x").unwrap(), &serde_json::json!(1));
459    }
460
461    #[test]
462    fn read_docs_single_and_array() {
463        let dir = make_tmp("loader");
464        // single object
465        let mut f1 = File::create(dir.join("one.json")).unwrap();
466        write!(
467            f1,
468            "{}",
469            serde_json::json!({
470                "text": "A", "metadata": {"embedding": [1,2,3], "lang": "en"}
471            })
472        )
473        .unwrap();
474
475        // array with one valid and one invalid
476        let mut f2 = File::create(dir.join("arr.json")).unwrap();
477        write!(
478            f2,
479            "{}",
480            serde_json::json!([
481                {"text": "B", "metadata": {"embedding": [0.0] }},
482                {"text": "C", "metadata": {"no_embedding": true }}
483            ])
484        )
485        .unwrap();
486
487        let (docs, receipts) = read_docs(&dir).expect("read");
488        // Should load 2 docs (A, B)
489        assert_eq!(docs.len(), 2);
490        // Receipts contain entries for both files
491        let names: Vec<_> = receipts.iter().map(|(n, _)| n.clone()).collect();
492        assert!(names.iter().any(|n| n.ends_with("one.json")));
493        assert!(names.iter().any(|n| n.ends_with("arr.json")));
494
495        // cleanup
496        let _ = fs::remove_dir_all(&dir);
497    }
498}