Abdullah bin Abbas reported,

A madwoman who had committed adultery was brought to Umar. He consulted a number of people about her case, and then Umar ordered that she be stoned.She was led past Ali bin Abu Talib, may Allah be pleased with him, and he asked, "What is the matter with this woman?"They said, "She is the madwoman of such and such a tribe. She committed adultery, so Umar ordered that she be stoned."Ali said, "Take her back."Then he went to Umar and said, "Commander of the Faithful, do you not know that the pen has been lifted from three, from the insane person until he recovers, from the sleeper until he awakens, and from the child until he reaches the age of understanding?"Umar said, "Yes, indeed."Ali said, "Then why is this woman to be stoned?"Umar said, "For no reason at all."Ali said, "Then let her go."So Umar let her go, and he began to say, "Allah is the Greatest."In another wording it says, "until he reaches the age of understanding," and, "from the insane person until he comes to his senses," and, "Umar began to say, 'Allah is the Greatest.'"

Abu Dawud 4400

Sahih

حدثنا يوسف بن موسى حدثنا وكيع عن الأعمش نحوه وقال أيضا حتى يعقل وقال وعن المجنون حتى يفيق قال فجعل عمر يكبر

أبو داود 4400صحيح
Contents
Reference
Commentary
Ayat
Collection
Sunan Abu Dawud
Book
Legal punishments
Chapter
Insane person who steals or commits a crime deserving a hadd punishment
Numbering
Darussalam 4400
Abu Dawud 4400