dtcs 0.13.0

Reference implementation of the Data Transformation Contract Standard (DTCS)
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
//! Portable semantic-family differential fixtures (proposal R3).

use std::collections::BTreeMap;
use std::path::Path;

use indexmap::IndexMap;
use serde::{Deserialize, Serialize};
use serde_json::Value;

use crate::analysis::expr::{format_expression, from_structured_node, to_structured_node};
use crate::runtime::actions::apply_dataset_action;
use crate::runtime::{Dataset, Row, RuntimeValue};

use super::fixtures::read_fixture;
use super::model::ConformanceTestResult;

/// One action step in a portable differential fixture.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PortableActionStep {
    /// Registry action id (`dtcs:…`).
    pub action: String,
    /// Target interface / dataset id.
    pub target: String,
    /// Action parameters.
    #[serde(default)]
    pub parameters: IndexMap<String, Value>,
}

/// Portable differential fixture document.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PortableDifferentialFixture {
    /// Stable fixture id.
    pub id: String,
    /// Action sequence to apply.
    pub actions: Vec<PortableActionStep>,
    /// Input datasets keyed by interface id.
    pub input: BTreeMap<String, Vec<Value>>,
    /// Expected datasets keyed by interface id.
    pub expected: BTreeMap<String, Vec<Value>>,
    /// Optional expected error substring (negative cases).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub expect_error: Option<String>,
}

/// Evaluation mode for dual-path conformance.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PortableEvalMode {
    /// Evaluate expression strings directly.
    Direct,
    /// Lower strings to structured nodes and reformat before evaluation.
    StructuredLowering,
}

/// Run a portable differential fixture under one evaluation mode.
pub fn run_portable_fixture(
    fixture: &PortableDifferentialFixture,
    mode: PortableEvalMode,
) -> Result<BTreeMap<String, Dataset>, String> {
    let mut workspaces: BTreeMap<String, Dataset> = BTreeMap::new();
    for (name, rows) in &fixture.input {
        let mut dataset = Vec::new();
        for row in rows {
            dataset.push(json_row_to_runtime(row)?);
        }
        workspaces.insert(name.clone(), dataset);
    }

    for step in &fixture.actions {
        let params = match mode {
            PortableEvalMode::Direct => step.parameters.clone(),
            PortableEvalMode::StructuredLowering => lower_expr_params(&step.parameters)?,
        };
        apply_dataset_action(&step.action, &step.target, &params, &mut workspaces)?;
    }
    Ok(workspaces)
}

/// Compare runtime datasets to expected JSON rows.
pub fn datasets_match_expected(
    actual: &BTreeMap<String, Dataset>,
    expected: &BTreeMap<String, Vec<Value>>,
) -> Result<(), String> {
    for (name, expected_rows) in expected {
        let actual_rows = actual
            .get(name)
            .ok_or_else(|| format!("missing output dataset '{name}'"))?;
        let expected_runtime: Dataset = expected_rows
            .iter()
            .map(json_row_to_runtime)
            .collect::<Result<_, _>>()?;
        if actual_rows != &expected_runtime {
            return Err(format!(
                "dataset '{name}' mismatch: got {actual_rows:?}, expected {expected_runtime:?}"
            ));
        }
    }
    Ok(())
}

/// Load and execute a portable differential fixture for conformance.
pub fn run_portable_differential_case(
    fixtures_dir: &Path,
    relative: &str,
    test_id: &str,
    profile_id: &str,
) -> ConformanceTestResult {
    let bytes = match read_fixture(fixtures_dir, relative) {
        Ok(bytes) => bytes,
        Err(err) => {
            return ConformanceTestResult {
                id: test_id.into(),
                profile: profile_id.into(),
                passed: false,
                message: Some(err),
            };
        }
    };
    let fixture: PortableDifferentialFixture = match serde_json::from_slice(&bytes) {
        Ok(f) => f,
        Err(err) => {
            return ConformanceTestResult {
                id: test_id.into(),
                profile: profile_id.into(),
                passed: false,
                message: Some(format!("parse portable fixture: {err}")),
            };
        }
    };

    for mode in [
        PortableEvalMode::Direct,
        PortableEvalMode::StructuredLowering,
    ] {
        let result = run_portable_fixture(&fixture, mode);
        if let Some(expect_err) = &fixture.expect_error {
            match result {
                Err(err) if err.contains(expect_err) => continue,
                Err(err) => {
                    return ConformanceTestResult {
                        id: test_id.into(),
                        profile: profile_id.into(),
                        passed: false,
                        message: Some(format!(
                            "mode {mode:?}: expected error containing '{expect_err}', got '{err}'"
                        )),
                    };
                }
                Ok(_) => {
                    return ConformanceTestResult {
                        id: test_id.into(),
                        profile: profile_id.into(),
                        passed: false,
                        message: Some(format!(
                            "mode {mode:?}: expected error containing '{expect_err}'"
                        )),
                    };
                }
            }
        } else {
            let outputs = match result {
                Ok(outputs) => outputs,
                Err(err) => {
                    return ConformanceTestResult {
                        id: test_id.into(),
                        profile: profile_id.into(),
                        passed: false,
                        message: Some(format!("mode {mode:?}: {err}")),
                    };
                }
            };
            if let Err(err) = datasets_match_expected(&outputs, &fixture.expected) {
                return ConformanceTestResult {
                    id: test_id.into(),
                    profile: profile_id.into(),
                    passed: false,
                    message: Some(format!("mode {mode:?}: {err}")),
                };
            }
        }
    }

    ConformanceTestResult {
        id: test_id.into(),
        profile: profile_id.into(),
        passed: true,
        message: None,
    }
}

fn lower_expr_params(
    parameters: &IndexMap<String, Value>,
) -> Result<IndexMap<String, Value>, String> {
    let mut out = IndexMap::new();
    for (key, value) in parameters {
        if matches!(
            key.as_str(),
            "expr" | "condition" | "predicate" | "on" | "filter"
        ) && value.is_string()
        {
            let s = value.as_str().unwrap();
            let node = to_structured_node(s)?;
            let expr = from_structured_node(&node)?;
            out.insert(key.clone(), Value::String(format_expression(&expr)));
        } else {
            out.insert(key.clone(), lower_value(value)?);
        }
    }
    Ok(out)
}

fn lower_value(value: &Value) -> Result<Value, String> {
    match value {
        Value::Array(items) => {
            let lowered: Result<Vec<_>, _> = items.iter().map(lower_value).collect();
            Ok(Value::Array(lowered?))
        }
        Value::Object(map) => {
            let mut out = serde_json::Map::new();
            for (k, v) in map {
                if matches!(
                    k.as_str(),
                    "expr" | "condition" | "predicate" | "on" | "filter"
                ) && v.is_string()
                {
                    let s = v.as_str().unwrap();
                    let node = to_structured_node(s)?;
                    let expr = from_structured_node(&node)?;
                    out.insert(k.clone(), Value::String(format_expression(&expr)));
                } else {
                    out.insert(k.clone(), lower_value(v)?);
                }
            }
            Ok(Value::Object(out))
        }
        other => Ok(other.clone()),
    }
}

fn json_row_to_runtime(value: &Value) -> Result<Row, String> {
    let obj = value
        .as_object()
        .ok_or_else(|| "portable fixture rows must be objects".to_string())?;
    let mut row = BTreeMap::new();
    for (k, v) in obj {
        row.insert(k.clone(), json_to_runtime(v)?);
    }
    Ok(row)
}

fn json_to_runtime(value: &Value) -> Result<RuntimeValue, String> {
    Ok(match value {
        Value::Null => RuntimeValue::Null,
        Value::Bool(b) => RuntimeValue::Boolean(*b),
        Value::Number(n) => {
            if let Some(i) = n.as_i64() {
                RuntimeValue::Integer(i)
            } else if let Some(f) = n.as_f64() {
                RuntimeValue::Decimal(f)
            } else {
                return Err(format!("unsupported number {n}"));
            }
        }
        Value::String(s) => RuntimeValue::String(s.clone()),
        Value::Array(items) => {
            let values: Result<Vec<_>, _> = items.iter().map(json_to_runtime).collect();
            RuntimeValue::List(values?)
        }
        Value::Object(map) => {
            if map.len() == 1 {
                if let Some(token) = map.get("$missing") {
                    let _ = token;
                    return Ok(RuntimeValue::missing());
                }
                if let Some(reason) = map.get("$invalid").and_then(Value::as_str) {
                    return Ok(RuntimeValue::invalid(reason));
                }
                if let Some(date) = map.get("$date").and_then(Value::as_str) {
                    return Ok(RuntimeValue::Date(date.to_string()));
                }
                if let Some(dt) = map.get("$datetime").and_then(Value::as_str) {
                    return Ok(RuntimeValue::DateTime(dt.to_string()));
                }
            }
            let mut out = IndexMap::new();
            for (k, v) in map {
                out.insert(k.clone(), json_to_runtime(v)?);
            }
            RuntimeValue::Map(out)
        }
    })
}

/// Fixture for `portablePlanMigrate` assertions.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PortablePlanMigrateFixture {
    /// Stable fixture id.
    pub id: String,
    /// Source portable plan document (v1 or other).
    pub source: Value,
    /// Expected profile after successful migration.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub expect_profile: Option<String>,
    /// Optional expected error substring (negative cases).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub expect_error: Option<String>,
}

/// Load and execute a portable plan migration fixture for conformance.
pub fn run_portable_plan_migrate_case(
    fixtures_dir: &Path,
    relative: &str,
    test_id: &str,
    profile_id: &str,
) -> ConformanceTestResult {
    let bytes = match read_fixture(fixtures_dir, relative) {
        Ok(bytes) => bytes,
        Err(err) => {
            return ConformanceTestResult {
                id: test_id.into(),
                profile: profile_id.into(),
                passed: false,
                message: Some(err),
            };
        }
    };
    let fixture: PortablePlanMigrateFixture = match serde_json::from_slice(&bytes) {
        Ok(f) => f,
        Err(err) => {
            return ConformanceTestResult {
                id: test_id.into(),
                profile: profile_id.into(),
                passed: false,
                message: Some(format!("parse portable plan migrate fixture: {err}")),
            };
        }
    };
    let source_bytes = match serde_json::to_vec(&fixture.source) {
        Ok(bytes) => bytes,
        Err(err) => {
            return ConformanceTestResult {
                id: test_id.into(),
                profile: profile_id.into(),
                passed: false,
                message: Some(format!("serialize migrate source: {err}")),
            };
        }
    };
    let result = crate::plan::PortablePlan::from_json_migrating(&source_bytes);
    if let Some(expect_err) = &fixture.expect_error {
        return match result {
            Err(err) if err.contains(expect_err) => ConformanceTestResult {
                id: test_id.into(),
                profile: profile_id.into(),
                passed: true,
                message: None,
            },
            Err(err) => ConformanceTestResult {
                id: test_id.into(),
                profile: profile_id.into(),
                passed: false,
                message: Some(format!(
                    "expected error containing '{expect_err}', got '{err}'"
                )),
            },
            Ok(_) => ConformanceTestResult {
                id: test_id.into(),
                profile: profile_id.into(),
                passed: false,
                message: Some(format!(
                    "expected error containing '{expect_err}', but migration succeeded"
                )),
            },
        };
    }
    let plan = match result {
        Ok(plan) => plan,
        Err(err) => {
            return ConformanceTestResult {
                id: test_id.into(),
                profile: profile_id.into(),
                passed: false,
                message: Some(format!("migration failed: {err}")),
            };
        }
    };
    if plan.plan_identity != crate::plan::TRANSFORM_PLAN_IDENTITY {
        return ConformanceTestResult {
            id: test_id.into(),
            profile: profile_id.into(),
            passed: false,
            message: Some(format!(
                "expected planIdentity '{}', got '{}'",
                crate::plan::TRANSFORM_PLAN_IDENTITY,
                plan.plan_identity
            )),
        };
    }
    if let Some(expect_profile) = &fixture.expect_profile {
        if &plan.profile != expect_profile {
            return ConformanceTestResult {
                id: test_id.into(),
                profile: profile_id.into(),
                passed: false,
                message: Some(format!(
                    "expected profile '{expect_profile}', got '{}'",
                    plan.profile
                )),
            };
        }
    }
    if fixture.expect_error.is_none() {
        let Some(mode) = plan.error_mode.as_deref() else {
            return ConformanceTestResult {
                id: test_id.into(),
                profile: profile_id.into(),
                passed: false,
                message: Some("plan missing errorMode after migrate".into()),
            };
        };
        match plan.requirements.get("errorMode").and_then(|v| v.as_str()) {
            Some(req) if req == mode => {}
            Some(req) => {
                return ConformanceTestResult {
                    id: test_id.into(),
                    profile: profile_id.into(),
                    passed: false,
                    message: Some(format!(
                        "requirements.errorMode '{req}' != top-level errorMode '{mode}'"
                    )),
                };
            }
            None => {
                return ConformanceTestResult {
                    id: test_id.into(),
                    profile: profile_id.into(),
                    passed: false,
                    message: Some("migrated plan missing requirements.errorMode pin".into()),
                };
            }
        }
        for pin in [
            "regexGrammar",
            "formatGrammar",
            "unicodeVersion",
            "timezoneData",
            "randomAlgorithm",
        ] {
            if !plan.requirements.contains_key(pin) {
                return ConformanceTestResult {
                    id: test_id.into(),
                    profile: profile_id.into(),
                    passed: false,
                    message: Some(format!("migrated plan missing requirements.{pin} pin")),
                };
            }
        }
    }
    ConformanceTestResult {
        id: test_id.into(),
        profile: profile_id.into(),
        passed: true,
        message: None,
    }
}