Skip to content

fix(stdlib): resolve postponed annotations in generative stub signature - #1504

Merged
planetf1 merged 3 commits into
generative-computing:mainfrom
planetf1:issue-1476
Aug 6, 2026
Merged

planetf1 merged 3 commits into
generative-computing:mainfrom
planetf1:issue-1476

Conversation

@planetf1

@planetf1 planetf1 commented Aug 6, 2026 •

Copy link
Copy Markdown
Contributor

Pull Request

Issue

Fixes #1503

Description

Under from __future__ import annotations (PEP 563 postponed annotations), @generative stub signatures were corrupted before being sent to the model.

  • describe_function() used inspect.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.annotation was the string "str" rather than the type str, so the param_type is str check failed and string arguments were rendered unquoted (value: Alice instead of value: "Alice").

Both are fixed by passing eval_str=True to inspect.signature(), which resolves the annotation strings back to real types — the same resolution create_response_format() already gets for free via typing.get_type_hints().

Why eval_str=True is safe here: any annotation that would raise under eval_str=True (e.g. TYPE_CHECKING-only imports, forward references to not-yet-defined classes) already raises the identical NameError from the pre-existing get_type_hints(func) call in create_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() and GenerativeStub.__init__'s disallowed-param-name check) are deliberately left unchanged — neither inspects .annotation, so PEP 563 doesn't affect them, and adding eval_str there would only add a failure mode for no benefit.

Follow-ups (out of scope here):

Testing

  • Tests added to the respective file if code was changed
  • New code has 100% coverage if code was added
  • Ensure existing tests and github automation passes (a maintainer will kick off the github automation when the rest of the PR is populated)

Added test/stdlib/components/_pep563_fixtures.py, a fixture module with from __future__ import annotations (isolated in its own file since the import is a module-level directive), and two regression tests in test/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

  • AI coding assistants used

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.

  • Component
  • Requirement
  • Sampling Strategy
  • Tool

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.

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]>
@github-actions github-actions Bot added the bug Something isn't working label Aug 6, 2026
@planetf1
planetf1 marked this pull request as ready for review August 6, 2026 00:36
@planetf1
planetf1 requested a review from a team as a code owner August 6, 2026 00:36
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]>
@planetf1
planetf1 added this pull request to the merge queue Aug 6, 2026
Merged via the queue into generative-computing:main with commit c472907 Aug 6, 2026
10 checks passed
@planetf1
planetf1 deleted the issue-1476 branch August 6, 2026 15:12
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]>
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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

bug(stdlib): @generative stub signature corrupted under from __future__ import annotations

2 participants