Cache.lean

Lean 4 source, lean/DataMiningAsObservation/Cache.lean at commit bccca4f. Appendix C, Machine-checked statements, says what each file proves. All Lean files.

/-
Cache.lean. Chapter 13 section 13.5, the cache.

A cache reader reads the entries in its footprint and nothing else. Its hit rate over a
stream of requests is the fraction of requests whose key the cache holds, in the unit
interval, zero for a cold cache that holds nothing, one for a warm cache that holds the
whole footprint, and never lower for a cache that holds more. Which entries matter is a
property of the requests and not of the cache, which is why a cold and a warm measurement
of the same system are two different observers of it.
-/
import Mathlib

namespace DMO.Cache

open Finset

variable {κ : Type*} [DecidableEq κ]

/-- The requests that hit, those whose key the cache `C` holds. -/
def hits (R : Finset κ) (C : Finset κ) : Finset κ := R.filter fun k => k ∈ C

/-- The hit rate over the requests `R`. -/
noncomputable def hitRate (R C : Finset κ) : ℝ := (hits R C).card / R.card

/-- **The hit rate lies in the unit interval.** -/
theorem hitRate_mem_unit (R C : Finset κ) (hR : R.Nonempty) : 0 ≤ hitRate R C ∧ hitRate R C ≤ 1 := by
  unfold hitRate
  have hpos : (0 : ℝ) < R.card := by exact_mod_cast hR.card_pos
  refine ⟨by positivity, ?_⟩
  rw [div_le_one hpos]
  exact_mod_cast Finset.card_filter_le _ _

/-- **A cold cache hits nothing.** -/
theorem hitRate_cold (R : Finset κ) : hitRate R ∅ = 0 := by
  simp [hitRate, hits]

/-- **A warm cache holding the footprint hits everything.** -/
theorem hitRate_warm (R C : Finset κ) (hR : R.Nonempty) (h : R ⊆ C) : hitRate R C = 1 := by
  unfold hitRate hits
  rw [Finset.filter_true_of_mem fun k hk => h hk]
  exact div_self (by exact_mod_cast hR.card_pos.ne')

/-- **Holding more never lowers the hit rate.** -/
theorem hitRate_mono (R C C' : Finset κ) (h : C ⊆ C') : hitRate R C ≤ hitRate R C' := by
  unfold hitRate hits
  apply div_le_div_of_nonneg_right _ (by positivity)
  exact_mod_cast Finset.card_le_card (Finset.monotone_filter_right R fun _ _ hk => h hk)

/-- **The footprint is a property of the requests.** Entries outside the requests change no
hit rate, however many there are. -/
theorem hitRate_footprint (R C E : Finset κ) (hE : Disjoint R E) : hitRate R (C ∪ E) = hitRate R C := by
  unfold hitRate hits
  have h : R.filter (fun k => k ∈ C ∪ E) = R.filter (fun k => k ∈ C) := by
    apply Finset.filter_congr
    intro k hk
    have : k ∉ E := Finset.disjoint_left.1 hE hk
    simp [this]
  rw [h]

end DMO.Cache