seedkit-core 2.1.1

Core library for SeedKit — realistic database seed data generation
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
//! # LLM Response Parser
//!
//! Parses JSON classification responses from Claude or OpenAI and merges
//! them with the rule-based classification results. The merge strategy is
//! conservative: LLM overrides only apply to columns that the rule engine
//! classified as `Unknown`.

use std::collections::BTreeMap;

use serde::Deserialize;

use super::truncate;
use crate::classify::semantic::SemanticType;
use crate::error::{Result, SeedKitError};

/// A single column classification from the LLM response.
#[derive(Debug, Deserialize)]
struct LlmClassification {
    table: String,
    column: String,
    semantic_type: SemanticType,
    #[serde(default)]
    confidence: f64,
}

/// Parse the LLM's JSON response into a list of classifications.
///
/// Uses a two-stage deserialization strategy:
/// 1. Parse the JSON string into a `Vec<serde_json::Value>` (untyped).
/// 2. Attempt to parse each element individually into `LlmClassification`.
///
/// This "firebreak" ensures that a single hallucinated `semantic_type`
/// (e.g., `"UserEmail"` instead of `"Email"`) only drops that one row
/// instead of nuking the entire array.
fn parse_llm_response(response: &str) -> Result<Vec<LlmClassification>> {
    let raw_array = raw_rows(response)?;

    // Stage 2: Parse each object individually, dropping invalid rows
    let mut classifications = Vec::new();
    for raw_obj in raw_array {
        match serde_json::from_value::<LlmClassification>(raw_obj.clone()) {
            Ok(valid) => classifications.push(valid),
            Err(e) => {
                tracing::debug!(
                    "Dropped invalid LLM classification row: {}. Error: {}",
                    raw_obj,
                    e,
                );
            }
        }
    }

    Ok(classifications)
}

/// Stage 1: the untyped rows of a response. Claude's structured output and
/// OpenAI's JSON schema mode return `{"classifications": [...]}`; otherwise
/// look for a bare array in the text.
pub(crate) fn raw_rows(response: &str) -> Result<Vec<serde_json::Value>> {
    let wrapped = serde_json::from_str::<serde_json::Value>(response.trim())
        .ok()
        .and_then(|mut value| match value.get_mut("classifications")?.take() {
            serde_json::Value::Array(rows) => Some(rows),
            _ => None,
        });
    match wrapped {
        Some(rows) => Ok(rows),
        None => {
            serde_json::from_str(extract_json_array(response)).map_err(|e| SeedKitError::LlmError {
                message: format!(
                    "Failed to parse LLM response as JSON array: {}. Response: {}",
                    e,
                    truncate(response, 200),
                ),
            })
        }
    }
}

/// Extract the JSON array from a response that may contain markdown fences
/// or conversational wrapper text.
///
/// Uses a three-tier extraction strategy:
/// 1. Markdown code fences (`\`\`\`json ... \`\`\``) — most reliable
/// 2. Regex matching `[{...}]` — avoids binding to peripheral brackets
///    in conversational text like `[as requested]`
/// 3. Raw trimmed response — last resort
fn extract_json_array(response: &str) -> &str {
    let trimmed = response.trim();

    // Tier 1: Markdown code fences (most reliable)
    if let Some(start) = trimmed.find("```json") {
        let after_fence = &trimmed[start + 7..];
        if let Some(end) = after_fence.find("```") {
            return after_fence[..end].trim();
        }
    }
    if let Some(start) = trimmed.find("```") {
        let after_fence = &trimmed[start + 3..];
        if let Some(end) = after_fence.find("```") {
            return after_fence[..end].trim();
        }
    }

    // Tier 2: Regex — match `[` followed by `{`, any content, `}` then `]`.
    // This avoids the greedy bracket trap where `find('[')` binds to
    // peripheral brackets in conversational text.
    static ARRAY_RE: std::sync::LazyLock<regex::Regex> =
        std::sync::LazyLock::new(|| regex::Regex::new(r"(?s)\[\s*\{.*\}\s*\]").unwrap());

    if let Some(mat) = ARRAY_RE.find(trimmed) {
        return mat.as_str();
    }

    trimmed
}

/// Merge LLM classifications with rule-based results.
///
/// The merge strategy is conservative:
/// - If the rule engine already assigned a specific type (not `Unknown`),
///   keep the rule-based result.
/// - If the rule engine classified as `Unknown` and the LLM has a
///   classification with confidence >= 0.5, use the LLM result.
pub fn merge_classifications(
    rule_based: &BTreeMap<(String, String), SemanticType>,
    llm_response: &str,
) -> BTreeMap<(String, String), SemanticType> {
    let mut merged = rule_based.clone();

    let llm_results = match parse_llm_response(llm_response) {
        Ok(r) => r,
        Err(e) => {
            tracing::warn!("Failed to parse LLM response, using rule-based only: {}", e);
            return merged;
        }
    };

    for classification in llm_results {
        let key = (classification.table, classification.column);
        let existing = merged.get(&key).copied().unwrap_or(SemanticType::Unknown);

        if existing == SemanticType::Unknown && classification.confidence >= 0.5 {
            merged.insert(key, classification.semantic_type);
        }
    }

    merged
}

/// Build a BTreeMap of AI classifications suitable for storing in the lock file.
///
/// Filters to only include entries where the LLM changed the classification
/// (i.e., the rule engine had `Unknown`).
pub fn build_ai_classification_cache(
    rule_based: &BTreeMap<(String, String), SemanticType>,
    merged: &BTreeMap<(String, String), SemanticType>,
) -> BTreeMap<String, BTreeMap<String, SemanticType>> {
    let mut cache: BTreeMap<String, BTreeMap<String, SemanticType>> = BTreeMap::new();

    for ((table, column), semantic_type) in merged {
        let rule_type = rule_based.get(&(table.clone(), column.clone()));
        // Only cache entries where the LLM provided a new classification
        if rule_type.is_none_or(|rt| *rt == SemanticType::Unknown)
            && *semantic_type != SemanticType::Unknown
        {
            cache
                .entry(table.clone())
                .or_default()
                .insert(column.clone(), *semantic_type);
        }
    }

    cache
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn unparseable_non_ascii_response_reports_an_error() {
        // The error preview cuts at 200 bytes, inside the 2-byte "é".
        let response = format!("x{}", "é".repeat(150));
        let err = parse_llm_response(&response).unwrap_err().to_string();
        assert!(err.contains(&"é".repeat(99)), "{err}");
    }

    #[test]
    fn test_parse_bare_json_array() {
        let response = r#"[
            {"table": "users", "column": "bio", "semantic_type": "Bio", "confidence": 0.9}
        ]"#;

        let results = parse_llm_response(response).unwrap();
        assert_eq!(results.len(), 1);
        assert_eq!(results[0].table, "users");
        assert_eq!(results[0].column, "bio");
        assert_eq!(results[0].semantic_type, SemanticType::Bio);
        assert!((results[0].confidence - 0.9).abs() < f64::EPSILON);
    }

    #[test]
    fn test_parse_markdown_fenced_json() {
        let response = r#"Here are the classifications:

```json
[
    {"table": "products", "column": "sku", "semantic_type": "Sku", "confidence": 0.95}
]
```

These are my best guesses."#;

        let results = parse_llm_response(response).unwrap();
        assert_eq!(results.len(), 1);
        assert_eq!(results[0].semantic_type, SemanticType::Sku);
    }

    #[test]
    fn test_parse_plain_fenced_json() {
        let response = "```\n[{\"table\":\"t\",\"column\":\"c\",\"semantic_type\":\"Email\",\"confidence\":0.8}]\n```";

        let results = parse_llm_response(response).unwrap();
        assert_eq!(results.len(), 1);
        assert_eq!(results[0].semantic_type, SemanticType::Email);
    }

    #[test]
    fn test_parse_invalid_json() {
        let response = "this is not json at all";
        let result = parse_llm_response(response);
        assert!(result.is_err());
    }

    #[test]
    fn test_merge_overrides_unknown_only() {
        let mut rule_based = BTreeMap::new();
        rule_based.insert(
            ("users".to_string(), "email".to_string()),
            SemanticType::Email,
        );
        rule_based.insert(
            ("users".to_string(), "bio".to_string()),
            SemanticType::Unknown,
        );
        rule_based.insert(
            ("users".to_string(), "tagline".to_string()),
            SemanticType::Unknown,
        );

        let llm_response = r#"[
            {"table": "users", "column": "email", "semantic_type": "Phone", "confidence": 0.9},
            {"table": "users", "column": "bio", "semantic_type": "Bio", "confidence": 0.85},
            {"table": "users", "column": "tagline", "semantic_type": "Sentence", "confidence": 0.3}
        ]"#;

        let merged = merge_classifications(&rule_based, llm_response);

        // email: rule-based already classified it as Email, LLM should NOT override
        assert_eq!(
            merged[&("users".to_string(), "email".to_string())],
            SemanticType::Email
        );
        // bio: was Unknown, LLM confidence 0.85 >= 0.5, should override
        assert_eq!(
            merged[&("users".to_string(), "bio".to_string())],
            SemanticType::Bio
        );
        // tagline: was Unknown, but LLM confidence 0.3 < 0.5, should stay Unknown
        assert_eq!(
            merged[&("users".to_string(), "tagline".to_string())],
            SemanticType::Unknown
        );
    }

    #[test]
    fn test_merge_with_invalid_llm_response_falls_back() {
        let mut rule_based = BTreeMap::new();
        rule_based.insert(
            ("users".to_string(), "email".to_string()),
            SemanticType::Email,
        );

        let merged = merge_classifications(&rule_based, "invalid json!!!");

        // Should return rule_based unchanged
        assert_eq!(merged.len(), 1);
        assert_eq!(
            merged[&("users".to_string(), "email".to_string())],
            SemanticType::Email
        );
    }

    #[test]
    fn test_build_ai_classification_cache() {
        let mut rule_based = BTreeMap::new();
        rule_based.insert(
            ("users".to_string(), "email".to_string()),
            SemanticType::Email,
        );
        rule_based.insert(
            ("users".to_string(), "bio".to_string()),
            SemanticType::Unknown,
        );

        let mut merged = rule_based.clone();
        merged.insert(("users".to_string(), "bio".to_string()), SemanticType::Bio);

        let cache = build_ai_classification_cache(&rule_based, &merged);

        // Only "bio" should be in the cache (it was Unknown→Bio)
        assert_eq!(cache.len(), 1);
        assert_eq!(cache["users"]["bio"], SemanticType::Bio);
        // "email" was already classified by rules, not in cache
        assert!(cache.get("users").unwrap().get("email").is_none());
    }

    #[test]
    fn test_extract_json_array_with_surrounding_text() {
        let response = "Some text before\n[{\"key\": \"val\"}]\nSome text after";
        let extracted = extract_json_array(response);
        assert_eq!(extracted, r#"[{"key": "val"}]"#);
    }

    #[test]
    fn test_confidence_defaults_to_zero() {
        let response = r#"[{"table": "t", "column": "c", "semantic_type": "Email"}]"#;
        let results = parse_llm_response(response).unwrap();
        assert!((results[0].confidence - 0.0).abs() < f64::EPSILON);
    }

    // --- Fix 1: Greedy bracket trap ---

    #[test]
    fn test_extract_json_array_ignores_peripheral_brackets() {
        // LLM wraps output in conversational text that also contains brackets
        let response = r#"Here is the JSON [as requested]:
[{"table": "users", "column": "email", "semantic_type": "Email", "confidence": 0.9}]
[End of output]"#;

        let extracted = extract_json_array(response);
        // Should extract the actual JSON array, not the "[as requested]...[End of output]" span
        assert!(
            extracted.starts_with("[{"),
            "Expected JSON array start, got: {}",
            extracted
        );
        assert!(
            extracted.ends_with("}]"),
            "Expected JSON array end, got: {}",
            extracted
        );

        // Verify it actually parses
        let results = parse_llm_response(response).unwrap();
        assert_eq!(results.len(), 1);
        assert_eq!(results[0].semantic_type, SemanticType::Email);
    }

    // --- Fix 2: Per-row deserialization firebreak ---

    #[test]
    fn test_hallucinated_semantic_type_drops_one_row_not_all() {
        // 3 rows: two valid, one with a hallucinated "UserEmail" type
        let response = r#"[
            {"table": "users", "column": "email", "semantic_type": "Email", "confidence": 0.9},
            {"table": "users", "column": "bio", "semantic_type": "UserEmail", "confidence": 0.8},
            {"table": "users", "column": "tagline", "semantic_type": "Sentence", "confidence": 0.7}
        ]"#;

        let results = parse_llm_response(response).unwrap();
        // Should get 2 valid rows, not 0 (the hallucinated row is dropped)
        assert_eq!(results.len(), 2);
        assert_eq!(results[0].semantic_type, SemanticType::Email);
        assert_eq!(results[1].semantic_type, SemanticType::Sentence);
    }

    #[test]
    fn test_all_hallucinated_returns_empty_not_error() {
        let response = r#"[
            {"table": "users", "column": "x", "semantic_type": "FooBar", "confidence": 0.9},
            {"table": "users", "column": "y", "semantic_type": "BazQux", "confidence": 0.8}
        ]"#;

        let results = parse_llm_response(response).unwrap();
        assert_eq!(results.len(), 0);
    }

    #[test]
    fn test_missing_required_fields_drops_row() {
        // Missing "column" field in second row
        let response = r#"[
            {"table": "users", "column": "email", "semantic_type": "Email", "confidence": 0.9},
            {"table": "users", "semantic_type": "Bio", "confidence": 0.8}
        ]"#;

        let results = parse_llm_response(response).unwrap();
        assert_eq!(results.len(), 1);
        assert_eq!(results[0].column, "email");
    }

    #[test]
    fn parses_the_structured_output_object() {
        let response = r#"{"classifications": [
            {"table": "users", "column": "bio", "semantic_type": "Bio", "confidence": 0.9}
        ]}"#;
        let results = parse_llm_response(response).unwrap();
        assert_eq!(results.len(), 1);
        assert_eq!(results[0].semantic_type, SemanticType::Bio);

        let empty = parse_llm_response(r#"{"classifications": []}"#).unwrap();
        assert!(empty.is_empty());
    }
}