Repository navigation
fix: resolve postponed annotations without failing on TYPE_CHECKING return types - #1509
Conversation
Match the module-top-level import style used in PR generative-computing#1509's test/backends/test_tools_pep563.py for the same fixture pattern. Assisted-by: Claude Code Signed-off-by: Nigel Jones <[email protected]>
…re (generative-computing#1504) * fix(stdlib): resolve postponed annotations in generative stub signature inspect.signature(func) returns literal annotation strings when the caller's module has `from __future__ import annotations` (PEP 563), corrupting both the rendered function signature and the argument value-quoting check in describe_function()/get_argument(). Pass eval_str=True so annotations resolve the same way typing.get_type_hints() already resolves them elsewhere in the codebase. Fixes generative-computing#1503 Assisted-by: Claude Code Signed-off-by: Nigel Jones <[email protected]> * fix(stdlib): drop stale issue ref and guard PEP 563 test preconditions Regression test comments cited generative-computing#1476 (the original, unrelated report) instead of generative-computing#1503 (this fix); per project convention, drop the numeric ref rather than just correct it. Also pin each test's precondition via __annotations__ so it can't pass vacuously if the fixture module ever drops `from __future__ import annotations`. Assisted-by: Claude Code Signed-off-by: Nigel Jones <[email protected]> * test(stdlib): move PEP 563 fixture imports to module level Match the module-top-level import style used in PR generative-computing#1509's test/backends/test_tools_pep563.py for the same fixture pattern. Assisted-by: Claude Code Signed-off-by: Nigel Jones <[email protected]> --------- Signed-off-by: Nigel Jones <[email protected]>
ajbozarth
left a comment
There was a problem hiding this comment.
Fix is correct and I reproduced the failure and the fix locally. One structural change on how the test is split across files — details inline.
6da9180 to
2447632
Compare
convert_function_to_ollama_tool read raw inspect.signature() annotations, which are unresolved strings under `from __future__ import annotations` (PEP 563). Pydantic could not build a schema for any non-builtin parameter type, raising PydanticUserError. Resolve with eval_str=True, matching the fix already applied to genstub.py for the same root cause. Assisted-by: Claude Code Signed-off-by: Nigel Jones <[email protected]>
2447632 to
172f0c1
Compare
…eturn annotation regression Assisted-by: opencode Signed-off-by: Nigel Jones <[email protected]>
|
Addressed: the test lives in |
…st module Addresses review feedback on generative-computing#1509. The PEP 563 regression tests were moved into test_discriminated_union_tools.py, already the only module exercising convert_function_to_ollama_tool, rather than living in a second module for the same function. The previous change only renamed the standalone file instead of moving the tests, which did not address the review. Also renames the samples module to _postponed_annotation_samples.py, dropping the PEP number from the filename as requested. The module-level 'from __future__ import annotations' still requires the sample code to sit in its own module; only the tests move. Verified the moved tests are not vacuous: against the pre-fix baseline 2 of 4 fail, and against parameter-blind eval_str=True resolution 3 of 4 fail. Assisted-by: Claude Code Signed-off-by: Nigel Jones <[email protected]>
|
rewriting/fixing up after some local workspace confusion |
ajbozarth
left a comment
There was a problem hiding this comment.
Both earlier threads resolved cleanly — the tests are now in test_discriminated_union_tools.py as TestPostponedAnnotations (fits the file's existing class style, no need to switch to module-level functions) and the sample module name drops the PEP number. Verified locally: all 27 tests in the file pass, ruff/mypy clean, and the fix matches #1507 — the per-parameter approach also correctly avoids the regression that plain eval_str=True would introduce on TYPE_CHECKING-only return annotations. One small non-blocking nit inline.
…nt no-op Adds the same precondition assert the first test in TestPostponedAnnotations already has to the three TYPE_CHECKING-only cases, confirming their sample annotations are still postponed strings. Without it, dropping `from __future__ import annotations` from _postponed_annotation_samples.py would make these tests pass without exercising the resolution path at all. Ref generative-computing#1507 Assisted-by: Claude Code Signed-off-by: Nigel Jones <[email protected]>
`inspect.signature` follows `__wrapped__`, so the annotations reaching the per-parameter fallback can belong to a function in a different module than the object passed in. Reading globals from that object meant a `functools.wraps` decorator's module supplied the resolution namespace, so a colliding type name resolved to the wrong type and produced a silently incorrect tool schema where the previous code raised `PydanticUserError`. Take the namespace from `inspect.unwrap(func, stop=...)`, using the same stop predicate `inspect.signature` itself uses, so both read the same object. This is a no-op for undecorated functions. Also from review: - correct the lead comment, which described the per-parameter loop as being used instead of `eval_str=True` rather than as its fallback - log the unresolved annotation at debug rather than swallowing it silently - record why the `eval` is bounded, next to its noqa - guard the TYPE_CHECKING-only tests so they fail instead of passing vacuously if the sample module's import moves out of `if TYPE_CHECKING:` - match on the unresolved name in the `PydanticUserError` assertion Assisted-by: Claude Code Signed-off-by: Nigel Jones <[email protected]>
The outer `except` around `inspect.signature(func, eval_str=True)` discarded the exception entirely, while the per-parameter handler inside it logs at debug. That asymmetry meant there was no way to tell why the fallback had engaged for a given tool without attaching a debugger. Log the exception type and message at debug, matching the inner handler. Assisted-by: Claude Code Signed-off-by: Nigel Jones <[email protected]>
`test_decorated_tool_resolves_in_wrapped_functions_module` covers a type name absent from the decorator's module, which degrades loudly to `PydanticUserError`. It does not cover the worse case the namespace fix exists for: a name that is present in the decorator's module but bound to a different type, where resolving in the wrong namespace succeeds and emits a plausible-looking schema for entirely the wrong type. Add `Zone` to the samples module and a shadowing `Zone` with a different field in the test module, so a wrapper defined in the test module resolves against the wrong binding under the previous behaviour. Verified the new test fails without the `inspect.unwrap` namespace fix, producing a schema with `wrong_field: integer` in place of `identifier: string` and raising nothing. Assisted-by: Claude Code Signed-off-by: Nigel Jones <[email protected]>
…lper The try-`eval_str`-then-resolve-per-parameter logic is needed by more than one call site, so move it out of `convert_function_to_ollama_tool` into `mellea/helpers/annotation_helpers.resolve_signature_annotations`. Imported directly from the submodule rather than re-exported through `mellea/helpers/__init__.py`, matching how `tools.py` already imports `_run_async_in_thread`. That keeps it out of the public API surface. No behavioural change: the existing tool-conversion tests pass unmodified. Assisted-by: Claude Code Signed-off-by: Nigel Jones <[email protected]>
…back In the per-parameter fallback an unannotated parameter arrives as `inspect._empty` rather than a string, so it takes the branch that skips resolution. Nothing exercised that branch, leaving the helper at 75% branch coverage. Add a sample with one bare and one annotated parameter alongside a TYPE_CHECKING-only return, and assert the bare one still reaches the schema defaulting to `str`. Takes the helper to 100% statement and branch coverage. Assisted-by: Claude Code Signed-off-by: Nigel Jones <[email protected]>
…KING returns generative-computing#1504 fixed generative-computing#1503 by switching two `genstub.py` call sites to `inspect.signature(func, eval_str=True)`. That resolves postponed parameter annotations, but it also evaluates the return annotation, so an unresolvable return type — a `TYPE_CHECKING`-only import, or a forward reference — raises `NameError` at both sites even when every parameter resolves cleanly: - `get_argument` reads only the named parameter's annotation, so the return annotation is incidental and resolving it should never fail the call. - `describe_function` renders the signature into the prompt via `GenerativeStub.jinja2`, so the return annotation *is* consumed by the model. An unresolvable one is therefore left as its postponed string and renders quoted — `-> 'Decimal'` — which still names the type, rather than being dropped from the prompt. The alternative, omitting it entirely, tells the model less. Both now use the shared `resolve_signature_annotations` helper. The generative-computing#1503 behaviour is unchanged for resolvable annotations: the existing assertions that no parameter renders quoted still pass. Scope of what generative-computing#1504 actually broke: only *direct* calls to these two functions, which previously returned a quoted string rather than raising. No `@generative` user could observe it, because `create_response_format` already failed earlier in `GenerativeStub.__init__` — a separate defect dating to `88a4d754` (generative-computing#801), not to generative-computing#1504. That one is fixed in the following commit; see generative-computing#1529. Also renames `_pep563_fixtures.py` to `_postponed_annotation_samples.py` with its call sites, per review feedback on this PR: the module holds no `@pytest.fixture`, and the PEP number does not belong in the filename. The backends equivalent was renamed on that basis; this one merged under the old name via generative-computing#1504. The import and an assertion embedding the full module path are both updated. Verified: both new tests fail against the pre-fix code with `NameError`. Assisted-by: Claude Code Signed-off-by: Nigel Jones <[email protected]>
`create_response_format` resolves annotations with `get_type_hints`, which
evaluates every annotation including the return type. `GenerativeStub.__init__`
calls it, so a `@generative` stub whose return type exists only under
`if TYPE_CHECKING:` raised `NameError` at decoration time — meaning the
containing module could not be imported at all, with no model call involved.
Only the return type is read here, and an unannotated function already falls
back to `Any` via `type_hints.get("return", Any)`. Degrade an unresolvable
return to that same `Any` rather than failing the decoration. The response model
then parses the result as `Any` instead of the declared type, which is the
behaviour an unannotated stub already gets.
The earlier commit in this PR fixed `describe_function` and `get_argument` but
missed this site, and CI passed regardless: both tests called those functions
directly, so nothing exercised the `@generative` decoration path. Add a test at
that entry point as well as one for `create_response_format` itself.
Assisted-by: Claude Code
Signed-off-by: Nigel Jones <[email protected]>
cea1a95 to
8c4224c
Compare
ajbozarth
left a comment
There was a problem hiding this comment.
Some feedback from Claude.
All three items from my earlier round are addressed, nothing reverted. Tests green, mypy/ruff clean. One optional nit inline.
| target = inspect.unwrap(func, stop=lambda f: hasattr(f, "__signature__")) | ||
| # A module's globals already carry `__builtins__`, so no defensive copy is | ||
| # needed. | ||
| g = getattr(target, "__globals__", {}) |
There was a problem hiding this comment.
Optional/non-blocking: this passes only __globals__ to eval, no localns, so an annotation referencing a name local to a TYPE_CHECKING block or enclosing scope resolves to its string rather than the type. That's the documented, intended degradation here — just flagging it's narrower than get_type_hints's globalns+localns merge. Fine to leave as-is.
04c177d
Issue
Fixes #1507
Fixes #1529
Description
convert_function_to_ollama_tool()built its dynamic Pydantic schema model from rawinspect.signature(func)parameter annotations. Underfrom __future__ import annotations(PEP 563), those annotations are strings rather than real type objects, so Pydantic could not resolve any non-builtin parameter type — raisingPydanticUserErrorat tool-conversion time. Builtin types (str,int, ...) happened to work by luck via Pydantic's builtin-name lookup.Fix: try
eval_str=Truefirst; on any exception (e.g. a TYPE_CHECKING-only return type), fall back to resolving each string parameter annotation individually, leaving genuinely-unresolvable ones as strings for Pydantic to report. This is a strict behavioural superset ofmain— the fallback starts frominspect.signature(func)(identical tomain) and only ever replaces string annotations with successfully-resolved objects, so no regression is structurally possible on that path.Which namespace the fallback evaluates in.
inspect.signaturefollows__wrapped__, so for a function wrapped byfunctools.wrapsthe annotations it returns belong to the wrapped function, which may live in a different module than the object passed in. Reading globals from the passed-in object would let the decorator's module supply the resolution namespace, which fails two ways: if the type name is simply absent there, the annotation stays a string and Pydantic reports it; if the name exists but refers to a different type, it resolves to that type and emits a silently incorrect tool schema where the pre-existing code raisedPydanticUserError. The second is the worse outcome — a wrong schema that looks valid. So the namespace is taken frominspect.unwrap(func, stop=lambda f: hasattr(f, "__signature__")), reusing the same stop predicateinspect.signatureapplies internally so both read the same object. No-op for undecorated functions.Why not
eval_str=Truealone? The full-signature approach was blocked by four independent reviewers: it evaluates the return annotation too (which this schema never consumes), turning TYPE_CHECKING-only or forward-referenced return types into hardNameError/AttributeErrorwheremainsucceeded. 84 in-repo callables have this shape, includingpython_toolinmellea/stdlib/tools/interpreter.py. A naive try/except fallback (Fix A) is insufficient — it reintroducesPydanticUserErrorwhen TYPE_CHECKING return + custom parameter coexist.Also fixed here: the same root cause in
genstub.py(#1529)The same "resolving the whole signature to get the parameters" mistake exists in
genstub.py, so this PR mergesmainand fixes it there too rather than leaving a known break in a sibling module to a follow-up.Confirmed against
main(72488902) before the fix: a@generativestub with aTYPE_CHECKING-only return annotation raisesNameError: name 'Decimal' is not definedat decoration time, so the containing module cannot be imported at all.Provenance. The decoration failure is not a #1504 regression.
get_type_hintsenteredcreate_response_formatin88a4d754(#801), and the failure has existed since then — verified by checking outa535fc63, the parent of #1504, where the same reproducer raises the identicalNameErrorfrom the same frame. #1504's contribution is two lines (describe_functionandget_argumentswitching toeval_str=True), which makes direct calls to those functions raise where they previously returned a quoted string; no@generativeuser could observe that, becausecreate_response_formatalready failed earlier in__init__. Full detail in #1529.Three call sites are affected, and they differ in whether the return annotation is actually needed:
create_response_format(get_type_hints) types the Pydantic response model that parses model output, so the return type is required. An unresolvable return now falls back toAny— the same fallback an unannotated function already receives viatype_hints.get("return", Any)— rather than failing the import.describe_function(eval_str=True) renders the signature into the prompt viaGenerativeStub.jinja2, so the return annotation is consumed by the model. An unresolvable one is left as its postponed string and renders quoted —-> 'Decimal'— which still names the type.get_argument(eval_str=True) reads only the named parameter's annotation, so the return annotation is incidental and must never fail the call.Each degradation is bounded by behaviour the project already ships —
Anyfor an unannotated return, and quoted annotations as the pre-#1504 norm — rather than introducing a new state.Shared helper. With three call sites needing the same logic, it moves to
mellea/helpers/annotation_helpers.resolve_signature_annotations. Imported directly from the submodule rather than re-exported throughmellea/helpers/__init__.py— matching howtools.pyalready imports_run_async_in_thread— so the public API surface does not grow. 100% statement and branch coverage via its callers.Test module rename. Review feedback noted that
_pep563_fixtures.pycontains no@pytest.fixture, and that the PEP number does not belong in a filename. The backends equivalent was renamed on that basis; the stdlib one merged under the old name via #1504 and is renamed to match, including an assertion that embeds the full module path.What changed
mellea/backends/tools.pyconvert_function_to_ollama_tool; uses shared helpermellea/helpers/annotation_helpers.pyresolve_signature_annotationshelper: tryeval_str=True, fall back per-parameter usinginspect.unwrapnamespacemellea/stdlib/components/genstub.pydescribe_function,get_argumentuse shared helper;create_response_formatdegrades unresolvable return toAnytest/backends/_postponed_annotation_samples.pyfrom __future__ import annotations; contains the test inputs for tools teststest/backends/test_discriminated_union_tools.pyTestPostponedAnnotationsclass with 7 cases forconvert_function_to_ollama_toolpostponed-annotation handlingtest/stdlib/components/_postponed_annotation_samples.py_pep563_fixtures.py; sample module for genstub teststest/stdlib/components/test_genstub_unit.pydescribe_function,get_argument,create_response_format, and end-to-end@generativedecorationTesting
Tests for
convert_function_to_ollama_toollive inTestPostponedAnnotationsin the existingtest/backends/test_discriminated_union_tools.py, alongside the otherconvert_function_to_ollama_toolcases; only thefrom __future__ import annotationssample code is isolated intest/backends/_postponed_annotation_samples.py, since the directive is module-scoped.Seven cases: a postponed custom parameter type; TYPE_CHECKING-only return with builtin params; TYPE_CHECKING-only return combined with a custom parameter (the case that distinguishes per-parameter resolution from a plain try/except fallback); a genuinely unresolvable parameter asserting it still surfaces as
PydanticUserError; twofunctools.wraps-decorated cases (absent name degrades loudly; colliding name — present in the wrapper's module but bound to a different type — produces a wrong schema silently under the previous code and is verified to fail without theinspect.unwrapfix); and an unannotated parameter alongside a TYPE_CHECKING-only return covering theinspect._emptybranch in the helper (takes it to 100% branch coverage).Each test asserts its own precondition — that the annotation under test is still a postponed string, and for TYPE_CHECKING cases that
inspect.signature(..., eval_str=True)still raises — so none can quietly stop exercising the resolution path if the sample module changes.Four tests in
test/stdlib/components/test_genstub_unit.py:describe_functionresolving parameters while rendering the unresolvable return as-> 'Decimal';get_argumentno longer raising;create_response_formatdegrading toAny; andgenerative(...)decoration succeeding end to end. All four verified to fail against the pre-fix code.Each of the three fix commits passes its affected test modules independently, so
git bisectstays usable.Attribution
Adding a new component, requirement, sampling strategy, or tool?