Repository navigation
fix(stdlib): resolve postponed annotations in generative stub signature - #1504
Merged
Merged
Conversation
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]>
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]>
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]>
jakelorocco
approved these changes
Aug 6, 2026
Merged
via the queue into
generative-computing:main
with commit Aug 6, 2026
c472907
10 checks passed
planetf1
added a commit
to planetf1/mellea
that referenced
this pull request
Aug 11, 2026
…KING returns generative-computing#1504 fixed generative-computing#1503 by switching `genstub.py` to `inspect.signature(func, eval_str=True)`. That resolves postponed parameter annotations, but it also evaluates the return annotation — so a `@generative` stub whose return type is imported only under `if TYPE_CHECKING:` raises `NameError` where it previously worked. Both call sites are affected: - `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. 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]>
This was referenced Aug 11, 2026
planetf1
added a commit
to planetf1/mellea
that referenced
this pull request
Aug 11, 2026
…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]>
psschwei
pushed a commit
to psschwei/mellea
that referenced
this pull request
Aug 12, 2026
…eturn types (generative-computing#1509) * fix(backends): resolve postponed annotations in ollama tool schema 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]> * fix(backends): resolve postponed annotations per-parameter to avoid return annotation regression Assisted-by: opencode Signed-off-by: Nigel Jones <[email protected]> * test(backends): fold postponed-annotation tests into existing tool test 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]> * test(backends): guard TC-only postponed-annotation tests against silent 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]> * fix(backends): resolve tool annotations in the wrapped function's module `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]> * refactor(backends): log why the tool annotation fallback engaged 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(backends): cover a colliding type name in wrapped tool resolution `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]> * refactor(backends): extract postponed-annotation resolution into a helper 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]> * test(backends): cover an unannotated parameter in the annotation fallback 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]> * fix(stdlib): resolve genstub annotations without failing on TYPE_CHECKING 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]> * fix(stdlib): survive an unresolvable return type at stub decoration time `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]> --------- Signed-off-by: Nigel Jones <[email protected]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Pull Request
Issue
Fixes #1503
Description
Under
from __future__ import annotations(PEP 563 postponed annotations),@generativestub signatures were corrupted before being sent to the model.describe_function()usedinspect.signature(func), which renders postponed annotations as literal strings —(product_description: str) -> list[Requirement]became(product_description: 'str') -> 'list[Requirement]'in the prompt.get_argument()had the same issue at the parameter level:param.annotationwas the string"str"rather than the typestr, so theparam_type is strcheck failed and string arguments were rendered unquoted (value: Aliceinstead ofvalue: "Alice").Both are fixed by passing
eval_str=Truetoinspect.signature(), which resolves the annotation strings back to real types — the same resolutioncreate_response_format()already gets for free viatyping.get_type_hints().Why
eval_str=Trueis safe here: any annotation that would raise undereval_str=True(e.g.TYPE_CHECKING-only imports, forward references to not-yet-defined classes) already raises the identicalNameErrorfrom the pre-existingget_type_hints(func)call increate_response_format(), which every@generative-decorated function goes through at decoration time. So this cannot break any function that could previously be decorated with@generative— it only changes which of two co-located calls raises first.The two other
inspect.signature(func)call sites in this file (bind_function_arguments()andGenerativeStub.__init__'s disallowed-param-name check) are deliberately left unchanged — neither inspects.annotation, so PEP 563 doesn't affect them, and addingeval_strthere would only add a failure mode for no benefit.Follow-ups (out of scope here):
mellea/backends/tools.py'sconvert_function_to_ollama_toolhas the same root-cause bug for tool-schema generation from annotated functions — filed as convert_function_to_ollama_tool breaks under from __future__ import annotations (PEP 563) #1507, fixed in fix: resolve postponed annotations without failing on TYPE_CHECKING return types #1509.@generative→ prompt-template chain under PEP 563 (the new tests calldescribe_function/get_argumentdirectly); worth adding later.Testing
Added
test/stdlib/components/_pep563_fixtures.py, a fixture module withfrom __future__ import annotations(isolated in its own file since the import is a module-level directive), and two regression tests intest/stdlib/components/test_genstub_unit.py— each with a precondition guard on__annotations__so they can't pass vacuously if PEP 563 is later dropped from the fixture module.uv run python -m pytest test/stdlib/components/test_genstub_unit.py -v— 33 passed.uv run ruff format --check,uv run ruff check,uv run mypy— all clean on the three changed files.Attribution
Adding a new component, requirement, sampling strategy, or tool?
If your PR adds or modifies one of the types below, check the matching box. A checklist of type-specific review items will be posted as a comment.
NOTE: Please ensure you have an issue that has been acknowledged by a core contributor and routed you to open a pull request against this repository. Otherwise, please open an issue before continuing with this pull request.