use std::sync::Arc;
use greentic_aw_runtime::knowledge::KnowledgeChunk;
use serde::Deserialize;
use crate::pack::PackRuntime;
const CORPUS_SIDECAR: &str = "knowledge_corpus.json";
const CHUNK_CHARS: usize = 1500;
const CHUNK_OVERLAP_CHARS: usize = 200;
#[derive(Debug, Clone, Copy)]
pub(crate) struct EmbeddingExpectation<'a> {
pub model: &'a str,
pub dim: usize,
}
#[derive(Debug, Deserialize)]
struct CorpusAnnotation {
#[serde(default)]
files: Vec<CorpusFile>,
}
#[derive(Debug, Deserialize)]
struct CorpusFile {
asset_path: String,
#[serde(default)]
original_name: String,
#[serde(default)]
vectors_asset_path: Option<String>,
}
#[derive(Debug, Deserialize)]
struct VectorsAsset {
#[serde(default)]
embedding_model: String,
#[serde(default)]
dims: usize,
#[serde(default)]
chunks: Vec<VectorChunk>,
}
#[derive(Debug, Deserialize)]
struct VectorChunk {
#[serde(default)]
chunk_index: usize,
#[serde(default)]
chunk_text: String,
#[serde(default)]
vector: Vec<f32>,
}
pub(crate) fn collect(
packs: &[Arc<PackRuntime>],
expected: Option<EmbeddingExpectation<'_>>,
) -> Vec<KnowledgeChunk> {
let mut chunks = Vec::new();
for pack in packs {
let Some(bytes) = pack.read_pack_file(CORPUS_SIDECAR) else {
continue;
};
let pack_id = pack.metadata().pack_id.clone();
let annotation: CorpusAnnotation = match serde_json::from_slice(&bytes) {
Ok(annotation) => annotation,
Err(error) => {
tracing::warn!(pack_id = %pack_id, error = %error, "knowledge: malformed knowledge_corpus.json; skipping pack corpus");
continue;
}
};
for file in &annotation.files {
collect_file(&mut chunks, &pack_id, file, expected, &|name| {
pack.read_pack_file(name)
});
}
}
chunks
}
fn precomputed_rejection(
asset: &VectorsAsset,
expected: EmbeddingExpectation<'_>,
) -> Option<String> {
if asset.embedding_model != expected.model {
return Some(format!(
"built with model {:?} but the runner is configured for {}",
asset.embedding_model, expected.model
));
}
let mismatched = asset
.chunks
.iter()
.find(|chunk| chunk.vector.len() != expected.dim)?;
Some(format!(
"chunk_index {} has dimension {} but the runner's embedder produces {}",
mismatched.chunk_index,
mismatched.vector.len(),
expected.dim
))
}
fn collect_file<R: Fn(&str) -> Option<Vec<u8>>>(
out: &mut Vec<KnowledgeChunk>,
pack_id: &str,
file: &CorpusFile,
expected: Option<EmbeddingExpectation<'_>>,
read: &R,
) {
let doc_id = if file.original_name.is_empty() {
file.asset_path.clone()
} else {
file.original_name.clone()
};
if let Some(vec_path) = file.vectors_asset_path.as_deref() {
match load_vectors(read, pack_id, vec_path) {
Some(asset) if !asset.chunks.is_empty() => {
match expected.and_then(|expected| precomputed_rejection(&asset, expected)) {
None => {
append_vector_chunks(out, pack_id, &file.asset_path, &doc_id, asset);
return;
}
Some(reason) => tracing::warn!(
pack_id = %pack_id,
vectors_asset = %vec_path,
fallback_asset = %file.asset_path,
%reason,
"knowledge: precomputed vectors do not match the configured embedder; \
falling back to text re-chunk"
),
}
}
_ => {
tracing::warn!(
pack_id = %pack_id,
vectors_asset = %vec_path,
fallback_asset = %file.asset_path,
"knowledge: precomputed vectors asset unusable; falling back to text re-chunk"
);
}
}
}
let Some(raw) = read(&file.asset_path) else {
tracing::warn!(pack_id = %pack_id, asset = %file.asset_path, "knowledge: corpus asset missing from pack; skipping");
return;
};
let text = match String::from_utf8(raw) {
Ok(text) => text,
Err(_) => {
tracing::warn!(pack_id = %pack_id, asset = %file.asset_path, "knowledge: corpus asset is not UTF-8; skipping");
return;
}
};
append_chunks(out, pack_id, &file.asset_path, &doc_id, &text);
}
fn load_vectors<R: Fn(&str) -> Option<Vec<u8>>>(
read: &R,
pack_id: &str,
vec_path: &str,
) -> Option<VectorsAsset> {
let bytes = read(vec_path)?;
match serde_json::from_slice::<VectorsAsset>(&bytes) {
Ok(asset) => {
tracing::debug!(
pack_id = %pack_id,
vectors_asset = %vec_path,
embedding_model = %asset.embedding_model,
dims = asset.dims,
chunks = asset.chunks.len(),
"knowledge: loaded precomputed vectors asset"
);
Some(asset)
}
Err(error) => {
tracing::warn!(
pack_id = %pack_id,
vectors_asset = %vec_path,
error = %error,
"knowledge: failed to parse precomputed vectors asset"
);
None
}
}
}
fn append_vector_chunks(
out: &mut Vec<KnowledgeChunk>,
pack_id: &str,
asset_path: &str,
doc_id: &str,
asset: VectorsAsset,
) {
for chunk in asset.chunks {
let mut metadata = serde_json::Map::new();
metadata.insert("pack_id".into(), pack_id.into());
metadata.insert("asset_path".into(), asset_path.into());
out.push(KnowledgeChunk {
doc_id: doc_id.to_string(),
chunk_index: chunk.chunk_index,
text: chunk.chunk_text,
metadata,
embedding: Some(chunk.vector),
});
}
}
fn append_chunks(
out: &mut Vec<KnowledgeChunk>,
pack_id: &str,
asset_path: &str,
doc_id: &str,
text: &str,
) {
if text.trim().is_empty() {
return;
}
let chars: Vec<char> = text.chars().collect();
let step = CHUNK_CHARS.saturating_sub(CHUNK_OVERLAP_CHARS).max(1);
let mut start = 0;
let mut chunk_index = 0;
while start < chars.len() {
let end = (start + CHUNK_CHARS).min(chars.len());
let window: String = chars[start..end].iter().collect();
if !window.trim().is_empty() {
let mut metadata = serde_json::Map::new();
metadata.insert("pack_id".into(), pack_id.into());
metadata.insert("asset_path".into(), asset_path.into());
out.push(KnowledgeChunk {
doc_id: doc_id.to_string(),
chunk_index,
text: window,
metadata,
embedding: None,
});
chunk_index += 1;
}
if end == chars.len() {
break;
}
start += step;
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn short_text_is_a_single_chunk() {
let mut out = Vec::new();
append_chunks(
&mut out,
"p",
"assets/knowledge/a.txt",
"a.txt",
"hello world",
);
assert_eq!(out.len(), 1);
assert_eq!(out[0].doc_id, "a.txt");
assert_eq!(out[0].chunk_index, 0);
assert_eq!(out[0].text, "hello world");
assert_eq!(
out[0].metadata.get("asset_path").and_then(|v| v.as_str()),
Some("assets/knowledge/a.txt")
);
}
#[test]
fn long_text_windows_with_overlap_and_sequential_indices() {
let text = "x".repeat(CHUNK_CHARS * 2 + 100);
let mut out = Vec::new();
append_chunks(&mut out, "p", "a", "doc", &text);
assert!(
out.len() >= 3,
"expected multiple windows, got {}",
out.len()
);
for (i, c) in out.iter().enumerate() {
assert_eq!(c.chunk_index, i, "chunk indices must be sequential");
assert!(c.text.chars().count() <= CHUNK_CHARS);
}
}
#[test]
fn whitespace_only_text_produces_no_chunks() {
let mut out = Vec::new();
append_chunks(&mut out, "p", "a", "doc", " \n\t ");
assert!(out.is_empty());
}
fn corpus_file(
asset_path: &str,
original_name: &str,
vectors_asset_path: Option<&str>,
) -> CorpusFile {
CorpusFile {
asset_path: asset_path.to_string(),
original_name: original_name.to_string(),
vectors_asset_path: vectors_asset_path.map(str::to_string),
}
}
fn matching_expectation() -> EmbeddingExpectation<'static> {
EmbeddingExpectation {
model: "text-embedding-3-small",
dim: 3,
}
}
fn vectors_asset_bytes(model: &str, dims: usize, vector: Vec<f32>) -> Vec<u8> {
serde_json::to_vec(&serde_json::json!({
"embedding_model": model,
"dims": dims,
"chunks": [
{ "chunk_index": 0, "chunk_text": "first chunk", "vector": vector }
]
}))
.unwrap()
}
fn read_pair(vec_bytes: Vec<u8>) -> impl Fn(&str) -> Option<Vec<u8>> {
move |name: &str| match name {
"assets/knowledge/a.vec.json" => Some(vec_bytes.clone()),
"assets/knowledge/a.txt" => Some(b"hello world".to_vec()),
_ => None,
}
}
fn vectored_file() -> CorpusFile {
corpus_file(
"assets/knowledge/a.txt",
"a.txt",
Some("assets/knowledge/a.vec.json"),
)
}
#[test]
fn model_mismatch_falls_back_to_text_rechunk() {
let read = read_pair(vectors_asset_bytes(
"text-embedding-ada-002",
3,
vec![0.5, 0.25, 0.125],
));
let mut out = Vec::new();
collect_file(
&mut out,
"p",
&vectored_file(),
Some(matching_expectation()),
&read,
);
assert_eq!(out.len(), 1, "must re-chunk the text instead");
assert_eq!(out[0].text, "hello world");
assert_eq!(
out[0].embedding, None,
"the foreign-model vector must be dropped so the backend re-embeds"
);
}
#[test]
fn dim_mismatch_falls_back_to_text_rechunk() {
let read = read_pair(vectors_asset_bytes(
"text-embedding-3-small",
1536,
vec![0.5; 1536],
));
let mut out = Vec::new();
collect_file(
&mut out,
"p",
&vectored_file(),
Some(matching_expectation()),
&read,
);
assert_eq!(out.len(), 1, "the document must survive as re-chunked text");
assert_eq!(out[0].text, "hello world");
assert_eq!(
out[0].embedding, None,
"the wrong-width vector must be dropped so the backend re-embeds"
);
}
#[test]
fn blank_model_falls_back_to_text_rechunk() {
let read = read_pair(vectors_asset_bytes("", 3, vec![0.5, 0.25, 0.125]));
let mut out = Vec::new();
collect_file(
&mut out,
"p",
&vectored_file(),
Some(matching_expectation()),
&read,
);
assert_eq!(out.len(), 1);
assert_eq!(
out[0].embedding, None,
"unverifiable provenance must not be trusted"
);
}
#[test]
fn one_wrong_width_chunk_rejects_the_whole_asset() {
let vec_bytes = serde_json::to_vec(&serde_json::json!({
"embedding_model": "text-embedding-3-small",
"dims": 3,
"chunks": [
{ "chunk_index": 0, "chunk_text": "good", "vector": [0.5, 0.25, 0.125] },
{ "chunk_index": 1, "chunk_text": "bad", "vector": [0.5, 0.25] }
]
}))
.unwrap();
let read = read_pair(vec_bytes);
let mut out = Vec::new();
collect_file(
&mut out,
"p",
&vectored_file(),
Some(matching_expectation()),
&read,
);
assert_eq!(
out.len(),
1,
"must re-chunk the text, not emit the one good precomputed chunk"
);
assert_eq!(out[0].text, "hello world");
assert_eq!(out[0].embedding, None);
}
#[test]
fn wrong_dims_claim_with_correct_vectors_is_accepted() {
let read = read_pair(vectors_asset_bytes(
"text-embedding-3-small",
999,
vec![0.5, 0.25, 0.125],
));
let mut out = Vec::new();
collect_file(
&mut out,
"p",
&vectored_file(),
Some(matching_expectation()),
&read,
);
assert_eq!(out.len(), 1);
assert_eq!(out[0].embedding, Some(vec![0.5, 0.25, 0.125]));
}
#[test]
fn no_expectation_accepts_precomputed_verbatim() {
let read = read_pair(vectors_asset_bytes(
"some-other-model",
3,
vec![0.5, 0.25, 0.125],
));
let mut out = Vec::new();
collect_file(&mut out, "p", &vectored_file(), None, &read);
assert_eq!(out.len(), 1);
assert_eq!(out[0].embedding, Some(vec![0.5, 0.25, 0.125]));
}
#[test]
fn vectors_asset_emits_precomputed_chunks_without_rechunking() {
let vec_json = serde_json::json!({
"embedding_model": "text-embedding-3-small",
"dims": 3,
"chunks": [
{ "chunk_index": 0, "chunk_text": "first chunk", "vector": [0.5, 0.25, 0.125] },
{ "chunk_index": 1, "chunk_text": "second chunk", "vector": [1.0, -2.0, 0.75] }
]
});
let vec_bytes = serde_json::to_vec(&vec_json).unwrap();
let long_txt = "z".repeat(CHUNK_CHARS * 3).into_bytes();
let read = |name: &str| -> Option<Vec<u8>> {
match name {
"assets/knowledge/faq.vec.json" => Some(vec_bytes.clone()),
"assets/knowledge/faq.txt" => Some(long_txt.clone()),
_ => None,
}
};
let file = corpus_file(
"assets/knowledge/faq.txt",
"faq.pdf",
Some("assets/knowledge/faq.vec.json"),
);
let mut out = Vec::new();
collect_file(
&mut out,
"pack-1",
&file,
Some(matching_expectation()),
&read,
);
assert_eq!(
out.len(),
2,
"must emit exactly the 2 precomputed chunks, not re-chunk the .txt"
);
assert_eq!(out[0].doc_id, "faq.pdf");
assert_eq!(out[0].chunk_index, 0);
assert_eq!(out[0].text, "first chunk");
assert_eq!(out[0].embedding, Some(vec![0.5, 0.25, 0.125]));
assert_eq!(out[1].chunk_index, 1);
assert_eq!(out[1].text, "second chunk");
assert_eq!(out[1].embedding, Some(vec![1.0, -2.0, 0.75]));
assert_eq!(
out[0].metadata.get("pack_id").and_then(|v| v.as_str()),
Some("pack-1")
);
assert_eq!(
out[0].metadata.get("asset_path").and_then(|v| v.as_str()),
Some("assets/knowledge/faq.txt")
);
}
#[test]
fn no_vectors_asset_path_rechunks_with_no_embedding() {
let read = |name: &str| -> Option<Vec<u8>> {
(name == "assets/knowledge/a.txt").then(|| b"hello world".to_vec())
};
let file = corpus_file("assets/knowledge/a.txt", "a.txt", None);
let mut out = Vec::new();
collect_file(&mut out, "p", &file, Some(matching_expectation()), &read);
assert_eq!(out.len(), 1);
assert_eq!(out[0].doc_id, "a.txt");
assert_eq!(out[0].text, "hello world");
assert_eq!(
out[0].embedding, None,
"no vectors asset => backend embeds at ingest"
);
}
#[test]
fn missing_vectors_asset_falls_back_to_text_rechunk() {
let read = |name: &str| -> Option<Vec<u8>> {
(name == "assets/knowledge/a.txt").then(|| b"hello world".to_vec())
};
let file = corpus_file(
"assets/knowledge/a.txt",
"a.txt",
Some("assets/knowledge/a.vec.json"),
);
let mut out = Vec::new();
collect_file(&mut out, "p", &file, Some(matching_expectation()), &read);
assert_eq!(out.len(), 1, "must not panic; falls back to text re-chunk");
assert_eq!(out[0].text, "hello world");
assert_eq!(out[0].embedding, None);
}
#[test]
fn corrupt_vectors_asset_falls_back_to_text_rechunk() {
let read = |name: &str| -> Option<Vec<u8>> {
match name {
"assets/knowledge/a.vec.json" => Some(b"{ not valid json".to_vec()),
"assets/knowledge/a.txt" => Some(b"hello world".to_vec()),
_ => None,
}
};
let file = corpus_file(
"assets/knowledge/a.txt",
"a.txt",
Some("assets/knowledge/a.vec.json"),
);
let mut out = Vec::new();
collect_file(&mut out, "p", &file, Some(matching_expectation()), &read);
assert_eq!(
out.len(),
1,
"corrupt vectors asset must fall back, not panic"
);
assert_eq!(out[0].text, "hello world");
assert_eq!(out[0].embedding, None);
}
#[test]
fn empty_vectors_asset_falls_back_to_text_rechunk() {
let vec_json = serde_json::json!({
"embedding_model": "text-embedding-3-small",
"dims": 3,
"chunks": []
});
let vec_bytes = serde_json::to_vec(&vec_json).unwrap();
let read = |name: &str| -> Option<Vec<u8>> {
match name {
"assets/knowledge/a.vec.json" => Some(vec_bytes.clone()),
"assets/knowledge/a.txt" => Some(b"hello world".to_vec()),
_ => None,
}
};
let file = corpus_file(
"assets/knowledge/a.txt",
"a.txt",
Some("assets/knowledge/a.vec.json"),
);
let mut out = Vec::new();
collect_file(&mut out, "p", &file, Some(matching_expectation()), &read);
assert_eq!(
out.len(),
1,
"empty chunk list must fall back to text re-chunk"
);
assert_eq!(out[0].embedding, None);
}
#[test]
fn multibyte_text_does_not_panic_and_preserves_codepoints() {
let text = "café☕".repeat(CHUNK_CHARS);
let mut out = Vec::new();
append_chunks(&mut out, "p", "a", "doc", &text);
assert!(!out.is_empty());
let rejoined: String = out.iter().map(|c| c.text.as_str()).collect();
assert!(rejoined.contains("café☕"));
}
}