Skip to content

fix: resolve postponed annotations without failing on TYPE_CHECKING return types - #1509

Merged
planetf1 merged 12 commits into
generative-computing:mainfrom
planetf1:fix/issue-1507
Aug 12, 2026
Merged

planetf1 merged 12 commits into
generative-computing:mainfrom
planetf1:fix/issue-1507

Conversation

@planetf1

@planetf1 planetf1 commented Aug 6, 2026 •

Copy link
Copy Markdown
Contributor

Issue

Fixes #1507
Fixes #1529

Description

convert_function_to_ollama_tool() built its dynamic Pydantic schema model from raw inspect.signature(func) parameter annotations. Under from __future__ import annotations (PEP 563), those annotations are strings rather than real type objects, so Pydantic could not resolve any non-builtin parameter type — raising PydanticUserError at tool-conversion time. Builtin types (str, int, ...) happened to work by luck via Pydantic's builtin-name lookup.

Fix: try eval_str=True first; 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 of main — the fallback starts from inspect.signature(func) (identical to main) 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.signature follows __wrapped__, so for a function wrapped by functools.wraps the 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 raised PydanticUserError. The second is the worse outcome — a wrong schema that looks valid. So the namespace is taken from inspect.unwrap(func, stop=lambda f: hasattr(f, "__signature__")), reusing the same stop predicate inspect.signature applies internally so both read the same object. No-op for undecorated functions.

Why not eval_str=True alone? 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 hard NameError/AttributeError where main succeeded. 84 in-repo callables have this shape, including python_tool in mellea/stdlib/tools/interpreter.py. A naive try/except fallback (Fix A) is insufficient — it reintroduces PydanticUserError when 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 merges main and 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 @generative stub with a TYPE_CHECKING-only return annotation raises NameError: name 'Decimal' is not defined at decoration time, so the containing module cannot be imported at all.

Provenance. The decoration failure is not a #1504 regression. get_type_hints entered create_response_format in 88a4d754 (#801), and the failure has existed since then — verified by checking out a535fc63, the parent of #1504, where the same reproducer raises the identical NameError from the same frame. #1504's contribution is two lines (describe_function and get_argument switching to eval_str=True), which makes direct calls to those functions raise where they previously returned a quoted string; no @generative user could observe that, because create_response_format already 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 to Any — the same fallback an unannotated function already receives via type_hints.get("return", Any) — rather than failing the import.
  • describe_function (eval_str=True) renders the signature into the prompt via GenerativeStub.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 — Any for 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 through mellea/helpers/__init__.py — matching how tools.py already 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.py contains 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

File Change
mellea/backends/tools.py Per-parameter fallback in convert_function_to_ollama_tool; uses shared helper
mellea/helpers/annotation_helpers.py New resolve_signature_annotations helper: try eval_str=True, fall back per-parameter using inspect.unwrap namespace
mellea/stdlib/components/genstub.py describe_function, get_argument use shared helper; create_response_format degrades unresolvable return to Any
test/backends/_postponed_annotation_samples.py Sample module with from __future__ import annotations; contains the test inputs for tools tests
test/backends/test_discriminated_union_tools.py TestPostponedAnnotations class with 7 cases for convert_function_to_ollama_tool postponed-annotation handling
test/stdlib/components/_postponed_annotation_samples.py Renamed from _pep563_fixtures.py; sample module for genstub tests
test/stdlib/components/test_genstub_unit.py 4 new tests: describe_function, get_argument, create_response_format, and end-to-end @generative decoration

Testing

Tests for convert_function_to_ollama_tool live in TestPostponedAnnotations in the existing test/backends/test_discriminated_union_tools.py, alongside the other convert_function_to_ollama_tool cases; only the from __future__ import annotations sample code is isolated in test/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; two functools.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 the inspect.unwrap fix); and an unannotated parameter alongside a TYPE_CHECKING-only return covering the inspect._empty branch 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_function resolving parameters while rendering the unresolvable return as -> 'Decimal'; get_argument no longer raising; create_response_format degrading to Any; and generative(...) decoration succeeding end to end. All four verified to fail against the pre-fix code.

uv run pytest test/backends/test_discriminated_union_tools.py test/stdlib/components/test_genstub_unit.py -x -q
# all pass

uv run pytest test/ -m "not qualitative" -q
# 3882 passed, 21 skipped

uv run mypy .
# Success: no issues found

uv run ruff format . && uv run ruff check .
# clean

Each of the three fix commits passes its affected test modules independently, so git bisect stays usable.

Attribution

  • AI coding assistants used

Adding a new component, requirement, sampling strategy, or tool?

  • Component
  • Requirement
  • Sampling Strategy
  • Tool

@github-actions github-actions Bot added the bug Something isn't working label Aug 6, 2026
planetf1 added a commit to planetf1/mellea that referenced this pull request Aug 6, 2026
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 marked this pull request as ready for review August 6, 2026 09:16
@planetf1
planetf1 requested a review from a team as a code owner August 6, 2026 09:16
ajbozarth pushed a commit to ajbozarth/mellea that referenced this pull request Aug 6, 2026
…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 ajbozarth left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread test/backends/test_tools_pep563.py Resolved
Comment thread test/backends/_pep563_tool_fixtures.py Resolved
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]>
…eturn annotation regression

Assisted-by: opencode
Signed-off-by: Nigel Jones <[email protected]>
@planetf1

planetf1 commented Aug 7, 2026 •

Copy link
Copy Markdown
Contributor Author

Addressed: the test lives in test_pep563_tool_annotations.py alongside the full PEP 563 test suite. Dropped test_tools_pep563.py entirely.

…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]>
@planetf1
planetf1 marked this pull request as draft August 7, 2026 15:30
@planetf1

planetf1 commented Aug 7, 2026

Copy link
Copy Markdown
Contributor Author

rewriting/fixing up after some local workspace confusion

@ajbozarth ajbozarth left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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]>
@planetf1 planetf1 changed the title fix(backends): resolve postponed annotations in ollama tool schema fix: resolve postponed annotations without failing on TYPE_CHECKING return types 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]>
`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]>
@planetf1
planetf1 marked this pull request as ready for review August 11, 2026 10:46

@ajbozarth ajbozarth left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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__", {})

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@planetf1
planetf1 added this pull request to the merge queue Aug 12, 2026
Merged via the queue into generative-computing:main with commit 04c177d Aug 12, 2026
12 checks passed
@planetf1
planetf1 deleted the fix/issue-1507 branch August 12, 2026 09:03
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

2 participants