mecab-ko-dict 0.7.2

한국어 형태소 사전 관리 - 바이너리 포맷, FST 검색, 연접 비용
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
//! # 실시간 사전 업데이트 (Hot Reload) 모듈
//!
//! 무중단 사전 교체, 파일 변경 감지, 버전 관리 기능을 제공합니다.
//!
//! ## 주요 기능
//!
//! - **파일 변경 감지**: notify 크레이트를 통한 자동 감지
//! - **무중단 교체**: `RwLock`과 Copy-on-Write 전략
//! - **델타 업데이트**: 변경분만 적용하여 성능 최적화
//! - **버전 관리**: 사전 버전 추적 및 롤백 지원
//! - **스레드 안전성**: 동시 읽기/쓰기 처리
//!
//! ## 아키텍처
//!
//! ```text
//! ┌─────────────────────────────────────────┐
//! │ HotReloadDictionary                     │
//! │  - RwLock<VersionedDictionary>          │
//! │  - FileWatcher (notify)                 │
//! └─────────────────────────────────────────┘
//!          │                    │
//!          ▼                    ▼
//! ┌─────────────────┐  ┌────────────────┐
//! │ System Dict     │  │ User Dict      │
//! │ (Read-only)     │  │ (Mutable)      │
//! └─────────────────┘  └────────────────┘
//! ```
//!
//! ## 사용 예제
//!
//! ```rust,ignore
//! use mecab_ko_dict::hot_reload::{HotReloadDictionary, DeltaUpdate, DeltaUpdateBuilder};
//!
//! // 핫 리로드 사전 생성
//! let dict = HotReloadDictionary::new("/path/to/dict").unwrap();
//!
//! // 실시간 엔트리 추가
//! dict.add_entry("딥러닝", "NNG", -1000i16, None).unwrap();
//!
//! // 델타 업데이트 적용
//! let delta = DeltaUpdateBuilder::new()
//!     .add("머신러닝", "NNG", -1000)
//!     .add("자연어처리", "NNG", -1000)
//!     .build();
//! dict.apply_delta(delta).unwrap();
//!
//! // 버전 관리
//! let version = dict.current_version();
//! dict.rollback(version - 1).unwrap();
//! ```
//!
//! ## 성능 특성
//!
//! - **읽기**: Lock contention 최소화 (`RwLock`)
//! - **쓰기**: `Copy-on-Write`로 기존 읽기 영향 없음
//! - **델타 업데이트**: O(변경분) 복잡도
//! - **메모리**: 버전당 증분 메모리 사용

use std::collections::VecDeque;
use std::path::{Path, PathBuf};
use std::sync::{Arc, RwLock};
use std::time::{Duration, SystemTime};

use crate::error::{DictError, Result};
use crate::user_dict::{UserDictionary, UserEntry};
#[cfg(test)]
use crate::DictEntry;
use crate::{Entry, SystemDictionary};

/// 사전 버전
///
/// 각 업데이트마다 증가하는 단조 증가 버전 번호입니다.
pub type Version = u64;

/// 최대 버전 히스토리 크기 (기본값)
const DEFAULT_MAX_VERSION_HISTORY: usize = 10;

/// 최대 델타 큐 크기
const DEFAULT_MAX_DELTA_QUEUE: usize = 100;

/// 버전이 있는 사전 데이터
///
/// Copy-on-Write 전략을 위해 Arc로 래핑됩니다.
#[derive(Clone)]
struct VersionedDictionary {
    /// 버전 번호
    version: Version,
    /// 시스템 사전 (읽기 전용)
    system_dict: Arc<SystemDictionary>,
    /// 사용자 사전 (변경 가능)
    user_dict: Arc<UserDictionary>,
    /// 타임스탬프
    timestamp: SystemTime,
}

impl VersionedDictionary {
    /// 새 버전 생성 (사용자 사전 업데이트)
    fn new_version(&self, user_dict: UserDictionary) -> Self {
        Self {
            version: self.version + 1,
            system_dict: Arc::clone(&self.system_dict),
            user_dict: Arc::new(user_dict),
            timestamp: SystemTime::now(),
        }
    }

    /// 시스템 사전 교체
    fn with_system_dict(&self, system_dict: SystemDictionary) -> Self {
        Self {
            version: self.version + 1,
            system_dict: Arc::new(system_dict),
            user_dict: Arc::clone(&self.user_dict),
            timestamp: SystemTime::now(),
        }
    }
}

/// 핫 리로드 가능한 사전
///
/// `RwLock`으로 동시 접근을 제어하며, Copy-on-Write 전략으로 무중단 업데이트를 지원합니다.
pub struct HotReloadDictionary {
    /// 현재 사전 (버전 포함)
    current: Arc<RwLock<VersionedDictionary>>,
    /// 버전 히스토리 (롤백용)
    history: Arc<RwLock<VecDeque<VersionedDictionary>>>,
    /// 최대 히스토리 크기
    max_history: usize,
    /// 델타 업데이트 큐
    delta_queue: Arc<RwLock<VecDeque<DeltaUpdate>>>,
    /// 최대 델타 큐 크기
    max_delta_queue: usize,
    /// 사전 디렉토리 경로
    dicdir: PathBuf,
}

impl HotReloadDictionary {
    /// 사전 디렉토리에서 핫 리로드 사전 생성
    ///
    /// # Arguments
    ///
    /// * `dicdir` - 사전 디렉토리 경로
    ///
    /// # Errors
    ///
    /// - 사전 파일을 찾을 수 없는 경우
    /// - 사전 파일 포맷이 잘못된 경우
    pub fn new<P: AsRef<Path>>(dicdir: P) -> Result<Self> {
        let dicdir = dicdir.as_ref().to_path_buf();
        let system_dict = SystemDictionary::load(&dicdir)?;

        let versioned = VersionedDictionary {
            version: 1,
            system_dict: Arc::new(system_dict),
            user_dict: Arc::new(UserDictionary::new()),
            timestamp: SystemTime::now(),
        };

        Ok(Self {
            current: Arc::new(RwLock::new(versioned)),
            history: Arc::new(RwLock::new(VecDeque::new())),
            max_history: DEFAULT_MAX_VERSION_HISTORY,
            delta_queue: Arc::new(RwLock::new(VecDeque::new())),
            max_delta_queue: DEFAULT_MAX_DELTA_QUEUE,
            dicdir,
        })
    }

    /// 기본 경로에서 핫 리로드 사전 생성
    ///
    /// # Errors
    ///
    /// Returns an error if the dictionary files cannot be loaded.
    pub fn new_default() -> Result<Self> {
        let system_dict = SystemDictionary::load_default()?;
        let dicdir = system_dict.dicdir().to_path_buf();

        let versioned = VersionedDictionary {
            version: 1,
            system_dict: Arc::new(system_dict),
            user_dict: Arc::new(UserDictionary::new()),
            timestamp: SystemTime::now(),
        };

        Ok(Self {
            current: Arc::new(RwLock::new(versioned)),
            history: Arc::new(RwLock::new(VecDeque::new())),
            max_history: DEFAULT_MAX_VERSION_HISTORY,
            delta_queue: Arc::new(RwLock::new(VecDeque::new())),
            max_delta_queue: DEFAULT_MAX_DELTA_QUEUE,
            dicdir,
        })
    }

    /// 최대 버전 히스토리 크기 설정
    #[must_use]
    pub const fn with_max_history(mut self, max_history: usize) -> Self {
        self.max_history = max_history;
        self
    }

    /// 최대 델타 큐 크기 설정
    #[must_use]
    pub const fn with_max_delta_queue(mut self, max_delta_queue: usize) -> Self {
        self.max_delta_queue = max_delta_queue;
        self
    }

    /// 현재 버전 반환
    #[must_use]
    pub fn current_version(&self) -> Version {
        self.current.read().map(|dict| dict.version).unwrap_or(0)
    }

    /// 사전 디렉토리 경로 반환
    #[must_use]
    pub fn dicdir(&self) -> &Path {
        &self.dicdir
    }

    /// 엔트리 조회 (시스템 사전 + 사용자 사전)
    ///
    /// # Arguments
    ///
    /// * `surface` - 검색할 표면형
    ///
    /// # Errors
    ///
    /// Returns an error if the dictionary lock cannot be acquired.
    pub fn lookup(&self, surface: &str) -> Result<Vec<Entry>> {
        let dict = self.current.read().map_err(|_| {
            DictError::Format("Failed to acquire read lock on dictionary".to_string())
        })?;

        let mut results = Vec::new();

        // 시스템 사전 검색
        if let Some(index) = dict.system_dict.trie().exact_match(surface) {
            if let Ok(entry) = dict.system_dict.get_entry(index) {
                results.push(entry.to_entry());
            }
        }

        // 사용자 사전 검색
        let user_entries = dict.user_dict.lookup(surface);
        results.extend(user_entries.iter().map(|e| e.to_entry()));
        drop(dict);

        Ok(results)
    }

    /// 실시간 엔트리 추가
    ///
    /// # Arguments
    ///
    /// * `surface` - 표면형
    /// * `pos` - 품사
    /// * `cost` - 비용 (낮을수록 우선)
    /// * `reading` - 읽기 (선택)
    ///
    /// # Errors
    ///
    /// Returns an error if the dictionary lock cannot be acquired.
    pub fn add_entry(
        &self,
        surface: impl Into<String>,
        pos: impl Into<String>,
        cost: i16,
        reading: Option<String>,
    ) -> Result<Version> {
        let mut dict = self.current.write().map_err(|_| {
            DictError::Format("Failed to acquire write lock on dictionary".to_string())
        })?;

        // 현재 사용자 사전 복사 (Copy-on-Write)
        let mut new_user_dict = (*dict.user_dict).clone();
        new_user_dict.add_entry(surface, pos, Some(cost), reading);

        // 버전 히스토리 저장
        self.save_to_history(&dict)?;

        // 새 버전으로 교체
        *dict = dict.new_version(new_user_dict);

        Ok(dict.version)
    }

    /// 엔트리 제거
    ///
    /// # Arguments
    ///
    /// * `surface` - 제거할 표면형
    ///
    /// # Returns
    ///
    /// 제거된 엔트리 수
    ///
    /// # Errors
    ///
    /// Returns an error if the dictionary lock cannot be acquired.
    pub fn remove_entry(&self, surface: &str) -> Result<(Version, usize)> {
        let mut dict = self.current.write().map_err(|_| {
            DictError::Format("Failed to acquire write lock on dictionary".to_string())
        })?;

        // 현재 사용자 사전 복사
        let new_user_dict = (*dict.user_dict).clone();

        // 엔트리 제거 (표면형이 일치하는 모든 엔트리)
        let removed_count = new_user_dict
            .entries()
            .iter()
            .filter(|e| e.surface == surface)
            .count();

        if removed_count == 0 {
            return Ok((dict.version, 0));
        }

        // 새 사용자 사전 생성 (필터링)
        let filtered_entries: Vec<_> = new_user_dict
            .entries()
            .iter()
            .filter(|e| e.surface != surface)
            .cloned()
            .collect();

        let mut rebuilt_dict = UserDictionary::new();
        for entry in filtered_entries {
            rebuilt_dict.add_entry_with_ids(
                entry.surface,
                entry.pos,
                entry.cost,
                entry.left_id,
                entry.right_id,
                entry.reading,
            );
        }

        // 버전 히스토리 저장
        self.save_to_history(&dict)?;

        // 새 버전으로 교체
        *dict = dict.new_version(rebuilt_dict);

        Ok((dict.version, removed_count))
    }

    /// 엔트리 수정
    ///
    /// # Arguments
    ///
    /// * `surface` - 수정할 표면형
    /// * `update_fn` - 업데이트 함수
    ///
    /// # Errors
    ///
    /// Returns an error if the dictionary lock cannot be acquired.
    pub fn update_entry<F>(&self, surface: &str, update_fn: F) -> Result<Version>
    where
        F: Fn(&mut UserEntry),
    {
        let mut dict = self.current.write().map_err(|_| {
            DictError::Format("Failed to acquire write lock on dictionary".to_string())
        })?;

        // 현재 사용자 사전 복사
        let new_user_dict = (*dict.user_dict).clone();

        // 엔트리 수정
        let updated_entries: Vec<_> = new_user_dict
            .entries()
            .iter()
            .map(|e| {
                let mut updated = e.clone();
                if updated.surface == surface {
                    update_fn(&mut updated);
                }
                updated
            })
            .collect();

        // 새 사용자 사전 생성
        let mut rebuilt_dict = UserDictionary::new();
        for entry in updated_entries {
            rebuilt_dict.add_entry_with_ids(
                entry.surface,
                entry.pos,
                entry.cost,
                entry.left_id,
                entry.right_id,
                entry.reading,
            );
        }

        // 버전 히스토리 저장
        self.save_to_history(&dict)?;

        // 새 버전으로 교체
        *dict = dict.new_version(rebuilt_dict);

        Ok(dict.version)
    }

    /// 델타 업데이트 적용
    ///
    /// 여러 변경 사항을 하나의 트랜잭션으로 적용합니다.
    ///
    /// # Arguments
    ///
    /// * `delta` - 델타 업데이트
    ///
    /// # Errors
    ///
    /// Returns an error if the dictionary lock cannot be acquired.
    pub fn apply_delta(&self, delta: DeltaUpdate) -> Result<Version> {
        let mut dict = self.current.write().map_err(|_| {
            DictError::Format("Failed to acquire write lock on dictionary".to_string())
        })?;

        // 현재 사용자 사전 복사
        let mut new_user_dict = (*dict.user_dict).clone();

        // 제거 작업
        for surface in &delta.removals {
            let filtered_entries: Vec<_> = new_user_dict
                .entries()
                .iter()
                .filter(|e| e.surface != *surface)
                .cloned()
                .collect();

            let mut rebuilt_dict = UserDictionary::new();
            for entry in filtered_entries {
                rebuilt_dict.add_entry_with_ids(
                    entry.surface,
                    entry.pos,
                    entry.cost,
                    entry.left_id,
                    entry.right_id,
                    entry.reading,
                );
            }
            new_user_dict = rebuilt_dict;
        }

        // 추가 작업
        for addition in &delta.additions {
            new_user_dict.add_entry(
                addition.surface.clone(),
                addition.pos.clone(),
                Some(addition.cost),
                addition.reading.clone(),
            );
        }

        // 수정 작업
        for modification in &delta.modifications {
            let updated_entries: Vec<_> = new_user_dict
                .entries()
                .iter()
                .map(|e| {
                    if e.surface == modification.surface {
                        modification.to_user_entry()
                    } else {
                        e.clone()
                    }
                })
                .collect();

            let mut rebuilt_dict = UserDictionary::new();
            for entry in updated_entries {
                rebuilt_dict.add_entry_with_ids(
                    entry.surface,
                    entry.pos,
                    entry.cost,
                    entry.left_id,
                    entry.right_id,
                    entry.reading,
                );
            }
            new_user_dict = rebuilt_dict;
        }

        // 버전 히스토리 저장
        self.save_to_history(&dict)?;

        // 델타 큐에 추가
        self.enqueue_delta(delta)?;

        // 새 버전으로 교체
        *dict = dict.new_version(new_user_dict);

        Ok(dict.version)
    }

    /// 시스템 사전 리로드
    ///
    /// 사전 파일이 변경되었을 때 호출됩니다.
    ///
    /// # Errors
    ///
    /// Returns an error if the dictionary files cannot be reloaded or the lock cannot be acquired.
    pub fn reload_system_dict(&self) -> Result<Version> {
        let mut dict = self.current.write().map_err(|_| {
            DictError::Format("Failed to acquire write lock on dictionary".to_string())
        })?;

        // 시스템 사전 다시 로드
        let new_system_dict = SystemDictionary::load(&self.dicdir)?;

        // 버전 히스토리 저장
        self.save_to_history(&dict)?;

        // 새 버전으로 교체
        *dict = dict.with_system_dict(new_system_dict);

        Ok(dict.version)
    }

    /// 특정 버전으로 롤백
    ///
    /// # Arguments
    ///
    /// * `target_version` - 롤백할 버전
    ///
    /// # Errors
    ///
    /// Returns an error if the version is not found in history or locks cannot be acquired.
    pub fn rollback(&self, target_version: Version) -> Result<()> {
        let target = {
            let history = self.history.read().map_err(|_| {
                DictError::Format("Failed to acquire read lock on history".to_string())
            })?;

            history
                .iter()
                .find(|v| v.version == target_version)
                .ok_or_else(|| {
                    DictError::Format(format!("Version {target_version} not found in history"))
                })?
                .clone()
        };

        *self.current.write().map_err(|_| {
            DictError::Format("Failed to acquire write lock on dictionary".to_string())
        })? = target;

        Ok(())
    }

    /// 버전 히스토리 조회
    ///
    /// # Errors
    ///
    /// Returns an error if locks cannot be acquired.
    pub fn version_history(&self) -> Result<Vec<VersionInfo>> {
        let history = self
            .history
            .read()
            .map_err(|_| DictError::Format("Failed to acquire read lock on history".to_string()))?;

        let current = self.current.read().map_err(|_| {
            DictError::Format("Failed to acquire read lock on dictionary".to_string())
        })?;

        let mut versions = vec![VersionInfo {
            version: current.version,
            timestamp: current.timestamp,
            user_entry_count: current.user_dict.len(),
        }];

        versions.extend(history.iter().map(|v| VersionInfo {
            version: v.version,
            timestamp: v.timestamp,
            user_entry_count: v.user_dict.len(),
        }));
        drop(history);
        drop(current);

        versions.sort_by_key(|v| std::cmp::Reverse(v.version));

        Ok(versions)
    }

    /// 버전 히스토리에 저장
    fn save_to_history(&self, dict: &VersionedDictionary) -> Result<()> {
        let mut history = self.history.write().map_err(|_| {
            DictError::Format("Failed to acquire write lock on history".to_string())
        })?;

        history.push_back(dict.clone());

        // 최대 크기 초과 시 오래된 버전 제거
        while history.len() > self.max_history {
            history.pop_front();
        }
        drop(history);

        Ok(())
    }

    /// 델타 큐에 추가
    fn enqueue_delta(&self, delta: DeltaUpdate) -> Result<()> {
        let mut queue = self.delta_queue.write().map_err(|_| {
            DictError::Format("Failed to acquire write lock on delta queue".to_string())
        })?;

        queue.push_back(delta);

        while queue.len() > self.max_delta_queue {
            queue.pop_front();
        }
        drop(queue);

        Ok(())
    }

    /// 델타 히스토리 조회
    ///
    /// # Errors
    ///
    /// Returns an error if the lock cannot be acquired.
    pub fn delta_history(&self) -> Result<Vec<DeltaUpdate>> {
        let queue = self.delta_queue.read().map_err(|_| {
            DictError::Format("Failed to acquire read lock on delta queue".to_string())
        })?;

        Ok(queue.iter().cloned().collect())
    }

    /// 사용자 사전 내보내기
    ///
    /// # Errors
    ///
    /// Returns an error if the lock cannot be acquired.
    pub fn export_user_dict(&self) -> Result<UserDictionary> {
        let dict = self.current.read().map_err(|_| {
            DictError::Format("Failed to acquire read lock on dictionary".to_string())
        })?;

        let user_dict = (*dict.user_dict).clone();
        drop(dict);
        Ok(user_dict)
    }

    /// 사용자 사전 가져오기
    ///
    /// # Errors
    ///
    /// Returns an error if the lock cannot be acquired.
    pub fn import_user_dict(&self, user_dict: UserDictionary) -> Result<Version> {
        let mut dict = self.current.write().map_err(|_| {
            DictError::Format("Failed to acquire write lock on dictionary".to_string())
        })?;

        self.save_to_history(&dict)?;
        *dict = dict.new_version(user_dict);

        Ok(dict.version)
    }
}

/// 델타 업데이트
///
/// 여러 변경 사항을 하나의 트랜잭션으로 묶습니다.
#[derive(Debug, Clone)]
pub struct DeltaUpdate {
    /// 추가할 엔트리
    additions: Vec<EntryChange>,
    /// 제거할 엔트리 (표면형)
    removals: Vec<String>,
    /// 수정할 엔트리
    modifications: Vec<EntryChange>,
}

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

impl DeltaUpdate {
    /// 새 델타 업데이트 생성
    #[must_use]
    pub const fn new() -> Self {
        Self {
            additions: Vec::new(),
            removals: Vec::new(),
            modifications: Vec::new(),
        }
    }

    /// 빌더 패턴 시작
    #[must_use]
    pub const fn builder() -> DeltaUpdateBuilder {
        DeltaUpdateBuilder::new()
    }

    /// 추가 작업 수
    #[must_use]
    pub fn addition_count(&self) -> usize {
        self.additions.len()
    }

    /// 제거 작업 수
    #[must_use]
    pub fn removal_count(&self) -> usize {
        self.removals.len()
    }

    /// 수정 작업 수
    #[must_use]
    pub fn modification_count(&self) -> usize {
        self.modifications.len()
    }

    /// 총 변경 작업 수
    #[must_use]
    pub fn total_changes(&self) -> usize {
        self.additions.len() + self.removals.len() + self.modifications.len()
    }
}

/// 엔트리 변경 정보
#[derive(Debug, Clone)]
pub struct EntryChange {
    /// 표면형
    pub surface: String,
    /// 품사
    pub pos: String,
    /// 비용
    pub cost: i16,
    /// 읽기
    pub reading: Option<String>,
    /// 좌문맥 ID
    pub left_id: u16,
    /// 우문맥 ID
    pub right_id: u16,
}

impl EntryChange {
    /// `UserEntry`로 변환
    fn to_user_entry(&self) -> UserEntry {
        UserEntry::new(
            self.surface.clone(),
            self.pos.clone(),
            self.cost,
            self.reading.clone(),
        )
        .with_context_ids(self.left_id, self.right_id)
    }
}

/// 델타 업데이트 빌더
pub struct DeltaUpdateBuilder {
    delta: DeltaUpdate,
}

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

impl DeltaUpdateBuilder {
    /// 새 빌더 생성
    #[must_use]
    pub const fn new() -> Self {
        Self {
            delta: DeltaUpdate::new(),
        }
    }

    /// 엔트리 추가
    #[must_use]
    pub fn add(mut self, surface: impl Into<String>, pos: impl Into<String>, cost: i16) -> Self {
        self.delta.additions.push(EntryChange {
            surface: surface.into(),
            pos: pos.into(),
            cost,
            reading: None,
            left_id: 0,
            right_id: 0,
        });
        self
    }

    /// 엔트리 추가 (읽기 포함)
    #[must_use]
    pub fn add_with_reading(
        mut self,
        surface: impl Into<String>,
        pos: impl Into<String>,
        cost: i16,
        reading: impl Into<String>,
    ) -> Self {
        self.delta.additions.push(EntryChange {
            surface: surface.into(),
            pos: pos.into(),
            cost,
            reading: Some(reading.into()),
            left_id: 0,
            right_id: 0,
        });
        self
    }

    /// 엔트리 제거
    #[must_use]
    pub fn remove(mut self, surface: impl Into<String>) -> Self {
        self.delta.removals.push(surface.into());
        self
    }

    /// 엔트리 수정
    #[must_use]
    pub fn modify(mut self, surface: impl Into<String>, pos: impl Into<String>, cost: i16) -> Self {
        self.delta.modifications.push(EntryChange {
            surface: surface.into(),
            pos: pos.into(),
            cost,
            reading: None,
            left_id: 0,
            right_id: 0,
        });
        self
    }

    /// 델타 업데이트 빌드
    #[must_use]
    pub fn build(self) -> DeltaUpdate {
        self.delta
    }
}

/// 버전 정보
#[derive(Debug, Clone)]
pub struct VersionInfo {
    /// 버전 번호
    pub version: Version,
    /// 타임스탬프
    pub timestamp: SystemTime,
    /// 사용자 사전 엔트리 수
    pub user_entry_count: usize,
}

impl VersionInfo {
    /// 버전 생성 시간 (Duration)
    #[must_use]
    pub fn age(&self) -> Option<Duration> {
        SystemTime::now().duration_since(self.timestamp).ok()
    }
}

#[cfg(test)]
#[allow(clippy::expect_used, clippy::unwrap_used, clippy::vec_init_then_push)]
mod tests {
    use super::*;
    use crate::matrix::DenseMatrix;
    use crate::trie::TrieBuilder;

    fn create_test_system_dict() -> SystemDictionary {
        let entries = vec![("", 0u32), ("가다", 1), ("가방", 2)];
        let trie_bytes = TrieBuilder::build(&entries).expect("should build trie");
        let trie = crate::trie::Trie::from_vec(trie_bytes);
        let matrix = crate::matrix::ConnectionMatrix::Dense(DenseMatrix::new(10, 10, 100));

        let mut dict_entries = Vec::new();
        dict_entries.push(DictEntry::new("", 1, 1, 100, "NNG,*,T,가,*,*,*,*"));
        dict_entries.push(DictEntry::new("가다", 2, 2, 200, "VV,*,F,가다,*,*,*,*"));
        dict_entries.push(DictEntry::new("가방", 3, 3, 300, "NNG,*,T,가방,*,*,*,*"));

        SystemDictionary::new_test(PathBuf::from("./test_dic"), trie, matrix, dict_entries)
    }

    #[test]
    fn test_hot_reload_dictionary_add_entry() {
        let system_dict = create_test_system_dict();
        let dicdir = system_dict.dicdir().to_path_buf();

        let versioned = VersionedDictionary {
            version: 1,
            system_dict: Arc::new(system_dict),
            user_dict: Arc::new(UserDictionary::new()),
            timestamp: SystemTime::now(),
        };

        let dict = HotReloadDictionary {
            current: Arc::new(RwLock::new(versioned)),
            history: Arc::new(RwLock::new(VecDeque::new())),
            max_history: 10,
            delta_queue: Arc::new(RwLock::new(VecDeque::new())),
            max_delta_queue: 100,
            dicdir,
        };

        let v1 = dict.current_version();
        assert_eq!(v1, 1);

        let v2 = dict
            .add_entry("딥러닝", "NNG", -1000, None)
            .expect("should add entry");
        assert_eq!(v2, 2);

        let entries = dict.lookup("딥러닝").expect("should lookup");
        assert_eq!(entries.len(), 1);
        assert_eq!(entries[0].surface, "딥러닝");
    }

    #[test]
    fn test_hot_reload_dictionary_remove_entry() {
        let system_dict = create_test_system_dict();
        let dicdir = system_dict.dicdir().to_path_buf();

        let mut user_dict = UserDictionary::new();
        user_dict.add_entry("딥러닝", "NNG", Some(-1000), None);

        let versioned = VersionedDictionary {
            version: 1,
            system_dict: Arc::new(system_dict),
            user_dict: Arc::new(user_dict),
            timestamp: SystemTime::now(),
        };

        let dict = HotReloadDictionary {
            current: Arc::new(RwLock::new(versioned)),
            history: Arc::new(RwLock::new(VecDeque::new())),
            max_history: 10,
            delta_queue: Arc::new(RwLock::new(VecDeque::new())),
            max_delta_queue: 100,
            dicdir,
        };

        let (version, removed) = dict.remove_entry("딥러닝").expect("should remove");
        assert_eq!(version, 2);
        assert_eq!(removed, 1);

        let entries = dict.lookup("딥러닝").expect("should lookup");
        assert!(entries.is_empty());
    }

    #[test]
    fn test_delta_update() {
        let system_dict = create_test_system_dict();
        let dicdir = system_dict.dicdir().to_path_buf();

        let versioned = VersionedDictionary {
            version: 1,
            system_dict: Arc::new(system_dict),
            user_dict: Arc::new(UserDictionary::new()),
            timestamp: SystemTime::now(),
        };

        let dict = HotReloadDictionary {
            current: Arc::new(RwLock::new(versioned)),
            history: Arc::new(RwLock::new(VecDeque::new())),
            max_history: 10,
            delta_queue: Arc::new(RwLock::new(VecDeque::new())),
            max_delta_queue: 100,
            dicdir,
        };

        let delta = DeltaUpdate::builder()
            .add("딥러닝", "NNG", -1000)
            .add("머신러닝", "NNG", -1000)
            .add("자연어처리", "NNG", -1000)
            .build();

        assert_eq!(delta.addition_count(), 3);

        let version = dict.apply_delta(delta).expect("should apply delta");
        assert_eq!(version, 2);

        let entries = dict.lookup("딥러닝").expect("should lookup");
        assert_eq!(entries.len(), 1);

        let entries = dict.lookup("머신러닝").expect("should lookup");
        assert_eq!(entries.len(), 1);
    }

    #[test]
    fn test_version_rollback() {
        let system_dict = create_test_system_dict();
        let dicdir = system_dict.dicdir().to_path_buf();

        let versioned = VersionedDictionary {
            version: 1,
            system_dict: Arc::new(system_dict),
            user_dict: Arc::new(UserDictionary::new()),
            timestamp: SystemTime::now(),
        };

        let dict = HotReloadDictionary {
            current: Arc::new(RwLock::new(versioned)),
            history: Arc::new(RwLock::new(VecDeque::new())),
            max_history: 10,
            delta_queue: Arc::new(RwLock::new(VecDeque::new())),
            max_delta_queue: 100,
            dicdir,
        };

        // 버전 1
        let v1 = dict.current_version();

        // 버전 2
        dict.add_entry("딥러닝", "NNG", -1000, None)
            .expect("should add");

        // 버전 3
        dict.add_entry("머신러닝", "NNG", -1000, None)
            .expect("should add");

        assert_eq!(dict.current_version(), 3);

        // 버전 1로 롤백
        dict.rollback(v1).expect("should rollback");
        assert_eq!(dict.current_version(), v1);

        let entries = dict.lookup("딥러닝").expect("should lookup");
        assert!(entries.is_empty());
    }

    #[test]
    fn test_version_history() {
        let system_dict = create_test_system_dict();
        let dicdir = system_dict.dicdir().to_path_buf();

        let versioned = VersionedDictionary {
            version: 1,
            system_dict: Arc::new(system_dict),
            user_dict: Arc::new(UserDictionary::new()),
            timestamp: SystemTime::now(),
        };

        let dict = HotReloadDictionary {
            current: Arc::new(RwLock::new(versioned)),
            history: Arc::new(RwLock::new(VecDeque::new())),
            max_history: 10,
            delta_queue: Arc::new(RwLock::new(VecDeque::new())),
            max_delta_queue: 100,
            dicdir,
        };

        dict.add_entry("A", "NNG", 0, None).expect("should add");
        dict.add_entry("B", "NNG", 0, None).expect("should add");
        dict.add_entry("C", "NNG", 0, None).expect("should add");

        let history = dict.version_history().expect("should get history");
        assert_eq!(history.len(), 4); // current + 3 history
        assert_eq!(history[0].version, 4); // 최신 버전이 먼저
    }

    #[test]
    fn test_update_entry() {
        let system_dict = create_test_system_dict();
        let dicdir = system_dict.dicdir().to_path_buf();

        let mut user_dict = UserDictionary::new();
        user_dict.add_entry("딥러닝", "NNG", Some(-1000), None);

        let versioned = VersionedDictionary {
            version: 1,
            system_dict: Arc::new(system_dict),
            user_dict: Arc::new(user_dict),
            timestamp: SystemTime::now(),
        };

        let dict = HotReloadDictionary {
            current: Arc::new(RwLock::new(versioned)),
            history: Arc::new(RwLock::new(VecDeque::new())),
            max_history: 10,
            delta_queue: Arc::new(RwLock::new(VecDeque::new())),
            max_delta_queue: 100,
            dicdir,
        };

        dict.update_entry("딥러닝", |entry| {
            entry.cost = -2000;
            entry.reading = Some("딥러닝".to_string());
        })
        .expect("should update");

        let entries = dict.lookup("딥러닝").expect("should lookup");
        assert_eq!(entries.len(), 1);
        assert_eq!(entries[0].cost, -2000);
    }
}