copybook-codec 0.4.3

Deterministic COBOL copybook codec for EBCDIC/ASCII fixed and RDW records.
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
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
// SPDX-License-Identifier: AGPL-3.0-or-later
//! ODO and REDEFINES error handling with comprehensive validation
//!
//! This module implements the normative error handling behavior for ODO (OCCURS DEPENDING ON)
//! and REDEFINES clauses, including strict vs lenient mode handling and comprehensive
//! validation with proper error context.

use crate::options::{DecodeOptions, EncodeOptions};
#[cfg(test)]
use copybook_core::Occurs;
use copybook_core::{Error, ErrorCode, ErrorContext, Field, Result, Schema};
use serde_json::Value;
use std::collections::HashMap;
use tracing::{debug, warn};

/// ODO validation result
#[derive(Debug, Clone)]
pub struct OdoValidationResult {
    /// Actual count to use (clamped if necessary)
    pub actual_count: u32,
    /// Whether clamping occurred
    pub was_clamped: bool,
    /// Warning to report if clamping occurred
    pub warning: Option<Error>,
}

/// REDEFINES encoding context for ambiguity detection
#[derive(Debug, Clone)]
pub struct RedefinesContext {
    /// Map of cluster paths to their non-null views
    pub cluster_views: HashMap<String, Vec<String>>,
    /// Map of field paths to their cluster root
    pub field_to_cluster: HashMap<String, String>,
}

/// Validate ODO counter value with strict/lenient mode handling (NORMATIVE)
///
/// In lenient mode: clamp out-of-bounds counter to min/max with warnings
/// In strict mode: treat out-of-bounds ODO as fatal error and abort immediately
///
/// # Errors
/// Returns an error when the counter is out of bounds in strict mode or cannot be safely clamped in lenient mode.
#[allow(clippy::too_many_arguments)]
#[inline]
#[must_use = "Handle the Result or propagate the error"]
pub fn validate_odo_counter(
    counter_value: u32,
    min_count: u32,
    max_count: u32,
    field_path: &str,
    counter_path: &str,
    record_index: u64,
    byte_offset: u64,
    strict_mode: bool,
) -> Result<OdoValidationResult> {
    debug!(
        "Validating ODO counter: value={}, min={}, max={}, field={}, counter={}, record={}, strict={}",
        counter_value, min_count, max_count, field_path, counter_path, record_index, strict_mode
    );

    // Check if value is within bounds
    if counter_value >= min_count && counter_value <= max_count {
        return Ok(OdoValidationResult {
            actual_count: counter_value,
            was_clamped: false,
            warning: None,
        });
    }

    // Value is out of bounds - handle based on mode
    if strict_mode {
        // In strict mode, ODO out-of-bounds is fatal (NORMATIVE)
        let error_msg = if counter_value < min_count {
            format!(
                "ODO counter value {counter_value} is below minimum {min_count} for array '{field_path}'"
            )
        } else {
            format!(
                "ODO counter value {counter_value} exceeds maximum {max_count} for array '{field_path}'"
            )
        };

        return Err(
            Error::new(ErrorCode::CBKS301_ODO_CLIPPED, error_msg).with_context(ErrorContext {
                record_index: Some(record_index),
                field_path: Some(field_path.to_string()),
                byte_offset: Some(byte_offset),
                line_number: None,
                details: Some(format!(
                    "counter_field={counter_path}, counter_value={counter_value}"
                )),
            }),
        );
    }

    // In lenient mode, clamp and warn (NORMATIVE)
    let (actual_count, error_code, action) = if counter_value < min_count {
        (
            min_count,
            ErrorCode::CBKS302_ODO_RAISED,
            "raised to minimum",
        )
    } else {
        (
            max_count,
            ErrorCode::CBKS301_ODO_CLIPPED,
            "clipped to maximum",
        )
    };

    let warning = Error::new(
        error_code,
        format!(
            "ODO counter value {counter_value} {action} {actual_count} for array '{field_path}' (was {counter_value})"
        ),
    )
    .with_context(ErrorContext {
        record_index: Some(record_index),
        field_path: Some(field_path.to_string()),
        byte_offset: Some(byte_offset),
        line_number: None,
        details: Some(format!(
            "counter_field={counter_path}, original_value={counter_value}, clamped_value={actual_count}"
        )),
    });

    warn!("{}", warning);

    Ok(OdoValidationResult {
        actual_count,
        was_clamped: true,
        warning: Some(warning),
    })
}

/// Validate ODO tail position constraints (NORMATIVE)
///
/// Ensures that ODO arrays are only at the tail position of their containing group
/// and that counter fields are not inside REDEFINES or ODO regions.
///
/// # Errors
/// Returns an error if ODO constraints are violated.
#[cfg(test)]
#[inline]
#[must_use = "Handle the Result or propagate the error"]
pub fn validate_odo_tail_position(
    schema: &Schema,
    odo_field_path: &str,
    counter_field_path: &str,
) -> Result<()> {
    debug!(
        "Validating ODO tail position: array={}, counter={}",
        odo_field_path, counter_field_path
    );

    // Find the ODO field and its parent group
    let odo_field = schema.find_field(odo_field_path).ok_or_else(|| {
        Error::new(
            ErrorCode::CBKS121_COUNTER_NOT_FOUND,
            format!("ODO array field '{odo_field_path}' not found in schema"),
        )
    })?;

    // Validate that the field actually has ODO
    match &odo_field.occurs {
        Some(Occurs::ODO {
            min: _,
            max: _,
            counter_path: _,
        }) => (),
        _ => {
            return Err(Error::new(
                ErrorCode::CBKP021_ODO_NOT_TAIL,
                format!("Field '{odo_field_path}' is not an ODO array"),
            ));
        }
    }

    // Find the counter field
    let counter_field = schema.find_field(counter_field_path).ok_or_else(|| {
        Error::new(
            ErrorCode::CBKS121_COUNTER_NOT_FOUND,
            format!("ODO counter field '{counter_field_path}' not found in schema"),
        )
    })?;

    // Validate counter precedes array in byte order
    if counter_field.offset >= odo_field.offset {
        return Err(Error::new(
            ErrorCode::CBKP021_ODO_NOT_TAIL,
            format!(
                "ODO counter '{counter_field_path}' (offset {}) must precede array '{odo_field_path}' (offset {}) in byte order",
                counter_field.offset, odo_field.offset
            ),
        ));
    }

    // Additional validation: check if counter is in a REDEFINES region
    if counter_field.redefines_of.is_some() {
        return Err(Error::new(
            ErrorCode::CBKS121_COUNTER_NOT_FOUND,
            format!("ODO counter field '{counter_field_path}' cannot be inside a REDEFINES region"),
        ));
    }

    // Check if counter is inside another ODO region (simplified check)
    // This would require more complex parent traversal in a full implementation
    debug!(
        "ODO tail position validation passed for array '{}' with counter '{}'",
        odo_field_path, counter_field_path
    );

    Ok(())
}

/// Build REDEFINES context for encoding ambiguity detection
///
/// Analyzes the JSON data to identify which views under each REDEFINES cluster
/// have non-null values, enabling proper ambiguity detection during encoding.
pub fn build_redefines_context(schema: &Schema, json_data: &Value) -> RedefinesContext {
    let mut context = RedefinesContext {
        cluster_views: HashMap::new(),
        field_to_cluster: HashMap::new(),
    };

    // Collect all REDEFINES relationships from schema
    collect_redefines_relationships(schema, &mut context);

    // Analyze JSON data to find non-null views
    if let Value::Object(obj) = json_data {
        analyze_json_for_redefines(&mut context, obj);
    }

    debug!(
        "Built REDEFINES context: {} clusters, {} field mappings",
        context.cluster_views.len(),
        context.field_to_cluster.len()
    );

    context
}

/// Validate REDEFINES encoding for ambiguity (NORMATIVE)
///
/// Implements the normative REDEFINES encode precedence:
/// 1. If --use-raw and record-level `__raw_b64` present and values match canonical decode → emit raw bytes
/// 2. Else if exactly one view under the cluster is non-null → emit from that view
/// 3. Else → error `CBKE501_JSON_TYPE_MISMATCH` (ambiguous write)
///
/// # Errors
/// Returns `CBKE501_JSON_TYPE_MISMATCH` with cluster path context for ambiguous writes.
#[inline]
#[must_use = "Handle the Result or propagate the error"]
pub fn validate_redefines_encoding(
    context: &RedefinesContext,
    cluster_path: &str,
    field_path: &str,
    json_data: &Value,
    use_raw: bool,
    record_index: u64,
    byte_offset: u64,
) -> Result<()> {
    debug!(
        "Validating REDEFINES encoding: cluster={}, field={}, use_raw={}",
        cluster_path, field_path, use_raw
    );

    // Check for raw data precedence (step 1)
    if use_raw
        && let Value::Object(obj) = json_data
        && let Some(Value::String(_)) = obj.get("__raw_b64")
    {
        debug!("Using raw data for REDEFINES cluster '{}'", cluster_path);
        return Ok(());
    }

    // Check for single non-null view (step 2)
    let non_null_views = context
        .cluster_views
        .get(cluster_path)
        .map_or(0, std::vec::Vec::len);

    if non_null_views == 0 {
        return Err(Error::new(
            ErrorCode::CBKE501_JSON_TYPE_MISMATCH,
            format!("No non-null views found for REDEFINES cluster '{cluster_path}'"),
        )
        .with_context(ErrorContext {
            record_index: Some(record_index),
            field_path: Some(field_path.to_string()),
            byte_offset: Some(byte_offset),
            line_number: None,
            details: Some(format!("cluster_path={cluster_path}")),
        }));
    }

    if non_null_views == 1 {
        debug!(
            "Single non-null view found for REDEFINES cluster '{}'",
            cluster_path
        );
        return Ok(());
    }

    // Multiple non-null views - ambiguous write (step 3)
    let views_list = context
        .cluster_views
        .get(cluster_path)
        .map_or_else(|| "unknown".to_string(), |views| views.join(", "));

    Err(Error::new(
        ErrorCode::CBKE501_JSON_TYPE_MISMATCH,
        format!(
            "Ambiguous REDEFINES write: multiple non-null views ({views_list}) for cluster '{cluster_path}'"
        ),
    )
    .with_context(ErrorContext {
        record_index: Some(record_index),
        field_path: Some(field_path.to_string()),
        byte_offset: Some(byte_offset),
        line_number: None,
        details: Some(format!(
            "cluster_path={cluster_path}, non_null_views={non_null_views}"
        )),
    }))
}

/// Handle missing ODO counter field references
///
/// Provides comprehensive error reporting when ODO counter fields cannot be found,
/// including suggestions for common naming issues.
///
/// # Errors
/// Returns `CBKS121_COUNTER_NOT_FOUND` with detailed context and suggestions.
pub fn handle_missing_counter_field(
    counter_path: &str,
    array_path: &str,
    schema: &Schema,
    record_index: u64,
    byte_offset: u64,
) -> Error {
    debug!(
        "Handling missing counter field: counter={}, array={}",
        counter_path, array_path
    );

    // Try to find similar field names for suggestions
    let all_fields = schema.all_fields();
    let mut suggestions = Vec::new();

    for field in all_fields {
        if field.path.contains(counter_path) || counter_path.contains(&field.name) {
            suggestions.push(field.path.clone());
        }
    }

    let details = if suggestions.is_empty() {
        format!("array_field={array_path}, searched_paths=all_schema_fields")
    } else {
        format!(
            "array_field={array_path}, similar_fields=[{}]",
            suggestions.join(", ")
        )
    };

    Error::new(
        ErrorCode::CBKS121_COUNTER_NOT_FOUND,
        format!(
            "ODO counter field '{counter_path}' not found for array '{array_path}'. {}",
            if suggestions.is_empty() {
                "No similar field names found in schema."
            } else {
                "Did you mean one of the similar fields listed in details?"
            }
        ),
    )
    .with_context(ErrorContext {
        record_index: Some(record_index),
        field_path: Some(array_path.to_string()),
        byte_offset: Some(byte_offset),
        line_number: None,
        details: Some(details),
    })
}

/// Collect REDEFINES relationships from schema
fn collect_redefines_relationships(schema: &Schema, context: &mut RedefinesContext) {
    collect_redefines_from_fields(&schema.fields, context);
}

/// Recursively collect REDEFINES relationships from fields
fn collect_redefines_from_fields(fields: &[Field], context: &mut RedefinesContext) {
    for field in fields {
        if let Some(ref target) = field.redefines_of {
            // Map this field to its cluster (use target name, not full path for JSON matching)
            let target_name = target.split('.').next_back().unwrap_or(target);
            context
                .field_to_cluster
                .insert(field.name.clone(), target_name.to_string());

            // Initialize cluster if not present (use target name, not full path)
            context
                .cluster_views
                .entry(target_name.to_string())
                .or_default();
        }

        // Recursively process children
        collect_redefines_from_fields(&field.children, context);
    }
}

/// Analyze JSON data to find non-null REDEFINES views
fn analyze_json_for_redefines(
    context: &mut RedefinesContext,
    json_obj: &serde_json::Map<String, Value>,
) {
    for (key, value) in json_obj {
        // Skip metadata fields
        if key.starts_with("__") {
            continue;
        }

        // Check if this field is part of a REDEFINES cluster
        if let Some(cluster_path) = context.field_to_cluster.get(key) {
            if !value.is_null() {
                // Add this view to the cluster's non-null views
                let views = context
                    .cluster_views
                    .entry(cluster_path.clone())
                    .or_default();
                if !views.contains(key) {
                    views.push(key.clone());
                }
            }
        } else {
            // Check if this field is a REDEFINES target (original field)
            if context.cluster_views.contains_key(key) && !value.is_null() {
                // This is the original field that others redefine
                let views = context.cluster_views.entry(key.clone()).or_default();
                if !views.contains(key) {
                    views.push(key.clone());
                }
            }
        }

        // Recursively analyze nested objects
        if let Value::Object(nested_obj) = value {
            analyze_json_for_redefines(context, nested_obj);
        }
    }
}

/// Context information for ODO validation operations
#[derive(Clone)]
pub struct OdoValidationContext {
    pub field_path: String,
    pub counter_path: String,
    pub record_index: u64,
    pub byte_offset: u64,
}

/// Create comprehensive error context for CBKD/CBKE errors
///
/// Ensures all data decode (CBKD*) and encode (CBKE*) errors include
/// `record_index`, `field_path`, and `byte_offset` context as required.
pub fn create_comprehensive_error_context(
    record_index: u64,
    field_path: &str,
    byte_offset: u64,
    additional_details: Option<String>,
) -> ErrorContext {
    ErrorContext {
        record_index: Some(record_index),
        field_path: Some(field_path.to_string()),
        byte_offset: Some(byte_offset),
        line_number: None,
        details: additional_details,
    }
}

/// Validate ODO array bounds during decode with comprehensive error handling
///
/// This function combines ODO counter validation with proper error context
/// and handles both strict and lenient modes according to normative behavior.
///
/// # Errors
/// Returns an error when the decoded counter value falls outside the declared ODO bounds.
#[inline]
#[must_use = "Handle the Result or propagate the error"]
pub fn validate_odo_decode(
    counter_value: u32,
    min_count: u32,
    max_count: u32,
    context: &OdoValidationContext,
    options: &DecodeOptions,
) -> Result<OdoValidationResult> {
    validate_odo_counter(
        counter_value,
        min_count,
        max_count,
        &context.field_path,
        &context.counter_path,
        context.record_index,
        context.byte_offset,
        options.strict_mode,
    )
}

/// Validate ODO array bounds during encode with comprehensive error handling
///
/// This function validates ODO array lengths during encoding and ensures
/// proper error context is included in all error reports.
///
/// # Errors
/// Returns an error if the array length is outside the declared ODO bounds.
#[inline]
#[must_use = "Handle the Result or propagate the error"]
pub fn validate_odo_encode(
    array_length: usize,
    min_count: u32,
    max_count: u32,
    context: &OdoValidationContext,
    options: &EncodeOptions,
) -> Result<u32> {
    let array_length_u32 = u32::try_from(array_length).map_err(|_| {
        Error::new(
            ErrorCode::CBKE521_ARRAY_LEN_OOB,
            format!("Array length {array_length} exceeds u32::MAX"),
        )
        .with_context(create_comprehensive_error_context(
            context.record_index,
            &context.field_path,
            context.byte_offset,
            Some(format!("Array length: {array_length}")),
        ))
    })?;

    let validation_result = validate_odo_counter(
        array_length_u32,
        min_count,
        max_count,
        &context.field_path,
        &context.counter_path,
        context.record_index,
        context.byte_offset,
        options.strict_mode,
    )?;

    if validation_result.was_clamped {
        // In encode mode, we should probably error even in lenient mode
        // since we can't "clamp" the input JSON array
        return Err(Error::new(
            ErrorCode::CBKE521_ARRAY_LEN_OOB,
            format!(
                "JSON array length {array_length} is out of bounds for ODO field '{}' (min={min_count}, max={max_count})",
                context.field_path
            ),
        )
        .with_context(create_comprehensive_error_context(
            context.record_index,
            &context.field_path,
            context.byte_offset,
            Some(format!(
                "counter_field={}, array_length={array_length}",
                context.counter_path
            )),
        )));
    }

    Ok(validation_result.actual_count)
}

#[cfg(test)]
#[allow(clippy::expect_used)]
#[allow(clippy::unwrap_used)]
mod tests {
    use super::*;
    use anyhow::{Context, Result};
    use copybook_core::{Field, FieldKind, Schema};

    type TestResult = Result<()>;

    fn create_test_schema_with_odo() -> Schema {
        let mut schema = Schema::new();

        // Counter field
        let counter = Field {
            path: "ROOT.COUNTER".to_string(),
            name: "COUNTER".to_string(),
            level: 5,
            kind: FieldKind::ZonedDecimal {
                digits: 3,
                scale: 0,
                signed: false,
                sign_separate: None,
            },
            offset: 0,
            len: 3,
            redefines_of: None,
            occurs: None,
            sync_padding: None,
            synchronized: false,
            blank_when_zero: false,
            resolved_renames: None,
            children: vec![],
        };

        // ODO array field
        let array_field = Field {
            path: "ROOT.ARRAY".to_string(),
            name: "ARRAY".to_string(),
            level: 5,
            kind: FieldKind::Alphanum { len: 10 },
            offset: 3,
            len: 10,
            redefines_of: None,
            occurs: Some(Occurs::ODO {
                min: 0,
                max: 5,
                counter_path: "ROOT.COUNTER".to_string(),
            }),
            sync_padding: None,
            synchronized: false,
            blank_when_zero: false,
            resolved_renames: None,
            children: vec![],
        };

        schema.fields = vec![counter, array_field];
        schema
    }

    #[test]
    fn test_odo_validation_within_bounds() -> TestResult {
        let result = validate_odo_counter(3, 0, 5, "ROOT.ARRAY", "ROOT.COUNTER", 1, 3, false)?;

        assert_eq!(result.actual_count, 3);
        assert!(!result.was_clamped);
        assert!(result.warning.is_none());

        Ok(())
    }

    #[test]
    fn test_odo_validation_strict_mode_over_max() -> TestResult {
        let error = validate_odo_counter(10, 0, 5, "ROOT.ARRAY", "ROOT.COUNTER", 1, 3, true)
            .err()
            .context("expected ODO validation to fail in strict mode")?;

        assert_eq!(error.code, ErrorCode::CBKS301_ODO_CLIPPED);

        let context = error
            .context
            .context("expected error context for strict ODO failure")?;
        assert_eq!(context.record_index, Some(1));
        assert_eq!(context.field_path, Some("ROOT.ARRAY".to_string()));
        assert_eq!(context.byte_offset, Some(3));

        Ok(())
    }

    #[test]
    fn test_odo_validation_lenient_mode_clamp_max() -> TestResult {
        let result = validate_odo_counter(10, 0, 5, "ROOT.ARRAY", "ROOT.COUNTER", 1, 3, false)?;

        assert_eq!(result.actual_count, 5);
        assert!(result.was_clamped);

        let warning = result
            .warning
            .context("expected warning when lenient mode clamps to max")?;
        assert_eq!(warning.code, ErrorCode::CBKS301_ODO_CLIPPED);

        Ok(())
    }

    #[test]
    fn test_odo_validation_lenient_mode_raise_min() -> TestResult {
        let result = validate_odo_counter(0, 1, 5, "ROOT.ARRAY", "ROOT.COUNTER", 1, 3, false)?;

        assert_eq!(result.actual_count, 1);
        assert!(result.was_clamped);

        let warning = result
            .warning
            .context("expected warning when lenient mode raises to min")?;
        assert_eq!(warning.code, ErrorCode::CBKS302_ODO_RAISED);

        Ok(())
    }

    #[test]
    fn test_odo_tail_position_validation() {
        let schema = create_test_schema_with_odo();

        let result = validate_odo_tail_position(&schema, "ROOT.ARRAY", "ROOT.COUNTER");

        assert!(result.is_ok());
    }

    #[test]
    fn test_odo_tail_position_validation_counter_after_array() -> TestResult {
        let mut schema = create_test_schema_with_odo();

        // Swap offsets to make counter come after array
        schema.fields[0].offset = 10; // counter
        schema.fields[1].offset = 0; // array

        let result = validate_odo_tail_position(&schema, "ROOT.ARRAY", "ROOT.COUNTER");

        let error = result
            .err()
            .context("expected failure when counter trails array")?;
        assert_eq!(error.code, ErrorCode::CBKP021_ODO_NOT_TAIL);
        Ok(())
    }

    #[test]
    fn test_missing_counter_field_handling() -> TestResult {
        let schema = Schema::new(); // Empty schema

        let error = handle_missing_counter_field("NONEXISTENT", "ROOT.ARRAY", &schema, 1, 10);

        assert_eq!(error.code, ErrorCode::CBKS121_COUNTER_NOT_FOUND);
        let context = error
            .context
            .context("expected context describing missing counter field")?;
        assert_eq!(context.record_index, Some(1));
        assert_eq!(context.field_path, Some("ROOT.ARRAY".to_string()));
        assert_eq!(context.byte_offset, Some(10));
        Ok(())
    }

    #[test]
    fn test_redefines_context_building() {
        let mut schema = Schema::new();

        // Original field
        let field_a = Field {
            path: "ROOT.FIELD_A".to_string(),
            name: "FIELD_A".to_string(),
            level: 5,
            kind: FieldKind::Alphanum { len: 10 },
            offset: 0,
            len: 10,
            redefines_of: None,
            occurs: None,
            sync_padding: None,
            synchronized: false,
            blank_when_zero: false,
            resolved_renames: None,
            children: vec![],
        };

        // REDEFINES field
        let field_b = Field {
            path: "ROOT.FIELD_B".to_string(),
            name: "FIELD_B".to_string(),
            level: 5,
            kind: FieldKind::ZonedDecimal {
                digits: 5,
                scale: 0,
                signed: false,
                sign_separate: None,
            },
            offset: 0,
            len: 5,
            redefines_of: Some("ROOT.FIELD_A".to_string()),
            occurs: None,
            sync_padding: None,
            synchronized: false,
            blank_when_zero: false,
            resolved_renames: None,
            children: vec![],
        };

        schema.fields = vec![field_a, field_b];

        let json_data = serde_json::json!({
            "FIELD_A": "Hello",
            "FIELD_B": null
        });

        let context = build_redefines_context(&schema, &json_data);

        assert_eq!(context.field_to_cluster.len(), 1);
        assert!(context.field_to_cluster.contains_key("FIELD_B"));
        assert_eq!(context.field_to_cluster["FIELD_B"], "FIELD_A");
    }

    #[test]
    fn test_comprehensive_error_context() {
        let context = create_comprehensive_error_context(
            42,
            "ROOT.TEST_FIELD",
            100,
            Some("additional info".to_string()),
        );

        assert_eq!(context.record_index, Some(42));
        assert_eq!(context.field_path, Some("ROOT.TEST_FIELD".to_string()));
        assert_eq!(context.byte_offset, Some(100));
        assert_eq!(context.details, Some("additional info".to_string()));
    }
}