YongGoose commented on code in PR #1026:
URL: https://github.com/apache/burr/pull/1026#discussion_r4718563592
##########
burr/core/application.py:
##########
@@ -166,6 +206,30 @@ def _remap_injected_inputs(method: Callable, inputs:
Dict[str, Any]) -> Dict[str
return inputs
+def _remap_single_step_inputs(
+ action: Action, inputs: Dict[str, Any], stream_runner: bool = False
+) -> Dict[str, Any]:
+ """Remaps injected inputs to the method that the caller is about to invoke.
+
+ ``step()``/``astep()`` invoke ``run_and_update``. For a streaming action
that method may be the
+ base-class adapter forwarding ``**run_kwargs`` to
``stream_run_and_update``, so the latter must
+ be inspected as a fallback. ``stream_result()``/``astream_result()`` invoke
+ ``stream_run_and_update`` directly; inspecting ``run_and_update`` first
could bind to a mangled
+ name from a different defining class and corrupt that call.
+
+ :param action: the single-step action that is about to run
+ :param inputs: the processed inputs, including the injected dunders
+ :param stream_runner: True when ``stream_run_and_update`` is the method
being called
+ :return: potentially new dict with the injected values under their mangled
names
+ """
+ if stream_runner:
+ return _remap_injected_inputs(action.stream_run_and_update, inputs)
+ inputs = _remap_injected_inputs(action.run_and_update, inputs)
+ if action.streaming:
Review Comment:
This fallback handles `SingleStepStreamingAction` reached through the
`run_and_update` adapter. Multi-step `StreamingAction`/`AsyncStreamingAction`
have the same adapter shape and are still broken. `StreamingAction.run(self,
state, **run_kwargs)` (`burr/core/action.py:1354`) forwards to `stream_run`,
and `_run_function` only remaps against that adapter
(`burr/core/application.py:251`; the same applies to `_arun_function` at
`:264`). With this PR applied, a class-based `stream_run(self, state,
__context)` still fails through `step()`/`astep()`:
```
TypeError: MultiStream.stream_run() got an unexpected keyword argument
'__context'
```
`stream_result()`/`astream_result()` work for the same class. The bug
predates this PR and is outside its title. Still, `StreamingAction` is the
public, documented class (`docs/concepts/streaming-actions.rst`). On `main` +
this PR, I added these lines after the existing remap in both `_run_function`
and `_arun_function`:
```python
if isinstance(function, Action) and function.streaming:
inputs = _remap_injected_inputs(function.stream_run, inputs)
```
With that change, `step()` and `astep()` pass for both classes, and `pytest
tests/core tests/tracking` stays at 548 passed. Would you add this here, or
should it go to a follow-up issue?
##########
tests/core/test_application.py:
##########
@@ -4207,6 +4218,194 @@ def
test_remap_context_variable_with_mangled_context_kwargs():
assert _remap_dunder_parameters(_action.run, inputs, ["__context",
"__tracer"]) == expected
+def test_remap_context_variable_does_not_clobber_input_ending_with_dunder():
+ _action = ActionWithSuffixedContextInput()
+
+ inputs = {
+ "__context": "context_value",
+ "user__context": "user_value",
+ "foo": "foo_value",
+ }
+ expected = {
+ "user__context": "user_value",
+ "foo": "foo_value",
+ "_ActionWithSuffixedContextInput__context": "context_value",
+ }
+ assert _remap_dunder_parameters(_action.run, inputs, ["__context",
"__tracer"]) == expected
+
+
+class ActionWithUnderscorePrefixedContextInput(ActionWithoutContext):
+ """Neither name is a mangled form of the injected ``__context``: one
leading underscore is not
+ enough to be mangled, and another class' mangled name is not this
class'."""
+
+ def run(self, _user__context, _OtherAction__context, foo, __context):
+ pass
+
+ def inputs(self) -> Union[list[str], tuple[list[str], list[str]]]:
+ return ["_user__context", "_OtherAction__context", "foo", "__context"]
+
+
+def
test_remap_context_variable_does_not_clobber_underscore_prefixed_or_foreign_names():
+ _action = ActionWithUnderscorePrefixedContextInput()
+
+ inputs = {
+ "__context": "context_value",
+ "_user__context": "user_value",
+ "_OtherAction__context": "other_value",
+ "foo": "foo_value",
+ }
+ expected = {
+ "_user__context": "user_value",
+ "_OtherAction__context": "other_value",
+ "foo": "foo_value",
+ "_ActionWithUnderscorePrefixedContextInput__context": "context_value",
+ }
+ assert _remap_dunder_parameters(_action.run, inputs, ["__context",
"__tracer"]) == expected
+
+
+class _LeadingUnderscoreAction(ActionWithoutContext):
+ """CPython strips leading underscores from the class name before
mangling."""
+
+ def run(self, foo, __context):
+ pass
+
+ def inputs(self) -> Union[list[str], tuple[list[str], list[str]]]:
+ return ["foo", "__context"]
+
+
+def test_remap_context_variable_strips_leading_underscores_from_class_name():
+ _action = _LeadingUnderscoreAction()
+
+ result = _remap_dunder_parameters(
+ _action.run, {"foo": 1, "__context": "context_value"}, ["__context"]
+ )
+ assert result == {"foo": 1, "_LeadingUnderscoreAction__context":
"context_value"}
+
+
+class TracerBase(ActionWithoutContext):
+ def run(self, other_param, foo, __tracer, __context):
+ pass
+
+ def inputs(self) -> Union[list[str], tuple[list[str], list[str]]]:
+ return ["other_param", "foo", "__tracer", "__context"]
+
+
+class TracerChild(TracerBase):
+ pass
+
+
+def
test_remap_context_variable_uses_the_defining_class_for_inherited_methods():
+ """``run`` is defined in ``TracerBase``, so the mangled parameters keep
the base name even though
+ the runtime object is a ``TracerChild`` -- mangling follows
``__qualname__``, not ``type(self)``.
+ """
+ _action = TracerChild()
+
+ inputs = {
+ "other_param": 1,
+ "foo": "foo_value",
+ "__tracer": "tracer_value",
+ "__context": "context_value",
+ }
+ expected = {
+ "other_param": 1,
+ "foo": "foo_value",
+ "_TracerBase__tracer": "tracer_value",
+ "_TracerBase__context": "context_value",
+ }
+ assert _remap_dunder_parameters(_action.run, inputs, ["__context",
"__tracer"]) == expected
+
+
+class ___(ActionWithoutContext):
Review Comment:
Nit: this pins a class whose name is only underscores. The guard it covers
is cheap to keep, but the test adds a module-level class named `___` to a
shared test module for a shape that's unlikely in practice. I'd drop the test
and keep the guard.
##########
burr/core/application.py:
##########
@@ -127,6 +127,43 @@ def _adjust_single_step_output(
_raise_fn_return_validation_error(output, action_name)
+def _mangled_parameter_for_class(
+ run_method: Callable, dunder_param: str, params: List[str]
+) -> Optional[str]:
+ """Return the parameter name CPython produced for ``dunder_param`` in
``run_method``.
+
+ CPython rewrites an identifier that starts with two underscores and does
not end with two
+ underscores into ``_ClassName__identifier``, where ``ClassName`` is the
name of the class whose
+ *body defines the method* with any leading underscores stripped -- not the
runtime class, so an
+ inherited ``run`` keeps the base class' name. ``__qualname__`` records
exactly that defining
+ class, which is why it is used here instead of ``type(self).__name__``. A
class whose name is
+ only underscores is not mangled at all, so there is no candidate to derive.
+
+ Deriving the one candidate name, rather than scanning the signature for
anything ending with the
+ dunder, is what keeps a regular user input (``user__context``,
``_user__context``, or a name that
+ merely looks like another class' mangled form) from being mistaken for the
injected parameter and
+ overwritten.
+
+ :param run_method: the bound or unbound method about to be called
+ :param dunder_param: the injected name, e.g. ``"__context"``
+ :param params: the parameter names of ``run_method``
+ :return: the mangled parameter name, or None when the method takes no such
parameter
+ """
+ if not dunder_param.startswith("__") or dunder_param.endswith("__"):
+ return None
+ parts = (getattr(run_method, "__qualname__", "") or "").split(".")
+ if len(parts) < 2:
+ return None # module-level function or lambda: nothing was ever
mangled
+ class_name = parts[-2].lstrip("_")
Review Comment:
`parts[-2]` misses a case that the old suffix scan handled. CPython also
mangles names in functions nested inside a class body, using the innermost
enclosing class. But when a helper in the class body builds `run`, its
`__qualname__` is `NestedDef._make.<locals>.run`. `parts[-2]` is then
`<locals>`, and no candidate matches:
```python
class NestedDef(Action):
def _make():
def run(self, state, __context): ...
return run
run = _make()
```
On `main`, `step()` works for this action because the suffix scan finds
`_NestedDef__context`. With this PR it raises `TypeError:
NestedDef._make.<locals>.run() got an unexpected keyword argument '__context'`.
The pattern is rare, so this isn't blocking. The change below skips the
function parts of the qualname. I applied exactly this to `dc0f8f9`: the nested
case passes, black and flake8 are clean, and `pytest tests/core tests/tracking`
gives 471 passed, the same as the unmodified head.
```suggestion
# CPython mangles with the innermost enclosing class. A part followed by
"<locals>" is a
# function, so a run defined by a helper inside the class body still
resolves to that class.
owners = [
part
for i, part in enumerate(parts[:-1])
if part != "<locals>" and parts[i + 1] != "<locals>"
]
if not owners:
return None
class_name = owners[-1].lstrip("_")
```
##########
tests/core/test_application.py:
##########
@@ -4207,6 +4218,194 @@ def
test_remap_context_variable_with_mangled_context_kwargs():
assert _remap_dunder_parameters(_action.run, inputs, ["__context",
"__tracer"]) == expected
+def test_remap_context_variable_does_not_clobber_input_ending_with_dunder():
+ _action = ActionWithSuffixedContextInput()
+
+ inputs = {
+ "__context": "context_value",
+ "user__context": "user_value",
+ "foo": "foo_value",
+ }
+ expected = {
+ "user__context": "user_value",
+ "foo": "foo_value",
+ "_ActionWithSuffixedContextInput__context": "context_value",
+ }
+ assert _remap_dunder_parameters(_action.run, inputs, ["__context",
"__tracer"]) == expected
+
+
+class ActionWithUnderscorePrefixedContextInput(ActionWithoutContext):
+ """Neither name is a mangled form of the injected ``__context``: one
leading underscore is not
+ enough to be mangled, and another class' mangled name is not this
class'."""
+
+ def run(self, _user__context, _OtherAction__context, foo, __context):
+ pass
+
+ def inputs(self) -> Union[list[str], tuple[list[str], list[str]]]:
+ return ["_user__context", "_OtherAction__context", "foo", "__context"]
+
+
+def
test_remap_context_variable_does_not_clobber_underscore_prefixed_or_foreign_names():
+ _action = ActionWithUnderscorePrefixedContextInput()
+
+ inputs = {
+ "__context": "context_value",
+ "_user__context": "user_value",
+ "_OtherAction__context": "other_value",
+ "foo": "foo_value",
+ }
+ expected = {
+ "_user__context": "user_value",
+ "_OtherAction__context": "other_value",
+ "foo": "foo_value",
+ "_ActionWithUnderscorePrefixedContextInput__context": "context_value",
+ }
+ assert _remap_dunder_parameters(_action.run, inputs, ["__context",
"__tracer"]) == expected
+
+
+class _LeadingUnderscoreAction(ActionWithoutContext):
+ """CPython strips leading underscores from the class name before
mangling."""
+
+ def run(self, foo, __context):
+ pass
+
+ def inputs(self) -> Union[list[str], tuple[list[str], list[str]]]:
+ return ["foo", "__context"]
+
+
+def test_remap_context_variable_strips_leading_underscores_from_class_name():
+ _action = _LeadingUnderscoreAction()
+
+ result = _remap_dunder_parameters(
+ _action.run, {"foo": 1, "__context": "context_value"}, ["__context"]
+ )
+ assert result == {"foo": 1, "_LeadingUnderscoreAction__context":
"context_value"}
+
+
+class TracerBase(ActionWithoutContext):
+ def run(self, other_param, foo, __tracer, __context):
+ pass
+
+ def inputs(self) -> Union[list[str], tuple[list[str], list[str]]]:
+ return ["other_param", "foo", "__tracer", "__context"]
+
+
+class TracerChild(TracerBase):
+ pass
+
+
+def
test_remap_context_variable_uses_the_defining_class_for_inherited_methods():
+ """``run`` is defined in ``TracerBase``, so the mangled parameters keep
the base name even though
+ the runtime object is a ``TracerChild`` -- mangling follows
``__qualname__``, not ``type(self)``.
+ """
+ _action = TracerChild()
+
+ inputs = {
+ "other_param": 1,
+ "foo": "foo_value",
+ "__tracer": "tracer_value",
+ "__context": "context_value",
+ }
+ expected = {
+ "other_param": 1,
+ "foo": "foo_value",
+ "_TracerBase__tracer": "tracer_value",
+ "_TracerBase__context": "context_value",
+ }
+ assert _remap_dunder_parameters(_action.run, inputs, ["__context",
"__tracer"]) == expected
+
+
+class ___(ActionWithoutContext):
+ """A class name made only of underscores. CPython skips mangling entirely
in that case, so
+ ``__context`` stays literal and ``___context`` is an ordinary user input,
not its mangled form.
+ The name is deliberately degenerate: it is the only shape for which the
derived candidate would
+ collapse onto the dunder itself."""
+
+ def run(self, ___context):
+ pass
+
+ def inputs(self) -> Union[list[str], tuple[list[str], list[str]]]:
+ return ["__context", "___context"]
+
+
+def test_remap_context_variable_leaves_all_underscore_class_names_alone():
+ """Without a guard the derived candidate is ``___context``, which is a
parameter a user may
+ legitimately declare -- the injected context would silently overwrite
their input."""
+ _action = ___()
+
+ inputs = {"__context": "context_value", "___context": "user_value"}
+ assert _remap_dunder_parameters(_action.run, inputs, ["__context",
"__tracer"]) == inputs
+
+
+def test_remap_context_variable_injected_value_wins_for_its_own_parameter():
Review Comment:
Nit: the docstring calls passing the mangled name directly "an undocumented
back door". Pinning its precedence in a test makes that back door look
supported. Unless the precedence is meant to be part of the contract, I'd drop
this test.
##########
tests/core/test_application.py:
##########
@@ -4207,6 +4218,194 @@ def
test_remap_context_variable_with_mangled_context_kwargs():
assert _remap_dunder_parameters(_action.run, inputs, ["__context",
"__tracer"]) == expected
+def test_remap_context_variable_does_not_clobber_input_ending_with_dunder():
+ _action = ActionWithSuffixedContextInput()
+
+ inputs = {
+ "__context": "context_value",
+ "user__context": "user_value",
+ "foo": "foo_value",
+ }
+ expected = {
+ "user__context": "user_value",
+ "foo": "foo_value",
+ "_ActionWithSuffixedContextInput__context": "context_value",
+ }
+ assert _remap_dunder_parameters(_action.run, inputs, ["__context",
"__tracer"]) == expected
+
+
+class ActionWithUnderscorePrefixedContextInput(ActionWithoutContext):
+ """Neither name is a mangled form of the injected ``__context``: one
leading underscore is not
+ enough to be mangled, and another class' mangled name is not this
class'."""
+
+ def run(self, _user__context, _OtherAction__context, foo, __context):
+ pass
+
+ def inputs(self) -> Union[list[str], tuple[list[str], list[str]]]:
+ return ["_user__context", "_OtherAction__context", "foo", "__context"]
+
+
+def
test_remap_context_variable_does_not_clobber_underscore_prefixed_or_foreign_names():
+ _action = ActionWithUnderscorePrefixedContextInput()
+
+ inputs = {
+ "__context": "context_value",
+ "_user__context": "user_value",
+ "_OtherAction__context": "other_value",
+ "foo": "foo_value",
+ }
+ expected = {
+ "_user__context": "user_value",
+ "_OtherAction__context": "other_value",
+ "foo": "foo_value",
+ "_ActionWithUnderscorePrefixedContextInput__context": "context_value",
+ }
+ assert _remap_dunder_parameters(_action.run, inputs, ["__context",
"__tracer"]) == expected
+
+
+class _LeadingUnderscoreAction(ActionWithoutContext):
+ """CPython strips leading underscores from the class name before
mangling."""
+
+ def run(self, foo, __context):
+ pass
+
+ def inputs(self) -> Union[list[str], tuple[list[str], list[str]]]:
+ return ["foo", "__context"]
+
+
+def test_remap_context_variable_strips_leading_underscores_from_class_name():
+ _action = _LeadingUnderscoreAction()
+
+ result = _remap_dunder_parameters(
+ _action.run, {"foo": 1, "__context": "context_value"}, ["__context"]
+ )
+ assert result == {"foo": 1, "_LeadingUnderscoreAction__context":
"context_value"}
+
+
+class TracerBase(ActionWithoutContext):
+ def run(self, other_param, foo, __tracer, __context):
+ pass
+
+ def inputs(self) -> Union[list[str], tuple[list[str], list[str]]]:
+ return ["other_param", "foo", "__tracer", "__context"]
+
+
+class TracerChild(TracerBase):
+ pass
+
+
+def
test_remap_context_variable_uses_the_defining_class_for_inherited_methods():
+ """``run`` is defined in ``TracerBase``, so the mangled parameters keep
the base name even though
+ the runtime object is a ``TracerChild`` -- mangling follows
``__qualname__``, not ``type(self)``.
+ """
+ _action = TracerChild()
+
+ inputs = {
+ "other_param": 1,
+ "foo": "foo_value",
+ "__tracer": "tracer_value",
+ "__context": "context_value",
+ }
+ expected = {
+ "other_param": 1,
+ "foo": "foo_value",
+ "_TracerBase__tracer": "tracer_value",
+ "_TracerBase__context": "context_value",
+ }
+ assert _remap_dunder_parameters(_action.run, inputs, ["__context",
"__tracer"]) == expected
+
+
+class ___(ActionWithoutContext):
+ """A class name made only of underscores. CPython skips mangling entirely
in that case, so
+ ``__context`` stays literal and ``___context`` is an ordinary user input,
not its mangled form.
+ The name is deliberately degenerate: it is the only shape for which the
derived candidate would
+ collapse onto the dunder itself."""
+
+ def run(self, ___context):
+ pass
+
+ def inputs(self) -> Union[list[str], tuple[list[str], list[str]]]:
+ return ["__context", "___context"]
+
+
+def test_remap_context_variable_leaves_all_underscore_class_names_alone():
+ """Without a guard the derived candidate is ``___context``, which is a
parameter a user may
+ legitimately declare -- the injected context would silently overwrite
their input."""
+ _action = ___()
+
+ inputs = {"__context": "context_value", "___context": "user_value"}
+ assert _remap_dunder_parameters(_action.run, inputs, ["__context",
"__tracer"]) == inputs
+
+
+def test_remap_context_variable_injected_value_wins_for_its_own_parameter():
+ """A caller passing the mangled name directly is using an undocumented
back door; the injected
+ value is what the declared ``__context`` binds to. Pinned so the
precedence is not implicit."""
+ _action = ActionWithContext()
+
+ inputs = {
+ "__context": "injected",
+ "_ActionWithContext__context": "caller_supplied",
+ "other_param": "other_value",
+ "foo": "foo_value",
+ }
+ result = _remap_dunder_parameters(_action.run, inputs, ["__context",
"__tracer"])
+ assert result["_ActionWithContext__context"] == "injected"
+
+
+@action(reads=[], writes=["app_id"])
+def _function_based_context_action(state: State, __context:
ApplicationContext) -> State:
+ return state.update(app_id=__context.app_id)
+
+
+def test_function_based_action_still_receives_context_after_remap_change():
Review Comment:
Nit: this repeats the existing `test_app_step_context`
(`tests/core/test_application.py:1959`), which also runs a function-based
action declaring `__context` through `app.step()` and asserts on the injected
context. This one could be dropped.
--
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]