Definition
In constrained-random test generation, a constraint is a predicate that is attached to a randomized object so that the generator only produces values satisfying the predicate. Each constraint is supplied together with a tuple naming the random variables whose values are passed to it as arguments.
Mechanism in constrainedrandom
The constrainedrandom Python library exposes constraints through the add_constraint method on RandObj subclasses. The call takes:
- A callable (often a plain Python function) that returns a truthy value when the constraint is satisfied.
- A tuple of random-variable names; the current values of those variables are passed positionally to the callable when it is evaluated.
In the documented ldInstr example, two constraints are registered:
wb_dst_src(wb, dst0, src0)— when writeback (wb) is set, forbidsdst0from equallingsrc0; otherwise trivially satisfied.sum_src0_imm0(src0_value, imm0)— requires the sum of the model-suppliedsrc0_valueand the immediateimm0to be word-aligned (address & 3 == 0) and to fit within 32 bits (address < 0xffffffff).
Both are wired up with self.add_constraint(...), with the second argument naming the dependent variables in the order they will be supplied to the function.
Relationship to random variables
Constraints operate on random variables (add_rand_var). Random variables can declare a bit width and a generation order, and may be backed by either a width or a user-supplied value function (fn). Constraints reference the variables by name; their positional arguments are filled from the variable values at evaluation time.
Broader context
- In constraint logic programming, constraints generalize Prolog's equality over Herbrand terms to decidable theories, supporting declarative modeling and combinatorial solving. [arxiv:2402.17286]
- In program analysis, constraint-based reachability uses constraint solving over computational domains (conditionals, loops, arrays, memory) — interpreting classical filtering consistencies from constraint programming — to analyze infinite-state imperative programs. [arxiv:1302.3290]
These are conceptual relatives: the same word "constraint" denotes a declarative predicate over variables used by a solver, whether the solver drives a logic program, a static analyzer, or a hardware-verification randomizer.
See also
ldInstr— example randomized object that uses constraints.