algeon-cudf 0.1.2

Safe libcudf execution component for Algeon
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
//! Typed diagnostic facts for `cudf::Error`.
//!
//! Facts are machine-readable values that downstreams match on for policy.
//!
//! - Each `FactKeyName` binds to exactly one `FactValue` variant; the pairing
//!   is enforced at the writer-API type layer via `FactKey<T>`.
//! - A key keeps its first value. The leaf error that reports a failure
//!   writes first, so a wrapper that inserts the same key later cannot
//!   overwrite the original failure location; wrappers add context through
//!   the call chain and details.
//! - Public downstream API is read-only. Internal writers use the typed
//!   `with_fact(FactKey<T>, T)` shape.

use std::{borrow::Cow, fmt, marker::PhantomData};

use indexmap::IndexMap;

use crate::core::types::TypeId;

/// Stable canonical keys under which machine-readable facts are indexed.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum FactKeyName {
    /// Caller column identifier associated with the failure.
    ColumnName,
    /// Zero-based column position associated with the failure.
    ColumnIndex,
    /// Row count required by the failed input contract.
    ExpectedRows,
    /// Observed row count that did not satisfy the input contract.
    ActualRows,
    /// Item count required by the operation, such as partition fields or columns.
    ExpectedCount,
    /// Observed item count compared with the required count.
    ActualCount,
    /// cuDF type of the left input in a type compatibility check.
    LeftTypeId,
    /// cuDF type of the right input in a type compatibility check.
    RightTypeId,
    /// Process-visible CUDA ordinal of the left input.
    LeftDevice,
    /// Process-visible CUDA ordinal of the right input.
    RightDevice,
    /// Number of rows in the table involved in the failure.
    TableRowCount,
    /// Number of columns in the table involved in the failure.
    TableColumnCount,
    /// Number of keys supplied to the operation.
    KeysCount,
    /// Number of distinct keys observed by validation.
    DistinctKeysCount,
    /// cuDF type associated with the failed operation.
    TypeId,
    /// Stable reason identifying the failed value validation.
    ValidationReason,
    /// Execution-binding identity attached to validated input storage.
    ExecutionBindingId,
    /// Process-visible CUDA ordinal on which input validation ran.
    ValidationDevice,
    /// Diagnostic stream identifier used for input validation.
    ValidationStream,
    /// Number of scalar bytes copied to the host to establish validation evidence.
    ControlPlaneScalarBytes,
}

impl fmt::Display for FactKeyName {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_snake_case())
    }
}

/// Type-checked handle used by the internal writer API.
///
/// The phantom `T` encodes the legal value type for `name` so
/// `with_fact(FactKey<Usize>, "not-a-number")` is a compile error.
#[derive(Debug)]
pub(crate) struct FactKey<T> {
    name: FactKeyName,
    _marker: PhantomData<fn() -> T>,
}

impl<T> Clone for FactKey<T> {
    fn clone(&self) -> Self {
        *self
    }
}
impl<T> Copy for FactKey<T> {}

impl<T> FactKey<T> {
    pub(crate) const fn new(name: FactKeyName) -> Self {
        Self { name, _marker: PhantomData }
    }

    pub(crate) const fn name(&self) -> FactKeyName {
        self.name
    }
}

/// Typed machine-readable fact value.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum FactValue {
    /// Text fact retaining either borrowed static text or owned text.
    Str(Cow<'static, str>),
    /// Nonnegative count represented by the host pointer-sized integer type.
    Usize(usize),
    /// Signed integer fact.
    I64(i64),
    /// Typed cuDF data-type identity.
    TypeId(TypeId),
    /// Process-visible CUDA device ordinal.
    DeviceId(i32),
    /// Unsigned fixed-width counter or identity.
    U64(u64),
}

impl fmt::Display for FactValue {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            FactValue::Str(s) => f.write_str(s),
            FactValue::Usize(v) => write!(f, "{v}"),
            FactValue::I64(v) => write!(f, "{v}"),
            FactValue::TypeId(t) => write!(f, "{t}"),
            FactValue::DeviceId(d) => write!(f, "{d}"),
            FactValue::U64(v) => write!(f, "{v}"),
        }
    }
}

/// Tag identifying the legal `FactValue` variant for a given `FactKeyName`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum FactValueVariant {
    Str,
    Usize,
    I64,
    TypeId,
    DeviceId,
    U64,
}

impl FactValueVariant {
    pub(crate) const fn of_value(value: &FactValue) -> Self {
        match value {
            FactValue::Str(_) => FactValueVariant::Str,
            FactValue::Usize(_) => FactValueVariant::Usize,
            FactValue::I64(_) => FactValueVariant::I64,
            FactValue::TypeId(_) => FactValueVariant::TypeId,
            FactValue::DeviceId(_) => FactValueVariant::DeviceId,
            FactValue::U64(_) => FactValueVariant::U64,
        }
    }
}

impl FactKeyName {
    /// Returns the canonical snake_case identity for this key.
    ///
    /// This mirrors `Display`. `from_snake_case` parses these strings back into
    /// the same keys.
    pub const fn as_snake_case(self) -> &'static str {
        match self {
            FactKeyName::ColumnName => "column_name",
            FactKeyName::ColumnIndex => "column_index",
            FactKeyName::ExpectedRows => "expected_rows",
            FactKeyName::ActualRows => "actual_rows",
            FactKeyName::ExpectedCount => "expected_count",
            FactKeyName::ActualCount => "actual_count",
            FactKeyName::LeftTypeId => "left_type_id",
            FactKeyName::RightTypeId => "right_type_id",
            FactKeyName::LeftDevice => "left_device",
            FactKeyName::RightDevice => "right_device",
            FactKeyName::TableRowCount => "table_row_count",
            FactKeyName::TableColumnCount => "table_column_count",
            FactKeyName::KeysCount => "keys_count",
            FactKeyName::DistinctKeysCount => "distinct_keys_count",
            FactKeyName::TypeId => "type_id",
            FactKeyName::ValidationReason => "validation_reason",
            FactKeyName::ExecutionBindingId => "execution_binding_id",
            FactKeyName::ValidationDevice => "validation_device",
            FactKeyName::ValidationStream => "validation_stream",
            FactKeyName::ControlPlaneScalarBytes => "control_plane_scalar_bytes",
        }
    }

    /// Parses the canonical snake_case identity back into a `FactKeyName`.
    ///
    /// Returns `None` for any string that is not a known canonical key.
    pub fn from_snake_case(name: &str) -> Option<Self> {
        Some(match name {
            "column_name" => FactKeyName::ColumnName,
            "column_index" => FactKeyName::ColumnIndex,
            "expected_rows" => FactKeyName::ExpectedRows,
            "actual_rows" => FactKeyName::ActualRows,
            "expected_count" => FactKeyName::ExpectedCount,
            "actual_count" => FactKeyName::ActualCount,
            "left_type_id" => FactKeyName::LeftTypeId,
            "right_type_id" => FactKeyName::RightTypeId,
            "left_device" => FactKeyName::LeftDevice,
            "right_device" => FactKeyName::RightDevice,
            "table_row_count" => FactKeyName::TableRowCount,
            "table_column_count" => FactKeyName::TableColumnCount,
            "keys_count" => FactKeyName::KeysCount,
            "distinct_keys_count" => FactKeyName::DistinctKeysCount,
            "type_id" => FactKeyName::TypeId,
            "validation_reason" => FactKeyName::ValidationReason,
            "execution_binding_id" => FactKeyName::ExecutionBindingId,
            "validation_device" => FactKeyName::ValidationDevice,
            "validation_stream" => FactKeyName::ValidationStream,
            "control_plane_scalar_bytes" => FactKeyName::ControlPlaneScalarBytes,
            _ => return None,
        })
    }

    /// Returns the unique `FactValue` variant legal for this key.
    ///
    /// Adding a new `FactKeyName` without extending this is a compile error.
    pub(crate) const fn legal_variant(self) -> FactValueVariant {
        match self {
            FactKeyName::ColumnName => FactValueVariant::Str,
            FactKeyName::ColumnIndex => FactValueVariant::Usize,
            FactKeyName::ExpectedRows => FactValueVariant::Usize,
            FactKeyName::ActualRows => FactValueVariant::Usize,
            FactKeyName::ExpectedCount => FactValueVariant::Usize,
            FactKeyName::ActualCount => FactValueVariant::Usize,
            FactKeyName::LeftTypeId => FactValueVariant::TypeId,
            FactKeyName::RightTypeId => FactValueVariant::TypeId,
            FactKeyName::LeftDevice => FactValueVariant::DeviceId,
            FactKeyName::RightDevice => FactValueVariant::DeviceId,
            FactKeyName::TableRowCount => FactValueVariant::Usize,
            FactKeyName::TableColumnCount => FactValueVariant::Usize,
            FactKeyName::KeysCount => FactValueVariant::Usize,
            FactKeyName::DistinctKeysCount => FactValueVariant::Usize,
            FactKeyName::TypeId => FactValueVariant::TypeId,
            FactKeyName::ValidationReason => FactValueVariant::Str,
            FactKeyName::ExecutionBindingId => FactValueVariant::U64,
            FactKeyName::ValidationDevice => FactValueVariant::DeviceId,
            FactKeyName::ValidationStream => FactValueVariant::Usize,
            FactKeyName::ControlPlaneScalarBytes => FactValueVariant::Usize,
        }
    }
}

/// Converts the value type of a `FactKey<T>` into a stored fact value.
///
/// Key/value pairing is enforced by `FactKey<T>` and by `Error::with_fact`,
/// which accepts only a value of the key's type.
pub(crate) trait IntoFactValue {
    fn into_fact_value(self) -> FactValue;
}

impl IntoFactValue for &'static str {
    fn into_fact_value(self) -> FactValue {
        FactValue::Str(Cow::Borrowed(self))
    }
}

impl IntoFactValue for String {
    fn into_fact_value(self) -> FactValue {
        FactValue::Str(Cow::Owned(self))
    }
}

impl IntoFactValue for Cow<'static, str> {
    fn into_fact_value(self) -> FactValue {
        FactValue::Str(self)
    }
}

impl IntoFactValue for usize {
    fn into_fact_value(self) -> FactValue {
        FactValue::Usize(self)
    }
}

impl IntoFactValue for i64 {
    fn into_fact_value(self) -> FactValue {
        FactValue::I64(self)
    }
}

impl IntoFactValue for u64 {
    fn into_fact_value(self) -> FactValue {
        FactValue::U64(self)
    }
}

impl IntoFactValue for TypeId {
    fn into_fact_value(self) -> FactValue {
        FactValue::TypeId(self)
    }
}

/// Wrapper around `i32` for device-id facts so that arbitrary `i32` integers
/// do not accidentally satisfy `FactKey<DeviceIdFact>`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub(crate) struct DeviceIdFact(pub(crate) i32);

impl IntoFactValue for DeviceIdFact {
    fn into_fact_value(self) -> FactValue {
        FactValue::DeviceId(self.0)
    }
}

pub(crate) const FACT_COLUMN_NAME: FactKey<Cow<'static, str>> = FactKey::new(FactKeyName::ColumnName);
pub(crate) const FACT_COLUMN_INDEX: FactKey<usize> = FactKey::new(FactKeyName::ColumnIndex);
pub(crate) const FACT_EXPECTED_ROWS: FactKey<usize> = FactKey::new(FactKeyName::ExpectedRows);
pub(crate) const FACT_ACTUAL_ROWS: FactKey<usize> = FactKey::new(FactKeyName::ActualRows);
pub(crate) const FACT_EXPECTED_COUNT: FactKey<usize> = FactKey::new(FactKeyName::ExpectedCount);
pub(crate) const FACT_ACTUAL_COUNT: FactKey<usize> = FactKey::new(FactKeyName::ActualCount);
pub(crate) const FACT_LEFT_TYPE_ID: FactKey<TypeId> = FactKey::new(FactKeyName::LeftTypeId);
pub(crate) const FACT_RIGHT_TYPE_ID: FactKey<TypeId> = FactKey::new(FactKeyName::RightTypeId);
pub(crate) const FACT_LEFT_DEVICE: FactKey<DeviceIdFact> = FactKey::new(FactKeyName::LeftDevice);
pub(crate) const FACT_RIGHT_DEVICE: FactKey<DeviceIdFact> = FactKey::new(FactKeyName::RightDevice);
pub(crate) const FACT_TABLE_ROW_COUNT: FactKey<usize> = FactKey::new(FactKeyName::TableRowCount);
pub(crate) const FACT_TABLE_COLUMN_COUNT: FactKey<usize> = FactKey::new(FactKeyName::TableColumnCount);
pub(crate) const FACT_KEYS_COUNT: FactKey<usize> = FactKey::new(FactKeyName::KeysCount);
pub(crate) const FACT_DISTINCT_KEYS_COUNT: FactKey<usize> = FactKey::new(FactKeyName::DistinctKeysCount);
pub(crate) const FACT_TYPE_ID: FactKey<TypeId> = FactKey::new(FactKeyName::TypeId);
pub(crate) const FACT_VALIDATION_REASON: FactKey<&'static str> = FactKey::new(FactKeyName::ValidationReason);
pub(crate) const FACT_EXECUTION_BINDING_ID: FactKey<u64> = FactKey::new(FactKeyName::ExecutionBindingId);
pub(crate) const FACT_VALIDATION_DEVICE: FactKey<DeviceIdFact> = FactKey::new(FactKeyName::ValidationDevice);
pub(crate) const FACT_VALIDATION_STREAM: FactKey<usize> = FactKey::new(FactKeyName::ValidationStream);
pub(crate) const FACT_CONTROL_PLANE_SCALAR_BYTES: FactKey<usize> = FactKey::new(FactKeyName::ControlPlaneScalarBytes);

/// Container for canonical facts. Keys are unique; the first value wins.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Facts {
    inner: IndexMap<FactKeyName, FactValue>,
}

impl Facts {
    pub(crate) fn new() -> Self {
        Self::default()
    }

    /// Returns whether this error carries no canonical facts.
    pub fn is_empty(&self) -> bool {
        self.inner.is_empty()
    }

    /// Returns the number of distinct canonical fact keys retained by this error.
    pub fn len(&self) -> usize {
        self.inner.len()
    }

    /// Borrows the first value recorded for `key`, or returns `None` when the key is absent.
    pub fn get(&self, key: FactKeyName) -> Option<&FactValue> {
        self.inner.get(&key)
    }

    /// Returns whether a value was recorded under the canonical key.
    pub fn contains(&self, key: FactKeyName) -> bool {
        self.inner.contains_key(&key)
    }

    /// Borrows canonical key/value pairs in their original insertion order.
    pub fn iter(&self) -> impl Iterator<Item = (FactKeyName, &FactValue)> {
        self.inner.iter().map(|(k, v)| (*k, v))
    }

    /// Leaf-wins insertion; used by typed `with_fact(FactKey<T>, T)`.
    ///
    /// The first value bound to a key is kept and later duplicates are
    /// dropped. Wrappers add context through the call chain and details; they
    /// do not overwrite the leaf error's facts.
    pub(crate) fn insert(&mut self, key: FactKeyName, value: FactValue) {
        debug_assert_eq!(
            FactValueVariant::of_value(&value),
            key.legal_variant(),
            "{key} bound to wrong FactValue variant"
        );
        self.inner.entry(key).or_insert(value);
    }
}

impl fmt::Display for Facts {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("{ ")?;
        let mut first = true;
        for (key, value) in self.iter() {
            if !first {
                f.write_str(", ")?;
            }
            first = false;
            write!(f, "{key}: {value}")?;
        }
        f.write_str(" }")
    }
}

#[cfg(test)]
mod tests {
    //! Crate-internal tests that lock the `Facts` writer contract.
    //!
    //! Leaf-wins insertion and wrong-variant behavior are crate-internal
    //! invariants, so the tests must live inside the crate too.

    use std::panic::{AssertUnwindSafe, catch_unwind};

    use super::{FactKeyName, FactValue, Facts};

    #[test]
    fn insert_keeps_first_value_on_duplicate_key() {
        let mut facts = Facts::new();
        facts.insert(FactKeyName::ExpectedRows, FactValue::Usize(3));
        facts.insert(FactKeyName::ExpectedRows, FactValue::Usize(99));
        assert_eq!(facts.get(FactKeyName::ExpectedRows), Some(&FactValue::Usize(3)));
    }

    #[test]
    fn insert_panics_on_wrong_value_variant() {
        let panic = catch_unwind(AssertUnwindSafe(|| {
            let mut facts = Facts::new();
            facts.insert(FactKeyName::ExpectedRows, FactValue::Str("3".into()));
        }));

        assert!(panic.is_err(), "wrong FactValue variant must panic instead of smuggling numbers through strings");
    }
}