Mining Function Specifications (for dynamic invariants)
3 days ago
4
When testing a program, one not only needs to cover its several behaviors; one also needs to check whether the result is as expected. In this chapter, we introduce a technique that allows us to mine function specifications from a set of given executions, resulting in abstract and formal descriptions of what the function expects and what it delivers.
These so-called dynamic invariants produce pre- and post-conditions over function arguments and variables from a set of executions. They are useful in a variety of contexts:
Dynamic invariants provide important information for symbolic fuzzing, such as types and ranges of function arguments.
Dynamic invariants provide pre- and postconditions for formal program proofs and verification.
Dynamic invariants provide numerous assertions that can check whether function behavior has changed
Checks provided by dynamic invariants can be very useful as oracles for checking the effects of generated tests
Traditionally, dynamic invariants are dependent on the executions they are derived from. However, when paired with comprehensive test generators, they quickly become very precise, as we show in this chapter.
Prerequisites
You should be familiar with tracing program executions, as in the chapter on coverage.
Later in this section, we access the internal abstract syntax tree representations of Python programs and transform them, as in the chapter on information flow.
The functions_with_invariants() method will return a representation of sum2() annotated with inferred pre- and postconditions that all hold for the observed values.
Such type specifications and invariants can be helpful as oracles (to detect deviations from a given set of runs) as well as for all kinds of symbolic code analyses. The chapter gives details on how to customize the properties checked for.
When implementing a function or program, one usually works against a specification – a set of documented requirements to be satisfied by the code. Such specifications can come in natural language. A formal specification, however, allows the computer to check whether the specification is satisfied.
In the introduction to testing, we have seen how preconditions and postconditions can describe what a function does. Consider the following (simple) square root function:
The assertion assert p checks the condition p; if it does not hold, execution is aborted. Here, the actual body is not yet written; we use the assertions as a specification of what any_sqrt() expects, and what it delivers.
The topmost assertion is the precondition, stating the requirements on the function arguments. The assertion at the end is the postcondition, stating the properties of the function result (including its relationship with the original arguments). Using these pre- and postconditions as a specification, we can now go and implement a square root function that satisfies them. Once implemented, we can have the assertions check at runtime whether any_sqrt() works as expected; a symbolic or concolic test generator will even specifically try to find inputs where the assertions do not hold. (An assertion can be seen as a conditional branch towards aborting the execution, and any technique that tries to cover all code branches will also try to invalidate as many assertions as possible.)
However, not every piece of code is developed with explicit specifications in the first place; let alone does most code comes with formal pre- and post-conditions. (Just take a look at the chapters in this book.) This is a pity: As Ken Thompson famously said, "Without specifications, there are no bugs – only surprises". It is also a problem for testing, since, of course, testing needs some specification to test against. This raises the interesting question: Can we somehow retrofit existing code with "specifications" that properly describe their behavior, allowing developers to simply check them rather than having to write them from scratch? This is what we do in this chapter.
Before we go into mining specifications, let us first discuss why it could be useful to have them. As a motivating example, consider the full implementation of a square root function from the introduction to testing:
defmy_sqrt(x):"""Computes the square root of x, using the Newton-Raphson method"""approx=Noneguess=x/2whileapprox!=guess:approx=guessguess=(approx+x/approx)/2returnapprox
my_sqrt() does not come with any functionality that would check types or values. Hence, it is easy for callers to make mistakes when calling my_sqrt():
withExpectError():my_sqrt("foo")
Traceback (most recent call last):
File "/var/folders/n2/xd9445p97rb3xh7m1dfx8_4h0006ts/T/ipykernel_35443/829521914.py", line 2, in <module>
my_sqrt("foo")
File "/var/folders/n2/xd9445p97rb3xh7m1dfx8_4h0006ts/T/ipykernel_35443/2661069967.py", line 4, in my_sqrt
guess = x / 2
~~^~~
TypeError: unsupported operand type(s) for /: 'str' and 'int' (expected)
withExpectError():x=my_sqrt(0.0)
Traceback (most recent call last):
File "/var/folders/n2/xd9445p97rb3xh7m1dfx8_4h0006ts/T/ipykernel_35443/1975547953.py", line 2, in <module>
x = my_sqrt(0.0)
^^^^^^^^^^^^
File "/var/folders/n2/xd9445p97rb3xh7m1dfx8_4h0006ts/T/ipykernel_35443/2661069967.py", line 7, in my_sqrt
guess = (approx + x / approx) / 2
~~^~~~~~~~
ZeroDivisionError: float division by zero (expected)
At least, the Python system catches these errors at runtime. The following call, however, simply lets the function enter an infinite loop:
withExpectTimeout(1):x=my_sqrt(-1.0)
Traceback (most recent call last):
File "/var/folders/n2/xd9445p97rb3xh7m1dfx8_4h0006ts/T/ipykernel_35443/1349814288.py", line 2, in <module>
x = my_sqrt(-1.0)
^^^^^^^^^^^^^
File "/var/folders/n2/xd9445p97rb3xh7m1dfx8_4h0006ts/T/ipykernel_35443/2661069967.py", line 5, in my_sqrt
while approx != guess:
^^^^^^^^^^^^^^^
File "Timeout.ipynb", line 43, in timeout_handler
raise TimeoutError()
TimeoutError (expected)
Our goal is to avoid such errors by annotating functions with information that prevents errors like the above ones. The idea is to provide a specification of expected properties – a specification that can then be checked at runtime or statically.
For our Python code, one of the most important "specifications" we need is types. Python being a "dynamically" typed language means that all data types are determined at run time; the code itself does not explicitly state whether a variable is an integer, a string, an array, a dictionary – or whatever.
As writer of Python code, omitting explicit type declarations may save time (and allows for some fun hacks). It is not sure whether a lack of types helps in reading and understanding code for humans. For a computer trying to analyze code, the lack of explicit types is detrimental. If, say, a constraint solver, sees if x: and cannot know whether x is supposed to be a number or a string, this introduces an ambiguity. Such ambiguities may multiply over the entire analysis in a combinatorial explosion – or in the analysis yielding an overly inaccurate result.
Python 3.6 and later allows data types as annotations to function arguments (actually, to all variables) and return values. We can, for instance, state that my_sqrt() is a function that accepts a floating-point value and returns one:
defmy_sqrt_with_type_annotations(x:float)->float:"""Computes the square root of x, using the Newton-Raphson method"""returnmy_sqrt(x)
By default, such annotations are ignored by the Python interpreter. Therefore, one can still call my_sqrt_typed() with a string as an argument and get the exact same result as above. However, one can make use of special typechecking modules that would check types – dynamically at runtime or statically by analyzing the code without having to execute it.
(Commented out as enforce is not supported by Python 3.9)
The Python enforce package provides a function decorator that automatically inserts type-checking code that is executed at runtime. Here is how to use it:
# @enforce.runtime_validation# def my_sqrt_with_checked_type_annotations(x: float) -> float:# """Computes the square root of x, using the Newton-Raphson method"""# return my_sqrt(x)
Now, invoking my_sqrt_with_checked_type_annotations() raises an exception when invoked with a type different from the one declared:
# with ExpectError():# my_sqrt_with_checked_type_annotations(True)
Note that this error is not caught by the "untyped" variant, where passing a boolean value happily returns $\sqrt{1}$ as result.
In Python (and other languages), the boolean values True and False can be implicitly converted to the integers 1 and 0; however, it is hard to think of a call to sqrt() where this would not be an error.
Type annotations can also be checked statically – that is, without even running the code. Let us create a simple Python file consisting of the above my_sqrt_typed() definition and a bad invocation.
These are the contents of our newly created Python file:
defmy_sqrt(x):
"""Computes the square root of x, using the Newton-Raphson method"""
approx = None
guess = x / 2while approx != guess:
approx = guess
guess = (approx + x / approx) / 2return approx
defmy_sqrt_with_type_annotations(x: float) -> float:
"""Computes the square root of x, using the Newton-Raphson method"""return my_sqrt(x)
print(my_sqrt_with_type_annotations('123'))
Mypy is a type checker for Python programs. As it checks types statically, types induce no overhead at runtime; plus, a static check can be faster than a lengthy series of tests with runtime type checking enabled. Let us see what mypy produces on the above file:
/var/folders/n2/xd9445p97rb3xh7m1dfx8_4h0006ts/T/tmpe7k1dgu9.py:1: error: Function is missing a type annotation [no-untyped-def]
/var/folders/n2/xd9445p97rb3xh7m1dfx8_4h0006ts/T/tmpe7k1dgu9.py:12: error: Returning Any from function declared to return "float"[no-any-return]
/var/folders/n2/xd9445p97rb3xh7m1dfx8_4h0006ts/T/tmpe7k1dgu9.py:12: error: Call to untyped function "my_sqrt" in typed context [no-untyped-call]
/var/folders/n2/xd9445p97rb3xh7m1dfx8_4h0006ts/T/tmpe7k1dgu9.py:14: error: Argument 1 to "my_sqrt_with_type_annotations" has incompatible type "str"; expected "float"[arg-type]Found 4 errors in 1 file (checked 1 source file)
We see that mypy complains about untyped function definitions such as my_sqrt(); most important, however, it finds that the call to my_sqrt_with_type_annotations() in the last line has the wrong type.
With mypy, we can achieve the same type safety with Python as in statically typed languages – provided that we as programmers also produce the necessary type annotations. Is there a simple way to obtain these?
Our first task will be to mine type annotations (as part of the code) from values we observe at run time. These type annotations would be mined from actual function executions, learning from (normal) runs what the expected argument and return types should be. By observing a series of calls such as these, we could infer that both x and the return value are of type float:
How can we mine types from executions? The answer is simple:
We observe a function during execution
We track the types of its arguments
We include these types as annotations into the code.
To do so, we can make use of Python's tracing facility we already observed in the chapter on coverage. With every call to a function, we retrieve the arguments, their values, and their types.
To observe argument types at runtime, we define a tracer function that tracks the execution of my_sqrt(), checking its arguments and return values. The Tracker class is set to trace functions in a with block as follows:
As in the chapter on coverage, we use the sys.settrace() function to trace individual functions during execution. We turn on tracking when the with block starts; at this point, the __enter__() method is called. When execution of the with block ends, __exit()__ is called.
classTracker:def__init__(self,log=False):self._log=logself.reset()defreset(self):self._calls={}self._stack=[]deftraceit(self):"""Placeholder to be overloaded in subclasses"""pass# Start of `with` blockdef__enter__(self):self.original_trace_function=sys.gettrace()sys.settrace(self.traceit)returnself# End of `with` blockdef__exit__(self,exc_type,exc_value,tb):sys.settrace(self.original_trace_function)
The traceit() method does nothing yet; this is done in specialized subclasses. The CallTracker class implements a traceit() function that checks for function calls and returns:
classCallTracker(Tracker):deftraceit(self,frame,event,arg):"""Tracking function: Record all calls and all args"""ifevent=="call":self.trace_call(frame,event,arg)elifevent=="return":self.trace_return(frame,event,arg)returnself.traceit
trace_call() is called when a function is called; it retrieves the function name and current arguments, and saves them on a stack.
classCallTracker(CallTracker):deftrace_call(self,frame,event,arg):"""Save current function name and args on the stack"""code=frame.f_codefunction_name=code.co_namearguments=get_arguments(frame)self._stack.append((function_name,arguments))ifself._log:print(simple_call_string(function_name,arguments))
defget_arguments(frame):"""Return call arguments in the given frame"""# When called, all arguments are local variableslocal_variables=dict(frame.f_locals)# explicit copyarguments=[(var,frame.f_locals[var])forvarinlocal_variables]arguments.reverse()# Want same order as callreturnarguments
When the function returns, trace_return() is called. We now also have the return value. We log the whole call with arguments and return value (if desired) and save it in our list of calls.
classCallTracker(CallTracker):deftrace_return(self,frame,event,arg):"""Get return value and store complete call with arguments and return value"""code=frame.f_codefunction_name=code.co_namereturn_value=arg# TODO: Could call get_arguments() here to also retrieve _final_ values of argument variablescalled_function_name,called_arguments=self._stack.pop()assertfunction_name==called_function_nameifself._log:print(simple_call_string(function_name,called_arguments),"returns",return_value)self.add_call(function_name,called_arguments,return_value)
simple_call_string() is a helper for logging that prints out calls in a user-friendly manner.
defsimple_call_string(function_name,argument_list,return_value=None):"""Return function_name(arg[0], arg[1], ...) as a string"""call=function_name+"("+ \
", ".join([var+"="+repr(value)for(var,value)inargument_list])+")"ifreturn_valueisnotNone:call+=" = "+repr(return_value)returncall
add_call() saves the calls in a list; each function name has its own list.
classCallTracker(CallTracker):defadd_call(self,function_name,arguments,return_value=None):"""Add given call to list of calls"""iffunction_namenotinself._calls:self._calls[function_name]=[]self._calls[function_name].append((arguments,return_value))
Using calls(), we can retrieve the list of calls, either for a given function, or for all functions.
classCallTracker(CallTracker):defcalls(self,function_name=None):"""Return list of calls for function_name, or a mapping function_name -> calls for all functions tracked"""iffunction_nameisNone:returnself._callsreturnself._calls[function_name]
Let us now put this to use. We turn on logging to track the individual calls and their return values:
Despite what you may have read or heard, Python actually is a typed language. It is just that it is dynamically typed – types are used and checked only at runtime (rather than declared in the code, where they can be statically checked at compile time). We can thus retrieve types of all values within Python:
We can retrieve the type of the first argument to my_sqrt():
This is a representation we could place in a static type checker, allowing to check whether calls to my_sqrt() actually pass a number. A dynamic type checker could run such checks at runtime. And of course, any symbolic interpretation will greatly profit from the additional annotations.
By default, Python does not do anything with such annotations. However, tools can access annotations from functions and other objects:
my_sqrt_annotated.__annotations__
{'x': float, 'return': float}
This is how run-time checkers access the annotations to check against.
Our plan is to annotate functions automatically, based on the types we have seen. To do so, we need a few modules that allow us to convert a function into a tree representation (called abstract syntax trees, or ASTs) and back; we already have seen these in the chapters on concolic and symbolic testing.
We can get the source of a Python function using inspect.getsource(). (Note that this does not work for functions defined in other notebooks.)
'def my_sqrt(x):\n """Computes the square root of x, using the Newton-Raphson method"""\n approx = None\n guess = x / 2\n while approx != guess:\n approx = guess\n guess = (approx + x / approx) / 2\n return approx\n'
To view these in a visually pleasing form, our function print_content(s, suffix) formats and highlights the string s as if it were a file with ending suffix. We can thus view (and highlight) the source as if it were a Python file:
print_content(my_sqrt_source,'.py')
defmy_sqrt(x):
"""Computes the square root of x, using the Newton-Raphson method"""
approx = None
guess = x / 2while approx != guess:
approx = guess
guess = (approx + x / approx) / 2return approx
Parsing this gives us an abstract syntax tree (AST) – a representation of the program in tree form.
my_sqrt_ast=ast.parse(my_sqrt_source)
What does this AST look like? The helper functions ast.dump() (textual output) and showast.show_ast() (graphical output with showast) allow us to inspect the structure of the tree. We see that the function starts as a FunctionDef with name and arguments, followed by a body, which is a list of statements of type Expr (the docstring), type Assign (assignments), While (while loop with its own body), and finally Return.
The function ast.unparse() converts such a tree back into the more familiar textual Python code representation. Comments are gone, and there may be more parentheses than before, but the result has the same semantics:
print_content(ast.unparse(my_sqrt_ast),'.py')
defmy_sqrt(x):
"""Computes the square root of x, using the Newton-Raphson method"""
approx = None
guess = x / 2while approx != guess:
approx = guess
guess = (approx + x / approx) / 2return approx
Let us now go and transform these trees to add type annotations. We start with a helper function parse_type(name) which parses a type name into an AST.
We now define a helper function that actually adds type annotations to a function AST. The TypeTransformer class builds on the Python standard library ast.NodeTransformer infrastructure. It would be called as
TypeTransformer({'x':'int'},'float').visit(ast)
to annotate the arguments of my_sqrt(): x with int, and the return type with float. The returned AST can then be unparsed, compiled or analyzed.
The core of TypeTransformer is the method visit_FunctionDef(), which is called for every function definition in the AST. Its argument node is the subtree of the function definition to be transformed. Our implementation accesses the individual arguments and invokes annotate_args() on them; it also sets the return type in the returns attribute of the node.
classTypeTransformer(TypeTransformer):defvisit_FunctionDef(self,node):"""Add annotation to function"""# Set argument typesnew_args=[]forarginnode.args.args:new_args.append(self.annotate_arg(arg))new_arguments=ast.arguments(node.args.posonlyargs,new_args,node.args.vararg,node.args.kwonlyargs,node.args.kw_defaults,node.args.kwarg,node.args.defaults)# Set return typeifself.return_typeisnotNone:node.returns=parse_type(self.return_type)returnast.copy_location(ast.FunctionDef(node.name,new_arguments,node.body,node.decorator_list,node.returns),node)
Each argument gets its own annotation, taken from the types originally passed to the class:
classTypeTransformer(TypeTransformer):defannotate_arg(self,arg):"""Add annotation to single function argument"""arg_name=arg.argifarg_nameinself.argument_types:arg.annotation=parse_type(self.argument_types[arg_name])returnarg
Does this work? Let us annotate the AST from my_sqrt() with types for the arguments and return types:
Let us now annotate functions with types mined at runtime. We start with a simple function type_string() that determines the appropriate type of a given value (as a string):
deftype_string(value):returntype(value).__name__
For composite structures, type_string() does not examine element types; hence, the type of [3] is simply list instead of, say, list[int]. For now, list will do fine.
type_string() will be used to infer the types of argument values found at runtime, as returned by CallTracker.calls():
For each function, we get the source and its AST and then get to the actual annotation in annotate_function_ast_with_types():
defannotate_function_with_types(function_name,function_calls):function=globals()[function_name]# May raise KeyError for internal functionsfunction_code=inspect.getsource(function)function_ast=ast.parse(function_code)returnannotate_function_ast_with_types(function_ast,function_calls)
The function annotate_function_ast_with_types() invokes the TypeTransformer with the calls seen, and for each call, iterate over the arguments, determine their types, and annotate the AST with these. The universal type Any is used when we encounter type conflicts, which we will discuss below.
Let us bring all of this together in a single class TypeAnnotator that first tracks calls of functions and then allows accessing the AST (and the source code form) of the tracked functions annotated with types. The method typed_functions() returns the annotated functions as a string; typed_functions_ast() returns their AST.
After tracking, we can immediately retrieve an annotated version of the functions tracked:
print_content(annotator.typed_functions(),'.py')
defmy_sqrt(x: float) -> float:
"""Computes the square root of x, using the Newton-Raphson method"""
approx = None
guess = x / 2while approx != guess:
approx = guess
guess = (approx + x / approx) / 2return approx
This also works for multiple and diverse functions. One could go and implement an automatic type annotator for Python files based on the types seen during execution.
defhello(name: str):
print('Hello,', name)defmy_sqrt(x: float) -> float:
"""Computes the square root of x, using the Newton-Raphson method"""
approx = None
guess = x / 2while approx != guess:
approx = guess
guess = (approx + x / approx) / 2return approx
A content as above could now be sent to a type checker, which would detect any type inconsistency between callers and callees. Likewise, type annotations such as the ones above greatly benefit symbolic code analysis (as in the chapter on symbolic fuzzing), as they effectively constrain the set of values that arguments and variables can take.
Let us now resolve the role of the magic Any type in annotate_function_ast_with_types(). If we see multiple types for the same argument, we set its type to Any. For my_sqrt(), this makes sense, as its arguments can be integers as well as floats:
defsum3(a: Any, b: Any, c: Any) -> Any:
return a + b + c
A type Any makes it explicit that an object can, indeed, have any type; it will not be type-checked at runtime or statically. To some extent, this defeats the power of type checking; but it also preserves some of the type flexibility that many Python programmers enjoy. Besides Any, the typing module supports several additional ways to define ambiguous types; we will keep this in mind for a later exercise.
Besides basic data types. we can check several further properties from arguments. We can, for instance, whether an argument can be negative, zero, or positive; or that one argument should be smaller than the second; or that the result should be the sum of two arguments – properties that cannot be expressed in a (Python) type.
Such properties are called invariants, as they hold across all invocations of a function. Specifically, invariants come as pre- and postconditions – conditions that always hold at the beginning and at the end of a function. (There are also data and object invariants that express always-holding properties over the state of data or objects, but we do not consider these in this book.)
Annotating Functions with Pre- and Postconditions¶
The classical means to specify pre- and postconditions is via assertions, which we have introduced in the chapter on testing. A precondition checks whether the arguments to a function satisfy the expected properties; a postcondition does the same for the result. We can express and check both using assertions as follows:
A nicer way, however, is to syntactically separate invariants from the function at hand. Using appropriate decorators, we could specify pre- and postconditions as follows:
@preconditionlambdax:x>=0@postconditionlambdareturn_value,x:return_value*return_value==xdefmy_sqrt_with_invariants(x):# normal code without assertions...
The decorators @precondition and @postcondition would run the given functions (specified as anonymous lambda functions) before and after the decorated function, respectively. If the functions return False, the condition is violated. @precondition gets the function arguments as arguments; @postcondition additionally gets the return value as first argument.
defcondition(precondition=None,postcondition=None):defdecorator(func):@functools.wraps(func)# preserves name, docstring, etcdefwrapper(*args,**kwargs):ifpreconditionisnotNone:assertprecondition(*args,**kwargs),"Precondition violated"retval=func(*args,**kwargs)# call original function or methodifpostconditionisnotNone:assertpostcondition(retval,*args,**kwargs),"Postcondition violated"returnretvalreturnwrapperreturndecoratordefprecondition(check):returncondition(precondition=check)defpostcondition(check):returncondition(postcondition=check)
With these, we can now start decorating my_sqrt():
Traceback (most recent call last):
File "/var/folders/n2/xd9445p97rb3xh7m1dfx8_4h0006ts/T/ipykernel_35443/1985029262.py", line 2, in <module>
y = buggy_my_sqrt_with_postcondition(2.0)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/var/folders/n2/xd9445p97rb3xh7m1dfx8_4h0006ts/T/ipykernel_35443/906718213.py", line 10, in wrapper
assert postcondition(retval, *args, **kwargs), "Postcondition violated"
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError: Postcondition violated (expected)
While checking pre- and postconditions is a great way to catch errors, specifying them can be cumbersome. Let us try to see whether we can (again) mine some of them.
To mine invariants, we can use the same tracking functionality as before; instead of saving values for individual variables, though, we now check whether the values satisfy specific properties or not. For instance, if all values of x seen satisfy the condition x > 0, then we make x > 0 an invariant of the function. If we see positive, zero, and negative values of x, though, then there is no property of x left to talk about.
The general idea is thus:
Check all variable values observed against a set of predefined properties; and
Keep only those properties that hold for all runs observed.
What precisely do we mean by properties? Here is a small collection of value properties that would frequently be used in invariants. All these properties would be evaluated with the metavariables X, Y, and Z (actually, any upper-case identifier) being replaced with the names of function parameters:
When my_sqrt(x) is called as, say my_sqrt(5.0), we see that x = 5.0 holds. The above properties would then all be checked for x. Only the properties X > 0, X >= 0, and X != 0 hold for the call seen; and hence x > 0, x >= 0, and x != 0 would make potential preconditions for my_sqrt(x).
We can check for many more properties such as relations between two arguments:
Let us first introduce a few helper functions before we can get to the actual mining. metavars() extracts the set of meta-variables (X, Y, Z, etc.) from a property. To this end, we parse the property as a Python expression and then visit the identifiers.
To produce a property as invariant, we need to be able to instantiate it with variable names. The instantiation of X > 0 with X being instantiated to a, for instance, gets us a > 0. To this end, the function instantiate_prop() takes a property and a collection of variable names and instantiates the meta-variables left-to-right with the corresponding variables names in the collection.
To extract invariants from an execution, we need to check them on all possible instantiations of arguments. If the function to be checked has two arguments a and b, we instantiate the property X < Y both as a < b and b < a and check each of them.
To get all combinations, we use the Python permutations() function:
The function true_property_instantiations() takes a property and a list of tuples (var_name, value). It then produces all instantiations of the property with the given values and returns those that evaluate to True.
Let us now run the above invariant extraction on function arguments and return values as observed during a function execution. To this end, we extend the CallTracker class into an InvariantTracker class, which automatically computes invariants for all functions and all calls observed during tracking.
By default, an InvariantTracker uses the properties as defined above; however, one can specify alternate sets of properties.
The key method of the InvariantTracker is the invariants() method. This iterates over the calls observed and checks which properties hold. Only the intersection of properties – that is, the set of properties that hold for all calls – is preserved, and eventually returned. The special variable return_value is set to hold the return value.
We see that the both x and the return value have a float type. We also see that both are always greater than zero. These are properties that may make useful pre- and postconditions, notably for symbolic analysis.
However, there's also an invariant which does not universally hold, namely return_value <= x, as the following example shows:
Clearly, 0.1 > 0.01 holds. This is a case of us not learning from sufficiently diverse inputs. As soon as we have a call including x = 0.1, though, the invariant return_value <= x is eliminated:
We will discuss later how to ensure sufficient diversity in inputs. (Hint: This involves test generation.)
Let us try out our invariant tracker on sum3(). We see that all types are well-defined; the properties that all arguments are non-zero, however, is specific to the calls observed.
If we invoke sum3() with strings instead, we get different invariants. Notably, we obtain the postcondition that the return value starts with the value of a – a universal postcondition if strings are used.
If we invoke sum3() with both strings and numbers (and zeros, too), there are no properties left that would hold across all calls. That's the price of flexibility.
As with types, above, we would like to have some functionality where we can add the mined invariants as annotations to existing functions. To this end, we introduce the InvariantAnnotator class, extending InvariantTracker.
We start with a helper method. params() returns a comma-separated list of parameter names as observed during calls.
Now for the actual annotation. preconditions() returns the preconditions from the mined invariants (i.e., those properties that do not depend on the return value) as a string with annotations:
With these, we can take a function and add both pre- and postconditions as annotations:
classInvariantAnnotator(InvariantAnnotator):deffunctions_with_invariants(self):functions=""forfunction_nameinself.invariants():try:function=self.function_with_invariants(function_name)exceptKeyError:continuefunctions+=functionreturnfunctionsdeffunction_with_invariants(self,function_name):function=globals()[function_name]# Can throw KeyErrorsource=inspect.getsource(function)return"\n".join(self.preconditions(function_name)+self.postconditions(function_name))+'\n'+source
Here comes function_with_invariants() in all its glory:
Almost all these properties (except for the very first) are relevant. Of course, the reason the invariants are so neat is that the return value is equal to len(L) is that X == len(Y) is part of the list of properties to be checked.
@precondition(lambda b, a: isinstance(a, int))
@precondition(lambda b, a: isinstance(b, int))
@postcondition(lambda return_value, b, a: a == return_value - b)
@postcondition(lambda return_value, b, a: b == return_value - a)
@postcondition(lambda return_value, b, a: isinstance(return_value, int))
@postcondition(lambda return_value, b, a: return_value == a + b)
@postcondition(lambda return_value, b, a: return_value == b + a)
defsum2(a, b):
return a + b
If we have a function without return value, the return value is None, and we can only mine preconditions. (Well, we get a "postcondition" that the return value is non-zero, which holds for None).
A function with invariants, as above, can be fed into the Python interpreter, such that all pre- and postconditions are checked. We create a function my_sqrt_annotated() which includes all the invariants mined above.
@precondition(lambda x: isinstance(x, float))
@precondition(lambda x: x != 0)
@precondition(lambda x: x > 0)
@precondition(lambda x: x >= 0)
@postcondition(lambda return_value, x: isinstance(return_value, float))
@postcondition(lambda return_value, x: return_value != 0)
@postcondition(lambda return_value, x: return_value > 0)
@postcondition(lambda return_value, x: return_value >= 0)
defmy_sqrt_annotated(x):
"""Computes the square root of x, using the Newton-Raphson method"""
approx = None
guess = x / 2while approx != guess:
approx = guess
guess = (approx + x / approx) / 2return approx
The "annotated" version checks against invalid arguments – or more precisely, against arguments with properties that have not been observed yet:
withExpectError():my_sqrt_annotated(-1.0)
Traceback (most recent call last):
File "/var/folders/n2/xd9445p97rb3xh7m1dfx8_4h0006ts/T/ipykernel_35443/3390953352.py", line 2, in <module>
my_sqrt_annotated(-1.0)
File "/var/folders/n2/xd9445p97rb3xh7m1dfx8_4h0006ts/T/ipykernel_35443/906718213.py", line 8, in wrapper
retval = func(*args, **kwargs) # call original function or method
^^^^^^^^^^^^^^^^^^^^^
File "/var/folders/n2/xd9445p97rb3xh7m1dfx8_4h0006ts/T/ipykernel_35443/906718213.py", line 8, in wrapper
retval = func(*args, **kwargs) # call original function or method
^^^^^^^^^^^^^^^^^^^^^
File "/var/folders/n2/xd9445p97rb3xh7m1dfx8_4h0006ts/T/ipykernel_35443/906718213.py", line 6, in wrapper
assert precondition(*args, **kwargs), "Precondition violated"
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError: Precondition violated (expected)
This is in contrast to the original version, which just hangs on negative values:
withExpectTimeout(1):my_sqrt(-1.0)
Traceback (most recent call last):
File "/var/folders/n2/xd9445p97rb3xh7m1dfx8_4h0006ts/T/ipykernel_35443/2605599394.py", line 2, in <module>
my_sqrt(-1.0)
File "/var/folders/n2/xd9445p97rb3xh7m1dfx8_4h0006ts/T/ipykernel_35443/2661069967.py", line 5, in my_sqrt
while approx != guess:
^^^^^^^^^^^^^^^
File "Timeout.ipynb", line 43, in timeout_handler
raise TimeoutError()
TimeoutError (expected)
If we make changes to the function definition such that the properties of the return value change, such regressions are caught as violations of the postconditions. Let us illustrate this by simply inverting the result, and return $-2$ as square root of 4.
@precondition(lambda x: isinstance(x, float))
@precondition(lambda x: x != 0)
@precondition(lambda x: x > 0)
@precondition(lambda x: x >= 0)
@postcondition(lambda return_value, x: isinstance(return_value, float))
@postcondition(lambda return_value, x: return_value != 0)
@postcondition(lambda return_value, x: return_value > 0)
@postcondition(lambda return_value, x: return_value >= 0)
defmy_sqrt_negative(x):
"""Computes the square root of x, using the Newton-Raphson method"""
approx = None
guess = x / 2while approx != guess:
approx = guess
guess = (approx + x / approx) / 2return -approx
Technically speaking, $-2$ is a square root of 4, since $(-2)^2 = 4$ holds. Yet, such a change may be unexpected by callers of my_sqrt(), and hence, this would be caught with the first call:
withExpectError():my_sqrt_negative(2.0)
Traceback (most recent call last):
File "/var/folders/n2/xd9445p97rb3xh7m1dfx8_4h0006ts/T/ipykernel_35443/2428286732.py", line 2, in <module>
my_sqrt_negative(2.0) # type: ignore
^^^^^^^^^^^^^^^^^^^^^
File "/var/folders/n2/xd9445p97rb3xh7m1dfx8_4h0006ts/T/ipykernel_35443/906718213.py", line 8, in wrapper
retval = func(*args, **kwargs) # call original function or method
^^^^^^^^^^^^^^^^^^^^^
File "/var/folders/n2/xd9445p97rb3xh7m1dfx8_4h0006ts/T/ipykernel_35443/906718213.py", line 8, in wrapper
retval = func(*args, **kwargs) # call original function or method
^^^^^^^^^^^^^^^^^^^^^
File "/var/folders/n2/xd9445p97rb3xh7m1dfx8_4h0006ts/T/ipykernel_35443/906718213.py", line 8, in wrapper
retval = func(*args, **kwargs) # call original function or method
^^^^^^^^^^^^^^^^^^^^^
[Previous line repeated 4 more times]
File "/var/folders/n2/xd9445p97rb3xh7m1dfx8_4h0006ts/T/ipykernel_35443/906718213.py", line 10, in wrapper
assert postcondition(retval, *args, **kwargs), "Postcondition violated"
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError: Postcondition violated (expected)
We see how pre- and postconditions, as well as types, can serve as oracles during testing. In particular, once we have mined them for a set of functions, we can check them again and again with test generators – especially after code changes. The more checks we have, and the more specific they are, the more likely it is we can detect unwanted effects of changes.
Mined specifications can only be as good as the executions they were mined from. If we only see a single call to, say, sum2() as defined above, we will be faced with several mined pre- and postconditions that overspecialize towards the values seen:
@precondition(lambda b, a: a != 0)
@precondition(lambda b, a: a <= b)
@precondition(lambda b, a: a == b)
@precondition(lambda b, a: a > 0)
@precondition(lambda b, a: a >= 0)
@precondition(lambda b, a: a >= b)
@precondition(lambda b, a: b != 0)
@precondition(lambda b, a: b <= a)
@precondition(lambda b, a: b == a)
@precondition(lambda b, a: b > 0)
@precondition(lambda b, a: b >= 0)
@precondition(lambda b, a: b >= a)
@precondition(lambda b, a: isinstance(a, int))
@precondition(lambda b, a: isinstance(b, int))
@postcondition(lambda return_value, b, a: a < return_value)
@postcondition(lambda return_value, b, a: a <= b <= return_value)
@postcondition(lambda return_value, b, a: a <= return_value)
@postcondition(lambda return_value, b, a: a == return_value - b)
@postcondition(lambda return_value, b, a: a == return_value / b)
@postcondition(lambda return_value, b, a: b < return_value)
@postcondition(lambda return_value, b, a: b <= a <= return_value)
@postcondition(lambda return_value, b, a: b <= return_value)
@postcondition(lambda return_value, b, a: b == return_value - a)
@postcondition(lambda return_value, b, a: b == return_value / a)
@postcondition(lambda return_value, b, a: isinstance(return_value, int))
@postcondition(lambda return_value, b, a: return_value != 0)
@postcondition(lambda return_value, b, a: return_value == a * b)
@postcondition(lambda return_value, b, a: return_value == a + b)
@postcondition(lambda return_value, b, a: return_value == b * a)
@postcondition(lambda return_value, b, a: return_value == b + a)
@postcondition(lambda return_value, b, a: return_value > 0)
@postcondition(lambda return_value, b, a: return_value > a)
@postcondition(lambda return_value, b, a: return_value > b)
@postcondition(lambda return_value, b, a: return_value >= 0)
@postcondition(lambda return_value, b, a: return_value >= a)
@postcondition(lambda return_value, b, a: return_value >= a >= b)
@postcondition(lambda return_value, b, a: return_value >= b)
@postcondition(lambda return_value, b, a: return_value >= b >= a)
defsum2(a, b):
return a + b
The mined precondition a == b, for instance, only holds for the single call observed; the same holds for the mined postcondition return_value == a * b. Yet, sum2() can obviously be successfully called with other values that do not satisfy these conditions.
To get out of this trap, we have to learn from more and more diverse runs. If we have a few more calls of sum2(), we see how the set of invariants quickly gets smaller:
@precondition(lambda b, a: isinstance(a, int))
@precondition(lambda b, a: isinstance(b, int))
@postcondition(lambda return_value, b, a: a == return_value - b)
@postcondition(lambda return_value, b, a: b == return_value - a)
@postcondition(lambda return_value, b, a: isinstance(return_value, int))
@postcondition(lambda return_value, b, a: return_value == a + b)
@postcondition(lambda return_value, b, a: return_value == b + a)
defsum2(a, b):
return a + b
But where to we get such diverse runs from? This is the job of generating software tests. A simple grammar for calls of sum2() will easily resolve the problem.
fromGrammarFuzzerimportGrammarFuzzer# minor dependencyfromGrammarsimportis_valid_grammar,crange# minor dependencyfromGrammarsimportconvert_ebnf_grammar,Grammar# minor dependency
@precondition(lambda b, a: a != 0)
@precondition(lambda b, a: isinstance(a, int))
@precondition(lambda b, a: isinstance(b, int))
@postcondition(lambda return_value, b, a: a == return_value - b)
@postcondition(lambda return_value, b, a: b == return_value - a)
@postcondition(lambda return_value, b, a: isinstance(return_value, int))
@postcondition(lambda return_value, b, a: return_value != 0)
@postcondition(lambda return_value, b, a: return_value == a + b)
@postcondition(lambda return_value, b, a: return_value == b + a)
defsum2(a, b):
return a + b
But then, writing tests (or a test driver) just to derive a set of pre- and postconditions may possibly be too much effort – in particular, since tests can easily be derived from given pre- and postconditions in the first place. Hence, it would be wiser to first specify invariants and then let test generators or program provers do the job.
Also, an API grammar, such as above, will have to be set up such that it actually respects preconditions – in our case, we invoke sqrt() with positive numbers only, already assuming its precondition. In some way, one thus needs a specification (a model, a grammar) to mine another specification – a chicken-and-egg problem.
However, there is one way out of this problem: If one can automatically generate tests at the system level, then one has an infinite source of executions to learn invariants from. In each of these executions, all functions would be called with values that satisfy the (implicit) precondition, allowing us to mine invariants for these functions. This holds, because at the system level, invalid inputs must be rejected by the system in the first place. The meaningful precondition at the system level, ensuring that only valid inputs get through, thus gets broken down into a multitude of meaningful preconditions (and subsequent postconditions) at the function level.
The big requirement for this, though, is that one needs good test generators at the system level. In the next part, we will discuss how to automatically generate tests for a variety of domains, from configuration to graphical user interfaces.
The DAIKON dynamic invariant detector can be considered the mother of function specification miners. Continuously maintained and extended for more than 20 years, it mines likely invariants in the style of this chapter for a variety of languages, including C, C++, C#, Eiffel, F#, Java, Perl, and Visual Basic. On top of the functionality discussed above, it holds a rich catalog of patterns for likely invariants, supports data invariants, can eliminate invariants that are implied by others, and determines statistical confidence to disregard unlikely invariants. The corresponding paper [Ernst et al, 2001] is one of the seminal and most-cited papers of Software Engineering. A multitude of works have been published based on DAIKON and detecting invariants; see this curated list for details.
The interaction between test generators and invariant detection is already discussed in [Ernst et al, 2001] (incidentally also using grammars). The Eclat tool [Pacheco et al, 2005] is a model example of tight interaction between a unit-level test generator and DAIKON-style invariant mining, where the mined invariants are used to produce oracles and to systematically guide the test generator towards fault-revealing inputs.
Mining specifications is not restricted to pre- and postconditions. The paper "Mining Specifications" [Ammons et al, 2002] is another classic in the field, learning state protocols from executions. Grammar mining, as described in our chapter with the same name can also be seen as a specification mining approach, this time learning specifications of input formats.
As it comes to adding type annotations to existing code, the blog post "The state of type hints in Python" gives a great overview on how Python type hints can be used and checked. To add type annotations, there are two important tools available that also implement our above approach:
MonkeyType implements the above approach of tracing executions and annotating Python 3 arguments, returns, and variables with type hints.
PyAnnotate does a similar job, focusing on code in Python 2. It does not produce Python 3-style annotations, but instead produces annotations as comments that can be processed by static type checkers.
These tools have been created by engineers at Facebook and Dropbox, respectively, assisting them in checking millions of lines of code for type issues.
Our code for mining types and invariants is in no way complete. There are dozens of ways to extend our implementations, some of which we discuss in exercises.
The Python typing module allows expressing that an argument can have multiple types. For my_sqrt(x), this allows expressing that x can be an int or a float:
In Python, one cannot only annotate arguments with types, but actually also local and global variables – for instance, approx and guess in our my_sqrt() implementation:
defmy_sqrt_with_local_types(x:Union[int,float])->float:"""Computes the square root of x, using the Newton-Raphson method"""approx:Optional[float]=Noneguess:float=x/2whileapprox!=guess:approx=guessguess=(approx+x/approx)/2returnapprox
Extend the TypeAnnotator such that it also annotates local variables with types. Search the function AST for assignments, determine the type of the assigned value, and make it an annotation on the left-hand side.
Traceback (most recent call last):
File "/var/folders/n2/xd9445p97rb3xh7m1dfx8_4h0006ts/T/ipykernel_35443/2212034949.py", line 2, in <module>
remove_first_char('')
File "/var/folders/n2/xd9445p97rb3xh7m1dfx8_4h0006ts/T/ipykernel_35443/906718213.py", line 6, in wrapper
assert precondition(*args, **kwargs), "Precondition violated"
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError: Precondition violated (expected)
The following implementation adds an optional doc keyword argument which is printed if the invariant is violated:
defverbose_condition(precondition=None,postcondition=None,doc='Unknown'):defdecorator(func):@functools.wraps(func)# preserves name, docstring, etcdefwrapper(*args,**kwargs):ifpreconditionisnotNone:assertprecondition(*args,**kwargs),"Precondition violated: "+docretval=func(*args,**kwargs)# call original function or methodifpostconditionisnotNone:assertpostcondition(retval,*args,**kwargs),"Postcondition violated: "+docreturnretvalreturnwrapperreturndecorator
If the value of an argument changes during function execution, this can easily confuse our implementation: The values are tracked at the beginning of the function, but checked only when it returns. Extend the InvariantAnnotator and the infrastructure it uses such that
it saves argument values both at the beginning and at the end of a function invocation;
postconditions can be expressed over both initial values of arguments as well as the final values of arguments;
the mined postconditions refer to both these values as well.
Several mined invariant are actually implied by others: If x > 0 holds, then this implies x >= 0 and x != 0. Extend the InvariantAnnotator such that implications between properties are explicitly encoded, and such that implied properties are no longer listed as invariants. See [Ernst et al, 2001] for ideas.
Postconditions may also refer to the values of local variables. Consider extending InvariantAnnotator and its infrastructure such that the values of local variables at the end of the execution are also recorded and made part of the invariant inference mechanism.
After mining a first set of invariants, have a concolic fuzzer generate tests that systematically attempt to invalidate pre- and postconditions. How far can you generalize?
The larger the set of properties to be checked, the more potential invariants can be discovered. Create a grammar that systematically produces a large set of properties. See [Ernst et al, 2001] for possible patterns.
Rather than producing invariants as annotations for pre- and postconditions, insert them as assert statements into the function code, as in:
defmy_sqrt(x):'Computes the square root of x, using the Newton-Raphson method'assertisinstance(x,int),'violated precondition'assert(x>0),'violated precondition'approx=Noneguess=(x/2)while(approx!=guess):approx=guessguess=((approx+(x/approx))/2)return_value=approxassert(return_value<x),'violated postcondition'assertisinstance(return_value,float),'violated postcondition'returnapprox
Such a formulation may make it easier for test generators and symbolic analysis to access and interpret pre- and postconditions.