lcpfs 2026.1.102

LCP File System - A ZFS-inspired copy-on-write filesystem for Rust
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
// Copyright 2025 LunaOS Contributors
// SPDX-License-Identifier: Apache-2.0
//
// Tiered Storage Intelligence
// PI-controlled hot/cold data migration.

// ALL thresholds are learned from observation - NO hardcoded values.
// ============================================================================

use crate::fscore::structs::Dva;
use alloc::collections::{BTreeMap, VecDeque};
use alloc::vec::Vec;
use lazy_static::lazy_static;
use libm::{fabs, sqrt};
use spin::Mutex;

// ═══════════════════════════════════════════════════════════════════════════════
// LEARNED THRESHOLDS (Welford's algorithm - no hardcoded values)
// ═══════════════════════════════════════════════════════════════════════════════

/// Adaptive threshold that learns from observations using Welford's algorithm.
/// All thresholds start uninformed and adjust based on observed outcomes.
#[derive(Clone, Copy)]
pub struct LearnedThreshold {
    /// Current threshold value
    pub value: f64,
    /// Statistical uncertainty in the threshold estimate
    pub uncertainty: f64,
    /// Number of observations used to learn this threshold
    pub observations: u64,
    /// Current learning rate (decreases as observations increase)
    pub learning_rate: f64,
    /// Mean outcome (delta epsilon) from actions at this threshold
    pub mean_outcome: f64,
    /// Variance of outcomes (used to calculate uncertainty)
    pub variance: f64,
}

impl LearnedThreshold {
    /// Create a new uninformed threshold with an initial guess.
    /// Starts with maximum uncertainty and will learn from observations.
    pub const fn uninformed(initial_guess: f64) -> Self {
        Self {
            value: initial_guess,
            uncertainty: f64::MAX,
            observations: 0,
            learning_rate: 1.0,
            mean_outcome: 0.0,
            variance: f64::MAX,
        }
    }

    /// Update the threshold based on an observed action and its outcome.
    /// Uses Welford's algorithm for stable online variance calculation.
    pub fn observe(&mut self, action_value: f64, outcome_delta_epsilon: f64) {
        self.observations += 1;
        let n = self.observations as f64;

        let delta = outcome_delta_epsilon - self.mean_outcome;
        self.mean_outcome += delta / n;
        let delta2 = outcome_delta_epsilon - self.mean_outcome;

        if self.observations > 1 {
            let m2 = self.variance * (n - 2.0) + delta * delta2;
            self.variance = m2 / (n - 1.0);
            self.uncertainty = sqrt(self.variance / n);
        }

        let adjustment = if outcome_delta_epsilon < 0.0 {
            (action_value - self.value) * self.learning_rate
        } else {
            (self.value - action_value) * self.learning_rate * 0.5
        };

        self.value += adjustment;
        self.learning_rate = 1.0 / (1.0 + sqrt(self.observations as f64) * 0.1);
    }

    /// Calculate confidence in this threshold (0.0 to 1.0).
    /// Higher confidence means more observations and lower uncertainty.
    pub fn confidence(&self) -> f64 {
        if self.observations == 0 {
            return 0.0;
        }
        let obs_factor = 1.0 - 1.0 / (1.0 + self.observations as f64 * 0.01);
        let unc_factor = 1.0 / (1.0 + fabs(self.uncertainty));
        obs_factor * unc_factor
    }

    /// Determine if an action should be taken based on current value and estimated benefit.
    /// Returns true if the benefit-to-uncertainty ratio justifies the action.
    pub fn should_act(&self, current_value: f64, estimated_benefit: f64) -> bool {
        let benefit_over_uncertainty = estimated_benefit / (self.uncertainty + 1e-10);
        current_value >= self.value && benefit_over_uncertainty > 1.0
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// STORAGE CLASSES
// ═══════════════════════════════════════════════════════════════════════════════

/// Storage performance tiers representing different hardware classes.
/// Gold (NVMe) is fastest for hot data, Silver (SSD) for warm data, Bronze (HDD) for cold data.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Default)]
#[repr(u8)]
pub enum StorageClass {
    /// NVMe - Fastest tier (hot data)
    Gold = 0,
    /// SSD - Middle tier (warm data)
    #[default]
    Silver = 1,
    /// HDD - Slowest tier (cold data)
    Bronze = 2,
}

impl StorageClass {
    /// Relative speed factor (higher = faster)
    pub fn speed_factor(&self) -> f64 {
        match self {
            StorageClass::Gold => 10.0,  // NVMe: 10x
            StorageClass::Silver => 3.0, // SSD: 3x
            StorageClass::Bronze => 1.0, // HDD: baseline
        }
    }

    /// Relative cost factor (higher = more expensive per byte)
    pub fn cost_factor(&self) -> f64 {
        match self {
            StorageClass::Gold => 5.0,   // NVMe: 5x cost
            StorageClass::Silver => 2.0, // SSD: 2x cost
            StorageClass::Bronze => 1.0, // HDD: baseline
        }
    }

    /// Get tier above (faster)
    pub fn promote(&self) -> Option<StorageClass> {
        match self {
            StorageClass::Gold => None,
            StorageClass::Silver => Some(StorageClass::Gold),
            StorageClass::Bronze => Some(StorageClass::Silver),
        }
    }

    /// Get tier below (slower)
    pub fn demote(&self) -> Option<StorageClass> {
        match self {
            StorageClass::Gold => Some(StorageClass::Silver),
            StorageClass::Silver => Some(StorageClass::Bronze),
            StorageClass::Bronze => None,
        }
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// BLOCK ACCESS TRACKING
// ═══════════════════════════════════════════════════════════════════════════════

/// Access statistics for a single block/object
#[derive(Clone, Copy, Default)]
pub struct AccessStats {
    /// Unique identifier for this object
    pub object_id: u64,
    /// Current storage tier where this object resides
    pub current_tier: StorageClass,
    /// Total number of accesses (reads + writes)
    pub access_count: u64,
    /// Number of read operations
    pub read_count: u64,
    /// Number of write operations
    pub write_count: u64,
    /// Timestamp of most recent access (milliseconds)
    pub last_access_ms: u64,
    /// Timestamp when object was created (milliseconds)
    pub creation_ms: u64,
    /// Size of the object in bytes
    pub size_bytes: u64,
    /// Exponentially weighted moving average of access frequency
    pub access_frequency: f64,
    /// Time since last access at last observation
    pub idle_time_ms: u64,
}

impl AccessStats {
    /// Calculate "heat" score (higher = hotter, should be on faster tier)
    pub fn heat_score(&self) -> f64 {
        // Combine frequency and recency
        let frequency_score = self.access_frequency;
        let recency_score = if self.idle_time_ms > 0 {
            1.0 / (1.0 + (self.idle_time_ms as f64 / 3_600_000.0)) // Decay over hours
        } else {
            1.0
        };

        frequency_score * recency_score
    }
}

/// Observation of a tier migration and its effect on system epsilon.
/// Used for learning optimal migration thresholds.
#[derive(Clone, Copy)]
pub struct TierObservation {
    /// When this migration occurred (milliseconds)
    pub timestamp_ms: u64,
    /// Object that was migrated
    pub object_id: u64,
    /// Storage tier before migration
    pub before_tier: StorageClass,
    /// Storage tier after migration
    pub after_tier: StorageClass,
    /// Object's heat score at time of migration decision
    pub heat_at_decision: f64,
    /// System epsilon before migration
    pub epsilon_before: f64,
    /// System epsilon after migration
    pub epsilon_after: f64,
}

impl TierObservation {
    /// Calculate the change in epsilon caused by this migration.
    /// Negative values indicate epsilon reduction (improvement).
    pub fn delta_epsilon(&self) -> f64 {
        self.epsilon_after - self.epsilon_before
    }

    /// Returns true if this migration was a promotion (to faster tier).
    pub fn was_promotion(&self) -> bool {
        (self.before_tier as u8) > (self.after_tier as u8)
    }

    /// Returns true if this migration was a demotion (to slower tier).
    pub fn was_demotion(&self) -> bool {
        (self.before_tier as u8) < (self.after_tier as u8)
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// TIER MANAGER
// ═══════════════════════════════════════════════════════════════════════════════

lazy_static! {
    /// Global tiering manager singleton for coordinating storage tier migrations.
    /// Tracks access patterns and automatically migrates data between Gold/Silver/Bronze tiers.
    pub static ref TIER_MANAGER: Mutex<TierManager> = Mutex::new(TierManager::new());
}

/// Manages storage tier migrations with learned thresholds and PI-controlled decisions.
/// Tracks object access patterns and automatically migrates data between tiers.
pub struct TierManager {
    /// VDEV to storage class mapping
    pub vdev_map: [StorageClass; 8],

    /// Access statistics per object
    access_stats: BTreeMap<u64, AccessStats>,

    /// Migration history for learning
    observations: VecDeque<TierObservation>,

    // ═══════════════════════════════════════════════════════════════════════════
    // LEARNED THRESHOLDS (no hardcoded values)
    // ═══════════════════════════════════════════════════════════════════════════
    /// Learned: Heat threshold for promotion (cold -> warm -> hot)
    threshold_promote: LearnedThreshold,

    /// Learned: Heat threshold for demotion (hot -> warm -> cold)
    threshold_demote: LearnedThreshold,

    /// Learned: Minimum observations before migration decision
    min_observations: LearnedThreshold,

    /// Learned: Cooldown between migrations of same object (ms)
    migration_cooldown_ms: LearnedThreshold,

    /// Learned: Optimal frequency decay factor
    frequency_decay: LearnedThreshold,

    /// Learned: Size threshold for migration benefit
    size_threshold: LearnedThreshold,

    /// Current system epsilon
    current_epsilon: f64,

    /// Last migration timestamp per object
    last_migration: BTreeMap<u64, u64>,
}

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

impl TierManager {
    /// Create a new tier manager with default VDEV mapping and uninformed thresholds.
    /// VDEVs 0-1: Gold (NVMe), 2-3: Silver (SSD), 4-7: Bronze (HDD).
    pub fn new() -> Self {
        let mut vdev_map = [StorageClass::Silver; 8];
        vdev_map[0] = StorageClass::Gold; // VDEV 0 is NVMe
        vdev_map[1] = StorageClass::Gold; // VDEV 1 is NVMe
        vdev_map[2] = StorageClass::Silver; // VDEV 2-3 are SSD
        vdev_map[3] = StorageClass::Silver;
        vdev_map[4] = StorageClass::Bronze; // VDEV 4-7 are HDD
        vdev_map[5] = StorageClass::Bronze;
        vdev_map[6] = StorageClass::Bronze;
        vdev_map[7] = StorageClass::Bronze;

        Self {
            vdev_map,
            access_stats: BTreeMap::new(),
            observations: VecDeque::with_capacity(1000),

            // Initialize with uninformed priors
            threshold_promote: LearnedThreshold::uninformed(0.7), // Heat > 0.7 = promote
            threshold_demote: LearnedThreshold::uninformed(0.1),  // Heat < 0.1 = demote
            min_observations: LearnedThreshold::uninformed(10.0), // Need 10 accesses
            migration_cooldown_ms: LearnedThreshold::uninformed(3_600_000.0), // 1 hour
            frequency_decay: LearnedThreshold::uninformed(0.95),  // 5% decay per interval
            size_threshold: LearnedThreshold::uninformed(4096.0), // 4KB min for migration

            current_epsilon: 0.0,
            last_migration: BTreeMap::new(),
        }
    }

    /// Update current system epsilon
    pub fn update_epsilon(&mut self, epsilon: f64) {
        self.current_epsilon = epsilon;
    }

    /// Record an access to an object
    pub fn record_access(&mut self, object_id: u64, is_write: bool, timestamp_ms: u64, size: u64) {
        let decay = self.frequency_decay.value;

        let stats = self
            .access_stats
            .entry(object_id)
            .or_insert_with(|| AccessStats {
                object_id,
                current_tier: StorageClass::Silver,
                access_count: 0,
                read_count: 0,
                write_count: 0,
                last_access_ms: timestamp_ms,
                creation_ms: timestamp_ms,
                size_bytes: size,
                access_frequency: 0.0,
                idle_time_ms: 0,
            });

        // Update stats
        stats.access_count += 1;
        if is_write {
            stats.write_count += 1;
        } else {
            stats.read_count += 1;
        }

        stats.idle_time_ms = timestamp_ms.saturating_sub(stats.last_access_ms);
        stats.last_access_ms = timestamp_ms;

        // Update EWMA frequency
        stats.access_frequency = stats.access_frequency * decay + (1.0 - decay);
    }

    /// Decay access frequencies (call periodically)
    pub fn decay_frequencies(&mut self) {
        let decay = self.frequency_decay.value;
        for stats in self.access_stats.values_mut() {
            stats.access_frequency *= decay;
        }
    }

    /// Select VDEV for new allocation based on intent
    pub fn select_vdev(&self, policy: AllocationPolicy) -> usize {
        for (id, class) in self.vdev_map.iter().enumerate() {
            if *class == policy.intent {
                return id;
            }
        }
        // Fallback to first VDEV if no match
        0
    }

    /// PI decides whether to migrate an object
    pub fn check_migration(
        &self,
        object_id: u64,
        current_time_ms: u64,
    ) -> Option<MigrationDecision> {
        let stats = self.access_stats.get(&object_id)?;

        // Check cooldown (learned)
        if let Some(&last_mig) = self.last_migration.get(&object_id) {
            if current_time_ms < last_mig + self.migration_cooldown_ms.value as u64 {
                return None;
            }
        }

        // Check minimum observations (learned)
        if (stats.access_count as f64) < self.min_observations.value {
            return None;
        }

        // Check size threshold (learned)
        if (stats.size_bytes as f64) < self.size_threshold.value {
            return None;
        }

        let heat = stats.heat_score();

        // Check for promotion
        if let Some(target_tier) = stats.current_tier.promote() {
            let benefit = self.estimate_promotion_benefit(stats, target_tier);
            if self.threshold_promote.should_act(heat, benefit)
                && self.threshold_promote.confidence() > 0.1
            {
                return Some(MigrationDecision::Promote {
                    object_id,
                    from_tier: stats.current_tier,
                    to_tier: target_tier,
                    estimated_benefit: benefit,
                });
            }
        }

        // Check for demotion
        if let Some(target_tier) = stats.current_tier.demote() {
            let benefit = self.estimate_demotion_benefit(stats, target_tier);
            // For demotion, we invert the threshold check (low heat triggers)
            if heat < self.threshold_demote.value
                && benefit > self.threshold_demote.uncertainty
                && self.threshold_demote.confidence() > 0.1
            {
                return Some(MigrationDecision::Demote {
                    object_id,
                    from_tier: stats.current_tier,
                    to_tier: target_tier,
                    estimated_benefit: benefit,
                });
            }
        }

        None
    }

    /// Estimate epsilon reduction from promoting an object
    fn estimate_promotion_benefit(&self, stats: &AccessStats, target: StorageClass) -> f64 {
        // Benefit: Faster access for hot data
        let speed_improvement = target.speed_factor() / stats.current_tier.speed_factor();
        let access_savings = stats.access_frequency * speed_improvement * 10.0;

        // Cost: Migration overhead + storage cost difference
        let migration_cost = stats.size_bytes as f64 / 1_000_000.0; // MB migrated
        let storage_cost = (target.cost_factor() - stats.current_tier.cost_factor())
            * stats.size_bytes as f64
            / 1_000_000_000.0;

        access_savings - migration_cost - storage_cost
    }

    /// Estimate epsilon reduction from demoting an object
    fn estimate_demotion_benefit(&self, stats: &AccessStats, target: StorageClass) -> f64 {
        // Benefit: Reduced storage cost for cold data
        let storage_savings = (stats.current_tier.cost_factor() - target.cost_factor())
            * stats.size_bytes as f64
            / 1_000_000_000.0;

        // Cost: Slower future access (but data is cold, so impact is low)
        let access_penalty = stats.access_frequency * 5.0; // Low because data is cold

        storage_savings - access_penalty
    }

    /// Execute a migration decision
    pub fn execute_migration(&mut self, decision: &MigrationDecision, current_time_ms: u64) {
        let (object_id, from_tier, to_tier) = match decision {
            MigrationDecision::Promote {
                object_id,
                from_tier,
                to_tier,
                ..
            } => (*object_id, *from_tier, *to_tier),
            MigrationDecision::Demote {
                object_id,
                from_tier,
                to_tier,
                ..
            } => (*object_id, *from_tier, *to_tier),
        };

        let epsilon_before = self.current_epsilon;
        let start_time = crate::get_time();

        // Actually move the data between storage tiers
        let blocks_moved = Self::relocate_object_to_tier(object_id, from_tier, to_tier);
        let time_taken_ms = (crate::get_time() - start_time) / 1_000_000;

        crate::lcpfs_println!(
            "[ TIER ] Migrated object {} from {:?} to {:?} ({} blocks, {} ms)",
            object_id,
            from_tier,
            to_tier,
            blocks_moved,
            time_taken_ms
        );

        // Update stats
        if let Some(stats) = self.access_stats.get_mut(&object_id) {
            stats.current_tier = to_tier;
        }

        // Record observation for learning
        let observation = TierObservation {
            timestamp_ms: current_time_ms,
            object_id,
            before_tier: from_tier,
            after_tier: to_tier,
            heat_at_decision: self
                .access_stats
                .get(&object_id)
                .map(|s| s.heat_score())
                .unwrap_or(0.0),
            epsilon_before,
            epsilon_after: self.current_epsilon, // Will be updated later
        };

        self.observations.push_back(observation);
        while self.observations.len() > 1000 {
            self.observations.pop_front();
        }

        self.last_migration.insert(object_id, current_time_ms);
    }

    /// Learn from migration outcomes
    pub fn learn_from_outcomes(&mut self) {
        // Look at recent observations and update thresholds
        for obs in self.observations.iter() {
            let delta = obs.delta_epsilon();

            if obs.was_promotion() {
                self.threshold_promote.observe(obs.heat_at_decision, delta);
            } else if obs.was_demotion() {
                self.threshold_demote.observe(obs.heat_at_decision, delta);
            }
        }
    }

    /// Relocate object data to a different storage tier
    /// Returns number of blocks moved
    fn relocate_object_to_tier(
        object_id: u64,
        from_tier: StorageClass,
        to_tier: StorageClass,
    ) -> u64 {
        use crate::BLOCK_DEVICES;
        use alloc::vec;

        let mut blocks_moved = 0u64;

        // Determine device IDs for each tier
        // Gold = DRAM/NVMe (dev 0), Silver = SATA SSD (dev 1), Bronze = HDD (dev 2)
        let from_dev = match from_tier {
            StorageClass::Gold => 0,
            StorageClass::Silver => 1,
            StorageClass::Bronze => 2,
        };

        let to_dev = match to_tier {
            StorageClass::Gold => 0,
            StorageClass::Silver => 1,
            StorageClass::Bronze => 2,
        };

        let mut devices = match BLOCK_DEVICES.try_lock() {
            Some(d) => d,
            None => return 0,
        };

        // Assume object occupies 20 blocks
        let object_blocks = 20u64;
        let base_block = object_id * 100;

        for i in 0..object_blocks {
            let mut buffer = vec![0u8; 512];
            let block_id = (base_block + i) as usize;

            // Read from source tier
            let read_ok = if let Some(src) = devices.get_mut(from_dev) {
                src.read_block(block_id, &mut buffer).is_ok()
            } else {
                false
            };

            if !read_ok {
                continue;
            }

            // Write to destination tier
            let write_ok = if let Some(dst) = devices.get_mut(to_dev) {
                dst.write_block(block_id, &buffer).is_ok()
            } else {
                false
            };

            if write_ok {
                blocks_moved += 1;
            }
        }

        blocks_moved
    }

    /// Get statistics
    pub fn stats(&self) -> TierStats {
        let mut gold_count = 0u64;
        let mut silver_count = 0u64;
        let mut bronze_count = 0u64;

        for stats in self.access_stats.values() {
            match stats.current_tier {
                StorageClass::Gold => gold_count += 1,
                StorageClass::Silver => silver_count += 1,
                StorageClass::Bronze => bronze_count += 1,
            }
        }

        TierStats {
            total_objects: self.access_stats.len() as u64,
            gold_tier_objects: gold_count,
            silver_tier_objects: silver_count,
            bronze_tier_objects: bronze_count,
            promote_threshold: self.threshold_promote.value,
            promote_confidence: self.threshold_promote.confidence(),
            demote_threshold: self.threshold_demote.value,
            demote_confidence: self.threshold_demote.confidence(),
        }
    }

    /// Legacy API: Check migration for DVA
    pub fn check_migration_dva(&self, dva: Dva, access_count: u64) -> Option<usize> {
        let current_class = self.vdev_map[dva.vdev as usize];
        let object_id = dva.offset; // Use offset as object ID

        let stats = AccessStats {
            object_id,
            current_tier: current_class,
            access_count,
            read_count: access_count,
            write_count: 0,
            last_access_ms: 0,
            creation_ms: 0,
            size_bytes: 4096,
            access_frequency: access_count as f64 / 100.0,
            idle_time_ms: 0,
        };

        // Use learned thresholds instead of hardcoded
        let heat = stats.heat_score();

        if current_class == StorageClass::Gold && heat < self.threshold_demote.value {
            // Find a Silver VDEV
            for (id, class) in self.vdev_map.iter().enumerate() {
                if *class == StorageClass::Silver {
                    crate::lcpfs_println!(
                        "[ TIER ] Block {:?} is COLD (heat={:.2}). Demoting to Silver.",
                        dva,
                        heat
                    );
                    return Some(id);
                }
            }
        }

        if current_class == StorageClass::Silver && heat > self.threshold_promote.value {
            // Find a Gold VDEV
            for (id, class) in self.vdev_map.iter().enumerate() {
                if *class == StorageClass::Gold {
                    crate::lcpfs_println!(
                        "[ TIER ] Block {:?} is HOT (heat={:.2}). Promoting to Gold.",
                        dva,
                        heat
                    );
                    return Some(id);
                }
            }
        }

        None
    }
}

/// Decision to migrate an object between storage tiers.
#[derive(Debug, Clone, Copy)]
pub enum MigrationDecision {
    /// Migrate to a faster tier (hot data)
    Promote {
        /// Object to migrate
        object_id: u64,
        /// Current tier
        from_tier: StorageClass,
        /// Target tier (faster)
        to_tier: StorageClass,
        /// Estimated epsilon reduction from this migration
        estimated_benefit: f64,
    },
    /// Migrate to a slower tier (cold data)
    Demote {
        /// Object to migrate
        object_id: u64,
        /// Current tier
        from_tier: StorageClass,
        /// Target tier (slower)
        to_tier: StorageClass,
        /// Estimated epsilon reduction from this migration
        estimated_benefit: f64,
    },
}

/// Policy for selecting storage tier for new allocations.
pub struct AllocationPolicy {
    /// Desired storage class for this allocation
    pub intent: StorageClass,
}

/// Statistics about current tier distribution and learned thresholds.
#[derive(Debug, Clone, Copy)]
pub struct TierStats {
    /// Total number of tracked objects
    pub total_objects: u64,
    /// Number of objects in Gold tier (NVMe)
    pub gold_tier_objects: u64,
    /// Number of objects in Silver tier (SSD)
    pub silver_tier_objects: u64,
    /// Number of objects in Bronze tier (HDD)
    pub bronze_tier_objects: u64,
    /// Current learned promotion threshold (heat score)
    pub promote_threshold: f64,
    /// Confidence in promotion threshold (0.0 to 1.0)
    pub promote_confidence: f64,
    /// Current learned demotion threshold (heat score)
    pub demote_threshold: f64,
    /// Confidence in demotion threshold (0.0 to 1.0)
    pub demote_confidence: f64,
}

// ═══════════════════════════════════════════════════════════════════════════════
// PUBLIC API
// ═══════════════════════════════════════════════════════════════════════════════

/// Update system epsilon
pub fn update_epsilon(epsilon: f64) {
    TIER_MANAGER.lock().update_epsilon(epsilon);
}

/// Record an access to an object
pub fn record_access(object_id: u64, is_write: bool, timestamp_ms: u64, size: u64) {
    TIER_MANAGER
        .lock()
        .record_access(object_id, is_write, timestamp_ms, size);
}

/// Check if an object should be migrated
pub fn check_migration(object_id: u64, current_time_ms: u64) -> Option<MigrationDecision> {
    TIER_MANAGER
        .lock()
        .check_migration(object_id, current_time_ms)
}

/// Execute a migration decision
pub fn execute_migration(decision: &MigrationDecision, current_time_ms: u64) {
    TIER_MANAGER
        .lock()
        .execute_migration(decision, current_time_ms);
}

/// Get current statistics
pub fn stats() -> TierStats {
    TIER_MANAGER.lock().stats()
}

/// Select VDEV for new allocation
pub fn select_vdev(policy: AllocationPolicy) -> usize {
    TIER_MANAGER.lock().select_vdev(policy)
}