xihaian251 opened a new issue, #1017:
URL: https://github.com/apache/burr/issues/1017
`Application.stream_result()` and `Application.astream_result()` dispatch
`pre_run_step` before `_process_inputs()` has run, so the hook receives the
caller's raw dictionary instead of the one the action gets.
`Application.step()` does it in the right order; `Application.astep()` is
covered by #979. These two are neither.
## Bug description
In `stream_result`, the first `try` block ends with:
```python
self._increment_sequence_id()
self._adapter_set.call_all_lifecycle_hooks_sync(
"pre_run_step",
...,
inputs=inputs, # raw
)
```
and `_process_inputs()` only runs afterwards, in the second `try` block:
```python
action_inputs = self._process_inputs(inputs, next_action)
if not next_action.streaming:
action, result, state = self._step(inputs=inputs, _run_hooks=False)
```
`astream_result` has the same shape (`pre_run_step` with `inputs=inputs`,
`_process_inputs` later).
That one mis-ordering produces three observable problems:
1. **The hook sees a different dictionary than the action.** Undeclared keys
are still there, and the dependencies `_process_inputs` injects (`__context`,
`__tracer`) are missing.
2. **A step that is about to be rejected gets announced anyway.**
`_process_inputs` raises for reserved `__`-prefixed keys and for missing
required inputs, but `pre_run_step` has already fired by then — and
`post_run_step` fires in the error handler too, so the tracking stream records
a step that never started.
3. **Inputs are processed twice on a non-streaming halt** — see #1007. The
entry computes `action_inputs`, then delegates to `_step`/`_astep`, which
process the same dict again; the first result is thrown away and the injected
dependency is constructed twice.
Problem 1 is not only cosmetic. `TracerFactoryContextHook.pre_run_step`
(`burr/core/application.py`) reads `inputs["__tracer"]` and, when it is absent,
constructs its own `TracerFactory`. So on these entry points the tracing
context and the action run against **two different factory objects**.
## Steps to reproduce
```python
import asyncio
from burr.core import ApplicationBuilder, State, action
from burr.core.application import ApplicationContext
from burr.lifecycle.base import PreRunStepHook
class Spy(PreRunStepHook):
def __init__(self):
self.seen = []
def pre_run_step(self, *, inputs, action, state, **kw):
self.seen.append(dict(inputs))
@action(reads=[], writes=["value"])
def sync_action(state: State, value: int, __context: ApplicationContext) ->
State:
return state.update(value=value)
@action(reads=[], writes=["value"])
async def async_action(state: State, value: int, __context:
ApplicationContext) -> State:
return state.update(value=value)
async def main():
for name, act, run in (
("step", sync_action, lambda a: a.step(inputs={"value": 1, "noise":
2})),
("stream_result", sync_action,
lambda a: list(a.stream_result(halt_after=["sync_action"],
inputs={"value": 1, "noise":
2})[1])),
("astep", async_action, lambda a: a.astep(inputs={"value": 1,
"noise": 2})),
("astream_result", async_action,
lambda a: a.astream_result(halt_after=["async_action"],
inputs={"value": 1, "noise": 2})),
):
spy = Spy()
app =
ApplicationBuilder().with_actions(act).with_entrypoint(act.__name__).with_hooks(spy).build()
out = run(app)
if asyncio.iscoroutine(out):
await out
print(f"{name:16} pre_run_step saw {sorted(spy.seen[0])}")
asyncio.run(main())
```
Observed on `main` (`222b32c3`) -- verbatim, keys are sorted for display:
```text
step pre_run_step saw ['__context', 'value']
stream_result pre_run_step saw ['noise', 'value']
astep pre_run_step saw ['noise', 'value']
astream_result pre_run_step saw ['noise', 'value']
```
`step()` hands the hook the filtered dictionary plus the injected
`__context`; the other three hand it the caller's dictionary.
## Measured consequences
Object identity of the injected dependency (`_context_factory` returns a new
`ApplicationContext` per call, so a mismatch means the inputs were built more
than once):
| entry point | hook sees `__context` | hook's object `is` action's object |
|---|---|---|
| `step()` | yes | **yes** |
| `astep()` | no | **no** |
| `stream_result()` | no | **no** |
| `astream_result()` | no | **no** |
`_process_inputs()` calls per action execution:
| entry point | action kind | calls |
|---|---|---|
| `step()` | sync | 1 |
| `astep()` | async / sync-delegated | 1 / 1 |
| `stream_result()` | non-streaming halt | **2** |
| `stream_result()` | streaming halt | 1 |
| `astream_result()` | non-streaming halt | **2** (sync and async action) |
| `astream_result()` | streaming halt | 1 |
Tracker records written for a step rejected by input validation
(`LocalTrackingClient`, with `inputs={"__reserved": 1}` and with a missing
required input — both identical):
| entry point | records |
|---|---|
| `step()` | none |
| `astep()` / `stream_result()` / `astream_result()` | `begin_entry`,
`end_entry` |
## Expected behavior
Same as #979 states, applied to these entry points:
- inputs are validated and processed before `pre_run_step` is invoked;
- the hook receives the processed inputs that are passed to the action;
- the same processed dictionary is used by both the hook and the action;
- `pre_run_step` does not fire when input validation fails.
## Relationship to other work
- #979 / #980 / #995 cover `astep()`. They edit `_step`/`_astep` and do not
move the dispatch in `stream_result`/`astream_result`, so these two entry
points stay open regardless of which of them lands.
- #1007 is symptom 3 above.
- #999 is one instance of symptom 2: with a tracker attached, a rejected
step surfaced `KeyError(('…', 'action', None))` from `post_end_stream` instead
of the `ValueError`. #1000 guards that call, so this issue is not about
re-fixing it.
- @enekoreto already identified this in a review on #980 ("`stream_result`
and `astream_result` have the same problem … Should I open an issue for those
two?") — filing this so the observation does not get lost.
- PR #937 established that injected `__context`/`__tracer` are meant to
reach async and streaming actions; this is the hook side of the same contract.
## A trap for whoever fixes it
Leaving `_process_inputs()` where it is and moving the `pre_run_step`
dispatch *down* to it reintroduces the #999 symptom through a different hook.
Measured on a branch built that way: `stream_result(inputs={"__reserved": 1,
…})` raises `KeyError((app_id, 0))` instead of `ValueError`, from
`TracerFactoryContextHook.post_run_step`, which indexes
`self.token_pointer_map[(app_id, sequence_id)]` with a bare subscript and only
catches `ValueError`. `post_run_step` is not independent of `pre_run_step`.
Suppressing the announcement of a rejected step has to suppress both halves,
and the processing has to move *up*, not the hook *down*.
## Environment
Windows 11, Python 3.13.1 and 3.12.14 (results identical). Measurements
taken on `222b32c3`.
--
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]