seedkit-core 2.1.1

Core library for SeedKit — realistic database seed data generation
Documentation
//! # Column Classification Requests
//!
//! Asks the LLM about the columns the rule engine left `Unknown`, in batches,
//! and asks again for any listed column an answer leaves out. In testing, a
//! model sometimes closed the result array after one column; the per-column
//! check keeps that from silently dropping classifications.

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;

/// Columns per request. 150 columns took Claude Opus 5.5 about 6,300 output
/// tokens (well under the 16,000 limit) and 45 seconds.
pub const MAX_COLUMNS_PER_REQUEST: usize = 150;

/// The first request plus up to two follow-ups for omitted columns.
pub const MAX_ROUNDS: usize = 3;

/// Classify `targets`, calling `ask` with each prompt. Returns
/// `{"classifications": [...]}` with at most one row per target; rows for
/// columns that were not requested are dropped.
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?;
            // An unreadable answer counts as answering nothing; the columns
            // are requested again in the next round.
            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);
                // A type SeedKit does not have leaves the column unanswered.
                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})
    }

    /// Answers each prompt with the listed columns, minus any in `skip`.
    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());
            // The first answer stops after one column, as observed live.
            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;
            // Never answers c1, and adds a column nobody asked about.
            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() {
        // Gemini's schema cannot enumerate the types, so a row may name one
        // SeedKit does not have.
        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());
    }
}