use std::collections::HashSet;
use std::future::Future;
use super::prompt::classification_prompt;
pub use super::prompt::ClassificationTarget;
use crate::classify::semantic::SemanticType;
use crate::error::Result;
pub const MAX_COLUMNS_PER_REQUEST: usize = 150;
pub const MAX_ROUNDS: usize = 3;
pub async fn classify_columns<F, Fut>(
ddl: &str,
targets: &[ClassificationTarget],
mut ask: F,
) -> Result<String>
where
F: FnMut(String) -> Fut,
Fut: Future<Output = Result<String>>,
{
let mut rows = Vec::new();
let mut pending: Vec<&ClassificationTarget> = targets.iter().collect();
for _ in 0..MAX_ROUNDS {
if pending.is_empty() {
break;
}
let mut answered: HashSet<(String, String)> = HashSet::new();
for batch in pending.chunks(MAX_COLUMNS_PER_REQUEST) {
let batch: Vec<ClassificationTarget> = batch.iter().map(|t| (*t).clone()).collect();
let response = ask(classification_prompt(ddl, &batch)).await?;
let returned = super::parse::raw_rows(&response).unwrap_or_else(|err| {
tracing::debug!("Ignoring unreadable LLM response: {err}");
Vec::new()
});
for row in returned {
let key = (
row["table"].as_str().unwrap_or_default().to_owned(),
row["column"].as_str().unwrap_or_default().to_owned(),
);
let requested = batch.iter().any(|t| t.table == key.0 && t.column == key.1);
let known =
serde_json::from_value::<SemanticType>(row["semantic_type"].clone()).is_ok();
if requested && known && answered.insert(key) {
rows.push(row);
}
}
}
pending.retain(|t| !answered.contains(&(t.table.clone(), t.column.clone())));
}
if !pending.is_empty() {
tracing::warn!(
"The LLM did not classify {} of {} columns",
pending.len(),
targets.len()
);
}
Ok(serde_json::json!({ "classifications": rows }).to_string())
}
#[cfg(test)]
mod tests {
use super::*;
use std::cell::RefCell;
fn targets(n: usize) -> Vec<ClassificationTarget> {
(0..n)
.map(|i| ClassificationTarget::new("items", &format!("c{i}"), "TEXT"))
.collect()
}
fn row(column: &str) -> serde_json::Value {
serde_json::json!({"table": "items", "column": column, "semantic_type": "Sku", "confidence": 0.9})
}
fn answer(prompt: &str, skip: &[&str]) -> String {
let rows: Vec<_> = prompt
.lines()
.filter_map(|l| l.strip_prefix("- items."))
.map(|l| l.split(' ').next().unwrap())
.filter(|c| !skip.contains(c))
.map(row)
.collect();
serde_json::json!({"classifications": rows}).to_string()
}
fn columns(response: &str) -> Vec<String> {
let parsed: serde_json::Value = serde_json::from_str(response).unwrap();
let mut found: Vec<String> = parsed["classifications"]
.as_array()
.unwrap()
.iter()
.map(|r| r["column"].as_str().unwrap().to_owned())
.collect();
found.sort();
found
}
#[tokio::test]
async fn omitted_columns_are_requested_again() {
let prompts = RefCell::new(Vec::new());
let response = classify_columns("DDL", &targets(3), |prompt| {
let first = prompts.borrow().is_empty();
prompts.borrow_mut().push(prompt.clone());
let reply = answer(&prompt, if first { &["c1", "c2"] } else { &[] });
async move { Ok(reply) }
})
.await
.unwrap();
assert_eq!(columns(&response), ["c0", "c1", "c2"]);
let prompts = prompts.into_inner();
assert_eq!(prompts.len(), 2);
assert!(!prompts[1].contains("- items.c0 ") && prompts[1].contains("- items.c2 "));
}
#[tokio::test]
async fn large_target_lists_are_split_into_batches() {
let sizes = RefCell::new(Vec::new());
let response = classify_columns("DDL", &targets(MAX_COLUMNS_PER_REQUEST + 10), |prompt| {
sizes
.borrow_mut()
.push(prompt.lines().filter(|l| l.starts_with("- items.")).count());
let reply = answer(&prompt, &[]);
async move { Ok(reply) }
})
.await
.unwrap();
assert_eq!(sizes.into_inner(), [MAX_COLUMNS_PER_REQUEST, 10]);
assert_eq!(columns(&response).len(), MAX_COLUMNS_PER_REQUEST + 10);
}
#[tokio::test]
async fn unrequested_rows_are_dropped_and_rounds_are_bounded() {
let calls = RefCell::new(0);
let response = classify_columns("DDL", &targets(2), |_| {
*calls.borrow_mut() += 1;
let reply =
serde_json::json!({"classifications": [row("c0"), row("other")]}).to_string();
async move { Ok(reply) }
})
.await
.unwrap();
assert_eq!(columns(&response), ["c0"]);
assert_eq!(calls.into_inner(), MAX_ROUNDS);
}
#[tokio::test]
async fn rows_with_unknown_semantic_types_are_requested_again() {
let calls = RefCell::new(0);
let response = classify_columns("DDL", &targets(1), |_| {
*calls.borrow_mut() += 1;
let semantic = if *calls.borrow() == 1 {
"ProductCode"
} else {
"Sku"
};
let reply = serde_json::json!({"classifications": [
{"table": "items", "column": "c0", "semantic_type": semantic, "confidence": 0.9}
]})
.to_string();
async move { Ok(reply) }
})
.await
.unwrap();
assert_eq!(calls.into_inner(), 2);
assert!(response.contains("\"Sku\"") && !response.contains("ProductCode"));
}
#[tokio::test]
async fn nothing_to_classify_makes_no_request() {
let response = classify_columns("DDL", &[], |_| async {
Err(crate::error::SeedKitError::Other(
"no request expected".into(),
))
})
.await
.unwrap();
assert!(columns(&response).is_empty());
}
}