Build a Policy Engine for Expense Validation
Data Structure DesignModel answerLast updated
Create a rule evaluation system that checks expense submissions against JSON-defined policies without deploying new code.
Problem
You're building the approval workflow for a corporate expense management platform. Business rules like "Any hotel booking over $300 needs manager approval" or "International travel requires supporting documentation" should be configurable by administrators through a UI, not hardcoded.
Your job is to design and implement a system that reads policy definitions from JSON and evaluates them against incoming expense records.
What You Need to Build
1. Policy Representation
Define a JSON format for expressing rules. It should support:
- Comparisons on expense fields: equality, numeric ordering, set membership, substring matching
- Logical composition: combining multiple checks with AND, OR, and NOT
- Outcome specification: what happens when a rule matches (block the expense, flag for review, require additional approval)
2. Evaluation Engine
Implement the evaluation logic. Given an expense object (as a dictionary) and a compiled policy, determine:
- Does this expense violate the policy?
- If so, which specific conditions failed?
- What message should the user see?
Your evaluator should handle:
- Fields that are missing from the expense data
- Type mismatches (comparing a string to a number)
- Deeply nested logical expressions
3. Safety and Correctness
The system must be safe to run in production:
- Reject malformed or malicious policy JSON at upload time, not at evaluation time
- Prevent unbounded recursion or memory use
- Never execute arbitrary code from policy definitions
- Handle ambiguous cases (missing data) explicitly rather than making assumptions
Example Policy
{
"id": "travel_advance_booking",
"description": "Flights booked less than a week out need director sign-off",
"condition": {
"op": "AND",
"clauses": [
{"field": "expense_type", "predicate": "EQ", "target": "AIRFARE"},
{"field": "days_until_travel", "predicate": "LT", "target": 7}
]
},
"outcome": {
"result": "ESCALATE",
"escalation_level": "DIRECTOR",
"reason": "Last-minute flight bookings require director approval per travel policy."
}
}
An expense with {"expense_type": "AIRFARE", "days_until_travel": 3, "amount": 450} would match this rule and trigger escalation.
What to Cover
- How you validate policy JSON before storing it
- How you structure the in-memory representation of a compiled rule
- How you handle cases where required fields are absent or have unexpected types
- How you would test individual operators, complex nested conditions, and schema constraints
- Trade-offs in your design: performance, expressiveness, debuggability
Hints
Hint 1
Think about how to represent boolean logic as a tree where leaves are comparisons and internal nodes are AND/OR/NOT.
Hint 2
Decide what happens when a field is missing: should missing data cause the rule to fail, pass, or return 'uncertain'?
Hint 3
Validate everything you can when the policy is saved, so runtime evaluation only has to worry about bad expense data.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer
Core Insight
The central design choice is to treat policy JSON as untrusted input and transform it into a validated, executable tree structure. This approach separates validation (which happens once, when an admin saves a policy) from evaluation (which happens on every expense submission).
Compilation phase: Parse the JSON, check that every field name is recognized, verify that operators match field types (you can't use greater-than on a string field), enforce structural limits (maximum nesting depth), and build an immutable tree of condition objects.
Evaluation phase: Walk the compiled tree against an expense dictionary. At each leaf, look up the field value and apply the comparison. At each branch, combine child results using boolean logic.
Three-Valued Logic
A key decision is how to handle missing or malformed data. Standard boolean logic (true/false) is insufficient because it forces you to guess: if has_receipt is absent, does has_receipt == false evaluate to true or false?
The solution is three-valued logic: every condition returns TRUE, FALSE, or UNKNOWN. A missing field or a type error (trying to compare a string to a number) produces UNKNOWN rather than silently defaulting to true or false.
Propagation rules:
- AND: If any child is FALSE, return FALSE. Otherwise, if any child is UNKNOWN, return UNKNOWN. Otherwise, return TRUE. (Short-circuit on first FALSE.)
- OR: If any child is TRUE, return TRUE. Otherwise, if any child is UNKNOWN, return UNKNOWN. Otherwise, return FALSE. (Short-circuit on first TRUE.)
- NOT: Swap TRUE and FALSE, leave UNKNOWN unchanged.
This ensures that if missing data could change the outcome, you report uncertainty rather than making a guess. For example, expense_type != "MEALS" AND amount > 100 returns FALSE if expense_type is "HOTEL", even if amount is missing—the first clause alone determines the result.
Architecture
from enum import Enum
from decimal import Decimal
from typing import Any
class Outcome(Enum):
TRUE = "TRUE"
FALSE = "FALSE"
UNKNOWN = "UNKNOWN"
# Abstract base
class ConditionNode:
def evaluate(self, expense: dict, errors: list[str]) -> Outcome:
raise NotImplementedError
# Leaf: single field comparison
class Comparison(ConditionNode):
def __init__(self, field: str, op: str, expected: Any, field_type: type):
self.field = field
self.op = op
self.expected = expected
self.field_type = field_type
def evaluate(self, expense, errors):
if self.field not in expense:
errors.append(f"Field '{self.field}' is missing")
return Outcome.UNKNOWN
actual = expense[self.field]
if not isinstance(actual, self.field_type):
errors.append(f"Field '{self.field}' has wrong type")
return Outcome.UNKNOWN
result = self._apply_op(actual, self.expected)
return Outcome.TRUE if result else Outcome.FALSE
def _apply_op(self, actual, expected):
ops = {
"EQ": lambda a, e: a == e,
"NE": lambda a, e: a != e,
"GT": lambda a, e: a > e,
"LT": lambda a, e: a < e,
"IN": lambda a, e: a in e,
}
return ops[self.op](actual, expected)
# Internal nodes
class AndNode(ConditionNode):
def __init__(self, children: list[ConditionNode]):
self.children = children
def evaluate(self, expense, errors):
result = Outcome.TRUE
for child in self.children:
r = child.evaluate(expense, errors)
if r == Outcome.FALSE:
return Outcome.FALSE
if r == Outcome.UNKNOWN:
result = Outcome.UNKNOWN
return result
class OrNode(ConditionNode):
def __init__(self, children: list[ConditionNode]):
self.children = children
def evaluate(self, expense, errors):
result = Outcome.FALSE
for child in self.children:
r = child.evaluate(expense, errors)
if r == Outcome.TRUE:
return Outcome.TRUE
if r == Outcome.UNKNOWN:
result = Outcome.UNKNOWN
return result
class NotNode(ConditionNode):
def __init__(self, child: ConditionNode):
self.child = child
def evaluate(self, expense, errors):
r = self.child.evaluate(expense, errors)
if r == Outcome.TRUE:
return Outcome.FALSE
if r == Outcome.FALSE:
return Outcome.TRUE
return Outcome.UNKNOWN
Compilation and Validation
When an admin uploads a policy, validate it immediately:
- Schema check: Ensure every node is either
{"op": "AND"|"OR"|"NOT", "clauses": [...]}or{"field": ..., "predicate": ..., "target": ...}. - Field whitelist: Maintain a registry of known fields and their types (e.g.,
{"amount": Decimal, "expense_type": str, "has_receipt": bool}). Reject unknown fields. - Operator compatibility: Numeric comparisons (GT, LT) only work on numeric fields. Set membership (IN) requires a list as the target value. String matching (CONTAINS) requires string fields.
- Structural limits: Cap tree depth at 16 and total node count at 256 to prevent resource exhaustion.
- Type coercion: Convert numeric literals to
Decimal(never float) to avoid precision issues.
If validation fails, reject the policy immediately with a clear error message. Admins fix the issue in the UI before saving again.
Evaluation API
class PolicyEngine:
def __init__(self, field_registry: dict[str, type]):
self.field_registry = field_registry
def compile_policy(self, policy_json: dict) -> ConditionNode:
# Validate and build tree
return self._compile_node(policy_json["condition"], depth=0, count=[0])
def evaluate(self, expense: dict, policy: ConditionNode) -> dict:
errors = []
result = policy.evaluate(expense, errors)
return {
"passed": result == Outcome.FALSE, # Policy is a violation rule
"status": result.value,
"diagnostic_messages": errors
}
Key point: A policy defines a violation condition. If the condition evaluates to TRUE, the expense violates the policy. FALSE means the policy is satisfied. UNKNOWN means the system cannot determine compliance with available data, so it fails closed (requires human review).
Testing Strategy
- Unit tests for operators: Verify each comparison works correctly with valid inputs and returns UNKNOWN for type mismatches.
- Logic tests: Confirm that AND, OR, NOT follow three-valued truth tables. Test short-circuit behavior.
- Compilation tests: Feed malformed JSON, unknown fields, incompatible operator/type pairs, and oversized trees. Each should fail at compile time with a specific error.
- Integration tests: Real-world policy examples evaluated against both compliant and violating expenses.
- Property-based tests: Generate random valid policies and valid expenses, then verify that evaluation always returns one of the three outcomes and never crashes.
Performance Considerations
Caching compiled policies: Store the ConditionNode tree in memory after compilation. Re-parsing JSON on every evaluation wastes CPU. In a production system, keep compiled policies in an LRU cache keyed by policy ID.
Lazy evaluation: Short-circuiting in AND/OR means you stop as soon as the result is determined. If the first clause of an AND is FALSE, you never evaluate the rest.
Complexity: Evaluation is O(n) in the number of nodes. With a depth cap of 16 and a node cap of 256, worst-case time is bounded and small.
Common Mistakes
- Using floats for money:
75.0vs75.00can produce inequality due to rounding. Always useDecimal. - Silent type coercion: If
amountis a string"100", don't silently convert it to a number—return UNKNOWN and log the issue. - No depth limit: A deeply nested policy can blow the call stack. Reject it at compile time.
- Guessing on missing data: Treating
missing_field == falseas true is a security hole. Return UNKNOWN instead. - Parsing JSON at evaluation time: Slow and risky. Compile once, evaluate many times.
Time Complexity: O(n) per evaluation, where n is the number of nodes in the policy tree.
Space Complexity: O(n) for the compiled tree, O(d) stack space during evaluation, where d is tree depth (capped at 16).