Reliable and robust software needs to function well even when given illegal inputs. One common way to handle illegal inputs is to equip the software with preconditions. Since manually deriving and specifying preconditions is an error-prone and tedious process, there is great need on automatic learning of preconditions. To learn stateful preconditions (i.e., preconditions constraining not only primitive-type inputs but also non-primitive-type inputs with object states), in this paper, we present a novel formalization for the inference problem of stateful precondition modulo a test generator (i.e., a testing-based teacher), where the quality of the precondition is based on its safety and maximality with respect to the test generator. Based on such formalization, we propose a novel learning framework for inferring stateful preconditions based on a machine-learning algorithm for decision trees, including techniques for addressing statefulness and complexity of the target precondition based on an incomplete set of data points. Given the iterative nature of our learning algorithm, we provide convergence arguments that our learning algorithm will eventually synthesize a safe and maximal precondition, if there is one. We instantiate our framework for two tasks of specification inference. Our evaluation on various C# classes from well-known benchmarks and open source projects demonstrates the effectiveness of the proposed framework.