skrawcz commented on PR #863:
URL: https://github.com/apache/burr/pull/863#issuecomment-6550769474
# PR Review: apache/burr #863 — Fix class-based typed state actions
- **Repo:** apache/burr
- **PR:** #863 — "Fix class-based typed state actions"
- **Author:** FenjuFu (iFLYTEK Astron community)
- **Branch:** `agent/fix-class-based-typed-state` → `main`
- **Closes:** #400
- **Size:** +163 / -3, 4 files
- **State at review:** OPEN
- **Reviewed at commit:** `809cdee2`
---
## Verdict: REQUEST CHANGES
The PR fixes a real, well-documented bug (#400) and takes a reasonable
architectural direction (state-conversion hooks on `ActionSchema`, with an
identity default preserving existing behavior). Core, action, and pydantic test
suites all pass (326 tests). However, the central mechanism —
`convert_state_after_update` in `PydanticActionSchema` — is **incorrect**: it
merges back **all** output-model fields rather than the action's declared
`writes`. This produces spurious `ValueError`s and violates the PR's own
"preserve unrelated fields / only writes declared keys" contract for any
realistic model. The included tests pass only because they use a
fully-pre-populated state that masks the bug. There is also a black formatting
violation the PR claims to have checked but did not.
---
## What the PR does
- Adds three **identity** hooks to `ActionSchema` (`burr/core/typing.py`):
`convert_state_before_run`, `convert_state_before_update`,
`convert_state_after_update`. Default returns `state` unchanged, so
`DefaultSchema` (and all non-pydantic actions) are behaviorally unchanged.
- Overrides these in `PydanticActionSchema`
(`burr/integrations/pydantic.py`) to build the declared input/output models and
merge typed updates back.
- Wires the hooks into the **two-step** class-based execution path:
`_run_function`, `_arun_function`, and `_run_reducer` in
`burr/core/application.py`.
- Adds `tests/integrations/test_class_based_pydantic.py` with a sync and an
async end-to-end test.
The root-cause analysis is accurate: previously the two-step path passed a
raw Burr `State` to `run()`/`update()`, so `state.initial_prompt` attribute
access failed even with a Pydantic schema. Single-step (`@action.pydantic`)
actions were unaffected because they do their own conversion inside
`action_function`, and this PR correctly does **not** touch that path (no
double-conversion).
---
## Blocking issues
### 1. `convert_state_after_update` writes ALL output-model fields, not
declared `writes` (correctness)
`burr/integrations/pydantic.py`:
```python
return merge_to_state(
model=state,
write_keys=list(self._output_type.model_fields), # <-- ALL fields
state=original_state,
)
```
It should use the reducer's declared `writes`. Consequences:
**(a) Spurious "attempted to write to keys it did not declare" error.** If
the output model has any field that is not in the initial state and not in
`writes`, `_run_reducer`'s guard (`extra_keys = new_keys -
set(reducer.writes)`) raises. Reproduced:
```
ValueError: Action w attempted to write to keys {'counter'} that it did not
declare. It declared: (['a'])!
```
(model with `counter: int = 0` not present in initial state, action writes
only `a`.)
**(b) Silent clobbering of undeclared fields.** Even when it doesn't raise
(all fields pre-exist in state), the action writes back every output-model
field — round-tripping fields it never declared. This directly contradicts the
PR's Impact claim that "unrelated fields" are preserved and that "existing
dict-based actions … keep their current behavior." A two-step action that
declares `writes=["a"]` must not mutate `b`.
The included tests dodge both because `build_class_based_app` seeds state
with `ClassBasedState()` (both `initial_prompt` and `observed_prompt` present
as `None`), so no field is ever "new" and the model round-trip happens to
reproduce identical values.
**Fix:** pass the action's declared writes, e.g. thread `reducer.writes`
into the hook (or have the hook accept a `write_keys` argument) rather than
`list(self._output_type.model_fields)`.
### 2. `convert_state_before_run` builds the full model from the
reads-subset (correctness)
`_run_function`/`_arun_function` call the hook with
`state.subset(*function.reads)`, and
`PydanticActionSchema.convert_state_before_run` does
`model_from_state(self._input_type, subset)`. Because the **full** input model
is instantiated from only the read keys, any **required** (no-default) model
field not in `reads` fails validation. Reproduced:
```
pydantic_core.ValidationError: 1 validation error for S
name
Field required [type=missing, ...]
```
(model with required `name`, action reads `[]`.)
The single-step path avoids exactly this by constructing `subset_model(...,
force_optional_fields=...)` dynamic subset models. The class-based path here
does not, so it is inconsistent with the established pydantic-action semantics
and broken for realistic models with required fields. Tests dodge this because
`ClassBasedState`'s fields are all `Optional[...] = None`.
**Fix:** build/subset an input model with non-read fields forced optional
(mirror `subset_model` usage in `pydantic_action`), or otherwise avoid
instantiating required-but-absent fields.
### 3. Black formatting violation (CI)
The diff introduces three consecutive blank lines after the new methods in
`burr/core/typing.py`:
```
return state # type: ignore[return-value]
class DictBasedTypingSystem(...):
```
`black --check burr/core/typing.py` reports "would reformat." The PR's
Validation section only ran `black --check` on the **test file**, not the
modified `typing.py`, so this slipped through and will fail CI's format gate.
---
## Non-blocking observations
- **Test coverage is too weak to protect the fix.** Both tests use an
all-optional, fully-pre-populated model, which is precisely the shape that
hides issues #1 and #2. Add cases: (a) a two-step action whose model has a
field outside its `writes`, asserting that field is untouched and no error is
raised; (b) a model with a required field not in `reads`; (c) assert unrelated
pre-existing state keys survive a write.
- **`convert_state_after_update`'s `TypeError` guard is reasonable**
(rejecting a non-model return from `update()`), but it duplicates intent with
the downstream reducer checks. Fine to keep; just note the error message
assumes the user returned the wrong type rather than, say, a dict.
- **`intermediate_result_type` type is `dict`** in the test schema
(`PydanticActionSchema(ClassBasedState, ClassBasedState, dict)`);
`_validate_result` still enforces dict results, consistent with existing
behavior. Good.
- **Async coverage is genuine:** `tests/pytest.ini` sets
`asyncio_mode=auto`, so the unmarked `async def test_...` actually executes and
exercises the shared `_run_reducer` (reducers are sync-only in Burr; both sync
and async run paths funnel through it). Verified via `-v` run.
- Minor: the new `ActionSchema` hooks use `# type: ignore[return-value]`
because they return `State` where `StateInputType`/`StateOutputType` is
declared — acceptable for identity defaults but worth a one-line comment
explaining the intentional identity fallback.
---
## Validation performed during review
- Created worktree at PR head `809cdee2`; installed `-e .[pydantic]`,
`pydantic[email]`, pytest, pytest-asyncio.
- `pytest tests/integrations/test_class_based_pydantic.py
tests/integrations/test_burr_pydantic.py` → **35 passed**.
- `pytest tests/core/test_application.py tests/core/test_action.py` → **291
passed** (no regression).
- Repro of issue #1(a): undeclared model field → `ValueError` (write-keys
guard). Confirmed.
- Repro of issue #2: required model field not in `reads` → pydantic
`ValidationError`. Confirmed.
- Repro showing all-optional pre-populated state masks the bugs (mirrors PR
tests). Confirmed.
- `black --check`/`--diff` on `burr/core/typing.py` → would reformat (triple
blank line). Confirmed.
---
## Summary
Right problem, right general approach, correct default-fallback design that
keeps existing behavior intact. But the pydantic conversion merges the wrong
key set (all model fields instead of declared writes) and instantiates the full
input model from a reads-subset, causing spurious errors and undeclared-field
writes for any non-trivial model. The tests pass only because they use a shape
that hides both defects, and there's a black violation the PR mis-reports as
clean. Address issues #1–#3 (and strengthen tests to lock them down) before
merge.
--
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]