Skip to content

Signature and parameter caches keep every function alive #21

Closed

Description

@hanhyperfx

_signature_cache and _parameter_cache in uncalled_for/introspection.py are plain dicts keyed by the function, with no limit. A function that the program drops stays alive for the life of the process, with everything its closure holds.

This matters for a server that builds its tools as closures per request or per user. FastMCP calls get_signature and get_dependency_parameters on each tool function, so each rebuilt server adds keys that are never removed.

Reproduction

fastmcp 3.3.1, uncalled-for 0.2.0, Python 3.12. The same dicts are on main today.

import asyncio
import gc
import weakref

from fastmcp import Client, FastMCP
from uncalled_for import introspection


async def build_and_call() -> weakref.ref:
    mcp = FastMCP("demo")
    index = list(range(100_000))

    def search(query: str) -> int:
        return len(index)

    mcp.tool(search)
    async with Client(mcp) as client:
        await client.call_tool("search", {"query": "q"})
    return weakref.ref(search)


async def main() -> None:
    refs = [await build_and_call() for _ in range(50)]
    gc.collect()
    alive = sum(ref() is not None for ref in refs)
    print(f"servers built and dropped: 50, tool functions still alive: {alive}")
    print(f"_signature_cache: {len(introspection._signature_cache)}, _parameter_cache: {len(introspection._parameter_cache)}")


asyncio.run(main())

Output:

servers built and dropped: 50, tool functions still alive: 50
_signature_cache: 50, _parameter_cache: 50

In our backend, 300 rebuilds of one 64-tool server grew the process by 54 MB.

Suggested change

Key both caches weakly, so a dropped function leaves them:

import weakref

_signature_cache: weakref.WeakKeyDictionary[Callable[..., Any], inspect.Signature] = weakref.WeakKeyDictionary()
_parameter_cache: weakref.WeakKeyDictionary[Callable[..., Any], dict[str, Dependency[Any]]] = weakref.WeakKeyDictionary()

A bound method is a new object on each attribute access, so it would miss the cache each time. A cache keyed by function.__func__ for a bound method would keep the hits. FastMCP also keeps the functions in its own LRU caches; that part is in a FastMCP issue.

Activity

  1. xu91102 commented on Oct 28, 2026

    @xu91102

    I reproduced the retention on unchanged main 34cdc60eb5ac487f34f3cfa3242554c278776b6a with Python 3.12.13 on macOS, using resolved_dependencies() directly rather than FastMCP. Ten calls successfully resolved a closure-backed Depends factory and returned the expected result. After dropping the callers and collecting garbage, all ten handlers, factories, and payload objects were still alive. A direct-call control released all its objects.

    There is a third strong function-keyed cache on current main: _annotation_cache in annotations.py. Clearing only the two caches mentioned above still left all ten groups alive; clearing the annotation cache as well released every handler, factory, and payload. The unchanged full suite passes (121 tests, 100% branch coverage), while a new regression through resolved_dependencies() fails because the discarded payload is retained.

    I am preparing a scoped correction for these three introspection caches, preserving cached results while functions are live and compatibility with callables that cannot be weakly referenced. This does not address FastMCP's separate caches or change the bounded without_dependencies() wrapper cache.

    AI disclosure: investigation, executed checks, and this comment were prepared with Codex.

  2. chrisguidry commented on Nov 3, 2026

    @chrisguidry
    Owner

    Thanks for digging into this, @xu91102, and for finding the third cache! I've assigned the issue to you, and I'm looking forward to the PR.

  3. added
    simmer
    on Nov 19, 2026
  4. self-assigned this
    on Nov 19, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

simmer

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions