Optimization — Advanced Example¶
The optimizer is valuable for catching accidentally contradictory conditions in complex business logic.
from therismos import F, optimize, FALSE
user_age = F("age", int)
user_role = F("role")
user_status = F("status")
account_tier = F("account_tier")
dept = F("department")
experience = F("experience_years", int)
available = F("available", bool)
# Complex filter built incrementally by different team members.
# Each level seemed reasonable in isolation, but together they create a contradiction.
complex_filter = (
(
(
(account_tier == "premium") &
((user_role == "developer") | (user_role == "designer"))
) |
(
(account_tier == "enterprise") &
(experience >= 5) &
(dept.is_in("engineering", "design"))
)
) &
(
(
(user_status == "active") &
(
((dept == "engineering") & (experience >= 2)) |
((dept == "design") & (user_role.is_in("designer", "lead_designer")))
)
) |
(user_role == "admin")
) &
(user_age >= 25) &
(user_age <= 50) &
(account_tier.is_in("premium", "enterprise", "trial")) &
# Someone later added "additional validation" without realising it contradicts above!
(user_age < 25) & # Must be under 25
(user_age > 50) & # AND must be over 50 — impossible!
(available == True)
)
result, records = optimize(complex_filter)
print(f"Optimized result: {result}")
# Output: FalseExpr()
print(f"Is FALSE: {result is FALSE}")
# Output: True
print("Optimization steps that revealed the contradiction:")
for i, record in enumerate(records, 1):
print(f"Step {i}: {record.reason}")
if "Contradiction" in record.reason:
print(f" *** This step detected the contradiction! ***")
The contradiction occurs because:
- Earlier levels require:
25 <= age <= 50 - Final level requires:
age < 25 AND age > 50— impossible
By examining the before expression in the contradiction record, you can identify exactly which requirements conflict and trace back through your business logic.
When This Matters¶
The optimizer's tracking feature is most valuable when:
- Multiple developers contribute conditions to the same filter over time
- Requirements evolve and accidentally introduce conflicts
- Combining filters from different parts of the application
- Migrating or refactoring legacy filtering logic
- Building user-facing query builders where users can create invalid combinations