Boolean Condition Trees for a Spending Policy Checker
Data Structure DesignModel answerLast updated
Design a data-driven policy engine whose rules combine field checks with nested AND, OR and NOT, covering representation, validation, missing-field behavior and explainable results.
You maintain a service that checks employee expenses against company spending policies. Today each policy is a single flat check. You are asked to let policies combine checks using nested AND, OR and NOT.
Policies must be expressible for cases like:
- The expense category is "restaurant", the expense type is "meals", and the amount is greater than 50.
- Either (the category is "entertainment" and the amount is greater than 100), or the expense is tagged as client hosting.
- The amount is greater than 100 and the vendor name is not equal to a given supplier.
Policies are submitted to the service as data through an API. They must never be executed as arbitrary code.
Describe your design and sketch an implementation. Cover:
- How you represent a condition, including both the combining nodes and the leaf checks.
- How you validate a policy when it is created, and what you reject.
- How you evaluate a policy against an expense, including what happens when a field is missing.
- How the engine reports which part of a policy caused a violation.
- How you would add new fields or operators later without rewriting the evaluator.
State your assumptions explicitly. In particular, decide which expense field each business term maps to, which operators are supported, whether an empty AND or OR is legal, what limits you place on depth and size, and whether composite conditions select individual expenses before any group-level aggregation (such as a per-trip total) is applied.
Hints
Hint 1
Model a condition as a small tagged tree: composite nodes (AND, OR, NOT) hold child conditions, and leaf nodes hold a field, an operator and a value. Evaluation is a simple recursion over this tree.
Hint 2
Do the hard work at creation time: check that fields exist, that each operator is legal for the field's type, that the value has the right type, that NOT has exactly one child, and that depth and node count are bounded. Evaluation then stays trivial and safe.
Hint 3
Decide missing-field behavior once and write it down. A common choice is that a leaf on a missing field evaluates to false (or to an explicit 'unknown'), so that NOT of a missing-field check does not silently pass. Also return a result tree, not just a boolean, so you can explain why a rule fired.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Assumptions (state these first)
- Condition fields map to concrete expense attributes:
category(e.g. "restaurant", "entertainment"),type(e.g. "meals"),amount(decimal, in a single currency or compared after conversion),vendor_name, andtags(a set of strings, where "client-hosting" is a tag). - Supported leaf operators depend on field type:
eq,neq,infor strings;gt,gte,lt,lte,eqfor numbers;containsfor tag sets. - Rules are JSON data. There is no
eval, no user-supplied code and no string expression parsing at runtime. - An empty AND or OR is rejected at creation, because its meaning is ambiguous (vacuous truth for AND, vacuous falsehood for OR) and it is almost always a bug.
- Limits: maximum depth 10, maximum 100 nodes per rule. These protect against stack overflow and abusive payloads.
- A rule is evaluated against one expense at a time. Composite conditions decide whether an individual expense is matched; any aggregation (for example "total of matching expenses per trip exceeds 500") is a separate layer that consumes the filtered expenses.
Representation
Use a small algebraic data type, serialized as JSON:
{ "op": "and", "children": [
{ "field": "category", "cmp": "eq", "value": "restaurant" },
{ "field": "type", "cmp": "eq", "value": "meals" },
{ "field": "amount", "cmp": "gt", "value": 50 }
]}
In code:
class Node: ...
class And(Node): children: list[Node]
class Or(Node): children: list[Node]
class Not(Node): child: Node
class Leaf(Node): field: str; cmp: str; value: object
The third example becomes And[ Leaf(amount gt 100), Not(Leaf(vendor_name eq "Acme")) ].
Validation (at creation, not at evaluation)
Parse the JSON into node objects in one pass and reject on the first error:
- Unknown
op, or a node that is neither composite nor leaf. - AND/OR with zero children; NOT with anything other than exactly one child. (A single-child AND/OR is legal but can be simplified.)
- Unknown field, or an operator not allowed for that field's type, using a registry such as
FIELDS = {"amount": NumberField, "vendor_name": StringField, ...}. - Value of the wrong type (a string compared with
gtagainstamount). - Depth or node count over the limits, enforced during parsing with a counter so a hostile payload fails early.
- Cycles are impossible if you build fresh objects from JSON, but if rules can reference other rules by ID, detect cycles explicitly.
Validated rules are stored as the parsed tree (or the validated JSON plus a schema version), so evaluation never has to re-check.
Evaluation
Recursive, with short-circuiting:
def evaluate(node, expense):
if isinstance(node, And):
results = []
for c in node.children:
r = evaluate(c, expense)
results.append(r)
if not r.value: break # short-circuit
return Result(all(r.value for r in results), node, results)
if isinstance(node, Or):
results = []
for c in node.children:
r = evaluate(c, expense)
results.append(r)
if r.value: break
return Result(any(r.value for r in results), node, results)
if isinstance(node, Not):
r = evaluate(node.child, expense)
return Result(not r.value, node, [r])
return eval_leaf(node, expense)
eval_leaf looks up the field's handler in the registry and applies the comparison. Time is O(n) in the number of nodes per expense, and recursion depth is bounded by the validated depth limit, so there is no stack risk.
Missing fields
This is the main semantic trap. Options:
- Leaf on a missing field is false. Simple and predictable. The catch is that
NOT(vendor_name eq "Acme")is then true when the vendor is missing, which may or may not be wanted. - Three-valued logic (true / false / unknown), like SQL. NOT(unknown) is unknown, and the rule finally treats unknown as "needs review" rather than pass or fail.
For a spending policy, I would pick option 2 if reviewers exist, or option 1 with an explicit documented rule (and a separate exists operator) if simplicity matters. Whatever you choose, test it explicitly, because it changes outcomes for NOT.
Explainability
Return a result tree instead of a bare boolean. Each result records the node, its value and its children's results. When a policy flags an expense, walk the tree and report the minimal explanation: for a failing AND, the first false child; for a passing OR, the first true child; for NOT, the inverted child. Output something like "Flagged: amount 140 > 100 and vendor was not 'Acme'". Note that short-circuiting means unevaluated children are absent from the trace, which is fine and usually desirable.
Extensibility
- Keep a field registry (name, type, accessor) and an operator registry per type. Adding a field or operator is one registration; the evaluator and validator do not change.
- Version the rule schema so old stored rules keep working.
- If performance matters, compile each tree into a closure once and cache it per rule.
Testing
- Truth-table tests for each composite, including nested NOT inside OR.
- Missing field with and without NOT.
- Boundary values (
amount == 50forgt 50is false). - Rejection tests: empty AND, NOT with two children, unknown field, wrong value type, depth 11.
- A property test comparing the tree evaluator against a straightforward reference implementation on random trees.
Common mistakes
- Parsing user rules with
evalor similar. - Validating at evaluation time, so bad rules fail only when a certain expense arrives.
- Leaving missing-field behavior undefined, so NOT results are surprising.
- Allowing unbounded depth or size.
- Returning only a boolean, which makes disputes with employees impossible to resolve.
- Mixing aggregation concerns (per-trip totals) into the per-expense condition tree.