digit50 opened a new issue, #960:
URL: https://github.com/apache/burr/issues/960
When a state key has the same name as one of the builtins that
`Condition.safe_expr` allows (`len`, `abs`, `min`, `max`, `sum`, `all`, `any`,
`str`, `int`, `float`, `bool`), `safe_expr` uses the builtin instead of the
state value. `Condition.expr` does the opposite, so the same expression gives a
different answer, sometimes silently.
# Current behavior
With state `{"count": 3, "max": 5, "sum": 0, "any": False}`:
- `count < max` is True under `expr` and raises `TypeError` under
`safe_expr`, because `max` is the builtin function.
- `sum == 0` is True under `expr` and False under `safe_expr`, with no error.
- `any` is False under `expr` and True under `safe_expr`, since a builtin
function is truthy.
In an application, a transition guarded by `Condition.safe_expr("sum == 0")`
after an action that writes `sum=0` takes the default edge instead, and nothing
is raised.
## Stack Traces
```
TypeError: '<' not supported between instances of 'int' and
'builtin_function_or_method'
```
## Steps to replicate behavior
1. Save the script below as `repro.py`.
2. `pip install apache-burr==0.43.0`
3. `python repro.py`
```python
from burr.core import ApplicationBuilder, State, action, default
from burr.core.action import Condition
state = State({"count": 3, "max": 5, "sum": 0, "any": False})
def run(cond):
try:
return cond.run(state)[Condition.KEY]
except Exception as e:
return f"{type(e).__name__}: {e}"
for text in ["count < max", "sum == 0", "any"]:
e = Condition.expr(text)
s = Condition.safe_expr(text)
print(f"{text!r}")
print(f" expr -> {run(e)!r}, reads={sorted(e.reads)}")
print(f" safe_expr -> {run(s)!r}, reads={sorted(s.reads)}")
print(f" expected -> safe_expr gives the same result as expr")
@action(reads=[], writes=["sum"])
def start(state: State) -> State:
return state.update(sum=0)
@action(reads=[], writes=[])
def zero(state: State) -> State:
return state
@action(reads=[], writes=[])
def other(state: State) -> State:
return state
app = (
ApplicationBuilder()
.with_actions(start=start, zero=zero, other=other)
.with_transitions(
("start", "zero", Condition.safe_expr("sum == 0")),
("start", "other", default),
)
.with_entrypoint("start")
.build()
)
app.step()
print("application with sum=0 and transition safe_expr('sum == 0'):")
print(f" observed next action: {app.get_next_action().name}")
print(" expected next action: zero")
```
Output:
```
'count < max'
expr -> True, reads=['count']
safe_expr -> "TypeError: '<' not supported between instances of 'int' and
'builtin_function_or_method'", reads=['count']
expected -> safe_expr gives the same result as expr
'sum == 0'
expr -> True, reads=[]
safe_expr -> False, reads=[]
expected -> safe_expr gives the same result as expr
'any'
expr -> False, reads=[]
safe_expr -> True, reads=[]
expected -> safe_expr gives the same result as expr
application with sum=0 and transition safe_expr('sum == 0'):
observed next action: other
expected next action: zero
```
## Library & System Information
- apache-burr 0.43.0 (code unchanged on main at f8488d0c)
- Python 3.12.3
- Linux
# Expected behavior
`safe_expr` resolves names the same way `expr` does: a state key wins over a
builtin of the same name, as the docstring says names are resolved against the
state via `State.get_all`. Alternatively, `safe_expr` should reject a state key
that shadows an allowlisted builtin with a clear error, rather than return a
different answer.
# Additional context
Cause: `_SafeExprInterpreter._eval_Name` in `burr/core/action.py` (lines
568-574 at f8488d0c) returns `_SAFE_EXPR_BUILTINS[node.id]` before it looks at
the state names. `expr()` calls `eval(..., None, state.get_all())`, so state
locals win there.
A related point: the names are also left out of `Condition.reads`, because
the name collector (lines 842-848) skips everything in `builtins.__dict__`.
`expr` has the same filter, so this part is not new, but it means the
missing-key check never covers a state key named `max` or `sum` under either
condition type.
Proposed fix: in `_eval_Name`, look up `self._names` first and fall back to
`_SAFE_EXPR_BUILTINS`, matching `expr()`. Filter `reads` against
`_SAFE_EXPR_BUILTINS` rather than all of `builtins.__dict__`, and add a test
with a state key named `max` or `sum`.
I'll open a PR with this fix.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]