```python:inference/core/cache/air_gapped.py
import logging
import weakref
from typing import Any, Dict, List, Optional

from inference.core.cache.air_gapped import is_model_cached

logger = logging.getLogger(__name__)



# Cache results of is_model_cached to avoid repeated filesystem/IO work
_IS_MODEL_CACHED_CACHE: Dict[str, bool] = {}

# Cache schema objects per manifest class. Use a weak key dict to avoid
# holding classes alive indefinitely.
_SCHEMA_CACHE: "weakref.WeakKeyDictionary[Any, dict]" = weakref.WeakKeyDictionary()


def has_cached_model_variant(model_variants: Optional[List[str]]) -> bool:
    """Return True if **any** of the given model variant IDs has cached artifacts.

    Args:
        model_variants: List of model IDs as returned by
            ``WorkflowBlockManifest.get_supported_model_variants()``.
            Returns ``False`` when *None* or empty.
    """
    if not model_variants:
        return False

    # Iterate manually to allow caching and to preserve exception propagation
    for mid in model_variants:
        if mid in _IS_MODEL_CACHED_CACHE:
            if _IS_MODEL_CACHED_CACHE[mid]:
                return True
            continue
        # Not cached yet: call the heavy function and cache its result.
        cached = is_model_cached(mid)
        _IS_MODEL_CACHED_CACHE[mid] = cached
        if cached:
            return True
    return False




def _load_blocks() -> list:
    """Load workflow blocks, isolating the heavy import for testability."""
    from inference.core.workflows.execution_engine.introspection.blocks_loader import \
        load_workflow_blocks

    return load_workflow_blocks()


def get_cached_foundation_models(
    blocks: Optional[list] = None,
) -> List[Dict[str, Any]]:
    """Return metadata for workflow blocks whose required weights are cached.

    Each block whose manifest class exposes ``get_supported_model_variants``
    is inspected.  If any variant it declares is present in the local cache
    the block is included in the result list.

    Args:
        blocks: Optional pre-loaded list of block specifications.  When
            *None* (the default) the blocks are loaded via the engine's
            block loader.
    """
    results: List[Dict[str, Any]] = []
    if blocks is None:
        try:
            blocks = _load_blocks()
        except Exception:
            logger.debug(
                "Could not load workflow blocks for foundation model scan",
                exc_info=True,
            )
            return results

    for block in blocks:
        manifest_cls = block.manifest_class
        model_variants = manifest_cls.get_supported_model_variants()
        if model_variants is None:
            continue

        if not has_cached_model_variant(model_variants):
            continue

        model_id = model_variants[0] if model_variants else ""

        block_name = model_id
        try:
            schema = manifest_cls.model_json_schema()
            # Cache successful schema lookups to avoid calling model_json_schema()
            # multiple times for the same manifest class.
            try:
                _SCHEMA_CACHE[manifest_cls] = schema
            except Exception:
                # If caching fails for any reason, proceed without caching.
                pass
            block_name = schema.get("name", model_id)
        except Exception:
            pass

        block_type_id = _get_block_type_identifier(block)

        results.append(
            {
                "model_id": model_id,
                "name": block_name,
                "task_type": "",
                "model_architecture": "",
                "is_foundation": True,
                "block_type": block_type_id,
            }
        )

    return results


def _get_block_type_identifier(block) -> str:
    """Extract the canonical ``type`` identifier from a block specification."""
    try:
        # Try to reuse a previously cached schema for this manifest class.
        schema = None
        try:
            schema = _SCHEMA_CACHE.get(block.manifest_class)  # type: ignore[attr-defined]
        except Exception:
            # If cache access fails, fall back to direct call.
            schema = None

        if schema is None:
            schema = block.manifest_class.model_json_schema()
            try:
                _SCHEMA_CACHE[block.manifest_class] = schema
            except Exception:
                # If caching fails for any reason, continue without caching.
                pass

        type_prop = schema.get("properties", {}).get("type", {})
        # The type field is typically a const or enum with one value.
        if "const" in type_prop:
            return type_prop["const"]
        if "enum" in type_prop and type_prop["enum"]:
            return type_prop["enum"][0]
    except Exception:
        pass
    return block.identifier
```