hirn-exec 0.1.0

DataFusion physical operators, scoring UDFs, and optimizer rules for hirn
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
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
//! `NliContradictionExec` — contradiction detection over content pairs.
//!
//! The operator ships with a deterministic heuristic classifier backend by
//! default. A model-backed classifier can be injected via
//! `NliContradictionExec::with_classifier(...)` when a heavyweight artifact is
//! available, which keeps CI deterministic while leaving a clean seam for
//! future ONNX-backed inference.

use std::any::Any;
use std::fmt;
use std::sync::Arc;

use arrow_array::{Array, Float32Array, RecordBatch, StringArray};
use arrow_schema::{DataType, Field, Schema, SchemaRef};
use datafusion_common::Result;
use datafusion_execution::{SendableRecordBatchStream, TaskContext};
use datafusion_physical_plan::execution_plan::{Boundedness, EmissionType};
use datafusion_physical_plan::stream::RecordBatchStreamAdapter;
use datafusion_physical_plan::{DisplayAs, DisplayFormatType, ExecutionPlan, PlanProperties};

/// NLI classification result for a content pair.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum NliLabel {
    Entailment,
    Contradiction,
    Neutral,
}

/// Configuration for NLI contradiction detection.
#[derive(Debug, Clone)]
pub struct NliConfig {
    /// Contradiction probability threshold (default: 0.7).
    pub contradiction_threshold: f32,
    /// Maximum number of content pairs classified per execution.
    pub max_batch_size: usize,
}

impl Default for NliConfig {
    fn default() -> Self {
        Self {
            contradiction_threshold: 0.7,
            max_batch_size: 64,
        }
    }
}

/// Backend used to classify content pairs.
pub trait NliClassifier: fmt::Debug + Send + Sync {
    fn classify(&self, text_a: &str, text_b: &str) -> (NliLabel, f32);

    fn backend_name(&self) -> &'static str {
        "custom"
    }
}

/// Deterministic heuristic classifier used by default in production and CI.
#[derive(Debug, Default)]
pub struct HeuristicNliClassifier;

impl NliClassifier for HeuristicNliClassifier {
    fn classify(&self, text_a: &str, text_b: &str) -> (NliLabel, f32) {
        heuristic_nli(text_a, text_b)
    }

    fn backend_name(&self) -> &'static str {
        "heuristic"
    }
}

/// DataFusion operator for NLI contradiction detection.
///
/// Input: pairs of content strings (from child plan).
/// Output: pairs with NLI scores and labels.
#[derive(Debug)]
pub struct NliContradictionExec {
    input: Arc<dyn ExecutionPlan>,
    schema: SchemaRef,
    properties: PlanProperties,
    config: NliConfig,
    classifier: Arc<dyn NliClassifier>,
}

impl NliContradictionExec {
    pub fn new(input: Arc<dyn ExecutionPlan>, config: NliConfig) -> Self {
        Self::with_classifier(input, config, Arc::new(HeuristicNliClassifier))
    }

    pub fn with_classifier(
        input: Arc<dyn ExecutionPlan>,
        config: NliConfig,
        classifier: Arc<dyn NliClassifier>,
    ) -> Self {
        let schema = Self::output_schema();
        let properties = PlanProperties::new(
            datafusion_physical_expr::EquivalenceProperties::new(schema.clone()),
            datafusion_physical_plan::Partitioning::UnknownPartitioning(1),
            EmissionType::Final,
            Boundedness::Bounded,
        );
        Self {
            input,
            schema,
            properties,
            config,
            classifier,
        }
    }

    pub fn output_schema() -> SchemaRef {
        Arc::new(Schema::new(vec![
            Field::new("content_a", DataType::Utf8, false),
            Field::new("content_b", DataType::Utf8, false),
            Field::new("label", DataType::Utf8, false),
            Field::new("contradiction_score", DataType::Float32, false),
        ]))
    }
}

impl DisplayAs for NliContradictionExec {
    fn fmt_as(&self, _t: DisplayFormatType, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "NliContradictionExec: threshold={}, backend={}",
            self.config.contradiction_threshold,
            self.classifier.backend_name()
        )
    }
}

impl ExecutionPlan for NliContradictionExec {
    fn name(&self) -> &str {
        "NliContradictionExec"
    }

    fn as_any(&self) -> &dyn Any {
        self
    }

    fn schema(&self) -> SchemaRef {
        self.schema.clone()
    }

    fn properties(&self) -> &PlanProperties {
        &self.properties
    }

    fn children(&self) -> Vec<&Arc<dyn ExecutionPlan>> {
        vec![&self.input]
    }

    fn with_new_children(
        self: Arc<Self>,
        children: Vec<Arc<dyn ExecutionPlan>>,
    ) -> Result<Arc<dyn ExecutionPlan>> {
        Ok(Arc::new(Self::with_classifier(
            children[0].clone(),
            self.config.clone(),
            self.classifier.clone(),
        )))
    }

    fn execute(
        &self,
        partition: usize,
        context: Arc<TaskContext>,
    ) -> Result<SendableRecordBatchStream> {
        let input = self.input.execute(partition, context)?;
        let schema = self.schema.clone();
        let stream_schema = schema.clone();
        let threshold = self.config.contradiction_threshold;
        let max_batch_size = self.config.max_batch_size;
        let classifier = self.classifier.clone();

        let fut = async move {
            use futures::StreamExt;

            let mut content_as = Vec::new();
            let mut content_bs = Vec::new();
            let mut labels = Vec::new();
            let mut scores = Vec::new();
            let mut total_pairs = 0usize;

            // Collect pairs from input batch (capped at max_batch_size).
            let mut stream = input;
            'outer: while let Some(batch) = stream.next().await {
                let batch = batch?;
                let col_a = batch
                    .column_by_name("content_a")
                    .or_else(|| batch.column_by_name("content"));
                let col_b = batch.column_by_name("content_b");

                if let (Some(a), Some(b)) = (col_a, col_b) {
                    if let (Some(arr_a), Some(arr_b)) = (
                        a.as_any().downcast_ref::<StringArray>(),
                        b.as_any().downcast_ref::<StringArray>(),
                    ) {
                        for i in 0..arr_a.len().min(arr_b.len()) {
                            if total_pairs >= max_batch_size {
                                break 'outer;
                            }
                            if !arr_a.is_null(i) && !arr_b.is_null(i) {
                                let text_a = arr_a.value(i);
                                let text_b = arr_b.value(i);
                                let (label, score) = classifier.classify(text_a, text_b);
                                content_as.push(text_a.to_string());
                                content_bs.push(text_b.to_string());
                                labels.push(match label {
                                    NliLabel::Contradiction => "contradiction",
                                    NliLabel::Entailment => "entailment",
                                    NliLabel::Neutral => "neutral",
                                });
                                scores.push(score);
                                total_pairs += 1;
                            }
                        }
                    }
                }
            }

            // Filter to pairs that are contradictions above threshold.
            let mut final_as = Vec::new();
            let mut final_bs = Vec::new();
            let mut final_labels = Vec::new();
            let mut final_scores = Vec::new();

            for i in 0..content_as.len() {
                if labels[i] == "contradiction" && scores[i] >= threshold {
                    final_as.push(content_as[i].clone());
                    final_bs.push(content_bs[i].clone());
                    final_labels.push(labels[i].to_string());
                    final_scores.push(scores[i]);
                }
            }

            let batch = RecordBatch::try_new(
                schema,
                vec![
                    Arc::new(StringArray::from(final_as)),
                    Arc::new(StringArray::from(final_bs)),
                    Arc::new(StringArray::from(final_labels)),
                    Arc::new(Float32Array::from(final_scores)),
                ],
            )?;

            Ok(batch)
        };

        let stream = futures::stream::once(fut);
        Ok(Box::pin(RecordBatchStreamAdapter::new(
            stream_schema,
            stream,
        )))
    }
}

// ── Heuristic NLI fallback ─────────────────────────────────────────────

/// Heuristic NLI when ONNX model is unavailable.
///
/// Uses negation patterns, entity-value conflicts, and keyword overlap
/// to estimate contradiction probability.
pub fn heuristic_nli(text_a: &str, text_b: &str) -> (NliLabel, f32) {
    let a_lower = text_a.to_lowercase();
    let b_lower = text_b.to_lowercase();

    let a_negated = contains_negation(&a_lower);
    let b_negated = contains_negation(&b_lower);

    // High word overlap + opposite negation ⇒ contradiction.
    let overlap = word_overlap(&a_lower, &b_lower);

    if overlap > 0.3 && a_negated != b_negated {
        return (NliLabel::Contradiction, 0.75 + overlap * 0.2);
    }

    // Antonym patterns.
    if has_antonym_pair(&a_lower, &b_lower) && overlap > 0.2 {
        return (NliLabel::Contradiction, 0.7 + overlap * 0.2);
    }

    // High overlap + same polarity ⇒ entailment.
    if overlap > 0.6 && a_negated == b_negated {
        return (NliLabel::Entailment, 0.6 + overlap * 0.3);
    }

    (NliLabel::Neutral, 0.3 + (1.0 - overlap) * 0.3)
}

fn contains_negation(text: &str) -> bool {
    let patterns = [
        "not ",
        "n't ",
        "never ",
        "no ",
        "doesn't ",
        "didn't ",
        "isn't ",
        "wasn't ",
        "aren't ",
        "won't ",
        "cannot ",
        "can't ",
        "shouldn't ",
        "wouldn't ",
        "hasn't ",
        "haven't ",
        "nor ",
        "neither ",
        "failed ",
        "unable ",
    ];
    patterns.iter().any(|p| text.contains(p))
}

fn word_overlap(a: &str, b: &str) -> f32 {
    let a_words: std::collections::HashSet<&str> = a.split_whitespace().collect();
    let b_words: std::collections::HashSet<&str> = b.split_whitespace().collect();

    if a_words.is_empty() || b_words.is_empty() {
        return 0.0;
    }

    let intersection = a_words.intersection(&b_words).count() as f32;
    let union = a_words.union(&b_words).count() as f32;

    intersection / union // Jaccard similarity
}

fn has_antonym_pair(a: &str, b: &str) -> bool {
    let antonyms = [
        ("running", "stopped"),
        ("running", "crashed"),
        ("success", "failure"),
        ("succeeded", "failed"),
        ("up", "down"),
        ("true", "false"),
        ("enabled", "disabled"),
        ("active", "inactive"),
        ("alive", "dead"),
        ("open", "closed"),
        ("started", "stopped"),
        ("healthy", "unhealthy"),
        ("online", "offline"),
        ("increase", "decrease"),
    ];

    for (w1, w2) in &antonyms {
        if (a.contains(w1) && b.contains(w2)) || (a.contains(w2) && b.contains(w1)) {
            return true;
        }
    }
    false
}

#[cfg(test)]
mod tests {
    use std::sync::Arc;

    use arrow_array::{Float32Array, StringArray};
    use arrow_schema::{DataType, Field, Schema};
    use datafusion_execution::TaskContext;
    use futures::StreamExt;

    use super::*;

    #[derive(Debug)]
    struct FixtureClassifier;

    impl NliClassifier for FixtureClassifier {
        fn classify(&self, text_a: &str, text_b: &str) -> (NliLabel, f32) {
            match (text_a, text_b) {
                ("alpha service is online", "alpha service is offline") => {
                    (NliLabel::Contradiction, 0.91)
                }
                ("beta rollout is stable", "beta rollout remains stable") => {
                    (NliLabel::Entailment, 0.88)
                }
                ("gamma deploy is ready", "gamma deploy is blocked") => {
                    (NliLabel::Contradiction, 0.95)
                }
                _ => (NliLabel::Neutral, 0.2),
            }
        }

        fn backend_name(&self) -> &'static str {
            "fixture"
        }
    }

    fn pair_schema(left_name: &str) -> SchemaRef {
        Arc::new(Schema::new(vec![
            Field::new(left_name, DataType::Utf8, false),
            Field::new("content_b", DataType::Utf8, false),
        ]))
    }

    #[tokio::test]
    async fn execute_default_heuristic_backend_detects_negation_contradictions() {
        let schema = pair_schema("content_a");
        let batch = RecordBatch::try_new(
            schema.clone(),
            vec![
                Arc::new(StringArray::from(vec![
                    "The service is running",
                    "The service is healthy",
                ])),
                Arc::new(StringArray::from(vec![
                    "The service is not running",
                    "The service handles requests",
                ])),
            ],
        )
        .unwrap();

        let input = Arc::new(crate::test_utils::MemoryBatchExec::new(schema, vec![batch]));
        let exec = NliContradictionExec::new(input, NliConfig::default());
        let mut stream = exec.execute(0, Arc::new(TaskContext::default())).unwrap();
        let result = stream.next().await.unwrap().unwrap();

        assert_eq!(result.num_rows(), 1, "only the contradiction should remain");

        let labels = result
            .column_by_name("label")
            .unwrap()
            .as_any()
            .downcast_ref::<StringArray>()
            .unwrap();
        let scores = result
            .column_by_name("contradiction_score")
            .unwrap()
            .as_any()
            .downcast_ref::<Float32Array>()
            .unwrap();

        assert_eq!(labels.value(0), "contradiction");
        assert!(scores.value(0) >= 0.7);
    }

    #[tokio::test]
    async fn execute_with_fixture_classifier_is_ci_safe_and_respects_limits() {
        let schema = pair_schema("content");
        let batch = RecordBatch::try_new(
            schema.clone(),
            vec![
                Arc::new(StringArray::from(vec![
                    "alpha service is online",
                    "beta rollout is stable",
                    "gamma deploy is ready",
                ])),
                Arc::new(StringArray::from(vec![
                    "alpha service is offline",
                    "beta rollout remains stable",
                    "gamma deploy is blocked",
                ])),
            ],
        )
        .unwrap();

        let input = Arc::new(crate::test_utils::MemoryBatchExec::new(schema, vec![batch]));
        let exec = NliContradictionExec::with_classifier(
            input,
            NliConfig {
                contradiction_threshold: 0.7,
                max_batch_size: 2,
            },
            Arc::new(FixtureClassifier),
        );
        let mut stream = exec.execute(0, Arc::new(TaskContext::default())).unwrap();
        let result = stream.next().await.unwrap().unwrap();

        assert_eq!(
            result.num_rows(),
            1,
            "batch cap should prevent later rows from being classified"
        );

        let content_as = result
            .column_by_name("content_a")
            .unwrap()
            .as_any()
            .downcast_ref::<StringArray>()
            .unwrap();
        let content_bs = result
            .column_by_name("content_b")
            .unwrap()
            .as_any()
            .downcast_ref::<StringArray>()
            .unwrap();
        let scores = result
            .column_by_name("contradiction_score")
            .unwrap()
            .as_any()
            .downcast_ref::<Float32Array>()
            .unwrap();

        assert_eq!(content_as.value(0), "alpha service is online");
        assert_eq!(content_bs.value(0), "alpha service is offline");
        assert!((scores.value(0) - 0.91).abs() < f32::EPSILON);
    }
}