Skip to main content

binoc_sdk/
types.rs

1use std::collections::BTreeMap;
2
3use serde::{Deserialize, Serialize};
4
5use crate::ir::DiffNode;
6
7// ── Artifact types ──────────────────────────────────────────────────
8
9/// Which side of a comparison an artifact describes.
10#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
11#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
12pub enum ArtifactSubject {
13    #[serde(rename = "left")]
14    Left,
15    #[serde(rename = "right")]
16    Right,
17    #[serde(rename = "pair")]
18    Pair,
19}
20
21/// Identifies an artifact's data format as a structured tuple of
22/// (package, name, version).
23///
24/// - **`package`** — the package that owns and defines this format,
25///   resolvable through the language's normal package system
26///   (e.g. `"binoc"`, `"binoc-csv"`, `"acme-parquet"`).
27/// - **`name`** — the format name within that package
28///   (e.g. `"tabular"`, `"relational-schema"`).
29/// - **`version`** — a single integer. Bump only for breaking schema
30///   changes. Adding optional fields to an existing version is fine
31///   and does not require a bump (JSON/serde naturally ignore unknown
32///   fields and default missing ones).
33#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
34#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
35pub struct ArtifactFormat {
36    pub package: String,
37    pub name: String,
38    pub version: u32,
39}
40
41impl ArtifactFormat {
42    pub fn new(package: impl Into<String>, name: impl Into<String>, version: u32) -> Self {
43        Self {
44            package: package.into(),
45            name: name.into(),
46            version,
47        }
48    }
49}
50
51impl std::fmt::Display for ArtifactFormat {
52    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
53        write!(f, "{}.{}.v{}", self.package, self.name, self.version)
54    }
55}
56
57/// Descriptor for a published artifact attached to a node.
58///
59/// Artifacts are the unified mechanism for both private reuse and
60/// cross-plugin composition. Parse rules publish artifacts; downstream rules
61/// consume them by format.
62#[derive(Debug, Clone, Serialize, Deserialize)]
63#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
64pub struct ArtifactDescriptor {
65    pub format: ArtifactFormat,
66    pub subject: ArtifactSubject,
67    pub producer: String,
68    /// Opaque handle managed by the SDK's DataAccess implementation.
69    /// Plugins should not create or interpret this value directly.
70    pub handle: String,
71}
72
73// ── Standard artifact formats ───────────────────────────────────────
74
75/// Standard format for tabular data artifacts.
76///
77/// Any parser for a tabular source format (CSV, TSV, Excel, Parquet, ...)
78/// should publish artifacts with this format so that generic tabular writers,
79/// compaction rules, and extractors can consume them without
80/// knowing the source format.
81pub fn tabular_v1() -> ArtifactFormat {
82    ArtifactFormat::new("binoc", "tabular", 1)
83}
84
85/// Standard format for a generic, format-neutral value tree.
86///
87/// Produced by parsers for tree-structured formats (JSON, JSONL of mixed shape,
88/// YAML, TOML, ...) and consumed by the structured-document writer. This is the
89/// fallback for any structured source that is not a consistently-shaped record
90/// collection. See the typed-record ADR.
91pub fn structured_document_v1() -> ArtifactFormat {
92    ArtifactFormat::new("binoc", "structured_document", 1)
93}
94
95/// Standard format for tier-3 *parser metadata* — facts a parser extracted about
96/// a node that are not the node's primary data payload: source-format identity
97/// and version, file-level properties, cross-table dictionaries, creator/tooling
98/// provenance. Rides as a second artifact on the parsed node (alongside a
99/// `tabular_v1` leaf, or on a multi-table container that has no table of its
100/// own). Consumed by format, like any artifact; carrying it is useful even with
101/// no current consumer (see the tiered-artifact-metadata ADR).
102pub fn parser_metadata_v1() -> ArtifactFormat {
103    ArtifactFormat::new("binoc", "parser_metadata", 1)
104}
105
106// ── Cell value model ────────────────────────────────────────────────
107
108static NULL_VALUE: Value = Value::Null;
109
110/// A single tabular cell value.
111///
112/// Scalars (`Null`/`Bool`/`Number`/`String`) diff by content. `Nested` holds a
113/// canonicalized object/array (object keys sorted recursively) and participates
114/// in diffs by equality only — a changed nested cell is reported as a cell edit,
115/// but binoc does not recurse into it (see the typed-record ADR). `String` cells
116/// are the all-untyped case used by CSV and other typeless sources.
117#[derive(Debug, Clone, PartialEq, Eq)]
118pub enum Value {
119    Null,
120    Bool(bool),
121    Number(serde_json::Number),
122    String(String),
123    Nested(Box<serde_json::Value>),
124}
125
126impl Value {
127    /// Build a cell value from arbitrary JSON, canonicalizing nested containers
128    /// so that equality is order-independent.
129    pub fn from_json(value: serde_json::Value) -> Self {
130        match value {
131            serde_json::Value::Null => Value::Null,
132            serde_json::Value::Bool(b) => Value::Bool(b),
133            serde_json::Value::Number(n) => Value::Number(n),
134            serde_json::Value::String(s) => Value::String(s),
135            other => Value::Nested(Box::new(canonicalize_json(other))),
136        }
137    }
138
139    /// The JSON representation of this cell, used when building edit params.
140    pub fn to_json(&self) -> serde_json::Value {
141        match self {
142            Value::Null => serde_json::Value::Null,
143            Value::Bool(b) => serde_json::Value::Bool(*b),
144            Value::Number(n) => serde_json::Value::Number(n.clone()),
145            Value::String(s) => serde_json::Value::String(s.clone()),
146            Value::Nested(v) => (**v).clone(),
147        }
148    }
149
150    /// A flat textual rendering for tokenization, CSV serialization, and scoring.
151    pub fn as_text(&self) -> std::borrow::Cow<'_, str> {
152        match self {
153            Value::Null => std::borrow::Cow::Borrowed(""),
154            Value::Bool(true) => std::borrow::Cow::Borrowed("true"),
155            Value::Bool(false) => std::borrow::Cow::Borrowed("false"),
156            Value::Number(n) => std::borrow::Cow::Owned(n.to_string()),
157            Value::String(s) => std::borrow::Cow::Borrowed(s.as_str()),
158            Value::Nested(v) => std::borrow::Cow::Owned(v.to_string()),
159        }
160    }
161
162    /// True when the value carries no content for keying/identity purposes
163    /// (null, or an empty/whitespace string).
164    pub fn is_blank(&self) -> bool {
165        match self {
166            Value::Null => true,
167            Value::String(s) => s.trim().is_empty(),
168            _ => false,
169        }
170    }
171
172    /// Feed a stable, type-tagged byte signature into a hasher (row alignment).
173    pub fn hash_into(&self, hasher: &mut blake3::Hasher) {
174        match self {
175            Value::Null => {
176                hasher.update(&[0]);
177            }
178            Value::Bool(b) => {
179                hasher.update(&[1, *b as u8]);
180            }
181            Value::Number(n) => {
182                hasher.update(&[2]);
183                hasher.update(n.to_string().as_bytes());
184            }
185            Value::String(s) => {
186                hasher.update(&[3]);
187                hasher.update(&(s.len() as u64).to_le_bytes());
188                hasher.update(s.as_bytes());
189            }
190            Value::Nested(v) => {
191                hasher.update(&[4]);
192                hasher.update(v.to_string().as_bytes());
193            }
194        }
195    }
196}
197
198impl Serialize for Value {
199    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
200        self.to_json().serialize(serializer)
201    }
202}
203
204impl<'de> Deserialize<'de> for Value {
205    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
206        Ok(Value::from_json(serde_json::Value::deserialize(
207            deserializer,
208        )?))
209    }
210}
211
212/// Recursively sort object keys so that nested-value equality is order-independent.
213fn canonicalize_json(value: serde_json::Value) -> serde_json::Value {
214    match value {
215        serde_json::Value::Array(items) => {
216            serde_json::Value::Array(items.into_iter().map(canonicalize_json).collect())
217        }
218        serde_json::Value::Object(map) => {
219            let sorted: BTreeMap<String, serde_json::Value> = map
220                .into_iter()
221                .map(|(k, v)| (k, canonicalize_json(v)))
222                .collect();
223            serde_json::Value::Object(sorted.into_iter().collect())
224        }
225        other => other,
226    }
227}
228
229// ── Format-neutral data types ───────────────────────────────────────
230
231/// Format-neutral tabular data: an ordered list of records with a shared column
232/// schema. Produced by CSV, JSON record arrays, JSONL, Excel, Parquet, DB, and
233/// other tabular parsers; consumed by tabular writers, compaction rules, and
234/// extractors.
235///
236/// This is the codec type for the [`tabular_v1`] artifact format.
237/// Serialize with `serde_json::to_vec`, deserialize with `serde_json::from_slice`.
238///
239/// The shape spectrum (rectangular?, named columns?, typed cells?) is *derived*
240/// from the data via [`TabularData::is_rectangular`],
241/// [`TabularData::has_named_columns`], and the cell `Value` variants — rules gate
242/// their behavior on those facts rather than on artifact subtypes.
243#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
244pub struct TabularData {
245    /// Column names. For headerless sources these are synthesized positional
246    /// labels and `has_header` is `false`.
247    pub headers: Vec<String>,
248    pub rows: Vec<Vec<Value>>,
249    /// Whether the source supplied real column names (CSV header, object keys).
250    #[serde(default = "default_true")]
251    pub has_header: bool,
252    /// Declared identity column names, in order. Empty when the source declares
253    /// no key; drives keyed row alignment when present.
254    #[serde(default, skip_serializing_if = "Vec::is_empty")]
255    pub key: Vec<String>,
256    /// Optional source-declared type per column (parallel to `headers`), when the
257    /// source format carries one (DB, Parquet, Stata). Empty means "none".
258    #[serde(default, skip_serializing_if = "Vec::is_empty")]
259    pub column_types: Vec<Option<String>>,
260    /// Optional per-column metadata bag (parallel to `headers`), when the source
261    /// format carries column-scoped facts a generic tabular consumer would not
262    /// otherwise see — labels, display formats, value-label set names, units.
263    /// Each entry is an open object (or `Null` for a column with no metadata).
264    /// Empty means "none". This is tier 1 of the tiered-metadata design (see the
265    /// tiered-artifact-metadata ADR): facts keyed to a *column*.
266    #[serde(default, skip_serializing_if = "Vec::is_empty")]
267    pub column_metadata: Vec<serde_json::Value>,
268    /// Optional table-scoped metadata bag — facts about *this table as a whole*
269    /// that are not per-column and not per-file (a single-table file folds its
270    /// source-format facts here; a table inside a multi-table container carries
271    /// only its own facts, e.g. dataset name/label). `Null` means "none". This
272    /// is tier 2 of the tiered-metadata design.
273    #[serde(default, skip_serializing_if = "serde_json::Value::is_null")]
274    pub table_metadata: serde_json::Value,
275}
276
277fn default_true() -> bool {
278    true
279}
280
281impl TabularData {
282    /// Construct from all-string cells (CSV and other untyped sources). Cells are
283    /// wrapped in [`Value::String`]; the result is byte-identical in behavior to
284    /// the legacy all-string tabular model.
285    pub fn from_string_rows(headers: Vec<String>, rows: Vec<Vec<String>>) -> Self {
286        Self {
287            headers,
288            rows: rows
289                .into_iter()
290                .map(|row| row.into_iter().map(Value::String).collect())
291                .collect(),
292            has_header: true,
293            key: Vec::new(),
294            column_types: Vec::new(),
295            column_metadata: Vec::new(),
296            table_metadata: serde_json::Value::Null,
297        }
298    }
299
300    /// Construct from typed rows with a named header.
301    pub fn new(headers: Vec<String>, rows: Vec<Vec<Value>>) -> Self {
302        Self {
303            headers,
304            rows,
305            has_header: true,
306            key: Vec::new(),
307            column_types: Vec::new(),
308            column_metadata: Vec::new(),
309            table_metadata: serde_json::Value::Null,
310        }
311    }
312
313    /// Attach tier-1 per-column metadata (parallel to `headers`). Builder-style
314    /// so producers can enrich a table without restating every field.
315    pub fn with_column_metadata(mut self, column_metadata: Vec<serde_json::Value>) -> Self {
316        self.column_metadata = column_metadata;
317        self
318    }
319
320    /// Attach tier-2 table-scoped metadata.
321    pub fn with_table_metadata(mut self, table_metadata: serde_json::Value) -> Self {
322        self.table_metadata = table_metadata;
323        self
324    }
325
326    pub fn column_index(&self, name: &str) -> Option<usize> {
327        self.headers.iter().position(|h| h == name)
328    }
329
330    pub fn column_values(&self, name: &str) -> Option<Vec<&Value>> {
331        let idx = self.column_index(name)?;
332        Some(
333            self.rows
334                .iter()
335                .map(|r| r.get(idx).unwrap_or(&NULL_VALUE))
336                .collect(),
337        )
338    }
339
340    /// Every row has arity equal to the column count.
341    pub fn is_rectangular(&self) -> bool {
342        let width = self.headers.len();
343        self.rows.iter().all(|row| row.len() == width)
344    }
345
346    /// The source supplied real, usable column names.
347    pub fn has_named_columns(&self) -> bool {
348        self.has_header && !self.headers.is_empty()
349    }
350
351    /// Columns can be identified across rows and snapshots — the precondition for
352    /// cell-grain and column-grain edits. Otherwise the writer degrades to
353    /// row-grain output.
354    pub fn stable_columns(&self) -> bool {
355        self.has_named_columns() || self.is_rectangular()
356    }
357
358    pub fn to_csv(&self) -> String {
359        let mut out = self.headers.join(",");
360        out.push('\n');
361        for row in &self.rows {
362            let cells: Vec<String> = row.iter().map(|v| v.as_text().into_owned()).collect();
363            out.push_str(&cells.join(","));
364            out.push('\n');
365        }
366        out
367    }
368}
369
370/// Generic format-neutral value tree. Codec type for [`structured_document_v1`].
371///
372/// All source formats transcode their content into a single `serde_json::Value`
373/// tree; `format` records the origin ("json", "yaml", "toml", ...) and `source`
374/// is an open bag of serialization facts (key order, indentation, BOM, trailing
375/// newline) that consumers ignore when unknown.
376#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
377pub struct StructuredDocument {
378    pub value: serde_json::Value,
379    pub format: String,
380    #[serde(default, skip_serializing_if = "serde_json::Value::is_null")]
381    pub source: serde_json::Value,
382}
383
384/// Codec type for [`parser_metadata_v1`] — tier-3 parser metadata.
385///
386/// `format` is the producer's source-format identity (e.g. `"stata_dta"`,
387/// `"sas7bdat"`, `"sas_xport"`), so a consumer can interpret `value` without
388/// guessing. `value` is an open bag of parser-level facts; consumers diff it
389/// generically and ignore keys they do not recognize. Deliberately flat: this
390/// is "a matching subtype for a record artifact" today, and may grow typed
391/// structure in a future version rather than via artifact-format inheritance.
392#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
393pub struct ParserMetadata {
394    pub format: String,
395    pub value: serde_json::Value,
396}
397
398impl ParserMetadata {
399    pub fn new(format: impl Into<String>, value: serde_json::Value) -> Self {
400        Self {
401            format: format.into(),
402            value,
403        }
404    }
405}
406
407// ── Dataset semantics config ───────────────────────────────────────
408
409/// SDK-owned dataset semantics section shared by plugins.
410///
411/// Hosts pass this through unchanged; plugins deserialize the parts they
412/// understand. The schema is intentionally conservative in v1.
413#[derive(Debug, Clone, Default, Serialize, Deserialize)]
414pub struct DatasetSemanticsV1 {
415    #[serde(default)]
416    pub defaults: DatasetDefaults,
417    #[serde(default)]
418    pub paths: Vec<PathConfigEntry>,
419    #[serde(default)]
420    pub files: FileIdentityConfig,
421    #[serde(default)]
422    pub correspondence: CorrespondenceConfig,
423    #[serde(default)]
424    pub reduced_precision: ReducedPrecisionConfig,
425    /// Path globs (same syntax as `paths[].match`) whose items are left out of
426    /// the comparison entirely, on both sides. Use for files that change on
427    /// every capture by construction, such as a capture manifest.
428    #[serde(default, skip_serializing_if = "Vec::is_empty")]
429    pub exclude: Vec<String>,
430}
431
432impl DatasetSemanticsV1 {
433    /// Top-level keys of the `dataset` section that the SDK schema defines.
434    /// Hosts and the stdlib use this to report unknown keys instead of
435    /// silently ignoring them.
436    pub const KNOWN_FIELDS: &'static [&'static str] = &[
437        "defaults",
438        "paths",
439        "files",
440        "correspondence",
441        "reduced_precision",
442        "exclude",
443    ];
444}
445
446#[derive(Debug, Clone, Serialize, Deserialize)]
447#[serde(deny_unknown_fields)]
448pub struct ReducedPrecisionConfig {
449    /// String sentinels that represent a suppressed published value after
450    /// reduced-precision post-processing. The empty string covers both blank
451    /// cells and `null`, preserving the historical blank/null sentinel.
452    #[serde(default = "default_suppression_sentinels")]
453    pub suppression_sentinels: Vec<String>,
454}
455
456impl Default for ReducedPrecisionConfig {
457    fn default() -> Self {
458        Self {
459            suppression_sentinels: default_suppression_sentinels(),
460        }
461    }
462}
463
464fn default_suppression_sentinels() -> Vec<String> {
465    vec!["*".into(), "(D)".into(), "(S)".into(), "".into()]
466}
467
468#[derive(Debug, Clone, Default, Serialize, Deserialize)]
469#[serde(deny_unknown_fields)]
470pub struct DatasetDefaults {
471    #[serde(default)]
472    pub row_identity: RowIdentity,
473}
474
475#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
476#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
477pub struct NodeIdentity {
478    #[serde(default, skip_serializing_if = "String::is_empty")]
479    pub key_attribute: String,
480}
481
482#[derive(Debug, Clone, Default, Serialize)]
483pub struct PathConfigEntry {
484    #[serde(default, rename = "match")]
485    pub match_: String,
486    #[serde(default, skip_serializing_if = "Option::is_none")]
487    pub content_type: Option<String>,
488    #[serde(default, skip_serializing_if = "Option::is_none")]
489    pub rule: Option<String>,
490    #[serde(default, skip_serializing_if = "Option::is_none")]
491    pub shape: Option<TabularShapeConfig>,
492    #[serde(default, skip_serializing_if = "Option::is_none")]
493    pub dialect: Option<CsvDialectConfig>,
494    #[serde(default, skip_serializing_if = "Option::is_none")]
495    pub records_path: Option<String>,
496    #[serde(default, skip_serializing_if = "Option::is_none")]
497    pub row_identity: Option<RowIdentityPatch>,
498    #[serde(default, skip_serializing_if = "Option::is_none")]
499    pub node_identity: Option<NodeIdentity>,
500    #[serde(skip)]
501    pub unknown_fields: Vec<String>,
502}
503
504impl<'de> Deserialize<'de> for PathConfigEntry {
505    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
506    where
507        D: serde::Deserializer<'de>,
508    {
509        #[derive(Default, Deserialize)]
510        struct RawPathConfigEntry {
511            #[serde(default, rename = "match")]
512            match_: String,
513            #[serde(default)]
514            content_type: Option<String>,
515            #[serde(default)]
516            rule: Option<String>,
517            #[serde(default)]
518            dialect: Option<CsvDialectConfig>,
519            #[serde(default)]
520            shape: Option<TabularShapeConfig>,
521            #[serde(default)]
522            records_path: Option<String>,
523            #[serde(default)]
524            row_identity: Option<RowIdentityPatch>,
525            #[serde(default)]
526            node_identity: Option<NodeIdentity>,
527            #[serde(flatten)]
528            extra: BTreeMap<String, serde_json::Value>,
529        }
530
531        let raw = RawPathConfigEntry::deserialize(deserializer)?;
532        Ok(Self {
533            match_: raw.match_,
534            content_type: raw.content_type,
535            rule: raw.rule,
536            dialect: raw.dialect,
537            shape: raw.shape,
538            records_path: raw.records_path,
539            row_identity: raw.row_identity,
540            node_identity: raw.node_identity,
541            unknown_fields: raw.extra.into_keys().collect(),
542        })
543    }
544}
545
546#[derive(Debug, Clone, Default, Serialize, Deserialize)]
547#[serde(deny_unknown_fields)]
548pub struct CorrespondenceConfig {
549    #[serde(default, skip_serializing_if = "Option::is_none")]
550    pub expand_renamed_unchanged_collections: Option<bool>,
551    /// Byte threshold above which stdlib tabular rules skip in-memory
552    /// `tabular_v1` materialization and use the bounded streaming keyed-writer
553    /// path instead. `None` uses the stdlib default.
554    #[serde(default, skip_serializing_if = "Option::is_none")]
555    pub large_tabular_threshold_bytes: Option<u64>,
556    /// Maximum decompressed size of a single gzip stream, in bytes. `None` uses
557    /// the stdlib default. Raise this for legitimately large `.gz` payloads;
558    /// the cap exists only as a decompression-bomb bound, so any value over a
559    /// bundle's real size is safe.
560    #[serde(default, skip_serializing_if = "Option::is_none")]
561    pub max_gzip_bytes: Option<u64>,
562    /// Maximum decompressed size of a single archive entry (one member of a
563    /// `.zip`/`.tar`/`.tgz`), in bytes. `None` uses the stdlib default.
564    #[serde(default, skip_serializing_if = "Option::is_none")]
565    pub max_archive_entry_bytes: Option<u64>,
566    /// Maximum total decompressed size of a whole archive (sum over all
567    /// extracted entries), in bytes. `None` uses the stdlib default. This is the
568    /// cap a real multi-GB government bundle is most likely to hit.
569    #[serde(default, skip_serializing_if = "Option::is_none")]
570    pub max_archive_total_bytes: Option<u64>,
571}
572
573#[derive(Debug, Clone, Default, Serialize, Deserialize)]
574#[serde(deny_unknown_fields)]
575pub struct FileIdentityConfig {
576    #[serde(default)]
577    pub correspondences: Vec<FileCorrespondenceRule>,
578}
579
580#[derive(Debug, Clone, Serialize, Deserialize)]
581pub struct FileCorrespondenceRule {
582    pub name: String,
583    #[serde(default)]
584    pub left: FileSelector,
585    #[serde(default)]
586    pub right: FileSelector,
587    pub key: String,
588    #[serde(default, skip_serializing_if = "Option::is_none")]
589    pub logical_path: Option<String>,
590    #[serde(default)]
591    pub cardinality: Cardinality,
592    #[serde(default)]
593    pub on_null_key: IdentityFailurePolicy,
594    #[serde(default)]
595    pub on_duplicate_key: IdentityFailurePolicy,
596    #[serde(default)]
597    pub report_path_change: bool,
598}
599
600#[derive(Debug, Clone, Default, Serialize, Deserialize)]
601pub struct FileSelector {
602    #[serde(default, skip_serializing_if = "Option::is_none")]
603    pub path: Option<String>,
604    #[serde(default, skip_serializing_if = "Option::is_none")]
605    pub path_regex: Option<String>,
606}
607
608#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
609#[serde(rename_all = "kebab-case")]
610pub enum Cardinality {
611    #[default]
612    OneToOne,
613}
614
615#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
616#[serde(rename_all = "snake_case")]
617pub enum IdentityFailurePolicy {
618    #[default]
619    Diagnostic,
620    Error,
621    Ignore,
622}
623
624#[derive(Debug, Clone, Serialize, Deserialize)]
625#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
626pub struct TabularParseConfig {
627    #[serde(default = "default_header")]
628    pub header: bool,
629    #[serde(default, skip_serializing_if = "Option::is_none")]
630    pub delimiter: Option<String>,
631    #[serde(default, skip_serializing_if = "Option::is_none")]
632    pub dialect: Option<CsvDialectConfig>,
633    #[serde(default, skip_serializing_if = "Option::is_none")]
634    pub header_line: Option<usize>,
635    #[serde(default, skip_serializing_if = "Option::is_none")]
636    pub skip_lines: Option<usize>,
637    /// JSON record collection path for document formats that need to expose a
638    /// nested array as the tabular record stream.
639    #[serde(default, skip_serializing_if = "Option::is_none")]
640    pub records_path: Option<String>,
641}
642
643impl Default for TabularParseConfig {
644    fn default() -> Self {
645        Self {
646            header: true,
647            delimiter: None,
648            dialect: None,
649            header_line: None,
650            skip_lines: None,
651            records_path: None,
652        }
653    }
654}
655
656fn default_header() -> bool {
657    true
658}
659
660#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
661#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
662pub struct CsvDialectConfig {
663    #[serde(default, skip_serializing_if = "Option::is_none")]
664    pub delimiter: Option<String>,
665    #[serde(default, skip_serializing_if = "Option::is_none")]
666    pub quote: Option<String>,
667    #[serde(default, skip_serializing_if = "Option::is_none")]
668    pub escape: Option<String>,
669    #[serde(default, skip_serializing_if = "Option::is_none")]
670    pub bom: Option<bool>,
671    #[serde(default, skip_serializing_if = "Option::is_none")]
672    pub newline: Option<String>,
673}
674
675#[derive(Debug, Clone, Default, Serialize, Deserialize)]
676#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
677pub struct TabularShapeConfig {
678    #[serde(default, skip_serializing_if = "Option::is_none")]
679    pub has_header: Option<bool>,
680    #[serde(default, skip_serializing_if = "Option::is_none")]
681    pub header_line: Option<usize>,
682    #[serde(default, skip_serializing_if = "Option::is_none")]
683    pub skip_lines: Option<usize>,
684}
685
686impl TabularShapeConfig {
687    pub fn apply_to_parse_config(&self, parse: &mut TabularParseConfig) {
688        if let Some(has_header) = self.has_header {
689            parse.header = has_header;
690        }
691        if let Some(header_line) = self.header_line {
692            parse.header_line = Some(header_line);
693        }
694        if let Some(skip_lines) = self.skip_lines {
695            parse.skip_lines = Some(skip_lines);
696        }
697    }
698}
699
700#[derive(Debug, Clone, Default, Serialize, Deserialize)]
701pub struct RowIdentity {
702    #[serde(default)]
703    pub columns: Vec<String>,
704    #[serde(default)]
705    pub by_position: Vec<usize>,
706    #[serde(default)]
707    pub cardinality: Cardinality,
708    #[serde(default)]
709    pub on_null_key: IdentityFailurePolicy,
710    #[serde(default)]
711    pub on_duplicate_key: IdentityFailurePolicy,
712}
713
714/// Presence-preserving row-identity overrides for a selected path.
715///
716/// Runtime identities and dataset defaults use [`RowIdentity`]. Entry-level
717/// configuration uses this patch type so an explicitly configured default
718/// enum value is distinguishable from an omitted field. `columns` and
719/// `by_position` are alternate key selectors; when both are present,
720/// `columns` takes precedence.
721#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
722pub struct RowIdentityPatch {
723    #[serde(default, skip_serializing_if = "Option::is_none")]
724    pub columns: Option<Vec<String>>,
725    #[serde(default, skip_serializing_if = "Option::is_none")]
726    pub by_position: Option<Vec<usize>>,
727    #[serde(default, skip_serializing_if = "Option::is_none")]
728    pub cardinality: Option<Cardinality>,
729    #[serde(default, skip_serializing_if = "Option::is_none")]
730    pub on_null_key: Option<IdentityFailurePolicy>,
731    #[serde(default, skip_serializing_if = "Option::is_none")]
732    pub on_duplicate_key: Option<IdentityFailurePolicy>,
733}
734
735impl RowIdentityPatch {
736    /// Apply this entry-level override to a concrete inherited identity.
737    pub fn apply_to(&self, identity: &mut RowIdentity) {
738        if let Some(columns) = &self.columns {
739            identity.columns = columns.clone();
740            identity.by_position.clear();
741        } else if let Some(by_position) = &self.by_position {
742            identity.by_position = by_position.clone();
743            identity.columns.clear();
744        }
745        if let Some(cardinality) = self.cardinality {
746            identity.cardinality = cardinality;
747        }
748        if let Some(policy) = self.on_null_key {
749            identity.on_null_key = policy;
750        }
751        if let Some(policy) = self.on_duplicate_key {
752            identity.on_duplicate_key = policy;
753        }
754    }
755
756    pub fn has_key_selector(&self) -> bool {
757        self.columns
758            .as_ref()
759            .is_some_and(|columns| !columns.is_empty())
760            || self
761                .by_position
762                .as_ref()
763                .is_some_and(|positions| !positions.is_empty())
764    }
765}
766
767/// A pair of tabular data (left/right sides of a comparison).
768#[derive(Debug, Clone, Serialize, Deserialize)]
769pub struct TabularDataPair {
770    pub left: Option<TabularData>,
771    pub right: Option<TabularData>,
772}
773
774impl TabularDataPair {
775    /// Build a `TabularDataPair` from [`tabular_v1`] artifacts on a node.
776    ///
777    /// Returns `None` if neither left nor right artifact is present.
778    /// This is the standard way for rules and extractors to obtain
779    /// tabular data without knowing the source format.
780    pub fn from_artifacts(
781        node: &crate::ir::DiffNode,
782        data: &dyn crate::traits::DataAccess,
783    ) -> Option<Self> {
784        let fmt = tabular_v1();
785        let left = node
786            .artifacts
787            .iter()
788            .find(|a| a.format == fmt && a.subject == ArtifactSubject::Left)
789            .and_then(|desc| data.get_artifact(desc).ok()?)
790            .and_then(|bytes| serde_json::from_slice(&bytes).ok());
791        let right = node
792            .artifacts
793            .iter()
794            .find(|a| a.format == fmt && a.subject == ArtifactSubject::Right)
795            .and_then(|desc| data.get_artifact(desc).ok()?)
796            .and_then(|bytes| serde_json::from_slice(&bytes).ok());
797        if left.is_none() && right.is_none() {
798            return None;
799        }
800        Some(Self { left, right })
801    }
802}
803
804// ── Tabular extraction ──────────────────────────────────────────────
805
806/// Shared extraction logic for tabular data.
807///
808/// Given a `TabularDataPair` and an aspect name, produces the
809/// corresponding `ExtractResult`. This is format-neutral — any
810/// writer or compatibility plugin that works with tabular artifacts can
811/// delegate extraction here.
812pub fn tabular_extract(
813    pair: &TabularDataPair,
814    _node: &DiffNode,
815    aspect: &str,
816) -> Option<ExtractResult> {
817    match aspect {
818        "rows_added" => {
819            let right = pair.right.as_ref()?;
820            let left_len = pair.left.as_ref().map_or(0, |l| l.rows.len());
821            if left_len >= right.rows.len() {
822                return Some(ExtractResult::Text("No rows added.\n".into()));
823            }
824            let added = TabularData::new(right.headers.clone(), right.rows[left_len..].to_vec());
825            Some(ExtractResult::Text(added.to_csv()))
826        }
827        "rows_removed" => {
828            let left = pair.left.as_ref()?;
829            let right_len = pair.right.as_ref().map_or(0, |r| r.rows.len());
830            if right_len >= left.rows.len() {
831                return Some(ExtractResult::Text("No rows removed.\n".into()));
832            }
833            let removed = TabularData::new(left.headers.clone(), left.rows[right_len..].to_vec());
834            Some(ExtractResult::Text(removed.to_csv()))
835        }
836        "cells_changed" => {
837            let left = pair.left.as_ref()?;
838            let right = pair.right.as_ref()?;
839            let common_cols = tabular_columns_in_common(left, right);
840            let min_rows = left.rows.len().min(right.rows.len());
841
842            let mut out = String::from("row,column,old_value,new_value\n");
843            for i in 0..min_rows {
844                for col in &common_cols {
845                    let li = left.column_index(col)?;
846                    let ri = right.column_index(col)?;
847                    let lv = left.rows[i].get(li).unwrap_or(&NULL_VALUE);
848                    let rv = right.rows[i].get(ri).unwrap_or(&NULL_VALUE);
849                    if lv != rv {
850                        out.push_str(&format!("{i},{col},{},{}\n", lv.as_text(), rv.as_text()));
851                    }
852                }
853            }
854            Some(ExtractResult::Text(out))
855        }
856        "columns_added" => {
857            let left = pair.left.as_ref()?;
858            let right = pair.right.as_ref()?;
859            let left_set: std::collections::BTreeSet<&str> =
860                left.headers.iter().map(|s| s.as_str()).collect();
861            let added: Vec<&str> = right
862                .headers
863                .iter()
864                .filter(|h| !left_set.contains(h.as_str()))
865                .map(|h| h.as_str())
866                .collect();
867            if added.is_empty() {
868                return Some(ExtractResult::Text("No columns added.\n".into()));
869            }
870            let mut out = String::new();
871            for col in &added {
872                out.push_str(&format!("{col}\n"));
873                if let Some(vals) = right.column_values(col) {
874                    for val in vals {
875                        out.push_str(&format!("  {}\n", val.as_text()));
876                    }
877                }
878            }
879            Some(ExtractResult::Text(out))
880        }
881        "columns_removed" => {
882            let left = pair.left.as_ref()?;
883            let right = pair.right.as_ref()?;
884            let right_set: std::collections::BTreeSet<&str> =
885                right.headers.iter().map(|s| s.as_str()).collect();
886            let removed: Vec<&str> = left
887                .headers
888                .iter()
889                .filter(|h| !right_set.contains(h.as_str()))
890                .map(|h| h.as_str())
891                .collect();
892            if removed.is_empty() {
893                return Some(ExtractResult::Text("No columns removed.\n".into()));
894            }
895            let mut out = String::new();
896            for col in &removed {
897                out.push_str(&format!("{col}\n"));
898                if let Some(vals) = left.column_values(col) {
899                    for val in vals {
900                        out.push_str(&format!("  {}\n", val.as_text()));
901                    }
902                }
903            }
904            Some(ExtractResult::Text(out))
905        }
906        "content" | "full" => {
907            let mut out = String::new();
908            if let Some(left) = &pair.left {
909                out.push_str("--- left\n");
910                out.push_str(&left.to_csv());
911            }
912            if let Some(right) = &pair.right {
913                out.push_str("+++ right\n");
914                out.push_str(&right.to_csv());
915            }
916            Some(ExtractResult::Text(out))
917        }
918        _ => None,
919    }
920}
921
922/// Keyed variant of [`tabular_extract`] for `rows_added`, `rows_removed`, and
923/// `cells_changed`: rows are matched by the values of `key_columns` instead of
924/// by position, so the result agrees with a keyed changeset. Returns `None`
925/// (letting the caller fall back to [`tabular_extract`]) when `key_columns` is
926/// empty, a key column is missing on either side, or the aspect is not one of
927/// those three.
928///
929/// A key that appears more than once on one side cannot be matched
930/// unambiguously; its rows are never reported as changed cells, and they
931/// count as added or removed only when the key is absent from the other side.
932pub fn tabular_extract_keyed(
933    pair: &TabularDataPair,
934    key_columns: &[String],
935    aspect: &str,
936) -> Option<ExtractResult> {
937    if key_columns.is_empty() || !matches!(aspect, "rows_added" | "rows_removed" | "cells_changed")
938    {
939        return None;
940    }
941    let empty = TabularData::new(Vec::new(), Vec::new());
942    let left = pair.left.as_ref().unwrap_or(&empty);
943    let right = pair.right.as_ref().unwrap_or(&empty);
944    let key_indexes = |table: &TabularData| -> Option<Vec<usize>> {
945        if table.headers.is_empty() {
946            return Some(Vec::new());
947        }
948        key_columns
949            .iter()
950            .map(|col| table.column_index(col))
951            .collect()
952    };
953    let left_idx = key_indexes(left)?;
954    let right_idx = key_indexes(right)?;
955    let key_of = |row: &[Value], idx: &[usize]| -> Vec<String> {
956        idx.iter()
957            .map(|&i| row.get(i).unwrap_or(&NULL_VALUE).as_text().into_owned())
958            .collect()
959    };
960    let mut left_rows: std::collections::BTreeMap<Vec<String>, Vec<&Vec<Value>>> =
961        Default::default();
962    for row in &left.rows {
963        left_rows
964            .entry(key_of(row, &left_idx))
965            .or_default()
966            .push(row);
967    }
968    let mut right_rows: std::collections::BTreeMap<Vec<String>, Vec<&Vec<Value>>> =
969        Default::default();
970    for row in &right.rows {
971        right_rows
972            .entry(key_of(row, &right_idx))
973            .or_default()
974            .push(row);
975    }
976
977    let unmatched = |table: &TabularData,
978                     idx: &[usize],
979                     other: &std::collections::BTreeMap<Vec<String>, Vec<&Vec<Value>>>,
980                     none: &str| {
981        let rows: Vec<Vec<Value>> = table
982            .rows
983            .iter()
984            .filter(|row| !other.contains_key(&key_of(row, idx)))
985            .cloned()
986            .collect();
987        if rows.is_empty() {
988            ExtractResult::Text(none.into())
989        } else {
990            ExtractResult::Text(TabularData::new(table.headers.clone(), rows).to_csv())
991        }
992    };
993
994    match aspect {
995        "rows_added" => Some(unmatched(right, &right_idx, &left_rows, "No rows added.\n")),
996        "rows_removed" => Some(unmatched(
997            left,
998            &left_idx,
999            &right_rows,
1000            "No rows removed.\n",
1001        )),
1002        _ => {
1003            let common_cols = tabular_columns_in_common(left, right);
1004            let mut out_rows = Vec::new();
1005            for (key, lrows) in &left_rows {
1006                let (Some(rrows), [lrow]) = (right_rows.get(key), lrows.as_slice()) else {
1007                    continue;
1008                };
1009                let [rrow] = rrows.as_slice() else {
1010                    continue;
1011                };
1012                for col in &common_cols {
1013                    let lv = lrow.get(left.column_index(col)?).unwrap_or(&NULL_VALUE);
1014                    let rv = rrow.get(right.column_index(col)?).unwrap_or(&NULL_VALUE);
1015                    if lv != rv {
1016                        out_rows.push(vec![
1017                            Value::String(key.join("|")),
1018                            Value::String(col.clone()),
1019                            lv.clone(),
1020                            rv.clone(),
1021                        ]);
1022                    }
1023                }
1024            }
1025            let headers = ["key", "column", "old_value", "new_value"]
1026                .map(String::from)
1027                .to_vec();
1028            Some(ExtractResult::Text(
1029                TabularData::new(headers, out_rows).to_csv(),
1030            ))
1031        }
1032    }
1033}
1034
1035fn tabular_columns_in_common(left: &TabularData, right: &TabularData) -> Vec<String> {
1036    let left_set: std::collections::BTreeSet<&str> =
1037        left.headers.iter().map(|s| s.as_str()).collect();
1038    right
1039        .headers
1040        .iter()
1041        .filter(|h| left_set.contains(h.as_str()))
1042        .cloned()
1043        .collect()
1044}
1045
1046// ── Item types ──────────────────────────────────────────────────────
1047
1048/// Metadata-only view of one side of a comparison. Carries logical identity
1049/// and content metadata but NOT a filesystem path — data access goes through
1050/// `DataAccess`.
1051///
1052/// # Metadata invariants
1053///
1054/// `content_hash`, `size`, and `media_type` are **opportunistic hints**.
1055/// Producers (expand rules like directory/zip, or data backends)
1056/// populate them when doing so is cheap — typically as a byproduct of work
1057/// they were already performing. Consumers **must not assume presence**, but
1058/// **may trust presence**: when a field is set, the value accurately reflects
1059/// the current bytes. Use [`ItemRef::resolve_hash`] / [`ItemRef::resolve_size`]
1060/// to obtain a value with a transparent fall-back read.
1061///
1062/// This keeps fast paths (directory-only listings, short-circuit identical
1063/// detection) cheap while letting consumers that need a value — most notably
1064/// the move detector, which correlates leaves across container boundaries —
1065/// hydrate on demand.
1066#[derive(Debug, Clone, Serialize, Deserialize)]
1067#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
1068pub struct ItemRef {
1069    /// User-meaningful location within a snapshot. `/>` marks a
1070    /// decompose boundary; a literal segment beginning with `>` is escaped
1071    /// as `\>`.
1072    pub logical_path: String,
1073    pub is_dir: bool,
1074    #[serde(default, skip_serializing_if = "Option::is_none")]
1075    pub content_hash: Option<String>,
1076    #[serde(default, skip_serializing_if = "Option::is_none")]
1077    pub size: Option<u64>,
1078    #[serde(default, skip_serializing_if = "Option::is_none")]
1079    pub media_type: Option<String>,
1080    /// Optional projection metadata supplied by rule packs while they still
1081    /// know the vocabulary. Core carries this through but does not interpret
1082    /// file names, media types, or plugin-specific tags.
1083    #[serde(default, skip_serializing_if = "crate::projection_hint_is_default")]
1084    pub projection_hint: crate::ProjectionHint,
1085    /// Optional stdlib-resolved tabular parse hints carried from dataset config
1086    /// to whichever tabular parser eventually claims this item.
1087    #[serde(default, skip_serializing_if = "Option::is_none")]
1088    pub tabular_parse: Option<TabularParseConfig>,
1089    /// Opaque identifier used by DataAccess implementations to locate data.
1090    /// Plugin authors should not create or interpret this value directly.
1091    #[serde(default)]
1092    pub handle: String,
1093}
1094
1095impl ItemRef {
1096    pub fn extension(&self) -> Option<String> {
1097        std::path::Path::new(&self.logical_path)
1098            .extension()
1099            .map(|e| format!(".{}", e.to_string_lossy().to_lowercase()))
1100    }
1101
1102    /// Return the item's BLAKE3 content hash, computing it from bytes if
1103    /// not already cached on this `ItemRef`. Never valid for directories.
1104    pub fn resolve_hash(&self, data: &dyn crate::DataAccess) -> crate::BinocResult<String> {
1105        if let Some(hash) = &self.content_hash {
1106            return Ok(hash.clone());
1107        }
1108        let mut reader = data.open_read(self)?;
1109        let mut hasher = blake3::Hasher::new();
1110        std::io::copy(&mut reader, &mut hasher)?;
1111        Ok(hasher.finalize().to_hex().to_string())
1112    }
1113
1114    /// Return the item's byte length, reading from the backend if not already
1115    /// cached on this `ItemRef`. Never valid for directories.
1116    pub fn resolve_size(&self, data: &dyn crate::DataAccess) -> crate::BinocResult<u64> {
1117        if let Some(size) = self.size {
1118            return Ok(size);
1119        }
1120        let bytes = data.read_bytes(self)?;
1121        Ok(bytes.len() as u64)
1122    }
1123}
1124
1125/// A pair of items to compare. Either side may be None (add/remove).
1126#[derive(Debug, Clone, Serialize, Deserialize)]
1127#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
1128pub struct ItemPair {
1129    pub left: Option<ItemRef>,
1130    pub right: Option<ItemRef>,
1131}
1132
1133impl ItemPair {
1134    pub fn both(left: ItemRef, right: ItemRef) -> Self {
1135        Self {
1136            left: Some(left),
1137            right: Some(right),
1138        }
1139    }
1140
1141    pub fn added(right: ItemRef) -> Self {
1142        Self {
1143            left: None,
1144            right: Some(right),
1145        }
1146    }
1147
1148    pub fn removed(left: ItemRef) -> Self {
1149        Self {
1150            left: Some(left),
1151            right: None,
1152        }
1153    }
1154
1155    pub fn logical_path(&self) -> &str {
1156        self.right
1157            .as_ref()
1158            .or(self.left.as_ref())
1159            .map(|i| i.logical_path.as_str())
1160            .unwrap_or("")
1161    }
1162
1163    pub fn extension(&self) -> Option<String> {
1164        self.right
1165            .as_ref()
1166            .or(self.left.as_ref())
1167            .and_then(|i| i.extension())
1168    }
1169
1170    pub fn media_type(&self) -> Option<&str> {
1171        self.right
1172            .as_ref()
1173            .or(self.left.as_ref())
1174            .and_then(|i| i.media_type.as_deref())
1175    }
1176
1177    pub fn is_dir(&self) -> bool {
1178        self.right.as_ref().is_some_and(|i| i.is_dir)
1179            || self.left.as_ref().is_some_and(|i| i.is_dir)
1180    }
1181
1182    pub fn matching_content_hash(&self) -> Option<&str> {
1183        match (&self.left, &self.right) {
1184            (Some(l), Some(r)) => match (&l.content_hash, &r.content_hash) {
1185                (Some(hl), Some(hr)) if hl == hr => Some(hl.as_str()),
1186                _ => None,
1187            },
1188            _ => None,
1189        }
1190    }
1191}
1192
1193/// Result of an extract (on-demand detail retrieval) operation.
1194pub enum ExtractResult {
1195    Text(String),
1196    Binary(Vec<u8>),
1197}
1198
1199#[cfg(test)]
1200mod tests {
1201    use super::*;
1202
1203    fn bare_item(logical: &str, is_dir: bool) -> ItemRef {
1204        ItemRef {
1205            logical_path: logical.into(),
1206            is_dir,
1207            content_hash: None,
1208            size: None,
1209            media_type: None,
1210            projection_hint: Default::default(),
1211            tabular_parse: None,
1212            handle: String::new(),
1213        }
1214    }
1215
1216    #[test]
1217    fn item_ref_extension() {
1218        let item = bare_item("data.csv", false);
1219        assert_eq!(item.extension(), Some(".csv".into()));
1220    }
1221
1222    #[test]
1223    fn item_ref_extension_none() {
1224        let item = bare_item("Makefile", false);
1225        assert_eq!(item.extension(), None);
1226    }
1227
1228    #[test]
1229    fn item_pair_logical_path_prefers_right() {
1230        let left = bare_item("left.txt", false);
1231        let right = bare_item("right.txt", false);
1232        let pair = ItemPair::both(left, right);
1233        assert_eq!(pair.logical_path(), "right.txt");
1234    }
1235
1236    #[test]
1237    fn item_pair_logical_path_falls_back_to_left() {
1238        let left = bare_item("only.txt", false);
1239        let pair = ItemPair::removed(left);
1240        assert_eq!(pair.logical_path(), "only.txt");
1241    }
1242
1243    #[test]
1244    fn item_pair_is_dir() {
1245        let dir = bare_item("sub", true);
1246        let pair = ItemPair::added(dir);
1247        assert!(pair.is_dir());
1248    }
1249
1250    #[test]
1251    fn item_pair_matching_hash() {
1252        let mut left = bare_item("f", false);
1253        left.content_hash = Some("abc".into());
1254        let mut right = bare_item("f", false);
1255        right.content_hash = Some("abc".into());
1256        let pair = ItemPair::both(left, right);
1257        assert_eq!(pair.matching_content_hash(), Some("abc"));
1258    }
1259
1260    #[test]
1261    fn row_identity_patch_deserialization_preserves_explicit_default_policy() {
1262        let semantics: DatasetSemanticsV1 = serde_json::from_value(serde_json::json!({
1263            "paths": [{
1264                "match": "data.csv",
1265                "row_identity": {
1266                    "columns": ["id"],
1267                    "on_null_key": "diagnostic"
1268                }
1269            }]
1270        }))
1271        .expect("dataset semantics");
1272
1273        let patch = semantics.paths[0]
1274            .row_identity
1275            .as_ref()
1276            .expect("row identity patch");
1277        assert_eq!(
1278            patch.columns.as_deref(),
1279            Some([String::from("id")].as_slice())
1280        );
1281        assert_eq!(patch.on_null_key, Some(IdentityFailurePolicy::Diagnostic));
1282        assert_eq!(patch.on_duplicate_key, None);
1283
1284        let serialized = serde_json::to_value(&semantics.paths[0]).expect("serialize path entry");
1285        assert_eq!(serialized["row_identity"]["on_null_key"], "diagnostic");
1286        assert!(serialized["row_identity"].get("on_duplicate_key").is_none());
1287    }
1288
1289    #[test]
1290    fn row_identity_patch_replaces_inherited_key_selector() {
1291        let mut identity = RowIdentity {
1292            columns: vec!["id".into()],
1293            on_null_key: IdentityFailurePolicy::Error,
1294            ..RowIdentity::default()
1295        };
1296        RowIdentityPatch {
1297            by_position: Some(vec![2]),
1298            on_null_key: Some(IdentityFailurePolicy::Diagnostic),
1299            ..RowIdentityPatch::default()
1300        }
1301        .apply_to(&mut identity);
1302
1303        assert!(identity.columns.is_empty());
1304        assert_eq!(identity.by_position, vec![2]);
1305        assert_eq!(identity.on_null_key, IdentityFailurePolicy::Diagnostic);
1306
1307        RowIdentityPatch {
1308            columns: Some(vec!["email".into()]),
1309            ..RowIdentityPatch::default()
1310        }
1311        .apply_to(&mut identity);
1312        assert_eq!(identity.columns, vec!["email"]);
1313        assert!(identity.by_position.is_empty());
1314    }
1315}