{
 "verdict": "pass",
 "decl": "ProbabilityTheory.infinite_monkey",
 "input": {
  "artifact": "https://api.imd.fun/artifacts/6e4fae65aef04d85944ab4a137b25818c8aefcfdf780efc03f9a49e047f73500",
  "artifact_sha256": "6e4fae65aef04d85944ab4a137b25818c8aefcfdf780efc03f9a49e047f73500",
  "producer_status": "proved",
  "has_lean_source": true
 },
 "lean_source": "import Mathlib.Probability.Independence.Basic\nimport Mathlib.Probability.IdentDistrib\nimport Mathlib.Analysis.SpecificLimits.Basic\n\nopen MeasureTheory Filter Set\nopen scoped ENNReal MeasureTheory ProbabilityTheory\n\nnamespace ProbabilityTheory\n\nvariable {Ω A : Type*} [MeasurableSpace Ω] [MeasurableSpace A]\n  [Fintype A] [MeasurableSingletonClass A]\n  {μ : Measure Ω} [IsProbabilityMeasure μ]\n\nprivate def monkeyBlock (X : ℕ → Ω → A) {k : ℕ} (w : Fin k → A) (n : ℕ) : Set Ω :=\n  ⋂ i : Fin k, X (n + (i : ℕ)) ⁻¹' {w i}\n\nomit [Fintype A] in\nprivate lemma measurableSet_monkeyBlock {X : ℕ → Ω → A} (hX : ∀ n, Measurable (X n))\n    {k : ℕ} (w : Fin k → A) (n : ℕ) : MeasurableSet (monkeyBlock X w n) := by\n  unfold monkeyBlock\n  exact MeasurableSet.iInter fun i ↦ (MeasurableSet.singleton (w i)).preimage (hX _)\n\nomit [Fintype A] [IsProbabilityMeasure μ] in\nprivate lemma measure_monkeyBlock {X : ℕ → Ω → A}\n    (h_indep : iIndepFun X μ) (h_ident : ∀ n, IdentDistrib (X n) (X 0) μ μ)\n    {k : ℕ} (w : Fin k → A) (n : ℕ) :\n    μ (monkeyBlock X w n) = ∏ i, μ (X 0 ⁻¹' {w i}) := by\n  have hinj : Function.Injective (fun i : Fin k ↦ n + (i : ℕ)) := by\n    intro i j hij\n    exact Fin.ext (Nat.add_left_cancel hij)\n  have hi := ProbabilityTheory.iIndepFun.precomp hinj h_indep\n  rw [monkeyBlock]\n  have hset : (⋂ i : Fin k, X (n + (i : ℕ)) ⁻¹' {w i}) =\n      ⋂ i ∈ (Finset.univ : Finset (Fin k)), X (n + (i : ℕ)) ⁻¹' {w i} := by simp\n  rw [hset, hi.measure_inter_preimage_eq_mul Finset.univ\n    (sets := fun i : Fin k ↦ {w i}) (by simp)]\n  apply Finset.prod_congr rfl\n  intro i _\n  exact (h_ident (n + i)).measure_preimage_eq (MeasurableSet.singleton (w i))\n\nprivate lemma block_base_mem_Ico {k N m j : ℕ} (hj : j < m) (i : Fin k) :\n    N + j * k + (i : ℕ) ∈ Finset.Ico N (N + m * k) := by\n  have hmul := Nat.mul_le_mul_right k (Nat.succ_le_iff.mpr hj)\n  have hjmul : j * k + k ≤ m * k := by simpa [Nat.add_mul] using hmul\n  have hi := i.isLt\n  simp only [Finset.mem_Ico]\n  omega\n\nprivate lemma block_next_mem_Ico {k N m : ℕ} (i : Fin k) :\n    N + m * k + (i : ℕ) ∈ Finset.Ico (N + m * k) (N + (m + 1) * k) := by\n  simp only [Finset.mem_Ico, Nat.add_mul]\n  omega\n\nprivate lemma monkeyBlock_misses_measure {X : ℕ → Ω → A} (hX : ∀ n, Measurable (X n))\n    (h_indep : iIndepFun X μ) (h_ident : ∀ n, IdentDistrib (X n) (X 0) μ μ)\n    {k : ℕ} (w : Fin k → A) (N m : ℕ) :\n    μ (⋂ j ∈ Finset.range m, (monkeyBlock X w (N + j * k))ᶜ) =\n      (1 - ∏ i, μ (X 0 ⁻¹' {w i})) ^ m := by\n  induction m with\n  | zero => simp\n  | succ m ihm =>\n      let S := Finset.Ico N (N + m * k)\n      let T := Finset.Ico (N + m * k) (N + (m + 1) * k)\n      have hST : Disjoint S T := by\n        rw [Finset.disjoint_left]\n        intro a haS haT\n        simp only [S, T, Finset.mem_Ico] at haS haT\n        omega\n      let F : (S → A) → Prop := fun z ↦\n        ∀ (j : ℕ) (hj : j < m), ¬ ∀ i : Fin k,\n          z ⟨N + j * k + (i : ℕ), block_base_mem_Ico hj i⟩ = w i\n      let G : (T → A) → Prop := fun z ↦\n        ¬ ∀ i : Fin k, z ⟨N + m * k + (i : ℕ), block_next_mem_Ico i⟩ = w i\n      have hfg : IndepFun\n          (fun ω ↦ F (fun i : S ↦ X i ω))\n          (fun ω ↦ G (fun i : T ↦ X i ω)) μ := by\n        exact (h_indep.indepFun_finset S T hST hX).comp\n          (measurable_of_finite F) (measurable_of_finite G)\n      have hpre : {ω | F (fun i : S ↦ X i ω)} =\n          ⋂ j ∈ Finset.range m, (monkeyBlock X w (N + j * k))ᶜ := by\n        ext ω\n        simp only [Set.mem_ofPred_eq, F, Set.mem_iInter, Finset.mem_range, mem_compl_iff,\n          monkeyBlock, Set.mem_preimage, Set.mem_singleton_iff, not_forall]\n      have hnew : {ω | G (fun i : T ↦ X i ω)} =\n          (monkeyBlock X w (N + m * k))ᶜ := by\n        ext ω\n        simp only [Set.mem_ofPred_eq, G, mem_compl_iff, monkeyBlock, Set.mem_iInter,\n          Set.mem_preimage, Set.mem_singleton_iff]\n      have hmul := hfg.measure_inter_preimage_eq_mul ({True} : Set Prop) ({True} : Set Prop)\n        (by simp) (by simp)\n      rw [show (fun ω ↦ F (fun i : S ↦ X i ω)) ⁻¹' ({True} : Set Prop) =\n          {ω | F (fun i : S ↦ X i ω)} by ext; simp,\n        show (fun ω ↦ G (fun i : T ↦ X i ω)) ⁻¹' ({True} : Set Prop) =\n          {ω | G (fun i : T ↦ X i ω)} by ext; simp,\n        hpre, hnew] at hmul\n      have hsucc : (⋂ j ∈ Finset.range (m + 1), (monkeyBlock X w (N + j * k))ᶜ) =\n          (⋂ j ∈ Finset.range m, (monkeyBlock X w (N + j * k))ᶜ) ∩\n            (monkeyBlock X w (N + m * k))ᶜ := by\n        rw [Finset.range_add_one]\n        simp [inter_comm]\n      rw [hsucc, hmul, ihm, measure_compl (measurableSet_monkeyBlock hX w _)\n          (measure_ne_top μ _), measure_univ, measure_monkeyBlock h_indep h_ident w _,\n        pow_succ]\n\n/-- **Infinite monkey theorem** (Wikidata Q487132).  If independent, identically distributed\nletters are drawn from a finite alphabet and every letter has positive probability, then almost\nsurely every finite word occurs as a contiguous block at arbitrarily large positions (and hence\ninfinitely often).  The assertion is simultaneous for all finite words. -/\ntheorem infinite_monkey (X : ℕ → Ω → A) (hX : ∀ n, Measurable (X n))\n    (h_indep : iIndepFun X μ) (h_ident : ∀ n, IdentDistrib (X n) (X 0) μ μ)\n    (h_pos : ∀ a, 0 < μ (X 0 ⁻¹' {a})) :\n    ∀ᵐ ω ∂μ, ∀ (k : ℕ) (w : Fin k → A) (N : ℕ),\n      ∃ n ≥ N, ∀ i : Fin k, X (n + (i : ℕ)) ω = w i := by\n  rw [ae_all_iff]\n  intro k\n  rw [ae_all_iff]\n  intro w\n  rw [ae_all_iff]\n  intro N\n  by_cases hk : k = 0\n  · subst k\n    filter_upwards [] with ω\n    exact ⟨N, le_rfl, fun i ↦ Fin.elim0 i⟩\n  · have hkpos : 0 < k := Nat.pos_of_ne_zero hk\n    let q : ℝ≥0∞ := ∏ i, μ (X 0 ⁻¹' {w i})\n    have hq0 : q ≠ 0 := Finset.prod_ne_zero_iff.mpr fun i _ ↦ (h_pos (w i)).ne'\n    have hq : 0 < q := bot_lt_iff_ne_bot.mpr hq0\n    have hr : 1 - q < (1 : ℝ≥0∞) :=\n      ENNReal.sub_lt_self ENNReal.one_ne_top one_ne_zero hq.ne'\n    let bad : Set Ω := {ω | ∀ n, N ≤ n → ω ∉ monkeyBlock X w n}\n    have hbad_le (m : ℕ) : μ bad ≤ (1 - q) ^ m := by\n      calc\n        μ bad ≤ μ (⋂ j ∈ Finset.range m, (monkeyBlock X w (N + j * k))ᶜ) := by\n          apply measure_mono\n          intro ω hω\n          simp only [bad, Set.mem_ofPred_eq, Set.mem_iInter, Finset.mem_range, mem_compl_iff] at hω ⊢\n          intro j hj\n          exact hω (N + j * k) (Nat.le_add_right N (j * k))\n        _ = (1 - q) ^ m := by\n          simpa [q] using monkeyBlock_misses_measure hX h_indep h_ident w N m\n    have hbad_zero : μ bad = 0 := by\n      apply le_zero_iff.mp\n      exact ge_of_tendsto (ENNReal.tendsto_pow_atTop_nhds_zero_of_lt_one hr)\n        (Eventually.of_forall hbad_le)\n    rw [ae_iff]\n    have hcompl : {ω | ¬ ∃ n ≥ N, ∀ i : Fin k, X (n + (i : ℕ)) ω = w i} = bad := by\n      ext ω\n      simp only [bad, Set.mem_ofPred_eq, not_exists, monkeyBlock, Set.mem_iInter,\n        Set.mem_preimage, Set.mem_singleton_iff]\n      aesop\n    rwa [hcompl]\n\n#print axioms ProbabilityTheory.infinite_monkey\n\nend ProbabilityTheory\n",
 "source_sha256": "32a3a686681be51647b115fdca9f116b22eaf0a126ed3bf3085a045fccb979f7",
 "build_output": "'ProbabilityTheory.infinite_monkey' depends on axioms: [propext, Classical.choice, Quot.sound]\n",
 "build": {
  "command": "export PATH=\"$(ls -d D/lean/*/bin|head -n1):$PATH\" LEAN_PATH=\"$(ls -d D/pk/*/.lake/build/lib/lean|paste -sd: -)\" && lean -DautoImplicit=false InfiniteMonkey.lean",
  "toolchain": "Lean (version 4.36.0, x86_64-unknown-linux-gnu, commit 611c117bfaf7b7ae1cfcf246ce6fba31e8f509e9, Release); Mathlib fc4f59e prebuilt (bundle pequalnp-e125f04d0dc6)",
  "bundles_sha256_checked": {
   "lean-4.36.0-linux.tar.zst": "2b7ab1ed8b92d2e6abfaf41344823b510064dbc9c0260cac73eb496ab2dea6eb (matches fetch.json)",
   "pequalnp-e125f04d0dc6-packages-lean-4.36.0-linux-x64.tar.zst": "69b68c745d0bd8dba3ab21966f8cdb14f9373bd4f1df1d17680f4b80dad98a88 (matches fetch.json)"
  },
  "exit_code": 0,
  "wall_time": "about 13 s",
  "errors": 0,
  "warnings": 0,
  "axioms": "[propext, Classical.choice, Quot.sound]",
  "forbidden_tokens": "A grep of the source for sorry, admit, native_decide, axiom, implemented_by, extern, unsafe, opaque found nothing.",
  "note": "The source was saved unchanged from the input's lean_source field (sha256 above) and compiled in a fresh directory with no other files. The #print axioms command is the second-to-last line; the last line is `end ProbabilityTheory`. That is harmless, but the brief's wording 'its last line' is not literally accurate."
 },
 "fidelity_review": {
  "summary": "Faithful. The Lean statement is the infinite monkey theorem in the vetted generality: a general probability space, iIndepFun, identical distribution with an arbitrary (possibly non-uniform) law in which every letter has positive mass, a finite alphabet, and one almost-sure event that serves every finite word (empty word included) at arbitrarily large starting positions.",
  "statement_checked": "theorem infinite_monkey (X : ℕ → Ω → A) (hX : ∀ n, Measurable (X n)) (h_indep : iIndepFun X μ) (h_ident : ∀ n, IdentDistrib (X n) (X 0) μ μ) (h_pos : ∀ a, 0 < μ (X 0 ⁻¹' {a})) : ∀ᵐ ω ∂μ, ∀ (k : ℕ) (w : Fin k → A) (N : ℕ), ∃ n ≥ N, ∀ i : Fin k, X (n + (i : ℕ)) ω = w i, where [MeasurableSpace Ω] [MeasurableSpace A] [Fintype A] [MeasurableSingletonClass A] {μ : Measure Ω} [IsProbabilityMeasure μ] (confirmed with #check against the compiled declaration).",
  "clauses": {
   "finite_alphabet": "OK. [Fintype A]. [MeasurableSingletonClass A] only makes the letter events measurable; on a finite type it forces every subset to be measurable, so it loses no generality. The alphabet may be any finite type, including one with a single letter.",
   "general_probability_space": "OK. Ω and the measurable space on it are arbitrary, and μ is any measure with [IsProbabilityMeasure μ]. Nothing assumes a product space or a coordinate process.",
   "independence": "OK. h_indep : iIndepFun X μ is Mathlib's mutual independence of the whole family: the σ-algebras comap (X i) are iIndep. That is the textbook notion, not pairwise independence.",
   "identically_distributed": "OK. ∀ n, IdentDistrib (X n) (X 0) μ μ says μ.map (X n) = μ.map (X 0), plus a.e.-measurability. The common law is arbitrary, so it need not be uniform.",
   "positive_letters": "OK. ∀ a, 0 < μ (X 0 ⁻¹' {a}): every letter has positive probability under X 0, and so under every X n by IdentDistrib. Equal probabilities are not required.",
   "measurability": "OK, a standard harmless hypothesis. hX : ∀ n, Measurable (X n) is stronger than the a.e.-measurability already implied by IdentDistrib, but every textbook random variable is measurable. (It could be weakened; see repairs, which are optional.)",
   "contiguous_block": "OK. ∀ i : Fin k, X (n + i) ω = w i says exactly that X n, ..., X (n+k-1) spells the word w = (w 0, ..., w (k-1)). Fin k → A ranges over all words of length k, and ∀ k ranges over all finite words.",
   "arbitrarily_late_and_infinitely_often": "OK. ∀ N, ∃ n ≥ N gives occurrences at arbitrarily large positions. In scratch I proved in Lean, from the theorem, the corollary ∀ᵐ ω ∂μ, ∀ k w, Set.Infinite {n | ∀ i : Fin k, X (n+i) ω = w i}, via Nat.frequently_atTop_iff_infinite. This compiled with no errors.",
   "single_event_for_all_words": "OK. The ∀ᵐ quantifier comes before ∀ k w N, so one μ-conull set of ω serves every word and every cutoff at once, as the vetted statement requires. A weaker 'for each word, almost surely' form would put ∀ k w outside ∀ᵐ, and that is not what is stated here.",
   "edge_cases": "Empty word: k = 0 is included, and the conclusion holds trivially at n = N. One-letter alphabet: allowed; I checked in scratch that the hypotheses hold for A = Unit with the Dirac product measure. Unequal probabilities: allowed; I checked a Bernoulli(1/3) law.",
   "non_vacuity": "Hypotheses are satisfiable, verified in Lean (scratch file, compiled with no errors and only deprecation warnings for PMF.bernoulli): for Ω = ℕ → Bool with Measure.infinitePi (fun _ ↦ (PMF.bernoulli (1/3) _).toMeasure) and X n ω = ω n, I proved hX, iIndepFun (via Mathlib's iIndepFun_infinitePi), IdentDistrib (via Measure.infinitePi_map_eval) and h_pos, then applied infinite_monkey. I did the same for A = Unit with Dirac measures.",
   "not_trivial": "The conclusion is not provable without the hypotheses: for a constant sequence X n = a with a two-letter alphabet, the word (b) never occurs. The proof does real work: the exact block-miss probability (1-q)^m by induction, using iIndepFun.indepFun_finset on disjoint index intervals, then a limit to zero and countable a.e. intersections. No hypothesis is contradictory, and no definition is redefined. The only auxiliary definition (private monkeyBlock) appears in proofs, not in the statement.",
   "proof_route": "Disjoint blocks at N + j*k for j < m, independence across two disjoint Finset.Ico index sets, and the miss probability (1 - ∏ μ(X 0 = w i))^m → 0. This is the standard textbook proof (the Wikipedia block argument), done directly rather than through Borel–Cantelli."
  },
  "style_and_upstream_notes": "The docstring quotes the informal statement and the Wikidata id Q487132. The name follows Mathlib's snake_case style. For an upstream PR you would remove the `#print axioms` line, perhaps import only what is needed (the imports are already narrow), and Mathlib reviewers might prefer a more descriptive name or an alias, e.g. `ae_forall_frequently_block_eq`. None of this affects correctness."
 },
 "prior_work": [
  {
   "search": "Mathlib master docs/1000.yaml entry for Q487132",
   "url": "https://raw.githubusercontent.com/leanprover-community/mathlib4/master/docs/1000.yaml",
   "finding": "Fetched 2026-11-26 (master head e54979a532247ae4eb9d5578a8fd40a1bc332101, committed 2026-11-26T12:14:34Z). The entry is only 'Q487132:\\n  title: Infinite monkey theorem', with no decl/decls/author field, so it is not formalized in Mathlib."
  },
  {
   "search": "1000+ missing theorems page",
   "url": "https://leanprover-community.github.io/1000-missing.html",
   "finding": "Still lists 'Q487132: Infinite monkey theorem' as missing."
  },
  {
   "search": "1000+ theorems (formalized) page",
   "url": "https://leanprover-community.github.io/1000.html",
   "finding": "Q487132 does not occur on the page (grep count 0)."
  },
  {
   "search": "Mathlib source at fc4f59e (Mathlib, Archive, Counterexamples), local grep for 'monkey' (case-insensitive)",
   "url": "https://github.com/leanprover-community/mathlib4/tree/fc4f59e",
   "finding": "No match. The closest existing result is the second Borel–Cantelli lemma ProbabilityTheory.measure_limsup_eq_one in Mathlib/Probability/BorelCantelli.lean, which is a tool and not the monkey theorem."
  },
  {
   "search": "Open Mathlib PRs: is:pr is:open \"infinite monkey\"",
   "url": "https://api.github.com/search/issues?q=repo:leanprover-community/mathlib4+is:pr+is:open+%22infinite+monkey%22",
   "finding": "total_count 0."
  },
  {
   "search": "Open Mathlib PRs: is:pr is:open Q487132",
   "url": "https://api.github.com/search/issues?q=repo:leanprover-community/mathlib4+is:pr+is:open+Q487132",
   "finding": "total_count 0."
  },
  {
   "search": "All Mathlib PRs (open or closed) mentioning \"monkey\"",
   "url": "https://api.github.com/search/issues?q=repo:leanprover-community/mathlib4+is:pr+%22monkey%22",
   "finding": "total_count 0."
  },
  {
   "search": "GitHub repository search 'infinite monkey lean'",
   "url": "https://api.github.com/search/repositories?q=infinite+monkey+lean",
   "finding": "total_count 0."
  },
  {
   "search": "GitHub code search \"infinite_monkey\" language:Lean",
   "url": "https://api.github.com/search/code?q=%22infinite_monkey%22+language:Lean",
   "finding": "UNVERIFIED: the API answered 401 'Requires authentication', so GitHub code search could not be run. Web searches ('\"infinite monkey\" Lean 4 Mathlib formalization'; '\"infinite monkey theorem\" leanprover zulip OR github lean') turned up no Lean formalization."
  },
  {
   "search": "Lean Zulip search 'infinite monkey'",
   "url": "https://leanprover.zulipchat.com/api/v1/messages?anchor=newest&num_before=20&num_after=0&narrow=%5B%7B%22operator%22%3A%22search%22%2C%22operand%22%3A%22infinite%20monkey%22%7D%5D",
   "finding": "UNVERIFIED: the API answered UNAUTHORIZED ('Not logged in'). The site web search found no indexed Zulip thread on a Lean formalization. That is not exhaustive."
  }
 ],
 "prior_work_conclusion": "No prior Lean formalization was found in Mathlib master, its 1000.yaml, the open Mathlib PRs or GitHub repository search. GitHub code search and an authenticated Zulip search could not be run and are UNVERIFIED.",
 "explanation": "Statement: take a finite alphabet A and an infinite sequence of random letters X0, X1, X2, ... on any probability space. The letters are mutually independent and all have the same distribution, and every letter has positive probability (the probabilities need not be equal). Then, with probability one, a single outcome ω has this property: every finite word w over A, of any length k and including the empty word, appears as a run of consecutive letters X n, ..., X (n+k-1) starting at some position n beyond any cutoff N you choose. So every word appears infinitely often. Proof: fix a nonempty word w of length k. By independence and identical distribution, the chance that a fixed block of k consecutive letters spells w is q = product of the probabilities of w's letters, and q > 0. Look at the non-overlapping blocks starting at N, N+k, N+2k, .... Because they use disjoint sets of letters they are independent, so the chance that the first m blocks all miss w is exactly (1-q)^m. The event 'w never appears at or after N' lies inside every such event, so its probability is at most (1-q)^m for every m, which tends to 0. That event therefore has probability 0. There are only countably many triples (k, w, N), and a countable union of null events is null, so a single probability-one event handles all words and all cutoffs at once. The empty word is trivial.",
 "database_entry": {
  "wikidata_id": "Q487132",
  "title": "Infinite monkey theorem",
  "declaration": "ProbabilityTheory.infinite_monkey",
  "file": "InfiniteMonkey.lean",
  "yaml": "Q487132:\n  title: Infinite monkey theorem\n  decl: ProbabilityTheory.infinite_monkey",
  "note": "The file is not in Mathlib. If upstreamed, the decl field applies once it is merged; until then an external-project entry would need the hosting URL, which does not exist yet (UNVERIFIED)."
 },
 "repairs": [
  "None required for correctness or fidelity.",
  "Optional, upstream style: remove the `#print axioms` line from the library file.",
  "Optional generalization: hX : ∀ n, Measurable (X n) could be weakened to AEMeasurable, which IdentDistrib already provides. The theorem as stated is the standard textbook form.",
  "Optional: the brief says the last line prints the axioms; in fact it is the second-to-last (followed by `end ProbabilityTheory`). This has no effect."
 ],
 "checks_not_done": [
  "GitHub code search (needs authentication): UNVERIFIED",
  "Authenticated Lean Zulip search: UNVERIFIED",
  "Build against a Mathlib newer than fc4f59e (only the pinned bundle was used): UNVERIFIED"
 ],
 "sources": [
  "https://leanprover-community.github.io/1000-missing.html",
  "https://raw.githubusercontent.com/leanprover-community/mathlib4/master/docs/1000.yaml",
  "https://api.github.com/search/issues?q=repo:leanprover-community/mathlib4+is:pr+is:open+%22infinite+monkey%22",
  "https://raw.githubusercontent.com/leanprover-community/mathlib4/fc4f59e/Mathlib/Probability/Independence/Basic.lean",
  "https://raw.githubusercontent.com/leanprover-community/mathlib4/fc4f59e/Mathlib/Probability/IdentDistrib.lean",
  "https://raw.githubusercontent.com/leanprover-community/mathlib4/fc4f59e/Mathlib/Probability/Independence/InfinitePi.lean",
  "https://raw.githubusercontent.com/leanprover-community/mathlib4/fc4f59e/Mathlib/Probability/BorelCantelli.lean",
  "https://en.wikipedia.org/wiki/Infinite_monkey_theorem",
  "https://github.com/Identity-md/lean-bundles/releases/download/pequalnp-e125f04d0dc6/fetch.json",
  "https://api.imd.fun/artifacts/6e4fae65aef04d85944ab4a137b25818c8aefcfdf780efc03f9a49e047f73500"
 ]
}