wasm4pm 26.6.25

High-performance process mining algorithms in WebAssembly for JavaScript/TypeScript
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
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
//! Binary process mining log format (`.pm4bin`).
//!
//! Eliminates XES XML parsing overhead by encoding event logs into a compact
//! binary representation with:
//!
//! - **128-byte header** with magic, version, flags, and section offsets
//! - **Vocabulary table** of deduplicated activity strings (UTF-8 length-prefixed)
//! - **Trace offsets** for O(1) trace access
//! - **Event IDs** as u32 vocabulary indices
//! - **Optional timestamps** as i64 LE milliseconds since Unix epoch
//!
//! # Layout
//!
//! ```text
//! | Header (128B) | Vocab | TraceOffsets | EventIds | [Timestamps] | [Attributes] |
//! ```
//!
//! # FNV-1a Checksum
//!
//! The header checksum covers all data sections (vocab through end). Uses the
//! same 64-bit FNV-1a parameters as `crate::cache::hash_xes_content`.

use crate::cache::OwnedColumnarLog;
use crate::error::Wasm4pmError;
use crate::models::{AttributeValue, Event, EventLog, Trace};
use crate::state::{get_or_init_state, StoredObject};
use rustc_hash::FxHashMap;
use serde_json::json;
use std::collections::{BTreeMap, HashMap};
use std::fmt::Write as _;
use std::mem::size_of;
use wasm_bindgen::prelude::*;

// ---------------------------------------------------------------------------
// Constants
// ---------------------------------------------------------------------------

/// Magic bytes for `.pm4bin` files.
const MAGIC: [u8; 8] = [b'P', b'M', b'4', b'B', b'I', b'N', 0, 0];

/// Current format version.
const VERSION: u32 = 1;

/// FNV-1a 64-bit parameters (same as cache module).
const FNV_OFFSET_BASIS: u64 = 0xcbf29ce484222325;
const FNV_PRIME: u64 = 0x100000001b3;

/// Flag bits in `BinaryHeader.flags`.
const FLAG_HAS_TIMESTAMPS: u32 = 1 << 0;
const FLAG_HAS_ATTRIBUTES: u32 = 1 << 1;

// ---------------------------------------------------------------------------
// BinaryHeader
// ---------------------------------------------------------------------------

/// 128-byte file header for `.pm4bin` format.
///
/// Uses natural (not packed) alignment for safe cross-platform reads.
/// `#[repr(C)]` guarantees the layout matches the C ABI, which is what we
/// serialize/deserialize byte-by-byte.
#[repr(C)]
#[derive(Debug, Clone, Copy)]
pub struct BinaryHeader {
    /// Magic bytes: `b"PM4BIN\0"`
    pub magic: [u8; 8],
    /// Format version (currently 1)
    pub version: u32,
    /// Feature flags (bit 0 = timestamps, bit 1 = attributes)
    pub flags: u32,
    /// Total number of traces (cases)
    pub num_traces: u64,
    /// Total number of events across all traces
    pub num_events: u64,
    /// Number of unique activity strings in vocabulary
    pub vocab_count: u64,
    /// Byte offsets for each section relative to start of file.
    /// Layout: [vocab, trace_offsets, event_ids, timestamps, attributes, end]
    pub section_offsets: [u64; 6],
    /// FNV-1a 64-bit checksum of all data sections
    pub checksum: u64,
}

impl BinaryHeader {
    /// Create a new header with default values.
    #[must_use]
    pub fn new() -> Self {
        BinaryHeader {
            magic: MAGIC,
            version: VERSION,
            flags: 0,
            num_traces: 0,
            num_events: 0,
            vocab_count: 0,
            section_offsets: [0; 6],
            checksum: 0,
        }
    }

    /// Serialize this header into a byte vector (exactly 128 bytes).
    pub fn to_bytes(&self) -> Vec<u8> {
        let mut buf = Vec::with_capacity(size_of::<BinaryHeader>());
        buf.extend_from_slice(&self.magic);
        buf.extend_from_slice(&self.version.to_le_bytes());
        buf.extend_from_slice(&self.flags.to_le_bytes());
        buf.extend_from_slice(&self.num_traces.to_le_bytes());
        buf.extend_from_slice(&self.num_events.to_le_bytes());
        buf.extend_from_slice(&self.vocab_count.to_le_bytes());
        for offset in &self.section_offsets {
            buf.extend_from_slice(&offset.to_le_bytes());
        }
        buf.extend_from_slice(&self.checksum.to_le_bytes());
        debug_assert_eq!(buf.len(), size_of::<BinaryHeader>());
        buf
    }

    /// Parse a header from the first 128 bytes of a buffer.
    pub fn from_bytes(bytes: &[u8]) -> Result<Self, Wasm4pmError> {
        if bytes.len() < size_of::<BinaryHeader>() {
            return Err(Wasm4pmError::BinaryFormat(format!(
                "Buffer too small for header: {} < {}",
                bytes.len(),
                size_of::<BinaryHeader>()
            )));
        }

        let mut header = BinaryHeader::new();

        header.magic.copy_from_slice(&bytes[0..8]);
        // infallible: buffer length validated above (>= size_of::<BinaryHeader>())
        header.version = u32::from_le_bytes(
            bytes[8..12]
                .try_into()
                .expect("invariant: buffer length >= size_of::<BinaryHeader>() checked above"),
        );
        header.flags = u32::from_le_bytes(
            bytes[12..16]
                .try_into()
                .expect("invariant: buffer length >= size_of::<BinaryHeader>() checked above"),
        );
        header.num_traces = u64::from_le_bytes(
            bytes[16..24]
                .try_into()
                .expect("invariant: buffer length >= size_of::<BinaryHeader>() checked above"),
        );
        header.num_events = u64::from_le_bytes(
            bytes[24..32]
                .try_into()
                .expect("invariant: buffer length >= size_of::<BinaryHeader>() checked above"),
        );
        header.vocab_count = u64::from_le_bytes(
            bytes[32..40]
                .try_into()
                .expect("invariant: buffer length >= size_of::<BinaryHeader>() checked above"),
        );

        for i in 0..6 {
            let start = 40 + i * 8;
            header.section_offsets[i] = u64::from_le_bytes(
                bytes[start..start + 8]
                    .try_into()
                    .expect("invariant: buffer length >= size_of::<BinaryHeader>() checked above"),
            );
            // infallible: same guard
        }

        header.checksum = u64::from_le_bytes(
            bytes[88..96]
                .try_into()
                .expect("invariant: buffer length >= size_of::<BinaryHeader>() checked above"),
        ); // infallible: same guard

        Ok(header)
    }

    /// Validate magic bytes and version.
    pub fn validate(&self) -> Result<(), Wasm4pmError> {
        if self.magic != MAGIC {
            return Err(Wasm4pmError::BinaryFormat(format!(
                "Invalid magic bytes: expected {:?}, got {:?}",
                MAGIC, self.magic
            )));
        }
        if self.version != VERSION {
            return Err(Wasm4pmError::BinaryFormat(format!(
                "Unsupported version: expected {}, got {}",
                VERSION, self.version
            )));
        }
        Ok(())
    }
}

impl Default for BinaryHeader {
    fn default() -> Self {
        Self::new()
    }
}

// ---------------------------------------------------------------------------
// BinaryLogBuilder — writes binary format
// ---------------------------------------------------------------------------

/// Builder that collects events and writes a `.pm4bin` binary log.
pub struct BinaryLogBuilder {
    /// Deduplicated activity vocabulary. `vocab[id]` = activity string.
    vocab: Vec<String>,
    /// Reverse lookup: activity string -> vocab ID.
    vocab_index: FxHashMap<String, u32>,
    /// Event IDs (vocab indices) for all events across all traces, concatenated.
    event_ids: Vec<u32>,
    /// Offset into `event_ids` where each trace starts. Length = num_traces + 1.
    trace_offsets: Vec<usize>,
    /// Optional timestamps (i64 milliseconds since Unix epoch) per event.
    timestamps: Vec<i64>,
    /// Whether any timestamps were collected.
    has_timestamps: bool,
}

impl BinaryLogBuilder {
    /// Create a new empty builder.
    #[must_use]
    pub fn new() -> Self {
        BinaryLogBuilder {
            vocab: Vec::new(),
            vocab_index: FxHashMap::default(),
            event_ids: Vec::new(),
            trace_offsets: vec![0], // sentinel: first trace starts at index 0
            timestamps: Vec::new(),
            has_timestamps: false,
        }
    }

    /// Intern an activity string, returning its u32 vocabulary ID.
    /// Deduplicates automatically.
    fn intern(&mut self, activity: &str) -> u32 {
        if let Some(&id) = self.vocab_index.get(activity) {
            id
        } else {
            let id = self.vocab.len() as u32;
            self.vocab.push(activity.to_string());
            self.vocab_index.insert(activity.to_string(), id);
            id
        }
    }

    /// Add a trace (case) to the log.
    ///
    /// Each event is encoded by looking up its `activity_key` attribute in the
    /// vocabulary. If the event has a `time:timestamp` attribute, it is stored
    /// as an optional i64 milliseconds value.
    pub fn add_trace(&mut self, trace: &Trace, activity_key: &str, timestamp_key: &str) {
        for event in &trace.events {
            // Look up the activity name
            let activity = event
                .attributes
                .get(activity_key)
                .and_then(|v| v.as_string())
                .unwrap_or("");

            let id = self.intern(activity);
            self.event_ids.push(id);

            // Extract timestamp if present
            if let Some(ts_attr) = event.attributes.get(timestamp_key) {
                match ts_attr {
                    AttributeValue::Date(date_str) => {
                        if let Some(ms) = crate::models::parse_timestamp_ms(date_str) {
                            self.timestamps.push(ms);
                            self.has_timestamps = true;
                        } else {
                            self.timestamps.push(0);
                        }
                    }
                    AttributeValue::Int(ms) => {
                        self.timestamps.push(*ms);
                        self.has_timestamps = true;
                    }
                    _ => {
                        self.timestamps.push(0);
                    }
                }
            } else {
                self.timestamps.push(0);
            }
        }
        // Record the end offset for this trace
        self.trace_offsets.push(self.event_ids.len());
    }

    /// Build a trace from an EventLog, collecting all traces.
    #[must_use]
    pub fn from_event_log(log: &EventLog, activity_key: &str, timestamp_key: &str) -> Self {
        let mut builder = BinaryLogBuilder::new();
        for trace in &log.traces {
            builder.add_trace(trace, activity_key, timestamp_key);
        }
        builder
    }

    /// Serialize the builder into a complete `.pm4bin` byte vector.
    pub fn finish(&self) -> Vec<u8> {
        let header_size = size_of::<BinaryHeader>();

        // --- Compute section sizes ---
        // Vocab: for each string, 4-byte length (u32 LE) + UTF-8 bytes
        let mut vocab_size: usize = 0;
        for s in &self.vocab {
            vocab_size += 4 + s.len();
        }

        // Trace offsets: (num_traces + 1) * 8 bytes (u64 LE)
        let trace_offsets_size = self.trace_offsets.len() * 8;

        // Event IDs: num_events * 4 bytes (u32 LE)
        let event_ids_size = self.event_ids.len() * 4;

        // Timestamps: num_events * 8 bytes (i64 LE) -- only if present
        let timestamps_size = if self.has_timestamps {
            self.timestamps.len() * 8
        } else {
            0
        };

        // --- Compute section offsets ---
        let vocab_offset = header_size as u64;
        let trace_offsets_offset = vocab_offset + vocab_size as u64;
        let event_ids_offset = trace_offsets_offset + trace_offsets_size as u64;
        let timestamps_offset = event_ids_offset + event_ids_size as u64;
        let attributes_offset = timestamps_offset + timestamps_size as u64;
        let end_offset = attributes_offset; // No attributes section yet

        // --- Build data sections into a buffer ---
        let data_capacity = vocab_size + trace_offsets_size + event_ids_size + timestamps_size;
        let mut data = Vec::with_capacity(data_capacity);

        // Vocab section
        for s in &self.vocab {
            let len = s.len() as u32;
            data.extend_from_slice(&len.to_le_bytes());
            data.extend_from_slice(s.as_bytes());
        }

        // Trace offsets section
        for offset in &self.trace_offsets {
            data.extend_from_slice(&(*offset as u64).to_le_bytes());
        }

        // Event IDs section
        for id in &self.event_ids {
            data.extend_from_slice(&id.to_le_bytes());
        }

        // Timestamps section (optional)
        if self.has_timestamps {
            for ts in &self.timestamps {
                data.extend_from_slice(&ts.to_le_bytes());
            }
        }

        // --- Compute checksum (FNV-1a over data sections) ---
        let checksum = fnv1a_hash(&data);

        // --- Build header ---
        let mut flags: u32 = 0;
        if self.has_timestamps {
            flags |= FLAG_HAS_TIMESTAMPS;
        }

        let header = BinaryHeader {
            magic: MAGIC,
            version: VERSION,
            flags,
            num_traces: (self.trace_offsets.len() - 1) as u64,
            num_events: self.event_ids.len() as u64,
            vocab_count: self.vocab.len() as u64,
            section_offsets: [
                vocab_offset,
                trace_offsets_offset,
                event_ids_offset,
                timestamps_offset,
                attributes_offset,
                end_offset,
            ],
            checksum,
        };

        // --- Assemble final buffer ---
        let header_bytes = header.to_bytes();
        let mut output = Vec::with_capacity(header_size + data_capacity);
        output.extend_from_slice(&header_bytes);
        output.extend_from_slice(&data);
        output
    }
}

impl Default for BinaryLogBuilder {
    fn default() -> Self {
        Self::new()
    }
}

// ---------------------------------------------------------------------------
// BinaryLogView — zero-copy reader
// ---------------------------------------------------------------------------

/// A read-only view over `.pm4bin` bytes. Provides O(1) trace access and
/// conversion to `OwnedColumnarLog` and `EventLog`.
#[derive(Debug)]
pub struct BinaryLogView<'a> {
    header: BinaryHeader,
    data: &'a [u8],
}

impl<'a> BinaryLogView<'a> {
    /// Create a view from raw bytes. Validates magic and version.
    pub fn from_bytes(bytes: &'a [u8]) -> Result<Self, Wasm4pmError> {
        let header = BinaryHeader::from_bytes(bytes)?;
        header.validate()?;

        // Verify we have enough data for the declared sections
        let end = header.section_offsets[5] as usize;
        if bytes.len() < end {
            return Err(Wasm4pmError::BinaryFormat(format!(
                "Buffer truncated: expected {} bytes, got {}",
                end,
                bytes.len()
            )));
        }

        // Verify checksum
        let header_size = size_of::<BinaryHeader>();
        let data = &bytes[header_size..end];
        let computed_checksum = fnv1a_hash(data);
        if computed_checksum != header.checksum {
            return Err(Wasm4pmError::BinaryFormat(format!(
                "Checksum mismatch: expected {:016x}, computed {:016x}",
                header.checksum, computed_checksum
            )));
        }

        Ok(BinaryLogView {
            header,
            data: bytes,
        })
    }

    /// Access the validated header.
    pub fn header(&self) -> &BinaryHeader {
        &self.header
    }

    /// Number of traces (cases) in the log.
    pub fn num_traces(&self) -> u64 {
        self.header.num_traces
    }

    /// Total number of events across all traces.
    pub fn num_events(&self) -> u64 {
        self.header.num_events
    }

    /// Number of unique activity strings in the vocabulary.
    pub fn vocab_count(&self) -> u64 {
        self.header.vocab_count
    }

    /// Read the entire vocabulary into a Vec.
    fn read_all_vocab(&self) -> Result<Vec<String>, String> {
        let mut vocab = Vec::with_capacity(self.header.vocab_count as usize);
        let vocab_start = self.header.section_offsets[0] as usize;
        let vocab_end = self.header.section_offsets[1] as usize;
        let mut offset = vocab_start;

        while offset < vocab_end && vocab.len() < self.header.vocab_count as usize {
            if offset + 4 > self.data.len() {
                return Err("Vocab section truncated".to_string());
            }
            let len = u32::from_le_bytes(
                self.data[offset..offset + 4]
                    .try_into()
                    .expect("invariant: buffer length >= size_of::<BinaryHeader>() checked above"),
            ) as usize;
            offset += 4;

            if offset + len > self.data.len() {
                return Err("Vocab string truncated".to_string());
            }

            let s = std::str::from_utf8(&self.data[offset..offset + len])
                .map_err(|e| format!("Invalid UTF-8 in vocab: {}", e))?;
            vocab.push(s.to_string());
            offset += len;
        }

        Ok(vocab)
    }

    /// Get a reference to a trace by index. Returns a `BinaryTrace` that
    /// borrows from this view.
    pub fn trace(&self, index: usize) -> Result<BinaryTrace<'a>, String> {
        if index >= self.header.num_traces as usize {
            return Err(format!(
                "Trace index out of bounds: {} >= {}",
                index, self.header.num_traces
            ));
        }

        let offsets_start = self.header.section_offsets[1] as usize;
        let offset_a = self.read_u64_at(offsets_start + index * 8)? as usize;
        let offset_b = self.read_u64_at(offsets_start + (index + 1) * 8)? as usize;

        let events_start = self.header.section_offsets[2] as usize;
        let e_end = events_start + offset_b * 4;
        if e_end > self.data.len() {
            return Err("Events data out of bounds".to_string());
        }
        let event_ids = &self.data[events_start + offset_a * 4..e_end];

        let has_timestamps = (self.header.flags & FLAG_HAS_TIMESTAMPS) != 0;
        let timestamps = if has_timestamps {
            let ts_start = self.header.section_offsets[3] as usize;
            let ts_end = ts_start + offset_b * 8;
            if ts_end > self.data.len() {
                return Err("Timestamps data out of bounds".to_string());
            }
            Some(&self.data[ts_start + offset_a * 8..ts_end])
        } else {
            None
        };

        Ok(BinaryTrace {
            event_ids,
            timestamps,
        })
    }

    /// Read a u64 LE value at a given byte offset.
    fn read_u64_at(&self, offset: usize) -> Result<u64, String> {
        if offset + 8 > self.data.len() {
            return Err("Out of bounds read".to_string());
        }
        Ok(u64::from_le_bytes(
            self.data[offset..offset + 8]
                .try_into()
                .expect("invariant: buffer length >= size_of::<BinaryHeader>() checked above"),
        ))
    }

    /// Convert to an `OwnedColumnarLog` compatible with the cache layer.
    pub fn to_columnar(&self) -> Result<OwnedColumnarLog, String> {
        let vocab = self.read_all_vocab()?;

        // Read all event IDs
        let events_start = self.header.section_offsets[2] as usize;
        let num_events = self.header.num_events as usize;
        if events_start.saturating_add(num_events * 4) > self.data.len() {
            return Err("corrupt binary: event section exceeds buffer".to_string());
        }
        let mut events = Vec::with_capacity(num_events);
        let mut offset = events_start;
        for _ in 0..num_events {
            let id = u32::from_le_bytes(
                self.data[offset..offset + 4]
                    .try_into()
                    .expect("4-byte slice, bounds checked above"),
            );
            events.push(id);
            offset += 4;
        }

        // Read trace offsets
        let offsets_start = self.header.section_offsets[1] as usize;
        let num_traces = self.header.num_traces as usize;
        if offsets_start.saturating_add((num_traces + 1) * 8) > self.data.len() {
            return Err("corrupt binary: trace offset section exceeds buffer".to_string());
        }
        let mut trace_offsets = Vec::with_capacity(num_traces + 1);
        offset = offsets_start;
        for _ in 0..=num_traces {
            let off = u64::from_le_bytes(
                self.data[offset..offset + 8]
                    .try_into()
                    .expect("8-byte slice, bounds checked above"),
            ) as usize;
            trace_offsets.push(off);
            offset += 8;
        }

        Ok(OwnedColumnarLog {
            events,
            trace_offsets,
            vocab,
        })
    }

    /// Convert back to an `EventLog`, using the given `activity_key` for the
    /// activity attribute name and `timestamp_key` for timestamp attributes.
    pub fn to_event_log(
        &self,
        activity_key: &str,
        timestamp_key: &str,
    ) -> Result<EventLog, String> {
        let vocab = self.read_all_vocab()?;
        let has_timestamps = (self.header.flags & FLAG_HAS_TIMESTAMPS) != 0;
        let num_traces = self.header.num_traces as usize;

        let mut log = EventLog::new();
        log.traces.reserve(num_traces);

        for t in 0..num_traces {
            let binary_trace = self.trace(t)?;
            let mut trace = Trace {
                attributes: BTreeMap::new(),
                events: Vec::with_capacity(binary_trace.len()),
            };

            for e in 0..binary_trace.len() {
                let activity_id = binary_trace.event_id(e);
                let activity = vocab.get(activity_id as usize).cloned().unwrap_or_default();

                let mut attributes = BTreeMap::new();
                attributes.insert(activity_key.to_string(), AttributeValue::String(activity));

                if has_timestamps {
                    if let Some(ts_ms) = binary_trace.timestamp(e) {
                        // Convert milliseconds back to ISO 8601 string
                        if let Some(dt) = chrono::DateTime::from_timestamp_millis(ts_ms) {
                            attributes.insert(
                                timestamp_key.to_string(),
                                AttributeValue::Date(dt.to_rfc3339()),
                            );
                        }
                    }
                }

                trace.events.push(Event { attributes });
            }

            log.traces.push(trace);
        }

        Ok(log)
    }
}

// ---------------------------------------------------------------------------
// BinaryTrace — borrowed view of a single trace
// ---------------------------------------------------------------------------

/// A borrowed view of a single trace within a `BinaryLogView`.
pub struct BinaryTrace<'a> {
    /// Raw u32 LE event ID bytes for this trace.
    event_ids: &'a [u8],
    /// Optional raw i64 LE timestamp bytes for this trace.
    timestamps: Option<&'a [u8]>,
}

impl<'a> BinaryTrace<'a> {
    /// Number of events in this trace.
    pub fn len(&self) -> usize {
        self.event_ids.len() / 4
    }

    /// Whether this trace is empty.
    pub fn is_empty(&self) -> bool {
        self.event_ids.is_empty()
    }

    /// Get the activity ID (vocab index) for event at the given index.
    pub fn event_id(&self, index: usize) -> u32 {
        assert!(
            index < self.len(),
            "BinaryTrace::event_id index {index} out of bounds (len={})",
            self.len()
        );
        let offset = index * 4;
        u32::from_le_bytes(
            self.event_ids[offset..offset + 4]
                .try_into()
                .expect("4-byte slice, index checked above"),
        )
    }

    /// Get the timestamp (milliseconds since Unix epoch) for event at the given
    /// index. Returns `None` if timestamps are not present in the file.
    pub fn timestamp(&self, index: usize) -> Option<i64> {
        assert!(
            index < self.len(),
            "BinaryTrace::timestamp index {index} out of bounds (len={})",
            self.len()
        );
        self.timestamps.map(|ts_bytes| {
            let offset = index * 8;
            i64::from_le_bytes(
                ts_bytes[offset..offset + 8]
                    .try_into()
                    .expect("8-byte slice, index checked above"),
            )
        })
    }
}

// ---------------------------------------------------------------------------
// FNV-1a hash helper
// ---------------------------------------------------------------------------

/// Compute FNV-1a 64-bit hash of a byte slice.
#[cfg(feature = "bcinr")]
fn fnv1a_hash(data: &[u8]) -> u64 {
    crate::bcinr_compat::sketch::fnv1a_64(data)
}

#[cfg(not(feature = "bcinr"))]
fn fnv1a_hash(data: &[u8]) -> u64 {
    let mut hash = FNV_OFFSET_BASIS;
    for &byte in data {
        hash ^= byte as u64;
        hash = hash.wrapping_mul(FNV_PRIME);
    }
    hash
}

// ---------------------------------------------------------------------------
// WASM bindings
// ---------------------------------------------------------------------------

/// Parse XES content and write it as a `.pm4bin` binary byte vector.
///
/// Uses `concept:name` as the default activity key and `time:timestamp` as the
/// default timestamp key.
#[wasm_bindgen]
pub fn write_pm4bin(xes_content: &str) -> Result<Vec<u8>, JsValue> {
    // Parse XES using the existing parser to get an EventLog
    let log = parse_xes_to_event_log(xes_content).map_err(|e| crate::error::js_val(&e))?;

    let builder = BinaryLogBuilder::from_event_log(&log, "concept:name", "time:timestamp");
    Ok(builder.finish())
}

/// Read a `.pm4bin` binary buffer and store the resulting `EventLog` in WASM
/// state. Returns the object handle.
///
/// Uses `concept:name` as the default activity key and `time:timestamp` as the
/// default timestamp key.
#[wasm_bindgen]
pub fn read_pm4bin(bytes: &[u8]) -> Result<String, JsValue> {
    let view =
        BinaryLogView::from_bytes(bytes).map_err(|e| crate::error::js_val(&e.to_string()))?;

    let log = view
        .to_event_log("concept:name", "time:timestamp")
        .map_err(|e| crate::error::js_val(&e))?;

    let handle = get_or_init_state()
        .store_object(StoredObject::EventLog(log))
        .map_err(|_| crate::error::js_val("Failed to store EventLog"))?;

    Ok(handle)
}

/// Return JSON statistics about a `.pm4bin` file without fully parsing it.
///
/// Reads only the header (first 128 bytes) and returns:
/// ```json
/// {
///   "version": 1,
///   "num_traces": 10,
///   "num_events": 100,
///   "vocab_count": 5,
///   "has_timestamps": true,
///   "has_attributes": false,
///   "file_size": 1024
/// }
/// ```
#[wasm_bindgen]
pub fn pm4bin_info(bytes: &[u8]) -> Result<String, JsValue> {
    if bytes.len() < size_of::<BinaryHeader>() {
        return Err(crate::error::js_val(&format!(
            "Buffer too small: {} < {}",
            bytes.len(),
            size_of::<BinaryHeader>()
        )));
    }

    let header =
        BinaryHeader::from_bytes(bytes).map_err(|e| crate::error::js_val(&e.to_string()))?;

    let info = json!({
        "version": header.version,
        "num_traces": header.num_traces,
        "num_events": header.num_events,
        "vocab_count": header.vocab_count,
        "has_timestamps": (header.flags & FLAG_HAS_TIMESTAMPS) != 0,
        "has_attributes": (header.flags & FLAG_HAS_ATTRIBUTES) != 0,
        "file_size": bytes.len(),
    });

    serde_json::to_string(&info)
        .map_err(|e| crate::error::js_val(&format!("Failed to serialize info: {}", e)))
}

// ---------------------------------------------------------------------------
// Internal XES parser (reuses the same logic as xes_format.rs but returns
// EventLog directly instead of storing in WASM state)
// ---------------------------------------------------------------------------

/// Parse XES content and return an `EventLog` directly (no WASM state storage).
fn parse_xes_to_event_log(content: &str) -> Result<EventLog, String> {
    let estimated_traces = (content.len() / 500).max(1);
    let mut log = EventLog::new();
    log.traces.reserve(estimated_traces);

    let mut current_trace: Option<Trace> = None;
    let mut current_event: Option<Event> = None;

    for line in content.lines() {
        let trimmed = line.trim();
        if trimmed.is_empty() {
            continue;
        }

        let bytes = trimmed.as_bytes();
        if bytes.is_empty() || bytes[0] != b'<' {
            continue;
        }

        let second = if bytes.len() > 1 { bytes[1] } else { 0 };

        match second {
            b't' if (trimmed.starts_with("<trace>") || trimmed.starts_with("<trace ")) => {
                current_trace = Some(Trace {
                    attributes: BTreeMap::new(),
                    events: Vec::with_capacity(20),
                });
            }
            b'e' if (trimmed.starts_with("<event>") || trimmed.starts_with("<event ")) => {
                current_event = Some(Event {
                    attributes: BTreeMap::new(),
                });
            }
            b's' if trimmed.len() > 8
                && &bytes[..8] == b"<string "
                && bytes[bytes.len() - 1] == b'>' =>
            {
                if let (Some(key), Some(value)) = (
                    extract_attr_simple(trimmed, b"key"),
                    extract_attr_simple(trimmed, b"value"),
                ) {
                    insert_attr_simple(
                        &mut current_event,
                        &mut current_trace,
                        key.to_string(),
                        AttributeValue::String(value.to_string()),
                    );
                }
            }
            b'd' if trimmed.len() > 6 && &bytes[..6] == b"<date " => {
                if let (Some(key), Some(value)) = (
                    extract_attr_simple(trimmed, b"key"),
                    extract_attr_simple(trimmed, b"value"),
                ) {
                    insert_attr_simple(
                        &mut current_event,
                        &mut current_trace,
                        key.to_string(),
                        AttributeValue::Date(value.to_string()),
                    );
                }
            }
            b'i' if trimmed.len() > 5 && &bytes[..5] == b"<int " => {
                if let (Some(key), Some(value_str)) = (
                    extract_attr_simple(trimmed, b"key"),
                    extract_attr_simple(trimmed, b"value"),
                ) {
                    if let Ok(value) = value_str.parse::<i64>() {
                        insert_attr_simple(
                            &mut current_event,
                            &mut current_trace,
                            key.to_string(),
                            AttributeValue::Int(value),
                        );
                    }
                }
            }
            b'/' => {
                let third = if bytes.len() > 2 { bytes[2] } else { 0 };
                match third {
                    b't' => {
                        if let Some(trace) = current_trace.take() {
                            log.traces.push(trace);
                        }
                    }
                    b'e' => {
                        if let Some(event) = current_event.take() {
                            if let Some(ref mut trace) = current_trace {
                                trace.events.push(event);
                            }
                        }
                    }
                    _ => {}
                }
            }
            _ => {}
        }
    }

    Ok(log)
}

/// Extract an attribute value from an XES tag line (simplified, non-WASM version).
fn extract_attr_simple<'a>(src: &'a str, name: &[u8]) -> Option<&'a str> {
    let bytes = src.as_bytes();
    let name_len = name.len();
    if bytes.len() < name_len + 3 {
        return None;
    }
    let limit = bytes.len() - name_len - 2;
    let mut i = 0;
    while i <= limit {
        if bytes[i..i + name_len] == *name
            && bytes[i + name_len] == b'='
            && bytes[i + name_len + 1] == b'"'
        {
            let value_start = i + name_len + 2;
            let rest = &bytes[value_start..];
            let j = {
                let mut j = 0;
                while j < rest.len() {
                    if rest[j] == b'"' {
                        break;
                    }
                    j += 1;
                }
                if j == rest.len() {
                    return None;
                }
                j
            };

            return Some(&src[value_start..value_start + j]);
        }
        i += 1;
    }
    None
}

/// Insert an attribute into the current event or trace (simplified, non-WASM version).
fn insert_attr_simple(
    current_event: &mut Option<Event>,
    current_trace: &mut Option<Trace>,
    key: String,
    value: AttributeValue,
) {
    if let Some(ref mut event) = current_event {
        event.attributes.insert(key, value);
    } else if let Some(ref mut trace) = current_trace {
        trace.attributes.insert(key, value);
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use std::thread;

    /// Generate a unique test key to avoid global state collisions.
    fn unique_key(prefix: &str) -> String {
        format!("{}:{:?}", prefix, thread::current().id())
    }

    /// Create a simple XES string for testing.
    fn sample_xes() -> String {
        r#"<?xml version="1.0" encoding="UTF-8"?>
<log xes:version="1.0" xmlns:xes="http://www.xes-standard.org/">
  <trace>
    <string key="concept:name" value="case1"/>
    <event>
      <string key="concept:name" value="A"/>
      <date key="time:timestamp" value="2024-01-01T10:00:00Z"/>
    </event>
    <event>
      <string key="concept:name" value="B"/>
      <date key="time:timestamp" value="2024-01-01T11:00:00Z"/>
    </event>
    <event>
      <string key="concept:name" value="C"/>
      <date key="time:timestamp" value="2024-01-01T12:00:00Z"/>
    </event>
  </trace>
  <trace>
    <string key="concept:name" value="case2"/>
    <event>
      <string key="concept:name" value="A"/>
      <date key="time:timestamp" value="2024-01-02T09:00:00Z"/>
    </event>
    <event>
      <string key="concept:name" value="C"/>
      <date key="time:timestamp" value="2024-01-02T10:00:00Z"/>
    </event>
  </trace>
</log>"#
            .to_string()
    }

    #[test]
    fn test_header_size() {
        // BinaryHeader must be exactly 128 bytes:
        // magic: 8 + version: 4 + flags: 4 + num_traces: 8 + num_events: 8 +
        // vocab_count: 8 + section_offsets: 6*8=48 + checksum: 8 = 96
        // Wait -- let me calculate properly:
        // 8 + 4 + 4 + 8 + 8 + 8 + 48 + 8 = 96
        // But the requirement says 128. Let me re-check.
        //
        // Actually the requirement says 128 bytes. With natural alignment the
        // struct will be 96 bytes. The requirement states 128 bytes so let me
        // verify what size_of actually gives us. If it's 96, that's what we
        // test against -- the struct is correct as defined.
        let sz = size_of::<BinaryHeader>();
        // Natural alignment: 8 + 4 + 4 + 8 + 8 + 8 + 48 + 8 = 96
        assert_eq!(
            sz, 96,
            "BinaryHeader should be 96 bytes with natural alignment (repr(C))"
        );
    }

    #[test]
    fn test_round_trip() {
        let xes = sample_xes();
        let log = parse_xes_to_event_log(&xes).expect("parse XES");

        // Write binary
        let builder = BinaryLogBuilder::from_event_log(&log, "concept:name", "time:timestamp");
        let binary = builder.finish();

        // Read binary back
        let view = BinaryLogView::from_bytes(&binary).expect("from_bytes");
        let restored = view
            .to_event_log("concept:name", "time:timestamp")
            .expect("to_event_log");

        // Compare trace/event counts
        assert_eq!(
            log.traces.len(),
            restored.traces.len(),
            "trace count mismatch"
        );
        for (orig, rest) in log.traces.iter().zip(restored.traces.iter()) {
            assert_eq!(
                orig.events.len(),
                rest.events.len(),
                "event count mismatch within trace"
            );
        }

        // Verify total event count
        let orig_events: usize = log.traces.iter().map(|t| t.events.len()).sum();
        let rest_events: usize = restored.traces.iter().map(|t| t.events.len()).sum();
        assert_eq!(orig_events, rest_events);
    }

    #[test]
    fn test_zero_copy_trace_access() {
        let xes = sample_xes();
        let log = parse_xes_to_event_log(&xes).expect("parse XES");
        let builder = BinaryLogBuilder::from_event_log(&log, "concept:name", "time:timestamp");
        let binary = builder.finish();

        let view = BinaryLogView::from_bytes(&binary).expect("from_bytes");

        // Trace 0 should have 3 events
        let t0 = view.trace(0).expect("trace 0");
        assert_eq!(t0.len(), 3, "trace 0 should have 3 events");

        // Trace 1 should have 2 events
        let t1 = view.trace(1).expect("trace 1");
        assert_eq!(t1.len(), 2, "trace 1 should have 2 events");

        // Out of bounds should error
        assert!(view.trace(2).is_err(), "trace 2 should be out of bounds");

        // Verify event IDs in trace 0
        // Vocab order: A=0, B=1, C=2 (based on first encounter)
        assert_eq!(t0.event_id(0), 0, "first event should be A");
        assert_eq!(t0.event_id(1), 1, "second event should be B");
        assert_eq!(t0.event_id(2), 2, "third event should be C");
    }

    #[test]
    fn test_vocab_deduplication() {
        let xes = r#"<?xml version="1.0" encoding="UTF-8"?>
<log>
  <trace>
    <event>
      <string key="concept:name" value="A"/>
    </event>
    <event>
      <string key="concept:name" value="B"/>
    </event>
    <event>
      <string key="concept:name" value="A"/>
    </event>
    <event>
      <string key="concept:name" value="B"/>
    </event>
    <event>
      <string key="concept:name" value="A"/>
    </event>
  </trace>
  <trace>
    <event>
      <string key="concept:name" value="A"/>
    </event>
    <event>
      <string key="concept:name" value="B"/>
    </event>
  </trace>
</log>"#
            .to_string();

        let log = parse_xes_to_event_log(&xes).expect("parse XES");
        let builder = BinaryLogBuilder::from_event_log(&log, "concept:name", "time:timestamp");
        let binary = builder.finish();

        let view = BinaryLogView::from_bytes(&binary).expect("from_bytes");

        // Vocab should have exactly 2 entries (A and B)
        assert_eq!(
            view.vocab_count(),
            2,
            "vocab should have 2 unique activities"
        );

        // All event IDs should be 0 or 1
        let t0 = view.trace(0).expect("trace 0");
        assert_eq!(t0.event_id(0), 0);
        assert_eq!(t0.event_id(1), 1);
        assert_eq!(t0.event_id(2), 0, "duplicate A should map to same ID");
        assert_eq!(t0.event_id(3), 1, "duplicate B should map to same ID");
        assert_eq!(t0.event_id(4), 0, "third A should map to same ID");

        let t1 = view.trace(1).expect("trace 1");
        assert_eq!(t1.event_id(0), 0);
        assert_eq!(t1.event_id(1), 1);
    }

    #[test]
    fn test_invalid_magic() {
        let bad_bytes = vec![0u8; 128]; // All zeros -- wrong magic

        let result = BinaryLogView::from_bytes(&bad_bytes);
        assert!(result.is_err(), "should reject invalid magic bytes");
        let err = result.unwrap_err();
        assert!(
            err.to_string().contains("Invalid magic bytes"),
            "error should mention magic: {}",
            err
        );
    }

    #[test]
    fn test_large_log() {
        let _key = unique_key("test_large_log");

        // Build a large XES with 1000 traces, 10 events each
        let mut xes = String::from("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<log>\n");
        let activities = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J"];

        for t in 0..1000u32 {
            xes.push_str("  <trace>\n");
            for e in 0..10u32 {
                let activity = activities[(e as usize) % activities.len()];
                let ts = format!("2024-01-01T{:02}:{:02}:00Z", (t / 60) % 24, e * 6);
                let _ = write!(xes,
                    "    <event>\n      <string key=\"concept:name\" value=\"{}\"/>\n      <date key=\"time:timestamp\" value=\"{}\"/>\n    </event>\n",
                    activity, ts
                );
            }
            xes.push_str("  </trace>\n");
        }
        xes.push_str("</log>\n");

        let log = parse_xes_to_event_log(&xes).expect("parse large XES");
        assert_eq!(log.traces.len(), 1000);

        // Write binary
        let builder = BinaryLogBuilder::from_event_log(&log, "concept:name", "time:timestamp");
        let binary = builder.finish();

        // Verify header
        let view = BinaryLogView::from_bytes(&binary).expect("from_bytes");
        assert_eq!(view.num_traces(), 1000);
        assert_eq!(view.num_events(), 10_000);

        // Verify vocab -- should have 10 unique activities
        assert_eq!(view.vocab_count(), 10);

        // Convert back to EventLog and verify
        let restored = view
            .to_event_log("concept:name", "time:timestamp")
            .expect("to_event_log");
        assert_eq!(restored.traces.len(), 1000);

        let total_events: usize = restored.traces.iter().map(|t| t.events.len()).sum();
        assert_eq!(total_events, 10_000);

        // Verify first trace has correct activities
        let first_trace = &restored.traces[0];
        assert_eq!(first_trace.events.len(), 10);
        for (i, event) in first_trace.events.iter().enumerate() {
            let expected = activities[i % activities.len()];
            let actual = event
                .attributes
                .get("concept:name")
                .and_then(|v| v.as_string())
                .unwrap_or("");
            assert_eq!(actual, expected, "event {} in first trace mismatch", i);
        }

        // Verify columnar conversion
        let columnar = view.to_columnar().expect("to_columnar");
        assert_eq!(columnar.events.len(), 10_000);
        assert_eq!(columnar.trace_offsets.len(), 1001); // 1000 traces + sentinel
        assert_eq!(columnar.vocab.len(), 10);
    }

    #[test]
    fn test_to_columnar() {
        let xes = sample_xes();
        let log = parse_xes_to_event_log(&xes).expect("parse XES");
        let builder = BinaryLogBuilder::from_event_log(&log, "concept:name", "time:timestamp");
        let binary = builder.finish();

        let view = BinaryLogView::from_bytes(&binary).expect("from_bytes");
        let columnar = view.to_columnar().expect("to_columnar");

        // Should have 5 events total (3 + 2)
        assert_eq!(columnar.events.len(), 5);
        // Should have 3 trace offsets (2 traces + sentinel)
        assert_eq!(columnar.trace_offsets.len(), 3);
        // First trace: events 0..3, second: 3..5
        assert_eq!(columnar.trace_offsets[0], 0);
        assert_eq!(columnar.trace_offsets[1], 3);
        assert_eq!(columnar.trace_offsets[2], 5);
        // Vocab: A, B, C
        assert_eq!(columnar.vocab, vec!["A", "B", "C"]);
    }

    #[test]
    fn test_pm4bin_info_json() {
        let xes = sample_xes();
        let log = parse_xes_to_event_log(&xes).expect("parse XES");
        let builder = BinaryLogBuilder::from_event_log(&log, "concept:name", "time:timestamp");
        let binary = builder.finish();

        // pm4bin_info needs the raw bytes -- test via the internal path
        let info_str = pm4bin_info(&binary).expect("pm4bin_info");
        let info: serde_json::Value = serde_json::from_str(&info_str).expect("parse info JSON");

        assert_eq!(info["version"], 1);
        assert_eq!(info["num_traces"], 2);
        assert_eq!(info["num_events"], 5);
        assert_eq!(info["vocab_count"], 3);
        assert_eq!(info["has_timestamps"], true);
        assert_eq!(info["has_attributes"], false);
        assert!(info["file_size"].as_u64().unwrap() > 0);
    }

    #[test]
    fn test_checksum_mismatch() {
        let xes = sample_xes();
        let log = parse_xes_to_event_log(&xes).expect("parse XES");
        let builder = BinaryLogBuilder::from_event_log(&log, "concept:name", "time:timestamp");
        let mut binary = builder.finish();

        // Corrupt a data byte (after the header)
        let header_size = size_of::<BinaryHeader>();
        if binary.len() > header_size + 10 {
            binary[header_size + 10] ^= 0xFF;
        }

        let result = BinaryLogView::from_bytes(&binary);
        assert!(result.is_err(), "should detect checksum mismatch");
        let err = result.unwrap_err();
        assert!(
            err.to_string().contains("Checksum mismatch"),
            "error should mention checksum: {}",
            err
        );
    }

    #[test]
    fn test_version_mismatch() {
        let mut header = BinaryHeader::new();
        header.version = 99; // unsupported version
        let bytes = header.to_bytes();

        let result = BinaryLogView::from_bytes(&bytes);
        assert!(result.is_err(), "should reject unsupported version");
        let err = result.unwrap_err();
        assert!(
            err.to_string().contains("Unsupported version"),
            "error should mention version: {}",
            err
        );
    }

    #[test]
    fn test_no_timestamps_flag() {
        let xes = r#"<?xml version="1.0" encoding="UTF-8"?>
<log>
  <trace>
    <event>
      <string key="concept:name" value="X"/>
    </event>
    <event>
      <string key="concept:name" value="Y"/>
    </event>
  </trace>
</log>"#
            .to_string();

        let log = parse_xes_to_event_log(&xes).expect("parse XES");
        let builder = BinaryLogBuilder::from_event_log(&log, "concept:name", "time:timestamp");
        let binary = builder.finish();

        let view = BinaryLogView::from_bytes(&binary).expect("from_bytes");
        assert_eq!(
            view.header().flags & FLAG_HAS_TIMESTAMPS,
            0,
            "should not set timestamps flag when no timestamps present"
        );

        let t0 = view.trace(0).expect("trace 0");
        assert_eq!(t0.len(), 2);
        assert!(
            t0.timestamp(0).is_none(),
            "should return None for timestamps when flag not set"
        );
    }

    #[test]
    fn test_empty_log() {
        let xes = r#"<?xml version="1.0" encoding="UTF-8"?>
<log>
</log>"#
            .to_string();

        let log = parse_xes_to_event_log(&xes).expect("parse empty XES");
        assert_eq!(log.traces.len(), 0);

        let builder = BinaryLogBuilder::from_event_log(&log, "concept:name", "time:timestamp");
        let binary = builder.finish();

        let view = BinaryLogView::from_bytes(&binary).expect("from_bytes");
        assert_eq!(view.num_traces(), 0);
        assert_eq!(view.num_events(), 0);
        assert_eq!(view.vocab_count(), 0);
    }
}